[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / AST / ASTImporter.cpp
blobc4e931e220f69b5d2402e33a3108ac8c315e701a
1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
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 // This file defines the ASTImporter class which imports AST nodes from one
10 // context into another context.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTImporterSharedState.h"
18 #include "clang/AST/ASTStructuralEquivalence.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclAccessPair.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclVisitor.h"
29 #include "clang/AST/DeclarationName.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExprObjC.h"
33 #include "clang/AST/ExternalASTSource.h"
34 #include "clang/AST/LambdaCapture.h"
35 #include "clang/AST/NestedNameSpecifier.h"
36 #include "clang/AST/OperationKinds.h"
37 #include "clang/AST/Stmt.h"
38 #include "clang/AST/StmtCXX.h"
39 #include "clang/AST/StmtObjC.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/AST/TypeVisitor.h"
46 #include "clang/AST/UnresolvedSet.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/ExceptionSpecificationType.h"
49 #include "clang/Basic/FileManager.h"
50 #include "clang/Basic/IdentifierTable.h"
51 #include "clang/Basic/LLVM.h"
52 #include "clang/Basic/LangOptions.h"
53 #include "clang/Basic/SourceLocation.h"
54 #include "clang/Basic/SourceManager.h"
55 #include "clang/Basic/Specifiers.h"
56 #include "llvm/ADT/APSInt.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/STLExtras.h"
60 #include "llvm/ADT/ScopeExit.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <memory>
69 #include <optional>
70 #include <type_traits>
71 #include <utility>
73 namespace clang {
75 using llvm::make_error;
76 using llvm::Error;
77 using llvm::Expected;
78 using ExpectedTypePtr = llvm::Expected<const Type *>;
79 using ExpectedType = llvm::Expected<QualType>;
80 using ExpectedStmt = llvm::Expected<Stmt *>;
81 using ExpectedExpr = llvm::Expected<Expr *>;
82 using ExpectedDecl = llvm::Expected<Decl *>;
83 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 using ExpectedName = llvm::Expected<DeclarationName>;
86 std::string ASTImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
91 case UnsupportedConstruct:
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
96 llvm_unreachable("Invalid error code.");
97 return "Invalid error code.";
100 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
102 std::error_code ASTImportError::convertToErrorCode() const {
103 llvm_unreachable("Function not implemented.");
106 char ASTImportError::ID;
108 template <class T>
109 SmallVector<Decl *, 2>
110 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
111 SmallVector<Decl *, 2> Redecls;
112 for (auto *R : D->getFirstDecl()->redecls()) {
113 if (R != D->getFirstDecl())
114 Redecls.push_back(R);
116 Redecls.push_back(D->getFirstDecl());
117 std::reverse(Redecls.begin(), Redecls.end());
118 return Redecls;
121 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
122 if (auto *FD = dyn_cast<FunctionDecl>(D))
123 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
124 if (auto *VD = dyn_cast<VarDecl>(D))
125 return getCanonicalForwardRedeclChain<VarDecl>(VD);
126 if (auto *TD = dyn_cast<TagDecl>(D))
127 return getCanonicalForwardRedeclChain<TagDecl>(TD);
128 llvm_unreachable("Bad declaration kind");
131 void updateFlags(const Decl *From, Decl *To) {
132 // Check if some flags or attrs are new in 'From' and copy into 'To'.
133 // FIXME: Other flags or attrs?
134 if (From->isUsed(false) && !To->isUsed(false))
135 To->setIsUsed();
138 /// How to handle import errors that occur when import of a child declaration
139 /// of a DeclContext fails.
140 class ChildErrorHandlingStrategy {
141 /// This context is imported (in the 'from' domain).
142 /// It is nullptr if a non-DeclContext is imported.
143 const DeclContext *const FromDC;
144 /// Ignore import errors of the children.
145 /// If true, the context can be imported successfully if a child
146 /// of it failed to import. Otherwise the import errors of the child nodes
147 /// are accumulated (joined) into the import error object of the parent.
148 /// (Import of a parent can fail in other ways.)
149 bool const IgnoreChildErrors;
151 public:
152 ChildErrorHandlingStrategy(const DeclContext *FromDC)
153 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {}
154 ChildErrorHandlingStrategy(const Decl *FromD)
155 : FromDC(dyn_cast<DeclContext>(FromD)),
156 IgnoreChildErrors(!isa<TagDecl>(FromD)) {}
158 /// Process the import result of a child (of the current declaration).
159 /// \param ResultErr The import error that can be used as result of
160 /// importing the parent. This may be changed by the function.
161 /// \param ChildErr Result of importing a child. Can be success or error.
162 void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
163 if (ChildErr && !IgnoreChildErrors)
164 ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
165 else
166 consumeError(std::move(ChildErr));
169 /// Determine if import failure of a child does not cause import failure of
170 /// its parent.
171 bool ignoreChildErrorOnParent(Decl *FromChildD) const {
172 if (!IgnoreChildErrors || !FromDC)
173 return false;
174 return FromDC->containsDecl(FromChildD);
178 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
179 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
180 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
181 ASTImporter &Importer;
183 // Use this instead of Importer.importInto .
184 template <typename ImportT>
185 [[nodiscard]] Error importInto(ImportT &To, const ImportT &From) {
186 return Importer.importInto(To, From);
189 // Use this to import pointers of specific type.
190 template <typename ImportT>
191 [[nodiscard]] Error importInto(ImportT *&To, ImportT *From) {
192 auto ToOrErr = Importer.Import(From);
193 if (ToOrErr)
194 To = cast_or_null<ImportT>(*ToOrErr);
195 return ToOrErr.takeError();
198 // Call the import function of ASTImporter for a baseclass of type `T` and
199 // cast the return value to `T`.
200 template <typename T>
201 auto import(T *From)
202 -> std::conditional_t<std::is_base_of_v<Type, T>, Expected<const T *>,
203 Expected<T *>> {
204 auto ToOrErr = Importer.Import(From);
205 if (!ToOrErr)
206 return ToOrErr.takeError();
207 return cast_or_null<T>(*ToOrErr);
210 template <typename T>
211 auto import(const T *From) {
212 return import(const_cast<T *>(From));
215 // Call the import function of ASTImporter for type `T`.
216 template <typename T>
217 Expected<T> import(const T &From) {
218 return Importer.Import(From);
221 // Import an std::optional<T> by importing the contained T, if any.
222 template <typename T>
223 Expected<std::optional<T>> import(std::optional<T> From) {
224 if (!From)
225 return std::nullopt;
226 return import(*From);
229 ExplicitSpecifier importExplicitSpecifier(Error &Err,
230 ExplicitSpecifier ESpec);
232 // Wrapper for an overload set.
233 template <typename ToDeclT> struct CallOverloadedCreateFun {
234 template <typename... Args> decltype(auto) operator()(Args &&... args) {
235 return ToDeclT::Create(std::forward<Args>(args)...);
239 // Always use these functions to create a Decl during import. There are
240 // certain tasks which must be done after the Decl was created, e.g. we
241 // must immediately register that as an imported Decl. The parameter `ToD`
242 // will be set to the newly created Decl or if had been imported before
243 // then to the already imported Decl. Returns a bool value set to true if
244 // the `FromD` had been imported before.
245 template <typename ToDeclT, typename FromDeclT, typename... Args>
246 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
247 Args &&...args) {
248 // There may be several overloads of ToDeclT::Create. We must make sure
249 // to call the one which would be chosen by the arguments, thus we use a
250 // wrapper for the overload set.
251 CallOverloadedCreateFun<ToDeclT> OC;
252 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
253 std::forward<Args>(args)...);
255 // Use this overload if a special Type is needed to be created. E.g if we
256 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
257 // then:
258 // TypedefNameDecl *ToTypedef;
259 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
260 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
261 typename... Args>
262 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
263 Args &&...args) {
264 CallOverloadedCreateFun<NewDeclT> OC;
265 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
266 std::forward<Args>(args)...);
268 // Use this version if a special create function must be
269 // used, e.g. CXXRecordDecl::CreateLambda .
270 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
271 typename... Args>
272 [[nodiscard]] bool
273 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
274 FromDeclT *FromD, Args &&...args) {
275 if (Importer.getImportDeclErrorIfAny(FromD)) {
276 ToD = nullptr;
277 return true; // Already imported but with error.
279 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
280 if (ToD)
281 return true; // Already imported.
282 ToD = CreateFun(std::forward<Args>(args)...);
283 // Keep track of imported Decls.
284 Importer.RegisterImportedDecl(FromD, ToD);
285 Importer.SharedState->markAsNewDecl(ToD);
286 InitializeImportedDecl(FromD, ToD);
287 return false; // A new Decl is created.
290 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
291 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
292 if (FromD->isUsed())
293 ToD->setIsUsed();
294 if (FromD->isImplicit())
295 ToD->setImplicit();
298 // Check if we have found an existing definition. Returns with that
299 // definition if yes, otherwise returns null.
300 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
301 const FunctionDecl *Definition = nullptr;
302 if (D->doesThisDeclarationHaveABody() &&
303 FoundFunction->hasBody(Definition))
304 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
305 return nullptr;
308 void addDeclToContexts(Decl *FromD, Decl *ToD) {
309 if (Importer.isMinimalImport()) {
310 // In minimal import case the decl must be added even if it is not
311 // contained in original context, for LLDB compatibility.
312 // FIXME: Check if a better solution is possible.
313 if (!FromD->getDescribedTemplate() &&
314 FromD->getFriendObjectKind() == Decl::FOK_None)
315 ToD->getLexicalDeclContext()->addDeclInternal(ToD);
316 return;
319 DeclContext *FromDC = FromD->getDeclContext();
320 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
321 DeclContext *ToDC = ToD->getDeclContext();
322 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
324 bool Visible = false;
325 if (FromDC->containsDeclAndLoad(FromD)) {
326 ToDC->addDeclInternal(ToD);
327 Visible = true;
329 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
330 ToLexicalDC->addDeclInternal(ToD);
331 Visible = true;
334 // If the Decl was added to any context, it was made already visible.
335 // Otherwise it is still possible that it should be visible.
336 if (!Visible) {
337 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
338 auto *ToNamed = cast<NamedDecl>(ToD);
339 DeclContextLookupResult FromLookup =
340 FromDC->lookup(FromNamed->getDeclName());
341 if (llvm::is_contained(FromLookup, FromNamed))
342 ToDC->makeDeclVisibleInContext(ToNamed);
347 void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
348 DeclContext *OldDC) {
349 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
350 if (!LT)
351 return;
353 for (NamedDecl *TP : Params)
354 LT->update(TP, OldDC);
357 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
358 updateLookupTableForTemplateParameters(
359 Params, Importer.getToContext().getTranslationUnitDecl());
362 public:
363 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
365 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
366 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
367 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
369 // Importing types
370 ExpectedType VisitType(const Type *T);
371 #define TYPE(Class, Base) \
372 ExpectedType Visit##Class##Type(const Class##Type *T);
373 #include "clang/AST/TypeNodes.inc"
375 // Importing declarations
376 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
377 SourceLocation &Loc);
378 Error ImportDeclParts(
379 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
380 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
381 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
382 Error ImportDeclarationNameLoc(
383 const DeclarationNameInfo &From, DeclarationNameInfo &To);
384 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
385 Error ImportDeclContext(
386 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
387 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
389 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
390 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
391 Expected<APValue> ImportAPValue(const APValue &FromValue);
393 using Designator = DesignatedInitExpr::Designator;
395 /// What we should import from the definition.
396 enum ImportDefinitionKind {
397 /// Import the default subset of the definition, which might be
398 /// nothing (if minimal import is set) or might be everything (if minimal
399 /// import is not set).
400 IDK_Default,
401 /// Import everything.
402 IDK_Everything,
403 /// Import only the bare bones needed to establish a valid
404 /// DeclContext.
405 IDK_Basic
408 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
409 return IDK == IDK_Everything ||
410 (IDK == IDK_Default && !Importer.isMinimalImport());
413 Error ImportInitializer(VarDecl *From, VarDecl *To);
414 Error ImportDefinition(
415 RecordDecl *From, RecordDecl *To,
416 ImportDefinitionKind Kind = IDK_Default);
417 Error ImportDefinition(
418 EnumDecl *From, EnumDecl *To,
419 ImportDefinitionKind Kind = IDK_Default);
420 Error ImportDefinition(
421 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
422 ImportDefinitionKind Kind = IDK_Default);
423 Error ImportDefinition(
424 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
425 ImportDefinitionKind Kind = IDK_Default);
426 Error ImportTemplateArguments(ArrayRef<TemplateArgument> FromArgs,
427 SmallVectorImpl<TemplateArgument> &ToArgs);
428 Expected<TemplateArgument>
429 ImportTemplateArgument(const TemplateArgument &From);
431 template <typename InContainerTy>
432 Error ImportTemplateArgumentListInfo(
433 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
435 template<typename InContainerTy>
436 Error ImportTemplateArgumentListInfo(
437 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
438 const InContainerTy &Container, TemplateArgumentListInfo &Result);
440 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
441 using FunctionTemplateAndArgsTy =
442 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
443 Expected<FunctionTemplateAndArgsTy>
444 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
445 FunctionDecl *FromFD);
446 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
447 DeclaratorDecl *ToD);
449 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
451 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
453 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
454 ParmVarDecl *ToParam);
456 Expected<InheritedConstructor>
457 ImportInheritedConstructor(const InheritedConstructor &From);
459 template <typename T>
460 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
462 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true,
463 bool IgnoreTemplateParmDepth = false);
464 ExpectedDecl VisitDecl(Decl *D);
465 ExpectedDecl VisitImportDecl(ImportDecl *D);
466 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
467 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
468 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
469 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
470 ExpectedDecl VisitBindingDecl(BindingDecl *D);
471 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
472 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
473 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
474 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
475 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
476 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
477 ExpectedDecl VisitLabelDecl(LabelDecl *D);
478 ExpectedDecl VisitEnumDecl(EnumDecl *D);
479 ExpectedDecl VisitRecordDecl(RecordDecl *D);
480 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
481 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
482 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
483 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
484 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
485 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
486 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
487 ExpectedDecl VisitFieldDecl(FieldDecl *D);
488 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
489 ExpectedDecl VisitFriendDecl(FriendDecl *D);
490 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
491 ExpectedDecl VisitVarDecl(VarDecl *D);
492 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
493 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
494 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
495 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
496 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
497 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
498 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
499 ExpectedDecl VisitUsingDecl(UsingDecl *D);
500 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
501 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
502 ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D);
503 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
504 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
505 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
506 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
507 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
508 ExpectedDecl
509 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
511 Expected<ObjCTypeParamList *>
512 ImportObjCTypeParamList(ObjCTypeParamList *list);
514 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
515 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
516 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
517 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
518 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
519 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
520 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
521 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
522 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
523 ExpectedDecl VisitClassTemplateSpecializationDecl(
524 ClassTemplateSpecializationDecl *D);
525 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
526 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
527 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
529 // Importing statements
530 ExpectedStmt VisitStmt(Stmt *S);
531 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
532 ExpectedStmt VisitDeclStmt(DeclStmt *S);
533 ExpectedStmt VisitNullStmt(NullStmt *S);
534 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
535 ExpectedStmt VisitCaseStmt(CaseStmt *S);
536 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
537 ExpectedStmt VisitLabelStmt(LabelStmt *S);
538 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
539 ExpectedStmt VisitIfStmt(IfStmt *S);
540 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
541 ExpectedStmt VisitWhileStmt(WhileStmt *S);
542 ExpectedStmt VisitDoStmt(DoStmt *S);
543 ExpectedStmt VisitForStmt(ForStmt *S);
544 ExpectedStmt VisitGotoStmt(GotoStmt *S);
545 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
546 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
547 ExpectedStmt VisitBreakStmt(BreakStmt *S);
548 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
549 // FIXME: MSAsmStmt
550 // FIXME: SEHExceptStmt
551 // FIXME: SEHFinallyStmt
552 // FIXME: SEHTryStmt
553 // FIXME: SEHLeaveStmt
554 // FIXME: CapturedStmt
555 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
556 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
557 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
558 // FIXME: MSDependentExistsStmt
559 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
560 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
561 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
562 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
563 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
564 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
565 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
567 // Importing expressions
568 ExpectedStmt VisitExpr(Expr *E);
569 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E);
570 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
571 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
572 ExpectedStmt VisitConvertVectorExpr(ConvertVectorExpr *E);
573 ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E);
574 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
575 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
576 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
577 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
578 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
579 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
580 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
581 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
582 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
583 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
584 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
585 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
586 ExpectedStmt VisitStringLiteral(StringLiteral *E);
587 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
588 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
589 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
590 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
591 ExpectedStmt VisitParenExpr(ParenExpr *E);
592 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
593 ExpectedStmt VisitStmtExpr(StmtExpr *E);
594 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
595 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
596 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
597 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
598 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
599 ExpectedStmt VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E);
600 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
601 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
602 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
603 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
604 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
605 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
606 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
607 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
608 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
609 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
610 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
611 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
612 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
613 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
614 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
615 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
616 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
617 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
618 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
619 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
620 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
621 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
622 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
623 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
624 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
625 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
626 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
627 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
628 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
629 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
630 ExpectedStmt VisitMemberExpr(MemberExpr *E);
631 ExpectedStmt VisitCallExpr(CallExpr *E);
632 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
633 ExpectedStmt VisitInitListExpr(InitListExpr *E);
634 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
635 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
636 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
637 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
638 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
639 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
640 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
641 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
642 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
643 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
645 // Helper for chaining together multiple imports. If an error is detected,
646 // subsequent imports will return default constructed nodes, so that failure
647 // can be detected with a single conditional branch after a sequence of
648 // imports.
649 template <typename T> T importChecked(Error &Err, const T &From) {
650 // Don't attempt to import nodes if we hit an error earlier.
651 if (Err)
652 return T{};
653 Expected<T> MaybeVal = import(From);
654 if (!MaybeVal) {
655 Err = MaybeVal.takeError();
656 return T{};
658 return *MaybeVal;
661 template<typename IIter, typename OIter>
662 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
663 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
664 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
665 Expected<ItemT> ToOrErr = import(*Ibegin);
666 if (!ToOrErr)
667 return ToOrErr.takeError();
668 *Obegin = *ToOrErr;
670 return Error::success();
673 // Import every item from a container structure into an output container.
674 // If error occurs, stops at first error and returns the error.
675 // The output container should have space for all needed elements (it is not
676 // expanded, new items are put into from the beginning).
677 template<typename InContainerTy, typename OutContainerTy>
678 Error ImportContainerChecked(
679 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
680 return ImportArrayChecked(
681 InContainer.begin(), InContainer.end(), OutContainer.begin());
684 template<typename InContainerTy, typename OIter>
685 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
686 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
689 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
690 CXXMethodDecl *FromMethod);
692 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
693 FunctionDecl *FromFD);
695 // Returns true if the given function has a placeholder return type and
696 // that type is declared inside the body of the function.
697 // E.g. auto f() { struct X{}; return X(); }
698 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
701 template <typename InContainerTy>
702 Error ASTNodeImporter::ImportTemplateArgumentListInfo(
703 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
704 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
705 auto ToLAngleLocOrErr = import(FromLAngleLoc);
706 if (!ToLAngleLocOrErr)
707 return ToLAngleLocOrErr.takeError();
708 auto ToRAngleLocOrErr = import(FromRAngleLoc);
709 if (!ToRAngleLocOrErr)
710 return ToRAngleLocOrErr.takeError();
712 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
713 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
714 return Err;
715 Result = ToTAInfo;
716 return Error::success();
719 template <>
720 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
721 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
722 return ImportTemplateArgumentListInfo(
723 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
726 template <>
727 Error ASTNodeImporter::ImportTemplateArgumentListInfo<
728 ASTTemplateArgumentListInfo>(
729 const ASTTemplateArgumentListInfo &From,
730 TemplateArgumentListInfo &Result) {
731 return ImportTemplateArgumentListInfo(
732 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
735 Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
736 ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
737 FunctionDecl *FromFD) {
738 assert(FromFD->getTemplatedKind() ==
739 FunctionDecl::TK_FunctionTemplateSpecialization);
741 FunctionTemplateAndArgsTy Result;
743 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
744 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
745 return std::move(Err);
747 // Import template arguments.
748 if (Error Err = ImportTemplateArguments(FTSInfo->TemplateArguments->asArray(),
749 std::get<1>(Result)))
750 return std::move(Err);
752 return Result;
755 template <>
756 Expected<TemplateParameterList *>
757 ASTNodeImporter::import(TemplateParameterList *From) {
758 SmallVector<NamedDecl *, 4> To(From->size());
759 if (Error Err = ImportContainerChecked(*From, To))
760 return std::move(Err);
762 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
763 if (!ToRequiresClause)
764 return ToRequiresClause.takeError();
766 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
767 if (!ToTemplateLocOrErr)
768 return ToTemplateLocOrErr.takeError();
769 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
770 if (!ToLAngleLocOrErr)
771 return ToLAngleLocOrErr.takeError();
772 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
773 if (!ToRAngleLocOrErr)
774 return ToRAngleLocOrErr.takeError();
776 return TemplateParameterList::Create(
777 Importer.getToContext(),
778 *ToTemplateLocOrErr,
779 *ToLAngleLocOrErr,
781 *ToRAngleLocOrErr,
782 *ToRequiresClause);
785 template <>
786 Expected<TemplateArgument>
787 ASTNodeImporter::import(const TemplateArgument &From) {
788 switch (From.getKind()) {
789 case TemplateArgument::Null:
790 return TemplateArgument();
792 case TemplateArgument::Type: {
793 ExpectedType ToTypeOrErr = import(From.getAsType());
794 if (!ToTypeOrErr)
795 return ToTypeOrErr.takeError();
796 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ false,
797 From.getIsDefaulted());
800 case TemplateArgument::Integral: {
801 ExpectedType ToTypeOrErr = import(From.getIntegralType());
802 if (!ToTypeOrErr)
803 return ToTypeOrErr.takeError();
804 return TemplateArgument(From, *ToTypeOrErr);
807 case TemplateArgument::Declaration: {
808 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
809 if (!ToOrErr)
810 return ToOrErr.takeError();
811 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
812 if (!ToTypeOrErr)
813 return ToTypeOrErr.takeError();
814 return TemplateArgument(dyn_cast<ValueDecl>((*ToOrErr)->getCanonicalDecl()),
815 *ToTypeOrErr, From.getIsDefaulted());
818 case TemplateArgument::NullPtr: {
819 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
820 if (!ToTypeOrErr)
821 return ToTypeOrErr.takeError();
822 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true,
823 From.getIsDefaulted());
826 case TemplateArgument::Template: {
827 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
828 if (!ToTemplateOrErr)
829 return ToTemplateOrErr.takeError();
831 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted());
834 case TemplateArgument::TemplateExpansion: {
835 Expected<TemplateName> ToTemplateOrErr =
836 import(From.getAsTemplateOrTemplatePattern());
837 if (!ToTemplateOrErr)
838 return ToTemplateOrErr.takeError();
840 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(),
841 From.getIsDefaulted());
844 case TemplateArgument::Expression:
845 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
846 return TemplateArgument(*ToExpr, From.getIsDefaulted());
847 else
848 return ToExpr.takeError();
850 case TemplateArgument::Pack: {
851 SmallVector<TemplateArgument, 2> ToPack;
852 ToPack.reserve(From.pack_size());
853 if (Error Err = ImportTemplateArguments(From.pack_elements(), ToPack))
854 return std::move(Err);
856 return TemplateArgument(
857 llvm::ArrayRef(ToPack).copy(Importer.getToContext()));
861 llvm_unreachable("Invalid template argument kind");
864 template <>
865 Expected<TemplateArgumentLoc>
866 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
867 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
868 if (!ArgOrErr)
869 return ArgOrErr.takeError();
870 TemplateArgument Arg = *ArgOrErr;
872 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
874 TemplateArgumentLocInfo ToInfo;
875 if (Arg.getKind() == TemplateArgument::Expression) {
876 ExpectedExpr E = import(FromInfo.getAsExpr());
877 if (!E)
878 return E.takeError();
879 ToInfo = TemplateArgumentLocInfo(*E);
880 } else if (Arg.getKind() == TemplateArgument::Type) {
881 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
882 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
883 else
884 return TSIOrErr.takeError();
885 } else {
886 auto ToTemplateQualifierLocOrErr =
887 import(FromInfo.getTemplateQualifierLoc());
888 if (!ToTemplateQualifierLocOrErr)
889 return ToTemplateQualifierLocOrErr.takeError();
890 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
891 if (!ToTemplateNameLocOrErr)
892 return ToTemplateNameLocOrErr.takeError();
893 auto ToTemplateEllipsisLocOrErr =
894 import(FromInfo.getTemplateEllipsisLoc());
895 if (!ToTemplateEllipsisLocOrErr)
896 return ToTemplateEllipsisLocOrErr.takeError();
897 ToInfo = TemplateArgumentLocInfo(
898 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
899 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
902 return TemplateArgumentLoc(Arg, ToInfo);
905 template <>
906 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
907 if (DG.isNull())
908 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
909 size_t NumDecls = DG.end() - DG.begin();
910 SmallVector<Decl *, 1> ToDecls;
911 ToDecls.reserve(NumDecls);
912 for (Decl *FromD : DG) {
913 if (auto ToDOrErr = import(FromD))
914 ToDecls.push_back(*ToDOrErr);
915 else
916 return ToDOrErr.takeError();
918 return DeclGroupRef::Create(Importer.getToContext(),
919 ToDecls.begin(),
920 NumDecls);
923 template <>
924 Expected<ASTNodeImporter::Designator>
925 ASTNodeImporter::import(const Designator &D) {
926 if (D.isFieldDesignator()) {
927 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
929 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
930 if (!ToDotLocOrErr)
931 return ToDotLocOrErr.takeError();
933 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
934 if (!ToFieldLocOrErr)
935 return ToFieldLocOrErr.takeError();
937 return DesignatedInitExpr::Designator::CreateFieldDesignator(
938 ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
941 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
942 if (!ToLBracketLocOrErr)
943 return ToLBracketLocOrErr.takeError();
945 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
946 if (!ToRBracketLocOrErr)
947 return ToRBracketLocOrErr.takeError();
949 if (D.isArrayDesignator())
950 return Designator::CreateArrayDesignator(D.getArrayIndex(),
951 *ToLBracketLocOrErr,
952 *ToRBracketLocOrErr);
954 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
955 if (!ToEllipsisLocOrErr)
956 return ToEllipsisLocOrErr.takeError();
958 assert(D.isArrayRangeDesignator());
959 return Designator::CreateArrayRangeDesignator(
960 D.getArrayIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
961 *ToRBracketLocOrErr);
964 template <>
965 Expected<ConceptReference *> ASTNodeImporter::import(ConceptReference *From) {
966 Error Err = Error::success();
967 auto ToNNS = importChecked(Err, From->getNestedNameSpecifierLoc());
968 auto ToTemplateKWLoc = importChecked(Err, From->getTemplateKWLoc());
969 auto ToConceptNameLoc =
970 importChecked(Err, From->getConceptNameInfo().getLoc());
971 auto ToConceptName = importChecked(Err, From->getConceptNameInfo().getName());
972 auto ToFoundDecl = importChecked(Err, From->getFoundDecl());
973 auto ToNamedConcept = importChecked(Err, From->getNamedConcept());
974 if (Err)
975 return std::move(Err);
976 TemplateArgumentListInfo ToTAInfo;
977 const auto *ASTTemplateArgs = From->getTemplateArgsAsWritten();
978 if (ASTTemplateArgs)
979 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo))
980 return std::move(Err);
981 auto *ConceptRef = ConceptReference::Create(
982 Importer.getToContext(), ToNNS, ToTemplateKWLoc,
983 DeclarationNameInfo(ToConceptName, ToConceptNameLoc), ToFoundDecl,
984 ToNamedConcept,
985 ASTTemplateArgs ? ASTTemplateArgumentListInfo::Create(
986 Importer.getToContext(), ToTAInfo)
987 : nullptr);
988 return ConceptRef;
991 template <>
992 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
993 ValueDecl *Var = nullptr;
994 if (From.capturesVariable()) {
995 if (auto VarOrErr = import(From.getCapturedVar()))
996 Var = *VarOrErr;
997 else
998 return VarOrErr.takeError();
1001 auto LocationOrErr = import(From.getLocation());
1002 if (!LocationOrErr)
1003 return LocationOrErr.takeError();
1005 SourceLocation EllipsisLoc;
1006 if (From.isPackExpansion())
1007 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
1008 return std::move(Err);
1010 return LambdaCapture(
1011 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1012 EllipsisLoc);
1015 template <typename T>
1016 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
1017 if (Found->getLinkageInternal() != From->getLinkageInternal())
1018 return false;
1020 if (From->hasExternalFormalLinkage())
1021 return Found->hasExternalFormalLinkage();
1022 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1023 return false;
1024 if (From->isInAnonymousNamespace())
1025 return Found->isInAnonymousNamespace();
1026 else
1027 return !Found->isInAnonymousNamespace() &&
1028 !Found->hasExternalFormalLinkage();
1031 template <>
1032 bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
1033 TypedefNameDecl *From) {
1034 if (Found->getLinkageInternal() != From->getLinkageInternal())
1035 return false;
1037 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1038 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1039 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1042 } // namespace clang
1044 //----------------------------------------------------------------------------
1045 // Import Types
1046 //----------------------------------------------------------------------------
1048 using namespace clang;
1050 ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1051 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1052 << T->getTypeClassName();
1053 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1056 ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1057 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1058 if (!UnderlyingTypeOrErr)
1059 return UnderlyingTypeOrErr.takeError();
1061 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1064 ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1065 switch (T->getKind()) {
1066 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1067 case BuiltinType::Id: \
1068 return Importer.getToContext().SingletonId;
1069 #include "clang/Basic/OpenCLImageTypes.def"
1070 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1071 case BuiltinType::Id: \
1072 return Importer.getToContext().Id##Ty;
1073 #include "clang/Basic/OpenCLExtensionTypes.def"
1074 #define SVE_TYPE(Name, Id, SingletonId) \
1075 case BuiltinType::Id: \
1076 return Importer.getToContext().SingletonId;
1077 #include "clang/Basic/AArch64SVEACLETypes.def"
1078 #define PPC_VECTOR_TYPE(Name, Id, Size) \
1079 case BuiltinType::Id: \
1080 return Importer.getToContext().Id##Ty;
1081 #include "clang/Basic/PPCTypes.def"
1082 #define RVV_TYPE(Name, Id, SingletonId) \
1083 case BuiltinType::Id: \
1084 return Importer.getToContext().SingletonId;
1085 #include "clang/Basic/RISCVVTypes.def"
1086 #define WASM_TYPE(Name, Id, SingletonId) \
1087 case BuiltinType::Id: \
1088 return Importer.getToContext().SingletonId;
1089 #include "clang/Basic/WebAssemblyReferenceTypes.def"
1090 #define SHARED_SINGLETON_TYPE(Expansion)
1091 #define BUILTIN_TYPE(Id, SingletonId) \
1092 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1093 #include "clang/AST/BuiltinTypes.def"
1095 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1096 // context supports C++.
1098 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1099 // context supports ObjC.
1101 case BuiltinType::Char_U:
1102 // The context we're importing from has an unsigned 'char'. If we're
1103 // importing into a context with a signed 'char', translate to
1104 // 'unsigned char' instead.
1105 if (Importer.getToContext().getLangOpts().CharIsSigned)
1106 return Importer.getToContext().UnsignedCharTy;
1108 return Importer.getToContext().CharTy;
1110 case BuiltinType::Char_S:
1111 // The context we're importing from has an unsigned 'char'. If we're
1112 // importing into a context with a signed 'char', translate to
1113 // 'unsigned char' instead.
1114 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1115 return Importer.getToContext().SignedCharTy;
1117 return Importer.getToContext().CharTy;
1119 case BuiltinType::WChar_S:
1120 case BuiltinType::WChar_U:
1121 // FIXME: If not in C++, shall we translate to the C equivalent of
1122 // wchar_t?
1123 return Importer.getToContext().WCharTy;
1126 llvm_unreachable("Invalid BuiltinType Kind!");
1129 ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1130 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1131 if (!ToOriginalTypeOrErr)
1132 return ToOriginalTypeOrErr.takeError();
1134 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1137 ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1138 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1139 if (!ToElementTypeOrErr)
1140 return ToElementTypeOrErr.takeError();
1142 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1145 ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1146 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1147 if (!ToPointeeTypeOrErr)
1148 return ToPointeeTypeOrErr.takeError();
1150 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1153 ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1154 // FIXME: Check for blocks support in "to" context.
1155 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1156 if (!ToPointeeTypeOrErr)
1157 return ToPointeeTypeOrErr.takeError();
1159 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1162 ExpectedType
1163 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1164 // FIXME: Check for C++ support in "to" context.
1165 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1166 if (!ToPointeeTypeOrErr)
1167 return ToPointeeTypeOrErr.takeError();
1169 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1172 ExpectedType
1173 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1174 // FIXME: Check for C++0x support in "to" context.
1175 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1176 if (!ToPointeeTypeOrErr)
1177 return ToPointeeTypeOrErr.takeError();
1179 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1182 ExpectedType
1183 ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1184 // FIXME: Check for C++ support in "to" context.
1185 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1186 if (!ToPointeeTypeOrErr)
1187 return ToPointeeTypeOrErr.takeError();
1189 ExpectedTypePtr ClassTypeOrErr = import(T->getClass());
1190 if (!ClassTypeOrErr)
1191 return ClassTypeOrErr.takeError();
1193 return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr,
1194 *ClassTypeOrErr);
1197 ExpectedType
1198 ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1199 Error Err = Error::success();
1200 auto ToElementType = importChecked(Err, T->getElementType());
1201 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1202 if (Err)
1203 return std::move(Err);
1205 return Importer.getToContext().getConstantArrayType(
1206 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1207 T->getIndexTypeCVRQualifiers());
1210 ExpectedType
1211 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1212 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1213 if (!ToElementTypeOrErr)
1214 return ToElementTypeOrErr.takeError();
1216 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1217 T->getSizeModifier(),
1218 T->getIndexTypeCVRQualifiers());
1221 ExpectedType
1222 ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1223 Error Err = Error::success();
1224 QualType ToElementType = importChecked(Err, T->getElementType());
1225 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1226 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1227 if (Err)
1228 return std::move(Err);
1229 return Importer.getToContext().getVariableArrayType(
1230 ToElementType, ToSizeExpr, T->getSizeModifier(),
1231 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1234 ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1235 const DependentSizedArrayType *T) {
1236 Error Err = Error::success();
1237 QualType ToElementType = importChecked(Err, T->getElementType());
1238 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1239 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1240 if (Err)
1241 return std::move(Err);
1242 // SizeExpr may be null if size is not specified directly.
1243 // For example, 'int a[]'.
1245 return Importer.getToContext().getDependentSizedArrayType(
1246 ToElementType, ToSizeExpr, T->getSizeModifier(),
1247 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1250 ExpectedType ASTNodeImporter::VisitDependentSizedExtVectorType(
1251 const DependentSizedExtVectorType *T) {
1252 Error Err = Error::success();
1253 QualType ToElementType = importChecked(Err, T->getElementType());
1254 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1255 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1256 if (Err)
1257 return std::move(Err);
1258 return Importer.getToContext().getDependentSizedExtVectorType(
1259 ToElementType, ToSizeExpr, ToAttrLoc);
1262 ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1263 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1264 if (!ToElementTypeOrErr)
1265 return ToElementTypeOrErr.takeError();
1267 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1268 T->getNumElements(),
1269 T->getVectorKind());
1272 ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1273 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1274 if (!ToElementTypeOrErr)
1275 return ToElementTypeOrErr.takeError();
1277 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1278 T->getNumElements());
1281 ExpectedType
1282 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1283 // FIXME: What happens if we're importing a function without a prototype
1284 // into C++? Should we make it variadic?
1285 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1286 if (!ToReturnTypeOrErr)
1287 return ToReturnTypeOrErr.takeError();
1289 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1290 T->getExtInfo());
1293 ExpectedType
1294 ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1295 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1296 if (!ToReturnTypeOrErr)
1297 return ToReturnTypeOrErr.takeError();
1299 // Import argument types
1300 SmallVector<QualType, 4> ArgTypes;
1301 for (const auto &A : T->param_types()) {
1302 ExpectedType TyOrErr = import(A);
1303 if (!TyOrErr)
1304 return TyOrErr.takeError();
1305 ArgTypes.push_back(*TyOrErr);
1308 // Import exception types
1309 SmallVector<QualType, 4> ExceptionTypes;
1310 for (const auto &E : T->exceptions()) {
1311 ExpectedType TyOrErr = import(E);
1312 if (!TyOrErr)
1313 return TyOrErr.takeError();
1314 ExceptionTypes.push_back(*TyOrErr);
1317 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1318 Error Err = Error::success();
1319 FunctionProtoType::ExtProtoInfo ToEPI;
1320 ToEPI.ExtInfo = FromEPI.ExtInfo;
1321 ToEPI.Variadic = FromEPI.Variadic;
1322 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1323 ToEPI.TypeQuals = FromEPI.TypeQuals;
1324 ToEPI.RefQualifier = FromEPI.RefQualifier;
1325 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1326 ToEPI.ExceptionSpec.NoexceptExpr =
1327 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
1328 ToEPI.ExceptionSpec.SourceDecl =
1329 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1330 ToEPI.ExceptionSpec.SourceTemplate =
1331 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
1332 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1334 if (Err)
1335 return std::move(Err);
1337 return Importer.getToContext().getFunctionType(
1338 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1341 ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1342 const UnresolvedUsingType *T) {
1343 Error Err = Error::success();
1344 auto ToD = importChecked(Err, T->getDecl());
1345 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1346 if (Err)
1347 return std::move(Err);
1349 return Importer.getToContext().getTypeDeclType(
1350 ToD, cast_or_null<TypeDecl>(ToPrevD));
1353 ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1354 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1355 if (!ToInnerTypeOrErr)
1356 return ToInnerTypeOrErr.takeError();
1358 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1361 ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1362 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1363 if (!ToDeclOrErr)
1364 return ToDeclOrErr.takeError();
1366 TypedefNameDecl *ToDecl = *ToDeclOrErr;
1367 if (ToDecl->getTypeForDecl())
1368 return QualType(ToDecl->getTypeForDecl(), 0);
1370 ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
1371 if (!ToUnderlyingTypeOrErr)
1372 return ToUnderlyingTypeOrErr.takeError();
1374 return Importer.getToContext().getTypedefType(ToDecl, *ToUnderlyingTypeOrErr);
1377 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1378 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1379 if (!ToExprOrErr)
1380 return ToExprOrErr.takeError();
1381 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr, T->getKind());
1384 ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1385 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnmodifiedType());
1386 if (!ToUnderlyingTypeOrErr)
1387 return ToUnderlyingTypeOrErr.takeError();
1388 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr,
1389 T->getKind());
1392 ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
1393 Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl());
1394 if (!FoundOrErr)
1395 return FoundOrErr.takeError();
1396 Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType());
1397 if (!UnderlyingOrErr)
1398 return UnderlyingOrErr.takeError();
1400 return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr);
1403 ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1404 // FIXME: Make sure that the "to" context supports C++0x!
1405 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1406 if (!ToExprOrErr)
1407 return ToExprOrErr.takeError();
1409 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1410 if (!ToUnderlyingTypeOrErr)
1411 return ToUnderlyingTypeOrErr.takeError();
1413 return Importer.getToContext().getDecltypeType(
1414 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1417 ExpectedType
1418 ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1419 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1420 if (!ToBaseTypeOrErr)
1421 return ToBaseTypeOrErr.takeError();
1423 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1424 if (!ToUnderlyingTypeOrErr)
1425 return ToUnderlyingTypeOrErr.takeError();
1427 return Importer.getToContext().getUnaryTransformType(
1428 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1431 ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1432 // FIXME: Make sure that the "to" context supports C++11!
1433 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1434 if (!ToDeducedTypeOrErr)
1435 return ToDeducedTypeOrErr.takeError();
1437 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1438 if (!ToTypeConstraintConcept)
1439 return ToTypeConstraintConcept.takeError();
1441 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1442 if (Error Err = ImportTemplateArguments(T->getTypeConstraintArguments(),
1443 ToTemplateArgs))
1444 return std::move(Err);
1446 return Importer.getToContext().getAutoType(
1447 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1448 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1449 ToTemplateArgs);
1452 ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1453 const DeducedTemplateSpecializationType *T) {
1454 // FIXME: Make sure that the "to" context supports C++17!
1455 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1456 if (!ToTemplateNameOrErr)
1457 return ToTemplateNameOrErr.takeError();
1458 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1459 if (!ToDeducedTypeOrErr)
1460 return ToDeducedTypeOrErr.takeError();
1462 return Importer.getToContext().getDeducedTemplateSpecializationType(
1463 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1466 ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1467 const InjectedClassNameType *T) {
1468 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1469 if (!ToDeclOrErr)
1470 return ToDeclOrErr.takeError();
1472 // The InjectedClassNameType is created in VisitRecordDecl when the
1473 // T->getDecl() is imported. Here we can return the existing type.
1474 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl();
1475 assert(Ty && isa<InjectedClassNameType>(Ty));
1476 return QualType(Ty, 0);
1479 ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1480 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1481 if (!ToDeclOrErr)
1482 return ToDeclOrErr.takeError();
1484 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1487 ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1488 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1489 if (!ToDeclOrErr)
1490 return ToDeclOrErr.takeError();
1492 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1495 ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1496 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1497 if (!ToModifiedTypeOrErr)
1498 return ToModifiedTypeOrErr.takeError();
1499 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1500 if (!ToEquivalentTypeOrErr)
1501 return ToEquivalentTypeOrErr.takeError();
1503 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1504 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1507 ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1508 const TemplateTypeParmType *T) {
1509 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1510 if (!ToDeclOrErr)
1511 return ToDeclOrErr.takeError();
1513 return Importer.getToContext().getTemplateTypeParmType(
1514 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1517 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1518 const SubstTemplateTypeParmType *T) {
1519 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1520 if (!ReplacedOrErr)
1521 return ReplacedOrErr.takeError();
1523 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1524 if (!ToReplacementTypeOrErr)
1525 return ToReplacementTypeOrErr.takeError();
1527 return Importer.getToContext().getSubstTemplateTypeParmType(
1528 *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(),
1529 T->getPackIndex());
1532 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
1533 const SubstTemplateTypeParmPackType *T) {
1534 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1535 if (!ReplacedOrErr)
1536 return ReplacedOrErr.takeError();
1538 Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
1539 if (!ToArgumentPack)
1540 return ToArgumentPack.takeError();
1542 return Importer.getToContext().getSubstTemplateTypeParmPackType(
1543 *ReplacedOrErr, T->getIndex(), T->getFinal(), *ToArgumentPack);
1546 ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1547 const TemplateSpecializationType *T) {
1548 auto ToTemplateOrErr = import(T->getTemplateName());
1549 if (!ToTemplateOrErr)
1550 return ToTemplateOrErr.takeError();
1552 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1553 if (Error Err =
1554 ImportTemplateArguments(T->template_arguments(), ToTemplateArgs))
1555 return std::move(Err);
1557 QualType ToCanonType;
1558 if (!T->isCanonicalUnqualified()) {
1559 QualType FromCanonType
1560 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1561 if (ExpectedType TyOrErr = import(FromCanonType))
1562 ToCanonType = *TyOrErr;
1563 else
1564 return TyOrErr.takeError();
1566 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1567 ToTemplateArgs,
1568 ToCanonType);
1571 ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1572 // Note: the qualifier in an ElaboratedType is optional.
1573 auto ToQualifierOrErr = import(T->getQualifier());
1574 if (!ToQualifierOrErr)
1575 return ToQualifierOrErr.takeError();
1577 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1578 if (!ToNamedTypeOrErr)
1579 return ToNamedTypeOrErr.takeError();
1581 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1582 if (!ToOwnedTagDeclOrErr)
1583 return ToOwnedTagDeclOrErr.takeError();
1585 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1586 *ToQualifierOrErr,
1587 *ToNamedTypeOrErr,
1588 *ToOwnedTagDeclOrErr);
1591 ExpectedType
1592 ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1593 ExpectedType ToPatternOrErr = import(T->getPattern());
1594 if (!ToPatternOrErr)
1595 return ToPatternOrErr.takeError();
1597 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1598 T->getNumExpansions(),
1599 /*ExpactPack=*/false);
1602 ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1603 const DependentTemplateSpecializationType *T) {
1604 auto ToQualifierOrErr = import(T->getQualifier());
1605 if (!ToQualifierOrErr)
1606 return ToQualifierOrErr.takeError();
1608 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1610 SmallVector<TemplateArgument, 2> ToPack;
1611 ToPack.reserve(T->template_arguments().size());
1612 if (Error Err = ImportTemplateArguments(T->template_arguments(), ToPack))
1613 return std::move(Err);
1615 return Importer.getToContext().getDependentTemplateSpecializationType(
1616 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1619 ExpectedType
1620 ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1621 auto ToQualifierOrErr = import(T->getQualifier());
1622 if (!ToQualifierOrErr)
1623 return ToQualifierOrErr.takeError();
1625 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1627 QualType Canon;
1628 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1629 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1630 Canon = (*TyOrErr).getCanonicalType();
1631 else
1632 return TyOrErr.takeError();
1635 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1636 *ToQualifierOrErr,
1637 Name, Canon);
1640 ExpectedType
1641 ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1642 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1643 if (!ToDeclOrErr)
1644 return ToDeclOrErr.takeError();
1646 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1649 ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1650 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1651 if (!ToBaseTypeOrErr)
1652 return ToBaseTypeOrErr.takeError();
1654 SmallVector<QualType, 4> TypeArgs;
1655 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1656 if (ExpectedType TyOrErr = import(TypeArg))
1657 TypeArgs.push_back(*TyOrErr);
1658 else
1659 return TyOrErr.takeError();
1662 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1663 for (auto *P : T->quals()) {
1664 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1665 Protocols.push_back(*ProtocolOrErr);
1666 else
1667 return ProtocolOrErr.takeError();
1671 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1672 Protocols,
1673 T->isKindOfTypeAsWritten());
1676 ExpectedType
1677 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1678 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1679 if (!ToPointeeTypeOrErr)
1680 return ToPointeeTypeOrErr.takeError();
1682 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1685 ExpectedType
1686 ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
1687 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1688 if (!ToUnderlyingTypeOrErr)
1689 return ToUnderlyingTypeOrErr.takeError();
1691 IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
1692 return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
1693 ToIdentifier);
1696 ExpectedType clang::ASTNodeImporter::VisitAdjustedType(const AdjustedType *T) {
1697 Error Err = Error::success();
1698 QualType ToOriginalType = importChecked(Err, T->getOriginalType());
1699 QualType ToAdjustedType = importChecked(Err, T->getAdjustedType());
1700 if (Err)
1701 return std::move(Err);
1703 return Importer.getToContext().getAdjustedType(ToOriginalType,
1704 ToAdjustedType);
1707 ExpectedType clang::ASTNodeImporter::VisitBitIntType(const BitIntType *T) {
1708 return Importer.getToContext().getBitIntType(T->isUnsigned(),
1709 T->getNumBits());
1712 ExpectedType clang::ASTNodeImporter::VisitBTFTagAttributedType(
1713 const clang::BTFTagAttributedType *T) {
1714 Error Err = Error::success();
1715 const BTFTypeTagAttr *ToBTFAttr = importChecked(Err, T->getAttr());
1716 QualType ToWrappedType = importChecked(Err, T->getWrappedType());
1717 if (Err)
1718 return std::move(Err);
1720 return Importer.getToContext().getBTFTagAttributedType(ToBTFAttr,
1721 ToWrappedType);
1724 ExpectedType clang::ASTNodeImporter::VisitConstantMatrixType(
1725 const clang::ConstantMatrixType *T) {
1726 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1727 if (!ToElementTypeOrErr)
1728 return ToElementTypeOrErr.takeError();
1730 return Importer.getToContext().getConstantMatrixType(
1731 *ToElementTypeOrErr, T->getNumRows(), T->getNumColumns());
1734 ExpectedType clang::ASTNodeImporter::VisitDependentAddressSpaceType(
1735 const clang::DependentAddressSpaceType *T) {
1736 Error Err = Error::success();
1737 QualType ToPointeeType = importChecked(Err, T->getPointeeType());
1738 Expr *ToAddrSpaceExpr = importChecked(Err, T->getAddrSpaceExpr());
1739 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1740 if (Err)
1741 return std::move(Err);
1743 return Importer.getToContext().getDependentAddressSpaceType(
1744 ToPointeeType, ToAddrSpaceExpr, ToAttrLoc);
1747 ExpectedType clang::ASTNodeImporter::VisitDependentBitIntType(
1748 const clang::DependentBitIntType *T) {
1749 ExpectedExpr ToNumBitsExprOrErr = import(T->getNumBitsExpr());
1750 if (!ToNumBitsExprOrErr)
1751 return ToNumBitsExprOrErr.takeError();
1752 return Importer.getToContext().getDependentBitIntType(T->isUnsigned(),
1753 *ToNumBitsExprOrErr);
1756 ExpectedType clang::ASTNodeImporter::VisitDependentSizedMatrixType(
1757 const clang::DependentSizedMatrixType *T) {
1758 Error Err = Error::success();
1759 QualType ToElementType = importChecked(Err, T->getElementType());
1760 Expr *ToRowExpr = importChecked(Err, T->getRowExpr());
1761 Expr *ToColumnExpr = importChecked(Err, T->getColumnExpr());
1762 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1763 if (Err)
1764 return std::move(Err);
1766 return Importer.getToContext().getDependentSizedMatrixType(
1767 ToElementType, ToRowExpr, ToColumnExpr, ToAttrLoc);
1770 ExpectedType clang::ASTNodeImporter::VisitDependentVectorType(
1771 const clang::DependentVectorType *T) {
1772 Error Err = Error::success();
1773 QualType ToElementType = importChecked(Err, T->getElementType());
1774 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1775 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1776 if (Err)
1777 return std::move(Err);
1779 return Importer.getToContext().getDependentVectorType(
1780 ToElementType, ToSizeExpr, ToAttrLoc, T->getVectorKind());
1783 ExpectedType clang::ASTNodeImporter::VisitObjCTypeParamType(
1784 const clang::ObjCTypeParamType *T) {
1785 Expected<ObjCTypeParamDecl *> ToDeclOrErr = import(T->getDecl());
1786 if (!ToDeclOrErr)
1787 return ToDeclOrErr.takeError();
1789 SmallVector<ObjCProtocolDecl *, 4> ToProtocols;
1790 for (ObjCProtocolDecl *FromProtocol : T->getProtocols()) {
1791 Expected<ObjCProtocolDecl *> ToProtocolOrErr = import(FromProtocol);
1792 if (!ToProtocolOrErr)
1793 return ToProtocolOrErr.takeError();
1794 ToProtocols.push_back(*ToProtocolOrErr);
1797 return Importer.getToContext().getObjCTypeParamType(*ToDeclOrErr,
1798 ToProtocols);
1801 ExpectedType clang::ASTNodeImporter::VisitPipeType(const clang::PipeType *T) {
1802 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1803 if (!ToElementTypeOrErr)
1804 return ToElementTypeOrErr.takeError();
1806 ASTContext &ToCtx = Importer.getToContext();
1807 if (T->isReadOnly())
1808 return ToCtx.getReadPipeType(*ToElementTypeOrErr);
1809 else
1810 return ToCtx.getWritePipeType(*ToElementTypeOrErr);
1813 //----------------------------------------------------------------------------
1814 // Import Declarations
1815 //----------------------------------------------------------------------------
1816 Error ASTNodeImporter::ImportDeclParts(
1817 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1818 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1819 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1820 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1821 // FIXME: We could support these constructs by importing a different type of
1822 // this parameter and by importing the original type of the parameter only
1823 // after the FunctionDecl is created. See
1824 // VisitFunctionDecl::UsedDifferentProtoType.
1825 DeclContext *OrigDC = D->getDeclContext();
1826 FunctionDecl *FunDecl;
1827 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1828 FunDecl->hasBody()) {
1829 auto getLeafPointeeType = [](const Type *T) {
1830 while (T->isPointerType() || T->isArrayType()) {
1831 T = T->getPointeeOrArrayElementType();
1833 return T;
1835 for (const ParmVarDecl *P : FunDecl->parameters()) {
1836 const Type *LeafT =
1837 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1838 auto *RT = dyn_cast<RecordType>(LeafT);
1839 if (RT && RT->getDecl() == D) {
1840 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1841 << D->getDeclKindName();
1842 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1847 // Import the context of this declaration.
1848 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1849 return Err;
1851 // Import the name of this declaration.
1852 if (Error Err = importInto(Name, D->getDeclName()))
1853 return Err;
1855 // Import the location of this declaration.
1856 if (Error Err = importInto(Loc, D->getLocation()))
1857 return Err;
1859 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1860 if (ToD)
1861 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1862 return Err;
1864 return Error::success();
1867 Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1868 NamedDecl *&ToD, SourceLocation &Loc) {
1870 // Import the name of this declaration.
1871 if (Error Err = importInto(Name, D->getDeclName()))
1872 return Err;
1874 // Import the location of this declaration.
1875 if (Error Err = importInto(Loc, D->getLocation()))
1876 return Err;
1878 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1879 if (ToD)
1880 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1881 return Err;
1883 return Error::success();
1886 Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1887 if (!FromD)
1888 return Error::success();
1890 if (!ToD)
1891 if (Error Err = importInto(ToD, FromD))
1892 return Err;
1894 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1895 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1896 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1897 !ToRecord->getDefinition()) {
1898 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1899 return Err;
1902 return Error::success();
1905 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1906 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1907 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1908 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1909 return Err;
1912 return Error::success();
1915 return Error::success();
1918 Error
1919 ASTNodeImporter::ImportDeclarationNameLoc(
1920 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1921 // NOTE: To.Name and To.Loc are already imported.
1922 // We only have to import To.LocInfo.
1923 switch (To.getName().getNameKind()) {
1924 case DeclarationName::Identifier:
1925 case DeclarationName::ObjCZeroArgSelector:
1926 case DeclarationName::ObjCOneArgSelector:
1927 case DeclarationName::ObjCMultiArgSelector:
1928 case DeclarationName::CXXUsingDirective:
1929 case DeclarationName::CXXDeductionGuideName:
1930 return Error::success();
1932 case DeclarationName::CXXOperatorName: {
1933 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1934 To.setCXXOperatorNameRange(*ToRangeOrErr);
1935 else
1936 return ToRangeOrErr.takeError();
1937 return Error::success();
1939 case DeclarationName::CXXLiteralOperatorName: {
1940 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1941 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1942 else
1943 return LocOrErr.takeError();
1944 return Error::success();
1946 case DeclarationName::CXXConstructorName:
1947 case DeclarationName::CXXDestructorName:
1948 case DeclarationName::CXXConversionFunctionName: {
1949 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1950 To.setNamedTypeInfo(*ToTInfoOrErr);
1951 else
1952 return ToTInfoOrErr.takeError();
1953 return Error::success();
1956 llvm_unreachable("Unknown name kind.");
1959 Error
1960 ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1961 if (Importer.isMinimalImport() && !ForceImport) {
1962 auto ToDCOrErr = Importer.ImportContext(FromDC);
1963 return ToDCOrErr.takeError();
1966 // We use strict error handling in case of records and enums, but not
1967 // with e.g. namespaces.
1969 // FIXME Clients of the ASTImporter should be able to choose an
1970 // appropriate error handling strategy for their needs. For instance,
1971 // they may not want to mark an entire namespace as erroneous merely
1972 // because there is an ODR error with two typedefs. As another example,
1973 // the client may allow EnumConstantDecls with same names but with
1974 // different values in two distinct translation units.
1975 ChildErrorHandlingStrategy HandleChildErrors(FromDC);
1977 auto MightNeedReordering = [](const Decl *D) {
1978 return isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D);
1981 // Import everything that might need reordering first.
1982 Error ChildErrors = Error::success();
1983 for (auto *From : FromDC->decls()) {
1984 if (!MightNeedReordering(From))
1985 continue;
1987 ExpectedDecl ImportedOrErr = import(From);
1989 // If we are in the process of ImportDefinition(...) for a RecordDecl we
1990 // want to make sure that we are also completing each FieldDecl. There
1991 // are currently cases where this does not happen and this is correctness
1992 // fix since operations such as code generation will expect this to be so.
1993 if (!ImportedOrErr) {
1994 HandleChildErrors.handleChildImportResult(ChildErrors,
1995 ImportedOrErr.takeError());
1996 continue;
1998 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1999 Decl *ImportedDecl = *ImportedOrErr;
2000 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
2001 if (FieldFrom && FieldTo) {
2002 Error Err = ImportFieldDeclDefinition(FieldFrom, FieldTo);
2003 HandleChildErrors.handleChildImportResult(ChildErrors, std::move(Err));
2007 // We reorder declarations in RecordDecls because they may have another order
2008 // in the "to" context than they have in the "from" context. This may happen
2009 // e.g when we import a class like this:
2010 // struct declToImport {
2011 // int a = c + b;
2012 // int b = 1;
2013 // int c = 2;
2014 // };
2015 // During the import of `a` we import first the dependencies in sequence,
2016 // thus the order would be `c`, `b`, `a`. We will get the normal order by
2017 // first removing the already imported members and then adding them in the
2018 // order as they appear in the "from" context.
2020 // Keeping field order is vital because it determines structure layout.
2022 // Here and below, we cannot call field_begin() method and its callers on
2023 // ToDC if it has an external storage. Calling field_begin() will
2024 // automatically load all the fields by calling
2025 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
2026 // call ASTImporter::Import(). This is because the ExternalASTSource
2027 // interface in LLDB is implemented by the means of the ASTImporter. However,
2028 // calling an import at this point would result in an uncontrolled import, we
2029 // must avoid that.
2031 auto ToDCOrErr = Importer.ImportContext(FromDC);
2032 if (!ToDCOrErr) {
2033 consumeError(std::move(ChildErrors));
2034 return ToDCOrErr.takeError();
2037 DeclContext *ToDC = *ToDCOrErr;
2038 // Remove all declarations, which may be in wrong order in the
2039 // lexical DeclContext and then add them in the proper order.
2040 for (auto *D : FromDC->decls()) {
2041 if (!MightNeedReordering(D))
2042 continue;
2044 assert(D && "DC contains a null decl");
2045 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(D)) {
2046 // Remove only the decls which we successfully imported.
2047 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
2048 // Remove the decl from its wrong place in the linked list.
2049 ToDC->removeDecl(ToD);
2050 // Add the decl to the end of the linked list.
2051 // This time it will be at the proper place because the enclosing for
2052 // loop iterates in the original (good) order of the decls.
2053 ToDC->addDeclInternal(ToD);
2057 // Import everything else.
2058 for (auto *From : FromDC->decls()) {
2059 if (MightNeedReordering(From))
2060 continue;
2062 ExpectedDecl ImportedOrErr = import(From);
2063 if (!ImportedOrErr)
2064 HandleChildErrors.handleChildImportResult(ChildErrors,
2065 ImportedOrErr.takeError());
2068 return ChildErrors;
2071 Error ASTNodeImporter::ImportFieldDeclDefinition(const FieldDecl *From,
2072 const FieldDecl *To) {
2073 RecordDecl *FromRecordDecl = nullptr;
2074 RecordDecl *ToRecordDecl = nullptr;
2075 // If we have a field that is an ArrayType we need to check if the array
2076 // element is a RecordDecl and if so we need to import the definition.
2077 QualType FromType = From->getType();
2078 QualType ToType = To->getType();
2079 if (FromType->isArrayType()) {
2080 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
2081 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2082 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2085 if (!FromRecordDecl || !ToRecordDecl) {
2086 const RecordType *RecordFrom = FromType->getAs<RecordType>();
2087 const RecordType *RecordTo = ToType->getAs<RecordType>();
2089 if (RecordFrom && RecordTo) {
2090 FromRecordDecl = RecordFrom->getDecl();
2091 ToRecordDecl = RecordTo->getDecl();
2095 if (FromRecordDecl && ToRecordDecl) {
2096 if (FromRecordDecl->isCompleteDefinition() &&
2097 !ToRecordDecl->isCompleteDefinition())
2098 return ImportDefinition(FromRecordDecl, ToRecordDecl);
2101 return Error::success();
2104 Error ASTNodeImporter::ImportDeclContext(
2105 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
2106 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
2107 if (!ToDCOrErr)
2108 return ToDCOrErr.takeError();
2109 ToDC = *ToDCOrErr;
2111 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
2112 auto ToLexicalDCOrErr = Importer.ImportContext(
2113 FromD->getLexicalDeclContext());
2114 if (!ToLexicalDCOrErr)
2115 return ToLexicalDCOrErr.takeError();
2116 ToLexicalDC = *ToLexicalDCOrErr;
2117 } else
2118 ToLexicalDC = ToDC;
2120 return Error::success();
2123 Error ASTNodeImporter::ImportImplicitMethods(
2124 const CXXRecordDecl *From, CXXRecordDecl *To) {
2125 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
2126 "Import implicit methods to or from non-definition");
2128 for (CXXMethodDecl *FromM : From->methods())
2129 if (FromM->isImplicit()) {
2130 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
2131 if (!ToMOrErr)
2132 return ToMOrErr.takeError();
2135 return Error::success();
2138 static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
2139 ASTImporter &Importer) {
2140 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
2141 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
2142 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
2143 else
2144 return ToTypedefOrErr.takeError();
2146 return Error::success();
2149 Error ASTNodeImporter::ImportDefinition(
2150 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
2151 auto DefinitionCompleter = [To]() {
2152 // There are cases in LLDB when we first import a class without its
2153 // members. The class will have DefinitionData, but no members. Then,
2154 // importDefinition is called from LLDB, which tries to get the members, so
2155 // when we get here, the class already has the DefinitionData set, so we
2156 // must unset the CompleteDefinition here to be able to complete again the
2157 // definition.
2158 To->setCompleteDefinition(false);
2159 To->completeDefinition();
2162 if (To->getDefinition() || To->isBeingDefined()) {
2163 if (Kind == IDK_Everything ||
2164 // In case of lambdas, the class already has a definition ptr set, but
2165 // the contained decls are not imported yet. Also, isBeingDefined was
2166 // set in CXXRecordDecl::CreateLambda. We must import the contained
2167 // decls here and finish the definition.
2168 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
2169 if (To->isLambda()) {
2170 auto *FromCXXRD = cast<CXXRecordDecl>(From);
2171 SmallVector<LambdaCapture, 8> ToCaptures;
2172 ToCaptures.reserve(FromCXXRD->capture_size());
2173 for (const auto &FromCapture : FromCXXRD->captures()) {
2174 if (auto ToCaptureOrErr = import(FromCapture))
2175 ToCaptures.push_back(*ToCaptureOrErr);
2176 else
2177 return ToCaptureOrErr.takeError();
2179 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
2180 ToCaptures);
2183 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2184 // Finish the definition of the lambda, set isBeingDefined to false.
2185 if (To->isLambda())
2186 DefinitionCompleter();
2187 return Result;
2190 return Error::success();
2193 To->startDefinition();
2194 // Set the definition to complete even if it is really not complete during
2195 // import. Some AST constructs (expressions) require the record layout
2196 // to be calculated (see 'clang::computeDependence') at the time they are
2197 // constructed. Import of such AST node is possible during import of the
2198 // same record, there is no way to have a completely defined record (all
2199 // fields imported) at that time without multiple AST import passes.
2200 if (!Importer.isMinimalImport())
2201 To->setCompleteDefinition(true);
2202 // Complete the definition even if error is returned.
2203 // The RecordDecl may be already part of the AST so it is better to
2204 // have it in complete state even if something is wrong with it.
2205 auto DefinitionCompleterScopeExit =
2206 llvm::make_scope_exit(DefinitionCompleter);
2208 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2209 return Err;
2211 // Add base classes.
2212 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2213 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2214 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2216 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2217 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2219 #define FIELD(Name, Width, Merge) \
2220 ToData.Name = FromData.Name;
2221 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2223 // Copy over the data stored in RecordDeclBits
2224 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2226 SmallVector<CXXBaseSpecifier *, 4> Bases;
2227 for (const auto &Base1 : FromCXX->bases()) {
2228 ExpectedType TyOrErr = import(Base1.getType());
2229 if (!TyOrErr)
2230 return TyOrErr.takeError();
2232 SourceLocation EllipsisLoc;
2233 if (Base1.isPackExpansion()) {
2234 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2235 EllipsisLoc = *LocOrErr;
2236 else
2237 return LocOrErr.takeError();
2240 // Ensure that we have a definition for the base.
2241 if (Error Err =
2242 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2243 return Err;
2245 auto RangeOrErr = import(Base1.getSourceRange());
2246 if (!RangeOrErr)
2247 return RangeOrErr.takeError();
2249 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2250 if (!TSIOrErr)
2251 return TSIOrErr.takeError();
2253 Bases.push_back(
2254 new (Importer.getToContext()) CXXBaseSpecifier(
2255 *RangeOrErr,
2256 Base1.isVirtual(),
2257 Base1.isBaseOfClass(),
2258 Base1.getAccessSpecifierAsWritten(),
2259 *TSIOrErr,
2260 EllipsisLoc));
2262 if (!Bases.empty())
2263 ToCXX->setBases(Bases.data(), Bases.size());
2266 if (shouldForceImportDeclContext(Kind)) {
2267 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2268 return Err;
2271 return Error::success();
2274 Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2275 if (To->getAnyInitializer())
2276 return Error::success();
2278 Expr *FromInit = From->getInit();
2279 if (!FromInit)
2280 return Error::success();
2282 ExpectedExpr ToInitOrErr = import(FromInit);
2283 if (!ToInitOrErr)
2284 return ToInitOrErr.takeError();
2286 To->setInit(*ToInitOrErr);
2287 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2288 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2289 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2290 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2291 // FIXME: Also import the initializer value.
2294 // FIXME: Other bits to merge?
2295 return Error::success();
2298 Error ASTNodeImporter::ImportDefinition(
2299 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2300 if (To->getDefinition() || To->isBeingDefined()) {
2301 if (Kind == IDK_Everything)
2302 return ImportDeclContext(From, /*ForceImport=*/true);
2303 return Error::success();
2306 To->startDefinition();
2308 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2309 return Err;
2311 ExpectedType ToTypeOrErr =
2312 import(Importer.getFromContext().getTypeDeclType(From));
2313 if (!ToTypeOrErr)
2314 return ToTypeOrErr.takeError();
2316 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2317 if (!ToPromotionTypeOrErr)
2318 return ToPromotionTypeOrErr.takeError();
2320 if (shouldForceImportDeclContext(Kind))
2321 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2322 return Err;
2324 // FIXME: we might need to merge the number of positive or negative bits
2325 // if the enumerator lists don't match.
2326 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2327 From->getNumPositiveBits(),
2328 From->getNumNegativeBits());
2329 return Error::success();
2332 Error ASTNodeImporter::ImportTemplateArguments(
2333 ArrayRef<TemplateArgument> FromArgs,
2334 SmallVectorImpl<TemplateArgument> &ToArgs) {
2335 for (const auto &Arg : FromArgs) {
2336 if (auto ToOrErr = import(Arg))
2337 ToArgs.push_back(*ToOrErr);
2338 else
2339 return ToOrErr.takeError();
2342 return Error::success();
2345 // FIXME: Do not forget to remove this and use only 'import'.
2346 Expected<TemplateArgument>
2347 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2348 return import(From);
2351 template <typename InContainerTy>
2352 Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2353 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2354 for (const auto &FromLoc : Container) {
2355 if (auto ToLocOrErr = import(FromLoc))
2356 ToTAInfo.addArgument(*ToLocOrErr);
2357 else
2358 return ToLocOrErr.takeError();
2360 return Error::success();
2363 static StructuralEquivalenceKind
2364 getStructuralEquivalenceKind(const ASTImporter &Importer) {
2365 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2366 : StructuralEquivalenceKind::Default;
2369 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
2370 bool IgnoreTemplateParmDepth) {
2371 // Eliminate a potential failure point where we attempt to re-import
2372 // something we're trying to import while completing ToRecord.
2373 Decl *ToOrigin = Importer.GetOriginalDecl(To);
2374 if (ToOrigin) {
2375 To = ToOrigin;
2378 StructuralEquivalenceContext Ctx(
2379 Importer.getFromContext(), Importer.getToContext(),
2380 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2381 /*StrictTypeSpelling=*/false, Complain, /*ErrorOnTagTypeMismatch=*/false,
2382 IgnoreTemplateParmDepth);
2383 return Ctx.IsEquivalent(From, To);
2386 ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2387 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2388 << D->getDeclKindName();
2389 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2392 ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2393 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2394 << D->getDeclKindName();
2395 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2398 ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2399 // Import the context of this declaration.
2400 DeclContext *DC, *LexicalDC;
2401 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2402 return std::move(Err);
2404 // Import the location of this declaration.
2405 ExpectedSLoc LocOrErr = import(D->getLocation());
2406 if (!LocOrErr)
2407 return LocOrErr.takeError();
2409 EmptyDecl *ToD;
2410 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2411 return ToD;
2413 ToD->setLexicalDeclContext(LexicalDC);
2414 LexicalDC->addDeclInternal(ToD);
2415 return ToD;
2418 ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2419 TranslationUnitDecl *ToD =
2420 Importer.getToContext().getTranslationUnitDecl();
2422 Importer.MapImported(D, ToD);
2424 return ToD;
2427 ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) {
2428 DeclContext *DC, *LexicalDC;
2429 DeclarationName Name;
2430 SourceLocation Loc;
2431 NamedDecl *ToND;
2432 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2433 return std::move(Err);
2434 if (ToND)
2435 return ToND;
2437 BindingDecl *ToD;
2438 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2439 Name.getAsIdentifierInfo()))
2440 return ToD;
2442 Error Err = Error::success();
2443 QualType ToType = importChecked(Err, D->getType());
2444 Expr *ToBinding = importChecked(Err, D->getBinding());
2445 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2446 if (Err)
2447 return std::move(Err);
2449 ToD->setBinding(ToType, ToBinding);
2450 ToD->setDecomposedDecl(ToDecomposedDecl);
2451 addDeclToContexts(D, ToD);
2453 return ToD;
2456 ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2457 ExpectedSLoc LocOrErr = import(D->getLocation());
2458 if (!LocOrErr)
2459 return LocOrErr.takeError();
2460 auto ColonLocOrErr = import(D->getColonLoc());
2461 if (!ColonLocOrErr)
2462 return ColonLocOrErr.takeError();
2464 // Import the context of this declaration.
2465 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2466 if (!DCOrErr)
2467 return DCOrErr.takeError();
2468 DeclContext *DC = *DCOrErr;
2470 AccessSpecDecl *ToD;
2471 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2472 DC, *LocOrErr, *ColonLocOrErr))
2473 return ToD;
2475 // Lexical DeclContext and Semantic DeclContext
2476 // is always the same for the accessSpec.
2477 ToD->setLexicalDeclContext(DC);
2478 DC->addDeclInternal(ToD);
2480 return ToD;
2483 ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2484 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2485 if (!DCOrErr)
2486 return DCOrErr.takeError();
2487 DeclContext *DC = *DCOrErr;
2488 DeclContext *LexicalDC = DC;
2490 Error Err = Error::success();
2491 auto ToLocation = importChecked(Err, D->getLocation());
2492 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2493 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2494 auto ToMessage = importChecked(Err, D->getMessage());
2495 if (Err)
2496 return std::move(Err);
2498 StaticAssertDecl *ToD;
2499 if (GetImportedOrCreateDecl(
2500 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2501 ToRParenLoc, D->isFailed()))
2502 return ToD;
2504 ToD->setLexicalDeclContext(LexicalDC);
2505 LexicalDC->addDeclInternal(ToD);
2506 return ToD;
2509 ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2510 // Import the major distinguishing characteristics of this namespace.
2511 DeclContext *DC, *LexicalDC;
2512 DeclarationName Name;
2513 SourceLocation Loc;
2514 NamedDecl *ToD;
2515 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2516 return std::move(Err);
2517 if (ToD)
2518 return ToD;
2520 NamespaceDecl *MergeWithNamespace = nullptr;
2521 if (!Name) {
2522 // This is an anonymous namespace. Adopt an existing anonymous
2523 // namespace if we can.
2524 // FIXME: Not testable.
2525 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2526 MergeWithNamespace = TU->getAnonymousNamespace();
2527 else
2528 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2529 } else {
2530 SmallVector<NamedDecl *, 4> ConflictingDecls;
2531 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2532 for (auto *FoundDecl : FoundDecls) {
2533 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2534 continue;
2536 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2537 MergeWithNamespace = FoundNS;
2538 ConflictingDecls.clear();
2539 break;
2542 ConflictingDecls.push_back(FoundDecl);
2545 if (!ConflictingDecls.empty()) {
2546 ExpectedName NameOrErr = Importer.HandleNameConflict(
2547 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2548 ConflictingDecls.size());
2549 if (NameOrErr)
2550 Name = NameOrErr.get();
2551 else
2552 return NameOrErr.takeError();
2556 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2557 if (!BeginLocOrErr)
2558 return BeginLocOrErr.takeError();
2559 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2560 if (!RBraceLocOrErr)
2561 return RBraceLocOrErr.takeError();
2563 // Create the "to" namespace, if needed.
2564 NamespaceDecl *ToNamespace = MergeWithNamespace;
2565 if (!ToNamespace) {
2566 if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC,
2567 D->isInline(), *BeginLocOrErr, Loc,
2568 Name.getAsIdentifierInfo(),
2569 /*PrevDecl=*/nullptr, D->isNested()))
2570 return ToNamespace;
2571 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2572 ToNamespace->setLexicalDeclContext(LexicalDC);
2573 LexicalDC->addDeclInternal(ToNamespace);
2575 // If this is an anonymous namespace, register it as the anonymous
2576 // namespace within its context.
2577 if (!Name) {
2578 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2579 TU->setAnonymousNamespace(ToNamespace);
2580 else
2581 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2584 Importer.MapImported(D, ToNamespace);
2586 if (Error Err = ImportDeclContext(D))
2587 return std::move(Err);
2589 return ToNamespace;
2592 ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2593 // Import the major distinguishing characteristics of this namespace.
2594 DeclContext *DC, *LexicalDC;
2595 DeclarationName Name;
2596 SourceLocation Loc;
2597 NamedDecl *LookupD;
2598 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2599 return std::move(Err);
2600 if (LookupD)
2601 return LookupD;
2603 // NOTE: No conflict resolution is done for namespace aliases now.
2605 Error Err = Error::success();
2606 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2607 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2608 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2609 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2610 auto ToNamespace = importChecked(Err, D->getNamespace());
2611 if (Err)
2612 return std::move(Err);
2614 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2616 NamespaceAliasDecl *ToD;
2617 if (GetImportedOrCreateDecl(
2618 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2619 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2620 return ToD;
2622 ToD->setLexicalDeclContext(LexicalDC);
2623 LexicalDC->addDeclInternal(ToD);
2625 return ToD;
2628 ExpectedDecl
2629 ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2630 // Import the major distinguishing characteristics of this typedef.
2631 DeclarationName Name;
2632 SourceLocation Loc;
2633 NamedDecl *ToD;
2634 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2635 // is created.
2636 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2637 return std::move(Err);
2638 if (ToD)
2639 return ToD;
2641 DeclContext *DC = cast_or_null<DeclContext>(
2642 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2643 DeclContext *LexicalDC =
2644 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2645 cast<Decl>(D->getLexicalDeclContext())));
2647 // If this typedef is not in block scope, determine whether we've
2648 // seen a typedef with the same name (that we can merge with) or any
2649 // other entity by that name (which name lookup could conflict with).
2650 // Note: Repeated typedefs are not valid in C99:
2651 // 'typedef int T; typedef int T;' is invalid
2652 // We do not care about this now.
2653 if (DC && !DC->isFunctionOrMethod()) {
2654 SmallVector<NamedDecl *, 4> ConflictingDecls;
2655 unsigned IDNS = Decl::IDNS_Ordinary;
2656 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2657 for (auto *FoundDecl : FoundDecls) {
2658 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2659 continue;
2660 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2661 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2662 continue;
2664 QualType FromUT = D->getUnderlyingType();
2665 QualType FoundUT = FoundTypedef->getUnderlyingType();
2666 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2667 // If the underlying declarations are unnamed records these can be
2668 // imported as different types. We should create a distinct typedef
2669 // node in this case.
2670 // If we found an existing underlying type with a record in a
2671 // different context (than the imported), this is already reason for
2672 // having distinct typedef nodes for these.
2673 // Again this can create situation like
2674 // 'typedef int T; typedef int T;' but this is hard to avoid without
2675 // a rename strategy at import.
2676 if (!FromUT.isNull() && !FoundUT.isNull()) {
2677 RecordDecl *FromR = FromUT->getAsRecordDecl();
2678 RecordDecl *FoundR = FoundUT->getAsRecordDecl();
2679 if (FromR && FoundR &&
2680 !hasSameVisibilityContextAndLinkage(FoundR, FromR))
2681 continue;
2683 // If the "From" context has a complete underlying type but we
2684 // already have a complete underlying type then return with that.
2685 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2686 return Importer.MapImported(D, FoundTypedef);
2687 // FIXME Handle redecl chain. When you do that make consistent changes
2688 // in ASTImporterLookupTable too.
2689 } else {
2690 ConflictingDecls.push_back(FoundDecl);
2695 if (!ConflictingDecls.empty()) {
2696 ExpectedName NameOrErr = Importer.HandleNameConflict(
2697 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2698 if (NameOrErr)
2699 Name = NameOrErr.get();
2700 else
2701 return NameOrErr.takeError();
2705 Error Err = Error::success();
2706 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
2707 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2708 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2709 if (Err)
2710 return std::move(Err);
2712 // Create the new typedef node.
2713 // FIXME: ToUnderlyingType is not used.
2714 (void)ToUnderlyingType;
2715 TypedefNameDecl *ToTypedef;
2716 if (IsAlias) {
2717 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2718 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2719 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2720 return ToTypedef;
2721 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2722 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2723 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2724 return ToTypedef;
2726 // Import the DeclContext and set it to the Typedef.
2727 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2728 return std::move(Err);
2729 ToTypedef->setDeclContext(DC);
2730 ToTypedef->setLexicalDeclContext(LexicalDC);
2731 // Add to the lookupTable because we could not do that in MapImported.
2732 Importer.AddToLookupTable(ToTypedef);
2734 ToTypedef->setAccess(D->getAccess());
2736 // Templated declarations should not appear in DeclContext.
2737 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2738 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2739 LexicalDC->addDeclInternal(ToTypedef);
2741 return ToTypedef;
2744 ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2745 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2748 ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2749 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2752 ExpectedDecl
2753 ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2754 // Import the major distinguishing characteristics of this typedef.
2755 DeclContext *DC, *LexicalDC;
2756 DeclarationName Name;
2757 SourceLocation Loc;
2758 NamedDecl *FoundD;
2759 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2760 return std::move(Err);
2761 if (FoundD)
2762 return FoundD;
2764 // If this typedef is not in block scope, determine whether we've
2765 // seen a typedef with the same name (that we can merge with) or any
2766 // other entity by that name (which name lookup could conflict with).
2767 if (!DC->isFunctionOrMethod()) {
2768 SmallVector<NamedDecl *, 4> ConflictingDecls;
2769 unsigned IDNS = Decl::IDNS_Ordinary;
2770 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2771 for (auto *FoundDecl : FoundDecls) {
2772 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2773 continue;
2774 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2775 return Importer.MapImported(D, FoundAlias);
2776 ConflictingDecls.push_back(FoundDecl);
2779 if (!ConflictingDecls.empty()) {
2780 ExpectedName NameOrErr = Importer.HandleNameConflict(
2781 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2782 if (NameOrErr)
2783 Name = NameOrErr.get();
2784 else
2785 return NameOrErr.takeError();
2789 Error Err = Error::success();
2790 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2791 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2792 if (Err)
2793 return std::move(Err);
2795 TypeAliasTemplateDecl *ToAlias;
2796 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2797 Name, ToTemplateParameters, ToTemplatedDecl))
2798 return ToAlias;
2800 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2802 ToAlias->setAccess(D->getAccess());
2803 ToAlias->setLexicalDeclContext(LexicalDC);
2804 LexicalDC->addDeclInternal(ToAlias);
2805 if (DC != Importer.getToContext().getTranslationUnitDecl())
2806 updateLookupTableForTemplateParameters(*ToTemplateParameters);
2807 return ToAlias;
2810 ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2811 // Import the major distinguishing characteristics of this label.
2812 DeclContext *DC, *LexicalDC;
2813 DeclarationName Name;
2814 SourceLocation Loc;
2815 NamedDecl *ToD;
2816 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2817 return std::move(Err);
2818 if (ToD)
2819 return ToD;
2821 assert(LexicalDC->isFunctionOrMethod());
2823 LabelDecl *ToLabel;
2824 if (D->isGnuLocal()) {
2825 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2826 if (!BeginLocOrErr)
2827 return BeginLocOrErr.takeError();
2828 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2829 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2830 return ToLabel;
2832 } else {
2833 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2834 Name.getAsIdentifierInfo()))
2835 return ToLabel;
2839 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2840 if (!ToStmtOrErr)
2841 return ToStmtOrErr.takeError();
2843 ToLabel->setStmt(*ToStmtOrErr);
2844 ToLabel->setLexicalDeclContext(LexicalDC);
2845 LexicalDC->addDeclInternal(ToLabel);
2846 return ToLabel;
2849 ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2850 // Import the major distinguishing characteristics of this enum.
2851 DeclContext *DC, *LexicalDC;
2852 DeclarationName Name;
2853 SourceLocation Loc;
2854 NamedDecl *ToD;
2855 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2856 return std::move(Err);
2857 if (ToD)
2858 return ToD;
2860 // Figure out what enum name we're looking for.
2861 unsigned IDNS = Decl::IDNS_Tag;
2862 DeclarationName SearchName = Name;
2863 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2864 if (Error Err = importInto(
2865 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2866 return std::move(Err);
2867 IDNS = Decl::IDNS_Ordinary;
2868 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2869 IDNS |= Decl::IDNS_Ordinary;
2871 // We may already have an enum of the same name; try to find and match it.
2872 EnumDecl *PrevDecl = nullptr;
2873 if (!DC->isFunctionOrMethod() && SearchName) {
2874 SmallVector<NamedDecl *, 4> ConflictingDecls;
2875 auto FoundDecls =
2876 Importer.findDeclsInToCtx(DC, SearchName);
2877 for (auto *FoundDecl : FoundDecls) {
2878 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2879 continue;
2881 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2882 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2883 FoundDecl = Tag->getDecl();
2886 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2887 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2888 continue;
2889 if (IsStructuralMatch(D, FoundEnum)) {
2890 EnumDecl *FoundDef = FoundEnum->getDefinition();
2891 if (D->isThisDeclarationADefinition() && FoundDef)
2892 return Importer.MapImported(D, FoundDef);
2893 PrevDecl = FoundEnum->getMostRecentDecl();
2894 break;
2896 ConflictingDecls.push_back(FoundDecl);
2900 if (!ConflictingDecls.empty()) {
2901 ExpectedName NameOrErr = Importer.HandleNameConflict(
2902 SearchName, DC, IDNS, ConflictingDecls.data(),
2903 ConflictingDecls.size());
2904 if (NameOrErr)
2905 Name = NameOrErr.get();
2906 else
2907 return NameOrErr.takeError();
2911 Error Err = Error::success();
2912 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2913 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2914 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2915 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2916 if (Err)
2917 return std::move(Err);
2919 // Create the enum declaration.
2920 EnumDecl *D2;
2921 if (GetImportedOrCreateDecl(
2922 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2923 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2924 D->isScopedUsingClassTag(), D->isFixed()))
2925 return D2;
2927 D2->setQualifierInfo(ToQualifierLoc);
2928 D2->setIntegerType(ToIntegerType);
2929 D2->setBraceRange(ToBraceRange);
2930 D2->setAccess(D->getAccess());
2931 D2->setLexicalDeclContext(LexicalDC);
2932 addDeclToContexts(D, D2);
2934 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2935 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2936 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2937 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2938 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2939 else
2940 return ToInstOrErr.takeError();
2941 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
2942 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
2943 else
2944 return POIOrErr.takeError();
2947 // Import the definition
2948 if (D->isCompleteDefinition())
2949 if (Error Err = ImportDefinition(D, D2))
2950 return std::move(Err);
2952 return D2;
2955 ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2956 bool IsFriendTemplate = false;
2957 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2958 IsFriendTemplate =
2959 DCXX->getDescribedClassTemplate() &&
2960 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2961 Decl::FOK_None;
2964 // Import the major distinguishing characteristics of this record.
2965 DeclContext *DC = nullptr, *LexicalDC = nullptr;
2966 DeclarationName Name;
2967 SourceLocation Loc;
2968 NamedDecl *ToD = nullptr;
2969 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2970 return std::move(Err);
2971 if (ToD)
2972 return ToD;
2974 // Figure out what structure name we're looking for.
2975 unsigned IDNS = Decl::IDNS_Tag;
2976 DeclarationName SearchName = Name;
2977 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2978 if (Error Err = importInto(
2979 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2980 return std::move(Err);
2981 IDNS = Decl::IDNS_Ordinary;
2982 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2983 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2985 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
2986 : DC->isDependentContext();
2987 bool DependentFriend = IsFriendTemplate && IsDependentContext;
2989 // We may already have a record of the same name; try to find and match it.
2990 RecordDecl *PrevDecl = nullptr;
2991 if (!DependentFriend && !DC->isFunctionOrMethod() && !D->isLambda()) {
2992 SmallVector<NamedDecl *, 4> ConflictingDecls;
2993 auto FoundDecls =
2994 Importer.findDeclsInToCtx(DC, SearchName);
2995 if (!FoundDecls.empty()) {
2996 // We're going to have to compare D against potentially conflicting Decls,
2997 // so complete it.
2998 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2999 D->getASTContext().getExternalSource()->CompleteType(D);
3002 for (auto *FoundDecl : FoundDecls) {
3003 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3004 continue;
3006 Decl *Found = FoundDecl;
3007 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
3008 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
3009 Found = Tag->getDecl();
3012 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
3013 // Do not emit false positive diagnostic in case of unnamed
3014 // struct/union and in case of anonymous structs. Would be false
3015 // because there may be several anonymous/unnamed structs in a class.
3016 // E.g. these are both valid:
3017 // struct A { // unnamed structs
3018 // struct { struct A *next; } entry0;
3019 // struct { struct A *next; } entry1;
3020 // };
3021 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
3022 if (!SearchName)
3023 if (!IsStructuralMatch(D, FoundRecord, false))
3024 continue;
3026 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
3027 continue;
3029 if (IsStructuralMatch(D, FoundRecord)) {
3030 RecordDecl *FoundDef = FoundRecord->getDefinition();
3031 if (D->isThisDeclarationADefinition() && FoundDef) {
3032 // FIXME: Structural equivalence check should check for same
3033 // user-defined methods.
3034 Importer.MapImported(D, FoundDef);
3035 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3036 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
3037 assert(FoundCXX && "Record type mismatch");
3039 if (!Importer.isMinimalImport())
3040 // FoundDef may not have every implicit method that D has
3041 // because implicit methods are created only if they are used.
3042 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
3043 return std::move(Err);
3046 PrevDecl = FoundRecord->getMostRecentDecl();
3047 break;
3049 ConflictingDecls.push_back(FoundDecl);
3050 } // kind is RecordDecl
3051 } // for
3053 if (!ConflictingDecls.empty() && SearchName) {
3054 ExpectedName NameOrErr = Importer.HandleNameConflict(
3055 SearchName, DC, IDNS, ConflictingDecls.data(),
3056 ConflictingDecls.size());
3057 if (NameOrErr)
3058 Name = NameOrErr.get();
3059 else
3060 return NameOrErr.takeError();
3064 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
3065 if (!BeginLocOrErr)
3066 return BeginLocOrErr.takeError();
3068 // Create the record declaration.
3069 RecordDecl *D2 = nullptr;
3070 CXXRecordDecl *D2CXX = nullptr;
3071 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3072 if (DCXX->isLambda()) {
3073 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
3074 if (!TInfoOrErr)
3075 return TInfoOrErr.takeError();
3076 if (GetImportedOrCreateSpecialDecl(
3077 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
3078 DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(),
3079 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
3080 return D2CXX;
3081 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering();
3082 ExpectedDecl CDeclOrErr = import(Numbering.ContextDecl);
3083 if (!CDeclOrErr)
3084 return CDeclOrErr.takeError();
3085 Numbering.ContextDecl = *CDeclOrErr;
3086 D2CXX->setLambdaNumbering(Numbering);
3087 } else if (DCXX->isInjectedClassName()) {
3088 // We have to be careful to do a similar dance to the one in
3089 // Sema::ActOnStartCXXMemberDeclarations
3090 const bool DelayTypeCreation = true;
3091 if (GetImportedOrCreateDecl(
3092 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
3093 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
3094 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
3095 return D2CXX;
3096 Importer.getToContext().getTypeDeclType(
3097 D2CXX, dyn_cast<CXXRecordDecl>(DC));
3098 } else {
3099 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
3100 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3101 Name.getAsIdentifierInfo(),
3102 cast_or_null<CXXRecordDecl>(PrevDecl)))
3103 return D2CXX;
3106 D2 = D2CXX;
3107 D2->setAccess(D->getAccess());
3108 D2->setLexicalDeclContext(LexicalDC);
3109 addDeclToContexts(D, D2);
3111 if (ClassTemplateDecl *FromDescribed =
3112 DCXX->getDescribedClassTemplate()) {
3113 ClassTemplateDecl *ToDescribed;
3114 if (Error Err = importInto(ToDescribed, FromDescribed))
3115 return std::move(Err);
3116 D2CXX->setDescribedClassTemplate(ToDescribed);
3117 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
3118 // In a record describing a template the type should be an
3119 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
3120 // previously set type to the correct value here (ToDescribed is not
3121 // available at record create).
3122 CXXRecordDecl *Injected = nullptr;
3123 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
3124 auto *Record = dyn_cast<CXXRecordDecl>(Found);
3125 if (Record && Record->isInjectedClassName()) {
3126 Injected = Record;
3127 break;
3130 // Create an injected type for the whole redecl chain.
3131 // The chain may contain an already existing injected type at the start,
3132 // if yes this should be reused. We must ensure that only one type
3133 // object exists for the injected type (including the injected record
3134 // declaration), ASTContext does not check it.
3135 SmallVector<Decl *, 2> Redecls =
3136 getCanonicalForwardRedeclChain(D2CXX);
3137 const Type *FrontTy =
3138 cast<CXXRecordDecl>(Redecls.front())->getTypeForDecl();
3139 QualType InjSpec;
3140 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>())
3141 InjSpec = InjTy->getInjectedSpecializationType();
3142 else
3143 InjSpec = ToDescribed->getInjectedClassNameSpecialization();
3144 for (auto *R : Redecls) {
3145 auto *RI = cast<CXXRecordDecl>(R);
3146 if (R != Redecls.front() ||
3147 !isa<InjectedClassNameType>(RI->getTypeForDecl()))
3148 RI->setTypeForDecl(nullptr);
3149 // This function tries to get the injected type from getTypeForDecl,
3150 // then from the previous declaration if possible. If not, it creates
3151 // a new type.
3152 Importer.getToContext().getInjectedClassNameType(RI, InjSpec);
3154 // Set the new type for the injected decl too.
3155 if (Injected) {
3156 Injected->setTypeForDecl(nullptr);
3157 // This function will copy the injected type from D2CXX into Injected.
3158 // The injected decl does not have a previous decl to copy from.
3159 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
3162 } else if (MemberSpecializationInfo *MemberInfo =
3163 DCXX->getMemberSpecializationInfo()) {
3164 TemplateSpecializationKind SK =
3165 MemberInfo->getTemplateSpecializationKind();
3166 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
3168 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
3169 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
3170 else
3171 return ToInstOrErr.takeError();
3173 if (ExpectedSLoc POIOrErr =
3174 import(MemberInfo->getPointOfInstantiation()))
3175 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
3176 *POIOrErr);
3177 else
3178 return POIOrErr.takeError();
3181 } else {
3182 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3183 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3184 Name.getAsIdentifierInfo(), PrevDecl))
3185 return D2;
3186 D2->setLexicalDeclContext(LexicalDC);
3187 addDeclToContexts(D, D2);
3190 if (auto BraceRangeOrErr = import(D->getBraceRange()))
3191 D2->setBraceRange(*BraceRangeOrErr);
3192 else
3193 return BraceRangeOrErr.takeError();
3194 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3195 D2->setQualifierInfo(*QualifierLocOrErr);
3196 else
3197 return QualifierLocOrErr.takeError();
3199 if (D->isAnonymousStructOrUnion())
3200 D2->setAnonymousStructOrUnion(true);
3202 if (D->isCompleteDefinition())
3203 if (Error Err = ImportDefinition(D, D2, IDK_Default))
3204 return std::move(Err);
3206 return D2;
3209 ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3210 // Import the major distinguishing characteristics of this enumerator.
3211 DeclContext *DC, *LexicalDC;
3212 DeclarationName Name;
3213 SourceLocation Loc;
3214 NamedDecl *ToD;
3215 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3216 return std::move(Err);
3217 if (ToD)
3218 return ToD;
3220 // Determine whether there are any other declarations with the same name and
3221 // in the same context.
3222 if (!LexicalDC->isFunctionOrMethod()) {
3223 SmallVector<NamedDecl *, 4> ConflictingDecls;
3224 unsigned IDNS = Decl::IDNS_Ordinary;
3225 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3226 for (auto *FoundDecl : FoundDecls) {
3227 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3228 continue;
3230 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3231 if (IsStructuralMatch(D, FoundEnumConstant))
3232 return Importer.MapImported(D, FoundEnumConstant);
3233 ConflictingDecls.push_back(FoundDecl);
3237 if (!ConflictingDecls.empty()) {
3238 ExpectedName NameOrErr = Importer.HandleNameConflict(
3239 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3240 if (NameOrErr)
3241 Name = NameOrErr.get();
3242 else
3243 return NameOrErr.takeError();
3247 ExpectedType TypeOrErr = import(D->getType());
3248 if (!TypeOrErr)
3249 return TypeOrErr.takeError();
3251 ExpectedExpr InitOrErr = import(D->getInitExpr());
3252 if (!InitOrErr)
3253 return InitOrErr.takeError();
3255 EnumConstantDecl *ToEnumerator;
3256 if (GetImportedOrCreateDecl(
3257 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3258 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3259 return ToEnumerator;
3261 ToEnumerator->setAccess(D->getAccess());
3262 ToEnumerator->setLexicalDeclContext(LexicalDC);
3263 LexicalDC->addDeclInternal(ToEnumerator);
3264 return ToEnumerator;
3267 Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
3268 DeclaratorDecl *ToD) {
3269 unsigned int Num = FromD->getNumTemplateParameterLists();
3270 if (Num == 0)
3271 return Error::success();
3272 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3273 for (unsigned int I = 0; I < Num; ++I)
3274 if (Expected<TemplateParameterList *> ToTPListOrErr =
3275 import(FromD->getTemplateParameterList(I)))
3276 ToTPLists[I] = *ToTPListOrErr;
3277 else
3278 return ToTPListOrErr.takeError();
3279 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3280 return Error::success();
3283 Error ASTNodeImporter::ImportTemplateInformation(
3284 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3285 switch (FromFD->getTemplatedKind()) {
3286 case FunctionDecl::TK_NonTemplate:
3287 case FunctionDecl::TK_FunctionTemplate:
3288 return Error::success();
3290 case FunctionDecl::TK_DependentNonTemplate:
3291 if (Expected<FunctionDecl *> InstFDOrErr =
3292 import(FromFD->getInstantiatedFromDecl()))
3293 ToFD->setInstantiatedFromDecl(*InstFDOrErr);
3294 return Error::success();
3295 case FunctionDecl::TK_MemberSpecialization: {
3296 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3298 if (Expected<FunctionDecl *> InstFDOrErr =
3299 import(FromFD->getInstantiatedFromMemberFunction()))
3300 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3301 else
3302 return InstFDOrErr.takeError();
3304 if (ExpectedSLoc POIOrErr = import(
3305 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3306 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3307 else
3308 return POIOrErr.takeError();
3310 return Error::success();
3313 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3314 auto FunctionAndArgsOrErr =
3315 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3316 if (!FunctionAndArgsOrErr)
3317 return FunctionAndArgsOrErr.takeError();
3319 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3320 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3322 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3323 TemplateArgumentListInfo ToTAInfo;
3324 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3325 if (FromTAArgsAsWritten)
3326 if (Error Err = ImportTemplateArgumentListInfo(
3327 *FromTAArgsAsWritten, ToTAInfo))
3328 return Err;
3330 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3331 if (!POIOrErr)
3332 return POIOrErr.takeError();
3334 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3335 return Err;
3337 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3338 ToFD->setFunctionTemplateSpecialization(
3339 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3340 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3341 return Error::success();
3344 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3345 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3346 UnresolvedSet<8> Candidates;
3347 for (FunctionTemplateDecl *FTD : FromInfo->getCandidates()) {
3348 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = import(FTD))
3349 Candidates.addDecl(*ToFTDOrErr);
3350 else
3351 return ToFTDOrErr.takeError();
3354 // Import TemplateArgumentListInfo.
3355 TemplateArgumentListInfo ToTAInfo;
3356 const auto *FromTAArgsAsWritten = FromInfo->TemplateArgumentsAsWritten;
3357 if (FromTAArgsAsWritten)
3358 if (Error Err =
3359 ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
3360 return Err;
3362 ToFD->setDependentTemplateSpecialization(
3363 Importer.getToContext(), Candidates,
3364 FromTAArgsAsWritten ? &ToTAInfo : nullptr);
3365 return Error::success();
3368 llvm_unreachable("All cases should be covered!");
3371 Expected<FunctionDecl *>
3372 ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3373 auto FunctionAndArgsOrErr =
3374 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3375 if (!FunctionAndArgsOrErr)
3376 return FunctionAndArgsOrErr.takeError();
3378 FunctionTemplateDecl *Template;
3379 TemplateArgsTy ToTemplArgs;
3380 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3381 void *InsertPos = nullptr;
3382 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3383 return FoundSpec;
3386 Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3387 FunctionDecl *ToFD) {
3388 if (Stmt *FromBody = FromFD->getBody()) {
3389 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3390 ToFD->setBody(*ToBodyOrErr);
3391 else
3392 return ToBodyOrErr.takeError();
3394 return Error::success();
3397 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3398 // which is equal to the given DC, or D is equal to DC.
3399 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3400 const DeclContext *DCi = dyn_cast<DeclContext>(D);
3401 if (!DCi)
3402 DCi = D->getDeclContext();
3403 assert(DCi && "Declaration should have a context");
3404 while (DCi != D->getTranslationUnitDecl()) {
3405 if (DCi == DC)
3406 return true;
3407 DCi = DCi->getParent();
3409 return false;
3412 // Check if there is a declaration that has 'DC' as parent context and is
3413 // referenced from statement 'S' or one of its children. The search is done in
3414 // BFS order through children of 'S'.
3415 static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
3416 SmallVector<const Stmt *> ToProcess;
3417 ToProcess.push_back(S);
3418 while (!ToProcess.empty()) {
3419 const Stmt *CurrentS = ToProcess.pop_back_val();
3420 ToProcess.append(CurrentS->child_begin(), CurrentS->child_end());
3421 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CurrentS))
3422 if (const Decl *D = DeclRef->getDecl())
3423 if (isAncestorDeclContextOf(DC, D))
3424 return true;
3426 return false;
3429 namespace {
3430 /// Check if a type has any reference to a declaration that is inside the body
3431 /// of a function.
3432 /// The \c CheckType(QualType) function should be used to determine
3433 /// this property.
3435 /// The type visitor visits one type object only (not recursive).
3436 /// To find all referenced declarations we must discover all type objects until
3437 /// the canonical type is reached (walk over typedef and similar objects). This
3438 /// is done by loop over all "sugar" type objects. For every such type we must
3439 /// check all declarations that are referenced from it. For this check the
3440 /// visitor is used. In the visit functions all referenced declarations except
3441 /// the one that follows in the sugar chain (if any) must be checked. For this
3442 /// check the same visitor is re-used (it has no state-dependent data).
3444 /// The visit functions have 3 possible return values:
3445 /// - True, found a declaration inside \c ParentDC.
3446 /// - False, found declarations only outside \c ParentDC and it is not possible
3447 /// to find more declarations (the "sugar" chain does not continue).
3448 /// - Empty optional value, found no declarations or only outside \c ParentDC,
3449 /// but it is possible to find more declarations in the type "sugar" chain.
3450 /// The loop over the "sugar" types can be implemented by using type visit
3451 /// functions only (call \c CheckType with the desugared type). With the current
3452 /// solution no visit function is needed if the type has only a desugared type
3453 /// as data.
3454 class IsTypeDeclaredInsideVisitor
3455 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
3456 public:
3457 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
3458 : ParentDC(ParentDC) {}
3460 bool CheckType(QualType T) {
3461 // Check the chain of "sugar" types.
3462 // The "sugar" types are typedef or similar types that have the same
3463 // canonical type.
3464 if (std::optional<bool> Res = Visit(T.getTypePtr()))
3465 return *Res;
3466 QualType DsT =
3467 T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3468 while (DsT != T) {
3469 if (std::optional<bool> Res = Visit(DsT.getTypePtr()))
3470 return *Res;
3471 T = DsT;
3472 DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3474 return false;
3477 std::optional<bool> VisitTagType(const TagType *T) {
3478 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl()))
3479 for (const auto &Arg : Spec->getTemplateArgs().asArray())
3480 if (checkTemplateArgument(Arg))
3481 return true;
3482 return isAncestorDeclContextOf(ParentDC, T->getDecl());
3485 std::optional<bool> VisitPointerType(const PointerType *T) {
3486 return CheckType(T->getPointeeType());
3489 std::optional<bool> VisitReferenceType(const ReferenceType *T) {
3490 return CheckType(T->getPointeeTypeAsWritten());
3493 std::optional<bool> VisitTypedefType(const TypedefType *T) {
3494 const TypedefNameDecl *TD = T->getDecl();
3495 assert(TD);
3496 return isAncestorDeclContextOf(ParentDC, TD);
3499 std::optional<bool> VisitUsingType(const UsingType *T) {
3500 if (T->getFoundDecl() &&
3501 isAncestorDeclContextOf(ParentDC, T->getFoundDecl()))
3502 return true;
3504 return {};
3507 std::optional<bool>
3508 VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
3509 for (const auto &Arg : T->template_arguments())
3510 if (checkTemplateArgument(Arg))
3511 return true;
3512 // This type is a "sugar" to a record type, it can have a desugared type.
3513 return {};
3516 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
3517 if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr()))
3518 return true;
3520 return CheckType(T->getElementType());
3523 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
3524 llvm_unreachable(
3525 "Variable array should not occur in deduced return type of a function");
3528 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
3529 llvm_unreachable("Incomplete array should not occur in deduced return type "
3530 "of a function");
3533 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
3534 llvm_unreachable("Dependent array should not occur in deduced return type "
3535 "of a function");
3538 private:
3539 const DeclContext *const ParentDC;
3541 bool checkTemplateArgument(const TemplateArgument &Arg) {
3542 switch (Arg.getKind()) {
3543 case TemplateArgument::Null:
3544 return false;
3545 case TemplateArgument::Integral:
3546 return CheckType(Arg.getIntegralType());
3547 case TemplateArgument::Type:
3548 return CheckType(Arg.getAsType());
3549 case TemplateArgument::Expression:
3550 return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr());
3551 case TemplateArgument::Declaration:
3552 // FIXME: The declaration in this case is not allowed to be in a function?
3553 return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl());
3554 case TemplateArgument::NullPtr:
3555 // FIXME: The type is not allowed to be in the function?
3556 return CheckType(Arg.getNullPtrType());
3557 case TemplateArgument::Pack:
3558 for (const auto &PackArg : Arg.getPackAsArray())
3559 if (checkTemplateArgument(PackArg))
3560 return true;
3561 return false;
3562 case TemplateArgument::Template:
3563 // Templates can not be defined locally in functions.
3564 // A template passed as argument can be not in ParentDC.
3565 return false;
3566 case TemplateArgument::TemplateExpansion:
3567 // Templates can not be defined locally in functions.
3568 // A template passed as argument can be not in ParentDC.
3569 return false;
3571 llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
3574 } // namespace
3576 bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
3577 QualType FromTy = D->getType();
3578 const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3579 assert(FromFPT && "Must be called on FunctionProtoType");
3581 QualType RetT = FromFPT->getReturnType();
3582 if (isa<AutoType>(RetT.getTypePtr())) {
3583 FunctionDecl *Def = D->getDefinition();
3584 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
3585 return Visitor.CheckType(RetT);
3588 return false;
3591 ExplicitSpecifier
3592 ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3593 Expr *ExplicitExpr = ESpec.getExpr();
3594 if (ExplicitExpr)
3595 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3596 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3599 ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3601 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3602 auto RedeclIt = Redecls.begin();
3603 // Import the first part of the decl chain. I.e. import all previous
3604 // declarations starting from the canonical decl.
3605 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3606 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3607 if (!ToRedeclOrErr)
3608 return ToRedeclOrErr.takeError();
3610 assert(*RedeclIt == D);
3612 // Import the major distinguishing characteristics of this function.
3613 DeclContext *DC, *LexicalDC;
3614 DeclarationName Name;
3615 SourceLocation Loc;
3616 NamedDecl *ToD;
3617 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3618 return std::move(Err);
3619 if (ToD)
3620 return ToD;
3622 FunctionDecl *FoundByLookup = nullptr;
3623 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3625 // If this is a function template specialization, then try to find the same
3626 // existing specialization in the "to" context. The lookup below will not
3627 // find any specialization, but would find the primary template; thus, we
3628 // have to skip normal lookup in case of specializations.
3629 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3630 if (D->getTemplatedKind() ==
3631 FunctionDecl::TK_FunctionTemplateSpecialization) {
3632 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3633 if (!FoundFunctionOrErr)
3634 return FoundFunctionOrErr.takeError();
3635 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3636 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3637 return Def;
3638 FoundByLookup = FoundFunction;
3641 // Try to find a function in our own ("to") context with the same name, same
3642 // type, and in the same context as the function we're importing.
3643 else if (!LexicalDC->isFunctionOrMethod()) {
3644 SmallVector<NamedDecl *, 4> ConflictingDecls;
3645 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3646 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3647 for (auto *FoundDecl : FoundDecls) {
3648 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3649 continue;
3651 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3652 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3653 continue;
3655 if (IsStructuralMatch(D, FoundFunction)) {
3656 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3657 return Def;
3658 FoundByLookup = FoundFunction;
3659 break;
3661 // FIXME: Check for overloading more carefully, e.g., by boosting
3662 // Sema::IsOverload out to the AST library.
3664 // Function overloading is okay in C++.
3665 if (Importer.getToContext().getLangOpts().CPlusPlus)
3666 continue;
3668 // Complain about inconsistent function types.
3669 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3670 << Name << D->getType() << FoundFunction->getType();
3671 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3672 << FoundFunction->getType();
3673 ConflictingDecls.push_back(FoundDecl);
3677 if (!ConflictingDecls.empty()) {
3678 ExpectedName NameOrErr = Importer.HandleNameConflict(
3679 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3680 if (NameOrErr)
3681 Name = NameOrErr.get();
3682 else
3683 return NameOrErr.takeError();
3687 // We do not allow more than one in-class declaration of a function. This is
3688 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3689 // assumes there is only one in-class declaration. Building a redecl
3690 // chain would result in more than one in-class declaration for
3691 // overrides (even if they are part of the same redecl chain inside the
3692 // derived class.)
3693 if (FoundByLookup) {
3694 if (isa<CXXMethodDecl>(FoundByLookup)) {
3695 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3696 if (!D->doesThisDeclarationHaveABody()) {
3697 if (FunctionTemplateDecl *DescribedD =
3698 D->getDescribedFunctionTemplate()) {
3699 // Handle a "templated" function together with its described
3700 // template. This avoids need for a similar check at import of the
3701 // described template.
3702 assert(FoundByLookup->getDescribedFunctionTemplate() &&
3703 "Templated function mapped to non-templated?");
3704 Importer.MapImported(DescribedD,
3705 FoundByLookup->getDescribedFunctionTemplate());
3707 return Importer.MapImported(D, FoundByLookup);
3708 } else {
3709 // Let's continue and build up the redecl chain in this case.
3710 // FIXME Merge the functions into one decl.
3716 DeclarationNameInfo NameInfo(Name, Loc);
3717 // Import additional name location/type info.
3718 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3719 return std::move(Err);
3721 QualType FromTy = D->getType();
3722 TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3723 // Set to true if we do not import the type of the function as is. There are
3724 // cases when the original type would result in an infinite recursion during
3725 // the import. To avoid an infinite recursion when importing, we create the
3726 // FunctionDecl with a simplified function type and update it only after the
3727 // relevant AST nodes are already imported.
3728 // The type is related to TypeSourceInfo (it references the type), so we must
3729 // do the same with TypeSourceInfo.
3730 bool UsedDifferentProtoType = false;
3731 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3732 QualType FromReturnTy = FromFPT->getReturnType();
3733 // Functions with auto return type may define a struct inside their body
3734 // and the return type could refer to that struct.
3735 // E.g.: auto foo() { struct X{}; return X(); }
3736 // To avoid an infinite recursion when importing, create the FunctionDecl
3737 // with a simplified return type.
3738 if (hasAutoReturnTypeDeclaredInside(D)) {
3739 FromReturnTy = Importer.getFromContext().VoidTy;
3740 UsedDifferentProtoType = true;
3742 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3743 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3744 // FunctionDecl that we are importing the FunctionProtoType for.
3745 // To avoid an infinite recursion when importing, create the FunctionDecl
3746 // with a simplified function type.
3747 if (FromEPI.ExceptionSpec.SourceDecl ||
3748 FromEPI.ExceptionSpec.SourceTemplate ||
3749 FromEPI.ExceptionSpec.NoexceptExpr) {
3750 FunctionProtoType::ExtProtoInfo DefaultEPI;
3751 FromEPI = DefaultEPI;
3752 UsedDifferentProtoType = true;
3754 FromTy = Importer.getFromContext().getFunctionType(
3755 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3756 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3757 FromTy, D->getBeginLoc());
3760 Error Err = Error::success();
3761 auto T = importChecked(Err, FromTy);
3762 auto TInfo = importChecked(Err, FromTSI);
3763 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3764 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3765 auto ToDefaultLoc = importChecked(Err, D->getDefaultLoc());
3766 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3767 auto TrailingRequiresClause =
3768 importChecked(Err, D->getTrailingRequiresClause());
3769 if (Err)
3770 return std::move(Err);
3772 // Import the function parameters.
3773 SmallVector<ParmVarDecl *, 8> Parameters;
3774 for (auto *P : D->parameters()) {
3775 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3776 Parameters.push_back(*ToPOrErr);
3777 else
3778 return ToPOrErr.takeError();
3781 // Create the imported function.
3782 FunctionDecl *ToFunction = nullptr;
3783 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3784 ExplicitSpecifier ESpec =
3785 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3786 if (Err)
3787 return std::move(Err);
3788 auto ToInheritedConstructor = InheritedConstructor();
3789 if (FromConstructor->isInheritingConstructor()) {
3790 Expected<InheritedConstructor> ImportedInheritedCtor =
3791 import(FromConstructor->getInheritedConstructor());
3792 if (!ImportedInheritedCtor)
3793 return ImportedInheritedCtor.takeError();
3794 ToInheritedConstructor = *ImportedInheritedCtor;
3796 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3797 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3798 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3799 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3800 ToInheritedConstructor, TrailingRequiresClause))
3801 return ToFunction;
3802 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3804 Error Err = Error::success();
3805 auto ToOperatorDelete = importChecked(
3806 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3807 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3808 if (Err)
3809 return std::move(Err);
3811 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3812 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3813 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3814 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3815 TrailingRequiresClause))
3816 return ToFunction;
3818 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3820 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3821 } else if (CXXConversionDecl *FromConversion =
3822 dyn_cast<CXXConversionDecl>(D)) {
3823 ExplicitSpecifier ESpec =
3824 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3825 if (Err)
3826 return std::move(Err);
3827 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3828 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3829 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3830 D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3831 SourceLocation(), TrailingRequiresClause))
3832 return ToFunction;
3833 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3834 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3835 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3836 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3837 Method->UsesFPIntrin(), Method->isInlineSpecified(),
3838 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3839 return ToFunction;
3840 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3841 ExplicitSpecifier ESpec =
3842 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3843 CXXConstructorDecl *Ctor =
3844 importChecked(Err, Guide->getCorrespondingConstructor());
3845 if (Err)
3846 return std::move(Err);
3847 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3848 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3849 NameInfo, T, TInfo, ToEndLoc, Ctor))
3850 return ToFunction;
3851 cast<CXXDeductionGuideDecl>(ToFunction)
3852 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind());
3853 } else {
3854 if (GetImportedOrCreateDecl(
3855 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3856 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3857 D->isInlineSpecified(), D->hasWrittenPrototype(),
3858 D->getConstexprKind(), TrailingRequiresClause))
3859 return ToFunction;
3862 // Connect the redecl chain.
3863 if (FoundByLookup) {
3864 auto *Recent = const_cast<FunctionDecl *>(
3865 FoundByLookup->getMostRecentDecl());
3866 ToFunction->setPreviousDecl(Recent);
3867 // FIXME Probably we should merge exception specifications. E.g. In the
3868 // "To" context the existing function may have exception specification with
3869 // noexcept-unevaluated, while the newly imported function may have an
3870 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3871 // decl and its redeclarations may be required.
3874 ToFunction->setQualifierInfo(ToQualifierLoc);
3875 ToFunction->setAccess(D->getAccess());
3876 ToFunction->setLexicalDeclContext(LexicalDC);
3877 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3878 ToFunction->setTrivial(D->isTrivial());
3879 ToFunction->setPure(D->isPure());
3880 ToFunction->setDefaulted(D->isDefaulted());
3881 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3882 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3883 ToFunction->setFriendConstraintRefersToEnclosingTemplate(
3884 D->FriendConstraintRefersToEnclosingTemplate());
3885 ToFunction->setRangeEnd(ToEndLoc);
3886 ToFunction->setDefaultLoc(ToDefaultLoc);
3888 // Set the parameters.
3889 for (auto *Param : Parameters) {
3890 Param->setOwningFunction(ToFunction);
3891 ToFunction->addDeclInternal(Param);
3892 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3893 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3895 ToFunction->setParams(Parameters);
3897 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3898 // params it refers to.
3899 if (TInfo) {
3900 if (auto ProtoLoc =
3901 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3902 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3903 ProtoLoc.setParam(I, Parameters[I]);
3907 // Import the describing template function, if any.
3908 if (FromFT) {
3909 auto ToFTOrErr = import(FromFT);
3910 if (!ToFTOrErr)
3911 return ToFTOrErr.takeError();
3914 // Import Ctor initializers.
3915 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3916 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3917 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3918 // Import first, then allocate memory and copy if there was no error.
3919 if (Error Err = ImportContainerChecked(
3920 FromConstructor->inits(), CtorInitializers))
3921 return std::move(Err);
3922 auto **Memory =
3923 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3924 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3925 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3926 ToCtor->setCtorInitializers(Memory);
3927 ToCtor->setNumCtorInitializers(NumInitializers);
3931 // If it is a template, import all related things.
3932 if (Error Err = ImportTemplateInformation(D, ToFunction))
3933 return std::move(Err);
3935 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3936 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3937 FromCXXMethod))
3938 return std::move(Err);
3940 if (D->doesThisDeclarationHaveABody()) {
3941 Error Err = ImportFunctionDeclBody(D, ToFunction);
3943 if (Err)
3944 return std::move(Err);
3947 // Import and set the original type in case we used another type.
3948 if (UsedDifferentProtoType) {
3949 if (ExpectedType TyOrErr = import(D->getType()))
3950 ToFunction->setType(*TyOrErr);
3951 else
3952 return TyOrErr.takeError();
3953 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
3954 ToFunction->setTypeSourceInfo(*TSIOrErr);
3955 else
3956 return TSIOrErr.takeError();
3959 // FIXME: Other bits to merge?
3961 addDeclToContexts(D, ToFunction);
3963 // Import the rest of the chain. I.e. import all subsequent declarations.
3964 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3965 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3966 if (!ToRedeclOrErr)
3967 return ToRedeclOrErr.takeError();
3970 return ToFunction;
3973 ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3974 return VisitFunctionDecl(D);
3977 ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3978 return VisitCXXMethodDecl(D);
3981 ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3982 return VisitCXXMethodDecl(D);
3985 ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3986 return VisitCXXMethodDecl(D);
3989 ExpectedDecl
3990 ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3991 return VisitFunctionDecl(D);
3994 ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3995 // Import the major distinguishing characteristics of a variable.
3996 DeclContext *DC, *LexicalDC;
3997 DeclarationName Name;
3998 SourceLocation Loc;
3999 NamedDecl *ToD;
4000 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4001 return std::move(Err);
4002 if (ToD)
4003 return ToD;
4005 // Determine whether we've already imported this field.
4006 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4007 for (auto *FoundDecl : FoundDecls) {
4008 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
4009 // For anonymous fields, match up by index.
4010 if (!Name &&
4011 ASTImporter::getFieldIndex(D) !=
4012 ASTImporter::getFieldIndex(FoundField))
4013 continue;
4015 if (Importer.IsStructurallyEquivalent(D->getType(),
4016 FoundField->getType())) {
4017 Importer.MapImported(D, FoundField);
4018 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
4019 // initializer of a FieldDecl might not had been instantiated in the
4020 // "To" context. However, the "From" context might instantiated that,
4021 // thus we have to merge that.
4022 // Note: `hasInClassInitializer()` is not the same as non-null
4023 // `getInClassInitializer()` value.
4024 if (Expr *FromInitializer = D->getInClassInitializer()) {
4025 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) {
4026 // Import of the FromInitializer may result in the setting of
4027 // InClassInitializer. If not, set it here.
4028 assert(FoundField->hasInClassInitializer() &&
4029 "Field should have an in-class initializer if it has an "
4030 "expression for it.");
4031 if (!FoundField->getInClassInitializer())
4032 FoundField->setInClassInitializer(*ToInitializerOrErr);
4033 } else {
4034 return ToInitializerOrErr.takeError();
4037 return FoundField;
4040 // FIXME: Why is this case not handled with calling HandleNameConflict?
4041 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4042 << Name << D->getType() << FoundField->getType();
4043 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4044 << FoundField->getType();
4046 return make_error<ASTImportError>(ASTImportError::NameConflict);
4050 Error Err = Error::success();
4051 auto ToType = importChecked(Err, D->getType());
4052 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
4053 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4054 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4055 if (Err)
4056 return std::move(Err);
4057 const Type *ToCapturedVLAType = nullptr;
4058 if (Error Err = Importer.importInto(
4059 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
4060 return std::move(Err);
4062 FieldDecl *ToField;
4063 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
4064 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4065 ToType, ToTInfo, ToBitWidth, D->isMutable(),
4066 D->getInClassInitStyle()))
4067 return ToField;
4069 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before
4070 // we add fields in CXXRecordDecl::addedMember, otherwise record will be
4071 // marked as having non-zero size.
4072 Err = Importer.ImportAttrs(ToField, D);
4073 if (Err)
4074 return std::move(Err);
4075 ToField->setAccess(D->getAccess());
4076 ToField->setLexicalDeclContext(LexicalDC);
4077 ToField->setImplicit(D->isImplicit());
4078 if (ToCapturedVLAType)
4079 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
4080 LexicalDC->addDeclInternal(ToField);
4081 // Import initializer only after the field was created, it may have recursive
4082 // reference to the field.
4083 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
4084 if (Err)
4085 return std::move(Err);
4086 if (ToInitializer) {
4087 auto *AlreadyImported = ToField->getInClassInitializer();
4088 if (AlreadyImported)
4089 assert(ToInitializer == AlreadyImported &&
4090 "Duplicate import of in-class initializer.");
4091 else
4092 ToField->setInClassInitializer(ToInitializer);
4095 return ToField;
4098 ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
4099 // Import the major distinguishing characteristics of a variable.
4100 DeclContext *DC, *LexicalDC;
4101 DeclarationName Name;
4102 SourceLocation Loc;
4103 NamedDecl *ToD;
4104 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4105 return std::move(Err);
4106 if (ToD)
4107 return ToD;
4109 // Determine whether we've already imported this field.
4110 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4111 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4112 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
4113 // For anonymous indirect fields, match up by index.
4114 if (!Name &&
4115 ASTImporter::getFieldIndex(D) !=
4116 ASTImporter::getFieldIndex(FoundField))
4117 continue;
4119 if (Importer.IsStructurallyEquivalent(D->getType(),
4120 FoundField->getType(),
4121 !Name.isEmpty())) {
4122 Importer.MapImported(D, FoundField);
4123 return FoundField;
4126 // If there are more anonymous fields to check, continue.
4127 if (!Name && I < N-1)
4128 continue;
4130 // FIXME: Why is this case not handled with calling HandleNameConflict?
4131 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4132 << Name << D->getType() << FoundField->getType();
4133 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4134 << FoundField->getType();
4136 return make_error<ASTImportError>(ASTImportError::NameConflict);
4140 // Import the type.
4141 auto TypeOrErr = import(D->getType());
4142 if (!TypeOrErr)
4143 return TypeOrErr.takeError();
4145 auto **NamedChain =
4146 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
4148 unsigned i = 0;
4149 for (auto *PI : D->chain())
4150 if (Expected<NamedDecl *> ToD = import(PI))
4151 NamedChain[i++] = *ToD;
4152 else
4153 return ToD.takeError();
4155 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
4156 IndirectFieldDecl *ToIndirectField;
4157 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
4158 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
4159 // FIXME here we leak `NamedChain` which is allocated before
4160 return ToIndirectField;
4162 ToIndirectField->setAccess(D->getAccess());
4163 ToIndirectField->setLexicalDeclContext(LexicalDC);
4164 LexicalDC->addDeclInternal(ToIndirectField);
4165 return ToIndirectField;
4168 /// Used as return type of getFriendCountAndPosition.
4169 struct FriendCountAndPosition {
4170 /// Number of similar looking friends.
4171 unsigned int TotalCount;
4172 /// Index of the specific FriendDecl.
4173 unsigned int IndexOfDecl;
4176 static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1,
4177 FriendDecl *FD2) {
4178 if ((!FD1->getFriendType()) != (!FD2->getFriendType()))
4179 return false;
4181 if (const TypeSourceInfo *TSI = FD1->getFriendType())
4182 return Importer.IsStructurallyEquivalent(
4183 TSI->getType(), FD2->getFriendType()->getType(), /*Complain=*/false);
4185 ASTImporter::NonEquivalentDeclSet NonEquivalentDecls;
4186 StructuralEquivalenceContext Ctx(
4187 FD1->getASTContext(), FD2->getASTContext(), NonEquivalentDecls,
4188 StructuralEquivalenceKind::Default,
4189 /* StrictTypeSpelling = */ false, /* Complain = */ false);
4190 return Ctx.IsEquivalent(FD1, FD2);
4193 static FriendCountAndPosition getFriendCountAndPosition(ASTImporter &Importer,
4194 FriendDecl *FD) {
4195 unsigned int FriendCount = 0;
4196 std::optional<unsigned int> FriendPosition;
4197 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
4199 for (FriendDecl *FoundFriend : RD->friends()) {
4200 if (FoundFriend == FD) {
4201 FriendPosition = FriendCount;
4202 ++FriendCount;
4203 } else if (IsEquivalentFriend(Importer, FD, FoundFriend)) {
4204 ++FriendCount;
4208 assert(FriendPosition && "Friend decl not found in own parent.");
4210 return {FriendCount, *FriendPosition};
4213 ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
4214 // Import the major distinguishing characteristics of a declaration.
4215 DeclContext *DC, *LexicalDC;
4216 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4217 return std::move(Err);
4219 // Determine whether we've already imported this decl.
4220 // FriendDecl is not a NamedDecl so we cannot use lookup.
4221 // We try to maintain order and count of redundant friend declarations.
4222 const auto *RD = cast<CXXRecordDecl>(DC);
4223 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
4224 for (FriendDecl *ImportedFriend : RD->friends())
4225 if (IsEquivalentFriend(Importer, D, ImportedFriend))
4226 ImportedEquivalentFriends.push_back(ImportedFriend);
4228 FriendCountAndPosition CountAndPosition =
4229 getFriendCountAndPosition(Importer, D);
4231 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
4232 "Class with non-matching friends is imported, ODR check wrong?");
4233 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
4234 return Importer.MapImported(
4235 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
4237 // Not found. Create it.
4238 // The declarations will be put into order later by ImportDeclContext.
4239 FriendDecl::FriendUnion ToFU;
4240 if (NamedDecl *FriendD = D->getFriendDecl()) {
4241 NamedDecl *ToFriendD;
4242 if (Error Err = importInto(ToFriendD, FriendD))
4243 return std::move(Err);
4245 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
4246 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
4247 ToFriendD->setObjectOfFriendDecl(false);
4249 ToFU = ToFriendD;
4250 } else { // The friend is a type, not a decl.
4251 if (auto TSIOrErr = import(D->getFriendType()))
4252 ToFU = *TSIOrErr;
4253 else
4254 return TSIOrErr.takeError();
4257 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
4258 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
4259 for (unsigned I = 0; I < D->NumTPLists; I++) {
4260 if (auto ListOrErr = import(FromTPLists[I]))
4261 ToTPLists[I] = *ListOrErr;
4262 else
4263 return ListOrErr.takeError();
4266 auto LocationOrErr = import(D->getLocation());
4267 if (!LocationOrErr)
4268 return LocationOrErr.takeError();
4269 auto FriendLocOrErr = import(D->getFriendLoc());
4270 if (!FriendLocOrErr)
4271 return FriendLocOrErr.takeError();
4273 FriendDecl *FrD;
4274 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
4275 *LocationOrErr, ToFU,
4276 *FriendLocOrErr, ToTPLists))
4277 return FrD;
4279 FrD->setAccess(D->getAccess());
4280 FrD->setLexicalDeclContext(LexicalDC);
4281 LexicalDC->addDeclInternal(FrD);
4282 return FrD;
4285 ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
4286 // Import the major distinguishing characteristics of an ivar.
4287 DeclContext *DC, *LexicalDC;
4288 DeclarationName Name;
4289 SourceLocation Loc;
4290 NamedDecl *ToD;
4291 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4292 return std::move(Err);
4293 if (ToD)
4294 return ToD;
4296 // Determine whether we've already imported this ivar
4297 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4298 for (auto *FoundDecl : FoundDecls) {
4299 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
4300 if (Importer.IsStructurallyEquivalent(D->getType(),
4301 FoundIvar->getType())) {
4302 Importer.MapImported(D, FoundIvar);
4303 return FoundIvar;
4306 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
4307 << Name << D->getType() << FoundIvar->getType();
4308 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
4309 << FoundIvar->getType();
4311 return make_error<ASTImportError>(ASTImportError::NameConflict);
4315 Error Err = Error::success();
4316 auto ToType = importChecked(Err, D->getType());
4317 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4318 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4319 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4320 if (Err)
4321 return std::move(Err);
4323 ObjCIvarDecl *ToIvar;
4324 if (GetImportedOrCreateDecl(
4325 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
4326 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4327 ToType, ToTypeSourceInfo,
4328 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
4329 return ToIvar;
4331 ToIvar->setLexicalDeclContext(LexicalDC);
4332 LexicalDC->addDeclInternal(ToIvar);
4333 return ToIvar;
4336 ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
4338 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
4339 auto RedeclIt = Redecls.begin();
4340 // Import the first part of the decl chain. I.e. import all previous
4341 // declarations starting from the canonical decl.
4342 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4343 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4344 if (!RedeclOrErr)
4345 return RedeclOrErr.takeError();
4347 assert(*RedeclIt == D);
4349 // Import the major distinguishing characteristics of a variable.
4350 DeclContext *DC, *LexicalDC;
4351 DeclarationName Name;
4352 SourceLocation Loc;
4353 NamedDecl *ToD;
4354 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4355 return std::move(Err);
4356 if (ToD)
4357 return ToD;
4359 // Try to find a variable in our own ("to") context with the same name and
4360 // in the same context as the variable we're importing.
4361 VarDecl *FoundByLookup = nullptr;
4362 if (D->isFileVarDecl()) {
4363 SmallVector<NamedDecl *, 4> ConflictingDecls;
4364 unsigned IDNS = Decl::IDNS_Ordinary;
4365 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4366 for (auto *FoundDecl : FoundDecls) {
4367 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4368 continue;
4370 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4371 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4372 continue;
4373 if (Importer.IsStructurallyEquivalent(D->getType(),
4374 FoundVar->getType())) {
4376 // The VarDecl in the "From" context has a definition, but in the
4377 // "To" context we already have a definition.
4378 VarDecl *FoundDef = FoundVar->getDefinition();
4379 if (D->isThisDeclarationADefinition() && FoundDef)
4380 // FIXME Check for ODR error if the two definitions have
4381 // different initializers?
4382 return Importer.MapImported(D, FoundDef);
4384 // The VarDecl in the "From" context has an initializer, but in the
4385 // "To" context we already have an initializer.
4386 const VarDecl *FoundDInit = nullptr;
4387 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4388 // FIXME Diagnose ODR error if the two initializers are different?
4389 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4391 FoundByLookup = FoundVar;
4392 break;
4395 const ArrayType *FoundArray
4396 = Importer.getToContext().getAsArrayType(FoundVar->getType());
4397 const ArrayType *TArray
4398 = Importer.getToContext().getAsArrayType(D->getType());
4399 if (FoundArray && TArray) {
4400 if (isa<IncompleteArrayType>(FoundArray) &&
4401 isa<ConstantArrayType>(TArray)) {
4402 // Import the type.
4403 if (auto TyOrErr = import(D->getType()))
4404 FoundVar->setType(*TyOrErr);
4405 else
4406 return TyOrErr.takeError();
4408 FoundByLookup = FoundVar;
4409 break;
4410 } else if (isa<IncompleteArrayType>(TArray) &&
4411 isa<ConstantArrayType>(FoundArray)) {
4412 FoundByLookup = FoundVar;
4413 break;
4417 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4418 << Name << D->getType() << FoundVar->getType();
4419 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4420 << FoundVar->getType();
4421 ConflictingDecls.push_back(FoundDecl);
4425 if (!ConflictingDecls.empty()) {
4426 ExpectedName NameOrErr = Importer.HandleNameConflict(
4427 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4428 if (NameOrErr)
4429 Name = NameOrErr.get();
4430 else
4431 return NameOrErr.takeError();
4435 Error Err = Error::success();
4436 auto ToType = importChecked(Err, D->getType());
4437 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4438 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4439 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4440 if (Err)
4441 return std::move(Err);
4443 VarDecl *ToVar;
4444 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4445 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4446 if (Error Err =
4447 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4448 return std::move(Err);
4449 DecompositionDecl *ToDecomp;
4450 if (GetImportedOrCreateDecl(
4451 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4452 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4453 return ToDecomp;
4454 ToVar = ToDecomp;
4455 } else {
4456 // Create the imported variable.
4457 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4458 ToInnerLocStart, Loc,
4459 Name.getAsIdentifierInfo(), ToType,
4460 ToTypeSourceInfo, D->getStorageClass()))
4461 return ToVar;
4464 ToVar->setTSCSpec(D->getTSCSpec());
4465 ToVar->setQualifierInfo(ToQualifierLoc);
4466 ToVar->setAccess(D->getAccess());
4467 ToVar->setLexicalDeclContext(LexicalDC);
4469 if (FoundByLookup) {
4470 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4471 ToVar->setPreviousDecl(Recent);
4474 // Import the described template, if any.
4475 if (D->getDescribedVarTemplate()) {
4476 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4477 if (!ToVTOrErr)
4478 return ToVTOrErr.takeError();
4479 } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) {
4480 TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
4481 VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
4482 if (Expected<VarDecl *> ToInstOrErr = import(FromInst))
4483 ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
4484 else
4485 return ToInstOrErr.takeError();
4486 if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
4487 ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
4488 else
4489 return POIOrErr.takeError();
4492 if (Error Err = ImportInitializer(D, ToVar))
4493 return std::move(Err);
4495 if (D->isConstexpr())
4496 ToVar->setConstexpr(true);
4498 addDeclToContexts(D, ToVar);
4500 // Import the rest of the chain. I.e. import all subsequent declarations.
4501 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4502 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4503 if (!RedeclOrErr)
4504 return RedeclOrErr.takeError();
4507 return ToVar;
4510 ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4511 // Parameters are created in the translation unit's context, then moved
4512 // into the function declaration's context afterward.
4513 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4515 Error Err = Error::success();
4516 auto ToDeclName = importChecked(Err, D->getDeclName());
4517 auto ToLocation = importChecked(Err, D->getLocation());
4518 auto ToType = importChecked(Err, D->getType());
4519 if (Err)
4520 return std::move(Err);
4522 // Create the imported parameter.
4523 ImplicitParamDecl *ToParm = nullptr;
4524 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4525 ToLocation, ToDeclName.getAsIdentifierInfo(),
4526 ToType, D->getParameterKind()))
4527 return ToParm;
4528 return ToParm;
4531 Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4532 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4533 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4534 ToParam->setExplicitObjectParameterLoc(
4535 FromParam->getExplicitObjectParamThisLoc());
4536 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4538 if (FromParam->hasUninstantiatedDefaultArg()) {
4539 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4540 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4541 else
4542 return ToDefArgOrErr.takeError();
4543 } else if (FromParam->hasUnparsedDefaultArg()) {
4544 ToParam->setUnparsedDefaultArg();
4545 } else if (FromParam->hasDefaultArg()) {
4546 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4547 ToParam->setDefaultArg(*ToDefArgOrErr);
4548 else
4549 return ToDefArgOrErr.takeError();
4552 return Error::success();
4555 Expected<InheritedConstructor>
4556 ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) {
4557 Error Err = Error::success();
4558 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor());
4559 ConstructorUsingShadowDecl *ToShadow =
4560 importChecked(Err, From.getShadowDecl());
4561 if (Err)
4562 return std::move(Err);
4563 return InheritedConstructor(ToShadow, ToBaseCtor);
4566 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4567 // Parameters are created in the translation unit's context, then moved
4568 // into the function declaration's context afterward.
4569 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4571 Error Err = Error::success();
4572 auto ToDeclName = importChecked(Err, D->getDeclName());
4573 auto ToLocation = importChecked(Err, D->getLocation());
4574 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4575 auto ToType = importChecked(Err, D->getType());
4576 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4577 if (Err)
4578 return std::move(Err);
4580 ParmVarDecl *ToParm;
4581 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4582 ToInnerLocStart, ToLocation,
4583 ToDeclName.getAsIdentifierInfo(), ToType,
4584 ToTypeSourceInfo, D->getStorageClass(),
4585 /*DefaultArg*/ nullptr))
4586 return ToParm;
4588 // Set the default argument. It should be no problem if it was already done.
4589 // Do not import the default expression before GetImportedOrCreateDecl call
4590 // to avoid possible infinite import loop because circular dependency.
4591 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4592 return std::move(Err);
4594 if (D->isObjCMethodParameter()) {
4595 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4596 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4597 } else {
4598 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4599 D->getFunctionScopeIndex());
4602 return ToParm;
4605 ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4606 // Import the major distinguishing characteristics of a method.
4607 DeclContext *DC, *LexicalDC;
4608 DeclarationName Name;
4609 SourceLocation Loc;
4610 NamedDecl *ToD;
4611 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4612 return std::move(Err);
4613 if (ToD)
4614 return ToD;
4616 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4617 for (auto *FoundDecl : FoundDecls) {
4618 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4619 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4620 continue;
4622 // Check return types.
4623 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4624 FoundMethod->getReturnType())) {
4625 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4626 << D->isInstanceMethod() << Name << D->getReturnType()
4627 << FoundMethod->getReturnType();
4628 Importer.ToDiag(FoundMethod->getLocation(),
4629 diag::note_odr_objc_method_here)
4630 << D->isInstanceMethod() << Name;
4632 return make_error<ASTImportError>(ASTImportError::NameConflict);
4635 // Check the number of parameters.
4636 if (D->param_size() != FoundMethod->param_size()) {
4637 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4638 << D->isInstanceMethod() << Name
4639 << D->param_size() << FoundMethod->param_size();
4640 Importer.ToDiag(FoundMethod->getLocation(),
4641 diag::note_odr_objc_method_here)
4642 << D->isInstanceMethod() << Name;
4644 return make_error<ASTImportError>(ASTImportError::NameConflict);
4647 // Check parameter types.
4648 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4649 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4650 P != PEnd; ++P, ++FoundP) {
4651 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4652 (*FoundP)->getType())) {
4653 Importer.FromDiag((*P)->getLocation(),
4654 diag::warn_odr_objc_method_param_type_inconsistent)
4655 << D->isInstanceMethod() << Name
4656 << (*P)->getType() << (*FoundP)->getType();
4657 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4658 << (*FoundP)->getType();
4660 return make_error<ASTImportError>(ASTImportError::NameConflict);
4664 // Check variadic/non-variadic.
4665 // Check the number of parameters.
4666 if (D->isVariadic() != FoundMethod->isVariadic()) {
4667 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4668 << D->isInstanceMethod() << Name;
4669 Importer.ToDiag(FoundMethod->getLocation(),
4670 diag::note_odr_objc_method_here)
4671 << D->isInstanceMethod() << Name;
4673 return make_error<ASTImportError>(ASTImportError::NameConflict);
4676 // FIXME: Any other bits we need to merge?
4677 return Importer.MapImported(D, FoundMethod);
4681 Error Err = Error::success();
4682 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4683 auto ToReturnType = importChecked(Err, D->getReturnType());
4684 auto ToReturnTypeSourceInfo =
4685 importChecked(Err, D->getReturnTypeSourceInfo());
4686 if (Err)
4687 return std::move(Err);
4689 ObjCMethodDecl *ToMethod;
4690 if (GetImportedOrCreateDecl(
4691 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4692 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4693 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4694 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4695 D->getImplementationControl(), D->hasRelatedResultType()))
4696 return ToMethod;
4698 // FIXME: When we decide to merge method definitions, we'll need to
4699 // deal with implicit parameters.
4701 // Import the parameters
4702 SmallVector<ParmVarDecl *, 5> ToParams;
4703 for (auto *FromP : D->parameters()) {
4704 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4705 ToParams.push_back(*ToPOrErr);
4706 else
4707 return ToPOrErr.takeError();
4710 // Set the parameters.
4711 for (auto *ToParam : ToParams) {
4712 ToParam->setOwningFunction(ToMethod);
4713 ToMethod->addDeclInternal(ToParam);
4716 SmallVector<SourceLocation, 12> FromSelLocs;
4717 D->getSelectorLocs(FromSelLocs);
4718 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4719 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4720 return std::move(Err);
4722 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4724 ToMethod->setLexicalDeclContext(LexicalDC);
4725 LexicalDC->addDeclInternal(ToMethod);
4727 // Implicit params are declared when Sema encounters the definition but this
4728 // never happens when the method is imported. Manually declare the implicit
4729 // params now that the MethodDecl knows its class interface.
4730 if (D->getSelfDecl())
4731 ToMethod->createImplicitParams(Importer.getToContext(),
4732 ToMethod->getClassInterface());
4734 return ToMethod;
4737 ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4738 // Import the major distinguishing characteristics of a category.
4739 DeclContext *DC, *LexicalDC;
4740 DeclarationName Name;
4741 SourceLocation Loc;
4742 NamedDecl *ToD;
4743 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4744 return std::move(Err);
4745 if (ToD)
4746 return ToD;
4748 Error Err = Error::success();
4749 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4750 auto ToLocation = importChecked(Err, D->getLocation());
4751 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4752 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4753 if (Err)
4754 return std::move(Err);
4756 ObjCTypeParamDecl *Result;
4757 if (GetImportedOrCreateDecl(
4758 Result, D, Importer.getToContext(), DC, D->getVariance(),
4759 ToVarianceLoc, D->getIndex(),
4760 ToLocation, Name.getAsIdentifierInfo(),
4761 ToColonLoc, ToTypeSourceInfo))
4762 return Result;
4764 // Only import 'ObjCTypeParamType' after the decl is created.
4765 auto ToTypeForDecl = importChecked(Err, D->getTypeForDecl());
4766 if (Err)
4767 return std::move(Err);
4768 Result->setTypeForDecl(ToTypeForDecl);
4769 Result->setLexicalDeclContext(LexicalDC);
4770 return Result;
4773 ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4774 // Import the major distinguishing characteristics of a category.
4775 DeclContext *DC, *LexicalDC;
4776 DeclarationName Name;
4777 SourceLocation Loc;
4778 NamedDecl *ToD;
4779 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4780 return std::move(Err);
4781 if (ToD)
4782 return ToD;
4784 ObjCInterfaceDecl *ToInterface;
4785 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4786 return std::move(Err);
4788 // Determine if we've already encountered this category.
4789 ObjCCategoryDecl *MergeWithCategory
4790 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4791 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4792 if (!ToCategory) {
4794 Error Err = Error::success();
4795 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4796 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4797 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4798 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4799 if (Err)
4800 return std::move(Err);
4802 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4803 ToAtStartLoc, Loc,
4804 ToCategoryNameLoc,
4805 Name.getAsIdentifierInfo(), ToInterface,
4806 /*TypeParamList=*/nullptr,
4807 ToIvarLBraceLoc,
4808 ToIvarRBraceLoc))
4809 return ToCategory;
4811 ToCategory->setLexicalDeclContext(LexicalDC);
4812 LexicalDC->addDeclInternal(ToCategory);
4813 // Import the type parameter list after MapImported, to avoid
4814 // loops when bringing in their DeclContext.
4815 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4816 ToCategory->setTypeParamList(*PListOrErr);
4817 else
4818 return PListOrErr.takeError();
4820 // Import protocols
4821 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4822 SmallVector<SourceLocation, 4> ProtocolLocs;
4823 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4824 = D->protocol_loc_begin();
4825 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4826 FromProtoEnd = D->protocol_end();
4827 FromProto != FromProtoEnd;
4828 ++FromProto, ++FromProtoLoc) {
4829 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4830 Protocols.push_back(*ToProtoOrErr);
4831 else
4832 return ToProtoOrErr.takeError();
4834 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4835 ProtocolLocs.push_back(*ToProtoLocOrErr);
4836 else
4837 return ToProtoLocOrErr.takeError();
4840 // FIXME: If we're merging, make sure that the protocol list is the same.
4841 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4842 ProtocolLocs.data(), Importer.getToContext());
4844 } else {
4845 Importer.MapImported(D, ToCategory);
4848 // Import all of the members of this category.
4849 if (Error Err = ImportDeclContext(D))
4850 return std::move(Err);
4852 // If we have an implementation, import it as well.
4853 if (D->getImplementation()) {
4854 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4855 import(D->getImplementation()))
4856 ToCategory->setImplementation(*ToImplOrErr);
4857 else
4858 return ToImplOrErr.takeError();
4861 return ToCategory;
4864 Error ASTNodeImporter::ImportDefinition(
4865 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4866 if (To->getDefinition()) {
4867 if (shouldForceImportDeclContext(Kind))
4868 if (Error Err = ImportDeclContext(From))
4869 return Err;
4870 return Error::success();
4873 // Start the protocol definition
4874 To->startDefinition();
4876 // Import protocols
4877 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4878 SmallVector<SourceLocation, 4> ProtocolLocs;
4879 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4880 From->protocol_loc_begin();
4881 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4882 FromProtoEnd = From->protocol_end();
4883 FromProto != FromProtoEnd;
4884 ++FromProto, ++FromProtoLoc) {
4885 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4886 Protocols.push_back(*ToProtoOrErr);
4887 else
4888 return ToProtoOrErr.takeError();
4890 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4891 ProtocolLocs.push_back(*ToProtoLocOrErr);
4892 else
4893 return ToProtoLocOrErr.takeError();
4897 // FIXME: If we're merging, make sure that the protocol list is the same.
4898 To->setProtocolList(Protocols.data(), Protocols.size(),
4899 ProtocolLocs.data(), Importer.getToContext());
4901 if (shouldForceImportDeclContext(Kind)) {
4902 // Import all of the members of this protocol.
4903 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4904 return Err;
4906 return Error::success();
4909 ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4910 // If this protocol has a definition in the translation unit we're coming
4911 // from, but this particular declaration is not that definition, import the
4912 // definition and map to that.
4913 ObjCProtocolDecl *Definition = D->getDefinition();
4914 if (Definition && Definition != D) {
4915 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4916 return Importer.MapImported(D, *ImportedDefOrErr);
4917 else
4918 return ImportedDefOrErr.takeError();
4921 // Import the major distinguishing characteristics of a protocol.
4922 DeclContext *DC, *LexicalDC;
4923 DeclarationName Name;
4924 SourceLocation Loc;
4925 NamedDecl *ToD;
4926 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4927 return std::move(Err);
4928 if (ToD)
4929 return ToD;
4931 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4932 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4933 for (auto *FoundDecl : FoundDecls) {
4934 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4935 continue;
4937 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4938 break;
4941 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4942 if (!ToProto) {
4943 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4944 if (!ToAtBeginLocOrErr)
4945 return ToAtBeginLocOrErr.takeError();
4947 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4948 Name.getAsIdentifierInfo(), Loc,
4949 *ToAtBeginLocOrErr,
4950 /*PrevDecl=*/nullptr))
4951 return ToProto;
4952 ToProto->setLexicalDeclContext(LexicalDC);
4953 LexicalDC->addDeclInternal(ToProto);
4956 Importer.MapImported(D, ToProto);
4958 if (D->isThisDeclarationADefinition())
4959 if (Error Err = ImportDefinition(D, ToProto))
4960 return std::move(Err);
4962 return ToProto;
4965 ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4966 DeclContext *DC, *LexicalDC;
4967 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4968 return std::move(Err);
4970 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4971 if (!ExternLocOrErr)
4972 return ExternLocOrErr.takeError();
4974 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4975 if (!LangLocOrErr)
4976 return LangLocOrErr.takeError();
4978 bool HasBraces = D->hasBraces();
4980 LinkageSpecDecl *ToLinkageSpec;
4981 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4982 *ExternLocOrErr, *LangLocOrErr,
4983 D->getLanguage(), HasBraces))
4984 return ToLinkageSpec;
4986 if (HasBraces) {
4987 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4988 if (!RBraceLocOrErr)
4989 return RBraceLocOrErr.takeError();
4990 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4993 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4994 LexicalDC->addDeclInternal(ToLinkageSpec);
4996 return ToLinkageSpec;
4999 ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
5000 BaseUsingDecl *ToSI) {
5001 for (UsingShadowDecl *FromShadow : D->shadows()) {
5002 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
5003 ToSI->addShadowDecl(*ToShadowOrErr);
5004 else
5005 // FIXME: We return error here but the definition is already created
5006 // and available with lookups. How to fix this?..
5007 return ToShadowOrErr.takeError();
5009 return ToSI;
5012 ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
5013 DeclContext *DC, *LexicalDC;
5014 DeclarationName Name;
5015 SourceLocation Loc;
5016 NamedDecl *ToD = nullptr;
5017 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5018 return std::move(Err);
5019 if (ToD)
5020 return ToD;
5022 Error Err = Error::success();
5023 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
5024 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5025 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5026 if (Err)
5027 return std::move(Err);
5029 DeclarationNameInfo NameInfo(Name, ToLoc);
5030 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
5031 return std::move(Err);
5033 UsingDecl *ToUsing;
5034 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
5035 ToUsingLoc, ToQualifierLoc, NameInfo,
5036 D->hasTypename()))
5037 return ToUsing;
5039 ToUsing->setLexicalDeclContext(LexicalDC);
5040 LexicalDC->addDeclInternal(ToUsing);
5042 if (NamedDecl *FromPattern =
5043 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
5044 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
5045 Importer.getToContext().setInstantiatedFromUsingDecl(
5046 ToUsing, *ToPatternOrErr);
5047 else
5048 return ToPatternOrErr.takeError();
5051 return ImportUsingShadowDecls(D, ToUsing);
5054 ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
5055 DeclContext *DC, *LexicalDC;
5056 DeclarationName Name;
5057 SourceLocation Loc;
5058 NamedDecl *ToD = nullptr;
5059 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5060 return std::move(Err);
5061 if (ToD)
5062 return ToD;
5064 Error Err = Error::success();
5065 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5066 auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
5067 auto ToNameLoc = importChecked(Err, D->getLocation());
5068 auto *ToEnumType = importChecked(Err, D->getEnumType());
5069 if (Err)
5070 return std::move(Err);
5072 UsingEnumDecl *ToUsingEnum;
5073 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
5074 ToUsingLoc, ToEnumLoc, ToNameLoc, ToEnumType))
5075 return ToUsingEnum;
5077 ToUsingEnum->setLexicalDeclContext(LexicalDC);
5078 LexicalDC->addDeclInternal(ToUsingEnum);
5080 if (UsingEnumDecl *FromPattern =
5081 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) {
5082 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
5083 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
5084 *ToPatternOrErr);
5085 else
5086 return ToPatternOrErr.takeError();
5089 return ImportUsingShadowDecls(D, ToUsingEnum);
5092 ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
5093 DeclContext *DC, *LexicalDC;
5094 DeclarationName Name;
5095 SourceLocation Loc;
5096 NamedDecl *ToD = nullptr;
5097 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5098 return std::move(Err);
5099 if (ToD)
5100 return ToD;
5102 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
5103 if (!ToIntroducerOrErr)
5104 return ToIntroducerOrErr.takeError();
5106 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
5107 if (!ToTargetOrErr)
5108 return ToTargetOrErr.takeError();
5110 UsingShadowDecl *ToShadow;
5111 if (auto *FromConstructorUsingShadow =
5112 dyn_cast<ConstructorUsingShadowDecl>(D)) {
5113 Error Err = Error::success();
5114 ConstructorUsingShadowDecl *Nominated = importChecked(
5115 Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
5116 if (Err)
5117 return std::move(Err);
5118 // The 'Target' parameter of ConstructorUsingShadowDecl constructor
5119 // is really the "NominatedBaseClassShadowDecl" value if it exists
5120 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
5121 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
5122 // get the correct values.
5123 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
5124 ToShadow, D, Importer.getToContext(), DC, Loc,
5125 cast<UsingDecl>(*ToIntroducerOrErr),
5126 Nominated ? Nominated : *ToTargetOrErr,
5127 FromConstructorUsingShadow->constructsVirtualBase()))
5128 return ToShadow;
5129 } else {
5130 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
5131 Name, *ToIntroducerOrErr, *ToTargetOrErr))
5132 return ToShadow;
5135 ToShadow->setLexicalDeclContext(LexicalDC);
5136 ToShadow->setAccess(D->getAccess());
5138 if (UsingShadowDecl *FromPattern =
5139 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
5140 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
5141 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
5142 ToShadow, *ToPatternOrErr);
5143 else
5144 // FIXME: We return error here but the definition is already created
5145 // and available with lookups. How to fix this?..
5146 return ToPatternOrErr.takeError();
5149 LexicalDC->addDeclInternal(ToShadow);
5151 return ToShadow;
5154 ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
5155 DeclContext *DC, *LexicalDC;
5156 DeclarationName Name;
5157 SourceLocation Loc;
5158 NamedDecl *ToD = nullptr;
5159 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5160 return std::move(Err);
5161 if (ToD)
5162 return ToD;
5164 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
5165 if (!ToComAncestorOrErr)
5166 return ToComAncestorOrErr.takeError();
5168 Error Err = Error::success();
5169 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
5170 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5171 auto ToNamespaceKeyLocation =
5172 importChecked(Err, D->getNamespaceKeyLocation());
5173 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5174 auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
5175 if (Err)
5176 return std::move(Err);
5178 UsingDirectiveDecl *ToUsingDir;
5179 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
5180 ToUsingLoc,
5181 ToNamespaceKeyLocation,
5182 ToQualifierLoc,
5183 ToIdentLocation,
5184 ToNominatedNamespace, *ToComAncestorOrErr))
5185 return ToUsingDir;
5187 ToUsingDir->setLexicalDeclContext(LexicalDC);
5188 LexicalDC->addDeclInternal(ToUsingDir);
5190 return ToUsingDir;
5193 ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
5194 DeclContext *DC, *LexicalDC;
5195 DeclarationName Name;
5196 SourceLocation Loc;
5197 NamedDecl *ToD = nullptr;
5198 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5199 return std::move(Err);
5200 if (ToD)
5201 return ToD;
5203 auto ToInstantiatedFromUsingOrErr =
5204 Importer.Import(D->getInstantiatedFromUsingDecl());
5205 if (!ToInstantiatedFromUsingOrErr)
5206 return ToInstantiatedFromUsingOrErr.takeError();
5207 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
5208 if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
5209 return std::move(Err);
5211 UsingPackDecl *ToUsingPack;
5212 if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
5213 cast<NamedDecl>(*ToInstantiatedFromUsingOrErr),
5214 Expansions))
5215 return ToUsingPack;
5217 addDeclToContexts(D, ToUsingPack);
5219 return ToUsingPack;
5222 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
5223 UnresolvedUsingValueDecl *D) {
5224 DeclContext *DC, *LexicalDC;
5225 DeclarationName Name;
5226 SourceLocation Loc;
5227 NamedDecl *ToD = nullptr;
5228 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5229 return std::move(Err);
5230 if (ToD)
5231 return ToD;
5233 Error Err = Error::success();
5234 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
5235 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5236 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5237 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
5238 if (Err)
5239 return std::move(Err);
5241 DeclarationNameInfo NameInfo(Name, ToLoc);
5242 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
5243 return std::move(Err);
5245 UnresolvedUsingValueDecl *ToUsingValue;
5246 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
5247 ToUsingLoc, ToQualifierLoc, NameInfo,
5248 ToEllipsisLoc))
5249 return ToUsingValue;
5251 ToUsingValue->setAccess(D->getAccess());
5252 ToUsingValue->setLexicalDeclContext(LexicalDC);
5253 LexicalDC->addDeclInternal(ToUsingValue);
5255 return ToUsingValue;
5258 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
5259 UnresolvedUsingTypenameDecl *D) {
5260 DeclContext *DC, *LexicalDC;
5261 DeclarationName Name;
5262 SourceLocation Loc;
5263 NamedDecl *ToD = nullptr;
5264 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5265 return std::move(Err);
5266 if (ToD)
5267 return ToD;
5269 Error Err = Error::success();
5270 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5271 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
5272 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5273 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
5274 if (Err)
5275 return std::move(Err);
5277 UnresolvedUsingTypenameDecl *ToUsing;
5278 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
5279 ToUsingLoc, ToTypenameLoc,
5280 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
5281 return ToUsing;
5283 ToUsing->setAccess(D->getAccess());
5284 ToUsing->setLexicalDeclContext(LexicalDC);
5285 LexicalDC->addDeclInternal(ToUsing);
5287 return ToUsing;
5290 ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
5291 Decl* ToD = nullptr;
5292 switch (D->getBuiltinTemplateKind()) {
5293 case BuiltinTemplateKind::BTK__make_integer_seq:
5294 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
5295 break;
5296 case BuiltinTemplateKind::BTK__type_pack_element:
5297 ToD = Importer.getToContext().getTypePackElementDecl();
5298 break;
5300 assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
5301 Importer.MapImported(D, ToD);
5302 return ToD;
5305 Error ASTNodeImporter::ImportDefinition(
5306 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
5307 if (To->getDefinition()) {
5308 // Check consistency of superclass.
5309 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
5310 if (FromSuper) {
5311 if (auto FromSuperOrErr = import(FromSuper))
5312 FromSuper = *FromSuperOrErr;
5313 else
5314 return FromSuperOrErr.takeError();
5317 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
5318 if ((bool)FromSuper != (bool)ToSuper ||
5319 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
5320 Importer.ToDiag(To->getLocation(),
5321 diag::warn_odr_objc_superclass_inconsistent)
5322 << To->getDeclName();
5323 if (ToSuper)
5324 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
5325 << To->getSuperClass()->getDeclName();
5326 else
5327 Importer.ToDiag(To->getLocation(),
5328 diag::note_odr_objc_missing_superclass);
5329 if (From->getSuperClass())
5330 Importer.FromDiag(From->getSuperClassLoc(),
5331 diag::note_odr_objc_superclass)
5332 << From->getSuperClass()->getDeclName();
5333 else
5334 Importer.FromDiag(From->getLocation(),
5335 diag::note_odr_objc_missing_superclass);
5338 if (shouldForceImportDeclContext(Kind))
5339 if (Error Err = ImportDeclContext(From))
5340 return Err;
5341 return Error::success();
5344 // Start the definition.
5345 To->startDefinition();
5347 // If this class has a superclass, import it.
5348 if (From->getSuperClass()) {
5349 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
5350 To->setSuperClass(*SuperTInfoOrErr);
5351 else
5352 return SuperTInfoOrErr.takeError();
5355 // Import protocols
5356 SmallVector<ObjCProtocolDecl *, 4> Protocols;
5357 SmallVector<SourceLocation, 4> ProtocolLocs;
5358 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
5359 From->protocol_loc_begin();
5361 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
5362 FromProtoEnd = From->protocol_end();
5363 FromProto != FromProtoEnd;
5364 ++FromProto, ++FromProtoLoc) {
5365 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
5366 Protocols.push_back(*ToProtoOrErr);
5367 else
5368 return ToProtoOrErr.takeError();
5370 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
5371 ProtocolLocs.push_back(*ToProtoLocOrErr);
5372 else
5373 return ToProtoLocOrErr.takeError();
5377 // FIXME: If we're merging, make sure that the protocol list is the same.
5378 To->setProtocolList(Protocols.data(), Protocols.size(),
5379 ProtocolLocs.data(), Importer.getToContext());
5381 // Import categories. When the categories themselves are imported, they'll
5382 // hook themselves into this interface.
5383 for (auto *Cat : From->known_categories()) {
5384 auto ToCatOrErr = import(Cat);
5385 if (!ToCatOrErr)
5386 return ToCatOrErr.takeError();
5389 // If we have an @implementation, import it as well.
5390 if (From->getImplementation()) {
5391 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
5392 import(From->getImplementation()))
5393 To->setImplementation(*ToImplOrErr);
5394 else
5395 return ToImplOrErr.takeError();
5398 // Import all of the members of this class.
5399 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5400 return Err;
5402 return Error::success();
5405 Expected<ObjCTypeParamList *>
5406 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
5407 if (!list)
5408 return nullptr;
5410 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
5411 for (auto *fromTypeParam : *list) {
5412 if (auto toTypeParamOrErr = import(fromTypeParam))
5413 toTypeParams.push_back(*toTypeParamOrErr);
5414 else
5415 return toTypeParamOrErr.takeError();
5418 auto LAngleLocOrErr = import(list->getLAngleLoc());
5419 if (!LAngleLocOrErr)
5420 return LAngleLocOrErr.takeError();
5422 auto RAngleLocOrErr = import(list->getRAngleLoc());
5423 if (!RAngleLocOrErr)
5424 return RAngleLocOrErr.takeError();
5426 return ObjCTypeParamList::create(Importer.getToContext(),
5427 *LAngleLocOrErr,
5428 toTypeParams,
5429 *RAngleLocOrErr);
5432 ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
5433 // If this class has a definition in the translation unit we're coming from,
5434 // but this particular declaration is not that definition, import the
5435 // definition and map to that.
5436 ObjCInterfaceDecl *Definition = D->getDefinition();
5437 if (Definition && Definition != D) {
5438 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5439 return Importer.MapImported(D, *ImportedDefOrErr);
5440 else
5441 return ImportedDefOrErr.takeError();
5444 // Import the major distinguishing characteristics of an @interface.
5445 DeclContext *DC, *LexicalDC;
5446 DeclarationName Name;
5447 SourceLocation Loc;
5448 NamedDecl *ToD;
5449 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5450 return std::move(Err);
5451 if (ToD)
5452 return ToD;
5454 // Look for an existing interface with the same name.
5455 ObjCInterfaceDecl *MergeWithIface = nullptr;
5456 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5457 for (auto *FoundDecl : FoundDecls) {
5458 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5459 continue;
5461 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
5462 break;
5465 // Create an interface declaration, if one does not already exist.
5466 ObjCInterfaceDecl *ToIface = MergeWithIface;
5467 if (!ToIface) {
5468 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5469 if (!AtBeginLocOrErr)
5470 return AtBeginLocOrErr.takeError();
5472 if (GetImportedOrCreateDecl(
5473 ToIface, D, Importer.getToContext(), DC,
5474 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
5475 /*TypeParamList=*/nullptr,
5476 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
5477 return ToIface;
5478 ToIface->setLexicalDeclContext(LexicalDC);
5479 LexicalDC->addDeclInternal(ToIface);
5481 Importer.MapImported(D, ToIface);
5482 // Import the type parameter list after MapImported, to avoid
5483 // loops when bringing in their DeclContext.
5484 if (auto ToPListOrErr =
5485 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
5486 ToIface->setTypeParamList(*ToPListOrErr);
5487 else
5488 return ToPListOrErr.takeError();
5490 if (D->isThisDeclarationADefinition())
5491 if (Error Err = ImportDefinition(D, ToIface))
5492 return std::move(Err);
5494 return ToIface;
5497 ExpectedDecl
5498 ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
5499 ObjCCategoryDecl *Category;
5500 if (Error Err = importInto(Category, D->getCategoryDecl()))
5501 return std::move(Err);
5503 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5504 if (!ToImpl) {
5505 DeclContext *DC, *LexicalDC;
5506 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5507 return std::move(Err);
5509 Error Err = Error::success();
5510 auto ToLocation = importChecked(Err, D->getLocation());
5511 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5512 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5513 if (Err)
5514 return std::move(Err);
5516 if (GetImportedOrCreateDecl(
5517 ToImpl, D, Importer.getToContext(), DC,
5518 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5519 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5520 return ToImpl;
5522 ToImpl->setLexicalDeclContext(LexicalDC);
5523 LexicalDC->addDeclInternal(ToImpl);
5524 Category->setImplementation(ToImpl);
5527 Importer.MapImported(D, ToImpl);
5528 if (Error Err = ImportDeclContext(D))
5529 return std::move(Err);
5531 return ToImpl;
5534 ExpectedDecl
5535 ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
5536 // Find the corresponding interface.
5537 ObjCInterfaceDecl *Iface;
5538 if (Error Err = importInto(Iface, D->getClassInterface()))
5539 return std::move(Err);
5541 // Import the superclass, if any.
5542 ObjCInterfaceDecl *Super;
5543 if (Error Err = importInto(Super, D->getSuperClass()))
5544 return std::move(Err);
5546 ObjCImplementationDecl *Impl = Iface->getImplementation();
5547 if (!Impl) {
5548 // We haven't imported an implementation yet. Create a new @implementation
5549 // now.
5550 DeclContext *DC, *LexicalDC;
5551 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5552 return std::move(Err);
5554 Error Err = Error::success();
5555 auto ToLocation = importChecked(Err, D->getLocation());
5556 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5557 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5558 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5559 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5560 if (Err)
5561 return std::move(Err);
5563 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5564 DC, Iface, Super,
5565 ToLocation,
5566 ToAtStartLoc,
5567 ToSuperClassLoc,
5568 ToIvarLBraceLoc,
5569 ToIvarRBraceLoc))
5570 return Impl;
5572 Impl->setLexicalDeclContext(LexicalDC);
5574 // Associate the implementation with the class it implements.
5575 Iface->setImplementation(Impl);
5576 Importer.MapImported(D, Iface->getImplementation());
5577 } else {
5578 Importer.MapImported(D, Iface->getImplementation());
5580 // Verify that the existing @implementation has the same superclass.
5581 if ((Super && !Impl->getSuperClass()) ||
5582 (!Super && Impl->getSuperClass()) ||
5583 (Super && Impl->getSuperClass() &&
5584 !declaresSameEntity(Super->getCanonicalDecl(),
5585 Impl->getSuperClass()))) {
5586 Importer.ToDiag(Impl->getLocation(),
5587 diag::warn_odr_objc_superclass_inconsistent)
5588 << Iface->getDeclName();
5589 // FIXME: It would be nice to have the location of the superclass
5590 // below.
5591 if (Impl->getSuperClass())
5592 Importer.ToDiag(Impl->getLocation(),
5593 diag::note_odr_objc_superclass)
5594 << Impl->getSuperClass()->getDeclName();
5595 else
5596 Importer.ToDiag(Impl->getLocation(),
5597 diag::note_odr_objc_missing_superclass);
5598 if (D->getSuperClass())
5599 Importer.FromDiag(D->getLocation(),
5600 diag::note_odr_objc_superclass)
5601 << D->getSuperClass()->getDeclName();
5602 else
5603 Importer.FromDiag(D->getLocation(),
5604 diag::note_odr_objc_missing_superclass);
5606 return make_error<ASTImportError>(ASTImportError::NameConflict);
5610 // Import all of the members of this @implementation.
5611 if (Error Err = ImportDeclContext(D))
5612 return std::move(Err);
5614 return Impl;
5617 ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5618 // Import the major distinguishing characteristics of an @property.
5619 DeclContext *DC, *LexicalDC;
5620 DeclarationName Name;
5621 SourceLocation Loc;
5622 NamedDecl *ToD;
5623 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5624 return std::move(Err);
5625 if (ToD)
5626 return ToD;
5628 // Check whether we have already imported this property.
5629 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5630 for (auto *FoundDecl : FoundDecls) {
5631 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5632 // Instance and class properties can share the same name but are different
5633 // declarations.
5634 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5635 continue;
5637 // Check property types.
5638 if (!Importer.IsStructurallyEquivalent(D->getType(),
5639 FoundProp->getType())) {
5640 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5641 << Name << D->getType() << FoundProp->getType();
5642 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5643 << FoundProp->getType();
5645 return make_error<ASTImportError>(ASTImportError::NameConflict);
5648 // FIXME: Check property attributes, getters, setters, etc.?
5650 // Consider these properties to be equivalent.
5651 Importer.MapImported(D, FoundProp);
5652 return FoundProp;
5656 Error Err = Error::success();
5657 auto ToType = importChecked(Err, D->getType());
5658 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5659 auto ToAtLoc = importChecked(Err, D->getAtLoc());
5660 auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5661 if (Err)
5662 return std::move(Err);
5664 // Create the new property.
5665 ObjCPropertyDecl *ToProperty;
5666 if (GetImportedOrCreateDecl(
5667 ToProperty, D, Importer.getToContext(), DC, Loc,
5668 Name.getAsIdentifierInfo(), ToAtLoc,
5669 ToLParenLoc, ToType,
5670 ToTypeSourceInfo, D->getPropertyImplementation()))
5671 return ToProperty;
5673 auto ToGetterName = importChecked(Err, D->getGetterName());
5674 auto ToSetterName = importChecked(Err, D->getSetterName());
5675 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
5676 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
5677 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
5678 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
5679 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
5680 if (Err)
5681 return std::move(Err);
5683 ToProperty->setLexicalDeclContext(LexicalDC);
5684 LexicalDC->addDeclInternal(ToProperty);
5686 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5687 ToProperty->setPropertyAttributesAsWritten(
5688 D->getPropertyAttributesAsWritten());
5689 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
5690 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
5691 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5692 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5693 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5694 return ToProperty;
5697 ExpectedDecl
5698 ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5699 ObjCPropertyDecl *Property;
5700 if (Error Err = importInto(Property, D->getPropertyDecl()))
5701 return std::move(Err);
5703 DeclContext *DC, *LexicalDC;
5704 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5705 return std::move(Err);
5707 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
5709 // Import the ivar (for an @synthesize).
5710 ObjCIvarDecl *Ivar = nullptr;
5711 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
5712 return std::move(Err);
5714 ObjCPropertyImplDecl *ToImpl
5715 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
5716 Property->getQueryKind());
5717 if (!ToImpl) {
5719 Error Err = Error::success();
5720 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
5721 auto ToLocation = importChecked(Err, D->getLocation());
5722 auto ToPropertyIvarDeclLoc =
5723 importChecked(Err, D->getPropertyIvarDeclLoc());
5724 if (Err)
5725 return std::move(Err);
5727 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5728 ToBeginLoc,
5729 ToLocation, Property,
5730 D->getPropertyImplementation(), Ivar,
5731 ToPropertyIvarDeclLoc))
5732 return ToImpl;
5734 ToImpl->setLexicalDeclContext(LexicalDC);
5735 LexicalDC->addDeclInternal(ToImpl);
5736 } else {
5737 // Check that we have the same kind of property implementation (@synthesize
5738 // vs. @dynamic).
5739 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5740 Importer.ToDiag(ToImpl->getLocation(),
5741 diag::warn_odr_objc_property_impl_kind_inconsistent)
5742 << Property->getDeclName()
5743 << (ToImpl->getPropertyImplementation()
5744 == ObjCPropertyImplDecl::Dynamic);
5745 Importer.FromDiag(D->getLocation(),
5746 diag::note_odr_objc_property_impl_kind)
5747 << D->getPropertyDecl()->getDeclName()
5748 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5750 return make_error<ASTImportError>(ASTImportError::NameConflict);
5753 // For @synthesize, check that we have the same
5754 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5755 Ivar != ToImpl->getPropertyIvarDecl()) {
5756 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5757 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5758 << Property->getDeclName()
5759 << ToImpl->getPropertyIvarDecl()->getDeclName()
5760 << Ivar->getDeclName();
5761 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5762 diag::note_odr_objc_synthesize_ivar_here)
5763 << D->getPropertyIvarDecl()->getDeclName();
5765 return make_error<ASTImportError>(ASTImportError::NameConflict);
5768 // Merge the existing implementation with the new implementation.
5769 Importer.MapImported(D, ToImpl);
5772 return ToImpl;
5775 ExpectedDecl
5776 ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5777 // For template arguments, we adopt the translation unit as our declaration
5778 // context. This context will be fixed when the actual template declaration
5779 // is created.
5781 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5782 if (!BeginLocOrErr)
5783 return BeginLocOrErr.takeError();
5785 ExpectedSLoc LocationOrErr = import(D->getLocation());
5786 if (!LocationOrErr)
5787 return LocationOrErr.takeError();
5789 TemplateTypeParmDecl *ToD = nullptr;
5790 if (GetImportedOrCreateDecl(
5791 ToD, D, Importer.getToContext(),
5792 Importer.getToContext().getTranslationUnitDecl(),
5793 *BeginLocOrErr, *LocationOrErr,
5794 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5795 D->wasDeclaredWithTypename(), D->isParameterPack(),
5796 D->hasTypeConstraint()))
5797 return ToD;
5799 // Import the type-constraint
5800 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5802 Error Err = Error::success();
5803 auto ToConceptRef = importChecked(Err, TC->getConceptReference());
5804 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
5805 if (Err)
5806 return std::move(Err);
5808 ToD->setTypeConstraint(ToConceptRef, ToIDC);
5811 if (D->hasDefaultArgument()) {
5812 Expected<TypeSourceInfo *> ToDefaultArgOrErr =
5813 import(D->getDefaultArgumentInfo());
5814 if (!ToDefaultArgOrErr)
5815 return ToDefaultArgOrErr.takeError();
5816 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5819 return ToD;
5822 ExpectedDecl
5823 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5825 Error Err = Error::success();
5826 auto ToDeclName = importChecked(Err, D->getDeclName());
5827 auto ToLocation = importChecked(Err, D->getLocation());
5828 auto ToType = importChecked(Err, D->getType());
5829 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5830 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5831 if (Err)
5832 return std::move(Err);
5834 NonTypeTemplateParmDecl *ToD = nullptr;
5835 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5836 Importer.getToContext().getTranslationUnitDecl(),
5837 ToInnerLocStart, ToLocation, D->getDepth(),
5838 D->getPosition(),
5839 ToDeclName.getAsIdentifierInfo(), ToType,
5840 D->isParameterPack(), ToTypeSourceInfo))
5841 return ToD;
5843 if (D->hasDefaultArgument()) {
5844 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
5845 if (!ToDefaultArgOrErr)
5846 return ToDefaultArgOrErr.takeError();
5847 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5850 return ToD;
5853 ExpectedDecl
5854 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5855 // Import the name of this declaration.
5856 auto NameOrErr = import(D->getDeclName());
5857 if (!NameOrErr)
5858 return NameOrErr.takeError();
5860 // Import the location of this declaration.
5861 ExpectedSLoc LocationOrErr = import(D->getLocation());
5862 if (!LocationOrErr)
5863 return LocationOrErr.takeError();
5865 // Import template parameters.
5866 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5867 if (!TemplateParamsOrErr)
5868 return TemplateParamsOrErr.takeError();
5870 TemplateTemplateParmDecl *ToD = nullptr;
5871 if (GetImportedOrCreateDecl(
5872 ToD, D, Importer.getToContext(),
5873 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5874 D->getDepth(), D->getPosition(), D->isParameterPack(),
5875 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
5876 return ToD;
5878 if (D->hasDefaultArgument()) {
5879 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5880 import(D->getDefaultArgument());
5881 if (!ToDefaultArgOrErr)
5882 return ToDefaultArgOrErr.takeError();
5883 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
5886 return ToD;
5889 // Returns the definition for a (forward) declaration of a TemplateDecl, if
5890 // it has any definition in the redecl chain.
5891 template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5892 assert(D->getTemplatedDecl() && "Should be called on templates only");
5893 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5894 if (!ToTemplatedDef)
5895 return nullptr;
5896 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5897 return cast_or_null<T>(TemplateWithDef);
5900 ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
5902 // Import the major distinguishing characteristics of this class template.
5903 DeclContext *DC, *LexicalDC;
5904 DeclarationName Name;
5905 SourceLocation Loc;
5906 NamedDecl *ToD;
5907 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5908 return std::move(Err);
5909 if (ToD)
5910 return ToD;
5912 bool IsFriendTemplate = D->getFriendObjectKind() != Decl::FOK_None;
5913 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
5914 : DC->isDependentContext();
5915 bool DependentFriend = IsFriendTemplate && IsDependentContext;
5917 ClassTemplateDecl *FoundByLookup = nullptr;
5919 // We may already have a template of the same name; try to find and match it.
5920 if (!DependentFriend && !DC->isFunctionOrMethod()) {
5921 SmallVector<NamedDecl *, 4> ConflictingDecls;
5922 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5923 for (auto *FoundDecl : FoundDecls) {
5924 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
5925 Decl::IDNS_TagFriend))
5926 continue;
5928 Decl *Found = FoundDecl;
5929 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5930 if (FoundTemplate) {
5931 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
5932 continue;
5934 // FIXME: sufficient conditon for 'IgnoreTemplateParmDepth'?
5935 bool IgnoreTemplateParmDepth =
5936 FoundTemplate->getFriendObjectKind() != Decl::FOK_None &&
5937 !D->specializations().empty();
5938 if (IsStructuralMatch(D, FoundTemplate, /*Complain=*/true,
5939 IgnoreTemplateParmDepth)) {
5940 ClassTemplateDecl *TemplateWithDef =
5941 getTemplateDefinition(FoundTemplate);
5942 if (D->isThisDeclarationADefinition() && TemplateWithDef)
5943 return Importer.MapImported(D, TemplateWithDef);
5944 if (!FoundByLookup)
5945 FoundByLookup = FoundTemplate;
5946 // Search in all matches because there may be multiple decl chains,
5947 // see ASTTests test ImportExistingFriendClassTemplateDef.
5948 continue;
5950 ConflictingDecls.push_back(FoundDecl);
5954 if (!ConflictingDecls.empty()) {
5955 ExpectedName NameOrErr = Importer.HandleNameConflict(
5956 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5957 ConflictingDecls.size());
5958 if (NameOrErr)
5959 Name = NameOrErr.get();
5960 else
5961 return NameOrErr.takeError();
5965 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5967 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5968 if (!TemplateParamsOrErr)
5969 return TemplateParamsOrErr.takeError();
5971 // Create the declaration that is being templated.
5972 CXXRecordDecl *ToTemplated;
5973 if (Error Err = importInto(ToTemplated, FromTemplated))
5974 return std::move(Err);
5976 // Create the class template declaration itself.
5977 ClassTemplateDecl *D2;
5978 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5979 *TemplateParamsOrErr, ToTemplated))
5980 return D2;
5982 ToTemplated->setDescribedClassTemplate(D2);
5984 D2->setAccess(D->getAccess());
5985 D2->setLexicalDeclContext(LexicalDC);
5987 addDeclToContexts(D, D2);
5988 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
5990 if (FoundByLookup) {
5991 auto *Recent =
5992 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5994 // It is possible that during the import of the class template definition
5995 // we start the import of a fwd friend decl of the very same class template
5996 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5997 // had been created earlier and by that time the lookup could not find
5998 // anything existing, so it has no previous decl. Later, (still during the
5999 // import of the fwd friend decl) we start to import the definition again
6000 // and this time the lookup finds the previous fwd friend class template.
6001 // In this case we must set up the previous decl for the templated decl.
6002 if (!ToTemplated->getPreviousDecl()) {
6003 assert(FoundByLookup->getTemplatedDecl() &&
6004 "Found decl must have its templated decl set");
6005 CXXRecordDecl *PrevTemplated =
6006 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6007 if (ToTemplated != PrevTemplated)
6008 ToTemplated->setPreviousDecl(PrevTemplated);
6011 D2->setPreviousDecl(Recent);
6014 return D2;
6017 ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
6018 ClassTemplateSpecializationDecl *D) {
6019 ClassTemplateDecl *ClassTemplate;
6020 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
6021 return std::move(Err);
6023 // Import the context of this declaration.
6024 DeclContext *DC, *LexicalDC;
6025 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6026 return std::move(Err);
6028 // Import template arguments.
6029 SmallVector<TemplateArgument, 2> TemplateArgs;
6030 if (Error Err =
6031 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
6032 return std::move(Err);
6033 // Try to find an existing specialization with these template arguments and
6034 // template parameter list.
6035 void *InsertPos = nullptr;
6036 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6037 ClassTemplatePartialSpecializationDecl *PartialSpec =
6038 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
6040 // Import template parameters.
6041 TemplateParameterList *ToTPList = nullptr;
6043 if (PartialSpec) {
6044 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
6045 if (!ToTPListOrErr)
6046 return ToTPListOrErr.takeError();
6047 ToTPList = *ToTPListOrErr;
6048 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
6049 *ToTPListOrErr,
6050 InsertPos);
6051 } else
6052 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
6054 if (PrevDecl) {
6055 if (IsStructuralMatch(D, PrevDecl)) {
6056 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
6057 if (D->isThisDeclarationADefinition() && PrevDefinition) {
6058 Importer.MapImported(D, PrevDefinition);
6059 // Import those default field initializers which have been
6060 // instantiated in the "From" context, but not in the "To" context.
6061 for (auto *FromField : D->fields()) {
6062 auto ToOrErr = import(FromField);
6063 if (!ToOrErr)
6064 return ToOrErr.takeError();
6067 // Import those methods which have been instantiated in the
6068 // "From" context, but not in the "To" context.
6069 for (CXXMethodDecl *FromM : D->methods()) {
6070 auto ToOrErr = import(FromM);
6071 if (!ToOrErr)
6072 return ToOrErr.takeError();
6075 // TODO Import instantiated default arguments.
6076 // TODO Import instantiated exception specifications.
6078 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
6079 // what else could be fused during an AST merge.
6080 return PrevDefinition;
6082 } else { // ODR violation.
6083 // FIXME HandleNameConflict
6084 return make_error<ASTImportError>(ASTImportError::NameConflict);
6088 // Import the location of this declaration.
6089 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6090 if (!BeginLocOrErr)
6091 return BeginLocOrErr.takeError();
6092 ExpectedSLoc IdLocOrErr = import(D->getLocation());
6093 if (!IdLocOrErr)
6094 return IdLocOrErr.takeError();
6096 // Create the specialization.
6097 ClassTemplateSpecializationDecl *D2 = nullptr;
6098 if (PartialSpec) {
6099 // Import TemplateArgumentListInfo.
6100 TemplateArgumentListInfo ToTAInfo;
6101 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
6102 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
6103 return std::move(Err);
6105 QualType CanonInjType;
6106 if (Error Err = importInto(
6107 CanonInjType, PartialSpec->getInjectedSpecializationType()))
6108 return std::move(Err);
6109 CanonInjType = CanonInjType.getCanonicalType();
6111 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
6112 D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr,
6113 *IdLocOrErr, ToTPList, ClassTemplate,
6114 llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()), ToTAInfo,
6115 CanonInjType,
6116 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
6117 return D2;
6119 // Update InsertPos, because preceding import calls may have invalidated
6120 // it by adding new specializations.
6121 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
6122 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
6123 InsertPos))
6124 // Add this partial specialization to the class template.
6125 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
6127 updateLookupTableForTemplateParameters(*ToTPList);
6128 } else { // Not a partial specialization.
6129 if (GetImportedOrCreateDecl(
6130 D2, D, Importer.getToContext(), D->getTagKind(), DC,
6131 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
6132 PrevDecl))
6133 return D2;
6135 // Update InsertPos, because preceding import calls may have invalidated
6136 // it by adding new specializations.
6137 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
6138 // Add this specialization to the class template.
6139 ClassTemplate->AddSpecialization(D2, InsertPos);
6142 D2->setSpecializationKind(D->getSpecializationKind());
6144 // Set the context of this specialization/instantiation.
6145 D2->setLexicalDeclContext(LexicalDC);
6147 // Add to the DC only if it was an explicit specialization/instantiation.
6148 if (D2->isExplicitInstantiationOrSpecialization()) {
6149 LexicalDC->addDeclInternal(D2);
6152 if (auto BraceRangeOrErr = import(D->getBraceRange()))
6153 D2->setBraceRange(*BraceRangeOrErr);
6154 else
6155 return BraceRangeOrErr.takeError();
6157 // Import the qualifier, if any.
6158 if (auto LocOrErr = import(D->getQualifierLoc()))
6159 D2->setQualifierInfo(*LocOrErr);
6160 else
6161 return LocOrErr.takeError();
6163 if (auto *TSI = D->getTypeAsWritten()) {
6164 if (auto TInfoOrErr = import(TSI))
6165 D2->setTypeAsWritten(*TInfoOrErr);
6166 else
6167 return TInfoOrErr.takeError();
6169 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
6170 D2->setTemplateKeywordLoc(*LocOrErr);
6171 else
6172 return LocOrErr.takeError();
6174 if (auto LocOrErr = import(D->getExternLoc()))
6175 D2->setExternLoc(*LocOrErr);
6176 else
6177 return LocOrErr.takeError();
6180 if (D->getPointOfInstantiation().isValid()) {
6181 if (auto POIOrErr = import(D->getPointOfInstantiation()))
6182 D2->setPointOfInstantiation(*POIOrErr);
6183 else
6184 return POIOrErr.takeError();
6187 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
6189 if (auto P = D->getInstantiatedFrom()) {
6190 if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) {
6191 if (auto CTDorErr = import(CTD))
6192 D2->setInstantiationOf(*CTDorErr);
6193 } else {
6194 auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(P);
6195 auto CTPSDOrErr = import(CTPSD);
6196 if (!CTPSDOrErr)
6197 return CTPSDOrErr.takeError();
6198 const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs();
6199 SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size());
6200 for (unsigned I = 0; I < DArgs.size(); ++I) {
6201 const TemplateArgument &DArg = DArgs[I];
6202 if (auto ArgOrErr = import(DArg))
6203 D2ArgsVec[I] = *ArgOrErr;
6204 else
6205 return ArgOrErr.takeError();
6207 D2->setInstantiationOf(
6208 *CTPSDOrErr,
6209 TemplateArgumentList::CreateCopy(Importer.getToContext(), D2ArgsVec));
6213 if (D->isCompleteDefinition())
6214 if (Error Err = ImportDefinition(D, D2))
6215 return std::move(Err);
6217 return D2;
6220 ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
6221 // Import the major distinguishing characteristics of this variable template.
6222 DeclContext *DC, *LexicalDC;
6223 DeclarationName Name;
6224 SourceLocation Loc;
6225 NamedDecl *ToD;
6226 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6227 return std::move(Err);
6228 if (ToD)
6229 return ToD;
6231 // We may already have a template of the same name; try to find and match it.
6232 assert(!DC->isFunctionOrMethod() &&
6233 "Variable templates cannot be declared at function scope");
6235 SmallVector<NamedDecl *, 4> ConflictingDecls;
6236 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6237 VarTemplateDecl *FoundByLookup = nullptr;
6238 for (auto *FoundDecl : FoundDecls) {
6239 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
6240 continue;
6242 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
6243 // Use the templated decl, some linkage flags are set only there.
6244 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
6245 D->getTemplatedDecl()))
6246 continue;
6247 if (IsStructuralMatch(D, FoundTemplate)) {
6248 // The Decl in the "From" context has a definition, but in the
6249 // "To" context we already have a definition.
6250 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
6251 if (D->isThisDeclarationADefinition() && FoundDef)
6252 // FIXME Check for ODR error if the two definitions have
6253 // different initializers?
6254 return Importer.MapImported(D, FoundDef);
6255 if (FoundTemplate->getDeclContext()->isRecord() &&
6256 D->getDeclContext()->isRecord())
6257 return Importer.MapImported(D, FoundTemplate);
6259 FoundByLookup = FoundTemplate;
6260 break;
6262 ConflictingDecls.push_back(FoundDecl);
6266 if (!ConflictingDecls.empty()) {
6267 ExpectedName NameOrErr = Importer.HandleNameConflict(
6268 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
6269 ConflictingDecls.size());
6270 if (NameOrErr)
6271 Name = NameOrErr.get();
6272 else
6273 return NameOrErr.takeError();
6276 VarDecl *DTemplated = D->getTemplatedDecl();
6278 // Import the type.
6279 // FIXME: Value not used?
6280 ExpectedType TypeOrErr = import(DTemplated->getType());
6281 if (!TypeOrErr)
6282 return TypeOrErr.takeError();
6284 // Create the declaration that is being templated.
6285 VarDecl *ToTemplated;
6286 if (Error Err = importInto(ToTemplated, DTemplated))
6287 return std::move(Err);
6289 // Create the variable template declaration itself.
6290 auto TemplateParamsOrErr = import(D->getTemplateParameters());
6291 if (!TemplateParamsOrErr)
6292 return TemplateParamsOrErr.takeError();
6294 VarTemplateDecl *ToVarTD;
6295 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
6296 Name, *TemplateParamsOrErr, ToTemplated))
6297 return ToVarTD;
6299 ToTemplated->setDescribedVarTemplate(ToVarTD);
6301 ToVarTD->setAccess(D->getAccess());
6302 ToVarTD->setLexicalDeclContext(LexicalDC);
6303 LexicalDC->addDeclInternal(ToVarTD);
6304 if (DC != Importer.getToContext().getTranslationUnitDecl())
6305 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
6307 if (FoundByLookup) {
6308 auto *Recent =
6309 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6310 if (!ToTemplated->getPreviousDecl()) {
6311 auto *PrevTemplated =
6312 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6313 if (ToTemplated != PrevTemplated)
6314 ToTemplated->setPreviousDecl(PrevTemplated);
6316 ToVarTD->setPreviousDecl(Recent);
6319 return ToVarTD;
6322 ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
6323 VarTemplateSpecializationDecl *D) {
6324 // If this record has a definition in the translation unit we're coming from,
6325 // but this particular declaration is not that definition, import the
6326 // definition and map to that.
6327 VarDecl *Definition = D->getDefinition();
6328 if (Definition && Definition != D) {
6329 if (ExpectedDecl ImportedDefOrErr = import(Definition))
6330 return Importer.MapImported(D, *ImportedDefOrErr);
6331 else
6332 return ImportedDefOrErr.takeError();
6335 VarTemplateDecl *VarTemplate = nullptr;
6336 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
6337 return std::move(Err);
6339 // Import the context of this declaration.
6340 DeclContext *DC, *LexicalDC;
6341 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6342 return std::move(Err);
6344 // Import the location of this declaration.
6345 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6346 if (!BeginLocOrErr)
6347 return BeginLocOrErr.takeError();
6349 auto IdLocOrErr = import(D->getLocation());
6350 if (!IdLocOrErr)
6351 return IdLocOrErr.takeError();
6353 // Import template arguments.
6354 SmallVector<TemplateArgument, 2> TemplateArgs;
6355 if (Error Err =
6356 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
6357 return std::move(Err);
6359 // Try to find an existing specialization with these template arguments.
6360 void *InsertPos = nullptr;
6361 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
6362 TemplateArgs, InsertPos);
6363 if (D2) {
6364 // We already have a variable template specialization with these template
6365 // arguments.
6367 // FIXME: Check for specialization vs. instantiation errors.
6369 if (VarDecl *FoundDef = D2->getDefinition()) {
6370 if (!D->isThisDeclarationADefinition() ||
6371 IsStructuralMatch(D, FoundDef)) {
6372 // The record types structurally match, or the "from" translation
6373 // unit only had a forward declaration anyway; call it the same
6374 // variable.
6375 return Importer.MapImported(D, FoundDef);
6378 } else {
6379 TemplateArgumentListInfo ToTAInfo;
6380 if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) {
6381 if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo))
6382 return std::move(Err);
6385 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
6386 // Create a new specialization.
6387 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
6388 // Import TemplateArgumentListInfo
6389 TemplateArgumentListInfo ArgInfos;
6390 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
6391 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
6392 if (Error Err = ImportTemplateArgumentListInfo(
6393 *FromTAArgsAsWritten, ArgInfos))
6394 return std::move(Err);
6396 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
6397 if (!ToTPListOrErr)
6398 return ToTPListOrErr.takeError();
6400 PartVarSpecDecl *ToPartial;
6401 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
6402 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
6403 VarTemplate, QualType(), nullptr,
6404 D->getStorageClass(), TemplateArgs, ArgInfos))
6405 return ToPartial;
6407 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
6408 FromPartial->getInstantiatedFromMember()))
6409 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
6410 else
6411 return ToInstOrErr.takeError();
6413 if (FromPartial->isMemberSpecialization())
6414 ToPartial->setMemberSpecialization();
6416 D2 = ToPartial;
6418 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
6419 // to adopt template parameters.
6420 // updateLookupTableForTemplateParameters(**ToTPListOrErr);
6421 } else { // Full specialization
6422 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
6423 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
6424 QualType(), nullptr, D->getStorageClass(),
6425 TemplateArgs))
6426 return D2;
6429 QualType T;
6430 if (Error Err = importInto(T, D->getType()))
6431 return std::move(Err);
6432 D2->setType(T);
6434 auto TInfoOrErr = import(D->getTypeSourceInfo());
6435 if (!TInfoOrErr)
6436 return TInfoOrErr.takeError();
6437 D2->setTypeSourceInfo(*TInfoOrErr);
6439 if (D->getPointOfInstantiation().isValid()) {
6440 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
6441 D2->setPointOfInstantiation(*POIOrErr);
6442 else
6443 return POIOrErr.takeError();
6446 D2->setSpecializationKind(D->getSpecializationKind());
6447 D2->setTemplateArgsInfo(ToTAInfo);
6449 // Add this specialization to the class template.
6450 VarTemplate->AddSpecialization(D2, InsertPos);
6452 // Import the qualifier, if any.
6453 if (auto LocOrErr = import(D->getQualifierLoc()))
6454 D2->setQualifierInfo(*LocOrErr);
6455 else
6456 return LocOrErr.takeError();
6458 if (D->isConstexpr())
6459 D2->setConstexpr(true);
6461 // Add the specialization to this context.
6462 D2->setLexicalDeclContext(LexicalDC);
6463 LexicalDC->addDeclInternal(D2);
6465 D2->setAccess(D->getAccess());
6468 if (Error Err = ImportInitializer(D, D2))
6469 return std::move(Err);
6471 return D2;
6474 ExpectedDecl
6475 ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
6476 DeclContext *DC, *LexicalDC;
6477 DeclarationName Name;
6478 SourceLocation Loc;
6479 NamedDecl *ToD;
6481 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6482 return std::move(Err);
6484 if (ToD)
6485 return ToD;
6487 const FunctionTemplateDecl *FoundByLookup = nullptr;
6489 // Try to find a function in our own ("to") context with the same name, same
6490 // type, and in the same context as the function we're importing.
6491 // FIXME Split this into a separate function.
6492 if (!LexicalDC->isFunctionOrMethod()) {
6493 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
6494 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6495 for (auto *FoundDecl : FoundDecls) {
6496 if (!FoundDecl->isInIdentifierNamespace(IDNS))
6497 continue;
6499 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
6500 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6501 continue;
6502 if (IsStructuralMatch(D, FoundTemplate)) {
6503 FunctionTemplateDecl *TemplateWithDef =
6504 getTemplateDefinition(FoundTemplate);
6505 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6506 return Importer.MapImported(D, TemplateWithDef);
6508 FoundByLookup = FoundTemplate;
6509 break;
6510 // TODO: handle conflicting names
6516 auto ParamsOrErr = import(D->getTemplateParameters());
6517 if (!ParamsOrErr)
6518 return ParamsOrErr.takeError();
6519 TemplateParameterList *Params = *ParamsOrErr;
6521 FunctionDecl *TemplatedFD;
6522 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
6523 return std::move(Err);
6525 // At creation of the template the template parameters are "adopted"
6526 // (DeclContext is changed). After this possible change the lookup table
6527 // must be updated.
6528 // At deduction guides the DeclContext of the template parameters may be
6529 // different from what we would expect, it may be the class template, or a
6530 // probably different CXXDeductionGuideDecl. This may come from the fact that
6531 // the template parameter objects may be shared between deduction guides or
6532 // the class template, and at creation of multiple FunctionTemplateDecl
6533 // objects (for deduction guides) the same parameters are re-used. The
6534 // "adoption" happens multiple times with different parent, even recursively
6535 // for TemplateTemplateParmDecl. The same happens at import when the
6536 // FunctionTemplateDecl objects are created, but in different order.
6537 // In this way the DeclContext of these template parameters is not necessarily
6538 // the same as in the "from" context.
6539 SmallVector<DeclContext *, 2> OldParamDC;
6540 OldParamDC.reserve(Params->size());
6541 llvm::transform(*Params, std::back_inserter(OldParamDC),
6542 [](NamedDecl *ND) { return ND->getDeclContext(); });
6544 FunctionTemplateDecl *ToFunc;
6545 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
6546 Params, TemplatedFD))
6547 return ToFunc;
6549 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6551 ToFunc->setAccess(D->getAccess());
6552 ToFunc->setLexicalDeclContext(LexicalDC);
6553 addDeclToContexts(D, ToFunc);
6555 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
6556 if (LT && !OldParamDC.empty()) {
6557 for (unsigned int I = 0; I < OldParamDC.size(); ++I)
6558 LT->updateForced(Params->getParam(I), OldParamDC[I]);
6561 if (FoundByLookup) {
6562 auto *Recent =
6563 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6564 if (!TemplatedFD->getPreviousDecl()) {
6565 assert(FoundByLookup->getTemplatedDecl() &&
6566 "Found decl must have its templated decl set");
6567 auto *PrevTemplated =
6568 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6569 if (TemplatedFD != PrevTemplated)
6570 TemplatedFD->setPreviousDecl(PrevTemplated);
6572 ToFunc->setPreviousDecl(Recent);
6575 return ToFunc;
6578 //----------------------------------------------------------------------------
6579 // Import Statements
6580 //----------------------------------------------------------------------------
6582 ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
6583 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
6584 << S->getStmtClassName();
6585 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
6589 ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
6590 if (Importer.returnWithErrorInTest())
6591 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
6592 SmallVector<IdentifierInfo *, 4> Names;
6593 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6594 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
6595 // ToII is nullptr when no symbolic name is given for output operand
6596 // see ParseStmtAsm::ParseAsmOperandsOpt
6597 Names.push_back(ToII);
6600 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6601 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
6602 // ToII is nullptr when no symbolic name is given for input operand
6603 // see ParseStmtAsm::ParseAsmOperandsOpt
6604 Names.push_back(ToII);
6607 SmallVector<StringLiteral *, 4> Clobbers;
6608 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
6609 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
6610 Clobbers.push_back(*ClobberOrErr);
6611 else
6612 return ClobberOrErr.takeError();
6616 SmallVector<StringLiteral *, 4> Constraints;
6617 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6618 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
6619 Constraints.push_back(*OutputOrErr);
6620 else
6621 return OutputOrErr.takeError();
6624 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6625 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
6626 Constraints.push_back(*InputOrErr);
6627 else
6628 return InputOrErr.takeError();
6631 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6632 S->getNumLabels());
6633 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
6634 return std::move(Err);
6636 if (Error Err =
6637 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
6638 return std::move(Err);
6640 if (Error Err = ImportArrayChecked(
6641 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6642 return std::move(Err);
6644 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
6645 if (!AsmLocOrErr)
6646 return AsmLocOrErr.takeError();
6647 auto AsmStrOrErr = import(S->getAsmString());
6648 if (!AsmStrOrErr)
6649 return AsmStrOrErr.takeError();
6650 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
6651 if (!RParenLocOrErr)
6652 return RParenLocOrErr.takeError();
6654 return new (Importer.getToContext()) GCCAsmStmt(
6655 Importer.getToContext(),
6656 *AsmLocOrErr,
6657 S->isSimple(),
6658 S->isVolatile(),
6659 S->getNumOutputs(),
6660 S->getNumInputs(),
6661 Names.data(),
6662 Constraints.data(),
6663 Exprs.data(),
6664 *AsmStrOrErr,
6665 S->getNumClobbers(),
6666 Clobbers.data(),
6667 S->getNumLabels(),
6668 *RParenLocOrErr);
6671 ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
6673 Error Err = Error::success();
6674 auto ToDG = importChecked(Err, S->getDeclGroup());
6675 auto ToBeginLoc = importChecked(Err, S->getBeginLoc());
6676 auto ToEndLoc = importChecked(Err, S->getEndLoc());
6677 if (Err)
6678 return std::move(Err);
6679 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
6682 ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
6683 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
6684 if (!ToSemiLocOrErr)
6685 return ToSemiLocOrErr.takeError();
6686 return new (Importer.getToContext()) NullStmt(
6687 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
6690 ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
6691 SmallVector<Stmt *, 8> ToStmts(S->size());
6693 if (Error Err = ImportContainerChecked(S->body(), ToStmts))
6694 return std::move(Err);
6696 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
6697 if (!ToLBracLocOrErr)
6698 return ToLBracLocOrErr.takeError();
6700 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
6701 if (!ToRBracLocOrErr)
6702 return ToRBracLocOrErr.takeError();
6704 FPOptionsOverride FPO =
6705 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride();
6706 return CompoundStmt::Create(Importer.getToContext(), ToStmts, FPO,
6707 *ToLBracLocOrErr, *ToRBracLocOrErr);
6710 ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
6712 Error Err = Error::success();
6713 auto ToLHS = importChecked(Err, S->getLHS());
6714 auto ToRHS = importChecked(Err, S->getRHS());
6715 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6716 auto ToCaseLoc = importChecked(Err, S->getCaseLoc());
6717 auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc());
6718 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6719 if (Err)
6720 return std::move(Err);
6722 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
6723 ToCaseLoc, ToEllipsisLoc, ToColonLoc);
6724 ToStmt->setSubStmt(ToSubStmt);
6726 return ToStmt;
6729 ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
6731 Error Err = Error::success();
6732 auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc());
6733 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6734 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6735 if (Err)
6736 return std::move(Err);
6738 return new (Importer.getToContext()) DefaultStmt(
6739 ToDefaultLoc, ToColonLoc, ToSubStmt);
6742 ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
6744 Error Err = Error::success();
6745 auto ToIdentLoc = importChecked(Err, S->getIdentLoc());
6746 auto ToLabelDecl = importChecked(Err, S->getDecl());
6747 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6748 if (Err)
6749 return std::move(Err);
6751 return new (Importer.getToContext()) LabelStmt(
6752 ToIdentLoc, ToLabelDecl, ToSubStmt);
6755 ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
6756 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
6757 if (!ToAttrLocOrErr)
6758 return ToAttrLocOrErr.takeError();
6759 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
6760 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
6761 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
6762 return std::move(Err);
6763 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
6764 if (!ToSubStmtOrErr)
6765 return ToSubStmtOrErr.takeError();
6767 return AttributedStmt::Create(
6768 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
6771 ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
6773 Error Err = Error::success();
6774 auto ToIfLoc = importChecked(Err, S->getIfLoc());
6775 auto ToInit = importChecked(Err, S->getInit());
6776 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6777 auto ToCond = importChecked(Err, S->getCond());
6778 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6779 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6780 auto ToThen = importChecked(Err, S->getThen());
6781 auto ToElseLoc = importChecked(Err, S->getElseLoc());
6782 auto ToElse = importChecked(Err, S->getElse());
6783 if (Err)
6784 return std::move(Err);
6786 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->getStatementKind(),
6787 ToInit, ToConditionVariable, ToCond, ToLParenLoc,
6788 ToRParenLoc, ToThen, ToElseLoc, ToElse);
6791 ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
6793 Error Err = Error::success();
6794 auto ToInit = importChecked(Err, S->getInit());
6795 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6796 auto ToCond = importChecked(Err, S->getCond());
6797 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6798 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6799 auto ToBody = importChecked(Err, S->getBody());
6800 auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc());
6801 if (Err)
6802 return std::move(Err);
6804 auto *ToStmt =
6805 SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable,
6806 ToCond, ToLParenLoc, ToRParenLoc);
6807 ToStmt->setBody(ToBody);
6808 ToStmt->setSwitchLoc(ToSwitchLoc);
6810 // Now we have to re-chain the cases.
6811 SwitchCase *LastChainedSwitchCase = nullptr;
6812 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
6813 SC = SC->getNextSwitchCase()) {
6814 Expected<SwitchCase *> ToSCOrErr = import(SC);
6815 if (!ToSCOrErr)
6816 return ToSCOrErr.takeError();
6817 if (LastChainedSwitchCase)
6818 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
6819 else
6820 ToStmt->setSwitchCaseList(*ToSCOrErr);
6821 LastChainedSwitchCase = *ToSCOrErr;
6824 return ToStmt;
6827 ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
6829 Error Err = Error::success();
6830 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6831 auto ToCond = importChecked(Err, S->getCond());
6832 auto ToBody = importChecked(Err, S->getBody());
6833 auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
6834 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6835 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6836 if (Err)
6837 return std::move(Err);
6839 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
6840 ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc);
6843 ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
6845 Error Err = Error::success();
6846 auto ToBody = importChecked(Err, S->getBody());
6847 auto ToCond = importChecked(Err, S->getCond());
6848 auto ToDoLoc = importChecked(Err, S->getDoLoc());
6849 auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
6850 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6851 if (Err)
6852 return std::move(Err);
6854 return new (Importer.getToContext()) DoStmt(
6855 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
6858 ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
6860 Error Err = Error::success();
6861 auto ToInit = importChecked(Err, S->getInit());
6862 auto ToCond = importChecked(Err, S->getCond());
6863 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6864 auto ToInc = importChecked(Err, S->getInc());
6865 auto ToBody = importChecked(Err, S->getBody());
6866 auto ToForLoc = importChecked(Err, S->getForLoc());
6867 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6868 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6869 if (Err)
6870 return std::move(Err);
6872 return new (Importer.getToContext()) ForStmt(
6873 Importer.getToContext(),
6874 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
6875 ToRParenLoc);
6878 ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
6880 Error Err = Error::success();
6881 auto ToLabel = importChecked(Err, S->getLabel());
6882 auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
6883 auto ToLabelLoc = importChecked(Err, S->getLabelLoc());
6884 if (Err)
6885 return std::move(Err);
6887 return new (Importer.getToContext()) GotoStmt(
6888 ToLabel, ToGotoLoc, ToLabelLoc);
6891 ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
6893 Error Err = Error::success();
6894 auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
6895 auto ToStarLoc = importChecked(Err, S->getStarLoc());
6896 auto ToTarget = importChecked(Err, S->getTarget());
6897 if (Err)
6898 return std::move(Err);
6900 return new (Importer.getToContext()) IndirectGotoStmt(
6901 ToGotoLoc, ToStarLoc, ToTarget);
6904 ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
6905 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
6906 if (!ToContinueLocOrErr)
6907 return ToContinueLocOrErr.takeError();
6908 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
6911 ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
6912 auto ToBreakLocOrErr = import(S->getBreakLoc());
6913 if (!ToBreakLocOrErr)
6914 return ToBreakLocOrErr.takeError();
6915 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
6918 ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
6920 Error Err = Error::success();
6921 auto ToReturnLoc = importChecked(Err, S->getReturnLoc());
6922 auto ToRetValue = importChecked(Err, S->getRetValue());
6923 auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate());
6924 if (Err)
6925 return std::move(Err);
6927 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
6928 ToNRVOCandidate);
6931 ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
6933 Error Err = Error::success();
6934 auto ToCatchLoc = importChecked(Err, S->getCatchLoc());
6935 auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl());
6936 auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock());
6937 if (Err)
6938 return std::move(Err);
6940 return new (Importer.getToContext()) CXXCatchStmt (
6941 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
6944 ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
6945 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
6946 if (!ToTryLocOrErr)
6947 return ToTryLocOrErr.takeError();
6949 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
6950 if (!ToTryBlockOrErr)
6951 return ToTryBlockOrErr.takeError();
6953 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
6954 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
6955 CXXCatchStmt *FromHandler = S->getHandler(HI);
6956 if (auto ToHandlerOrErr = import(FromHandler))
6957 ToHandlers[HI] = *ToHandlerOrErr;
6958 else
6959 return ToHandlerOrErr.takeError();
6962 return CXXTryStmt::Create(Importer.getToContext(), *ToTryLocOrErr,
6963 cast<CompoundStmt>(*ToTryBlockOrErr), ToHandlers);
6966 ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
6968 Error Err = Error::success();
6969 auto ToInit = importChecked(Err, S->getInit());
6970 auto ToRangeStmt = importChecked(Err, S->getRangeStmt());
6971 auto ToBeginStmt = importChecked(Err, S->getBeginStmt());
6972 auto ToEndStmt = importChecked(Err, S->getEndStmt());
6973 auto ToCond = importChecked(Err, S->getCond());
6974 auto ToInc = importChecked(Err, S->getInc());
6975 auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt());
6976 auto ToBody = importChecked(Err, S->getBody());
6977 auto ToForLoc = importChecked(Err, S->getForLoc());
6978 auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc());
6979 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6980 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6981 if (Err)
6982 return std::move(Err);
6984 return new (Importer.getToContext()) CXXForRangeStmt(
6985 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
6986 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
6989 ExpectedStmt
6990 ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
6991 Error Err = Error::success();
6992 auto ToElement = importChecked(Err, S->getElement());
6993 auto ToCollection = importChecked(Err, S->getCollection());
6994 auto ToBody = importChecked(Err, S->getBody());
6995 auto ToForLoc = importChecked(Err, S->getForLoc());
6996 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6997 if (Err)
6998 return std::move(Err);
7000 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
7001 ToCollection,
7002 ToBody,
7003 ToForLoc,
7004 ToRParenLoc);
7007 ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7009 Error Err = Error::success();
7010 auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc());
7011 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7012 auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl());
7013 auto ToCatchBody = importChecked(Err, S->getCatchBody());
7014 if (Err)
7015 return std::move(Err);
7017 return new (Importer.getToContext()) ObjCAtCatchStmt (
7018 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
7021 ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7022 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
7023 if (!ToAtFinallyLocOrErr)
7024 return ToAtFinallyLocOrErr.takeError();
7025 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
7026 if (!ToAtFinallyStmtOrErr)
7027 return ToAtFinallyStmtOrErr.takeError();
7028 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
7029 *ToAtFinallyStmtOrErr);
7032 ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
7034 Error Err = Error::success();
7035 auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc());
7036 auto ToTryBody = importChecked(Err, S->getTryBody());
7037 auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt());
7038 if (Err)
7039 return std::move(Err);
7041 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
7042 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
7043 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
7044 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
7045 ToCatchStmts[CI] = *ToCatchStmtOrErr;
7046 else
7047 return ToCatchStmtOrErr.takeError();
7050 return ObjCAtTryStmt::Create(Importer.getToContext(),
7051 ToAtTryLoc, ToTryBody,
7052 ToCatchStmts.begin(), ToCatchStmts.size(),
7053 ToFinallyStmt);
7056 ExpectedStmt
7057 ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
7059 Error Err = Error::success();
7060 auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc());
7061 auto ToSynchExpr = importChecked(Err, S->getSynchExpr());
7062 auto ToSynchBody = importChecked(Err, S->getSynchBody());
7063 if (Err)
7064 return std::move(Err);
7066 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
7067 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
7070 ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7071 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
7072 if (!ToThrowLocOrErr)
7073 return ToThrowLocOrErr.takeError();
7074 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
7075 if (!ToThrowExprOrErr)
7076 return ToThrowExprOrErr.takeError();
7077 return new (Importer.getToContext()) ObjCAtThrowStmt(
7078 *ToThrowLocOrErr, *ToThrowExprOrErr);
7081 ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
7082 ObjCAutoreleasePoolStmt *S) {
7083 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
7084 if (!ToAtLocOrErr)
7085 return ToAtLocOrErr.takeError();
7086 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
7087 if (!ToSubStmtOrErr)
7088 return ToSubStmtOrErr.takeError();
7089 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
7090 *ToSubStmtOrErr);
7093 //----------------------------------------------------------------------------
7094 // Import Expressions
7095 //----------------------------------------------------------------------------
7096 ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
7097 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
7098 << E->getStmtClassName();
7099 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
7102 ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) {
7103 Error Err = Error::success();
7104 auto ToType = importChecked(Err, E->getType());
7105 auto BLoc = importChecked(Err, E->getBeginLoc());
7106 auto RParenLoc = importChecked(Err, E->getEndLoc());
7107 if (Err)
7108 return std::move(Err);
7109 auto ParentContextOrErr = Importer.ImportContext(E->getParentContext());
7110 if (!ParentContextOrErr)
7111 return ParentContextOrErr.takeError();
7113 return new (Importer.getToContext())
7114 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc,
7115 RParenLoc, *ParentContextOrErr);
7118 ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
7120 Error Err = Error::success();
7121 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7122 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7123 auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo());
7124 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7125 auto ToType = importChecked(Err, E->getType());
7126 if (Err)
7127 return std::move(Err);
7129 return new (Importer.getToContext()) VAArgExpr(
7130 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
7131 E->isMicrosoftABI());
7134 ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
7136 Error Err = Error::success();
7137 auto ToCond = importChecked(Err, E->getCond());
7138 auto ToLHS = importChecked(Err, E->getLHS());
7139 auto ToRHS = importChecked(Err, E->getRHS());
7140 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7141 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7142 auto ToType = importChecked(Err, E->getType());
7143 if (Err)
7144 return std::move(Err);
7146 ExprValueKind VK = E->getValueKind();
7147 ExprObjectKind OK = E->getObjectKind();
7149 // The value of CondIsTrue only matters if the value is not
7150 // condition-dependent.
7151 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
7153 return new (Importer.getToContext())
7154 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
7155 ToRParenLoc, CondIsTrue);
7158 ExpectedStmt ASTNodeImporter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
7159 Error Err = Error::success();
7160 auto *ToSrcExpr = importChecked(Err, E->getSrcExpr());
7161 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7162 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7163 auto ToType = importChecked(Err, E->getType());
7164 auto *ToTSI = importChecked(Err, E->getTypeSourceInfo());
7165 if (Err)
7166 return std::move(Err);
7168 return new (Importer.getToContext())
7169 ConvertVectorExpr(ToSrcExpr, ToTSI, ToType, E->getValueKind(),
7170 E->getObjectKind(), ToBuiltinLoc, ToRParenLoc);
7173 ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
7174 Error Err = Error::success();
7175 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7176 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7177 auto ToType = importChecked(Err, E->getType());
7178 const unsigned NumSubExprs = E->getNumSubExprs();
7180 llvm::SmallVector<Expr *, 8> ToSubExprs;
7181 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs);
7182 ToSubExprs.resize(NumSubExprs);
7184 if ((Err = ImportContainerChecked(FromSubExprs, ToSubExprs)))
7185 return std::move(Err);
7187 return new (Importer.getToContext()) ShuffleVectorExpr(
7188 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc);
7191 ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
7192 ExpectedType TypeOrErr = import(E->getType());
7193 if (!TypeOrErr)
7194 return TypeOrErr.takeError();
7196 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
7197 if (!BeginLocOrErr)
7198 return BeginLocOrErr.takeError();
7200 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
7203 ExpectedStmt
7204 ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
7205 Error Err = Error::success();
7206 auto ToGenericLoc = importChecked(Err, E->getGenericLoc());
7207 Expr *ToControllingExpr = nullptr;
7208 TypeSourceInfo *ToControllingType = nullptr;
7209 if (E->isExprPredicate())
7210 ToControllingExpr = importChecked(Err, E->getControllingExpr());
7211 else
7212 ToControllingType = importChecked(Err, E->getControllingType());
7213 assert((ToControllingExpr || ToControllingType) &&
7214 "Either the controlling expr or type must be nonnull");
7215 auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc());
7216 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7217 if (Err)
7218 return std::move(Err);
7220 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
7221 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
7222 if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes))
7223 return std::move(Err);
7225 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
7226 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
7227 if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs))
7228 return std::move(Err);
7230 const ASTContext &ToCtx = Importer.getToContext();
7231 if (E->isResultDependent()) {
7232 if (ToControllingExpr) {
7233 return GenericSelectionExpr::Create(
7234 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7235 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7236 E->containsUnexpandedParameterPack());
7238 return GenericSelectionExpr::Create(
7239 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7240 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7241 E->containsUnexpandedParameterPack());
7244 if (ToControllingExpr) {
7245 return GenericSelectionExpr::Create(
7246 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7247 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7248 E->containsUnexpandedParameterPack(), E->getResultIndex());
7250 return GenericSelectionExpr::Create(
7251 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7252 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7253 E->containsUnexpandedParameterPack(), E->getResultIndex());
7256 ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
7258 Error Err = Error::success();
7259 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7260 auto ToType = importChecked(Err, E->getType());
7261 auto ToFunctionName = importChecked(Err, E->getFunctionName());
7262 if (Err)
7263 return std::move(Err);
7265 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
7266 E->getIdentKind(), E->isTransparent(),
7267 ToFunctionName);
7270 ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
7272 Error Err = Error::success();
7273 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
7274 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
7275 auto ToDecl = importChecked(Err, E->getDecl());
7276 auto ToLocation = importChecked(Err, E->getLocation());
7277 auto ToType = importChecked(Err, E->getType());
7278 if (Err)
7279 return std::move(Err);
7281 NamedDecl *ToFoundD = nullptr;
7282 if (E->getDecl() != E->getFoundDecl()) {
7283 auto FoundDOrErr = import(E->getFoundDecl());
7284 if (!FoundDOrErr)
7285 return FoundDOrErr.takeError();
7286 ToFoundD = *FoundDOrErr;
7289 TemplateArgumentListInfo ToTAInfo;
7290 TemplateArgumentListInfo *ToResInfo = nullptr;
7291 if (E->hasExplicitTemplateArgs()) {
7292 if (Error Err =
7293 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
7294 E->template_arguments(), ToTAInfo))
7295 return std::move(Err);
7296 ToResInfo = &ToTAInfo;
7299 auto *ToE = DeclRefExpr::Create(
7300 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
7301 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
7302 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
7303 if (E->hadMultipleCandidates())
7304 ToE->setHadMultipleCandidates(true);
7305 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
7306 return ToE;
7309 ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
7310 ExpectedType TypeOrErr = import(E->getType());
7311 if (!TypeOrErr)
7312 return TypeOrErr.takeError();
7314 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
7317 ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
7318 ExpectedExpr ToInitOrErr = import(E->getInit());
7319 if (!ToInitOrErr)
7320 return ToInitOrErr.takeError();
7322 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
7323 if (!ToEqualOrColonLocOrErr)
7324 return ToEqualOrColonLocOrErr.takeError();
7326 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
7327 // List elements from the second, the first is Init itself
7328 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
7329 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
7330 ToIndexExprs[I - 1] = *ToArgOrErr;
7331 else
7332 return ToArgOrErr.takeError();
7335 SmallVector<Designator, 4> ToDesignators(E->size());
7336 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
7337 return std::move(Err);
7339 return DesignatedInitExpr::Create(
7340 Importer.getToContext(), ToDesignators,
7341 ToIndexExprs, *ToEqualOrColonLocOrErr,
7342 E->usesGNUSyntax(), *ToInitOrErr);
7345 ExpectedStmt
7346 ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
7347 ExpectedType ToTypeOrErr = import(E->getType());
7348 if (!ToTypeOrErr)
7349 return ToTypeOrErr.takeError();
7351 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7352 if (!ToLocationOrErr)
7353 return ToLocationOrErr.takeError();
7355 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
7356 *ToTypeOrErr, *ToLocationOrErr);
7359 ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
7360 ExpectedType ToTypeOrErr = import(E->getType());
7361 if (!ToTypeOrErr)
7362 return ToTypeOrErr.takeError();
7364 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7365 if (!ToLocationOrErr)
7366 return ToLocationOrErr.takeError();
7368 return IntegerLiteral::Create(
7369 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
7373 ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
7374 ExpectedType ToTypeOrErr = import(E->getType());
7375 if (!ToTypeOrErr)
7376 return ToTypeOrErr.takeError();
7378 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7379 if (!ToLocationOrErr)
7380 return ToLocationOrErr.takeError();
7382 return FloatingLiteral::Create(
7383 Importer.getToContext(), E->getValue(), E->isExact(),
7384 *ToTypeOrErr, *ToLocationOrErr);
7387 ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
7388 auto ToTypeOrErr = import(E->getType());
7389 if (!ToTypeOrErr)
7390 return ToTypeOrErr.takeError();
7392 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7393 if (!ToSubExprOrErr)
7394 return ToSubExprOrErr.takeError();
7396 return new (Importer.getToContext()) ImaginaryLiteral(
7397 *ToSubExprOrErr, *ToTypeOrErr);
7400 ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) {
7401 auto ToTypeOrErr = import(E->getType());
7402 if (!ToTypeOrErr)
7403 return ToTypeOrErr.takeError();
7405 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7406 if (!ToLocationOrErr)
7407 return ToLocationOrErr.takeError();
7409 return new (Importer.getToContext()) FixedPointLiteral(
7410 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
7411 Importer.getToContext().getFixedPointScale(*ToTypeOrErr));
7414 ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
7415 ExpectedType ToTypeOrErr = import(E->getType());
7416 if (!ToTypeOrErr)
7417 return ToTypeOrErr.takeError();
7419 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7420 if (!ToLocationOrErr)
7421 return ToLocationOrErr.takeError();
7423 return new (Importer.getToContext()) CharacterLiteral(
7424 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
7427 ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
7428 ExpectedType ToTypeOrErr = import(E->getType());
7429 if (!ToTypeOrErr)
7430 return ToTypeOrErr.takeError();
7432 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
7433 if (Error Err = ImportArrayChecked(
7434 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
7435 return std::move(Err);
7437 return StringLiteral::Create(
7438 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
7439 *ToTypeOrErr, ToLocations.data(), ToLocations.size());
7442 ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
7444 Error Err = Error::success();
7445 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
7446 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
7447 auto ToType = importChecked(Err, E->getType());
7448 auto ToInitializer = importChecked(Err, E->getInitializer());
7449 if (Err)
7450 return std::move(Err);
7452 return new (Importer.getToContext()) CompoundLiteralExpr(
7453 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
7454 ToInitializer, E->isFileScope());
7457 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
7459 Error Err = Error::success();
7460 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7461 auto ToType = importChecked(Err, E->getType());
7462 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7463 if (Err)
7464 return std::move(Err);
7466 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
7467 if (Error Err = ImportArrayChecked(
7468 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
7469 ToExprs.begin()))
7470 return std::move(Err);
7472 return new (Importer.getToContext()) AtomicExpr(
7474 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
7477 ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
7478 Error Err = Error::success();
7479 auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc());
7480 auto ToLabelLoc = importChecked(Err, E->getLabelLoc());
7481 auto ToLabel = importChecked(Err, E->getLabel());
7482 auto ToType = importChecked(Err, E->getType());
7483 if (Err)
7484 return std::move(Err);
7486 return new (Importer.getToContext()) AddrLabelExpr(
7487 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
7489 ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
7490 Error Err = Error::success();
7491 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7492 auto ToResult = importChecked(Err, E->getAPValueResult());
7493 if (Err)
7494 return std::move(Err);
7496 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult);
7498 ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
7499 Error Err = Error::success();
7500 auto ToLParen = importChecked(Err, E->getLParen());
7501 auto ToRParen = importChecked(Err, E->getRParen());
7502 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7503 if (Err)
7504 return std::move(Err);
7506 return new (Importer.getToContext())
7507 ParenExpr(ToLParen, ToRParen, ToSubExpr);
7510 ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
7511 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
7512 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
7513 return std::move(Err);
7515 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
7516 if (!ToLParenLocOrErr)
7517 return ToLParenLocOrErr.takeError();
7519 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
7520 if (!ToRParenLocOrErr)
7521 return ToRParenLocOrErr.takeError();
7523 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
7524 ToExprs, *ToRParenLocOrErr);
7527 ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
7528 Error Err = Error::success();
7529 auto ToSubStmt = importChecked(Err, E->getSubStmt());
7530 auto ToType = importChecked(Err, E->getType());
7531 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
7532 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7533 if (Err)
7534 return std::move(Err);
7536 return new (Importer.getToContext())
7537 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
7538 E->getTemplateDepth());
7541 ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
7542 Error Err = Error::success();
7543 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7544 auto ToType = importChecked(Err, E->getType());
7545 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7546 if (Err)
7547 return std::move(Err);
7549 auto *UO = UnaryOperator::CreateEmpty(Importer.getToContext(),
7550 E->hasStoredFPFeatures());
7551 UO->setType(ToType);
7552 UO->setSubExpr(ToSubExpr);
7553 UO->setOpcode(E->getOpcode());
7554 UO->setOperatorLoc(ToOperatorLoc);
7555 UO->setCanOverflow(E->canOverflow());
7556 if (E->hasStoredFPFeatures())
7557 UO->setStoredFPFeatures(E->getStoredFPFeatures());
7559 return UO;
7562 ExpectedStmt
7564 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
7565 Error Err = Error::success();
7566 auto ToType = importChecked(Err, E->getType());
7567 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7568 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7569 if (Err)
7570 return std::move(Err);
7572 if (E->isArgumentType()) {
7573 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
7574 import(E->getArgumentTypeInfo());
7575 if (!ToArgumentTypeInfoOrErr)
7576 return ToArgumentTypeInfoOrErr.takeError();
7578 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7579 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
7580 ToRParenLoc);
7583 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr());
7584 if (!ToArgumentExprOrErr)
7585 return ToArgumentExprOrErr.takeError();
7587 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7588 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
7591 ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
7592 Error Err = Error::success();
7593 auto ToLHS = importChecked(Err, E->getLHS());
7594 auto ToRHS = importChecked(Err, E->getRHS());
7595 auto ToType = importChecked(Err, E->getType());
7596 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7597 if (Err)
7598 return std::move(Err);
7600 return BinaryOperator::Create(
7601 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
7602 E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
7603 E->getFPFeatures());
7606 ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
7607 Error Err = Error::success();
7608 auto ToCond = importChecked(Err, E->getCond());
7609 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7610 auto ToLHS = importChecked(Err, E->getLHS());
7611 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7612 auto ToRHS = importChecked(Err, E->getRHS());
7613 auto ToType = importChecked(Err, E->getType());
7614 if (Err)
7615 return std::move(Err);
7617 return new (Importer.getToContext()) ConditionalOperator(
7618 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
7619 E->getValueKind(), E->getObjectKind());
7622 ExpectedStmt
7623 ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
7624 Error Err = Error::success();
7625 auto ToCommon = importChecked(Err, E->getCommon());
7626 auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue());
7627 auto ToCond = importChecked(Err, E->getCond());
7628 auto ToTrueExpr = importChecked(Err, E->getTrueExpr());
7629 auto ToFalseExpr = importChecked(Err, E->getFalseExpr());
7630 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7631 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7632 auto ToType = importChecked(Err, E->getType());
7633 if (Err)
7634 return std::move(Err);
7636 return new (Importer.getToContext()) BinaryConditionalOperator(
7637 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
7638 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
7639 E->getObjectKind());
7642 ExpectedStmt ASTNodeImporter::VisitCXXRewrittenBinaryOperator(
7643 CXXRewrittenBinaryOperator *E) {
7644 Error Err = Error::success();
7645 auto ToSemanticForm = importChecked(Err, E->getSemanticForm());
7646 if (Err)
7647 return std::move(Err);
7649 return new (Importer.getToContext())
7650 CXXRewrittenBinaryOperator(ToSemanticForm, E->isReversed());
7653 ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
7654 Error Err = Error::success();
7655 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7656 auto ToQueriedTypeSourceInfo =
7657 importChecked(Err, E->getQueriedTypeSourceInfo());
7658 auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression());
7659 auto ToEndLoc = importChecked(Err, E->getEndLoc());
7660 auto ToType = importChecked(Err, E->getType());
7661 if (Err)
7662 return std::move(Err);
7664 return new (Importer.getToContext()) ArrayTypeTraitExpr(
7665 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
7666 ToDimensionExpression, ToEndLoc, ToType);
7669 ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
7670 Error Err = Error::success();
7671 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7672 auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression());
7673 auto ToEndLoc = importChecked(Err, E->getEndLoc());
7674 auto ToType = importChecked(Err, E->getType());
7675 if (Err)
7676 return std::move(Err);
7678 return new (Importer.getToContext()) ExpressionTraitExpr(
7679 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
7680 ToEndLoc, ToType);
7683 ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
7684 Error Err = Error::success();
7685 auto ToLocation = importChecked(Err, E->getLocation());
7686 auto ToType = importChecked(Err, E->getType());
7687 auto ToSourceExpr = importChecked(Err, E->getSourceExpr());
7688 if (Err)
7689 return std::move(Err);
7691 return new (Importer.getToContext()) OpaqueValueExpr(
7692 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
7695 ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
7696 Error Err = Error::success();
7697 auto ToLHS = importChecked(Err, E->getLHS());
7698 auto ToRHS = importChecked(Err, E->getRHS());
7699 auto ToType = importChecked(Err, E->getType());
7700 auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc());
7701 if (Err)
7702 return std::move(Err);
7704 return new (Importer.getToContext()) ArraySubscriptExpr(
7705 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
7706 ToRBracketLoc);
7709 ExpectedStmt
7710 ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
7711 Error Err = Error::success();
7712 auto ToLHS = importChecked(Err, E->getLHS());
7713 auto ToRHS = importChecked(Err, E->getRHS());
7714 auto ToType = importChecked(Err, E->getType());
7715 auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType());
7716 auto ToComputationResultType =
7717 importChecked(Err, E->getComputationResultType());
7718 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7719 if (Err)
7720 return std::move(Err);
7722 return CompoundAssignOperator::Create(
7723 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
7724 E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
7725 E->getFPFeatures(),
7726 ToComputationLHSType, ToComputationResultType);
7729 Expected<CXXCastPath>
7730 ASTNodeImporter::ImportCastPath(CastExpr *CE) {
7731 CXXCastPath Path;
7732 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
7733 if (auto SpecOrErr = import(*I))
7734 Path.push_back(*SpecOrErr);
7735 else
7736 return SpecOrErr.takeError();
7738 return Path;
7741 ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
7742 ExpectedType ToTypeOrErr = import(E->getType());
7743 if (!ToTypeOrErr)
7744 return ToTypeOrErr.takeError();
7746 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7747 if (!ToSubExprOrErr)
7748 return ToSubExprOrErr.takeError();
7750 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7751 if (!ToBasePathOrErr)
7752 return ToBasePathOrErr.takeError();
7754 return ImplicitCastExpr::Create(
7755 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr,
7756 &(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures());
7759 ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
7760 Error Err = Error::success();
7761 auto ToType = importChecked(Err, E->getType());
7762 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7763 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
7764 if (Err)
7765 return std::move(Err);
7767 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7768 if (!ToBasePathOrErr)
7769 return ToBasePathOrErr.takeError();
7770 CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
7772 switch (E->getStmtClass()) {
7773 case Stmt::CStyleCastExprClass: {
7774 auto *CCE = cast<CStyleCastExpr>(E);
7775 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc());
7776 if (!ToLParenLocOrErr)
7777 return ToLParenLocOrErr.takeError();
7778 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc());
7779 if (!ToRParenLocOrErr)
7780 return ToRParenLocOrErr.takeError();
7781 return CStyleCastExpr::Create(
7782 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(),
7783 ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten,
7784 *ToLParenLocOrErr, *ToRParenLocOrErr);
7787 case Stmt::CXXFunctionalCastExprClass: {
7788 auto *FCE = cast<CXXFunctionalCastExpr>(E);
7789 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc());
7790 if (!ToLParenLocOrErr)
7791 return ToLParenLocOrErr.takeError();
7792 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc());
7793 if (!ToRParenLocOrErr)
7794 return ToRParenLocOrErr.takeError();
7795 return CXXFunctionalCastExpr::Create(
7796 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten,
7797 E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(),
7798 *ToLParenLocOrErr, *ToRParenLocOrErr);
7801 case Stmt::ObjCBridgedCastExprClass: {
7802 auto *OCE = cast<ObjCBridgedCastExpr>(E);
7803 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc());
7804 if (!ToLParenLocOrErr)
7805 return ToLParenLocOrErr.takeError();
7806 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc());
7807 if (!ToBridgeKeywordLocOrErr)
7808 return ToBridgeKeywordLocOrErr.takeError();
7809 return new (Importer.getToContext()) ObjCBridgedCastExpr(
7810 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
7811 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
7813 default:
7814 llvm_unreachable("Cast expression of unsupported type!");
7815 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
7819 ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
7820 SmallVector<OffsetOfNode, 4> ToNodes;
7821 for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
7822 const OffsetOfNode &FromNode = E->getComponent(I);
7824 SourceLocation ToBeginLoc, ToEndLoc;
7826 if (FromNode.getKind() != OffsetOfNode::Base) {
7827 Error Err = Error::success();
7828 ToBeginLoc = importChecked(Err, FromNode.getBeginLoc());
7829 ToEndLoc = importChecked(Err, FromNode.getEndLoc());
7830 if (Err)
7831 return std::move(Err);
7834 switch (FromNode.getKind()) {
7835 case OffsetOfNode::Array:
7836 ToNodes.push_back(
7837 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
7838 break;
7839 case OffsetOfNode::Base: {
7840 auto ToBSOrErr = import(FromNode.getBase());
7841 if (!ToBSOrErr)
7842 return ToBSOrErr.takeError();
7843 ToNodes.push_back(OffsetOfNode(*ToBSOrErr));
7844 break;
7846 case OffsetOfNode::Field: {
7847 auto ToFieldOrErr = import(FromNode.getField());
7848 if (!ToFieldOrErr)
7849 return ToFieldOrErr.takeError();
7850 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
7851 break;
7853 case OffsetOfNode::Identifier: {
7854 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName());
7855 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
7856 break;
7861 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
7862 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
7863 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I));
7864 if (!ToIndexExprOrErr)
7865 return ToIndexExprOrErr.takeError();
7866 ToExprs[I] = *ToIndexExprOrErr;
7869 Error Err = Error::success();
7870 auto ToType = importChecked(Err, E->getType());
7871 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
7872 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7873 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7874 if (Err)
7875 return std::move(Err);
7877 return OffsetOfExpr::Create(
7878 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes,
7879 ToExprs, ToRParenLoc);
7882 ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
7883 Error Err = Error::success();
7884 auto ToType = importChecked(Err, E->getType());
7885 auto ToOperand = importChecked(Err, E->getOperand());
7886 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7887 auto ToEndLoc = importChecked(Err, E->getEndLoc());
7888 if (Err)
7889 return std::move(Err);
7891 CanThrowResult ToCanThrow;
7892 if (E->isValueDependent())
7893 ToCanThrow = CT_Dependent;
7894 else
7895 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
7897 return new (Importer.getToContext()) CXXNoexceptExpr(
7898 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
7901 ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
7902 Error Err = Error::success();
7903 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7904 auto ToType = importChecked(Err, E->getType());
7905 auto ToThrowLoc = importChecked(Err, E->getThrowLoc());
7906 if (Err)
7907 return std::move(Err);
7909 return new (Importer.getToContext()) CXXThrowExpr(
7910 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
7913 ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
7914 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation());
7915 if (!ToUsedLocOrErr)
7916 return ToUsedLocOrErr.takeError();
7918 auto ToParamOrErr = import(E->getParam());
7919 if (!ToParamOrErr)
7920 return ToParamOrErr.takeError();
7922 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
7923 if (!UsedContextOrErr)
7924 return UsedContextOrErr.takeError();
7926 // Import the default arg if it was not imported yet.
7927 // This is needed because it can happen that during the import of the
7928 // default expression (from VisitParmVarDecl) the same ParmVarDecl is
7929 // encountered here. The default argument for a ParmVarDecl is set in the
7930 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
7931 // see VisitParmVarDecl).
7932 ParmVarDecl *ToParam = *ToParamOrErr;
7933 if (!ToParam->getDefaultArg()) {
7934 std::optional<ParmVarDecl *> FromParam =
7935 Importer.getImportedFromDecl(ToParam);
7936 assert(FromParam && "ParmVarDecl was not imported?");
7938 if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam))
7939 return std::move(Err);
7941 Expr *RewrittenInit = nullptr;
7942 if (E->hasRewrittenInit()) {
7943 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
7944 if (!ExprOrErr)
7945 return ExprOrErr.takeError();
7946 RewrittenInit = ExprOrErr.get();
7948 return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
7949 *ToParamOrErr, RewrittenInit,
7950 *UsedContextOrErr);
7953 ExpectedStmt
7954 ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
7955 Error Err = Error::success();
7956 auto ToType = importChecked(Err, E->getType());
7957 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
7958 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7959 if (Err)
7960 return std::move(Err);
7962 return new (Importer.getToContext()) CXXScalarValueInitExpr(
7963 ToType, ToTypeSourceInfo, ToRParenLoc);
7966 ExpectedStmt
7967 ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
7968 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7969 if (!ToSubExprOrErr)
7970 return ToSubExprOrErr.takeError();
7972 auto ToDtorOrErr = import(E->getTemporary()->getDestructor());
7973 if (!ToDtorOrErr)
7974 return ToDtorOrErr.takeError();
7976 ASTContext &ToCtx = Importer.getToContext();
7977 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr);
7978 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr);
7981 ExpectedStmt
7983 ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
7984 Error Err = Error::success();
7985 auto ToConstructor = importChecked(Err, E->getConstructor());
7986 auto ToType = importChecked(Err, E->getType());
7987 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
7988 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
7989 if (Err)
7990 return std::move(Err);
7992 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
7993 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
7994 return std::move(Err);
7996 return CXXTemporaryObjectExpr::Create(
7997 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs,
7998 ToParenOrBraceRange, E->hadMultipleCandidates(),
7999 E->isListInitialization(), E->isStdInitListInitialization(),
8000 E->requiresZeroInitialization());
8003 ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl(
8004 LifetimeExtendedTemporaryDecl *D) {
8005 DeclContext *DC, *LexicalDC;
8006 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
8007 return std::move(Err);
8009 Error Err = Error::success();
8010 auto Temporary = importChecked(Err, D->getTemporaryExpr());
8011 auto ExtendingDecl = importChecked(Err, D->getExtendingDecl());
8012 if (Err)
8013 return std::move(Err);
8014 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
8016 LifetimeExtendedTemporaryDecl *To;
8017 if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl,
8018 D->getManglingNumber()))
8019 return To;
8021 To->setLexicalDeclContext(LexicalDC);
8022 LexicalDC->addDeclInternal(To);
8023 return To;
8026 ExpectedStmt
8027 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
8028 Error Err = Error::success();
8029 auto ToType = importChecked(Err, E->getType());
8030 Expr *ToTemporaryExpr = importChecked(
8031 Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
8032 auto ToMaterializedDecl =
8033 importChecked(Err, E->getLifetimeExtendedTemporaryDecl());
8034 if (Err)
8035 return std::move(Err);
8037 if (!ToTemporaryExpr)
8038 ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr());
8040 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
8041 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
8042 ToMaterializedDecl);
8044 return ToMTE;
8047 ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
8048 Error Err = Error::success();
8049 auto ToType = importChecked(Err, E->getType());
8050 auto ToPattern = importChecked(Err, E->getPattern());
8051 auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
8052 if (Err)
8053 return std::move(Err);
8055 return new (Importer.getToContext()) PackExpansionExpr(
8056 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
8059 ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
8060 Error Err = Error::success();
8061 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8062 auto ToPack = importChecked(Err, E->getPack());
8063 auto ToPackLoc = importChecked(Err, E->getPackLoc());
8064 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8065 if (Err)
8066 return std::move(Err);
8068 std::optional<unsigned> Length;
8069 if (!E->isValueDependent())
8070 Length = E->getPackLength();
8072 SmallVector<TemplateArgument, 8> ToPartialArguments;
8073 if (E->isPartiallySubstituted()) {
8074 if (Error Err = ImportTemplateArguments(E->getPartialArguments(),
8075 ToPartialArguments))
8076 return std::move(Err);
8079 return SizeOfPackExpr::Create(
8080 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc,
8081 Length, ToPartialArguments);
8085 ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
8086 Error Err = Error::success();
8087 auto ToOperatorNew = importChecked(Err, E->getOperatorNew());
8088 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
8089 auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens());
8090 auto ToArraySize = importChecked(Err, E->getArraySize());
8091 auto ToInitializer = importChecked(Err, E->getInitializer());
8092 auto ToType = importChecked(Err, E->getType());
8093 auto ToAllocatedTypeSourceInfo =
8094 importChecked(Err, E->getAllocatedTypeSourceInfo());
8095 auto ToSourceRange = importChecked(Err, E->getSourceRange());
8096 auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange());
8097 if (Err)
8098 return std::move(Err);
8100 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
8101 if (Error Err =
8102 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs))
8103 return std::move(Err);
8105 return CXXNewExpr::Create(
8106 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew,
8107 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(),
8108 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(),
8109 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange,
8110 ToDirectInitRange);
8113 ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8114 Error Err = Error::success();
8115 auto ToType = importChecked(Err, E->getType());
8116 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
8117 auto ToArgument = importChecked(Err, E->getArgument());
8118 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
8119 if (Err)
8120 return std::move(Err);
8122 return new (Importer.getToContext()) CXXDeleteExpr(
8123 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
8124 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
8125 ToBeginLoc);
8128 ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
8129 Error Err = Error::success();
8130 auto ToType = importChecked(Err, E->getType());
8131 auto ToLocation = importChecked(Err, E->getLocation());
8132 auto ToConstructor = importChecked(Err, E->getConstructor());
8133 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
8134 if (Err)
8135 return std::move(Err);
8137 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
8138 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8139 return std::move(Err);
8141 CXXConstructExpr *ToE = CXXConstructExpr::Create(
8142 Importer.getToContext(), ToType, ToLocation, ToConstructor,
8143 E->isElidable(), ToArgs, E->hadMultipleCandidates(),
8144 E->isListInitialization(), E->isStdInitListInitialization(),
8145 E->requiresZeroInitialization(), E->getConstructionKind(),
8146 ToParenOrBraceRange);
8147 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
8148 return ToE;
8151 ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
8152 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8153 if (!ToSubExprOrErr)
8154 return ToSubExprOrErr.takeError();
8156 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
8157 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects))
8158 return std::move(Err);
8160 return ExprWithCleanups::Create(
8161 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(),
8162 ToObjects);
8165 ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
8166 Error Err = Error::success();
8167 auto ToCallee = importChecked(Err, E->getCallee());
8168 auto ToType = importChecked(Err, E->getType());
8169 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8170 if (Err)
8171 return std::move(Err);
8173 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
8174 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8175 return std::move(Err);
8177 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs,
8178 ToType, E->getValueKind(), ToRParenLoc,
8179 E->getFPFeatures());
8182 ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
8183 ExpectedType ToTypeOrErr = import(E->getType());
8184 if (!ToTypeOrErr)
8185 return ToTypeOrErr.takeError();
8187 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
8188 if (!ToLocationOrErr)
8189 return ToLocationOrErr.takeError();
8191 return CXXThisExpr::Create(Importer.getToContext(), *ToLocationOrErr,
8192 *ToTypeOrErr, E->isImplicit());
8195 ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8196 ExpectedType ToTypeOrErr = import(E->getType());
8197 if (!ToTypeOrErr)
8198 return ToTypeOrErr.takeError();
8200 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
8201 if (!ToLocationOrErr)
8202 return ToLocationOrErr.takeError();
8204 return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(),
8205 *ToTypeOrErr, *ToLocationOrErr);
8208 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
8209 Error Err = Error::success();
8210 auto ToBase = importChecked(Err, E->getBase());
8211 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8212 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8213 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8214 auto ToMemberDecl = importChecked(Err, E->getMemberDecl());
8215 auto ToType = importChecked(Err, E->getType());
8216 auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl());
8217 auto ToName = importChecked(Err, E->getMemberNameInfo().getName());
8218 auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc());
8219 if (Err)
8220 return std::move(Err);
8222 DeclAccessPair ToFoundDecl =
8223 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
8225 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
8227 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8228 if (E->hasExplicitTemplateArgs()) {
8229 if (Error Err =
8230 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
8231 E->template_arguments(), ToTAInfo))
8232 return std::move(Err);
8233 ResInfo = &ToTAInfo;
8236 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(),
8237 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
8238 ToMemberDecl, ToFoundDecl, ToMemberNameInfo,
8239 ResInfo, ToType, E->getValueKind(),
8240 E->getObjectKind(), E->isNonOdrUse());
8243 ExpectedStmt
8244 ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
8245 Error Err = Error::success();
8246 auto ToBase = importChecked(Err, E->getBase());
8247 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8248 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8249 auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo());
8250 auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc());
8251 auto ToTildeLoc = importChecked(Err, E->getTildeLoc());
8252 if (Err)
8253 return std::move(Err);
8255 PseudoDestructorTypeStorage Storage;
8256 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
8257 IdentifierInfo *ToII = Importer.Import(FromII);
8258 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc());
8259 if (!ToDestroyedTypeLocOrErr)
8260 return ToDestroyedTypeLocOrErr.takeError();
8261 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
8262 } else {
8263 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo()))
8264 Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
8265 else
8266 return ToTIOrErr.takeError();
8269 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
8270 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
8271 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
8274 ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
8275 CXXDependentScopeMemberExpr *E) {
8276 Error Err = Error::success();
8277 auto ToType = importChecked(Err, E->getType());
8278 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8279 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8280 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8281 auto ToFirstQualifierFoundInScope =
8282 importChecked(Err, E->getFirstQualifierFoundInScope());
8283 if (Err)
8284 return std::move(Err);
8286 Expr *ToBase = nullptr;
8287 if (!E->isImplicitAccess()) {
8288 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
8289 ToBase = *ToBaseOrErr;
8290 else
8291 return ToBaseOrErr.takeError();
8294 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8296 if (E->hasExplicitTemplateArgs()) {
8297 if (Error Err =
8298 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
8299 E->template_arguments(), ToTAInfo))
8300 return std::move(Err);
8301 ResInfo = &ToTAInfo;
8303 auto ToMember = importChecked(Err, E->getMember());
8304 auto ToMemberLoc = importChecked(Err, E->getMemberLoc());
8305 if (Err)
8306 return std::move(Err);
8307 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
8309 // Import additional name location/type info.
8310 if (Error Err =
8311 ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo))
8312 return std::move(Err);
8314 return CXXDependentScopeMemberExpr::Create(
8315 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc,
8316 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope,
8317 ToMemberNameInfo, ResInfo);
8320 ExpectedStmt
8321 ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
8322 Error Err = Error::success();
8323 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8324 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8325 auto ToDeclName = importChecked(Err, E->getDeclName());
8326 auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc());
8327 auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc());
8328 auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc());
8329 if (Err)
8330 return std::move(Err);
8332 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
8333 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8334 return std::move(Err);
8336 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
8337 TemplateArgumentListInfo *ResInfo = nullptr;
8338 if (E->hasExplicitTemplateArgs()) {
8339 if (Error Err =
8340 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
8341 return std::move(Err);
8342 ResInfo = &ToTAInfo;
8345 return DependentScopeDeclRefExpr::Create(
8346 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc,
8347 ToNameInfo, ResInfo);
8350 ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
8351 CXXUnresolvedConstructExpr *E) {
8352 Error Err = Error::success();
8353 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
8354 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8355 auto ToType = importChecked(Err, E->getType());
8356 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
8357 if (Err)
8358 return std::move(Err);
8360 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8361 if (Error Err =
8362 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
8363 return std::move(Err);
8365 return CXXUnresolvedConstructExpr::Create(
8366 Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc,
8367 llvm::ArrayRef(ToArgs), ToRParenLoc, E->isListInitialization());
8370 ExpectedStmt
8371 ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
8372 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass());
8373 if (!ToNamingClassOrErr)
8374 return ToNamingClassOrErr.takeError();
8376 auto ToQualifierLocOrErr = import(E->getQualifierLoc());
8377 if (!ToQualifierLocOrErr)
8378 return ToQualifierLocOrErr.takeError();
8380 Error Err = Error::success();
8381 auto ToName = importChecked(Err, E->getName());
8382 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8383 if (Err)
8384 return std::move(Err);
8385 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8387 // Import additional name location/type info.
8388 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8389 return std::move(Err);
8391 UnresolvedSet<8> ToDecls;
8392 for (auto *D : E->decls())
8393 if (auto ToDOrErr = import(D))
8394 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8395 else
8396 return ToDOrErr.takeError();
8398 if (E->hasExplicitTemplateArgs()) {
8399 TemplateArgumentListInfo ToTAInfo;
8400 if (Error Err = ImportTemplateArgumentListInfo(
8401 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
8402 ToTAInfo))
8403 return std::move(Err);
8405 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
8406 if (!ToTemplateKeywordLocOrErr)
8407 return ToTemplateKeywordLocOrErr.takeError();
8409 const bool KnownDependent =
8410 (E->getDependence() & ExprDependence::TypeValue) ==
8411 ExprDependence::TypeValue;
8412 return UnresolvedLookupExpr::Create(
8413 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8414 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
8415 ToDecls.begin(), ToDecls.end(), KnownDependent);
8418 return UnresolvedLookupExpr::Create(
8419 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8420 ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(),
8421 ToDecls.end());
8424 ExpectedStmt
8425 ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
8426 Error Err = Error::success();
8427 auto ToType = importChecked(Err, E->getType());
8428 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8429 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8430 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8431 auto ToName = importChecked(Err, E->getName());
8432 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8433 if (Err)
8434 return std::move(Err);
8436 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8437 // Import additional name location/type info.
8438 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8439 return std::move(Err);
8441 UnresolvedSet<8> ToDecls;
8442 for (Decl *D : E->decls())
8443 if (auto ToDOrErr = import(D))
8444 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8445 else
8446 return ToDOrErr.takeError();
8448 TemplateArgumentListInfo ToTAInfo;
8449 TemplateArgumentListInfo *ResInfo = nullptr;
8450 if (E->hasExplicitTemplateArgs()) {
8451 TemplateArgumentListInfo FromTAInfo;
8452 E->copyTemplateArgumentsInto(FromTAInfo);
8453 if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo))
8454 return std::move(Err);
8455 ResInfo = &ToTAInfo;
8458 Expr *ToBase = nullptr;
8459 if (!E->isImplicitAccess()) {
8460 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
8461 ToBase = *ToBaseOrErr;
8462 else
8463 return ToBaseOrErr.takeError();
8466 return UnresolvedMemberExpr::Create(
8467 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType,
8468 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
8469 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end());
8472 ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
8473 Error Err = Error::success();
8474 auto ToCallee = importChecked(Err, E->getCallee());
8475 auto ToType = importChecked(Err, E->getType());
8476 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8477 if (Err)
8478 return std::move(Err);
8480 unsigned NumArgs = E->getNumArgs();
8481 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
8482 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8483 return std::move(Err);
8485 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8486 return CXXOperatorCallExpr::Create(
8487 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType,
8488 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(),
8489 OCE->getADLCallKind());
8492 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType,
8493 E->getValueKind(), ToRParenLoc, E->getFPFeatures(),
8494 /*MinNumArgs=*/0, E->getADLCallKind());
8497 ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
8498 CXXRecordDecl *FromClass = E->getLambdaClass();
8499 auto ToClassOrErr = import(FromClass);
8500 if (!ToClassOrErr)
8501 return ToClassOrErr.takeError();
8502 CXXRecordDecl *ToClass = *ToClassOrErr;
8504 auto ToCallOpOrErr = import(E->getCallOperator());
8505 if (!ToCallOpOrErr)
8506 return ToCallOpOrErr.takeError();
8508 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
8509 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits))
8510 return std::move(Err);
8512 Error Err = Error::success();
8513 auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange());
8514 auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc());
8515 auto ToEndLoc = importChecked(Err, E->getEndLoc());
8516 if (Err)
8517 return std::move(Err);
8519 return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange,
8520 E->getCaptureDefault(), ToCaptureDefaultLoc,
8521 E->hasExplicitParameters(),
8522 E->hasExplicitResultType(), ToCaptureInits,
8523 ToEndLoc, E->containsUnexpandedParameterPack());
8527 ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
8528 Error Err = Error::success();
8529 auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc());
8530 auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc());
8531 auto ToType = importChecked(Err, E->getType());
8532 if (Err)
8533 return std::move(Err);
8535 SmallVector<Expr *, 4> ToExprs(E->getNumInits());
8536 if (Error Err = ImportContainerChecked(E->inits(), ToExprs))
8537 return std::move(Err);
8539 ASTContext &ToCtx = Importer.getToContext();
8540 InitListExpr *To = new (ToCtx) InitListExpr(
8541 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
8542 To->setType(ToType);
8544 if (E->hasArrayFiller()) {
8545 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller()))
8546 To->setArrayFiller(*ToFillerOrErr);
8547 else
8548 return ToFillerOrErr.takeError();
8551 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
8552 if (auto ToFDOrErr = import(FromFD))
8553 To->setInitializedFieldInUnion(*ToFDOrErr);
8554 else
8555 return ToFDOrErr.takeError();
8558 if (InitListExpr *SyntForm = E->getSyntacticForm()) {
8559 if (auto ToSyntFormOrErr = import(SyntForm))
8560 To->setSyntacticForm(*ToSyntFormOrErr);
8561 else
8562 return ToSyntFormOrErr.takeError();
8565 // Copy InitListExprBitfields, which are not handled in the ctor of
8566 // InitListExpr.
8567 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator());
8569 return To;
8572 ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
8573 CXXStdInitializerListExpr *E) {
8574 ExpectedType ToTypeOrErr = import(E->getType());
8575 if (!ToTypeOrErr)
8576 return ToTypeOrErr.takeError();
8578 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8579 if (!ToSubExprOrErr)
8580 return ToSubExprOrErr.takeError();
8582 return new (Importer.getToContext()) CXXStdInitializerListExpr(
8583 *ToTypeOrErr, *ToSubExprOrErr);
8586 ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
8587 CXXInheritedCtorInitExpr *E) {
8588 Error Err = Error::success();
8589 auto ToLocation = importChecked(Err, E->getLocation());
8590 auto ToType = importChecked(Err, E->getType());
8591 auto ToConstructor = importChecked(Err, E->getConstructor());
8592 if (Err)
8593 return std::move(Err);
8595 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
8596 ToLocation, ToType, ToConstructor, E->constructsVBase(),
8597 E->inheritedFromVBase());
8600 ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
8601 Error Err = Error::success();
8602 auto ToType = importChecked(Err, E->getType());
8603 auto ToCommonExpr = importChecked(Err, E->getCommonExpr());
8604 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8605 if (Err)
8606 return std::move(Err);
8608 return new (Importer.getToContext()) ArrayInitLoopExpr(
8609 ToType, ToCommonExpr, ToSubExpr);
8612 ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
8613 ExpectedType ToTypeOrErr = import(E->getType());
8614 if (!ToTypeOrErr)
8615 return ToTypeOrErr.takeError();
8616 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
8619 ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8620 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc());
8621 if (!ToBeginLocOrErr)
8622 return ToBeginLocOrErr.takeError();
8624 auto ToFieldOrErr = import(E->getField());
8625 if (!ToFieldOrErr)
8626 return ToFieldOrErr.takeError();
8628 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
8629 if (!UsedContextOrErr)
8630 return UsedContextOrErr.takeError();
8632 FieldDecl *ToField = *ToFieldOrErr;
8633 assert(ToField->hasInClassInitializer() &&
8634 "Field should have in-class initializer if there is a default init "
8635 "expression that uses it.");
8636 if (!ToField->getInClassInitializer()) {
8637 // The in-class initializer may be not yet set in "To" AST even if the
8638 // field is already there. This must be set here to make construction of
8639 // CXXDefaultInitExpr work.
8640 auto ToInClassInitializerOrErr =
8641 import(E->getField()->getInClassInitializer());
8642 if (!ToInClassInitializerOrErr)
8643 return ToInClassInitializerOrErr.takeError();
8644 ToField->setInClassInitializer(*ToInClassInitializerOrErr);
8647 Expr *RewrittenInit = nullptr;
8648 if (E->hasRewrittenInit()) {
8649 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
8650 if (!ExprOrErr)
8651 return ExprOrErr.takeError();
8652 RewrittenInit = ExprOrErr.get();
8655 return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr,
8656 ToField, *UsedContextOrErr, RewrittenInit);
8659 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
8660 Error Err = Error::success();
8661 auto ToType = importChecked(Err, E->getType());
8662 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8663 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
8664 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8665 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8666 auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets());
8667 if (Err)
8668 return std::move(Err);
8670 ExprValueKind VK = E->getValueKind();
8671 CastKind CK = E->getCastKind();
8672 auto ToBasePathOrErr = ImportCastPath(E);
8673 if (!ToBasePathOrErr)
8674 return ToBasePathOrErr.takeError();
8676 if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) {
8677 return CXXStaticCastExpr::Create(
8678 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8679 ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc,
8680 ToAngleBrackets);
8681 } else if (isa<CXXDynamicCastExpr>(E)) {
8682 return CXXDynamicCastExpr::Create(
8683 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8684 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8685 } else if (isa<CXXReinterpretCastExpr>(E)) {
8686 return CXXReinterpretCastExpr::Create(
8687 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8688 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8689 } else if (isa<CXXConstCastExpr>(E)) {
8690 return CXXConstCastExpr::Create(
8691 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten,
8692 ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8693 } else {
8694 llvm_unreachable("Unknown cast type");
8695 return make_error<ASTImportError>();
8699 ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
8700 SubstNonTypeTemplateParmExpr *E) {
8701 Error Err = Error::success();
8702 auto ToType = importChecked(Err, E->getType());
8703 auto ToExprLoc = importChecked(Err, E->getExprLoc());
8704 auto ToAssociatedDecl = importChecked(Err, E->getAssociatedDecl());
8705 auto ToReplacement = importChecked(Err, E->getReplacement());
8706 if (Err)
8707 return std::move(Err);
8709 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
8710 ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl,
8711 E->getIndex(), E->getPackIndex(), E->isReferenceParameter());
8714 ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
8715 Error Err = Error::success();
8716 auto ToType = importChecked(Err, E->getType());
8717 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
8718 auto ToEndLoc = importChecked(Err, E->getEndLoc());
8719 if (Err)
8720 return std::move(Err);
8722 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
8723 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs))
8724 return std::move(Err);
8726 // According to Sema::BuildTypeTrait(), if E is value-dependent,
8727 // Value is always false.
8728 bool ToValue = (E->isValueDependent() ? false : E->getValue());
8730 return TypeTraitExpr::Create(
8731 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs,
8732 ToEndLoc, ToValue);
8735 ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
8736 ExpectedType ToTypeOrErr = import(E->getType());
8737 if (!ToTypeOrErr)
8738 return ToTypeOrErr.takeError();
8740 auto ToSourceRangeOrErr = import(E->getSourceRange());
8741 if (!ToSourceRangeOrErr)
8742 return ToSourceRangeOrErr.takeError();
8744 if (E->isTypeOperand()) {
8745 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo()))
8746 return new (Importer.getToContext()) CXXTypeidExpr(
8747 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
8748 else
8749 return ToTSIOrErr.takeError();
8752 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand());
8753 if (!ToExprOperandOrErr)
8754 return ToExprOperandOrErr.takeError();
8756 return new (Importer.getToContext()) CXXTypeidExpr(
8757 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
8760 ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
8761 Error Err = Error::success();
8763 QualType ToType = importChecked(Err, E->getType());
8764 UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
8765 SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
8766 Expr *ToLHS = importChecked(Err, E->getLHS());
8767 SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
8768 Expr *ToRHS = importChecked(Err, E->getRHS());
8769 SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
8771 if (Err)
8772 return std::move(Err);
8774 return new (Importer.getToContext())
8775 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
8776 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
8779 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
8780 CXXMethodDecl *FromMethod) {
8781 Error ImportErrors = Error::success();
8782 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
8783 if (auto ImportedOrErr = import(FromOverriddenMethod))
8784 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>(
8785 (*ImportedOrErr)->getCanonicalDecl()));
8786 else
8787 ImportErrors =
8788 joinErrors(std::move(ImportErrors), ImportedOrErr.takeError());
8790 return ImportErrors;
8793 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
8794 ASTContext &FromContext, FileManager &FromFileManager,
8795 bool MinimalImport,
8796 std::shared_ptr<ASTImporterSharedState> SharedState)
8797 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
8798 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
8799 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
8801 // Create a default state without the lookup table: LLDB case.
8802 if (!SharedState) {
8803 this->SharedState = std::make_shared<ASTImporterSharedState>();
8806 ImportedDecls[FromContext.getTranslationUnitDecl()] =
8807 ToContext.getTranslationUnitDecl();
8810 ASTImporter::~ASTImporter() = default;
8812 std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
8813 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
8814 "Try to get field index for non-field.");
8816 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
8817 if (!Owner)
8818 return std::nullopt;
8820 unsigned Index = 0;
8821 for (const auto *D : Owner->decls()) {
8822 if (D == F)
8823 return Index;
8825 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
8826 ++Index;
8829 llvm_unreachable("Field was not found in its parent context.");
8831 return std::nullopt;
8834 ASTImporter::FoundDeclsTy
8835 ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
8836 // We search in the redecl context because of transparent contexts.
8837 // E.g. a simple C language enum is a transparent context:
8838 // enum E { A, B };
8839 // Now if we had a global variable in the TU
8840 // int A;
8841 // then the enum constant 'A' and the variable 'A' violates ODR.
8842 // We can diagnose this only if we search in the redecl context.
8843 DeclContext *ReDC = DC->getRedeclContext();
8844 if (SharedState->getLookupTable()) {
8845 ASTImporterLookupTable::LookupResult LookupResult =
8846 SharedState->getLookupTable()->lookup(ReDC, Name);
8847 return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
8848 } else {
8849 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
8850 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
8851 // We must search by the slow case of localUncachedLookup because that is
8852 // working even if there is no LookupPtr for the DC. We could use
8853 // DC::buildLookup() to create the LookupPtr, but that would load external
8854 // decls again, we must avoid that case.
8855 // Also, even if we had the LookupPtr, we must find Decls which are not
8856 // in the LookupPtr, so we need the slow case.
8857 // These cases are handled in ASTImporterLookupTable, but we cannot use
8858 // that with LLDB since that traverses through the AST which initiates the
8859 // load of external decls again via DC::decls(). And again, we must avoid
8860 // loading external decls during the import.
8861 if (Result.empty())
8862 ReDC->localUncachedLookup(Name, Result);
8863 return Result;
8867 void ASTImporter::AddToLookupTable(Decl *ToD) {
8868 SharedState->addDeclToLookup(ToD);
8871 Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
8872 // Import the decl using ASTNodeImporter.
8873 ASTNodeImporter Importer(*this);
8874 return Importer.Visit(FromD);
8877 void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
8878 MapImported(FromD, ToD);
8881 llvm::Expected<ExprWithCleanups::CleanupObject>
8882 ASTImporter::Import(ExprWithCleanups::CleanupObject From) {
8883 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
8884 if (Expected<Expr *> R = Import(CLE))
8885 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R));
8888 // FIXME: Handle BlockDecl when we implement importing BlockExpr in
8889 // ASTNodeImporter.
8890 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
8893 ExpectedTypePtr ASTImporter::Import(const Type *FromT) {
8894 if (!FromT)
8895 return FromT;
8897 // Check whether we've already imported this type.
8898 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
8899 ImportedTypes.find(FromT);
8900 if (Pos != ImportedTypes.end())
8901 return Pos->second;
8903 // Import the type.
8904 ASTNodeImporter Importer(*this);
8905 ExpectedType ToTOrErr = Importer.Visit(FromT);
8906 if (!ToTOrErr)
8907 return ToTOrErr.takeError();
8909 // Record the imported type.
8910 ImportedTypes[FromT] = ToTOrErr->getTypePtr();
8912 return ToTOrErr->getTypePtr();
8915 Expected<QualType> ASTImporter::Import(QualType FromT) {
8916 if (FromT.isNull())
8917 return QualType{};
8919 ExpectedTypePtr ToTyOrErr = Import(FromT.getTypePtr());
8920 if (!ToTyOrErr)
8921 return ToTyOrErr.takeError();
8923 return ToContext.getQualifiedType(*ToTyOrErr, FromT.getLocalQualifiers());
8926 Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
8927 if (!FromTSI)
8928 return FromTSI;
8930 // FIXME: For now we just create a "trivial" type source info based
8931 // on the type and a single location. Implement a real version of this.
8932 ExpectedType TOrErr = Import(FromTSI->getType());
8933 if (!TOrErr)
8934 return TOrErr.takeError();
8935 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc());
8936 if (!BeginLocOrErr)
8937 return BeginLocOrErr.takeError();
8939 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
8942 namespace {
8943 // To use this object, it should be created before the new attribute is created,
8944 // and destructed after it is created. The construction already performs the
8945 // import of the data.
8946 template <typename T> struct AttrArgImporter {
8947 AttrArgImporter(const AttrArgImporter<T> &) = delete;
8948 AttrArgImporter(AttrArgImporter<T> &&) = default;
8949 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete;
8950 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default;
8952 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From)
8953 : To(I.importChecked(Err, From)) {}
8955 const T &value() { return To; }
8957 private:
8958 T To;
8961 // To use this object, it should be created before the new attribute is created,
8962 // and destructed after it is created. The construction already performs the
8963 // import of the data. The array data is accessible in a pointer form, this form
8964 // is used by the attribute classes. This object should be created once for the
8965 // array data to be imported (the array size is not imported, just copied).
8966 template <typename T> struct AttrArgArrayImporter {
8967 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete;
8968 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default;
8969 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete;
8970 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default;
8972 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err,
8973 const llvm::iterator_range<T *> &From,
8974 unsigned ArraySize) {
8975 if (Err)
8976 return;
8977 To.reserve(ArraySize);
8978 Err = I.ImportContainerChecked(From, To);
8981 T *value() { return To.data(); }
8983 private:
8984 llvm::SmallVector<T, 2> To;
8987 class AttrImporter {
8988 Error Err{Error::success()};
8989 Attr *ToAttr = nullptr;
8990 ASTImporter &Importer;
8991 ASTNodeImporter NImporter;
8993 public:
8994 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {}
8996 // Useful for accessing the imported attribute.
8997 template <typename T> T *castAttrAs() { return cast<T>(ToAttr); }
8998 template <typename T> const T *castAttrAs() const { return cast<T>(ToAttr); }
9000 // Create an "importer" for an attribute parameter.
9001 // Result of the 'value()' of that object is to be passed to the function
9002 // 'importAttr', in the order that is expected by the attribute class.
9003 template <class T> AttrArgImporter<T> importArg(const T &From) {
9004 return AttrArgImporter<T>(NImporter, Err, From);
9007 // Create an "importer" for an attribute parameter that has array type.
9008 // Result of the 'value()' of that object is to be passed to the function
9009 // 'importAttr', then the size of the array as next argument.
9010 template <typename T>
9011 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From,
9012 unsigned ArraySize) {
9013 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize);
9016 // Create an attribute object with the specified arguments.
9017 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg'
9018 // should be values that are passed to the 'Create' function of the attribute.
9019 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is
9020 // used here.) As much data is copied or imported from the old attribute
9021 // as possible. The passed arguments should be already imported.
9022 // If an import error happens, the internal error is set to it, and any
9023 // further import attempt is ignored.
9024 template <typename T, typename... Arg>
9025 void importAttr(const T *FromAttr, Arg &&...ImportedArg) {
9026 static_assert(std::is_base_of<Attr, T>::value,
9027 "T should be subclass of Attr.");
9028 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9030 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName());
9031 const IdentifierInfo *ToScopeName =
9032 Importer.Import(FromAttr->getScopeName());
9033 SourceRange ToAttrRange =
9034 NImporter.importChecked(Err, FromAttr->getRange());
9035 SourceLocation ToScopeLoc =
9036 NImporter.importChecked(Err, FromAttr->getScopeLoc());
9038 if (Err)
9039 return;
9041 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc,
9042 FromAttr->getParsedKind(), FromAttr->getForm());
9043 // The "SemanticSpelling" is not needed to be passed to the constructor.
9044 // That value is recalculated from the SpellingListIndex if needed.
9045 ToAttr = T::Create(Importer.getToContext(),
9046 std::forward<Arg>(ImportedArg)..., ToI);
9048 ToAttr->setImplicit(FromAttr->isImplicit());
9049 ToAttr->setPackExpansion(FromAttr->isPackExpansion());
9050 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(ToAttr))
9051 ToInheritableAttr->setInherited(FromAttr->isInherited());
9054 // Create a clone of the 'FromAttr' and import its source range only.
9055 // This causes objects with invalid references to be created if the 'FromAttr'
9056 // contains other data that should be imported.
9057 void cloneAttr(const Attr *FromAttr) {
9058 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9060 SourceRange ToRange = NImporter.importChecked(Err, FromAttr->getRange());
9061 if (Err)
9062 return;
9064 ToAttr = FromAttr->clone(Importer.getToContext());
9065 ToAttr->setRange(ToRange);
9068 // Get the result of the previous import attempt (can be used only once).
9069 llvm::Expected<Attr *> getResult() && {
9070 if (Err)
9071 return std::move(Err);
9072 assert(ToAttr && "Attribute should be created.");
9073 return ToAttr;
9076 } // namespace
9078 Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
9079 AttrImporter AI(*this);
9081 // FIXME: Is there some kind of AttrVisitor to use here?
9082 switch (FromAttr->getKind()) {
9083 case attr::Aligned: {
9084 auto *From = cast<AlignedAttr>(FromAttr);
9085 if (From->isAlignmentExpr())
9086 AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value());
9087 else
9088 AI.importAttr(From, false,
9089 AI.importArg(From->getAlignmentType()).value());
9090 break;
9093 case attr::Format: {
9094 const auto *From = cast<FormatAttr>(FromAttr);
9095 AI.importAttr(From, Import(From->getType()), From->getFormatIdx(),
9096 From->getFirstArg());
9097 break;
9100 case attr::EnableIf: {
9101 const auto *From = cast<EnableIfAttr>(FromAttr);
9102 AI.importAttr(From, AI.importArg(From->getCond()).value(),
9103 From->getMessage());
9104 break;
9107 case attr::AssertCapability: {
9108 const auto *From = cast<AssertCapabilityAttr>(FromAttr);
9109 AI.importAttr(From,
9110 AI.importArrayArg(From->args(), From->args_size()).value(),
9111 From->args_size());
9112 break;
9114 case attr::AcquireCapability: {
9115 const auto *From = cast<AcquireCapabilityAttr>(FromAttr);
9116 AI.importAttr(From,
9117 AI.importArrayArg(From->args(), From->args_size()).value(),
9118 From->args_size());
9119 break;
9121 case attr::TryAcquireCapability: {
9122 const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr);
9123 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9124 AI.importArrayArg(From->args(), From->args_size()).value(),
9125 From->args_size());
9126 break;
9128 case attr::ReleaseCapability: {
9129 const auto *From = cast<ReleaseCapabilityAttr>(FromAttr);
9130 AI.importAttr(From,
9131 AI.importArrayArg(From->args(), From->args_size()).value(),
9132 From->args_size());
9133 break;
9135 case attr::RequiresCapability: {
9136 const auto *From = cast<RequiresCapabilityAttr>(FromAttr);
9137 AI.importAttr(From,
9138 AI.importArrayArg(From->args(), From->args_size()).value(),
9139 From->args_size());
9140 break;
9142 case attr::GuardedBy: {
9143 const auto *From = cast<GuardedByAttr>(FromAttr);
9144 AI.importAttr(From, AI.importArg(From->getArg()).value());
9145 break;
9147 case attr::PtGuardedBy: {
9148 const auto *From = cast<PtGuardedByAttr>(FromAttr);
9149 AI.importAttr(From, AI.importArg(From->getArg()).value());
9150 break;
9152 case attr::AcquiredAfter: {
9153 const auto *From = cast<AcquiredAfterAttr>(FromAttr);
9154 AI.importAttr(From,
9155 AI.importArrayArg(From->args(), From->args_size()).value(),
9156 From->args_size());
9157 break;
9159 case attr::AcquiredBefore: {
9160 const auto *From = cast<AcquiredBeforeAttr>(FromAttr);
9161 AI.importAttr(From,
9162 AI.importArrayArg(From->args(), From->args_size()).value(),
9163 From->args_size());
9164 break;
9166 case attr::AssertExclusiveLock: {
9167 const auto *From = cast<AssertExclusiveLockAttr>(FromAttr);
9168 AI.importAttr(From,
9169 AI.importArrayArg(From->args(), From->args_size()).value(),
9170 From->args_size());
9171 break;
9173 case attr::AssertSharedLock: {
9174 const auto *From = cast<AssertSharedLockAttr>(FromAttr);
9175 AI.importAttr(From,
9176 AI.importArrayArg(From->args(), From->args_size()).value(),
9177 From->args_size());
9178 break;
9180 case attr::ExclusiveTrylockFunction: {
9181 const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr);
9182 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9183 AI.importArrayArg(From->args(), From->args_size()).value(),
9184 From->args_size());
9185 break;
9187 case attr::SharedTrylockFunction: {
9188 const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr);
9189 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9190 AI.importArrayArg(From->args(), From->args_size()).value(),
9191 From->args_size());
9192 break;
9194 case attr::LockReturned: {
9195 const auto *From = cast<LockReturnedAttr>(FromAttr);
9196 AI.importAttr(From, AI.importArg(From->getArg()).value());
9197 break;
9199 case attr::LocksExcluded: {
9200 const auto *From = cast<LocksExcludedAttr>(FromAttr);
9201 AI.importAttr(From,
9202 AI.importArrayArg(From->args(), From->args_size()).value(),
9203 From->args_size());
9204 break;
9206 case attr::CountedBy: {
9207 AI.cloneAttr(FromAttr);
9208 const auto *CBA = cast<CountedByAttr>(FromAttr);
9209 Expected<SourceRange> SR = Import(CBA->getCountedByFieldLoc()).get();
9210 if (!SR)
9211 return SR.takeError();
9212 AI.castAttrAs<CountedByAttr>()->setCountedByFieldLoc(SR.get());
9213 break;
9216 default: {
9217 // The default branch works for attributes that have no arguments to import.
9218 // FIXME: Handle every attribute type that has arguments of type to import
9219 // (most often Expr* or Decl* or type) in the switch above.
9220 AI.cloneAttr(FromAttr);
9221 break;
9225 return std::move(AI).getResult();
9228 Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
9229 return ImportedDecls.lookup(FromD);
9232 TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
9233 auto FromDPos = ImportedFromDecls.find(ToD);
9234 if (FromDPos == ImportedFromDecls.end())
9235 return nullptr;
9236 return FromDPos->second->getTranslationUnitDecl();
9239 Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) {
9240 if (!FromD->hasAttrs() || ToD->hasAttrs())
9241 return Error::success();
9242 for (const Attr *FromAttr : FromD->getAttrs()) {
9243 auto ToAttrOrErr = Import(FromAttr);
9244 if (ToAttrOrErr)
9245 ToD->addAttr(*ToAttrOrErr);
9246 else
9247 return ToAttrOrErr.takeError();
9249 return Error::success();
9252 Expected<Decl *> ASTImporter::Import(Decl *FromD) {
9253 if (!FromD)
9254 return nullptr;
9256 // Push FromD to the stack, and remove that when we return.
9257 ImportPath.push(FromD);
9258 auto ImportPathBuilder =
9259 llvm::make_scope_exit([this]() { ImportPath.pop(); });
9261 // Check whether there was a previous failed import.
9262 // If yes return the existing error.
9263 if (auto Error = getImportDeclErrorIfAny(FromD))
9264 return make_error<ASTImportError>(*Error);
9266 // Check whether we've already imported this declaration.
9267 Decl *ToD = GetAlreadyImportedOrNull(FromD);
9268 if (ToD) {
9269 // Already imported (possibly from another TU) and with an error.
9270 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9271 setImportDeclError(FromD, *Error);
9272 return make_error<ASTImportError>(*Error);
9275 // If FromD has some updated flags after last import, apply it.
9276 updateFlags(FromD, ToD);
9277 // If we encounter a cycle during an import then we save the relevant part
9278 // of the import path associated to the Decl.
9279 if (ImportPath.hasCycleAtBack())
9280 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack());
9281 return ToD;
9284 // Import the declaration.
9285 ExpectedDecl ToDOrErr = ImportImpl(FromD);
9286 if (!ToDOrErr) {
9287 // Failed to import.
9289 auto Pos = ImportedDecls.find(FromD);
9290 if (Pos != ImportedDecls.end()) {
9291 // Import failed after the object was created.
9292 // Remove all references to it.
9293 auto *ToD = Pos->second;
9294 ImportedDecls.erase(Pos);
9296 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
9297 // (e.g. with namespaces) that several decls from the 'from' context are
9298 // mapped to the same decl in the 'to' context. If we removed entries
9299 // from the LookupTable here then we may end up removing them multiple
9300 // times.
9302 // The Lookuptable contains decls only which are in the 'to' context.
9303 // Remove from the Lookuptable only if it is *imported* into the 'to'
9304 // context (and do not remove it if it was added during the initial
9305 // traverse of the 'to' context).
9306 auto PosF = ImportedFromDecls.find(ToD);
9307 if (PosF != ImportedFromDecls.end()) {
9308 // In the case of TypedefNameDecl we create the Decl first and only
9309 // then we import and set its DeclContext. So, the DC might not be set
9310 // when we reach here.
9311 if (ToD->getDeclContext())
9312 SharedState->removeDeclFromLookup(ToD);
9313 ImportedFromDecls.erase(PosF);
9316 // FIXME: AST may contain remaining references to the failed object.
9317 // However, the ImportDeclErrors in the shared state contains all the
9318 // failed objects together with their error.
9321 // Error encountered for the first time.
9322 // After takeError the error is not usable any more in ToDOrErr.
9323 // Get a copy of the error object (any more simple solution for this?).
9324 ASTImportError ErrOut;
9325 handleAllErrors(ToDOrErr.takeError(),
9326 [&ErrOut](const ASTImportError &E) { ErrOut = E; });
9327 setImportDeclError(FromD, ErrOut);
9328 // Set the error for the mapped to Decl, which is in the "to" context.
9329 if (Pos != ImportedDecls.end())
9330 SharedState->setImportDeclError(Pos->second, ErrOut);
9332 // Set the error for all nodes which have been created before we
9333 // recognized the error.
9334 for (const auto &Path : SavedImportPaths[FromD]) {
9335 // The import path contains import-dependency nodes first.
9336 // Save the node that was imported as dependency of the current node.
9337 Decl *PrevFromDi = FromD;
9338 for (Decl *FromDi : Path) {
9339 // Begin and end of the path equals 'FromD', skip it.
9340 if (FromDi == FromD)
9341 continue;
9342 // We should not set import error on a node and all following nodes in
9343 // the path if child import errors are ignored.
9344 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent(
9345 PrevFromDi))
9346 break;
9347 PrevFromDi = FromDi;
9348 setImportDeclError(FromDi, ErrOut);
9349 //FIXME Should we remove these Decls from ImportedDecls?
9350 // Set the error for the mapped to Decl, which is in the "to" context.
9351 auto Ii = ImportedDecls.find(FromDi);
9352 if (Ii != ImportedDecls.end())
9353 SharedState->setImportDeclError(Ii->second, ErrOut);
9354 // FIXME Should we remove these Decls from the LookupTable,
9355 // and from ImportedFromDecls?
9358 SavedImportPaths.erase(FromD);
9360 // Do not return ToDOrErr, error was taken out of it.
9361 return make_error<ASTImportError>(ErrOut);
9364 ToD = *ToDOrErr;
9366 // FIXME: Handle the "already imported with error" case. We can get here
9367 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
9368 // previously failed create was requested).
9369 // Later GetImportedOrCreateDecl can be updated to return the error.
9370 if (!ToD) {
9371 auto Err = getImportDeclErrorIfAny(FromD);
9372 assert(Err);
9373 return make_error<ASTImportError>(*Err);
9376 // We could import from the current TU without error. But previously we
9377 // already had imported a Decl as `ToD` from another TU (with another
9378 // ASTImporter object) and with an error.
9379 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9380 setImportDeclError(FromD, *Error);
9381 return make_error<ASTImportError>(*Error);
9384 // Make sure that ImportImpl registered the imported decl.
9385 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
9386 if (auto Error = ImportAttrs(ToD, FromD))
9387 return std::move(Error);
9389 // Notify subclasses.
9390 Imported(FromD, ToD);
9392 updateFlags(FromD, ToD);
9393 SavedImportPaths.erase(FromD);
9394 return ToDOrErr;
9397 llvm::Expected<InheritedConstructor>
9398 ASTImporter::Import(const InheritedConstructor &From) {
9399 return ASTNodeImporter(*this).ImportInheritedConstructor(From);
9402 Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
9403 if (!FromDC)
9404 return FromDC;
9406 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC));
9407 if (!ToDCOrErr)
9408 return ToDCOrErr.takeError();
9409 auto *ToDC = cast<DeclContext>(*ToDCOrErr);
9411 // When we're using a record/enum/Objective-C class/protocol as a context, we
9412 // need it to have a definition.
9413 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
9414 auto *FromRecord = cast<RecordDecl>(FromDC);
9415 if (ToRecord->isCompleteDefinition())
9416 return ToDC;
9418 // If FromRecord is not defined we need to force it to be.
9419 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases
9420 // it will start the definition but we never finish it.
9421 // If there are base classes they won't be imported and we will
9422 // be missing anything that we inherit from those bases.
9423 if (FromRecord->getASTContext().getExternalSource() &&
9424 !FromRecord->isCompleteDefinition())
9425 FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord);
9427 if (FromRecord->isCompleteDefinition())
9428 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9429 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic))
9430 return std::move(Err);
9431 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
9432 auto *FromEnum = cast<EnumDecl>(FromDC);
9433 if (ToEnum->isCompleteDefinition()) {
9434 // Do nothing.
9435 } else if (FromEnum->isCompleteDefinition()) {
9436 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9437 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic))
9438 return std::move(Err);
9439 } else {
9440 CompleteDecl(ToEnum);
9442 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
9443 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
9444 if (ToClass->getDefinition()) {
9445 // Do nothing.
9446 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
9447 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9448 FromDef, ToClass, ASTNodeImporter::IDK_Basic))
9449 return std::move(Err);
9450 } else {
9451 CompleteDecl(ToClass);
9453 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
9454 auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
9455 if (ToProto->getDefinition()) {
9456 // Do nothing.
9457 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
9458 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9459 FromDef, ToProto, ASTNodeImporter::IDK_Basic))
9460 return std::move(Err);
9461 } else {
9462 CompleteDecl(ToProto);
9466 return ToDC;
9469 Expected<Expr *> ASTImporter::Import(Expr *FromE) {
9470 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE)))
9471 return cast_or_null<Expr>(*ToSOrErr);
9472 else
9473 return ToSOrErr.takeError();
9476 Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
9477 if (!FromS)
9478 return nullptr;
9480 // Check whether we've already imported this statement.
9481 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
9482 if (Pos != ImportedStmts.end())
9483 return Pos->second;
9485 // Import the statement.
9486 ASTNodeImporter Importer(*this);
9487 ExpectedStmt ToSOrErr = Importer.Visit(FromS);
9488 if (!ToSOrErr)
9489 return ToSOrErr;
9491 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
9492 auto *FromE = cast<Expr>(FromS);
9493 // Copy ExprBitfields, which may not be handled in Expr subclasses
9494 // constructors.
9495 ToE->setValueKind(FromE->getValueKind());
9496 ToE->setObjectKind(FromE->getObjectKind());
9497 ToE->setDependence(FromE->getDependence());
9500 // Record the imported statement object.
9501 ImportedStmts[FromS] = *ToSOrErr;
9502 return ToSOrErr;
9505 Expected<NestedNameSpecifier *>
9506 ASTImporter::Import(NestedNameSpecifier *FromNNS) {
9507 if (!FromNNS)
9508 return nullptr;
9510 NestedNameSpecifier *Prefix = nullptr;
9511 if (Error Err = importInto(Prefix, FromNNS->getPrefix()))
9512 return std::move(Err);
9514 switch (FromNNS->getKind()) {
9515 case NestedNameSpecifier::Identifier:
9516 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
9517 return NestedNameSpecifier::Create(ToContext, Prefix,
9518 Import(FromNNS->getAsIdentifier()));
9520 case NestedNameSpecifier::Namespace:
9521 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
9522 return NestedNameSpecifier::Create(ToContext, Prefix,
9523 cast<NamespaceDecl>(*NSOrErr));
9524 } else
9525 return NSOrErr.takeError();
9527 case NestedNameSpecifier::NamespaceAlias:
9528 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
9529 return NestedNameSpecifier::Create(ToContext, Prefix,
9530 cast<NamespaceAliasDecl>(*NSADOrErr));
9531 else
9532 return NSADOrErr.takeError();
9534 case NestedNameSpecifier::Global:
9535 return NestedNameSpecifier::GlobalSpecifier(ToContext);
9537 case NestedNameSpecifier::Super:
9538 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
9539 return NestedNameSpecifier::SuperSpecifier(ToContext,
9540 cast<CXXRecordDecl>(*RDOrErr));
9541 else
9542 return RDOrErr.takeError();
9544 case NestedNameSpecifier::TypeSpec:
9545 case NestedNameSpecifier::TypeSpecWithTemplate:
9546 if (ExpectedTypePtr TyOrErr = Import(FromNNS->getAsType())) {
9547 bool TSTemplate =
9548 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
9549 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate,
9550 *TyOrErr);
9551 } else {
9552 return TyOrErr.takeError();
9556 llvm_unreachable("Invalid nested name specifier kind");
9559 Expected<NestedNameSpecifierLoc>
9560 ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
9561 // Copied from NestedNameSpecifier mostly.
9562 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
9563 NestedNameSpecifierLoc NNS = FromNNS;
9565 // Push each of the nested-name-specifiers's onto a stack for
9566 // serialization in reverse order.
9567 while (NNS) {
9568 NestedNames.push_back(NNS);
9569 NNS = NNS.getPrefix();
9572 NestedNameSpecifierLocBuilder Builder;
9574 while (!NestedNames.empty()) {
9575 NNS = NestedNames.pop_back_val();
9576 NestedNameSpecifier *Spec = nullptr;
9577 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier()))
9578 return std::move(Err);
9580 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
9582 SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
9583 if (Kind != NestedNameSpecifier::Super) {
9584 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc()))
9585 return std::move(Err);
9587 if (Kind != NestedNameSpecifier::Global)
9588 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc()))
9589 return std::move(Err);
9592 switch (Kind) {
9593 case NestedNameSpecifier::Identifier:
9594 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc,
9595 ToLocalEndLoc);
9596 break;
9598 case NestedNameSpecifier::Namespace:
9599 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc,
9600 ToLocalEndLoc);
9601 break;
9603 case NestedNameSpecifier::NamespaceAlias:
9604 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(),
9605 ToLocalBeginLoc, ToLocalEndLoc);
9606 break;
9608 case NestedNameSpecifier::TypeSpec:
9609 case NestedNameSpecifier::TypeSpecWithTemplate: {
9610 SourceLocation ToTLoc;
9611 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc()))
9612 return std::move(Err);
9613 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
9614 QualType(Spec->getAsType(), 0), ToTLoc);
9615 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate)
9616 // ToLocalBeginLoc is here the location of the 'template' keyword.
9617 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(),
9618 ToLocalEndLoc);
9619 else
9620 // No location for 'template' keyword here.
9621 Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(),
9622 ToLocalEndLoc);
9623 break;
9626 case NestedNameSpecifier::Global:
9627 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc);
9628 break;
9630 case NestedNameSpecifier::Super: {
9631 auto ToSourceRangeOrErr = Import(NNS.getSourceRange());
9632 if (!ToSourceRangeOrErr)
9633 return ToSourceRangeOrErr.takeError();
9635 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(),
9636 ToSourceRangeOrErr->getBegin(),
9637 ToSourceRangeOrErr->getEnd());
9642 return Builder.getWithLocInContext(getToContext());
9645 Expected<TemplateName> ASTImporter::Import(TemplateName From) {
9646 switch (From.getKind()) {
9647 case TemplateName::Template:
9648 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
9649 return TemplateName(cast<TemplateDecl>((*ToTemplateOrErr)->getCanonicalDecl()));
9650 else
9651 return ToTemplateOrErr.takeError();
9653 case TemplateName::OverloadedTemplate: {
9654 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
9655 UnresolvedSet<2> ToTemplates;
9656 for (auto *I : *FromStorage) {
9657 if (auto ToOrErr = Import(I))
9658 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
9659 else
9660 return ToOrErr.takeError();
9662 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
9663 ToTemplates.end());
9666 case TemplateName::AssumedTemplate: {
9667 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
9668 auto DeclNameOrErr = Import(FromStorage->getDeclName());
9669 if (!DeclNameOrErr)
9670 return DeclNameOrErr.takeError();
9671 return ToContext.getAssumedTemplateName(*DeclNameOrErr);
9674 case TemplateName::QualifiedTemplate: {
9675 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
9676 auto QualifierOrErr = Import(QTN->getQualifier());
9677 if (!QualifierOrErr)
9678 return QualifierOrErr.takeError();
9679 auto TNOrErr = Import(QTN->getUnderlyingTemplate());
9680 if (!TNOrErr)
9681 return TNOrErr.takeError();
9682 return ToContext.getQualifiedTemplateName(
9683 *QualifierOrErr, QTN->hasTemplateKeyword(), *TNOrErr);
9686 case TemplateName::DependentTemplate: {
9687 DependentTemplateName *DTN = From.getAsDependentTemplateName();
9688 auto QualifierOrErr = Import(DTN->getQualifier());
9689 if (!QualifierOrErr)
9690 return QualifierOrErr.takeError();
9692 if (DTN->isIdentifier()) {
9693 return ToContext.getDependentTemplateName(*QualifierOrErr,
9694 Import(DTN->getIdentifier()));
9697 return ToContext.getDependentTemplateName(*QualifierOrErr,
9698 DTN->getOperator());
9701 case TemplateName::SubstTemplateTemplateParm: {
9702 SubstTemplateTemplateParmStorage *Subst =
9703 From.getAsSubstTemplateTemplateParm();
9704 auto ReplacementOrErr = Import(Subst->getReplacement());
9705 if (!ReplacementOrErr)
9706 return ReplacementOrErr.takeError();
9708 auto AssociatedDeclOrErr = Import(Subst->getAssociatedDecl());
9709 if (!AssociatedDeclOrErr)
9710 return AssociatedDeclOrErr.takeError();
9712 return ToContext.getSubstTemplateTemplateParm(
9713 *ReplacementOrErr, *AssociatedDeclOrErr, Subst->getIndex(),
9714 Subst->getPackIndex());
9717 case TemplateName::SubstTemplateTemplateParmPack: {
9718 SubstTemplateTemplateParmPackStorage *SubstPack =
9719 From.getAsSubstTemplateTemplateParmPack();
9720 ASTNodeImporter Importer(*this);
9721 auto ArgPackOrErr =
9722 Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
9723 if (!ArgPackOrErr)
9724 return ArgPackOrErr.takeError();
9726 auto AssociatedDeclOrErr = Import(SubstPack->getAssociatedDecl());
9727 if (!AssociatedDeclOrErr)
9728 return AssociatedDeclOrErr.takeError();
9730 return ToContext.getSubstTemplateTemplateParmPack(
9731 *ArgPackOrErr, *AssociatedDeclOrErr, SubstPack->getIndex(),
9732 SubstPack->getFinal());
9734 case TemplateName::UsingTemplate: {
9735 auto UsingOrError = Import(From.getAsUsingShadowDecl());
9736 if (!UsingOrError)
9737 return UsingOrError.takeError();
9738 return TemplateName(cast<UsingShadowDecl>(*UsingOrError));
9742 llvm_unreachable("Invalid template name kind");
9745 Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
9746 if (FromLoc.isInvalid())
9747 return SourceLocation{};
9749 SourceManager &FromSM = FromContext.getSourceManager();
9750 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc);
9752 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
9753 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
9754 if (!ToFileIDOrErr)
9755 return ToFileIDOrErr.takeError();
9756 SourceManager &ToSM = ToContext.getSourceManager();
9757 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second);
9760 Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
9761 SourceLocation ToBegin, ToEnd;
9762 if (Error Err = importInto(ToBegin, FromRange.getBegin()))
9763 return std::move(Err);
9764 if (Error Err = importInto(ToEnd, FromRange.getEnd()))
9765 return std::move(Err);
9767 return SourceRange(ToBegin, ToEnd);
9770 Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
9771 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
9772 if (Pos != ImportedFileIDs.end())
9773 return Pos->second;
9775 SourceManager &FromSM = FromContext.getSourceManager();
9776 SourceManager &ToSM = ToContext.getSourceManager();
9777 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
9779 // Map the FromID to the "to" source manager.
9780 FileID ToID;
9781 if (FromSLoc.isExpansion()) {
9782 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
9783 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc());
9784 if (!ToSpLoc)
9785 return ToSpLoc.takeError();
9786 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart());
9787 if (!ToExLocS)
9788 return ToExLocS.takeError();
9789 unsigned ExLength = FromSM.getFileIDSize(FromID);
9790 SourceLocation MLoc;
9791 if (FromEx.isMacroArgExpansion()) {
9792 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, ExLength);
9793 } else {
9794 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd()))
9795 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, ExLength,
9796 FromEx.isExpansionTokenRange());
9797 else
9798 return ToExLocE.takeError();
9800 ToID = ToSM.getFileID(MLoc);
9801 } else {
9802 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
9804 if (!IsBuiltin && !Cache->BufferOverridden) {
9805 // Include location of this file.
9806 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
9807 if (!ToIncludeLoc)
9808 return ToIncludeLoc.takeError();
9810 // Every FileID that is not the main FileID needs to have a valid include
9811 // location so that the include chain points to the main FileID. When
9812 // importing the main FileID (which has no include location), we need to
9813 // create a fake include location in the main file to keep this property
9814 // intact.
9815 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
9816 if (FromID == FromSM.getMainFileID())
9817 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID());
9819 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
9820 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
9821 // disk again
9822 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
9823 // than mmap the files several times.
9824 auto Entry =
9825 ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName());
9826 // FIXME: The filename may be a virtual name that does probably not
9827 // point to a valid file and we get no Entry here. In this case try with
9828 // the memory buffer below.
9829 if (Entry)
9830 ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc,
9831 FromSLoc.getFile().getFileCharacteristic());
9835 if (ToID.isInvalid() || IsBuiltin) {
9836 // FIXME: We want to re-use the existing MemoryBuffer!
9837 std::optional<llvm::MemoryBufferRef> FromBuf =
9838 Cache->getBufferOrNone(FromContext.getDiagnostics(),
9839 FromSM.getFileManager(), SourceLocation{});
9840 if (!FromBuf)
9841 return llvm::make_error<ASTImportError>(ASTImportError::Unknown);
9843 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
9844 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
9845 FromBuf->getBufferIdentifier());
9846 ToID = ToSM.createFileID(std::move(ToBuf),
9847 FromSLoc.getFile().getFileCharacteristic());
9851 assert(ToID.isValid() && "Unexpected invalid fileID was created.");
9853 ImportedFileIDs[FromID] = ToID;
9854 return ToID;
9857 Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
9858 ExpectedExpr ToExprOrErr = Import(From->getInit());
9859 if (!ToExprOrErr)
9860 return ToExprOrErr.takeError();
9862 auto LParenLocOrErr = Import(From->getLParenLoc());
9863 if (!LParenLocOrErr)
9864 return LParenLocOrErr.takeError();
9866 auto RParenLocOrErr = Import(From->getRParenLoc());
9867 if (!RParenLocOrErr)
9868 return RParenLocOrErr.takeError();
9870 if (From->isBaseInitializer()) {
9871 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
9872 if (!ToTInfoOrErr)
9873 return ToTInfoOrErr.takeError();
9875 SourceLocation EllipsisLoc;
9876 if (From->isPackExpansion())
9877 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc()))
9878 return std::move(Err);
9880 return new (ToContext) CXXCtorInitializer(
9881 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
9882 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
9883 } else if (From->isMemberInitializer()) {
9884 ExpectedDecl ToFieldOrErr = Import(From->getMember());
9885 if (!ToFieldOrErr)
9886 return ToFieldOrErr.takeError();
9888 auto MemberLocOrErr = Import(From->getMemberLocation());
9889 if (!MemberLocOrErr)
9890 return MemberLocOrErr.takeError();
9892 return new (ToContext) CXXCtorInitializer(
9893 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr,
9894 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
9895 } else if (From->isIndirectMemberInitializer()) {
9896 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
9897 if (!ToIFieldOrErr)
9898 return ToIFieldOrErr.takeError();
9900 auto MemberLocOrErr = Import(From->getMemberLocation());
9901 if (!MemberLocOrErr)
9902 return MemberLocOrErr.takeError();
9904 return new (ToContext) CXXCtorInitializer(
9905 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr),
9906 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
9907 } else if (From->isDelegatingInitializer()) {
9908 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
9909 if (!ToTInfoOrErr)
9910 return ToTInfoOrErr.takeError();
9912 return new (ToContext)
9913 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
9914 *ToExprOrErr, *RParenLocOrErr);
9915 } else {
9916 // FIXME: assert?
9917 return make_error<ASTImportError>();
9921 Expected<CXXBaseSpecifier *>
9922 ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
9923 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
9924 if (Pos != ImportedCXXBaseSpecifiers.end())
9925 return Pos->second;
9927 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange());
9928 if (!ToSourceRange)
9929 return ToSourceRange.takeError();
9930 Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo());
9931 if (!ToTSI)
9932 return ToTSI.takeError();
9933 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc());
9934 if (!ToEllipsisLoc)
9935 return ToEllipsisLoc.takeError();
9936 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
9937 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
9938 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
9939 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
9940 return Imported;
9943 llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) {
9944 ASTNodeImporter Importer(*this);
9945 return Importer.ImportAPValue(FromValue);
9948 Error ASTImporter::ImportDefinition(Decl *From) {
9949 ExpectedDecl ToOrErr = Import(From);
9950 if (!ToOrErr)
9951 return ToOrErr.takeError();
9952 Decl *To = *ToOrErr;
9954 auto *FromDC = cast<DeclContext>(From);
9955 ASTNodeImporter Importer(*this);
9957 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
9958 if (!ToRecord->getDefinition()) {
9959 return Importer.ImportDefinition(
9960 cast<RecordDecl>(FromDC), ToRecord,
9961 ASTNodeImporter::IDK_Everything);
9965 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
9966 if (!ToEnum->getDefinition()) {
9967 return Importer.ImportDefinition(
9968 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything);
9972 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
9973 if (!ToIFace->getDefinition()) {
9974 return Importer.ImportDefinition(
9975 cast<ObjCInterfaceDecl>(FromDC), ToIFace,
9976 ASTNodeImporter::IDK_Everything);
9980 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
9981 if (!ToProto->getDefinition()) {
9982 return Importer.ImportDefinition(
9983 cast<ObjCProtocolDecl>(FromDC), ToProto,
9984 ASTNodeImporter::IDK_Everything);
9988 return Importer.ImportDeclContext(FromDC, true);
9991 Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
9992 if (!FromName)
9993 return DeclarationName{};
9995 switch (FromName.getNameKind()) {
9996 case DeclarationName::Identifier:
9997 return DeclarationName(Import(FromName.getAsIdentifierInfo()));
9999 case DeclarationName::ObjCZeroArgSelector:
10000 case DeclarationName::ObjCOneArgSelector:
10001 case DeclarationName::ObjCMultiArgSelector:
10002 if (auto ToSelOrErr = Import(FromName.getObjCSelector()))
10003 return DeclarationName(*ToSelOrErr);
10004 else
10005 return ToSelOrErr.takeError();
10007 case DeclarationName::CXXConstructorName: {
10008 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10009 return ToContext.DeclarationNames.getCXXConstructorName(
10010 ToContext.getCanonicalType(*ToTyOrErr));
10011 else
10012 return ToTyOrErr.takeError();
10015 case DeclarationName::CXXDestructorName: {
10016 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10017 return ToContext.DeclarationNames.getCXXDestructorName(
10018 ToContext.getCanonicalType(*ToTyOrErr));
10019 else
10020 return ToTyOrErr.takeError();
10023 case DeclarationName::CXXDeductionGuideName: {
10024 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
10025 return ToContext.DeclarationNames.getCXXDeductionGuideName(
10026 cast<TemplateDecl>(*ToTemplateOrErr));
10027 else
10028 return ToTemplateOrErr.takeError();
10031 case DeclarationName::CXXConversionFunctionName: {
10032 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10033 return ToContext.DeclarationNames.getCXXConversionFunctionName(
10034 ToContext.getCanonicalType(*ToTyOrErr));
10035 else
10036 return ToTyOrErr.takeError();
10039 case DeclarationName::CXXOperatorName:
10040 return ToContext.DeclarationNames.getCXXOperatorName(
10041 FromName.getCXXOverloadedOperator());
10043 case DeclarationName::CXXLiteralOperatorName:
10044 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
10045 Import(FromName.getCXXLiteralIdentifier()));
10047 case DeclarationName::CXXUsingDirective:
10048 // FIXME: STATICS!
10049 return DeclarationName::getUsingDirectiveName();
10052 llvm_unreachable("Invalid DeclarationName Kind!");
10055 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
10056 if (!FromId)
10057 return nullptr;
10059 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
10061 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
10062 ToId->setBuiltinID(FromId->getBuiltinID());
10064 return ToId;
10067 Expected<Selector> ASTImporter::Import(Selector FromSel) {
10068 if (FromSel.isNull())
10069 return Selector{};
10071 SmallVector<IdentifierInfo *, 4> Idents;
10072 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
10073 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
10074 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
10075 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
10078 llvm::Expected<APValue>
10079 ASTNodeImporter::ImportAPValue(const APValue &FromValue) {
10080 APValue Result;
10081 llvm::Error Err = llvm::Error::success();
10082 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
10083 for (unsigned Idx = 0; Idx < Size; Idx++) {
10084 APValue Tmp = importChecked(Err, From[Idx]);
10085 To[Idx] = Tmp;
10088 switch (FromValue.getKind()) {
10089 case APValue::None:
10090 case APValue::Indeterminate:
10091 case APValue::Int:
10092 case APValue::Float:
10093 case APValue::FixedPoint:
10094 case APValue::ComplexInt:
10095 case APValue::ComplexFloat:
10096 Result = FromValue;
10097 break;
10098 case APValue::Vector: {
10099 Result.MakeVector();
10100 MutableArrayRef<APValue> Elts =
10101 Result.setVectorUninit(FromValue.getVectorLength());
10102 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
10103 Elts.data(), FromValue.getVectorLength());
10104 break;
10106 case APValue::Array:
10107 Result.MakeArray(FromValue.getArrayInitializedElts(),
10108 FromValue.getArraySize());
10109 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
10110 ((const APValue::Arr *)(const char *)&Result.Data)->Elts,
10111 FromValue.getArrayInitializedElts());
10112 break;
10113 case APValue::Struct:
10114 Result.MakeStruct(FromValue.getStructNumBases(),
10115 FromValue.getStructNumFields());
10116 ImportLoop(
10117 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
10118 ((const APValue::StructData *)(const char *)&Result.Data)->Elts,
10119 FromValue.getStructNumBases() + FromValue.getStructNumFields());
10120 break;
10121 case APValue::Union: {
10122 Result.MakeUnion();
10123 const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField());
10124 APValue ImpValue = importChecked(Err, FromValue.getUnionValue());
10125 if (Err)
10126 return std::move(Err);
10127 Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue);
10128 break;
10130 case APValue::AddrLabelDiff: {
10131 Result.MakeAddrLabelDiff();
10132 const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS());
10133 const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS());
10134 if (Err)
10135 return std::move(Err);
10136 Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS),
10137 cast<AddrLabelExpr>(ImpRHS));
10138 break;
10140 case APValue::MemberPointer: {
10141 const Decl *ImpMemPtrDecl =
10142 importChecked(Err, FromValue.getMemberPointerDecl());
10143 if (Err)
10144 return std::move(Err);
10145 MutableArrayRef<const CXXRecordDecl *> ToPath =
10146 Result.setMemberPointerUninit(
10147 cast<const ValueDecl>(ImpMemPtrDecl),
10148 FromValue.isMemberPointerToDerivedMember(),
10149 FromValue.getMemberPointerPath().size());
10150 llvm::ArrayRef<const CXXRecordDecl *> FromPath =
10151 Result.getMemberPointerPath();
10152 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
10153 Idx++) {
10154 const Decl *ImpDecl = importChecked(Err, FromPath[Idx]);
10155 if (Err)
10156 return std::move(Err);
10157 ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl());
10159 break;
10161 case APValue::LValue:
10162 APValue::LValueBase Base;
10163 QualType FromElemTy;
10164 if (FromValue.getLValueBase()) {
10165 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
10166 "in C++20 dynamic allocation are transient so they shouldn't "
10167 "appear in the AST");
10168 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
10169 if (const auto *E =
10170 FromValue.getLValueBase().dyn_cast<const Expr *>()) {
10171 FromElemTy = E->getType();
10172 const Expr *ImpExpr = importChecked(Err, E);
10173 if (Err)
10174 return std::move(Err);
10175 Base = APValue::LValueBase(ImpExpr,
10176 FromValue.getLValueBase().getCallIndex(),
10177 FromValue.getLValueBase().getVersion());
10178 } else {
10179 FromElemTy =
10180 FromValue.getLValueBase().get<const ValueDecl *>()->getType();
10181 const Decl *ImpDecl = importChecked(
10182 Err, FromValue.getLValueBase().get<const ValueDecl *>());
10183 if (Err)
10184 return std::move(Err);
10185 Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl),
10186 FromValue.getLValueBase().getCallIndex(),
10187 FromValue.getLValueBase().getVersion());
10189 } else {
10190 FromElemTy = FromValue.getLValueBase().getTypeInfoType();
10191 const Type *ImpTypeInfo = importChecked(
10192 Err, FromValue.getLValueBase().get<TypeInfoLValue>().getType());
10193 QualType ImpType =
10194 importChecked(Err, FromValue.getLValueBase().getTypeInfoType());
10195 if (Err)
10196 return std::move(Err);
10197 Base = APValue::LValueBase::getTypeInfo(TypeInfoLValue(ImpTypeInfo),
10198 ImpType);
10201 CharUnits Offset = FromValue.getLValueOffset();
10202 unsigned PathLength = FromValue.getLValuePath().size();
10203 Result.MakeLValue();
10204 if (FromValue.hasLValuePath()) {
10205 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
10206 Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(),
10207 FromValue.isNullPointer());
10208 llvm::ArrayRef<APValue::LValuePathEntry> FromPath =
10209 FromValue.getLValuePath();
10210 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
10211 if (FromElemTy->isRecordType()) {
10212 const Decl *FromDecl =
10213 FromPath[LoopIdx].getAsBaseOrMember().getPointer();
10214 const Decl *ImpDecl = importChecked(Err, FromDecl);
10215 if (Err)
10216 return std::move(Err);
10217 if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl))
10218 FromElemTy = Importer.FromContext.getRecordType(RD);
10219 else
10220 FromElemTy = cast<ValueDecl>(FromDecl)->getType();
10221 ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType(
10222 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
10223 } else {
10224 FromElemTy =
10225 Importer.FromContext.getAsArrayType(FromElemTy)->getElementType();
10226 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
10227 FromPath[LoopIdx].getAsArrayIndex());
10230 } else
10231 Result.setLValue(Base, Offset, APValue::NoLValuePath{},
10232 FromValue.isNullPointer());
10234 if (Err)
10235 return std::move(Err);
10236 return Result;
10239 Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name,
10240 DeclContext *DC,
10241 unsigned IDNS,
10242 NamedDecl **Decls,
10243 unsigned NumDecls) {
10244 if (ODRHandling == ODRHandlingType::Conservative)
10245 // Report error at any name conflict.
10246 return make_error<ASTImportError>(ASTImportError::NameConflict);
10247 else
10248 // Allow to create the new Decl with the same name.
10249 return Name;
10252 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
10253 if (LastDiagFromFrom)
10254 ToContext.getDiagnostics().notePriorDiagnosticFrom(
10255 FromContext.getDiagnostics());
10256 LastDiagFromFrom = false;
10257 return ToContext.getDiagnostics().Report(Loc, DiagID);
10260 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
10261 if (!LastDiagFromFrom)
10262 FromContext.getDiagnostics().notePriorDiagnosticFrom(
10263 ToContext.getDiagnostics());
10264 LastDiagFromFrom = true;
10265 return FromContext.getDiagnostics().Report(Loc, DiagID);
10268 void ASTImporter::CompleteDecl (Decl *D) {
10269 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10270 if (!ID->getDefinition())
10271 ID->startDefinition();
10273 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
10274 if (!PD->getDefinition())
10275 PD->startDefinition();
10277 else if (auto *TD = dyn_cast<TagDecl>(D)) {
10278 if (!TD->getDefinition() && !TD->isBeingDefined()) {
10279 TD->startDefinition();
10280 TD->setCompleteDefinition(true);
10283 else {
10284 assert(0 && "CompleteDecl called on a Decl that can't be completed");
10288 Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
10289 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
10290 assert((Pos == ImportedDecls.end() || Pos->second == To) &&
10291 "Try to import an already imported Decl");
10292 if (Pos != ImportedDecls.end())
10293 return Pos->second;
10294 ImportedDecls[From] = To;
10295 // This mapping should be maintained only in this function. Therefore do not
10296 // check for additional consistency.
10297 ImportedFromDecls[To] = From;
10298 // In the case of TypedefNameDecl we create the Decl first and only then we
10299 // import and set its DeclContext. So, the DC is still not set when we reach
10300 // here from GetImportedOrCreateDecl.
10301 if (To->getDeclContext())
10302 AddToLookupTable(To);
10303 return To;
10306 std::optional<ASTImportError>
10307 ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
10308 auto Pos = ImportDeclErrors.find(FromD);
10309 if (Pos != ImportDeclErrors.end())
10310 return Pos->second;
10311 else
10312 return std::nullopt;
10315 void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) {
10316 auto InsertRes = ImportDeclErrors.insert({From, Error});
10317 (void)InsertRes;
10318 // Either we set the error for the first time, or we already had set one and
10319 // now we want to set the same error.
10320 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
10323 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
10324 bool Complain) {
10325 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
10326 ImportedTypes.find(From.getTypePtr());
10327 if (Pos != ImportedTypes.end()) {
10328 if (ExpectedType ToFromOrErr = Import(From)) {
10329 if (ToContext.hasSameType(*ToFromOrErr, To))
10330 return true;
10331 } else {
10332 llvm::consumeError(ToFromOrErr.takeError());
10336 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
10337 getStructuralEquivalenceKind(*this), false,
10338 Complain);
10339 return Ctx.IsEquivalent(From, To);