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.
11//
12//===----------------------------------------------------------------------===//
13
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>
72
73namespace clang {
74
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>;
85
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";
95 }
96 llvm_unreachable("Invalid error code.");
97 return "Invalid error code.";
98 }
99
100 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
101
102 std::error_code ASTImportError::convertToErrorCode() const {
103 llvm_unreachable("Function not implemented.");
104 }
105
106 char ASTImportError::ID;
107
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(Elt: R);
115 }
116 Redecls.push_back(Elt: D->getFirstDecl());
117 std::reverse(first: Redecls.begin(), last: Redecls.end());
118 return Redecls;
119 }
120
121 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
122 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
123 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
124 if (auto *VD = dyn_cast<VarDecl>(Val: D))
125 return getCanonicalForwardRedeclChain<VarDecl>(VD);
126 if (auto *TD = dyn_cast<TagDecl>(Val: D))
127 return getCanonicalForwardRedeclChain<TagDecl>(TD);
128 llvm_unreachable("Bad declaration kind");
129 }
130
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(CheckUsedAttr: false) && !To->isUsed(CheckUsedAttr: false))
135 To->setIsUsed();
136 }
137
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;
150
151 public:
152 ChildErrorHandlingStrategy(const DeclContext *FromDC)
153 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(Val: FromDC)) {}
154 ChildErrorHandlingStrategy(const Decl *FromD)
155 : FromDC(dyn_cast<DeclContext>(Val: FromD)),
156 IgnoreChildErrors(!isa<TagDecl>(Val: FromD)) {}
157
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(E1: std::move(ResultErr), E2: std::move(ChildErr));
165 else
166 consumeError(Err: std::move(ChildErr));
167 }
168
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(D: FromChildD);
175 }
176 };
177
178 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
179 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
180 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
181 ASTImporter &Importer;
182
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);
187 }
188
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();
196 }
197
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);
208 }
209
210 template <typename T>
211 auto import(const T *From) {
212 return import(const_cast<T *>(From));
213 }
214
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);
219 }
220
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);
227 }
228
229 ExplicitSpecifier importExplicitSpecifier(Error &Err,
230 ExplicitSpecifier ESpec);
231
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)...);
236 }
237 };
238
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)...);
254 }
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)...);
267 }
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.
278 }
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.
288 }
289
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();
296 }
297
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;
306 }
307
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(D: ToD);
316 return;
317 }
318
319 DeclContext *FromDC = FromD->getDeclContext();
320 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
321 DeclContext *ToDC = ToD->getDeclContext();
322 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
323
324 bool Visible = false;
325 if (FromDC->containsDeclAndLoad(D: FromD)) {
326 ToDC->addDeclInternal(D: ToD);
327 Visible = true;
328 }
329 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(D: FromD)) {
330 ToLexicalDC->addDeclInternal(D: ToD);
331 Visible = true;
332 }
333
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(Name: FromNamed->getDeclName());
341 if (llvm::is_contained(FromLookup, FromNamed))
342 ToDC->makeDeclVisibleInContext(D: ToNamed);
343 }
344 }
345 }
346
347 void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
348 DeclContext *OldDC) {
349 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
350 if (!LT)
351 return;
352
353 for (NamedDecl *TP : Params)
354 LT->update(ND: TP, OldDC);
355 }
356
357 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
358 updateLookupTableForTemplateParameters(
359 Params, Importer.getToContext().getTranslationUnitDecl());
360 }
361
362 public:
363 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
364
365 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
366 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
367 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
368
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"
374
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);
388
389 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
390 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
391 Expected<APValue> ImportAPValue(const APValue &FromValue);
392
393 using Designator = DesignatedInitExpr::Designator;
394
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
406 };
407
408 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
409 return IDK == IDK_Everything ||
410 (IDK == IDK_Default && !Importer.isMinimalImport());
411 }
412
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);
430
431 template <typename InContainerTy>
432 Error ImportTemplateArgumentListInfo(
433 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
434
435 template<typename InContainerTy>
436 Error ImportTemplateArgumentListInfo(
437 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
438 const InContainerTy &Container, TemplateArgumentListInfo &Result);
439
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);
448
449 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
450
451 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
452
453 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
454 ParmVarDecl *ToParam);
455
456 Expected<InheritedConstructor>
457 ImportInheritedConstructor(const InheritedConstructor &From);
458
459 template <typename T>
460 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
461
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);
510
511 Expected<ObjCTypeParamList *>
512 ImportObjCTypeParamList(ObjCTypeParamList *list);
513
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);
528
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);
566
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);
644
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{};
657 }
658 return *MaybeVal;
659 }
660
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;
669 }
670 return Error::success();
671 }
672
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());
682 }
683
684 template<typename InContainerTy, typename OIter>
685 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
686 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
687 }
688
689 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
690 CXXMethodDecl *FromMethod);
691
692 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
693 FunctionDecl *FromFD);
694
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 hasReturnTypeDeclaredInside(FunctionDecl *D);
699 };
700
701template <typename InContainerTy>
702Error 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();
711
712 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
713 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
714 return Err;
715 Result = ToTAInfo;
716 return Error::success();
717}
718
719template <>
720Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
721 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
722 return ImportTemplateArgumentListInfo(
723 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
724}
725
726template <>
727Error ASTNodeImporter::ImportTemplateArgumentListInfo<
728 ASTTemplateArgumentListInfo>(
729 const ASTTemplateArgumentListInfo &From,
730 TemplateArgumentListInfo &Result) {
731 return ImportTemplateArgumentListInfo(
732 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
733}
734
735Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
736ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
737 FunctionDecl *FromFD) {
738 assert(FromFD->getTemplatedKind() ==
739 FunctionDecl::TK_FunctionTemplateSpecialization);
740
741 FunctionTemplateAndArgsTy Result;
742
743 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
744 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
745 return std::move(Err);
746
747 // Import template arguments.
748 if (Error Err = ImportTemplateArguments(FromArgs: FTSInfo->TemplateArguments->asArray(),
749 ToArgs&: std::get<1>(Result)))
750 return std::move(Err);
751
752 return Result;
753}
754
755template <>
756Expected<TemplateParameterList *>
757ASTNodeImporter::import(TemplateParameterList *From) {
758 SmallVector<NamedDecl *, 4> To(From->size());
759 if (Error Err = ImportContainerChecked(*From, To))
760 return std::move(Err);
761
762 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
763 if (!ToRequiresClause)
764 return ToRequiresClause.takeError();
765
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();
775
776 return TemplateParameterList::Create(
777 C: Importer.getToContext(),
778 TemplateLoc: *ToTemplateLocOrErr,
779 LAngleLoc: *ToLAngleLocOrErr,
780 Params: To,
781 RAngleLoc: *ToRAngleLocOrErr,
782 RequiresClause: *ToRequiresClause);
783}
784
785template <>
786Expected<TemplateArgument>
787ASTNodeImporter::import(const TemplateArgument &From) {
788 switch (From.getKind()) {
789 case TemplateArgument::Null:
790 return TemplateArgument();
791
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());
798 }
799
800 case TemplateArgument::Integral: {
801 ExpectedType ToTypeOrErr = import(From.getIntegralType());
802 if (!ToTypeOrErr)
803 return ToTypeOrErr.takeError();
804 return TemplateArgument(From, *ToTypeOrErr);
805 }
806
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());
816 }
817
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());
824 }
825
826 case TemplateArgument::StructuralValue: {
827 ExpectedType ToTypeOrErr = import(From.getStructuralValueType());
828 if (!ToTypeOrErr)
829 return ToTypeOrErr.takeError();
830 Expected<APValue> ToValueOrErr = import(From.getAsStructuralValue());
831 if (!ToValueOrErr)
832 return ToValueOrErr.takeError();
833 return TemplateArgument(Importer.getToContext(), *ToTypeOrErr,
834 *ToValueOrErr);
835 }
836
837 case TemplateArgument::Template: {
838 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
839 if (!ToTemplateOrErr)
840 return ToTemplateOrErr.takeError();
841
842 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted());
843 }
844
845 case TemplateArgument::TemplateExpansion: {
846 Expected<TemplateName> ToTemplateOrErr =
847 import(From.getAsTemplateOrTemplatePattern());
848 if (!ToTemplateOrErr)
849 return ToTemplateOrErr.takeError();
850
851 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(),
852 From.getIsDefaulted());
853 }
854
855 case TemplateArgument::Expression:
856 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
857 return TemplateArgument(*ToExpr, From.getIsDefaulted());
858 else
859 return ToExpr.takeError();
860
861 case TemplateArgument::Pack: {
862 SmallVector<TemplateArgument, 2> ToPack;
863 ToPack.reserve(From.pack_size());
864 if (Error Err = ImportTemplateArguments(FromArgs: From.pack_elements(), ToArgs&: ToPack))
865 return std::move(Err);
866
867 return TemplateArgument(
868 llvm::ArrayRef(ToPack).copy(Importer.getToContext()));
869 }
870 }
871
872 llvm_unreachable("Invalid template argument kind");
873}
874
875template <>
876Expected<TemplateArgumentLoc>
877ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
878 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
879 if (!ArgOrErr)
880 return ArgOrErr.takeError();
881 TemplateArgument Arg = *ArgOrErr;
882
883 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
884
885 TemplateArgumentLocInfo ToInfo;
886 if (Arg.getKind() == TemplateArgument::Expression) {
887 ExpectedExpr E = import(FromInfo.getAsExpr());
888 if (!E)
889 return E.takeError();
890 ToInfo = TemplateArgumentLocInfo(*E);
891 } else if (Arg.getKind() == TemplateArgument::Type) {
892 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
893 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
894 else
895 return TSIOrErr.takeError();
896 } else {
897 auto ToTemplateQualifierLocOrErr =
898 import(FromInfo.getTemplateQualifierLoc());
899 if (!ToTemplateQualifierLocOrErr)
900 return ToTemplateQualifierLocOrErr.takeError();
901 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
902 if (!ToTemplateNameLocOrErr)
903 return ToTemplateNameLocOrErr.takeError();
904 auto ToTemplateEllipsisLocOrErr =
905 import(FromInfo.getTemplateEllipsisLoc());
906 if (!ToTemplateEllipsisLocOrErr)
907 return ToTemplateEllipsisLocOrErr.takeError();
908 ToInfo = TemplateArgumentLocInfo(
909 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
910 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
911 }
912
913 return TemplateArgumentLoc(Arg, ToInfo);
914}
915
916template <>
917Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
918 if (DG.isNull())
919 return DeclGroupRef::Create(C&: Importer.getToContext(), Decls: nullptr, NumDecls: 0);
920 size_t NumDecls = DG.end() - DG.begin();
921 SmallVector<Decl *, 1> ToDecls;
922 ToDecls.reserve(NumDecls);
923 for (Decl *FromD : DG) {
924 if (auto ToDOrErr = import(FromD))
925 ToDecls.push_back(*ToDOrErr);
926 else
927 return ToDOrErr.takeError();
928 }
929 return DeclGroupRef::Create(C&: Importer.getToContext(),
930 Decls: ToDecls.begin(),
931 NumDecls);
932}
933
934template <>
935Expected<ASTNodeImporter::Designator>
936ASTNodeImporter::import(const Designator &D) {
937 if (D.isFieldDesignator()) {
938 IdentifierInfo *ToFieldName = Importer.Import(FromId: D.getFieldName());
939
940 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
941 if (!ToDotLocOrErr)
942 return ToDotLocOrErr.takeError();
943
944 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
945 if (!ToFieldLocOrErr)
946 return ToFieldLocOrErr.takeError();
947
948 return DesignatedInitExpr::Designator::CreateFieldDesignator(
949 FieldName: ToFieldName, DotLoc: *ToDotLocOrErr, FieldLoc: *ToFieldLocOrErr);
950 }
951
952 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
953 if (!ToLBracketLocOrErr)
954 return ToLBracketLocOrErr.takeError();
955
956 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
957 if (!ToRBracketLocOrErr)
958 return ToRBracketLocOrErr.takeError();
959
960 if (D.isArrayDesignator())
961 return Designator::CreateArrayDesignator(Index: D.getArrayIndex(),
962 LBracketLoc: *ToLBracketLocOrErr,
963 RBracketLoc: *ToRBracketLocOrErr);
964
965 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
966 if (!ToEllipsisLocOrErr)
967 return ToEllipsisLocOrErr.takeError();
968
969 assert(D.isArrayRangeDesignator());
970 return Designator::CreateArrayRangeDesignator(
971 Index: D.getArrayIndex(), LBracketLoc: *ToLBracketLocOrErr, EllipsisLoc: *ToEllipsisLocOrErr,
972 RBracketLoc: *ToRBracketLocOrErr);
973}
974
975template <>
976Expected<ConceptReference *> ASTNodeImporter::import(ConceptReference *From) {
977 Error Err = Error::success();
978 auto ToNNS = importChecked(Err, From->getNestedNameSpecifierLoc());
979 auto ToTemplateKWLoc = importChecked(Err, From->getTemplateKWLoc());
980 auto ToConceptNameLoc =
981 importChecked(Err, From->getConceptNameInfo().getLoc());
982 auto ToConceptName = importChecked(Err, From->getConceptNameInfo().getName());
983 auto ToFoundDecl = importChecked(Err, From->getFoundDecl());
984 auto ToNamedConcept = importChecked(Err, From->getNamedConcept());
985 if (Err)
986 return std::move(Err);
987 TemplateArgumentListInfo ToTAInfo;
988 const auto *ASTTemplateArgs = From->getTemplateArgsAsWritten();
989 if (ASTTemplateArgs)
990 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo))
991 return std::move(Err);
992 auto *ConceptRef = ConceptReference::Create(
993 C: Importer.getToContext(), NNS: ToNNS, TemplateKWLoc: ToTemplateKWLoc,
994 ConceptNameInfo: DeclarationNameInfo(ToConceptName, ToConceptNameLoc), FoundDecl: ToFoundDecl,
995 NamedConcept: ToNamedConcept,
996 ArgsAsWritten: ASTTemplateArgs ? ASTTemplateArgumentListInfo::Create(
997 C: Importer.getToContext(), List: ToTAInfo)
998 : nullptr);
999 return ConceptRef;
1000}
1001
1002template <>
1003Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
1004 ValueDecl *Var = nullptr;
1005 if (From.capturesVariable()) {
1006 if (auto VarOrErr = import(From.getCapturedVar()))
1007 Var = *VarOrErr;
1008 else
1009 return VarOrErr.takeError();
1010 }
1011
1012 auto LocationOrErr = import(From.getLocation());
1013 if (!LocationOrErr)
1014 return LocationOrErr.takeError();
1015
1016 SourceLocation EllipsisLoc;
1017 if (From.isPackExpansion())
1018 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
1019 return std::move(Err);
1020
1021 return LambdaCapture(
1022 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1023 EllipsisLoc);
1024}
1025
1026template <typename T>
1027bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
1028 if (Found->getLinkageInternal() != From->getLinkageInternal())
1029 return false;
1030
1031 if (From->hasExternalFormalLinkage())
1032 return Found->hasExternalFormalLinkage();
1033 if (Importer.GetFromTU(ToD: Found) != From->getTranslationUnitDecl())
1034 return false;
1035 if (From->isInAnonymousNamespace())
1036 return Found->isInAnonymousNamespace();
1037 else
1038 return !Found->isInAnonymousNamespace() &&
1039 !Found->hasExternalFormalLinkage();
1040}
1041
1042template <>
1043bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
1044 TypedefNameDecl *From) {
1045 if (Found->getLinkageInternal() != From->getLinkageInternal())
1046 return false;
1047
1048 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1049 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1050 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1051}
1052
1053} // namespace clang
1054
1055//----------------------------------------------------------------------------
1056// Import Types
1057//----------------------------------------------------------------------------
1058
1059using namespace clang;
1060
1061ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1062 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1063 << T->getTypeClassName();
1064 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
1065}
1066
1067ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1068 ExpectedType UnderlyingTypeOrErr = import(From: T->getValueType());
1069 if (!UnderlyingTypeOrErr)
1070 return UnderlyingTypeOrErr.takeError();
1071
1072 return Importer.getToContext().getAtomicType(T: *UnderlyingTypeOrErr);
1073}
1074
1075ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1076 switch (T->getKind()) {
1077#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1078 case BuiltinType::Id: \
1079 return Importer.getToContext().SingletonId;
1080#include "clang/Basic/OpenCLImageTypes.def"
1081#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1082 case BuiltinType::Id: \
1083 return Importer.getToContext().Id##Ty;
1084#include "clang/Basic/OpenCLExtensionTypes.def"
1085#define SVE_TYPE(Name, Id, SingletonId) \
1086 case BuiltinType::Id: \
1087 return Importer.getToContext().SingletonId;
1088#include "clang/Basic/AArch64SVEACLETypes.def"
1089#define PPC_VECTOR_TYPE(Name, Id, Size) \
1090 case BuiltinType::Id: \
1091 return Importer.getToContext().Id##Ty;
1092#include "clang/Basic/PPCTypes.def"
1093#define RVV_TYPE(Name, Id, SingletonId) \
1094 case BuiltinType::Id: \
1095 return Importer.getToContext().SingletonId;
1096#include "clang/Basic/RISCVVTypes.def"
1097#define WASM_TYPE(Name, Id, SingletonId) \
1098 case BuiltinType::Id: \
1099 return Importer.getToContext().SingletonId;
1100#include "clang/Basic/WebAssemblyReferenceTypes.def"
1101#define SHARED_SINGLETON_TYPE(Expansion)
1102#define BUILTIN_TYPE(Id, SingletonId) \
1103 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1104#include "clang/AST/BuiltinTypes.def"
1105
1106 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1107 // context supports C++.
1108
1109 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1110 // context supports ObjC.
1111
1112 case BuiltinType::Char_U:
1113 // The context we're importing from has an unsigned 'char'. If we're
1114 // importing into a context with a signed 'char', translate to
1115 // 'unsigned char' instead.
1116 if (Importer.getToContext().getLangOpts().CharIsSigned)
1117 return Importer.getToContext().UnsignedCharTy;
1118
1119 return Importer.getToContext().CharTy;
1120
1121 case BuiltinType::Char_S:
1122 // The context we're importing from has an unsigned 'char'. If we're
1123 // importing into a context with a signed 'char', translate to
1124 // 'unsigned char' instead.
1125 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1126 return Importer.getToContext().SignedCharTy;
1127
1128 return Importer.getToContext().CharTy;
1129
1130 case BuiltinType::WChar_S:
1131 case BuiltinType::WChar_U:
1132 // FIXME: If not in C++, shall we translate to the C equivalent of
1133 // wchar_t?
1134 return Importer.getToContext().WCharTy;
1135 }
1136
1137 llvm_unreachable("Invalid BuiltinType Kind!");
1138}
1139
1140ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1141 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1142 if (!ToOriginalTypeOrErr)
1143 return ToOriginalTypeOrErr.takeError();
1144
1145 return Importer.getToContext().getDecayedType(T: *ToOriginalTypeOrErr);
1146}
1147
1148ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1149 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1150 if (!ToElementTypeOrErr)
1151 return ToElementTypeOrErr.takeError();
1152
1153 return Importer.getToContext().getComplexType(T: *ToElementTypeOrErr);
1154}
1155
1156ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1157 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1158 if (!ToPointeeTypeOrErr)
1159 return ToPointeeTypeOrErr.takeError();
1160
1161 return Importer.getToContext().getPointerType(T: *ToPointeeTypeOrErr);
1162}
1163
1164ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1165 // FIXME: Check for blocks support in "to" context.
1166 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1167 if (!ToPointeeTypeOrErr)
1168 return ToPointeeTypeOrErr.takeError();
1169
1170 return Importer.getToContext().getBlockPointerType(T: *ToPointeeTypeOrErr);
1171}
1172
1173ExpectedType
1174ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1175 // FIXME: Check for C++ support in "to" context.
1176 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1177 if (!ToPointeeTypeOrErr)
1178 return ToPointeeTypeOrErr.takeError();
1179
1180 return Importer.getToContext().getLValueReferenceType(T: *ToPointeeTypeOrErr);
1181}
1182
1183ExpectedType
1184ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1185 // FIXME: Check for C++0x support in "to" context.
1186 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1187 if (!ToPointeeTypeOrErr)
1188 return ToPointeeTypeOrErr.takeError();
1189
1190 return Importer.getToContext().getRValueReferenceType(T: *ToPointeeTypeOrErr);
1191}
1192
1193ExpectedType
1194ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1195 // FIXME: Check for C++ support in "to" context.
1196 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1197 if (!ToPointeeTypeOrErr)
1198 return ToPointeeTypeOrErr.takeError();
1199
1200 ExpectedTypePtr ClassTypeOrErr = import(From: T->getClass());
1201 if (!ClassTypeOrErr)
1202 return ClassTypeOrErr.takeError();
1203
1204 return Importer.getToContext().getMemberPointerType(T: *ToPointeeTypeOrErr,
1205 Cls: *ClassTypeOrErr);
1206}
1207
1208ExpectedType
1209ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1210 Error Err = Error::success();
1211 auto ToElementType = importChecked(Err, T->getElementType());
1212 auto ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1213 if (Err)
1214 return std::move(Err);
1215
1216 return Importer.getToContext().getConstantArrayType(
1217 EltTy: ToElementType, ArySize: T->getSize(), SizeExpr: ToSizeExpr, ASM: T->getSizeModifier(),
1218 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1219}
1220
1221ExpectedType
1222ASTNodeImporter::VisitArrayParameterType(const ArrayParameterType *T) {
1223 ExpectedType ToArrayTypeOrErr = VisitConstantArrayType(T);
1224 if (!ToArrayTypeOrErr)
1225 return ToArrayTypeOrErr.takeError();
1226
1227 return Importer.getToContext().getArrayParameterType(Ty: *ToArrayTypeOrErr);
1228}
1229
1230ExpectedType
1231ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1232 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1233 if (!ToElementTypeOrErr)
1234 return ToElementTypeOrErr.takeError();
1235
1236 return Importer.getToContext().getIncompleteArrayType(EltTy: *ToElementTypeOrErr,
1237 ASM: T->getSizeModifier(),
1238 IndexTypeQuals: T->getIndexTypeCVRQualifiers());
1239}
1240
1241ExpectedType
1242ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1243 Error Err = Error::success();
1244 QualType ToElementType = importChecked(Err, T->getElementType());
1245 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1246 SourceRange ToBracketsRange = importChecked(Err, From: T->getBracketsRange());
1247 if (Err)
1248 return std::move(Err);
1249 return Importer.getToContext().getVariableArrayType(
1250 EltTy: ToElementType, NumElts: ToSizeExpr, ASM: T->getSizeModifier(),
1251 IndexTypeQuals: T->getIndexTypeCVRQualifiers(), Brackets: ToBracketsRange);
1252}
1253
1254ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1255 const DependentSizedArrayType *T) {
1256 Error Err = Error::success();
1257 QualType ToElementType = importChecked(Err, T->getElementType());
1258 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1259 SourceRange ToBracketsRange = importChecked(Err, From: T->getBracketsRange());
1260 if (Err)
1261 return std::move(Err);
1262 // SizeExpr may be null if size is not specified directly.
1263 // For example, 'int a[]'.
1264
1265 return Importer.getToContext().getDependentSizedArrayType(
1266 EltTy: ToElementType, NumElts: ToSizeExpr, ASM: T->getSizeModifier(),
1267 IndexTypeQuals: T->getIndexTypeCVRQualifiers(), Brackets: ToBracketsRange);
1268}
1269
1270ExpectedType ASTNodeImporter::VisitDependentSizedExtVectorType(
1271 const DependentSizedExtVectorType *T) {
1272 Error Err = Error::success();
1273 QualType ToElementType = importChecked(Err, From: T->getElementType());
1274 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1275 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1276 if (Err)
1277 return std::move(Err);
1278 return Importer.getToContext().getDependentSizedExtVectorType(
1279 VectorType: ToElementType, SizeExpr: ToSizeExpr, AttrLoc: ToAttrLoc);
1280}
1281
1282ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1283 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1284 if (!ToElementTypeOrErr)
1285 return ToElementTypeOrErr.takeError();
1286
1287 return Importer.getToContext().getVectorType(VectorType: *ToElementTypeOrErr,
1288 NumElts: T->getNumElements(),
1289 VecKind: T->getVectorKind());
1290}
1291
1292ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1293 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1294 if (!ToElementTypeOrErr)
1295 return ToElementTypeOrErr.takeError();
1296
1297 return Importer.getToContext().getExtVectorType(VectorType: *ToElementTypeOrErr,
1298 NumElts: T->getNumElements());
1299}
1300
1301ExpectedType
1302ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1303 // FIXME: What happens if we're importing a function without a prototype
1304 // into C++? Should we make it variadic?
1305 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1306 if (!ToReturnTypeOrErr)
1307 return ToReturnTypeOrErr.takeError();
1308
1309 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1310 T->getExtInfo());
1311}
1312
1313ExpectedType
1314ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1315 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1316 if (!ToReturnTypeOrErr)
1317 return ToReturnTypeOrErr.takeError();
1318
1319 // Import argument types
1320 SmallVector<QualType, 4> ArgTypes;
1321 for (const auto &A : T->param_types()) {
1322 ExpectedType TyOrErr = import(From: A);
1323 if (!TyOrErr)
1324 return TyOrErr.takeError();
1325 ArgTypes.push_back(Elt: *TyOrErr);
1326 }
1327
1328 // Import exception types
1329 SmallVector<QualType, 4> ExceptionTypes;
1330 for (const auto &E : T->exceptions()) {
1331 ExpectedType TyOrErr = import(From: E);
1332 if (!TyOrErr)
1333 return TyOrErr.takeError();
1334 ExceptionTypes.push_back(Elt: *TyOrErr);
1335 }
1336
1337 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1338 Error Err = Error::success();
1339 FunctionProtoType::ExtProtoInfo ToEPI;
1340 ToEPI.ExtInfo = FromEPI.ExtInfo;
1341 ToEPI.Variadic = FromEPI.Variadic;
1342 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1343 ToEPI.TypeQuals = FromEPI.TypeQuals;
1344 ToEPI.RefQualifier = FromEPI.RefQualifier;
1345 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1346 ToEPI.ExceptionSpec.NoexceptExpr =
1347 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
1348 ToEPI.ExceptionSpec.SourceDecl =
1349 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1350 ToEPI.ExceptionSpec.SourceTemplate =
1351 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
1352 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1353
1354 if (Err)
1355 return std::move(Err);
1356
1357 return Importer.getToContext().getFunctionType(
1358 ResultTy: *ToReturnTypeOrErr, Args: ArgTypes, EPI: ToEPI);
1359}
1360
1361ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1362 const UnresolvedUsingType *T) {
1363 Error Err = Error::success();
1364 auto ToD = importChecked(Err, From: T->getDecl());
1365 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1366 if (Err)
1367 return std::move(Err);
1368
1369 return Importer.getToContext().getTypeDeclType(
1370 Decl: ToD, PrevDecl: cast_or_null<TypeDecl>(ToPrevD));
1371}
1372
1373ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1374 ExpectedType ToInnerTypeOrErr = import(From: T->getInnerType());
1375 if (!ToInnerTypeOrErr)
1376 return ToInnerTypeOrErr.takeError();
1377
1378 return Importer.getToContext().getParenType(NamedType: *ToInnerTypeOrErr);
1379}
1380
1381ExpectedType
1382ASTNodeImporter::VisitPackIndexingType(clang::PackIndexingType const *T) {
1383
1384 ExpectedType Pattern = import(From: T->getPattern());
1385 if (!Pattern)
1386 return Pattern.takeError();
1387 ExpectedExpr Index = import(From: T->getIndexExpr());
1388 if (!Index)
1389 return Index.takeError();
1390 return Importer.getToContext().getPackIndexingType(Pattern: *Pattern, IndexExpr: *Index);
1391}
1392
1393ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1394 Expected<TypedefNameDecl *> ToDeclOrErr = import(From: T->getDecl());
1395 if (!ToDeclOrErr)
1396 return ToDeclOrErr.takeError();
1397
1398 TypedefNameDecl *ToDecl = *ToDeclOrErr;
1399 if (ToDecl->getTypeForDecl())
1400 return QualType(ToDecl->getTypeForDecl(), 0);
1401
1402 ExpectedType ToUnderlyingTypeOrErr = import(From: T->desugar());
1403 if (!ToUnderlyingTypeOrErr)
1404 return ToUnderlyingTypeOrErr.takeError();
1405
1406 return Importer.getToContext().getTypedefType(Decl: ToDecl, Underlying: *ToUnderlyingTypeOrErr);
1407}
1408
1409ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1410 ExpectedExpr ToExprOrErr = import(From: T->getUnderlyingExpr());
1411 if (!ToExprOrErr)
1412 return ToExprOrErr.takeError();
1413 return Importer.getToContext().getTypeOfExprType(E: *ToExprOrErr, Kind: T->getKind());
1414}
1415
1416ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1417 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnmodifiedType());
1418 if (!ToUnderlyingTypeOrErr)
1419 return ToUnderlyingTypeOrErr.takeError();
1420 return Importer.getToContext().getTypeOfType(QT: *ToUnderlyingTypeOrErr,
1421 Kind: T->getKind());
1422}
1423
1424ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
1425 Expected<UsingShadowDecl *> FoundOrErr = import(From: T->getFoundDecl());
1426 if (!FoundOrErr)
1427 return FoundOrErr.takeError();
1428 Expected<QualType> UnderlyingOrErr = import(From: T->getUnderlyingType());
1429 if (!UnderlyingOrErr)
1430 return UnderlyingOrErr.takeError();
1431
1432 return Importer.getToContext().getUsingType(Found: *FoundOrErr, Underlying: *UnderlyingOrErr);
1433}
1434
1435ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1436 // FIXME: Make sure that the "to" context supports C++0x!
1437 ExpectedExpr ToExprOrErr = import(From: T->getUnderlyingExpr());
1438 if (!ToExprOrErr)
1439 return ToExprOrErr.takeError();
1440
1441 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1442 if (!ToUnderlyingTypeOrErr)
1443 return ToUnderlyingTypeOrErr.takeError();
1444
1445 return Importer.getToContext().getDecltypeType(
1446 e: *ToExprOrErr, UnderlyingType: *ToUnderlyingTypeOrErr);
1447}
1448
1449ExpectedType
1450ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1451 ExpectedType ToBaseTypeOrErr = import(From: T->getBaseType());
1452 if (!ToBaseTypeOrErr)
1453 return ToBaseTypeOrErr.takeError();
1454
1455 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1456 if (!ToUnderlyingTypeOrErr)
1457 return ToUnderlyingTypeOrErr.takeError();
1458
1459 return Importer.getToContext().getUnaryTransformType(
1460 BaseType: *ToBaseTypeOrErr, UnderlyingType: *ToUnderlyingTypeOrErr, UKind: T->getUTTKind());
1461}
1462
1463ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1464 // FIXME: Make sure that the "to" context supports C++11!
1465 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1466 if (!ToDeducedTypeOrErr)
1467 return ToDeducedTypeOrErr.takeError();
1468
1469 ExpectedDecl ToTypeConstraintConcept = import(From: T->getTypeConstraintConcept());
1470 if (!ToTypeConstraintConcept)
1471 return ToTypeConstraintConcept.takeError();
1472
1473 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1474 if (Error Err = ImportTemplateArguments(FromArgs: T->getTypeConstraintArguments(),
1475 ToArgs&: ToTemplateArgs))
1476 return std::move(Err);
1477
1478 return Importer.getToContext().getAutoType(
1479 DeducedType: *ToDeducedTypeOrErr, Keyword: T->getKeyword(), /*IsDependent*/false,
1480 /*IsPack=*/false, TypeConstraintConcept: cast_or_null<ConceptDecl>(Val: *ToTypeConstraintConcept),
1481 TypeConstraintArgs: ToTemplateArgs);
1482}
1483
1484ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1485 const DeducedTemplateSpecializationType *T) {
1486 // FIXME: Make sure that the "to" context supports C++17!
1487 Expected<TemplateName> ToTemplateNameOrErr = import(From: T->getTemplateName());
1488 if (!ToTemplateNameOrErr)
1489 return ToTemplateNameOrErr.takeError();
1490 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1491 if (!ToDeducedTypeOrErr)
1492 return ToDeducedTypeOrErr.takeError();
1493
1494 return Importer.getToContext().getDeducedTemplateSpecializationType(
1495 Template: *ToTemplateNameOrErr, DeducedType: *ToDeducedTypeOrErr, IsDependent: T->isDependentType());
1496}
1497
1498ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1499 const InjectedClassNameType *T) {
1500 Expected<CXXRecordDecl *> ToDeclOrErr = import(From: T->getDecl());
1501 if (!ToDeclOrErr)
1502 return ToDeclOrErr.takeError();
1503
1504 // The InjectedClassNameType is created in VisitRecordDecl when the
1505 // T->getDecl() is imported. Here we can return the existing type.
1506 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl();
1507 assert(Ty && isa<InjectedClassNameType>(Ty));
1508 return QualType(Ty, 0);
1509}
1510
1511ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1512 Expected<RecordDecl *> ToDeclOrErr = import(From: T->getDecl());
1513 if (!ToDeclOrErr)
1514 return ToDeclOrErr.takeError();
1515
1516 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1517}
1518
1519ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1520 Expected<EnumDecl *> ToDeclOrErr = import(From: T->getDecl());
1521 if (!ToDeclOrErr)
1522 return ToDeclOrErr.takeError();
1523
1524 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1525}
1526
1527ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1528 ExpectedType ToModifiedTypeOrErr = import(From: T->getModifiedType());
1529 if (!ToModifiedTypeOrErr)
1530 return ToModifiedTypeOrErr.takeError();
1531 ExpectedType ToEquivalentTypeOrErr = import(From: T->getEquivalentType());
1532 if (!ToEquivalentTypeOrErr)
1533 return ToEquivalentTypeOrErr.takeError();
1534
1535 return Importer.getToContext().getAttributedType(attrKind: T->getAttrKind(),
1536 modifiedType: *ToModifiedTypeOrErr, equivalentType: *ToEquivalentTypeOrErr);
1537}
1538
1539ExpectedType
1540ASTNodeImporter::VisitCountAttributedType(const CountAttributedType *T) {
1541 ExpectedType ToWrappedTypeOrErr = import(T->desugar());
1542 if (!ToWrappedTypeOrErr)
1543 return ToWrappedTypeOrErr.takeError();
1544
1545 Error Err = Error::success();
1546 Expr *CountExpr = importChecked(Err, From: T->getCountExpr());
1547
1548 SmallVector<TypeCoupledDeclRefInfo, 1> CoupledDecls;
1549 for (auto TI : T->dependent_decls()) {
1550 Expected<ValueDecl *> ToDeclOrErr = import(TI.getDecl());
1551 if (!ToDeclOrErr)
1552 return ToDeclOrErr.takeError();
1553 CoupledDecls.emplace_back(*ToDeclOrErr, TI.isDeref());
1554 }
1555
1556 return Importer.getToContext().getCountAttributedType(
1557 T: *ToWrappedTypeOrErr, CountExpr, CountInBytes: T->isCountInBytes(), OrNull: T->isOrNull(),
1558 DependentDecls: ArrayRef(CoupledDecls.data(), CoupledDecls.size()));
1559}
1560
1561ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1562 const TemplateTypeParmType *T) {
1563 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(From: T->getDecl());
1564 if (!ToDeclOrErr)
1565 return ToDeclOrErr.takeError();
1566
1567 return Importer.getToContext().getTemplateTypeParmType(
1568 Depth: T->getDepth(), Index: T->getIndex(), ParameterPack: T->isParameterPack(), ParmDecl: *ToDeclOrErr);
1569}
1570
1571ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1572 const SubstTemplateTypeParmType *T) {
1573 Expected<Decl *> ReplacedOrErr = import(From: T->getAssociatedDecl());
1574 if (!ReplacedOrErr)
1575 return ReplacedOrErr.takeError();
1576
1577 ExpectedType ToReplacementTypeOrErr = import(From: T->getReplacementType());
1578 if (!ToReplacementTypeOrErr)
1579 return ToReplacementTypeOrErr.takeError();
1580
1581 return Importer.getToContext().getSubstTemplateTypeParmType(
1582 Replacement: *ToReplacementTypeOrErr, AssociatedDecl: *ReplacedOrErr, Index: T->getIndex(),
1583 PackIndex: T->getPackIndex());
1584}
1585
1586ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
1587 const SubstTemplateTypeParmPackType *T) {
1588 Expected<Decl *> ReplacedOrErr = import(From: T->getAssociatedDecl());
1589 if (!ReplacedOrErr)
1590 return ReplacedOrErr.takeError();
1591
1592 Expected<TemplateArgument> ToArgumentPack = import(From: T->getArgumentPack());
1593 if (!ToArgumentPack)
1594 return ToArgumentPack.takeError();
1595
1596 return Importer.getToContext().getSubstTemplateTypeParmPackType(
1597 AssociatedDecl: *ReplacedOrErr, Index: T->getIndex(), Final: T->getFinal(), ArgPack: *ToArgumentPack);
1598}
1599
1600ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1601 const TemplateSpecializationType *T) {
1602 auto ToTemplateOrErr = import(From: T->getTemplateName());
1603 if (!ToTemplateOrErr)
1604 return ToTemplateOrErr.takeError();
1605
1606 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1607 if (Error Err =
1608 ImportTemplateArguments(FromArgs: T->template_arguments(), ToArgs&: ToTemplateArgs))
1609 return std::move(Err);
1610
1611 QualType ToCanonType;
1612 if (!T->isCanonicalUnqualified()) {
1613 QualType FromCanonType
1614 = Importer.getFromContext().getCanonicalType(T: QualType(T, 0));
1615 if (ExpectedType TyOrErr = import(From: FromCanonType))
1616 ToCanonType = *TyOrErr;
1617 else
1618 return TyOrErr.takeError();
1619 }
1620 return Importer.getToContext().getTemplateSpecializationType(T: *ToTemplateOrErr,
1621 Args: ToTemplateArgs,
1622 Canon: ToCanonType);
1623}
1624
1625ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1626 // Note: the qualifier in an ElaboratedType is optional.
1627 auto ToQualifierOrErr = import(From: T->getQualifier());
1628 if (!ToQualifierOrErr)
1629 return ToQualifierOrErr.takeError();
1630
1631 ExpectedType ToNamedTypeOrErr = import(From: T->getNamedType());
1632 if (!ToNamedTypeOrErr)
1633 return ToNamedTypeOrErr.takeError();
1634
1635 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(From: T->getOwnedTagDecl());
1636 if (!ToOwnedTagDeclOrErr)
1637 return ToOwnedTagDeclOrErr.takeError();
1638
1639 return Importer.getToContext().getElaboratedType(Keyword: T->getKeyword(),
1640 NNS: *ToQualifierOrErr,
1641 NamedType: *ToNamedTypeOrErr,
1642 OwnedTagDecl: *ToOwnedTagDeclOrErr);
1643}
1644
1645ExpectedType
1646ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1647 ExpectedType ToPatternOrErr = import(From: T->getPattern());
1648 if (!ToPatternOrErr)
1649 return ToPatternOrErr.takeError();
1650
1651 return Importer.getToContext().getPackExpansionType(Pattern: *ToPatternOrErr,
1652 NumExpansions: T->getNumExpansions(),
1653 /*ExpactPack=*/ExpectPackInType: false);
1654}
1655
1656ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1657 const DependentTemplateSpecializationType *T) {
1658 auto ToQualifierOrErr = import(From: T->getQualifier());
1659 if (!ToQualifierOrErr)
1660 return ToQualifierOrErr.takeError();
1661
1662 IdentifierInfo *ToName = Importer.Import(FromId: T->getIdentifier());
1663
1664 SmallVector<TemplateArgument, 2> ToPack;
1665 ToPack.reserve(N: T->template_arguments().size());
1666 if (Error Err = ImportTemplateArguments(FromArgs: T->template_arguments(), ToArgs&: ToPack))
1667 return std::move(Err);
1668
1669 return Importer.getToContext().getDependentTemplateSpecializationType(
1670 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1671}
1672
1673ExpectedType
1674ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1675 auto ToQualifierOrErr = import(From: T->getQualifier());
1676 if (!ToQualifierOrErr)
1677 return ToQualifierOrErr.takeError();
1678
1679 IdentifierInfo *Name = Importer.Import(FromId: T->getIdentifier());
1680
1681 QualType Canon;
1682 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1683 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1684 Canon = (*TyOrErr).getCanonicalType();
1685 else
1686 return TyOrErr.takeError();
1687 }
1688
1689 return Importer.getToContext().getDependentNameType(Keyword: T->getKeyword(),
1690 NNS: *ToQualifierOrErr,
1691 Name, Canon);
1692}
1693
1694ExpectedType
1695ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1696 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(From: T->getDecl());
1697 if (!ToDeclOrErr)
1698 return ToDeclOrErr.takeError();
1699
1700 return Importer.getToContext().getObjCInterfaceType(Decl: *ToDeclOrErr);
1701}
1702
1703ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1704 ExpectedType ToBaseTypeOrErr = import(From: T->getBaseType());
1705 if (!ToBaseTypeOrErr)
1706 return ToBaseTypeOrErr.takeError();
1707
1708 SmallVector<QualType, 4> TypeArgs;
1709 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1710 if (ExpectedType TyOrErr = import(From: TypeArg))
1711 TypeArgs.push_back(Elt: *TyOrErr);
1712 else
1713 return TyOrErr.takeError();
1714 }
1715
1716 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1717 for (auto *P : T->quals()) {
1718 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1719 Protocols.push_back(*ProtocolOrErr);
1720 else
1721 return ProtocolOrErr.takeError();
1722
1723 }
1724
1725 return Importer.getToContext().getObjCObjectType(Base: *ToBaseTypeOrErr, typeArgs: TypeArgs,
1726 protocols: Protocols,
1727 isKindOf: T->isKindOfTypeAsWritten());
1728}
1729
1730ExpectedType
1731ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1732 ExpectedType ToPointeeTypeOrErr = import(From: T->getPointeeType());
1733 if (!ToPointeeTypeOrErr)
1734 return ToPointeeTypeOrErr.takeError();
1735
1736 return Importer.getToContext().getObjCObjectPointerType(OIT: *ToPointeeTypeOrErr);
1737}
1738
1739ExpectedType
1740ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
1741 ExpectedType ToUnderlyingTypeOrErr = import(From: T->getUnderlyingType());
1742 if (!ToUnderlyingTypeOrErr)
1743 return ToUnderlyingTypeOrErr.takeError();
1744
1745 IdentifierInfo *ToIdentifier = Importer.Import(FromId: T->getMacroIdentifier());
1746 return Importer.getToContext().getMacroQualifiedType(UnderlyingTy: *ToUnderlyingTypeOrErr,
1747 MacroII: ToIdentifier);
1748}
1749
1750ExpectedType clang::ASTNodeImporter::VisitAdjustedType(const AdjustedType *T) {
1751 Error Err = Error::success();
1752 QualType ToOriginalType = importChecked(Err, From: T->getOriginalType());
1753 QualType ToAdjustedType = importChecked(Err, From: T->getAdjustedType());
1754 if (Err)
1755 return std::move(Err);
1756
1757 return Importer.getToContext().getAdjustedType(Orig: ToOriginalType,
1758 New: ToAdjustedType);
1759}
1760
1761ExpectedType clang::ASTNodeImporter::VisitBitIntType(const BitIntType *T) {
1762 return Importer.getToContext().getBitIntType(Unsigned: T->isUnsigned(),
1763 NumBits: T->getNumBits());
1764}
1765
1766ExpectedType clang::ASTNodeImporter::VisitBTFTagAttributedType(
1767 const clang::BTFTagAttributedType *T) {
1768 Error Err = Error::success();
1769 const BTFTypeTagAttr *ToBTFAttr = importChecked(Err, From: T->getAttr());
1770 QualType ToWrappedType = importChecked(Err, From: T->getWrappedType());
1771 if (Err)
1772 return std::move(Err);
1773
1774 return Importer.getToContext().getBTFTagAttributedType(BTFAttr: ToBTFAttr,
1775 Wrapped: ToWrappedType);
1776}
1777
1778ExpectedType clang::ASTNodeImporter::VisitConstantMatrixType(
1779 const clang::ConstantMatrixType *T) {
1780 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1781 if (!ToElementTypeOrErr)
1782 return ToElementTypeOrErr.takeError();
1783
1784 return Importer.getToContext().getConstantMatrixType(
1785 ElementType: *ToElementTypeOrErr, NumRows: T->getNumRows(), NumColumns: T->getNumColumns());
1786}
1787
1788ExpectedType clang::ASTNodeImporter::VisitDependentAddressSpaceType(
1789 const clang::DependentAddressSpaceType *T) {
1790 Error Err = Error::success();
1791 QualType ToPointeeType = importChecked(Err, From: T->getPointeeType());
1792 Expr *ToAddrSpaceExpr = importChecked(Err, From: T->getAddrSpaceExpr());
1793 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1794 if (Err)
1795 return std::move(Err);
1796
1797 return Importer.getToContext().getDependentAddressSpaceType(
1798 PointeeType: ToPointeeType, AddrSpaceExpr: ToAddrSpaceExpr, AttrLoc: ToAttrLoc);
1799}
1800
1801ExpectedType clang::ASTNodeImporter::VisitDependentBitIntType(
1802 const clang::DependentBitIntType *T) {
1803 ExpectedExpr ToNumBitsExprOrErr = import(From: T->getNumBitsExpr());
1804 if (!ToNumBitsExprOrErr)
1805 return ToNumBitsExprOrErr.takeError();
1806 return Importer.getToContext().getDependentBitIntType(Unsigned: T->isUnsigned(),
1807 BitsExpr: *ToNumBitsExprOrErr);
1808}
1809
1810ExpectedType clang::ASTNodeImporter::VisitDependentSizedMatrixType(
1811 const clang::DependentSizedMatrixType *T) {
1812 Error Err = Error::success();
1813 QualType ToElementType = importChecked(Err, T->getElementType());
1814 Expr *ToRowExpr = importChecked(Err, From: T->getRowExpr());
1815 Expr *ToColumnExpr = importChecked(Err, From: T->getColumnExpr());
1816 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1817 if (Err)
1818 return std::move(Err);
1819
1820 return Importer.getToContext().getDependentSizedMatrixType(
1821 ElementType: ToElementType, RowExpr: ToRowExpr, ColumnExpr: ToColumnExpr, AttrLoc: ToAttrLoc);
1822}
1823
1824ExpectedType clang::ASTNodeImporter::VisitDependentVectorType(
1825 const clang::DependentVectorType *T) {
1826 Error Err = Error::success();
1827 QualType ToElementType = importChecked(Err, From: T->getElementType());
1828 Expr *ToSizeExpr = importChecked(Err, From: T->getSizeExpr());
1829 SourceLocation ToAttrLoc = importChecked(Err, From: T->getAttributeLoc());
1830 if (Err)
1831 return std::move(Err);
1832
1833 return Importer.getToContext().getDependentVectorType(
1834 VectorType: ToElementType, SizeExpr: ToSizeExpr, AttrLoc: ToAttrLoc, VecKind: T->getVectorKind());
1835}
1836
1837ExpectedType clang::ASTNodeImporter::VisitObjCTypeParamType(
1838 const clang::ObjCTypeParamType *T) {
1839 Expected<ObjCTypeParamDecl *> ToDeclOrErr = import(From: T->getDecl());
1840 if (!ToDeclOrErr)
1841 return ToDeclOrErr.takeError();
1842
1843 SmallVector<ObjCProtocolDecl *, 4> ToProtocols;
1844 for (ObjCProtocolDecl *FromProtocol : T->getProtocols()) {
1845 Expected<ObjCProtocolDecl *> ToProtocolOrErr = import(FromProtocol);
1846 if (!ToProtocolOrErr)
1847 return ToProtocolOrErr.takeError();
1848 ToProtocols.push_back(*ToProtocolOrErr);
1849 }
1850
1851 return Importer.getToContext().getObjCTypeParamType(Decl: *ToDeclOrErr,
1852 protocols: ToProtocols);
1853}
1854
1855ExpectedType clang::ASTNodeImporter::VisitPipeType(const clang::PipeType *T) {
1856 ExpectedType ToElementTypeOrErr = import(From: T->getElementType());
1857 if (!ToElementTypeOrErr)
1858 return ToElementTypeOrErr.takeError();
1859
1860 ASTContext &ToCtx = Importer.getToContext();
1861 if (T->isReadOnly())
1862 return ToCtx.getReadPipeType(T: *ToElementTypeOrErr);
1863 else
1864 return ToCtx.getWritePipeType(T: *ToElementTypeOrErr);
1865}
1866
1867//----------------------------------------------------------------------------
1868// Import Declarations
1869//----------------------------------------------------------------------------
1870Error ASTNodeImporter::ImportDeclParts(
1871 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1872 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1873 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1874 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1875 // FIXME: We could support these constructs by importing a different type of
1876 // this parameter and by importing the original type of the parameter only
1877 // after the FunctionDecl is created. See
1878 // VisitFunctionDecl::UsedDifferentProtoType.
1879 DeclContext *OrigDC = D->getDeclContext();
1880 FunctionDecl *FunDecl;
1881 if (isa<RecordDecl>(Val: D) && (FunDecl = dyn_cast<FunctionDecl>(Val: OrigDC)) &&
1882 FunDecl->hasBody()) {
1883 auto getLeafPointeeType = [](const Type *T) {
1884 while (T->isPointerType() || T->isArrayType()) {
1885 T = T->getPointeeOrArrayElementType();
1886 }
1887 return T;
1888 };
1889 for (const ParmVarDecl *P : FunDecl->parameters()) {
1890 const Type *LeafT =
1891 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1892 auto *RT = dyn_cast<RecordType>(Val: LeafT);
1893 if (RT && RT->getDecl() == D) {
1894 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1895 << D->getDeclKindName();
1896 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
1897 }
1898 }
1899 }
1900
1901 // Import the context of this declaration.
1902 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1903 return Err;
1904
1905 // Import the name of this declaration.
1906 if (Error Err = importInto(To&: Name, From: D->getDeclName()))
1907 return Err;
1908
1909 // Import the location of this declaration.
1910 if (Error Err = importInto(Loc, D->getLocation()))
1911 return Err;
1912
1913 ToD = cast_or_null<NamedDecl>(Val: Importer.GetAlreadyImportedOrNull(D));
1914 if (ToD)
1915 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1916 return Err;
1917
1918 return Error::success();
1919}
1920
1921Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1922 NamedDecl *&ToD, SourceLocation &Loc) {
1923
1924 // Import the name of this declaration.
1925 if (Error Err = importInto(To&: Name, From: D->getDeclName()))
1926 return Err;
1927
1928 // Import the location of this declaration.
1929 if (Error Err = importInto(Loc, D->getLocation()))
1930 return Err;
1931
1932 ToD = cast_or_null<NamedDecl>(Val: Importer.GetAlreadyImportedOrNull(D));
1933 if (ToD)
1934 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1935 return Err;
1936
1937 return Error::success();
1938}
1939
1940Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1941 if (!FromD)
1942 return Error::success();
1943
1944 if (!ToD)
1945 if (Error Err = importInto(To&: ToD, From: FromD))
1946 return Err;
1947
1948 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(Val: FromD)) {
1949 if (RecordDecl *ToRecord = cast<RecordDecl>(Val: ToD)) {
1950 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1951 !ToRecord->getDefinition()) {
1952 if (Error Err = ImportDefinition(From: FromRecord, To: ToRecord))
1953 return Err;
1954 }
1955 }
1956 return Error::success();
1957 }
1958
1959 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(Val: FromD)) {
1960 if (EnumDecl *ToEnum = cast<EnumDecl>(Val: ToD)) {
1961 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1962 if (Error Err = ImportDefinition(From: FromEnum, To: ToEnum))
1963 return Err;
1964 }
1965 }
1966 return Error::success();
1967 }
1968
1969 return Error::success();
1970}
1971
1972Error
1973ASTNodeImporter::ImportDeclarationNameLoc(
1974 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1975 // NOTE: To.Name and To.Loc are already imported.
1976 // We only have to import To.LocInfo.
1977 switch (To.getName().getNameKind()) {
1978 case DeclarationName::Identifier:
1979 case DeclarationName::ObjCZeroArgSelector:
1980 case DeclarationName::ObjCOneArgSelector:
1981 case DeclarationName::ObjCMultiArgSelector:
1982 case DeclarationName::CXXUsingDirective:
1983 case DeclarationName::CXXDeductionGuideName:
1984 return Error::success();
1985
1986 case DeclarationName::CXXOperatorName: {
1987 if (auto ToRangeOrErr = import(From: From.getCXXOperatorNameRange()))
1988 To.setCXXOperatorNameRange(*ToRangeOrErr);
1989 else
1990 return ToRangeOrErr.takeError();
1991 return Error::success();
1992 }
1993 case DeclarationName::CXXLiteralOperatorName: {
1994 if (ExpectedSLoc LocOrErr = import(From: From.getCXXLiteralOperatorNameLoc()))
1995 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1996 else
1997 return LocOrErr.takeError();
1998 return Error::success();
1999 }
2000 case DeclarationName::CXXConstructorName:
2001 case DeclarationName::CXXDestructorName:
2002 case DeclarationName::CXXConversionFunctionName: {
2003 if (auto ToTInfoOrErr = import(From: From.getNamedTypeInfo()))
2004 To.setNamedTypeInfo(*ToTInfoOrErr);
2005 else
2006 return ToTInfoOrErr.takeError();
2007 return Error::success();
2008 }
2009 }
2010 llvm_unreachable("Unknown name kind.");
2011}
2012
2013Error
2014ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
2015 if (Importer.isMinimalImport() && !ForceImport) {
2016 auto ToDCOrErr = Importer.ImportContext(FromDC);
2017 return ToDCOrErr.takeError();
2018 }
2019
2020 // We use strict error handling in case of records and enums, but not
2021 // with e.g. namespaces.
2022 //
2023 // FIXME Clients of the ASTImporter should be able to choose an
2024 // appropriate error handling strategy for their needs. For instance,
2025 // they may not want to mark an entire namespace as erroneous merely
2026 // because there is an ODR error with two typedefs. As another example,
2027 // the client may allow EnumConstantDecls with same names but with
2028 // different values in two distinct translation units.
2029 ChildErrorHandlingStrategy HandleChildErrors(FromDC);
2030
2031 auto MightNeedReordering = [](const Decl *D) {
2032 return isa<FieldDecl>(Val: D) || isa<IndirectFieldDecl>(Val: D) || isa<FriendDecl>(Val: D);
2033 };
2034
2035 // Import everything that might need reordering first.
2036 Error ChildErrors = Error::success();
2037 for (auto *From : FromDC->decls()) {
2038 if (!MightNeedReordering(From))
2039 continue;
2040
2041 ExpectedDecl ImportedOrErr = import(From);
2042
2043 // If we are in the process of ImportDefinition(...) for a RecordDecl we
2044 // want to make sure that we are also completing each FieldDecl. There
2045 // are currently cases where this does not happen and this is correctness
2046 // fix since operations such as code generation will expect this to be so.
2047 if (!ImportedOrErr) {
2048 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors,
2049 ChildErr: ImportedOrErr.takeError());
2050 continue;
2051 }
2052 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(Val: From);
2053 Decl *ImportedDecl = *ImportedOrErr;
2054 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(Val: ImportedDecl);
2055 if (FieldFrom && FieldTo) {
2056 Error Err = ImportFieldDeclDefinition(From: FieldFrom, To: FieldTo);
2057 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors, ChildErr: std::move(Err));
2058 }
2059 }
2060
2061 // We reorder declarations in RecordDecls because they may have another order
2062 // in the "to" context than they have in the "from" context. This may happen
2063 // e.g when we import a class like this:
2064 // struct declToImport {
2065 // int a = c + b;
2066 // int b = 1;
2067 // int c = 2;
2068 // };
2069 // During the import of `a` we import first the dependencies in sequence,
2070 // thus the order would be `c`, `b`, `a`. We will get the normal order by
2071 // first removing the already imported members and then adding them in the
2072 // order as they appear in the "from" context.
2073 //
2074 // Keeping field order is vital because it determines structure layout.
2075 //
2076 // Here and below, we cannot call field_begin() method and its callers on
2077 // ToDC if it has an external storage. Calling field_begin() will
2078 // automatically load all the fields by calling
2079 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
2080 // call ASTImporter::Import(). This is because the ExternalASTSource
2081 // interface in LLDB is implemented by the means of the ASTImporter. However,
2082 // calling an import at this point would result in an uncontrolled import, we
2083 // must avoid that.
2084
2085 auto ToDCOrErr = Importer.ImportContext(FromDC);
2086 if (!ToDCOrErr) {
2087 consumeError(Err: std::move(ChildErrors));
2088 return ToDCOrErr.takeError();
2089 }
2090
2091 if (const auto *FromRD = dyn_cast<RecordDecl>(Val: FromDC)) {
2092 DeclContext *ToDC = *ToDCOrErr;
2093 // Remove all declarations, which may be in wrong order in the
2094 // lexical DeclContext and then add them in the proper order.
2095 for (auto *D : FromRD->decls()) {
2096 if (!MightNeedReordering(D))
2097 continue;
2098
2099 assert(D && "DC contains a null decl");
2100 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(D)) {
2101 // Remove only the decls which we successfully imported.
2102 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
2103 // Remove the decl from its wrong place in the linked list.
2104 ToDC->removeDecl(ToD);
2105 // Add the decl to the end of the linked list.
2106 // This time it will be at the proper place because the enclosing for
2107 // loop iterates in the original (good) order of the decls.
2108 ToDC->addDeclInternal(ToD);
2109 }
2110 }
2111 }
2112
2113 // Import everything else.
2114 for (auto *From : FromDC->decls()) {
2115 if (MightNeedReordering(From))
2116 continue;
2117
2118 ExpectedDecl ImportedOrErr = import(From);
2119 if (!ImportedOrErr)
2120 HandleChildErrors.handleChildImportResult(ResultErr&: ChildErrors,
2121 ChildErr: ImportedOrErr.takeError());
2122 }
2123
2124 return ChildErrors;
2125}
2126
2127Error ASTNodeImporter::ImportFieldDeclDefinition(const FieldDecl *From,
2128 const FieldDecl *To) {
2129 RecordDecl *FromRecordDecl = nullptr;
2130 RecordDecl *ToRecordDecl = nullptr;
2131 // If we have a field that is an ArrayType we need to check if the array
2132 // element is a RecordDecl and if so we need to import the definition.
2133 QualType FromType = From->getType();
2134 QualType ToType = To->getType();
2135 if (FromType->isArrayType()) {
2136 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
2137 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2138 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2139 }
2140
2141 if (!FromRecordDecl || !ToRecordDecl) {
2142 const RecordType *RecordFrom = FromType->getAs<RecordType>();
2143 const RecordType *RecordTo = ToType->getAs<RecordType>();
2144
2145 if (RecordFrom && RecordTo) {
2146 FromRecordDecl = RecordFrom->getDecl();
2147 ToRecordDecl = RecordTo->getDecl();
2148 }
2149 }
2150
2151 if (FromRecordDecl && ToRecordDecl) {
2152 if (FromRecordDecl->isCompleteDefinition() &&
2153 !ToRecordDecl->isCompleteDefinition())
2154 return ImportDefinition(From: FromRecordDecl, To: ToRecordDecl);
2155 }
2156
2157 return Error::success();
2158}
2159
2160Error ASTNodeImporter::ImportDeclContext(
2161 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
2162 auto ToDCOrErr = Importer.ImportContext(FromDC: FromD->getDeclContext());
2163 if (!ToDCOrErr)
2164 return ToDCOrErr.takeError();
2165 ToDC = *ToDCOrErr;
2166
2167 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
2168 auto ToLexicalDCOrErr = Importer.ImportContext(
2169 FromDC: FromD->getLexicalDeclContext());
2170 if (!ToLexicalDCOrErr)
2171 return ToLexicalDCOrErr.takeError();
2172 ToLexicalDC = *ToLexicalDCOrErr;
2173 } else
2174 ToLexicalDC = ToDC;
2175
2176 return Error::success();
2177}
2178
2179Error ASTNodeImporter::ImportImplicitMethods(
2180 const CXXRecordDecl *From, CXXRecordDecl *To) {
2181 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
2182 "Import implicit methods to or from non-definition");
2183
2184 for (CXXMethodDecl *FromM : From->methods())
2185 if (FromM->isImplicit()) {
2186 Expected<CXXMethodDecl *> ToMOrErr = import(From: FromM);
2187 if (!ToMOrErr)
2188 return ToMOrErr.takeError();
2189 }
2190
2191 return Error::success();
2192}
2193
2194static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
2195 ASTImporter &Importer) {
2196 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
2197 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
2198 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(Val: *ToTypedefOrErr));
2199 else
2200 return ToTypedefOrErr.takeError();
2201 }
2202 return Error::success();
2203}
2204
2205Error ASTNodeImporter::ImportDefinition(
2206 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
2207 auto DefinitionCompleter = [To]() {
2208 // There are cases in LLDB when we first import a class without its
2209 // members. The class will have DefinitionData, but no members. Then,
2210 // importDefinition is called from LLDB, which tries to get the members, so
2211 // when we get here, the class already has the DefinitionData set, so we
2212 // must unset the CompleteDefinition here to be able to complete again the
2213 // definition.
2214 To->setCompleteDefinition(false);
2215 To->completeDefinition();
2216 };
2217
2218 if (To->getDefinition() || To->isBeingDefined()) {
2219 if (Kind == IDK_Everything ||
2220 // In case of lambdas, the class already has a definition ptr set, but
2221 // the contained decls are not imported yet. Also, isBeingDefined was
2222 // set in CXXRecordDecl::CreateLambda. We must import the contained
2223 // decls here and finish the definition.
2224 (To->isLambda() && shouldForceImportDeclContext(IDK: Kind))) {
2225 if (To->isLambda()) {
2226 auto *FromCXXRD = cast<CXXRecordDecl>(Val: From);
2227 SmallVector<LambdaCapture, 8> ToCaptures;
2228 ToCaptures.reserve(N: FromCXXRD->capture_size());
2229 for (const auto &FromCapture : FromCXXRD->captures()) {
2230 if (auto ToCaptureOrErr = import(From: FromCapture))
2231 ToCaptures.push_back(Elt: *ToCaptureOrErr);
2232 else
2233 return ToCaptureOrErr.takeError();
2234 }
2235 cast<CXXRecordDecl>(Val: To)->setCaptures(Context&: Importer.getToContext(),
2236 Captures: ToCaptures);
2237 }
2238
2239 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2240 // Finish the definition of the lambda, set isBeingDefined to false.
2241 if (To->isLambda())
2242 DefinitionCompleter();
2243 return Result;
2244 }
2245
2246 return Error::success();
2247 }
2248
2249 To->startDefinition();
2250 // Set the definition to complete even if it is really not complete during
2251 // import. Some AST constructs (expressions) require the record layout
2252 // to be calculated (see 'clang::computeDependence') at the time they are
2253 // constructed. Import of such AST node is possible during import of the
2254 // same record, there is no way to have a completely defined record (all
2255 // fields imported) at that time without multiple AST import passes.
2256 if (!Importer.isMinimalImport())
2257 To->setCompleteDefinition(true);
2258 // Complete the definition even if error is returned.
2259 // The RecordDecl may be already part of the AST so it is better to
2260 // have it in complete state even if something is wrong with it.
2261 auto DefinitionCompleterScopeExit =
2262 llvm::make_scope_exit(F&: DefinitionCompleter);
2263
2264 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2265 return Err;
2266
2267 // Add base classes.
2268 auto *ToCXX = dyn_cast<CXXRecordDecl>(Val: To);
2269 auto *FromCXX = dyn_cast<CXXRecordDecl>(Val: From);
2270 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2271
2272 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2273 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2274
2275 #define FIELD(Name, Width, Merge) \
2276 ToData.Name = FromData.Name;
2277 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2278
2279 // Copy over the data stored in RecordDeclBits
2280 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2281
2282 SmallVector<CXXBaseSpecifier *, 4> Bases;
2283 for (const auto &Base1 : FromCXX->bases()) {
2284 ExpectedType TyOrErr = import(From: Base1.getType());
2285 if (!TyOrErr)
2286 return TyOrErr.takeError();
2287
2288 SourceLocation EllipsisLoc;
2289 if (Base1.isPackExpansion()) {
2290 if (ExpectedSLoc LocOrErr = import(From: Base1.getEllipsisLoc()))
2291 EllipsisLoc = *LocOrErr;
2292 else
2293 return LocOrErr.takeError();
2294 }
2295
2296 // Ensure that we have a definition for the base.
2297 if (Error Err =
2298 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2299 return Err;
2300
2301 auto RangeOrErr = import(From: Base1.getSourceRange());
2302 if (!RangeOrErr)
2303 return RangeOrErr.takeError();
2304
2305 auto TSIOrErr = import(From: Base1.getTypeSourceInfo());
2306 if (!TSIOrErr)
2307 return TSIOrErr.takeError();
2308
2309 Bases.push_back(
2310 Elt: new (Importer.getToContext()) CXXBaseSpecifier(
2311 *RangeOrErr,
2312 Base1.isVirtual(),
2313 Base1.isBaseOfClass(),
2314 Base1.getAccessSpecifierAsWritten(),
2315 *TSIOrErr,
2316 EllipsisLoc));
2317 }
2318 if (!Bases.empty())
2319 ToCXX->setBases(Bases: Bases.data(), NumBases: Bases.size());
2320 }
2321
2322 if (shouldForceImportDeclContext(IDK: Kind)) {
2323 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2324 return Err;
2325 }
2326
2327 return Error::success();
2328}
2329
2330Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2331 if (To->getAnyInitializer())
2332 return Error::success();
2333
2334 Expr *FromInit = From->getInit();
2335 if (!FromInit)
2336 return Error::success();
2337
2338 ExpectedExpr ToInitOrErr = import(From: FromInit);
2339 if (!ToInitOrErr)
2340 return ToInitOrErr.takeError();
2341
2342 To->setInit(*ToInitOrErr);
2343 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2344 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2345 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2346 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2347 // FIXME: Also import the initializer value.
2348 }
2349
2350 // FIXME: Other bits to merge?
2351 return Error::success();
2352}
2353
2354Error ASTNodeImporter::ImportDefinition(
2355 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2356 if (To->getDefinition() || To->isBeingDefined()) {
2357 if (Kind == IDK_Everything)
2358 return ImportDeclContext(From, /*ForceImport=*/true);
2359 return Error::success();
2360 }
2361
2362 To->startDefinition();
2363
2364 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2365 return Err;
2366
2367 ExpectedType ToTypeOrErr =
2368 import(From: Importer.getFromContext().getTypeDeclType(From));
2369 if (!ToTypeOrErr)
2370 return ToTypeOrErr.takeError();
2371
2372 ExpectedType ToPromotionTypeOrErr = import(From: From->getPromotionType());
2373 if (!ToPromotionTypeOrErr)
2374 return ToPromotionTypeOrErr.takeError();
2375
2376 if (shouldForceImportDeclContext(IDK: Kind))
2377 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2378 return Err;
2379
2380 // FIXME: we might need to merge the number of positive or negative bits
2381 // if the enumerator lists don't match.
2382 To->completeDefinition(NewType: *ToTypeOrErr, PromotionType: *ToPromotionTypeOrErr,
2383 NumPositiveBits: From->getNumPositiveBits(),
2384 NumNegativeBits: From->getNumNegativeBits());
2385 return Error::success();
2386}
2387
2388Error ASTNodeImporter::ImportTemplateArguments(
2389 ArrayRef<TemplateArgument> FromArgs,
2390 SmallVectorImpl<TemplateArgument> &ToArgs) {
2391 for (const auto &Arg : FromArgs) {
2392 if (auto ToOrErr = import(From: Arg))
2393 ToArgs.push_back(Elt: *ToOrErr);
2394 else
2395 return ToOrErr.takeError();
2396 }
2397
2398 return Error::success();
2399}
2400
2401// FIXME: Do not forget to remove this and use only 'import'.
2402Expected<TemplateArgument>
2403ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2404 return import(From);
2405}
2406
2407template <typename InContainerTy>
2408Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2409 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2410 for (const auto &FromLoc : Container) {
2411 if (auto ToLocOrErr = import(FromLoc))
2412 ToTAInfo.addArgument(Loc: *ToLocOrErr);
2413 else
2414 return ToLocOrErr.takeError();
2415 }
2416 return Error::success();
2417}
2418
2419static StructuralEquivalenceKind
2420getStructuralEquivalenceKind(const ASTImporter &Importer) {
2421 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2422 : StructuralEquivalenceKind::Default;
2423}
2424
2425bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
2426 bool IgnoreTemplateParmDepth) {
2427 // Eliminate a potential failure point where we attempt to re-import
2428 // something we're trying to import while completing ToRecord.
2429 Decl *ToOrigin = Importer.GetOriginalDecl(To);
2430 if (ToOrigin) {
2431 To = ToOrigin;
2432 }
2433
2434 StructuralEquivalenceContext Ctx(
2435 Importer.getFromContext(), Importer.getToContext(),
2436 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2437 /*StrictTypeSpelling=*/false, Complain, /*ErrorOnTagTypeMismatch=*/false,
2438 IgnoreTemplateParmDepth);
2439 return Ctx.IsEquivalent(D1: From, D2: To);
2440}
2441
2442ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2443 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2444 << D->getDeclKindName();
2445 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
2446}
2447
2448ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2449 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2450 << D->getDeclKindName();
2451 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
2452}
2453
2454ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2455 // Import the context of this declaration.
2456 DeclContext *DC, *LexicalDC;
2457 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2458 return std::move(Err);
2459
2460 // Import the location of this declaration.
2461 ExpectedSLoc LocOrErr = import(D->getLocation());
2462 if (!LocOrErr)
2463 return LocOrErr.takeError();
2464
2465 EmptyDecl *ToD;
2466 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: *LocOrErr))
2467 return ToD;
2468
2469 ToD->setLexicalDeclContext(LexicalDC);
2470 LexicalDC->addDeclInternal(ToD);
2471 return ToD;
2472}
2473
2474ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2475 TranslationUnitDecl *ToD =
2476 Importer.getToContext().getTranslationUnitDecl();
2477
2478 Importer.MapImported(D, ToD);
2479
2480 return ToD;
2481}
2482
2483ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) {
2484 DeclContext *DC, *LexicalDC;
2485 DeclarationName Name;
2486 SourceLocation Loc;
2487 NamedDecl *ToND;
2488 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2489 return std::move(Err);
2490 if (ToND)
2491 return ToND;
2492
2493 BindingDecl *ToD;
2494 if (GetImportedOrCreateDecl(ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2495 args: Name.getAsIdentifierInfo()))
2496 return ToD;
2497
2498 Error Err = Error::success();
2499 QualType ToType = importChecked(Err, D->getType());
2500 Expr *ToBinding = importChecked(Err, From: D->getBinding());
2501 ValueDecl *ToDecomposedDecl = importChecked(Err, From: D->getDecomposedDecl());
2502 if (Err)
2503 return std::move(Err);
2504
2505 ToD->setBinding(DeclaredType: ToType, Binding: ToBinding);
2506 ToD->setDecomposedDecl(ToDecomposedDecl);
2507 addDeclToContexts(D, ToD);
2508
2509 return ToD;
2510}
2511
2512ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2513 ExpectedSLoc LocOrErr = import(D->getLocation());
2514 if (!LocOrErr)
2515 return LocOrErr.takeError();
2516 auto ColonLocOrErr = import(From: D->getColonLoc());
2517 if (!ColonLocOrErr)
2518 return ColonLocOrErr.takeError();
2519
2520 // Import the context of this declaration.
2521 auto DCOrErr = Importer.ImportContext(FromDC: D->getDeclContext());
2522 if (!DCOrErr)
2523 return DCOrErr.takeError();
2524 DeclContext *DC = *DCOrErr;
2525
2526 AccessSpecDecl *ToD;
2527 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2528 DC, *LocOrErr, *ColonLocOrErr))
2529 return ToD;
2530
2531 // Lexical DeclContext and Semantic DeclContext
2532 // is always the same for the accessSpec.
2533 ToD->setLexicalDeclContext(DC);
2534 DC->addDeclInternal(ToD);
2535
2536 return ToD;
2537}
2538
2539ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2540 auto DCOrErr = Importer.ImportContext(FromDC: D->getDeclContext());
2541 if (!DCOrErr)
2542 return DCOrErr.takeError();
2543 DeclContext *DC = *DCOrErr;
2544 DeclContext *LexicalDC = DC;
2545
2546 Error Err = Error::success();
2547 auto ToLocation = importChecked(Err, D->getLocation());
2548 auto ToRParenLoc = importChecked(Err, From: D->getRParenLoc());
2549 auto ToAssertExpr = importChecked(Err, From: D->getAssertExpr());
2550 auto ToMessage = importChecked(Err, From: D->getMessage());
2551 if (Err)
2552 return std::move(Err);
2553
2554 StaticAssertDecl *ToD;
2555 if (GetImportedOrCreateDecl(
2556 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2557 ToRParenLoc, D->isFailed()))
2558 return ToD;
2559
2560 ToD->setLexicalDeclContext(LexicalDC);
2561 LexicalDC->addDeclInternal(ToD);
2562 return ToD;
2563}
2564
2565ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2566 // Import the major distinguishing characteristics of this namespace.
2567 DeclContext *DC, *LexicalDC;
2568 DeclarationName Name;
2569 SourceLocation Loc;
2570 NamedDecl *ToD;
2571 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2572 return std::move(Err);
2573 if (ToD)
2574 return ToD;
2575
2576 NamespaceDecl *MergeWithNamespace = nullptr;
2577 if (!Name) {
2578 // This is an anonymous namespace. Adopt an existing anonymous
2579 // namespace if we can.
2580 // FIXME: Not testable.
2581 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
2582 MergeWithNamespace = TU->getAnonymousNamespace();
2583 else
2584 MergeWithNamespace = cast<NamespaceDecl>(Val: DC)->getAnonymousNamespace();
2585 } else {
2586 SmallVector<NamedDecl *, 4> ConflictingDecls;
2587 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2588 for (auto *FoundDecl : FoundDecls) {
2589 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2590 continue;
2591
2592 if (auto *FoundNS = dyn_cast<NamespaceDecl>(Val: FoundDecl)) {
2593 MergeWithNamespace = FoundNS;
2594 ConflictingDecls.clear();
2595 break;
2596 }
2597
2598 ConflictingDecls.push_back(Elt: FoundDecl);
2599 }
2600
2601 if (!ConflictingDecls.empty()) {
2602 ExpectedName NameOrErr = Importer.HandleNameConflict(
2603 Name, DC, IDNS: Decl::IDNS_Namespace, Decls: ConflictingDecls.data(),
2604 NumDecls: ConflictingDecls.size());
2605 if (NameOrErr)
2606 Name = NameOrErr.get();
2607 else
2608 return NameOrErr.takeError();
2609 }
2610 }
2611
2612 ExpectedSLoc BeginLocOrErr = import(From: D->getBeginLoc());
2613 if (!BeginLocOrErr)
2614 return BeginLocOrErr.takeError();
2615 ExpectedSLoc RBraceLocOrErr = import(From: D->getRBraceLoc());
2616 if (!RBraceLocOrErr)
2617 return RBraceLocOrErr.takeError();
2618
2619 // Create the "to" namespace, if needed.
2620 NamespaceDecl *ToNamespace = MergeWithNamespace;
2621 if (!ToNamespace) {
2622 if (GetImportedOrCreateDecl(ToD&: ToNamespace, FromD: D, args&: Importer.getToContext(), args&: DC,
2623 args: D->isInline(), args&: *BeginLocOrErr, args&: Loc,
2624 args: Name.getAsIdentifierInfo(),
2625 /*PrevDecl=*/args: nullptr, args: D->isNested()))
2626 return ToNamespace;
2627 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2628 ToNamespace->setLexicalDeclContext(LexicalDC);
2629 LexicalDC->addDeclInternal(ToNamespace);
2630
2631 // If this is an anonymous namespace, register it as the anonymous
2632 // namespace within its context.
2633 if (!Name) {
2634 if (auto *TU = dyn_cast<TranslationUnitDecl>(Val: DC))
2635 TU->setAnonymousNamespace(ToNamespace);
2636 else
2637 cast<NamespaceDecl>(Val: DC)->setAnonymousNamespace(ToNamespace);
2638 }
2639 }
2640 Importer.MapImported(D, ToNamespace);
2641
2642 if (Error Err = ImportDeclContext(D))
2643 return std::move(Err);
2644
2645 return ToNamespace;
2646}
2647
2648ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2649 // Import the major distinguishing characteristics of this namespace.
2650 DeclContext *DC, *LexicalDC;
2651 DeclarationName Name;
2652 SourceLocation Loc;
2653 NamedDecl *LookupD;
2654 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2655 return std::move(Err);
2656 if (LookupD)
2657 return LookupD;
2658
2659 // NOTE: No conflict resolution is done for namespace aliases now.
2660
2661 Error Err = Error::success();
2662 auto ToNamespaceLoc = importChecked(Err, From: D->getNamespaceLoc());
2663 auto ToAliasLoc = importChecked(Err, From: D->getAliasLoc());
2664 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
2665 auto ToTargetNameLoc = importChecked(Err, From: D->getTargetNameLoc());
2666 auto ToNamespace = importChecked(Err, From: D->getNamespace());
2667 if (Err)
2668 return std::move(Err);
2669
2670 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2671
2672 NamespaceAliasDecl *ToD;
2673 if (GetImportedOrCreateDecl(
2674 ToD, FromD: D, args&: Importer.getToContext(), args&: DC, args&: ToNamespaceLoc, args&: ToAliasLoc,
2675 args&: ToIdentifier, args&: ToQualifierLoc, args&: ToTargetNameLoc, args&: ToNamespace))
2676 return ToD;
2677
2678 ToD->setLexicalDeclContext(LexicalDC);
2679 LexicalDC->addDeclInternal(ToD);
2680
2681 return ToD;
2682}
2683
2684ExpectedDecl
2685ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2686 // Import the major distinguishing characteristics of this typedef.
2687 DeclarationName Name;
2688 SourceLocation Loc;
2689 NamedDecl *ToD;
2690 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2691 // is created.
2692 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2693 return std::move(Err);
2694 if (ToD)
2695 return ToD;
2696
2697 DeclContext *DC = cast_or_null<DeclContext>(
2698 Importer.GetAlreadyImportedOrNull(FromD: cast<Decl>(D->getDeclContext())));
2699 DeclContext *LexicalDC =
2700 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2701 FromD: cast<Decl>(D->getLexicalDeclContext())));
2702
2703 // If this typedef is not in block scope, determine whether we've
2704 // seen a typedef with the same name (that we can merge with) or any
2705 // other entity by that name (which name lookup could conflict with).
2706 // Note: Repeated typedefs are not valid in C99:
2707 // 'typedef int T; typedef int T;' is invalid
2708 // We do not care about this now.
2709 if (DC && !DC->isFunctionOrMethod()) {
2710 SmallVector<NamedDecl *, 4> ConflictingDecls;
2711 unsigned IDNS = Decl::IDNS_Ordinary;
2712 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2713 for (auto *FoundDecl : FoundDecls) {
2714 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2715 continue;
2716 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2717 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2718 continue;
2719
2720 QualType FromUT = D->getUnderlyingType();
2721 QualType FoundUT = FoundTypedef->getUnderlyingType();
2722 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2723 // If the underlying declarations are unnamed records these can be
2724 // imported as different types. We should create a distinct typedef
2725 // node in this case.
2726 // If we found an existing underlying type with a record in a
2727 // different context (than the imported), this is already reason for
2728 // having distinct typedef nodes for these.
2729 // Again this can create situation like
2730 // 'typedef int T; typedef int T;' but this is hard to avoid without
2731 // a rename strategy at import.
2732 if (!FromUT.isNull() && !FoundUT.isNull()) {
2733 RecordDecl *FromR = FromUT->getAsRecordDecl();
2734 RecordDecl *FoundR = FoundUT->getAsRecordDecl();
2735 if (FromR && FoundR &&
2736 !hasSameVisibilityContextAndLinkage(FoundR, FromR))
2737 continue;
2738 }
2739 // If the "From" context has a complete underlying type but we
2740 // already have a complete underlying type then return with that.
2741 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2742 return Importer.MapImported(D, FoundTypedef);
2743 // FIXME Handle redecl chain. When you do that make consistent changes
2744 // in ASTImporterLookupTable too.
2745 } else {
2746 ConflictingDecls.push_back(FoundDecl);
2747 }
2748 }
2749 }
2750
2751 if (!ConflictingDecls.empty()) {
2752 ExpectedName NameOrErr = Importer.HandleNameConflict(
2753 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
2754 if (NameOrErr)
2755 Name = NameOrErr.get();
2756 else
2757 return NameOrErr.takeError();
2758 }
2759 }
2760
2761 Error Err = Error::success();
2762 auto ToUnderlyingType = importChecked(Err, From: D->getUnderlyingType());
2763 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
2764 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2765 if (Err)
2766 return std::move(Err);
2767
2768 // Create the new typedef node.
2769 // FIXME: ToUnderlyingType is not used.
2770 (void)ToUnderlyingType;
2771 TypedefNameDecl *ToTypedef;
2772 if (IsAlias) {
2773 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2774 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2775 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2776 return ToTypedef;
2777 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2778 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2779 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2780 return ToTypedef;
2781
2782 // Import the DeclContext and set it to the Typedef.
2783 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2784 return std::move(Err);
2785 ToTypedef->setDeclContext(DC);
2786 ToTypedef->setLexicalDeclContext(LexicalDC);
2787 // Add to the lookupTable because we could not do that in MapImported.
2788 Importer.AddToLookupTable(ToTypedef);
2789
2790 ToTypedef->setAccess(D->getAccess());
2791
2792 // Templated declarations should not appear in DeclContext.
2793 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(Val: D) : nullptr;
2794 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2795 LexicalDC->addDeclInternal(ToTypedef);
2796
2797 return ToTypedef;
2798}
2799
2800ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2801 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2802}
2803
2804ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2805 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2806}
2807
2808ExpectedDecl
2809ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2810 // Import the major distinguishing characteristics of this typedef.
2811 DeclContext *DC, *LexicalDC;
2812 DeclarationName Name;
2813 SourceLocation Loc;
2814 NamedDecl *FoundD;
2815 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2816 return std::move(Err);
2817 if (FoundD)
2818 return FoundD;
2819
2820 // If this typedef is not in block scope, determine whether we've
2821 // seen a typedef with the same name (that we can merge with) or any
2822 // other entity by that name (which name lookup could conflict with).
2823 if (!DC->isFunctionOrMethod()) {
2824 SmallVector<NamedDecl *, 4> ConflictingDecls;
2825 unsigned IDNS = Decl::IDNS_Ordinary;
2826 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2827 for (auto *FoundDecl : FoundDecls) {
2828 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2829 continue;
2830 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(Val: FoundDecl)) {
2831 if (IsStructuralMatch(D, FoundAlias))
2832 return Importer.MapImported(D, FoundAlias);
2833 ConflictingDecls.push_back(Elt: FoundDecl);
2834 }
2835 }
2836
2837 if (!ConflictingDecls.empty()) {
2838 ExpectedName NameOrErr = Importer.HandleNameConflict(
2839 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
2840 if (NameOrErr)
2841 Name = NameOrErr.get();
2842 else
2843 return NameOrErr.takeError();
2844 }
2845 }
2846
2847 Error Err = Error::success();
2848 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2849 auto ToTemplatedDecl = importChecked(Err, From: D->getTemplatedDecl());
2850 if (Err)
2851 return std::move(Err);
2852
2853 TypeAliasTemplateDecl *ToAlias;
2854 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2855 Name, ToTemplateParameters, ToTemplatedDecl))
2856 return ToAlias;
2857
2858 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2859
2860 ToAlias->setAccess(D->getAccess());
2861 ToAlias->setLexicalDeclContext(LexicalDC);
2862 LexicalDC->addDeclInternal(ToAlias);
2863 if (DC != Importer.getToContext().getTranslationUnitDecl())
2864 updateLookupTableForTemplateParameters(*ToTemplateParameters);
2865 return ToAlias;
2866}
2867
2868ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2869 // Import the major distinguishing characteristics of this label.
2870 DeclContext *DC, *LexicalDC;
2871 DeclarationName Name;
2872 SourceLocation Loc;
2873 NamedDecl *ToD;
2874 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2875 return std::move(Err);
2876 if (ToD)
2877 return ToD;
2878
2879 assert(LexicalDC->isFunctionOrMethod());
2880
2881 LabelDecl *ToLabel;
2882 if (D->isGnuLocal()) {
2883 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2884 if (!BeginLocOrErr)
2885 return BeginLocOrErr.takeError();
2886 if (GetImportedOrCreateDecl(ToD&: ToLabel, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2887 args: Name.getAsIdentifierInfo(), args&: *BeginLocOrErr))
2888 return ToLabel;
2889
2890 } else {
2891 if (GetImportedOrCreateDecl(ToD&: ToLabel, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
2892 args: Name.getAsIdentifierInfo()))
2893 return ToLabel;
2894
2895 }
2896
2897 Expected<LabelStmt *> ToStmtOrErr = import(From: D->getStmt());
2898 if (!ToStmtOrErr)
2899 return ToStmtOrErr.takeError();
2900
2901 ToLabel->setStmt(*ToStmtOrErr);
2902 ToLabel->setLexicalDeclContext(LexicalDC);
2903 LexicalDC->addDeclInternal(ToLabel);
2904 return ToLabel;
2905}
2906
2907ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2908 // Import the major distinguishing characteristics of this enum.
2909 DeclContext *DC, *LexicalDC;
2910 DeclarationName Name;
2911 SourceLocation Loc;
2912 NamedDecl *ToD;
2913 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2914 return std::move(Err);
2915 if (ToD)
2916 return ToD;
2917
2918 // Figure out what enum name we're looking for.
2919 unsigned IDNS = Decl::IDNS_Tag;
2920 DeclarationName SearchName = Name;
2921 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2922 if (Error Err = importInto(
2923 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2924 return std::move(Err);
2925 IDNS = Decl::IDNS_Ordinary;
2926 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2927 IDNS |= Decl::IDNS_Ordinary;
2928
2929 // We may already have an enum of the same name; try to find and match it.
2930 EnumDecl *PrevDecl = nullptr;
2931 if (!DC->isFunctionOrMethod() && SearchName) {
2932 SmallVector<NamedDecl *, 4> ConflictingDecls;
2933 auto FoundDecls =
2934 Importer.findDeclsInToCtx(DC, Name: SearchName);
2935 for (auto *FoundDecl : FoundDecls) {
2936 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2937 continue;
2938
2939 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Val: FoundDecl)) {
2940 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2941 FoundDecl = Tag->getDecl();
2942 }
2943
2944 if (auto *FoundEnum = dyn_cast<EnumDecl>(Val: FoundDecl)) {
2945 if (!hasSameVisibilityContextAndLinkage(Found: FoundEnum, From: D))
2946 continue;
2947 if (IsStructuralMatch(D, FoundEnum)) {
2948 EnumDecl *FoundDef = FoundEnum->getDefinition();
2949 if (D->isThisDeclarationADefinition() && FoundDef)
2950 return Importer.MapImported(D, FoundDef);
2951 PrevDecl = FoundEnum->getMostRecentDecl();
2952 break;
2953 }
2954 ConflictingDecls.push_back(Elt: FoundDecl);
2955 }
2956 }
2957
2958 if (!ConflictingDecls.empty()) {
2959 ExpectedName NameOrErr = Importer.HandleNameConflict(
2960 Name: SearchName, DC, IDNS, Decls: ConflictingDecls.data(),
2961 NumDecls: ConflictingDecls.size());
2962 if (NameOrErr)
2963 Name = NameOrErr.get();
2964 else
2965 return NameOrErr.takeError();
2966 }
2967 }
2968
2969 Error Err = Error::success();
2970 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2971 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2972 auto ToIntegerType = importChecked(Err, From: D->getIntegerType());
2973 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2974 if (Err)
2975 return std::move(Err);
2976
2977 // Create the enum declaration.
2978 EnumDecl *D2;
2979 if (GetImportedOrCreateDecl(
2980 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2981 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2982 D->isScopedUsingClassTag(), D->isFixed()))
2983 return D2;
2984
2985 D2->setQualifierInfo(ToQualifierLoc);
2986 D2->setIntegerType(ToIntegerType);
2987 D2->setBraceRange(ToBraceRange);
2988 D2->setAccess(D->getAccess());
2989 D2->setLexicalDeclContext(LexicalDC);
2990 addDeclToContexts(D, D2);
2991
2992 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2993 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2994 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2995 if (Expected<EnumDecl *> ToInstOrErr = import(From: FromInst))
2996 D2->setInstantiationOfMemberEnum(ED: *ToInstOrErr, TSK: SK);
2997 else
2998 return ToInstOrErr.takeError();
2999 if (ExpectedSLoc POIOrErr = import(From: MemberInfo->getPointOfInstantiation()))
3000 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3001 else
3002 return POIOrErr.takeError();
3003 }
3004
3005 // Import the definition
3006 if (D->isCompleteDefinition())
3007 if (Error Err = ImportDefinition(From: D, To: D2))
3008 return std::move(Err);
3009
3010 return D2;
3011}
3012
3013ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
3014 bool IsFriendTemplate = false;
3015 if (auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3016 IsFriendTemplate =
3017 DCXX->getDescribedClassTemplate() &&
3018 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
3019 Decl::FOK_None;
3020 }
3021
3022 // Import the major distinguishing characteristics of this record.
3023 DeclContext *DC = nullptr, *LexicalDC = nullptr;
3024 DeclarationName Name;
3025 SourceLocation Loc;
3026 NamedDecl *ToD = nullptr;
3027 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3028 return std::move(Err);
3029 if (ToD)
3030 return ToD;
3031
3032 // Figure out what structure name we're looking for.
3033 unsigned IDNS = Decl::IDNS_Tag;
3034 DeclarationName SearchName = Name;
3035 if (!SearchName && D->getTypedefNameForAnonDecl()) {
3036 if (Error Err = importInto(
3037 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
3038 return std::move(Err);
3039 IDNS = Decl::IDNS_Ordinary;
3040 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
3041 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
3042
3043 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
3044 : DC->isDependentContext();
3045 bool DependentFriend = IsFriendTemplate && IsDependentContext;
3046
3047 // We may already have a record of the same name; try to find and match it.
3048 RecordDecl *PrevDecl = nullptr;
3049 if (!DependentFriend && !DC->isFunctionOrMethod() && !D->isLambda()) {
3050 SmallVector<NamedDecl *, 4> ConflictingDecls;
3051 auto FoundDecls =
3052 Importer.findDeclsInToCtx(DC, Name: SearchName);
3053 if (!FoundDecls.empty()) {
3054 // We're going to have to compare D against potentially conflicting Decls,
3055 // so complete it.
3056 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
3057 D->getASTContext().getExternalSource()->CompleteType(D);
3058 }
3059
3060 for (auto *FoundDecl : FoundDecls) {
3061 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3062 continue;
3063
3064 Decl *Found = FoundDecl;
3065 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
3066 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
3067 Found = Tag->getDecl();
3068 }
3069
3070 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
3071 // Do not emit false positive diagnostic in case of unnamed
3072 // struct/union and in case of anonymous structs. Would be false
3073 // because there may be several anonymous/unnamed structs in a class.
3074 // E.g. these are both valid:
3075 // struct A { // unnamed structs
3076 // struct { struct A *next; } entry0;
3077 // struct { struct A *next; } entry1;
3078 // };
3079 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
3080 if (!SearchName)
3081 if (!IsStructuralMatch(From: D, To: FoundRecord, Complain: false))
3082 continue;
3083
3084 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
3085 continue;
3086
3087 if (IsStructuralMatch(From: D, To: FoundRecord)) {
3088 RecordDecl *FoundDef = FoundRecord->getDefinition();
3089 if (D->isThisDeclarationADefinition() && FoundDef) {
3090 // FIXME: Structural equivalence check should check for same
3091 // user-defined methods.
3092 Importer.MapImported(D, FoundDef);
3093 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3094 auto *FoundCXX = dyn_cast<CXXRecordDecl>(Val: FoundDef);
3095 assert(FoundCXX && "Record type mismatch");
3096
3097 if (!Importer.isMinimalImport())
3098 // FoundDef may not have every implicit method that D has
3099 // because implicit methods are created only if they are used.
3100 if (Error Err = ImportImplicitMethods(From: DCXX, To: FoundCXX))
3101 return std::move(Err);
3102 }
3103 }
3104 PrevDecl = FoundRecord->getMostRecentDecl();
3105 break;
3106 }
3107 ConflictingDecls.push_back(Elt: FoundDecl);
3108 } // kind is RecordDecl
3109 } // for
3110
3111 if (!ConflictingDecls.empty() && SearchName) {
3112 ExpectedName NameOrErr = Importer.HandleNameConflict(
3113 Name: SearchName, DC, IDNS, Decls: ConflictingDecls.data(),
3114 NumDecls: ConflictingDecls.size());
3115 if (NameOrErr)
3116 Name = NameOrErr.get();
3117 else
3118 return NameOrErr.takeError();
3119 }
3120 }
3121
3122 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
3123 if (!BeginLocOrErr)
3124 return BeginLocOrErr.takeError();
3125
3126 // Create the record declaration.
3127 RecordDecl *D2 = nullptr;
3128 CXXRecordDecl *D2CXX = nullptr;
3129 if (auto *DCXX = dyn_cast<CXXRecordDecl>(Val: D)) {
3130 if (DCXX->isLambda()) {
3131 auto TInfoOrErr = import(From: DCXX->getLambdaTypeInfo());
3132 if (!TInfoOrErr)
3133 return TInfoOrErr.takeError();
3134 if (GetImportedOrCreateSpecialDecl(
3135 ToD&: D2CXX, CreateFun: CXXRecordDecl::CreateLambda, FromD: D, args&: Importer.getToContext(),
3136 args&: DC, args&: *TInfoOrErr, args&: Loc, args: DCXX->getLambdaDependencyKind(),
3137 args: DCXX->isGenericLambda(), args: DCXX->getLambdaCaptureDefault()))
3138 return D2CXX;
3139 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering();
3140 ExpectedDecl CDeclOrErr = import(From: Numbering.ContextDecl);
3141 if (!CDeclOrErr)
3142 return CDeclOrErr.takeError();
3143 Numbering.ContextDecl = *CDeclOrErr;
3144 D2CXX->setLambdaNumbering(Numbering);
3145 } else if (DCXX->isInjectedClassName()) {
3146 // We have to be careful to do a similar dance to the one in
3147 // Sema::ActOnStartCXXMemberDeclarations
3148 const bool DelayTypeCreation = true;
3149 if (GetImportedOrCreateDecl(
3150 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
3151 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
3152 cast_or_null<CXXRecordDecl>(Val: PrevDecl), DelayTypeCreation))
3153 return D2CXX;
3154 Importer.getToContext().getTypeDeclType(
3155 D2CXX, dyn_cast<CXXRecordDecl>(Val: DC));
3156 } else {
3157 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
3158 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3159 Name.getAsIdentifierInfo(),
3160 cast_or_null<CXXRecordDecl>(Val: PrevDecl)))
3161 return D2CXX;
3162 }
3163
3164 D2 = D2CXX;
3165 D2->setAccess(D->getAccess());
3166 D2->setLexicalDeclContext(LexicalDC);
3167 addDeclToContexts(D, D2);
3168
3169 if (ClassTemplateDecl *FromDescribed =
3170 DCXX->getDescribedClassTemplate()) {
3171 ClassTemplateDecl *ToDescribed;
3172 if (Error Err = importInto(To&: ToDescribed, From: FromDescribed))
3173 return std::move(Err);
3174 D2CXX->setDescribedClassTemplate(ToDescribed);
3175 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
3176 // In a record describing a template the type should be an
3177 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
3178 // previously set type to the correct value here (ToDescribed is not
3179 // available at record create).
3180 CXXRecordDecl *Injected = nullptr;
3181 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
3182 auto *Record = dyn_cast<CXXRecordDecl>(Found);
3183 if (Record && Record->isInjectedClassName()) {
3184 Injected = Record;
3185 break;
3186 }
3187 }
3188 // Create an injected type for the whole redecl chain.
3189 // The chain may contain an already existing injected type at the start,
3190 // if yes this should be reused. We must ensure that only one type
3191 // object exists for the injected type (including the injected record
3192 // declaration), ASTContext does not check it.
3193 SmallVector<Decl *, 2> Redecls =
3194 getCanonicalForwardRedeclChain(D2CXX);
3195 const Type *FrontTy =
3196 cast<CXXRecordDecl>(Val: Redecls.front())->getTypeForDecl();
3197 QualType InjSpec;
3198 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>())
3199 InjSpec = InjTy->getInjectedSpecializationType();
3200 else
3201 InjSpec = ToDescribed->getInjectedClassNameSpecialization();
3202 for (auto *R : Redecls) {
3203 auto *RI = cast<CXXRecordDecl>(R);
3204 if (R != Redecls.front() ||
3205 !isa<InjectedClassNameType>(RI->getTypeForDecl()))
3206 RI->setTypeForDecl(nullptr);
3207 // This function tries to get the injected type from getTypeForDecl,
3208 // then from the previous declaration if possible. If not, it creates
3209 // a new type.
3210 Importer.getToContext().getInjectedClassNameType(RI, InjSpec);
3211 }
3212 // Set the new type for the injected decl too.
3213 if (Injected) {
3214 Injected->setTypeForDecl(nullptr);
3215 // This function will copy the injected type from D2CXX into Injected.
3216 // The injected decl does not have a previous decl to copy from.
3217 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
3218 }
3219 }
3220 } else if (MemberSpecializationInfo *MemberInfo =
3221 DCXX->getMemberSpecializationInfo()) {
3222 TemplateSpecializationKind SK =
3223 MemberInfo->getTemplateSpecializationKind();
3224 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
3225
3226 if (Expected<CXXRecordDecl *> ToInstOrErr = import(From: FromInst))
3227 D2CXX->setInstantiationOfMemberClass(RD: *ToInstOrErr, TSK: SK);
3228 else
3229 return ToInstOrErr.takeError();
3230
3231 if (ExpectedSLoc POIOrErr =
3232 import(From: MemberInfo->getPointOfInstantiation()))
3233 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
3234 *POIOrErr);
3235 else
3236 return POIOrErr.takeError();
3237 }
3238
3239 } else {
3240 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3241 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3242 Name.getAsIdentifierInfo(), PrevDecl))
3243 return D2;
3244 D2->setLexicalDeclContext(LexicalDC);
3245 addDeclToContexts(D, D2);
3246 }
3247
3248 if (auto BraceRangeOrErr = import(D->getBraceRange()))
3249 D2->setBraceRange(*BraceRangeOrErr);
3250 else
3251 return BraceRangeOrErr.takeError();
3252 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3253 D2->setQualifierInfo(*QualifierLocOrErr);
3254 else
3255 return QualifierLocOrErr.takeError();
3256
3257 if (D->isAnonymousStructOrUnion())
3258 D2->setAnonymousStructOrUnion(true);
3259
3260 if (D->isCompleteDefinition())
3261 if (Error Err = ImportDefinition(From: D, To: D2, Kind: IDK_Default))
3262 return std::move(Err);
3263
3264 return D2;
3265}
3266
3267ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3268 // Import the major distinguishing characteristics of this enumerator.
3269 DeclContext *DC, *LexicalDC;
3270 DeclarationName Name;
3271 SourceLocation Loc;
3272 NamedDecl *ToD;
3273 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3274 return std::move(Err);
3275 if (ToD)
3276 return ToD;
3277
3278 // Determine whether there are any other declarations with the same name and
3279 // in the same context.
3280 if (!LexicalDC->isFunctionOrMethod()) {
3281 SmallVector<NamedDecl *, 4> ConflictingDecls;
3282 unsigned IDNS = Decl::IDNS_Ordinary;
3283 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3284 for (auto *FoundDecl : FoundDecls) {
3285 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3286 continue;
3287
3288 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(Val: FoundDecl)) {
3289 if (IsStructuralMatch(D, FoundEnumConstant))
3290 return Importer.MapImported(D, FoundEnumConstant);
3291 ConflictingDecls.push_back(Elt: FoundDecl);
3292 }
3293 }
3294
3295 if (!ConflictingDecls.empty()) {
3296 ExpectedName NameOrErr = Importer.HandleNameConflict(
3297 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
3298 if (NameOrErr)
3299 Name = NameOrErr.get();
3300 else
3301 return NameOrErr.takeError();
3302 }
3303 }
3304
3305 ExpectedType TypeOrErr = import(D->getType());
3306 if (!TypeOrErr)
3307 return TypeOrErr.takeError();
3308
3309 ExpectedExpr InitOrErr = import(From: D->getInitExpr());
3310 if (!InitOrErr)
3311 return InitOrErr.takeError();
3312
3313 EnumConstantDecl *ToEnumerator;
3314 if (GetImportedOrCreateDecl(
3315 ToD&: ToEnumerator, FromD: D, args&: Importer.getToContext(), args: cast<EnumDecl>(Val: DC), args&: Loc,
3316 args: Name.getAsIdentifierInfo(), args&: *TypeOrErr, args&: *InitOrErr, args: D->getInitVal()))
3317 return ToEnumerator;
3318
3319 ToEnumerator->setAccess(D->getAccess());
3320 ToEnumerator->setLexicalDeclContext(LexicalDC);
3321 LexicalDC->addDeclInternal(ToEnumerator);
3322 return ToEnumerator;
3323}
3324
3325Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
3326 DeclaratorDecl *ToD) {
3327 unsigned int Num = FromD->getNumTemplateParameterLists();
3328 if (Num == 0)
3329 return Error::success();
3330 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3331 for (unsigned int I = 0; I < Num; ++I)
3332 if (Expected<TemplateParameterList *> ToTPListOrErr =
3333 import(From: FromD->getTemplateParameterList(index: I)))
3334 ToTPLists[I] = *ToTPListOrErr;
3335 else
3336 return ToTPListOrErr.takeError();
3337 ToD->setTemplateParameterListsInfo(Context&: Importer.ToContext, TPLists: ToTPLists);
3338 return Error::success();
3339}
3340
3341Error ASTNodeImporter::ImportTemplateInformation(
3342 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3343 switch (FromFD->getTemplatedKind()) {
3344 case FunctionDecl::TK_NonTemplate:
3345 case FunctionDecl::TK_FunctionTemplate:
3346 return Error::success();
3347
3348 case FunctionDecl::TK_DependentNonTemplate:
3349 if (Expected<FunctionDecl *> InstFDOrErr =
3350 import(From: FromFD->getInstantiatedFromDecl()))
3351 ToFD->setInstantiatedFromDecl(*InstFDOrErr);
3352 return Error::success();
3353 case FunctionDecl::TK_MemberSpecialization: {
3354 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3355
3356 if (Expected<FunctionDecl *> InstFDOrErr =
3357 import(From: FromFD->getInstantiatedFromMemberFunction()))
3358 ToFD->setInstantiationOfMemberFunction(FD: *InstFDOrErr, TSK);
3359 else
3360 return InstFDOrErr.takeError();
3361
3362 if (ExpectedSLoc POIOrErr = import(
3363 From: FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3364 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3365 else
3366 return POIOrErr.takeError();
3367
3368 return Error::success();
3369 }
3370
3371 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3372 auto FunctionAndArgsOrErr =
3373 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3374 if (!FunctionAndArgsOrErr)
3375 return FunctionAndArgsOrErr.takeError();
3376
3377 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3378 Context&: Importer.getToContext(), Args: std::get<1>(*FunctionAndArgsOrErr));
3379
3380 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3381 TemplateArgumentListInfo ToTAInfo;
3382 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3383 if (FromTAArgsAsWritten)
3384 if (Error Err = ImportTemplateArgumentListInfo(
3385 Container: *FromTAArgsAsWritten, ToTAInfo))
3386 return Err;
3387
3388 ExpectedSLoc POIOrErr = import(From: FTSInfo->getPointOfInstantiation());
3389 if (!POIOrErr)
3390 return POIOrErr.takeError();
3391
3392 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3393 return Err;
3394
3395 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3396 ToFD->setFunctionTemplateSpecialization(
3397 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3398 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3399 return Error::success();
3400 }
3401
3402 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3403 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3404 UnresolvedSet<8> Candidates;
3405 for (FunctionTemplateDecl *FTD : FromInfo->getCandidates()) {
3406 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = import(From: FTD))
3407 Candidates.addDecl(*ToFTDOrErr);
3408 else
3409 return ToFTDOrErr.takeError();
3410 }
3411
3412 // Import TemplateArgumentListInfo.
3413 TemplateArgumentListInfo ToTAInfo;
3414 const auto *FromTAArgsAsWritten = FromInfo->TemplateArgumentsAsWritten;
3415 if (FromTAArgsAsWritten)
3416 if (Error Err =
3417 ImportTemplateArgumentListInfo(Container: *FromTAArgsAsWritten, ToTAInfo))
3418 return Err;
3419
3420 ToFD->setDependentTemplateSpecialization(
3421 Context&: Importer.getToContext(), Templates: Candidates,
3422 TemplateArgs: FromTAArgsAsWritten ? &ToTAInfo : nullptr);
3423 return Error::success();
3424 }
3425 }
3426 llvm_unreachable("All cases should be covered!");
3427}
3428
3429Expected<FunctionDecl *>
3430ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3431 auto FunctionAndArgsOrErr =
3432 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3433 if (!FunctionAndArgsOrErr)
3434 return FunctionAndArgsOrErr.takeError();
3435
3436 FunctionTemplateDecl *Template;
3437 TemplateArgsTy ToTemplArgs;
3438 std::tie(args&: Template, args&: ToTemplArgs) = *FunctionAndArgsOrErr;
3439 void *InsertPos = nullptr;
3440 auto *FoundSpec = Template->findSpecialization(Args: ToTemplArgs, InsertPos);
3441 return FoundSpec;
3442}
3443
3444Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3445 FunctionDecl *ToFD) {
3446 if (Stmt *FromBody = FromFD->getBody()) {
3447 if (ExpectedStmt ToBodyOrErr = import(From: FromBody))
3448 ToFD->setBody(*ToBodyOrErr);
3449 else
3450 return ToBodyOrErr.takeError();
3451 }
3452 return Error::success();
3453}
3454
3455// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3456// which is equal to the given DC, or D is equal to DC.
3457static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3458 const DeclContext *DCi = dyn_cast<DeclContext>(Val: D);
3459 if (!DCi)
3460 DCi = D->getDeclContext();
3461 assert(DCi && "Declaration should have a context");
3462 while (DCi != D->getTranslationUnitDecl()) {
3463 if (DCi == DC)
3464 return true;
3465 DCi = DCi->getParent();
3466 }
3467 return false;
3468}
3469
3470// Check if there is a declaration that has 'DC' as parent context and is
3471// referenced from statement 'S' or one of its children. The search is done in
3472// BFS order through children of 'S'.
3473static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
3474 SmallVector<const Stmt *> ToProcess;
3475 ToProcess.push_back(Elt: S);
3476 while (!ToProcess.empty()) {
3477 const Stmt *CurrentS = ToProcess.pop_back_val();
3478 ToProcess.append(in_start: CurrentS->child_begin(), in_end: CurrentS->child_end());
3479 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(Val: CurrentS)) {
3480 if (const Decl *D = DeclRef->getDecl())
3481 if (isAncestorDeclContextOf(DC, D))
3482 return true;
3483 } else if (const auto *E =
3484 dyn_cast_or_null<SubstNonTypeTemplateParmExpr>(Val: CurrentS)) {
3485 if (const Decl *D = E->getAssociatedDecl())
3486 if (isAncestorDeclContextOf(DC, D))
3487 return true;
3488 }
3489 }
3490 return false;
3491}
3492
3493namespace {
3494/// Check if a type has any reference to a declaration that is inside the body
3495/// of a function.
3496/// The \c CheckType(QualType) function should be used to determine
3497/// this property.
3498///
3499/// The type visitor visits one type object only (not recursive).
3500/// To find all referenced declarations we must discover all type objects until
3501/// the canonical type is reached (walk over typedef and similar objects). This
3502/// is done by loop over all "sugar" type objects. For every such type we must
3503/// check all declarations that are referenced from it. For this check the
3504/// visitor is used. In the visit functions all referenced declarations except
3505/// the one that follows in the sugar chain (if any) must be checked. For this
3506/// check the same visitor is re-used (it has no state-dependent data).
3507///
3508/// The visit functions have 3 possible return values:
3509/// - True, found a declaration inside \c ParentDC.
3510/// - False, found declarations only outside \c ParentDC and it is not possible
3511/// to find more declarations (the "sugar" chain does not continue).
3512/// - Empty optional value, found no declarations or only outside \c ParentDC,
3513/// but it is possible to find more declarations in the type "sugar" chain.
3514/// The loop over the "sugar" types can be implemented by using type visit
3515/// functions only (call \c CheckType with the desugared type). With the current
3516/// solution no visit function is needed if the type has only a desugared type
3517/// as data.
3518class IsTypeDeclaredInsideVisitor
3519 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
3520public:
3521 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
3522 : ParentDC(ParentDC) {}
3523
3524 bool CheckType(QualType T) {
3525 // Check the chain of "sugar" types.
3526 // The "sugar" types are typedef or similar types that have the same
3527 // canonical type.
3528 if (std::optional<bool> Res = Visit(T: T.getTypePtr()))
3529 return *Res;
3530 QualType DsT =
3531 T.getSingleStepDesugaredType(Context: ParentDC->getParentASTContext());
3532 while (DsT != T) {
3533 if (std::optional<bool> Res = Visit(T: DsT.getTypePtr()))
3534 return *Res;
3535 T = DsT;
3536 DsT = T.getSingleStepDesugaredType(Context: ParentDC->getParentASTContext());
3537 }
3538 return false;
3539 }
3540
3541 std::optional<bool> VisitTagType(const TagType *T) {
3542 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(Val: T->getDecl()))
3543 for (const auto &Arg : Spec->getTemplateArgs().asArray())
3544 if (checkTemplateArgument(Arg))
3545 return true;
3546 return isAncestorDeclContextOf(ParentDC, T->getDecl());
3547 }
3548
3549 std::optional<bool> VisitPointerType(const PointerType *T) {
3550 return CheckType(T: T->getPointeeType());
3551 }
3552
3553 std::optional<bool> VisitReferenceType(const ReferenceType *T) {
3554 return CheckType(T: T->getPointeeTypeAsWritten());
3555 }
3556
3557 std::optional<bool> VisitTypedefType(const TypedefType *T) {
3558 const TypedefNameDecl *TD = T->getDecl();
3559 assert(TD);
3560 return isAncestorDeclContextOf(ParentDC, TD);
3561 }
3562
3563 std::optional<bool> VisitUsingType(const UsingType *T) {
3564 if (T->getFoundDecl() &&
3565 isAncestorDeclContextOf(ParentDC, T->getFoundDecl()))
3566 return true;
3567
3568 return {};
3569 }
3570
3571 std::optional<bool>
3572 VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
3573 for (const auto &Arg : T->template_arguments())
3574 if (checkTemplateArgument(Arg))
3575 return true;
3576 // This type is a "sugar" to a record type, it can have a desugared type.
3577 return {};
3578 }
3579
3580 std::optional<bool>
3581 VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3582 // The "associated declaration" can be the same as ParentDC.
3583 if (isAncestorDeclContextOf(DC: ParentDC, D: T->getAssociatedDecl()))
3584 return true;
3585 return {};
3586 }
3587
3588 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
3589 if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr()))
3590 return true;
3591
3592 return CheckType(T: T->getElementType());
3593 }
3594
3595 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
3596 llvm_unreachable(
3597 "Variable array should not occur in deduced return type of a function");
3598 }
3599
3600 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
3601 llvm_unreachable("Incomplete array should not occur in deduced return type "
3602 "of a function");
3603 }
3604
3605 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
3606 llvm_unreachable("Dependent array should not occur in deduced return type "
3607 "of a function");
3608 }
3609
3610private:
3611 const DeclContext *const ParentDC;
3612
3613 bool checkTemplateArgument(const TemplateArgument &Arg) {
3614 switch (Arg.getKind()) {
3615 case TemplateArgument::Null:
3616 return false;
3617 case TemplateArgument::Integral:
3618 return CheckType(T: Arg.getIntegralType());
3619 case TemplateArgument::Type:
3620 return CheckType(T: Arg.getAsType());
3621 case TemplateArgument::Expression:
3622 return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr());
3623 case TemplateArgument::Declaration:
3624 // FIXME: The declaration in this case is not allowed to be in a function?
3625 return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl());
3626 case TemplateArgument::NullPtr:
3627 // FIXME: The type is not allowed to be in the function?
3628 return CheckType(T: Arg.getNullPtrType());
3629 case TemplateArgument::StructuralValue:
3630 return CheckType(T: Arg.getStructuralValueType());
3631 case TemplateArgument::Pack:
3632 for (const auto &PackArg : Arg.getPackAsArray())
3633 if (checkTemplateArgument(Arg: PackArg))
3634 return true;
3635 return false;
3636 case TemplateArgument::Template:
3637 // Templates can not be defined locally in functions.
3638 // A template passed as argument can be not in ParentDC.
3639 return false;
3640 case TemplateArgument::TemplateExpansion:
3641 // Templates can not be defined locally in functions.
3642 // A template passed as argument can be not in ParentDC.
3643 return false;
3644 }
3645 llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
3646 };
3647};
3648} // namespace
3649
3650/// This function checks if the given function has a return type that contains
3651/// a reference (in any way) to a declaration inside the same function.
3652bool ASTNodeImporter::hasReturnTypeDeclaredInside(FunctionDecl *D) {
3653 QualType FromTy = D->getType();
3654 const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3655 assert(FromFPT && "Must be called on FunctionProtoType");
3656
3657 auto IsCXX11LambdaWithouTrailingReturn = [&]() {
3658 if (Importer.FromContext.getLangOpts().CPlusPlus14) // C++14 or later
3659 return false;
3660
3661 if (FromFPT->hasTrailingReturn())
3662 return false;
3663
3664 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3665 return cast<CXXRecordDecl>(MD->getDeclContext())->isLambda();
3666
3667 return false;
3668 };
3669
3670 QualType RetT = FromFPT->getReturnType();
3671 if (isa<AutoType>(Val: RetT.getTypePtr()) || IsCXX11LambdaWithouTrailingReturn()) {
3672 FunctionDecl *Def = D->getDefinition();
3673 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
3674 return Visitor.CheckType(T: RetT);
3675 }
3676
3677 return false;
3678}
3679
3680ExplicitSpecifier
3681ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3682 Expr *ExplicitExpr = ESpec.getExpr();
3683 if (ExplicitExpr)
3684 ExplicitExpr = importChecked(Err, From: ESpec.getExpr());
3685 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3686}
3687
3688ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3689
3690 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3691 auto RedeclIt = Redecls.begin();
3692 // Import the first part of the decl chain. I.e. import all previous
3693 // declarations starting from the canonical decl.
3694 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3695 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3696 if (!ToRedeclOrErr)
3697 return ToRedeclOrErr.takeError();
3698 }
3699 assert(*RedeclIt == D);
3700
3701 // Import the major distinguishing characteristics of this function.
3702 DeclContext *DC, *LexicalDC;
3703 DeclarationName Name;
3704 SourceLocation Loc;
3705 NamedDecl *ToD;
3706 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3707 return std::move(Err);
3708 if (ToD)
3709 return ToD;
3710
3711 FunctionDecl *FoundByLookup = nullptr;
3712 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3713
3714 // If this is a function template specialization, then try to find the same
3715 // existing specialization in the "to" context. The lookup below will not
3716 // find any specialization, but would find the primary template; thus, we
3717 // have to skip normal lookup in case of specializations.
3718 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3719 if (D->getTemplatedKind() ==
3720 FunctionDecl::TK_FunctionTemplateSpecialization) {
3721 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(FromFD: D);
3722 if (!FoundFunctionOrErr)
3723 return FoundFunctionOrErr.takeError();
3724 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3725 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3726 return Def;
3727 FoundByLookup = FoundFunction;
3728 }
3729 }
3730 // Try to find a function in our own ("to") context with the same name, same
3731 // type, and in the same context as the function we're importing.
3732 else if (!LexicalDC->isFunctionOrMethod()) {
3733 SmallVector<NamedDecl *, 4> ConflictingDecls;
3734 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3735 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3736 for (auto *FoundDecl : FoundDecls) {
3737 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3738 continue;
3739
3740 if (auto *FoundFunction = dyn_cast<FunctionDecl>(Val: FoundDecl)) {
3741 if (!hasSameVisibilityContextAndLinkage(Found: FoundFunction, From: D))
3742 continue;
3743
3744 if (IsStructuralMatch(D, FoundFunction)) {
3745 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3746 return Def;
3747 FoundByLookup = FoundFunction;
3748 break;
3749 }
3750 // FIXME: Check for overloading more carefully, e.g., by boosting
3751 // Sema::IsOverload out to the AST library.
3752
3753 // Function overloading is okay in C++.
3754 if (Importer.getToContext().getLangOpts().CPlusPlus)
3755 continue;
3756
3757 // Complain about inconsistent function types.
3758 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3759 << Name << D->getType() << FoundFunction->getType();
3760 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3761 << FoundFunction->getType();
3762 ConflictingDecls.push_back(Elt: FoundDecl);
3763 }
3764 }
3765
3766 if (!ConflictingDecls.empty()) {
3767 ExpectedName NameOrErr = Importer.HandleNameConflict(
3768 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
3769 if (NameOrErr)
3770 Name = NameOrErr.get();
3771 else
3772 return NameOrErr.takeError();
3773 }
3774 }
3775
3776 // We do not allow more than one in-class declaration of a function. This is
3777 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3778 // assumes there is only one in-class declaration. Building a redecl
3779 // chain would result in more than one in-class declaration for
3780 // overrides (even if they are part of the same redecl chain inside the
3781 // derived class.)
3782 if (FoundByLookup) {
3783 if (isa<CXXMethodDecl>(Val: FoundByLookup)) {
3784 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3785 if (!D->doesThisDeclarationHaveABody()) {
3786 if (FunctionTemplateDecl *DescribedD =
3787 D->getDescribedFunctionTemplate()) {
3788 // Handle a "templated" function together with its described
3789 // template. This avoids need for a similar check at import of the
3790 // described template.
3791 assert(FoundByLookup->getDescribedFunctionTemplate() &&
3792 "Templated function mapped to non-templated?");
3793 Importer.MapImported(DescribedD,
3794 FoundByLookup->getDescribedFunctionTemplate());
3795 }
3796 return Importer.MapImported(D, FoundByLookup);
3797 } else {
3798 // Let's continue and build up the redecl chain in this case.
3799 // FIXME Merge the functions into one decl.
3800 }
3801 }
3802 }
3803 }
3804
3805 DeclarationNameInfo NameInfo(Name, Loc);
3806 // Import additional name location/type info.
3807 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
3808 return std::move(Err);
3809
3810 QualType FromTy = D->getType();
3811 TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3812 // Set to true if we do not import the type of the function as is. There are
3813 // cases when the original type would result in an infinite recursion during
3814 // the import. To avoid an infinite recursion when importing, we create the
3815 // FunctionDecl with a simplified function type and update it only after the
3816 // relevant AST nodes are already imported.
3817 // The type is related to TypeSourceInfo (it references the type), so we must
3818 // do the same with TypeSourceInfo.
3819 bool UsedDifferentProtoType = false;
3820 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3821 QualType FromReturnTy = FromFPT->getReturnType();
3822 // Functions with auto return type may define a struct inside their body
3823 // and the return type could refer to that struct.
3824 // E.g.: auto foo() { struct X{}; return X(); }
3825 // To avoid an infinite recursion when importing, create the FunctionDecl
3826 // with a simplified return type.
3827 if (hasReturnTypeDeclaredInside(D)) {
3828 FromReturnTy = Importer.getFromContext().VoidTy;
3829 UsedDifferentProtoType = true;
3830 }
3831 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3832 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3833 // FunctionDecl that we are importing the FunctionProtoType for.
3834 // To avoid an infinite recursion when importing, create the FunctionDecl
3835 // with a simplified function type.
3836 if (FromEPI.ExceptionSpec.SourceDecl ||
3837 FromEPI.ExceptionSpec.SourceTemplate ||
3838 FromEPI.ExceptionSpec.NoexceptExpr) {
3839 FunctionProtoType::ExtProtoInfo DefaultEPI;
3840 FromEPI = DefaultEPI;
3841 UsedDifferentProtoType = true;
3842 }
3843 FromTy = Importer.getFromContext().getFunctionType(
3844 ResultTy: FromReturnTy, Args: FromFPT->getParamTypes(), EPI: FromEPI);
3845 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3846 T: FromTy, Loc: D->getBeginLoc());
3847 }
3848
3849 Error Err = Error::success();
3850 auto T = importChecked(Err, From: FromTy);
3851 auto TInfo = importChecked(Err, From: FromTSI);
3852 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3853 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3854 auto ToDefaultLoc = importChecked(Err, From: D->getDefaultLoc());
3855 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3856 auto TrailingRequiresClause =
3857 importChecked(Err, D->getTrailingRequiresClause());
3858 if (Err)
3859 return std::move(Err);
3860
3861 // Import the function parameters.
3862 SmallVector<ParmVarDecl *, 8> Parameters;
3863 for (auto *P : D->parameters()) {
3864 if (Expected<ParmVarDecl *> ToPOrErr = import(From: P))
3865 Parameters.push_back(Elt: *ToPOrErr);
3866 else
3867 return ToPOrErr.takeError();
3868 }
3869
3870 // Create the imported function.
3871 FunctionDecl *ToFunction = nullptr;
3872 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
3873 ExplicitSpecifier ESpec =
3874 importExplicitSpecifier(Err, ESpec: FromConstructor->getExplicitSpecifier());
3875 if (Err)
3876 return std::move(Err);
3877 auto ToInheritedConstructor = InheritedConstructor();
3878 if (FromConstructor->isInheritingConstructor()) {
3879 Expected<InheritedConstructor> ImportedInheritedCtor =
3880 import(From: FromConstructor->getInheritedConstructor());
3881 if (!ImportedInheritedCtor)
3882 return ImportedInheritedCtor.takeError();
3883 ToInheritedConstructor = *ImportedInheritedCtor;
3884 }
3885 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3886 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(Val: DC),
3887 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3888 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3889 ToInheritedConstructor, TrailingRequiresClause))
3890 return ToFunction;
3891 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(Val: D)) {
3892
3893 Error Err = Error::success();
3894 auto ToOperatorDelete = importChecked(
3895 Err, From: const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3896 auto ToThisArg = importChecked(Err, From: FromDtor->getOperatorDeleteThisArg());
3897 if (Err)
3898 return std::move(Err);
3899
3900 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3901 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(Val: DC),
3902 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3903 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3904 TrailingRequiresClause))
3905 return ToFunction;
3906
3907 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(Val: ToFunction);
3908
3909 ToDtor->setOperatorDelete(OD: ToOperatorDelete, ThisArg: ToThisArg);
3910 } else if (CXXConversionDecl *FromConversion =
3911 dyn_cast<CXXConversionDecl>(Val: D)) {
3912 ExplicitSpecifier ESpec =
3913 importExplicitSpecifier(Err, ESpec: FromConversion->getExplicitSpecifier());
3914 if (Err)
3915 return std::move(Err);
3916 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3917 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(Val: DC),
3918 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3919 D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3920 SourceLocation(), TrailingRequiresClause))
3921 return ToFunction;
3922 } else if (auto *Method = dyn_cast<CXXMethodDecl>(Val: D)) {
3923 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3924 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(Val: DC),
3925 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3926 Method->UsesFPIntrin(), Method->isInlineSpecified(),
3927 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3928 return ToFunction;
3929 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(Val: D)) {
3930 ExplicitSpecifier ESpec =
3931 importExplicitSpecifier(Err, ESpec: Guide->getExplicitSpecifier());
3932 CXXConstructorDecl *Ctor =
3933 importChecked(Err, From: Guide->getCorrespondingConstructor());
3934 if (Err)
3935 return std::move(Err);
3936 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3937 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3938 NameInfo, T, TInfo, ToEndLoc, Ctor))
3939 return ToFunction;
3940 cast<CXXDeductionGuideDecl>(Val: ToFunction)
3941 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind());
3942 } else {
3943 if (GetImportedOrCreateDecl(
3944 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3945 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3946 D->isInlineSpecified(), D->hasWrittenPrototype(),
3947 D->getConstexprKind(), TrailingRequiresClause))
3948 return ToFunction;
3949 }
3950
3951 // Connect the redecl chain.
3952 if (FoundByLookup) {
3953 auto *Recent = const_cast<FunctionDecl *>(
3954 FoundByLookup->getMostRecentDecl());
3955 ToFunction->setPreviousDecl(Recent);
3956 // FIXME Probably we should merge exception specifications. E.g. In the
3957 // "To" context the existing function may have exception specification with
3958 // noexcept-unevaluated, while the newly imported function may have an
3959 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3960 // decl and its redeclarations may be required.
3961 }
3962
3963 StringLiteral *Msg = D->getDeletedMessage();
3964 if (Msg) {
3965 auto Imported = import(From: Msg);
3966 if (!Imported)
3967 return Imported.takeError();
3968 Msg = *Imported;
3969 }
3970
3971 ToFunction->setQualifierInfo(ToQualifierLoc);
3972 ToFunction->setAccess(D->getAccess());
3973 ToFunction->setLexicalDeclContext(LexicalDC);
3974 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3975 ToFunction->setTrivial(D->isTrivial());
3976 ToFunction->setIsPureVirtual(D->isPureVirtual());
3977 ToFunction->setDefaulted(D->isDefaulted());
3978 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3979 ToFunction->setDeletedAsWritten(D: D->isDeletedAsWritten());
3980 ToFunction->setFriendConstraintRefersToEnclosingTemplate(
3981 D->FriendConstraintRefersToEnclosingTemplate());
3982 ToFunction->setRangeEnd(ToEndLoc);
3983 ToFunction->setDefaultLoc(ToDefaultLoc);
3984
3985 if (Msg)
3986 ToFunction->setDefaultedOrDeletedInfo(
3987 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
3988 Context&: Importer.getToContext(), Lookups: {}, DeletedMessage: Msg));
3989
3990 // Set the parameters.
3991 for (auto *Param : Parameters) {
3992 Param->setOwningFunction(ToFunction);
3993 ToFunction->addDeclInternal(Param);
3994 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3995 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3996 }
3997 ToFunction->setParams(Parameters);
3998
3999 // We need to complete creation of FunctionProtoTypeLoc manually with setting
4000 // params it refers to.
4001 if (TInfo) {
4002 if (auto ProtoLoc =
4003 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
4004 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
4005 ProtoLoc.setParam(I, Parameters[I]);
4006 }
4007 }
4008
4009 // Import the describing template function, if any.
4010 if (FromFT) {
4011 auto ToFTOrErr = import(From: FromFT);
4012 if (!ToFTOrErr)
4013 return ToFTOrErr.takeError();
4014 }
4015
4016 // Import Ctor initializers.
4017 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(Val: D)) {
4018 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
4019 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
4020 // Import first, then allocate memory and copy if there was no error.
4021 if (Error Err = ImportContainerChecked(
4022 InContainer: FromConstructor->inits(), OutContainer&: CtorInitializers))
4023 return std::move(Err);
4024 auto **Memory =
4025 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
4026 std::copy(first: CtorInitializers.begin(), last: CtorInitializers.end(), result: Memory);
4027 auto *ToCtor = cast<CXXConstructorDecl>(Val: ToFunction);
4028 ToCtor->setCtorInitializers(Memory);
4029 ToCtor->setNumCtorInitializers(NumInitializers);
4030 }
4031 }
4032
4033 // If it is a template, import all related things.
4034 if (Error Err = ImportTemplateInformation(FromFD: D, ToFD: ToFunction))
4035 return std::move(Err);
4036
4037 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(Val: D))
4038 if (Error Err = ImportOverriddenMethods(ToMethod: cast<CXXMethodDecl>(Val: ToFunction),
4039 FromMethod: FromCXXMethod))
4040 return std::move(Err);
4041
4042 if (D->doesThisDeclarationHaveABody()) {
4043 Error Err = ImportFunctionDeclBody(FromFD: D, ToFD: ToFunction);
4044
4045 if (Err)
4046 return std::move(Err);
4047 }
4048
4049 // Import and set the original type in case we used another type.
4050 if (UsedDifferentProtoType) {
4051 if (ExpectedType TyOrErr = import(D->getType()))
4052 ToFunction->setType(*TyOrErr);
4053 else
4054 return TyOrErr.takeError();
4055 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
4056 ToFunction->setTypeSourceInfo(*TSIOrErr);
4057 else
4058 return TSIOrErr.takeError();
4059 }
4060
4061 // FIXME: Other bits to merge?
4062
4063 addDeclToContexts(D, ToFunction);
4064
4065 // Import the rest of the chain. I.e. import all subsequent declarations.
4066 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4067 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
4068 if (!ToRedeclOrErr)
4069 return ToRedeclOrErr.takeError();
4070 }
4071
4072 return ToFunction;
4073}
4074
4075ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
4076 return VisitFunctionDecl(D);
4077}
4078
4079ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
4080 return VisitCXXMethodDecl(D);
4081}
4082
4083ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
4084 return VisitCXXMethodDecl(D);
4085}
4086
4087ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
4088 return VisitCXXMethodDecl(D);
4089}
4090
4091ExpectedDecl
4092ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
4093 return VisitFunctionDecl(D);
4094}
4095
4096ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
4097 // Import the major distinguishing characteristics of a variable.
4098 DeclContext *DC, *LexicalDC;
4099 DeclarationName Name;
4100 SourceLocation Loc;
4101 NamedDecl *ToD;
4102 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4103 return std::move(Err);
4104 if (ToD)
4105 return ToD;
4106
4107 // Determine whether we've already imported this field.
4108 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4109 for (auto *FoundDecl : FoundDecls) {
4110 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(Val: FoundDecl)) {
4111 // For anonymous fields, match up by index.
4112 if (!Name &&
4113 ASTImporter::getFieldIndex(D) !=
4114 ASTImporter::getFieldIndex(FoundField))
4115 continue;
4116
4117 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4118 To: FoundField->getType())) {
4119 Importer.MapImported(D, FoundField);
4120 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
4121 // initializer of a FieldDecl might not had been instantiated in the
4122 // "To" context. However, the "From" context might instantiated that,
4123 // thus we have to merge that.
4124 // Note: `hasInClassInitializer()` is not the same as non-null
4125 // `getInClassInitializer()` value.
4126 if (Expr *FromInitializer = D->getInClassInitializer()) {
4127 if (ExpectedExpr ToInitializerOrErr = import(From: FromInitializer)) {
4128 // Import of the FromInitializer may result in the setting of
4129 // InClassInitializer. If not, set it here.
4130 assert(FoundField->hasInClassInitializer() &&
4131 "Field should have an in-class initializer if it has an "
4132 "expression for it.");
4133 if (!FoundField->getInClassInitializer())
4134 FoundField->setInClassInitializer(*ToInitializerOrErr);
4135 } else {
4136 return ToInitializerOrErr.takeError();
4137 }
4138 }
4139 return FoundField;
4140 }
4141
4142 // FIXME: Why is this case not handled with calling HandleNameConflict?
4143 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4144 << Name << D->getType() << FoundField->getType();
4145 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4146 << FoundField->getType();
4147
4148 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4149 }
4150 }
4151
4152 Error Err = Error::success();
4153 auto ToType = importChecked(Err, D->getType());
4154 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
4155 auto ToBitWidth = importChecked(Err, From: D->getBitWidth());
4156 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4157 if (Err)
4158 return std::move(Err);
4159 const Type *ToCapturedVLAType = nullptr;
4160 if (Error Err = Importer.importInto(
4161 To&: ToCapturedVLAType, From: cast_or_null<Type>(Val: D->getCapturedVLAType())))
4162 return std::move(Err);
4163
4164 FieldDecl *ToField;
4165 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
4166 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4167 ToType, ToTInfo, ToBitWidth, D->isMutable(),
4168 D->getInClassInitStyle()))
4169 return ToField;
4170
4171 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before
4172 // we add fields in CXXRecordDecl::addedMember, otherwise record will be
4173 // marked as having non-zero size.
4174 Err = Importer.ImportAttrs(ToField, D);
4175 if (Err)
4176 return std::move(Err);
4177 ToField->setAccess(D->getAccess());
4178 ToField->setLexicalDeclContext(LexicalDC);
4179 ToField->setImplicit(D->isImplicit());
4180 if (ToCapturedVLAType)
4181 ToField->setCapturedVLAType(cast<VariableArrayType>(Val: ToCapturedVLAType));
4182 LexicalDC->addDeclInternal(ToField);
4183 // Import initializer only after the field was created, it may have recursive
4184 // reference to the field.
4185 auto ToInitializer = importChecked(Err, From: D->getInClassInitializer());
4186 if (Err)
4187 return std::move(Err);
4188 if (ToInitializer) {
4189 auto *AlreadyImported = ToField->getInClassInitializer();
4190 if (AlreadyImported)
4191 assert(ToInitializer == AlreadyImported &&
4192 "Duplicate import of in-class initializer.");
4193 else
4194 ToField->setInClassInitializer(ToInitializer);
4195 }
4196
4197 return ToField;
4198}
4199
4200ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
4201 // Import the major distinguishing characteristics of a variable.
4202 DeclContext *DC, *LexicalDC;
4203 DeclarationName Name;
4204 SourceLocation Loc;
4205 NamedDecl *ToD;
4206 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4207 return std::move(Err);
4208 if (ToD)
4209 return ToD;
4210
4211 // Determine whether we've already imported this field.
4212 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4213 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4214 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(Val: FoundDecls[I])) {
4215 // For anonymous indirect fields, match up by index.
4216 if (!Name &&
4217 ASTImporter::getFieldIndex(D) !=
4218 ASTImporter::getFieldIndex(FoundField))
4219 continue;
4220
4221 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4222 To: FoundField->getType(),
4223 Complain: !Name.isEmpty())) {
4224 Importer.MapImported(D, FoundField);
4225 return FoundField;
4226 }
4227
4228 // If there are more anonymous fields to check, continue.
4229 if (!Name && I < N-1)
4230 continue;
4231
4232 // FIXME: Why is this case not handled with calling HandleNameConflict?
4233 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4234 << Name << D->getType() << FoundField->getType();
4235 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4236 << FoundField->getType();
4237
4238 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4239 }
4240 }
4241
4242 // Import the type.
4243 auto TypeOrErr = import(D->getType());
4244 if (!TypeOrErr)
4245 return TypeOrErr.takeError();
4246
4247 auto **NamedChain =
4248 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
4249
4250 unsigned i = 0;
4251 for (auto *PI : D->chain())
4252 if (Expected<NamedDecl *> ToD = import(From: PI))
4253 NamedChain[i++] = *ToD;
4254 else
4255 return ToD.takeError();
4256
4257 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
4258 IndirectFieldDecl *ToIndirectField;
4259 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
4260 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
4261 // FIXME here we leak `NamedChain` which is allocated before
4262 return ToIndirectField;
4263
4264 ToIndirectField->setAccess(D->getAccess());
4265 ToIndirectField->setLexicalDeclContext(LexicalDC);
4266 LexicalDC->addDeclInternal(ToIndirectField);
4267 return ToIndirectField;
4268}
4269
4270/// Used as return type of getFriendCountAndPosition.
4271struct FriendCountAndPosition {
4272 /// Number of similar looking friends.
4273 unsigned int TotalCount;
4274 /// Index of the specific FriendDecl.
4275 unsigned int IndexOfDecl;
4276};
4277
4278static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1,
4279 FriendDecl *FD2) {
4280 if ((!FD1->getFriendType()) != (!FD2->getFriendType()))
4281 return false;
4282
4283 if (const TypeSourceInfo *TSI = FD1->getFriendType())
4284 return Importer.IsStructurallyEquivalent(
4285 From: TSI->getType(), To: FD2->getFriendType()->getType(), /*Complain=*/false);
4286
4287 ASTImporter::NonEquivalentDeclSet NonEquivalentDecls;
4288 StructuralEquivalenceContext Ctx(
4289 FD1->getASTContext(), FD2->getASTContext(), NonEquivalentDecls,
4290 StructuralEquivalenceKind::Default,
4291 /* StrictTypeSpelling = */ false, /* Complain = */ false);
4292 return Ctx.IsEquivalent(FD1, FD2);
4293}
4294
4295static FriendCountAndPosition getFriendCountAndPosition(ASTImporter &Importer,
4296 FriendDecl *FD) {
4297 unsigned int FriendCount = 0;
4298 std::optional<unsigned int> FriendPosition;
4299 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
4300
4301 for (FriendDecl *FoundFriend : RD->friends()) {
4302 if (FoundFriend == FD) {
4303 FriendPosition = FriendCount;
4304 ++FriendCount;
4305 } else if (IsEquivalentFriend(Importer, FD, FoundFriend)) {
4306 ++FriendCount;
4307 }
4308 }
4309
4310 assert(FriendPosition && "Friend decl not found in own parent.");
4311
4312 return {.TotalCount: FriendCount, .IndexOfDecl: *FriendPosition};
4313}
4314
4315ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
4316 // Import the major distinguishing characteristics of a declaration.
4317 DeclContext *DC, *LexicalDC;
4318 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4319 return std::move(Err);
4320
4321 // Determine whether we've already imported this decl.
4322 // FriendDecl is not a NamedDecl so we cannot use lookup.
4323 // We try to maintain order and count of redundant friend declarations.
4324 const auto *RD = cast<CXXRecordDecl>(Val: DC);
4325 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
4326 for (FriendDecl *ImportedFriend : RD->friends())
4327 if (IsEquivalentFriend(Importer, FD1: D, FD2: ImportedFriend))
4328 ImportedEquivalentFriends.push_back(Elt: ImportedFriend);
4329
4330 FriendCountAndPosition CountAndPosition =
4331 getFriendCountAndPosition(Importer, FD: D);
4332
4333 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
4334 "Class with non-matching friends is imported, ODR check wrong?");
4335 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
4336 return Importer.MapImported(
4337 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
4338
4339 // Not found. Create it.
4340 // The declarations will be put into order later by ImportDeclContext.
4341 FriendDecl::FriendUnion ToFU;
4342 if (NamedDecl *FriendD = D->getFriendDecl()) {
4343 NamedDecl *ToFriendD;
4344 if (Error Err = importInto(To&: ToFriendD, From: FriendD))
4345 return std::move(Err);
4346
4347 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
4348 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
4349 ToFriendD->setObjectOfFriendDecl(false);
4350
4351 ToFU = ToFriendD;
4352 } else { // The friend is a type, not a decl.
4353 if (auto TSIOrErr = import(From: D->getFriendType()))
4354 ToFU = *TSIOrErr;
4355 else
4356 return TSIOrErr.takeError();
4357 }
4358
4359 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
4360 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
4361 for (unsigned I = 0; I < D->NumTPLists; I++) {
4362 if (auto ListOrErr = import(FromTPLists[I]))
4363 ToTPLists[I] = *ListOrErr;
4364 else
4365 return ListOrErr.takeError();
4366 }
4367
4368 auto LocationOrErr = import(D->getLocation());
4369 if (!LocationOrErr)
4370 return LocationOrErr.takeError();
4371 auto FriendLocOrErr = import(From: D->getFriendLoc());
4372 if (!FriendLocOrErr)
4373 return FriendLocOrErr.takeError();
4374
4375 FriendDecl *FrD;
4376 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
4377 *LocationOrErr, ToFU,
4378 *FriendLocOrErr, ToTPLists))
4379 return FrD;
4380
4381 FrD->setAccess(D->getAccess());
4382 FrD->setLexicalDeclContext(LexicalDC);
4383 LexicalDC->addDeclInternal(FrD);
4384 return FrD;
4385}
4386
4387ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
4388 // Import the major distinguishing characteristics of an ivar.
4389 DeclContext *DC, *LexicalDC;
4390 DeclarationName Name;
4391 SourceLocation Loc;
4392 NamedDecl *ToD;
4393 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4394 return std::move(Err);
4395 if (ToD)
4396 return ToD;
4397
4398 // Determine whether we've already imported this ivar
4399 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4400 for (auto *FoundDecl : FoundDecls) {
4401 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(Val: FoundDecl)) {
4402 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4403 To: FoundIvar->getType())) {
4404 Importer.MapImported(D, FoundIvar);
4405 return FoundIvar;
4406 }
4407
4408 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
4409 << Name << D->getType() << FoundIvar->getType();
4410 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
4411 << FoundIvar->getType();
4412
4413 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4414 }
4415 }
4416
4417 Error Err = Error::success();
4418 auto ToType = importChecked(Err, D->getType());
4419 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4420 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4421 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4422 if (Err)
4423 return std::move(Err);
4424
4425 ObjCIvarDecl *ToIvar;
4426 if (GetImportedOrCreateDecl(
4427 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(Val: DC),
4428 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4429 ToType, ToTypeSourceInfo,
4430 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
4431 return ToIvar;
4432
4433 ToIvar->setLexicalDeclContext(LexicalDC);
4434 LexicalDC->addDeclInternal(ToIvar);
4435 return ToIvar;
4436}
4437
4438ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
4439
4440 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
4441 auto RedeclIt = Redecls.begin();
4442 // Import the first part of the decl chain. I.e. import all previous
4443 // declarations starting from the canonical decl.
4444 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4445 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4446 if (!RedeclOrErr)
4447 return RedeclOrErr.takeError();
4448 }
4449 assert(*RedeclIt == D);
4450
4451 // Import the major distinguishing characteristics of a variable.
4452 DeclContext *DC, *LexicalDC;
4453 DeclarationName Name;
4454 SourceLocation Loc;
4455 NamedDecl *ToD;
4456 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4457 return std::move(Err);
4458 if (ToD)
4459 return ToD;
4460
4461 // Try to find a variable in our own ("to") context with the same name and
4462 // in the same context as the variable we're importing.
4463 VarDecl *FoundByLookup = nullptr;
4464 if (D->isFileVarDecl()) {
4465 SmallVector<NamedDecl *, 4> ConflictingDecls;
4466 unsigned IDNS = Decl::IDNS_Ordinary;
4467 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4468 for (auto *FoundDecl : FoundDecls) {
4469 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4470 continue;
4471
4472 if (auto *FoundVar = dyn_cast<VarDecl>(Val: FoundDecl)) {
4473 if (!hasSameVisibilityContextAndLinkage(Found: FoundVar, From: D))
4474 continue;
4475 if (Importer.IsStructurallyEquivalent(From: D->getType(),
4476 To: FoundVar->getType())) {
4477
4478 // The VarDecl in the "From" context has a definition, but in the
4479 // "To" context we already have a definition.
4480 VarDecl *FoundDef = FoundVar->getDefinition();
4481 if (D->isThisDeclarationADefinition() && FoundDef)
4482 // FIXME Check for ODR error if the two definitions have
4483 // different initializers?
4484 return Importer.MapImported(D, FoundDef);
4485
4486 // The VarDecl in the "From" context has an initializer, but in the
4487 // "To" context we already have an initializer.
4488 const VarDecl *FoundDInit = nullptr;
4489 if (D->getInit() && FoundVar->getAnyInitializer(D&: FoundDInit))
4490 // FIXME Diagnose ODR error if the two initializers are different?
4491 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4492
4493 FoundByLookup = FoundVar;
4494 break;
4495 }
4496
4497 const ArrayType *FoundArray
4498 = Importer.getToContext().getAsArrayType(T: FoundVar->getType());
4499 const ArrayType *TArray
4500 = Importer.getToContext().getAsArrayType(T: D->getType());
4501 if (FoundArray && TArray) {
4502 if (isa<IncompleteArrayType>(Val: FoundArray) &&
4503 isa<ConstantArrayType>(Val: TArray)) {
4504 // Import the type.
4505 if (auto TyOrErr = import(D->getType()))
4506 FoundVar->setType(*TyOrErr);
4507 else
4508 return TyOrErr.takeError();
4509
4510 FoundByLookup = FoundVar;
4511 break;
4512 } else if (isa<IncompleteArrayType>(Val: TArray) &&
4513 isa<ConstantArrayType>(Val: FoundArray)) {
4514 FoundByLookup = FoundVar;
4515 break;
4516 }
4517 }
4518
4519 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4520 << Name << D->getType() << FoundVar->getType();
4521 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4522 << FoundVar->getType();
4523 ConflictingDecls.push_back(Elt: FoundDecl);
4524 }
4525 }
4526
4527 if (!ConflictingDecls.empty()) {
4528 ExpectedName NameOrErr = Importer.HandleNameConflict(
4529 Name, DC, IDNS, Decls: ConflictingDecls.data(), NumDecls: ConflictingDecls.size());
4530 if (NameOrErr)
4531 Name = NameOrErr.get();
4532 else
4533 return NameOrErr.takeError();
4534 }
4535 }
4536
4537 Error Err = Error::success();
4538 auto ToType = importChecked(Err, D->getType());
4539 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4540 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4541 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4542 if (Err)
4543 return std::move(Err);
4544
4545 VarDecl *ToVar;
4546 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(Val: D)) {
4547 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4548 if (Error Err =
4549 ImportArrayChecked(InContainer: FromDecomp->bindings(), Obegin: Bindings.begin()))
4550 return std::move(Err);
4551 DecompositionDecl *ToDecomp;
4552 if (GetImportedOrCreateDecl(
4553 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4554 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4555 return ToDecomp;
4556 ToVar = ToDecomp;
4557 } else {
4558 // Create the imported variable.
4559 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4560 ToInnerLocStart, Loc,
4561 Name.getAsIdentifierInfo(), ToType,
4562 ToTypeSourceInfo, D->getStorageClass()))
4563 return ToVar;
4564 }
4565
4566 ToVar->setTSCSpec(D->getTSCSpec());
4567 ToVar->setQualifierInfo(ToQualifierLoc);
4568 ToVar->setAccess(D->getAccess());
4569 ToVar->setLexicalDeclContext(LexicalDC);
4570 if (D->isInlineSpecified())
4571 ToVar->setInlineSpecified();
4572 if (D->isInline())
4573 ToVar->setImplicitlyInline();
4574
4575 if (FoundByLookup) {
4576 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4577 ToVar->setPreviousDecl(Recent);
4578 }
4579
4580 // Import the described template, if any.
4581 if (D->getDescribedVarTemplate()) {
4582 auto ToVTOrErr = import(From: D->getDescribedVarTemplate());
4583 if (!ToVTOrErr)
4584 return ToVTOrErr.takeError();
4585 } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) {
4586 TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
4587 VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
4588 if (Expected<VarDecl *> ToInstOrErr = import(From: FromInst))
4589 ToVar->setInstantiationOfStaticDataMember(VD: *ToInstOrErr, TSK: SK);
4590 else
4591 return ToInstOrErr.takeError();
4592 if (ExpectedSLoc POIOrErr = import(From: MSI->getPointOfInstantiation()))
4593 ToVar->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
4594 else
4595 return POIOrErr.takeError();
4596 }
4597
4598 if (Error Err = ImportInitializer(From: D, To: ToVar))
4599 return std::move(Err);
4600
4601 if (D->isConstexpr())
4602 ToVar->setConstexpr(true);
4603
4604 addDeclToContexts(D, ToVar);
4605
4606 // Import the rest of the chain. I.e. import all subsequent declarations.
4607 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4608 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4609 if (!RedeclOrErr)
4610 return RedeclOrErr.takeError();
4611 }
4612
4613 return ToVar;
4614}
4615
4616ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4617 // Parameters are created in the translation unit's context, then moved
4618 // into the function declaration's context afterward.
4619 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4620
4621 Error Err = Error::success();
4622 auto ToDeclName = importChecked(Err, D->getDeclName());
4623 auto ToLocation = importChecked(Err, D->getLocation());
4624 auto ToType = importChecked(Err, D->getType());
4625 if (Err)
4626 return std::move(Err);
4627
4628 // Create the imported parameter.
4629 ImplicitParamDecl *ToParm = nullptr;
4630 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4631 ToLocation, ToDeclName.getAsIdentifierInfo(),
4632 ToType, D->getParameterKind()))
4633 return ToParm;
4634 return ToParm;
4635}
4636
4637Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4638 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4639 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4640 ToParam->setExplicitObjectParameterLoc(
4641 FromParam->getExplicitObjectParamThisLoc());
4642 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4643
4644 if (FromParam->hasUninstantiatedDefaultArg()) {
4645 if (auto ToDefArgOrErr = import(From: FromParam->getUninstantiatedDefaultArg()))
4646 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4647 else
4648 return ToDefArgOrErr.takeError();
4649 } else if (FromParam->hasUnparsedDefaultArg()) {
4650 ToParam->setUnparsedDefaultArg();
4651 } else if (FromParam->hasDefaultArg()) {
4652 if (auto ToDefArgOrErr = import(From: FromParam->getDefaultArg()))
4653 ToParam->setDefaultArg(*ToDefArgOrErr);
4654 else
4655 return ToDefArgOrErr.takeError();
4656 }
4657
4658 return Error::success();
4659}
4660
4661Expected<InheritedConstructor>
4662ASTNodeImporter::ImportInheritedConstructor(const InheritedConstructor &From) {
4663 Error Err = Error::success();
4664 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From: From.getConstructor());
4665 ConstructorUsingShadowDecl *ToShadow =
4666 importChecked(Err, From: From.getShadowDecl());
4667 if (Err)
4668 return std::move(Err);
4669 return InheritedConstructor(ToShadow, ToBaseCtor);
4670}
4671
4672ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4673 // Parameters are created in the translation unit's context, then moved
4674 // into the function declaration's context afterward.
4675 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4676
4677 Error Err = Error::success();
4678 auto ToDeclName = importChecked(Err, D->getDeclName());
4679 auto ToLocation = importChecked(Err, D->getLocation());
4680 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4681 auto ToType = importChecked(Err, D->getType());
4682 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4683 if (Err)
4684 return std::move(Err);
4685
4686 ParmVarDecl *ToParm;
4687 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4688 ToInnerLocStart, ToLocation,
4689 ToDeclName.getAsIdentifierInfo(), ToType,
4690 ToTypeSourceInfo, D->getStorageClass(),
4691 /*DefaultArg*/ nullptr))
4692 return ToParm;
4693
4694 // Set the default argument. It should be no problem if it was already done.
4695 // Do not import the default expression before GetImportedOrCreateDecl call
4696 // to avoid possible infinite import loop because circular dependency.
4697 if (Error Err = ImportDefaultArgOfParmVarDecl(FromParam: D, ToParam: ToParm))
4698 return std::move(Err);
4699
4700 if (D->isObjCMethodParameter()) {
4701 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4702 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4703 } else {
4704 ToParm->setScopeInfo(scopeDepth: D->getFunctionScopeDepth(),
4705 parameterIndex: D->getFunctionScopeIndex());
4706 }
4707
4708 return ToParm;
4709}
4710
4711ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4712 // Import the major distinguishing characteristics of a method.
4713 DeclContext *DC, *LexicalDC;
4714 DeclarationName Name;
4715 SourceLocation Loc;
4716 NamedDecl *ToD;
4717 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4718 return std::move(Err);
4719 if (ToD)
4720 return ToD;
4721
4722 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4723 for (auto *FoundDecl : FoundDecls) {
4724 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(Val: FoundDecl)) {
4725 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4726 continue;
4727
4728 // Check return types.
4729 if (!Importer.IsStructurallyEquivalent(From: D->getReturnType(),
4730 To: FoundMethod->getReturnType())) {
4731 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4732 << D->isInstanceMethod() << Name << D->getReturnType()
4733 << FoundMethod->getReturnType();
4734 Importer.ToDiag(FoundMethod->getLocation(),
4735 diag::note_odr_objc_method_here)
4736 << D->isInstanceMethod() << Name;
4737
4738 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4739 }
4740
4741 // Check the number of parameters.
4742 if (D->param_size() != FoundMethod->param_size()) {
4743 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4744 << D->isInstanceMethod() << Name
4745 << D->param_size() << FoundMethod->param_size();
4746 Importer.ToDiag(FoundMethod->getLocation(),
4747 diag::note_odr_objc_method_here)
4748 << D->isInstanceMethod() << Name;
4749
4750 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4751 }
4752
4753 // Check parameter types.
4754 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4755 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4756 P != PEnd; ++P, ++FoundP) {
4757 if (!Importer.IsStructurallyEquivalent(From: (*P)->getType(),
4758 To: (*FoundP)->getType())) {
4759 Importer.FromDiag((*P)->getLocation(),
4760 diag::warn_odr_objc_method_param_type_inconsistent)
4761 << D->isInstanceMethod() << Name
4762 << (*P)->getType() << (*FoundP)->getType();
4763 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4764 << (*FoundP)->getType();
4765
4766 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4767 }
4768 }
4769
4770 // Check variadic/non-variadic.
4771 // Check the number of parameters.
4772 if (D->isVariadic() != FoundMethod->isVariadic()) {
4773 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4774 << D->isInstanceMethod() << Name;
4775 Importer.ToDiag(FoundMethod->getLocation(),
4776 diag::note_odr_objc_method_here)
4777 << D->isInstanceMethod() << Name;
4778
4779 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
4780 }
4781
4782 // FIXME: Any other bits we need to merge?
4783 return Importer.MapImported(D, FoundMethod);
4784 }
4785 }
4786
4787 Error Err = Error::success();
4788 auto ToEndLoc = importChecked(Err, From: D->getEndLoc());
4789 auto ToReturnType = importChecked(Err, From: D->getReturnType());
4790 auto ToReturnTypeSourceInfo =
4791 importChecked(Err, From: D->getReturnTypeSourceInfo());
4792 if (Err)
4793 return std::move(Err);
4794
4795 ObjCMethodDecl *ToMethod;
4796 if (GetImportedOrCreateDecl(
4797 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4798 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4799 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4800 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4801 D->getImplementationControl(), D->hasRelatedResultType()))
4802 return ToMethod;
4803
4804 // FIXME: When we decide to merge method definitions, we'll need to
4805 // deal with implicit parameters.
4806
4807 // Import the parameters
4808 SmallVector<ParmVarDecl *, 5> ToParams;
4809 for (auto *FromP : D->parameters()) {
4810 if (Expected<ParmVarDecl *> ToPOrErr = import(From: FromP))
4811 ToParams.push_back(Elt: *ToPOrErr);
4812 else
4813 return ToPOrErr.takeError();
4814 }
4815
4816 // Set the parameters.
4817 for (auto *ToParam : ToParams) {
4818 ToParam->setOwningFunction(ToMethod);
4819 ToMethod->addDeclInternal(ToParam);
4820 }
4821
4822 SmallVector<SourceLocation, 12> FromSelLocs;
4823 D->getSelectorLocs(SelLocs&: FromSelLocs);
4824 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4825 if (Error Err = ImportContainerChecked(InContainer: FromSelLocs, OutContainer&: ToSelLocs))
4826 return std::move(Err);
4827
4828 ToMethod->setMethodParams(C&: Importer.getToContext(), Params: ToParams, SelLocs: ToSelLocs);
4829
4830 ToMethod->setLexicalDeclContext(LexicalDC);
4831 LexicalDC->addDeclInternal(ToMethod);
4832
4833 // Implicit params are declared when Sema encounters the definition but this
4834 // never happens when the method is imported. Manually declare the implicit
4835 // params now that the MethodDecl knows its class interface.
4836 if (D->getSelfDecl())
4837 ToMethod->createImplicitParams(Context&: Importer.getToContext(),
4838 ID: ToMethod->getClassInterface());
4839
4840 return ToMethod;
4841}
4842
4843ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4844 // Import the major distinguishing characteristics of a category.
4845 DeclContext *DC, *LexicalDC;
4846 DeclarationName Name;
4847 SourceLocation Loc;
4848 NamedDecl *ToD;
4849 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4850 return std::move(Err);
4851 if (ToD)
4852 return ToD;
4853
4854 Error Err = Error::success();
4855 auto ToVarianceLoc = importChecked(Err, From: D->getVarianceLoc());
4856 auto ToLocation = importChecked(Err, D->getLocation());
4857 auto ToColonLoc = importChecked(Err, From: D->getColonLoc());
4858 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4859 if (Err)
4860 return std::move(Err);
4861
4862 ObjCTypeParamDecl *Result;
4863 if (GetImportedOrCreateDecl(
4864 Result, D, Importer.getToContext(), DC, D->getVariance(),
4865 ToVarianceLoc, D->getIndex(),
4866 ToLocation, Name.getAsIdentifierInfo(),
4867 ToColonLoc, ToTypeSourceInfo))
4868 return Result;
4869
4870 // Only import 'ObjCTypeParamType' after the decl is created.
4871 auto ToTypeForDecl = importChecked(Err, D->getTypeForDecl());
4872 if (Err)
4873 return std::move(Err);
4874 Result->setTypeForDecl(ToTypeForDecl);
4875 Result->setLexicalDeclContext(LexicalDC);
4876 return Result;
4877}
4878
4879ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4880 // Import the major distinguishing characteristics of a category.
4881 DeclContext *DC, *LexicalDC;
4882 DeclarationName Name;
4883 SourceLocation Loc;
4884 NamedDecl *ToD;
4885 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4886 return std::move(Err);
4887 if (ToD)
4888 return ToD;
4889
4890 ObjCInterfaceDecl *ToInterface;
4891 if (Error Err = importInto(To&: ToInterface, From: D->getClassInterface()))
4892 return std::move(Err);
4893
4894 // Determine if we've already encountered this category.
4895 ObjCCategoryDecl *MergeWithCategory
4896 = ToInterface->FindCategoryDeclaration(CategoryId: Name.getAsIdentifierInfo());
4897 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4898 if (!ToCategory) {
4899
4900 Error Err = Error::success();
4901 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4902 auto ToCategoryNameLoc = importChecked(Err, From: D->getCategoryNameLoc());
4903 auto ToIvarLBraceLoc = importChecked(Err, From: D->getIvarLBraceLoc());
4904 auto ToIvarRBraceLoc = importChecked(Err, From: D->getIvarRBraceLoc());
4905 if (Err)
4906 return std::move(Err);
4907
4908 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4909 ToAtStartLoc, Loc,
4910 ToCategoryNameLoc,
4911 Name.getAsIdentifierInfo(), ToInterface,
4912 /*TypeParamList=*/nullptr,
4913 ToIvarLBraceLoc,
4914 ToIvarRBraceLoc))
4915 return ToCategory;
4916
4917 ToCategory->setLexicalDeclContext(LexicalDC);
4918 LexicalDC->addDeclInternal(ToCategory);
4919 // Import the type parameter list after MapImported, to avoid
4920 // loops when bringing in their DeclContext.
4921 if (auto PListOrErr = ImportObjCTypeParamList(list: D->getTypeParamList()))
4922 ToCategory->setTypeParamList(*PListOrErr);
4923 else
4924 return PListOrErr.takeError();
4925
4926 // Import protocols
4927 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4928 SmallVector<SourceLocation, 4> ProtocolLocs;
4929 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4930 = D->protocol_loc_begin();
4931 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4932 FromProtoEnd = D->protocol_end();
4933 FromProto != FromProtoEnd;
4934 ++FromProto, ++FromProtoLoc) {
4935 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
4936 Protocols.push_back(Elt: *ToProtoOrErr);
4937 else
4938 return ToProtoOrErr.takeError();
4939
4940 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
4941 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
4942 else
4943 return ToProtoLocOrErr.takeError();
4944 }
4945
4946 // FIXME: If we're merging, make sure that the protocol list is the same.
4947 ToCategory->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
4948 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
4949
4950 } else {
4951 Importer.MapImported(D, ToCategory);
4952 }
4953
4954 // Import all of the members of this category.
4955 if (Error Err = ImportDeclContext(D))
4956 return std::move(Err);
4957
4958 // If we have an implementation, import it as well.
4959 if (D->getImplementation()) {
4960 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4961 import(From: D->getImplementation()))
4962 ToCategory->setImplementation(*ToImplOrErr);
4963 else
4964 return ToImplOrErr.takeError();
4965 }
4966
4967 return ToCategory;
4968}
4969
4970Error ASTNodeImporter::ImportDefinition(
4971 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4972 if (To->getDefinition()) {
4973 if (shouldForceImportDeclContext(IDK: Kind))
4974 if (Error Err = ImportDeclContext(From))
4975 return Err;
4976 return Error::success();
4977 }
4978
4979 // Start the protocol definition
4980 To->startDefinition();
4981
4982 // Import protocols
4983 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4984 SmallVector<SourceLocation, 4> ProtocolLocs;
4985 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4986 From->protocol_loc_begin();
4987 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4988 FromProtoEnd = From->protocol_end();
4989 FromProto != FromProtoEnd;
4990 ++FromProto, ++FromProtoLoc) {
4991 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
4992 Protocols.push_back(Elt: *ToProtoOrErr);
4993 else
4994 return ToProtoOrErr.takeError();
4995
4996 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
4997 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
4998 else
4999 return ToProtoLocOrErr.takeError();
5000
5001 }
5002
5003 // FIXME: If we're merging, make sure that the protocol list is the same.
5004 To->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
5005 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
5006
5007 if (shouldForceImportDeclContext(IDK: Kind)) {
5008 // Import all of the members of this protocol.
5009 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5010 return Err;
5011 }
5012 return Error::success();
5013}
5014
5015ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
5016 // If this protocol has a definition in the translation unit we're coming
5017 // from, but this particular declaration is not that definition, import the
5018 // definition and map to that.
5019 ObjCProtocolDecl *Definition = D->getDefinition();
5020 if (Definition && Definition != D) {
5021 if (ExpectedDecl ImportedDefOrErr = import(From: Definition))
5022 return Importer.MapImported(D, *ImportedDefOrErr);
5023 else
5024 return ImportedDefOrErr.takeError();
5025 }
5026
5027 // Import the major distinguishing characteristics of a protocol.
5028 DeclContext *DC, *LexicalDC;
5029 DeclarationName Name;
5030 SourceLocation Loc;
5031 NamedDecl *ToD;
5032 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5033 return std::move(Err);
5034 if (ToD)
5035 return ToD;
5036
5037 ObjCProtocolDecl *MergeWithProtocol = nullptr;
5038 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5039 for (auto *FoundDecl : FoundDecls) {
5040 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
5041 continue;
5042
5043 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(Val: FoundDecl)))
5044 break;
5045 }
5046
5047 ObjCProtocolDecl *ToProto = MergeWithProtocol;
5048 if (!ToProto) {
5049 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
5050 if (!ToAtBeginLocOrErr)
5051 return ToAtBeginLocOrErr.takeError();
5052
5053 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
5054 Name.getAsIdentifierInfo(), Loc,
5055 *ToAtBeginLocOrErr,
5056 /*PrevDecl=*/nullptr))
5057 return ToProto;
5058 ToProto->setLexicalDeclContext(LexicalDC);
5059 LexicalDC->addDeclInternal(ToProto);
5060 }
5061
5062 Importer.MapImported(D, ToProto);
5063
5064 if (D->isThisDeclarationADefinition())
5065 if (Error Err = ImportDefinition(From: D, To: ToProto))
5066 return std::move(Err);
5067
5068 return ToProto;
5069}
5070
5071ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
5072 DeclContext *DC, *LexicalDC;
5073 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5074 return std::move(Err);
5075
5076 ExpectedSLoc ExternLocOrErr = import(From: D->getExternLoc());
5077 if (!ExternLocOrErr)
5078 return ExternLocOrErr.takeError();
5079
5080 ExpectedSLoc LangLocOrErr = import(D->getLocation());
5081 if (!LangLocOrErr)
5082 return LangLocOrErr.takeError();
5083
5084 bool HasBraces = D->hasBraces();
5085
5086 LinkageSpecDecl *ToLinkageSpec;
5087 if (GetImportedOrCreateDecl(ToD&: ToLinkageSpec, FromD: D, args&: Importer.getToContext(), args&: DC,
5088 args&: *ExternLocOrErr, args&: *LangLocOrErr,
5089 args: D->getLanguage(), args&: HasBraces))
5090 return ToLinkageSpec;
5091
5092 if (HasBraces) {
5093 ExpectedSLoc RBraceLocOrErr = import(From: D->getRBraceLoc());
5094 if (!RBraceLocOrErr)
5095 return RBraceLocOrErr.takeError();
5096 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
5097 }
5098
5099 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
5100 LexicalDC->addDeclInternal(ToLinkageSpec);
5101
5102 return ToLinkageSpec;
5103}
5104
5105ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
5106 BaseUsingDecl *ToSI) {
5107 for (UsingShadowDecl *FromShadow : D->shadows()) {
5108 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(From: FromShadow))
5109 ToSI->addShadowDecl(S: *ToShadowOrErr);
5110 else
5111 // FIXME: We return error here but the definition is already created
5112 // and available with lookups. How to fix this?..
5113 return ToShadowOrErr.takeError();
5114 }
5115 return ToSI;
5116}
5117
5118ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
5119 DeclContext *DC, *LexicalDC;
5120 DeclarationName Name;
5121 SourceLocation Loc;
5122 NamedDecl *ToD = nullptr;
5123 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5124 return std::move(Err);
5125 if (ToD)
5126 return ToD;
5127
5128 Error Err = Error::success();
5129 auto ToLoc = importChecked(Err, From: D->getNameInfo().getLoc());
5130 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5131 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5132 if (Err)
5133 return std::move(Err);
5134
5135 DeclarationNameInfo NameInfo(Name, ToLoc);
5136 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
5137 return std::move(Err);
5138
5139 UsingDecl *ToUsing;
5140 if (GetImportedOrCreateDecl(ToD&: ToUsing, FromD: D, args&: Importer.getToContext(), args&: DC,
5141 args&: ToUsingLoc, args&: ToQualifierLoc, args&: NameInfo,
5142 args: D->hasTypename()))
5143 return ToUsing;
5144
5145 ToUsing->setLexicalDeclContext(LexicalDC);
5146 LexicalDC->addDeclInternal(ToUsing);
5147
5148 if (NamedDecl *FromPattern =
5149 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
5150 if (Expected<NamedDecl *> ToPatternOrErr = import(From: FromPattern))
5151 Importer.getToContext().setInstantiatedFromUsingDecl(
5152 ToUsing, *ToPatternOrErr);
5153 else
5154 return ToPatternOrErr.takeError();
5155 }
5156
5157 return ImportUsingShadowDecls(D, ToUsing);
5158}
5159
5160ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
5161 DeclContext *DC, *LexicalDC;
5162 DeclarationName Name;
5163 SourceLocation Loc;
5164 NamedDecl *ToD = nullptr;
5165 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5166 return std::move(Err);
5167 if (ToD)
5168 return ToD;
5169
5170 Error Err = Error::success();
5171 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5172 auto ToEnumLoc = importChecked(Err, From: D->getEnumLoc());
5173 auto ToNameLoc = importChecked(Err, D->getLocation());
5174 auto *ToEnumType = importChecked(Err, From: D->getEnumType());
5175 if (Err)
5176 return std::move(Err);
5177
5178 UsingEnumDecl *ToUsingEnum;
5179 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
5180 ToUsingLoc, ToEnumLoc, ToNameLoc, ToEnumType))
5181 return ToUsingEnum;
5182
5183 ToUsingEnum->setLexicalDeclContext(LexicalDC);
5184 LexicalDC->addDeclInternal(ToUsingEnum);
5185
5186 if (UsingEnumDecl *FromPattern =
5187 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(Inst: D)) {
5188 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(From: FromPattern))
5189 Importer.getToContext().setInstantiatedFromUsingEnumDecl(Inst: ToUsingEnum,
5190 Pattern: *ToPatternOrErr);
5191 else
5192 return ToPatternOrErr.takeError();
5193 }
5194
5195 return ImportUsingShadowDecls(D, ToUsingEnum);
5196}
5197
5198ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
5199 DeclContext *DC, *LexicalDC;
5200 DeclarationName Name;
5201 SourceLocation Loc;
5202 NamedDecl *ToD = nullptr;
5203 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5204 return std::move(Err);
5205 if (ToD)
5206 return ToD;
5207
5208 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(From: D->getIntroducer());
5209 if (!ToIntroducerOrErr)
5210 return ToIntroducerOrErr.takeError();
5211
5212 Expected<NamedDecl *> ToTargetOrErr = import(From: D->getTargetDecl());
5213 if (!ToTargetOrErr)
5214 return ToTargetOrErr.takeError();
5215
5216 UsingShadowDecl *ToShadow;
5217 if (auto *FromConstructorUsingShadow =
5218 dyn_cast<ConstructorUsingShadowDecl>(Val: D)) {
5219 Error Err = Error::success();
5220 ConstructorUsingShadowDecl *Nominated = importChecked(
5221 Err, From: FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
5222 if (Err)
5223 return std::move(Err);
5224 // The 'Target' parameter of ConstructorUsingShadowDecl constructor
5225 // is really the "NominatedBaseClassShadowDecl" value if it exists
5226 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
5227 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
5228 // get the correct values.
5229 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
5230 ToShadow, D, Importer.getToContext(), DC, Loc,
5231 cast<UsingDecl>(Val: *ToIntroducerOrErr),
5232 Nominated ? Nominated : *ToTargetOrErr,
5233 FromConstructorUsingShadow->constructsVirtualBase()))
5234 return ToShadow;
5235 } else {
5236 if (GetImportedOrCreateDecl(ToD&: ToShadow, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
5237 args&: Name, args&: *ToIntroducerOrErr, args&: *ToTargetOrErr))
5238 return ToShadow;
5239 }
5240
5241 ToShadow->setLexicalDeclContext(LexicalDC);
5242 ToShadow->setAccess(D->getAccess());
5243
5244 if (UsingShadowDecl *FromPattern =
5245 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(Inst: D)) {
5246 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(From: FromPattern))
5247 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
5248 Inst: ToShadow, Pattern: *ToPatternOrErr);
5249 else
5250 // FIXME: We return error here but the definition is already created
5251 // and available with lookups. How to fix this?..
5252 return ToPatternOrErr.takeError();
5253 }
5254
5255 LexicalDC->addDeclInternal(ToShadow);
5256
5257 return ToShadow;
5258}
5259
5260ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
5261 DeclContext *DC, *LexicalDC;
5262 DeclarationName Name;
5263 SourceLocation Loc;
5264 NamedDecl *ToD = nullptr;
5265 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5266 return std::move(Err);
5267 if (ToD)
5268 return ToD;
5269
5270 auto ToComAncestorOrErr = Importer.ImportContext(FromDC: D->getCommonAncestor());
5271 if (!ToComAncestorOrErr)
5272 return ToComAncestorOrErr.takeError();
5273
5274 Error Err = Error::success();
5275 auto ToNominatedNamespace = importChecked(Err, From: D->getNominatedNamespace());
5276 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5277 auto ToNamespaceKeyLocation =
5278 importChecked(Err, From: D->getNamespaceKeyLocation());
5279 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5280 auto ToIdentLocation = importChecked(Err, From: D->getIdentLocation());
5281 if (Err)
5282 return std::move(Err);
5283
5284 UsingDirectiveDecl *ToUsingDir;
5285 if (GetImportedOrCreateDecl(ToD&: ToUsingDir, FromD: D, args&: Importer.getToContext(), args&: DC,
5286 args&: ToUsingLoc,
5287 args&: ToNamespaceKeyLocation,
5288 args&: ToQualifierLoc,
5289 args&: ToIdentLocation,
5290 args&: ToNominatedNamespace, args&: *ToComAncestorOrErr))
5291 return ToUsingDir;
5292
5293 ToUsingDir->setLexicalDeclContext(LexicalDC);
5294 LexicalDC->addDeclInternal(ToUsingDir);
5295
5296 return ToUsingDir;
5297}
5298
5299ExpectedDecl ASTNodeImporter::VisitUsingPackDecl(UsingPackDecl *D) {
5300 DeclContext *DC, *LexicalDC;
5301 DeclarationName Name;
5302 SourceLocation Loc;
5303 NamedDecl *ToD = nullptr;
5304 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5305 return std::move(Err);
5306 if (ToD)
5307 return ToD;
5308
5309 auto ToInstantiatedFromUsingOrErr =
5310 Importer.Import(D->getInstantiatedFromUsingDecl());
5311 if (!ToInstantiatedFromUsingOrErr)
5312 return ToInstantiatedFromUsingOrErr.takeError();
5313 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
5314 if (Error Err = ImportArrayChecked(InContainer: D->expansions(), Obegin: Expansions.begin()))
5315 return std::move(Err);
5316
5317 UsingPackDecl *ToUsingPack;
5318 if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
5319 cast<NamedDecl>(*ToInstantiatedFromUsingOrErr),
5320 Expansions))
5321 return ToUsingPack;
5322
5323 addDeclToContexts(D, ToUsingPack);
5324
5325 return ToUsingPack;
5326}
5327
5328ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
5329 UnresolvedUsingValueDecl *D) {
5330 DeclContext *DC, *LexicalDC;
5331 DeclarationName Name;
5332 SourceLocation Loc;
5333 NamedDecl *ToD = nullptr;
5334 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5335 return std::move(Err);
5336 if (ToD)
5337 return ToD;
5338
5339 Error Err = Error::success();
5340 auto ToLoc = importChecked(Err, From: D->getNameInfo().getLoc());
5341 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5342 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5343 auto ToEllipsisLoc = importChecked(Err, From: D->getEllipsisLoc());
5344 if (Err)
5345 return std::move(Err);
5346
5347 DeclarationNameInfo NameInfo(Name, ToLoc);
5348 if (Error Err = ImportDeclarationNameLoc(From: D->getNameInfo(), To&: NameInfo))
5349 return std::move(Err);
5350
5351 UnresolvedUsingValueDecl *ToUsingValue;
5352 if (GetImportedOrCreateDecl(ToD&: ToUsingValue, FromD: D, args&: Importer.getToContext(), args&: DC,
5353 args&: ToUsingLoc, args&: ToQualifierLoc, args&: NameInfo,
5354 args&: ToEllipsisLoc))
5355 return ToUsingValue;
5356
5357 ToUsingValue->setAccess(D->getAccess());
5358 ToUsingValue->setLexicalDeclContext(LexicalDC);
5359 LexicalDC->addDeclInternal(ToUsingValue);
5360
5361 return ToUsingValue;
5362}
5363
5364ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
5365 UnresolvedUsingTypenameDecl *D) {
5366 DeclContext *DC, *LexicalDC;
5367 DeclarationName Name;
5368 SourceLocation Loc;
5369 NamedDecl *ToD = nullptr;
5370 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5371 return std::move(Err);
5372 if (ToD)
5373 return ToD;
5374
5375 Error Err = Error::success();
5376 auto ToUsingLoc = importChecked(Err, From: D->getUsingLoc());
5377 auto ToTypenameLoc = importChecked(Err, From: D->getTypenameLoc());
5378 auto ToQualifierLoc = importChecked(Err, From: D->getQualifierLoc());
5379 auto ToEllipsisLoc = importChecked(Err, From: D->getEllipsisLoc());
5380 if (Err)
5381 return std::move(Err);
5382
5383 UnresolvedUsingTypenameDecl *ToUsing;
5384 if (GetImportedOrCreateDecl(ToD&: ToUsing, FromD: D, args&: Importer.getToContext(), args&: DC,
5385 args&: ToUsingLoc, args&: ToTypenameLoc,
5386 args&: ToQualifierLoc, args&: Loc, args&: Name, args&: ToEllipsisLoc))
5387 return ToUsing;
5388
5389 ToUsing->setAccess(D->getAccess());
5390 ToUsing->setLexicalDeclContext(LexicalDC);
5391 LexicalDC->addDeclInternal(ToUsing);
5392
5393 return ToUsing;
5394}
5395
5396ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
5397 Decl* ToD = nullptr;
5398 switch (D->getBuiltinTemplateKind()) {
5399 case BuiltinTemplateKind::BTK__make_integer_seq:
5400 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
5401 break;
5402 case BuiltinTemplateKind::BTK__type_pack_element:
5403 ToD = Importer.getToContext().getTypePackElementDecl();
5404 break;
5405 }
5406 assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
5407 Importer.MapImported(D, ToD);
5408 return ToD;
5409}
5410
5411Error ASTNodeImporter::ImportDefinition(
5412 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
5413 if (To->getDefinition()) {
5414 // Check consistency of superclass.
5415 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
5416 if (FromSuper) {
5417 if (auto FromSuperOrErr = import(From: FromSuper))
5418 FromSuper = *FromSuperOrErr;
5419 else
5420 return FromSuperOrErr.takeError();
5421 }
5422
5423 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
5424 if ((bool)FromSuper != (bool)ToSuper ||
5425 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
5426 Importer.ToDiag(To->getLocation(),
5427 diag::warn_odr_objc_superclass_inconsistent)
5428 << To->getDeclName();
5429 if (ToSuper)
5430 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
5431 << To->getSuperClass()->getDeclName();
5432 else
5433 Importer.ToDiag(To->getLocation(),
5434 diag::note_odr_objc_missing_superclass);
5435 if (From->getSuperClass())
5436 Importer.FromDiag(From->getSuperClassLoc(),
5437 diag::note_odr_objc_superclass)
5438 << From->getSuperClass()->getDeclName();
5439 else
5440 Importer.FromDiag(From->getLocation(),
5441 diag::note_odr_objc_missing_superclass);
5442 }
5443
5444 if (shouldForceImportDeclContext(IDK: Kind))
5445 if (Error Err = ImportDeclContext(From))
5446 return Err;
5447 return Error::success();
5448 }
5449
5450 // Start the definition.
5451 To->startDefinition();
5452
5453 // If this class has a superclass, import it.
5454 if (From->getSuperClass()) {
5455 if (auto SuperTInfoOrErr = import(From: From->getSuperClassTInfo()))
5456 To->setSuperClass(*SuperTInfoOrErr);
5457 else
5458 return SuperTInfoOrErr.takeError();
5459 }
5460
5461 // Import protocols
5462 SmallVector<ObjCProtocolDecl *, 4> Protocols;
5463 SmallVector<SourceLocation, 4> ProtocolLocs;
5464 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
5465 From->protocol_loc_begin();
5466
5467 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
5468 FromProtoEnd = From->protocol_end();
5469 FromProto != FromProtoEnd;
5470 ++FromProto, ++FromProtoLoc) {
5471 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(From: *FromProto))
5472 Protocols.push_back(Elt: *ToProtoOrErr);
5473 else
5474 return ToProtoOrErr.takeError();
5475
5476 if (ExpectedSLoc ToProtoLocOrErr = import(From: *FromProtoLoc))
5477 ProtocolLocs.push_back(Elt: *ToProtoLocOrErr);
5478 else
5479 return ToProtoLocOrErr.takeError();
5480
5481 }
5482
5483 // FIXME: If we're merging, make sure that the protocol list is the same.
5484 To->setProtocolList(List: Protocols.data(), Num: Protocols.size(),
5485 Locs: ProtocolLocs.data(), C&: Importer.getToContext());
5486
5487 // Import categories. When the categories themselves are imported, they'll
5488 // hook themselves into this interface.
5489 for (auto *Cat : From->known_categories()) {
5490 auto ToCatOrErr = import(From: Cat);
5491 if (!ToCatOrErr)
5492 return ToCatOrErr.takeError();
5493 }
5494
5495 // If we have an @implementation, import it as well.
5496 if (From->getImplementation()) {
5497 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
5498 import(From: From->getImplementation()))
5499 To->setImplementation(*ToImplOrErr);
5500 else
5501 return ToImplOrErr.takeError();
5502 }
5503
5504 // Import all of the members of this class.
5505 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5506 return Err;
5507
5508 return Error::success();
5509}
5510
5511Expected<ObjCTypeParamList *>
5512ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
5513 if (!list)
5514 return nullptr;
5515
5516 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
5517 for (auto *fromTypeParam : *list) {
5518 if (auto toTypeParamOrErr = import(From: fromTypeParam))
5519 toTypeParams.push_back(Elt: *toTypeParamOrErr);
5520 else
5521 return toTypeParamOrErr.takeError();
5522 }
5523
5524 auto LAngleLocOrErr = import(From: list->getLAngleLoc());
5525 if (!LAngleLocOrErr)
5526 return LAngleLocOrErr.takeError();
5527
5528 auto RAngleLocOrErr = import(From: list->getRAngleLoc());
5529 if (!RAngleLocOrErr)
5530 return RAngleLocOrErr.takeError();
5531
5532 return ObjCTypeParamList::create(ctx&: Importer.getToContext(),
5533 lAngleLoc: *LAngleLocOrErr,
5534 typeParams: toTypeParams,
5535 rAngleLoc: *RAngleLocOrErr);
5536}
5537
5538ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
5539 // If this class has a definition in the translation unit we're coming from,
5540 // but this particular declaration is not that definition, import the
5541 // definition and map to that.
5542 ObjCInterfaceDecl *Definition = D->getDefinition();
5543 if (Definition && Definition != D) {
5544 if (ExpectedDecl ImportedDefOrErr = import(From: Definition))
5545 return Importer.MapImported(D, *ImportedDefOrErr);
5546 else
5547 return ImportedDefOrErr.takeError();
5548 }
5549
5550 // Import the major distinguishing characteristics of an @interface.
5551 DeclContext *DC, *LexicalDC;
5552 DeclarationName Name;
5553 SourceLocation Loc;
5554 NamedDecl *ToD;
5555 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5556 return std::move(Err);
5557 if (ToD)
5558 return ToD;
5559
5560 // Look for an existing interface with the same name.
5561 ObjCInterfaceDecl *MergeWithIface = nullptr;
5562 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5563 for (auto *FoundDecl : FoundDecls) {
5564 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5565 continue;
5566
5567 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(Val: FoundDecl)))
5568 break;
5569 }
5570
5571 // Create an interface declaration, if one does not already exist.
5572 ObjCInterfaceDecl *ToIface = MergeWithIface;
5573 if (!ToIface) {
5574 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5575 if (!AtBeginLocOrErr)
5576 return AtBeginLocOrErr.takeError();
5577
5578 if (GetImportedOrCreateDecl(
5579 ToD&: ToIface, FromD: D, args&: Importer.getToContext(), args&: DC,
5580 args&: *AtBeginLocOrErr, args: Name.getAsIdentifierInfo(),
5581 /*TypeParamList=*/args: nullptr,
5582 /*PrevDecl=*/args: nullptr, args&: Loc, args: D->isImplicitInterfaceDecl()))
5583 return ToIface;
5584 ToIface->setLexicalDeclContext(LexicalDC);
5585 LexicalDC->addDeclInternal(ToIface);
5586 }
5587 Importer.MapImported(D, ToIface);
5588 // Import the type parameter list after MapImported, to avoid
5589 // loops when bringing in their DeclContext.
5590 if (auto ToPListOrErr =
5591 ImportObjCTypeParamList(list: D->getTypeParamListAsWritten()))
5592 ToIface->setTypeParamList(*ToPListOrErr);
5593 else
5594 return ToPListOrErr.takeError();
5595
5596 if (D->isThisDeclarationADefinition())
5597 if (Error Err = ImportDefinition(From: D, To: ToIface))
5598 return std::move(Err);
5599
5600 return ToIface;
5601}
5602
5603ExpectedDecl
5604ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
5605 ObjCCategoryDecl *Category;
5606 if (Error Err = importInto(To&: Category, From: D->getCategoryDecl()))
5607 return std::move(Err);
5608
5609 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5610 if (!ToImpl) {
5611 DeclContext *DC, *LexicalDC;
5612 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5613 return std::move(Err);
5614
5615 Error Err = Error::success();
5616 auto ToLocation = importChecked(Err, D->getLocation());
5617 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5618 auto ToCategoryNameLoc = importChecked(Err, From: D->getCategoryNameLoc());
5619 if (Err)
5620 return std::move(Err);
5621
5622 if (GetImportedOrCreateDecl(
5623 ToImpl, D, Importer.getToContext(), DC,
5624 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5625 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5626 return ToImpl;
5627
5628 ToImpl->setLexicalDeclContext(LexicalDC);
5629 LexicalDC->addDeclInternal(ToImpl);
5630 Category->setImplementation(ToImpl);
5631 }
5632
5633 Importer.MapImported(D, ToImpl);
5634 if (Error Err = ImportDeclContext(D))
5635 return std::move(Err);
5636
5637 return ToImpl;
5638}
5639
5640ExpectedDecl
5641ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
5642 // Find the corresponding interface.
5643 ObjCInterfaceDecl *Iface;
5644 if (Error Err = importInto(Iface, D->getClassInterface()))
5645 return std::move(Err);
5646
5647 // Import the superclass, if any.
5648 ObjCInterfaceDecl *Super;
5649 if (Error Err = importInto(To&: Super, From: D->getSuperClass()))
5650 return std::move(Err);
5651
5652 ObjCImplementationDecl *Impl = Iface->getImplementation();
5653 if (!Impl) {
5654 // We haven't imported an implementation yet. Create a new @implementation
5655 // now.
5656 DeclContext *DC, *LexicalDC;
5657 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5658 return std::move(Err);
5659
5660 Error Err = Error::success();
5661 auto ToLocation = importChecked(Err, D->getLocation());
5662 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5663 auto ToSuperClassLoc = importChecked(Err, From: D->getSuperClassLoc());
5664 auto ToIvarLBraceLoc = importChecked(Err, From: D->getIvarLBraceLoc());
5665 auto ToIvarRBraceLoc = importChecked(Err, From: D->getIvarRBraceLoc());
5666 if (Err)
5667 return std::move(Err);
5668
5669 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5670 DC, Iface, Super,
5671 ToLocation,
5672 ToAtStartLoc,
5673 ToSuperClassLoc,
5674 ToIvarLBraceLoc,
5675 ToIvarRBraceLoc))
5676 return Impl;
5677
5678 Impl->setLexicalDeclContext(LexicalDC);
5679
5680 // Associate the implementation with the class it implements.
5681 Iface->setImplementation(Impl);
5682 Importer.MapImported(D, Iface->getImplementation());
5683 } else {
5684 Importer.MapImported(D, Iface->getImplementation());
5685
5686 // Verify that the existing @implementation has the same superclass.
5687 if ((Super && !Impl->getSuperClass()) ||
5688 (!Super && Impl->getSuperClass()) ||
5689 (Super && Impl->getSuperClass() &&
5690 !declaresSameEntity(Super->getCanonicalDecl(),
5691 Impl->getSuperClass()))) {
5692 Importer.ToDiag(Impl->getLocation(),
5693 diag::warn_odr_objc_superclass_inconsistent)
5694 << Iface->getDeclName();
5695 // FIXME: It would be nice to have the location of the superclass
5696 // below.
5697 if (Impl->getSuperClass())
5698 Importer.ToDiag(Impl->getLocation(),
5699 diag::note_odr_objc_superclass)
5700 << Impl->getSuperClass()->getDeclName();
5701 else
5702 Importer.ToDiag(Impl->getLocation(),
5703 diag::note_odr_objc_missing_superclass);
5704 if (D->getSuperClass())
5705 Importer.FromDiag(D->getLocation(),
5706 diag::note_odr_objc_superclass)
5707 << D->getSuperClass()->getDeclName();
5708 else
5709 Importer.FromDiag(D->getLocation(),
5710 diag::note_odr_objc_missing_superclass);
5711
5712 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5713 }
5714 }
5715
5716 // Import all of the members of this @implementation.
5717 if (Error Err = ImportDeclContext(D))
5718 return std::move(Err);
5719
5720 return Impl;
5721}
5722
5723ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5724 // Import the major distinguishing characteristics of an @property.
5725 DeclContext *DC, *LexicalDC;
5726 DeclarationName Name;
5727 SourceLocation Loc;
5728 NamedDecl *ToD;
5729 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5730 return std::move(Err);
5731 if (ToD)
5732 return ToD;
5733
5734 // Check whether we have already imported this property.
5735 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5736 for (auto *FoundDecl : FoundDecls) {
5737 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(Val: FoundDecl)) {
5738 // Instance and class properties can share the same name but are different
5739 // declarations.
5740 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5741 continue;
5742
5743 // Check property types.
5744 if (!Importer.IsStructurallyEquivalent(From: D->getType(),
5745 To: FoundProp->getType())) {
5746 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5747 << Name << D->getType() << FoundProp->getType();
5748 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5749 << FoundProp->getType();
5750
5751 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5752 }
5753
5754 // FIXME: Check property attributes, getters, setters, etc.?
5755
5756 // Consider these properties to be equivalent.
5757 Importer.MapImported(D, FoundProp);
5758 return FoundProp;
5759 }
5760 }
5761
5762 Error Err = Error::success();
5763 auto ToType = importChecked(Err, From: D->getType());
5764 auto ToTypeSourceInfo = importChecked(Err, From: D->getTypeSourceInfo());
5765 auto ToAtLoc = importChecked(Err, From: D->getAtLoc());
5766 auto ToLParenLoc = importChecked(Err, From: D->getLParenLoc());
5767 if (Err)
5768 return std::move(Err);
5769
5770 // Create the new property.
5771 ObjCPropertyDecl *ToProperty;
5772 if (GetImportedOrCreateDecl(
5773 ToD&: ToProperty, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc,
5774 args: Name.getAsIdentifierInfo(), args&: ToAtLoc,
5775 args&: ToLParenLoc, args&: ToType,
5776 args&: ToTypeSourceInfo, args: D->getPropertyImplementation()))
5777 return ToProperty;
5778
5779 auto ToGetterName = importChecked(Err, From: D->getGetterName());
5780 auto ToSetterName = importChecked(Err, From: D->getSetterName());
5781 auto ToGetterNameLoc = importChecked(Err, From: D->getGetterNameLoc());
5782 auto ToSetterNameLoc = importChecked(Err, From: D->getSetterNameLoc());
5783 auto ToGetterMethodDecl = importChecked(Err, From: D->getGetterMethodDecl());
5784 auto ToSetterMethodDecl = importChecked(Err, From: D->getSetterMethodDecl());
5785 auto ToPropertyIvarDecl = importChecked(Err, From: D->getPropertyIvarDecl());
5786 if (Err)
5787 return std::move(Err);
5788
5789 ToProperty->setLexicalDeclContext(LexicalDC);
5790 LexicalDC->addDeclInternal(ToProperty);
5791
5792 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5793 ToProperty->setPropertyAttributesAsWritten(
5794 D->getPropertyAttributesAsWritten());
5795 ToProperty->setGetterName(Sel: ToGetterName, Loc: ToGetterNameLoc);
5796 ToProperty->setSetterName(Sel: ToSetterName, Loc: ToSetterNameLoc);
5797 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5798 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5799 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5800 return ToProperty;
5801}
5802
5803ExpectedDecl
5804ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5805 ObjCPropertyDecl *Property;
5806 if (Error Err = importInto(To&: Property, From: D->getPropertyDecl()))
5807 return std::move(Err);
5808
5809 DeclContext *DC, *LexicalDC;
5810 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5811 return std::move(Err);
5812
5813 auto *InImpl = cast<ObjCImplDecl>(Val: LexicalDC);
5814
5815 // Import the ivar (for an @synthesize).
5816 ObjCIvarDecl *Ivar = nullptr;
5817 if (Error Err = importInto(To&: Ivar, From: D->getPropertyIvarDecl()))
5818 return std::move(Err);
5819
5820 ObjCPropertyImplDecl *ToImpl
5821 = InImpl->FindPropertyImplDecl(propertyId: Property->getIdentifier(),
5822 queryKind: Property->getQueryKind());
5823 if (!ToImpl) {
5824
5825 Error Err = Error::success();
5826 auto ToBeginLoc = importChecked(Err, From: D->getBeginLoc());
5827 auto ToLocation = importChecked(Err, D->getLocation());
5828 auto ToPropertyIvarDeclLoc =
5829 importChecked(Err, From: D->getPropertyIvarDeclLoc());
5830 if (Err)
5831 return std::move(Err);
5832
5833 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5834 ToBeginLoc,
5835 ToLocation, Property,
5836 D->getPropertyImplementation(), Ivar,
5837 ToPropertyIvarDeclLoc))
5838 return ToImpl;
5839
5840 ToImpl->setLexicalDeclContext(LexicalDC);
5841 LexicalDC->addDeclInternal(ToImpl);
5842 } else {
5843 // Check that we have the same kind of property implementation (@synthesize
5844 // vs. @dynamic).
5845 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5846 Importer.ToDiag(ToImpl->getLocation(),
5847 diag::warn_odr_objc_property_impl_kind_inconsistent)
5848 << Property->getDeclName()
5849 << (ToImpl->getPropertyImplementation()
5850 == ObjCPropertyImplDecl::Dynamic);
5851 Importer.FromDiag(D->getLocation(),
5852 diag::note_odr_objc_property_impl_kind)
5853 << D->getPropertyDecl()->getDeclName()
5854 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5855
5856 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5857 }
5858
5859 // For @synthesize, check that we have the same
5860 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5861 Ivar != ToImpl->getPropertyIvarDecl()) {
5862 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5863 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5864 << Property->getDeclName()
5865 << ToImpl->getPropertyIvarDecl()->getDeclName()
5866 << Ivar->getDeclName();
5867 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5868 diag::note_odr_objc_synthesize_ivar_here)
5869 << D->getPropertyIvarDecl()->getDeclName();
5870
5871 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
5872 }
5873
5874 // Merge the existing implementation with the new implementation.
5875 Importer.MapImported(D, ToImpl);
5876 }
5877
5878 return ToImpl;
5879}
5880
5881ExpectedDecl
5882ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5883 // For template arguments, we adopt the translation unit as our declaration
5884 // context. This context will be fixed when the actual template declaration
5885 // is created.
5886
5887 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5888 if (!BeginLocOrErr)
5889 return BeginLocOrErr.takeError();
5890
5891 ExpectedSLoc LocationOrErr = import(D->getLocation());
5892 if (!LocationOrErr)
5893 return LocationOrErr.takeError();
5894
5895 TemplateTypeParmDecl *ToD = nullptr;
5896 if (GetImportedOrCreateDecl(
5897 ToD, D, Importer.getToContext(),
5898 Importer.getToContext().getTranslationUnitDecl(),
5899 *BeginLocOrErr, *LocationOrErr,
5900 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5901 D->wasDeclaredWithTypename(), D->isParameterPack(),
5902 D->hasTypeConstraint()))
5903 return ToD;
5904
5905 // Import the type-constraint
5906 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5907
5908 Error Err = Error::success();
5909 auto ToConceptRef = importChecked(Err, From: TC->getConceptReference());
5910 auto ToIDC = importChecked(Err, From: TC->getImmediatelyDeclaredConstraint());
5911 if (Err)
5912 return std::move(Err);
5913
5914 ToD->setTypeConstraint(CR: ToConceptRef, ImmediatelyDeclaredConstraint: ToIDC);
5915 }
5916
5917 if (D->hasDefaultArgument()) {
5918 Expected<TypeSourceInfo *> ToDefaultArgOrErr =
5919 import(From: D->getDefaultArgumentInfo());
5920 if (!ToDefaultArgOrErr)
5921 return ToDefaultArgOrErr.takeError();
5922 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5923 }
5924
5925 return ToD;
5926}
5927
5928ExpectedDecl
5929ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5930
5931 Error Err = Error::success();
5932 auto ToDeclName = importChecked(Err, D->getDeclName());
5933 auto ToLocation = importChecked(Err, D->getLocation());
5934 auto ToType = importChecked(Err, D->getType());
5935 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5936 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5937 if (Err)
5938 return std::move(Err);
5939
5940 NonTypeTemplateParmDecl *ToD = nullptr;
5941 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5942 Importer.getToContext().getTranslationUnitDecl(),
5943 ToInnerLocStart, ToLocation, D->getDepth(),
5944 D->getPosition(),
5945 ToDeclName.getAsIdentifierInfo(), ToType,
5946 D->isParameterPack(), ToTypeSourceInfo))
5947 return ToD;
5948
5949 if (D->hasDefaultArgument()) {
5950 ExpectedExpr ToDefaultArgOrErr = import(From: D->getDefaultArgument());
5951 if (!ToDefaultArgOrErr)
5952 return ToDefaultArgOrErr.takeError();
5953 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5954 }
5955
5956 return ToD;
5957}
5958
5959ExpectedDecl
5960ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5961 // Import the name of this declaration.
5962 auto NameOrErr = import(D->getDeclName());
5963 if (!NameOrErr)
5964 return NameOrErr.takeError();
5965
5966 // Import the location of this declaration.
5967 ExpectedSLoc LocationOrErr = import(D->getLocation());
5968 if (!LocationOrErr)
5969 return LocationOrErr.takeError();
5970
5971 // Import template parameters.
5972 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5973 if (!TemplateParamsOrErr)
5974 return TemplateParamsOrErr.takeError();
5975
5976 TemplateTemplateParmDecl *ToD = nullptr;
5977 if (GetImportedOrCreateDecl(
5978 ToD, D, Importer.getToContext(),
5979 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5980 D->getDepth(), D->getPosition(), D->isParameterPack(),
5981 (*NameOrErr).getAsIdentifierInfo(), D->wasDeclaredWithTypename(),
5982 *TemplateParamsOrErr))
5983 return ToD;
5984
5985 if (D->hasDefaultArgument()) {
5986 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5987 import(From: D->getDefaultArgument());
5988 if (!ToDefaultArgOrErr)
5989 return ToDefaultArgOrErr.takeError();
5990 ToD->setDefaultArgument(C: Importer.getToContext(), DefArg: *ToDefaultArgOrErr);
5991 }
5992
5993 return ToD;
5994}
5995
5996// Returns the definition for a (forward) declaration of a TemplateDecl, if
5997// it has any definition in the redecl chain.
5998template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5999 assert(D->getTemplatedDecl() && "Should be called on templates only");
6000 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
6001 if (!ToTemplatedDef)
6002 return nullptr;
6003 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
6004 return cast_or_null<T>(TemplateWithDef);
6005}
6006
6007ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
6008
6009 // Import the major distinguishing characteristics of this class template.
6010 DeclContext *DC, *LexicalDC;
6011 DeclarationName Name;
6012 SourceLocation Loc;
6013 NamedDecl *ToD;
6014 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6015 return std::move(Err);
6016 if (ToD)
6017 return ToD;
6018
6019 // Should check if a declaration is friend in a dependent context.
6020 // Such templates are not linked together in a declaration chain.
6021 // The ASTImporter strategy is to map existing forward declarations to
6022 // imported ones only if strictly necessary, otherwise import these as new
6023 // forward declarations. In case of the "dependent friend" declarations, new
6024 // declarations are created, but not linked in a declaration chain.
6025 auto IsDependentFriend = [](ClassTemplateDecl *TD) {
6026 return TD->getFriendObjectKind() != Decl::FOK_None &&
6027 TD->getLexicalDeclContext()->isDependentContext();
6028 };
6029 bool DependentFriend = IsDependentFriend(D);
6030
6031 ClassTemplateDecl *FoundByLookup = nullptr;
6032
6033 // We may already have a template of the same name; try to find and match it.
6034 if (!DC->isFunctionOrMethod()) {
6035 SmallVector<NamedDecl *, 4> ConflictingDecls;
6036 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6037 for (auto *FoundDecl : FoundDecls) {
6038 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
6039 Decl::IDNS_TagFriend))
6040 continue;
6041
6042 Decl *Found = FoundDecl;
6043 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Val: Found);
6044 if (FoundTemplate) {
6045 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6046 continue;
6047
6048 // FIXME: sufficient conditon for 'IgnoreTemplateParmDepth'?
6049 bool IgnoreTemplateParmDepth =
6050 (FoundTemplate->getFriendObjectKind() != Decl::FOK_None) !=
6051 (D->getFriendObjectKind() != Decl::FOK_None);
6052 if (IsStructuralMatch(From: D, To: FoundTemplate, /*Complain=*/true,
6053 IgnoreTemplateParmDepth)) {
6054 if (DependentFriend || IsDependentFriend(FoundTemplate))
6055 continue;
6056
6057 ClassTemplateDecl *TemplateWithDef =
6058 getTemplateDefinition(FoundTemplate);
6059 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6060 return Importer.MapImported(D, TemplateWithDef);
6061 if (!FoundByLookup)
6062 FoundByLookup = FoundTemplate;
6063 // Search in all matches because there may be multiple decl chains,
6064 // see ASTTests test ImportExistingFriendClassTemplateDef.
6065 continue;
6066 }
6067 ConflictingDecls.push_back(Elt: FoundDecl);
6068 }
6069 }
6070
6071 if (!ConflictingDecls.empty()) {
6072 ExpectedName NameOrErr = Importer.HandleNameConflict(
6073 Name, DC, IDNS: Decl::IDNS_Ordinary, Decls: ConflictingDecls.data(),
6074 NumDecls: ConflictingDecls.size());
6075 if (NameOrErr)
6076 Name = NameOrErr.get();
6077 else
6078 return NameOrErr.takeError();
6079 }
6080 }
6081
6082 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
6083
6084 auto TemplateParamsOrErr = import(D->getTemplateParameters());
6085 if (!TemplateParamsOrErr)
6086 return TemplateParamsOrErr.takeError();
6087
6088 // Create the declaration that is being templated.
6089 CXXRecordDecl *ToTemplated;
6090 if (Error Err = importInto(To&: ToTemplated, From: FromTemplated))
6091 return std::move(Err);
6092
6093 // Create the class template declaration itself.
6094 ClassTemplateDecl *D2;
6095 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
6096 *TemplateParamsOrErr, ToTemplated))
6097 return D2;
6098
6099 ToTemplated->setDescribedClassTemplate(D2);
6100
6101 D2->setAccess(D->getAccess());
6102 D2->setLexicalDeclContext(LexicalDC);
6103
6104 addDeclToContexts(D, D2);
6105 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
6106
6107 if (FoundByLookup) {
6108 auto *Recent =
6109 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6110
6111 // It is possible that during the import of the class template definition
6112 // we start the import of a fwd friend decl of the very same class template
6113 // and we add the fwd friend decl to the lookup table. But the ToTemplated
6114 // had been created earlier and by that time the lookup could not find
6115 // anything existing, so it has no previous decl. Later, (still during the
6116 // import of the fwd friend decl) we start to import the definition again
6117 // and this time the lookup finds the previous fwd friend class template.
6118 // In this case we must set up the previous decl for the templated decl.
6119 if (!ToTemplated->getPreviousDecl()) {
6120 assert(FoundByLookup->getTemplatedDecl() &&
6121 "Found decl must have its templated decl set");
6122 CXXRecordDecl *PrevTemplated =
6123 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6124 if (ToTemplated != PrevTemplated)
6125 ToTemplated->setPreviousDecl(PrevTemplated);
6126 }
6127
6128 D2->setPreviousDecl(Recent);
6129 }
6130
6131 return D2;
6132}
6133
6134ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
6135 ClassTemplateSpecializationDecl *D) {
6136 ClassTemplateDecl *ClassTemplate;
6137 if (Error Err = importInto(To&: ClassTemplate, From: D->getSpecializedTemplate()))
6138 return std::move(Err);
6139
6140 // Import the context of this declaration.
6141 DeclContext *DC, *LexicalDC;
6142 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6143 return std::move(Err);
6144
6145 // Import template arguments.
6146 SmallVector<TemplateArgument, 2> TemplateArgs;
6147 if (Error Err =
6148 ImportTemplateArguments(FromArgs: D->getTemplateArgs().asArray(), ToArgs&: TemplateArgs))
6149 return std::move(Err);
6150 // Try to find an existing specialization with these template arguments and
6151 // template parameter list.
6152 void *InsertPos = nullptr;
6153 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6154 ClassTemplatePartialSpecializationDecl *PartialSpec =
6155 dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D);
6156
6157 // Import template parameters.
6158 TemplateParameterList *ToTPList = nullptr;
6159
6160 if (PartialSpec) {
6161 auto ToTPListOrErr = import(From: PartialSpec->getTemplateParameters());
6162 if (!ToTPListOrErr)
6163 return ToTPListOrErr.takeError();
6164 ToTPList = *ToTPListOrErr;
6165 PrevDecl = ClassTemplate->findPartialSpecialization(Args: TemplateArgs,
6166 TPL: *ToTPListOrErr,
6167 InsertPos);
6168 } else
6169 PrevDecl = ClassTemplate->findSpecialization(Args: TemplateArgs, InsertPos);
6170
6171 if (PrevDecl) {
6172 if (IsStructuralMatch(D, PrevDecl)) {
6173 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
6174 if (D->isThisDeclarationADefinition() && PrevDefinition) {
6175 Importer.MapImported(D, PrevDefinition);
6176 // Import those default field initializers which have been
6177 // instantiated in the "From" context, but not in the "To" context.
6178 for (auto *FromField : D->fields()) {
6179 auto ToOrErr = import(FromField);
6180 if (!ToOrErr)
6181 return ToOrErr.takeError();
6182 }
6183
6184 // Import those methods which have been instantiated in the
6185 // "From" context, but not in the "To" context.
6186 for (CXXMethodDecl *FromM : D->methods()) {
6187 auto ToOrErr = import(FromM);
6188 if (!ToOrErr)
6189 return ToOrErr.takeError();
6190 }
6191
6192 // TODO Import instantiated default arguments.
6193 // TODO Import instantiated exception specifications.
6194 //
6195 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
6196 // what else could be fused during an AST merge.
6197 return PrevDefinition;
6198 }
6199 } else { // ODR violation.
6200 // FIXME HandleNameConflict
6201 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
6202 }
6203 }
6204
6205 // Import the location of this declaration.
6206 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6207 if (!BeginLocOrErr)
6208 return BeginLocOrErr.takeError();
6209 ExpectedSLoc IdLocOrErr = import(D->getLocation());
6210 if (!IdLocOrErr)
6211 return IdLocOrErr.takeError();
6212
6213 // Create the specialization.
6214 ClassTemplateSpecializationDecl *D2 = nullptr;
6215 if (PartialSpec) {
6216 // Import TemplateArgumentListInfo.
6217 TemplateArgumentListInfo ToTAInfo;
6218 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
6219 if (Error Err = ImportTemplateArgumentListInfo(Container: ASTTemplateArgs, ToTAInfo))
6220 return std::move(Err);
6221
6222 QualType CanonInjType;
6223 if (Error Err = importInto(
6224 To&: CanonInjType, From: PartialSpec->getInjectedSpecializationType()))
6225 return std::move(Err);
6226 CanonInjType = CanonInjType.getCanonicalType();
6227
6228 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
6229 D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr,
6230 *IdLocOrErr, ToTPList, ClassTemplate,
6231 llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()), ToTAInfo,
6232 CanonInjType,
6233 cast_or_null<ClassTemplatePartialSpecializationDecl>(Val: PrevDecl)))
6234 return D2;
6235
6236 // Update InsertPos, because preceding import calls may have invalidated
6237 // it by adding new specializations.
6238 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(Val: D2);
6239 if (!ClassTemplate->findPartialSpecialization(Args: TemplateArgs, TPL: ToTPList,
6240 InsertPos))
6241 // Add this partial specialization to the class template.
6242 ClassTemplate->AddPartialSpecialization(D: PartSpec2, InsertPos);
6243 if (Expected<ClassTemplatePartialSpecializationDecl *> ToInstOrErr =
6244 import(From: PartialSpec->getInstantiatedFromMember()))
6245 PartSpec2->setInstantiatedFromMember(*ToInstOrErr);
6246 else
6247 return ToInstOrErr.takeError();
6248
6249 updateLookupTableForTemplateParameters(Params&: *ToTPList);
6250 } else { // Not a partial specialization.
6251 if (GetImportedOrCreateDecl(
6252 D2, D, Importer.getToContext(), D->getTagKind(), DC,
6253 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
6254 PrevDecl))
6255 return D2;
6256
6257 // Update InsertPos, because preceding import calls may have invalidated
6258 // it by adding new specializations.
6259 if (!ClassTemplate->findSpecialization(Args: TemplateArgs, InsertPos))
6260 // Add this specialization to the class template.
6261 ClassTemplate->AddSpecialization(D: D2, InsertPos);
6262 }
6263
6264 D2->setSpecializationKind(D->getSpecializationKind());
6265
6266 // Set the context of this specialization/instantiation.
6267 D2->setLexicalDeclContext(LexicalDC);
6268
6269 // Add to the DC only if it was an explicit specialization/instantiation.
6270 if (D2->isExplicitInstantiationOrSpecialization()) {
6271 LexicalDC->addDeclInternal(D2);
6272 }
6273
6274 if (auto BraceRangeOrErr = import(D->getBraceRange()))
6275 D2->setBraceRange(*BraceRangeOrErr);
6276 else
6277 return BraceRangeOrErr.takeError();
6278
6279 // Import the qualifier, if any.
6280 if (auto LocOrErr = import(D->getQualifierLoc()))
6281 D2->setQualifierInfo(*LocOrErr);
6282 else
6283 return LocOrErr.takeError();
6284
6285 if (auto *TSI = D->getTypeAsWritten()) {
6286 if (auto TInfoOrErr = import(From: TSI))
6287 D2->setTypeAsWritten(*TInfoOrErr);
6288 else
6289 return TInfoOrErr.takeError();
6290
6291 if (auto LocOrErr = import(From: D->getTemplateKeywordLoc()))
6292 D2->setTemplateKeywordLoc(*LocOrErr);
6293 else
6294 return LocOrErr.takeError();
6295
6296 if (auto LocOrErr = import(From: D->getExternLoc()))
6297 D2->setExternLoc(*LocOrErr);
6298 else
6299 return LocOrErr.takeError();
6300 }
6301
6302 if (D->getPointOfInstantiation().isValid()) {
6303 if (auto POIOrErr = import(From: D->getPointOfInstantiation()))
6304 D2->setPointOfInstantiation(*POIOrErr);
6305 else
6306 return POIOrErr.takeError();
6307 }
6308
6309 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
6310
6311 if (auto P = D->getInstantiatedFrom()) {
6312 if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) {
6313 if (auto CTDorErr = import(From: CTD))
6314 D2->setInstantiationOf(*CTDorErr);
6315 } else {
6316 auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(Val&: P);
6317 auto CTPSDOrErr = import(From: CTPSD);
6318 if (!CTPSDOrErr)
6319 return CTPSDOrErr.takeError();
6320 const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs();
6321 SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size());
6322 for (unsigned I = 0; I < DArgs.size(); ++I) {
6323 const TemplateArgument &DArg = DArgs[I];
6324 if (auto ArgOrErr = import(From: DArg))
6325 D2ArgsVec[I] = *ArgOrErr;
6326 else
6327 return ArgOrErr.takeError();
6328 }
6329 D2->setInstantiationOf(
6330 PartialSpec: *CTPSDOrErr,
6331 TemplateArgs: TemplateArgumentList::CreateCopy(Context&: Importer.getToContext(), Args: D2ArgsVec));
6332 }
6333 }
6334
6335 if (D->isCompleteDefinition())
6336 if (Error Err = ImportDefinition(D, D2))
6337 return std::move(Err);
6338
6339 return D2;
6340}
6341
6342ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
6343 // Import the major distinguishing characteristics of this variable template.
6344 DeclContext *DC, *LexicalDC;
6345 DeclarationName Name;
6346 SourceLocation Loc;
6347 NamedDecl *ToD;
6348 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6349 return std::move(Err);
6350 if (ToD)
6351 return ToD;
6352
6353 // We may already have a template of the same name; try to find and match it.
6354 assert(!DC->isFunctionOrMethod() &&
6355 "Variable templates cannot be declared at function scope");
6356
6357 SmallVector<NamedDecl *, 4> ConflictingDecls;
6358 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6359 VarTemplateDecl *FoundByLookup = nullptr;
6360 for (auto *FoundDecl : FoundDecls) {
6361 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
6362 continue;
6363
6364 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Val: FoundDecl)) {
6365 // Use the templated decl, some linkage flags are set only there.
6366 if (!hasSameVisibilityContextAndLinkage(Found: FoundTemplate->getTemplatedDecl(),
6367 From: D->getTemplatedDecl()))
6368 continue;
6369 if (IsStructuralMatch(D, FoundTemplate)) {
6370 // FIXME Check for ODR error if the two definitions have
6371 // different initializers?
6372 VarTemplateDecl *FoundDef = getTemplateDefinition(D: FoundTemplate);
6373 if (D->getDeclContext()->isRecord()) {
6374 assert(FoundTemplate->getDeclContext()->isRecord() &&
6375 "Member variable template imported as non-member, "
6376 "inconsistent imported AST?");
6377 if (FoundDef)
6378 return Importer.MapImported(D, FoundDef);
6379 if (!D->isThisDeclarationADefinition())
6380 return Importer.MapImported(D, FoundTemplate);
6381 } else {
6382 if (FoundDef && D->isThisDeclarationADefinition())
6383 return Importer.MapImported(D, FoundDef);
6384 }
6385 FoundByLookup = FoundTemplate;
6386 break;
6387 }
6388 ConflictingDecls.push_back(Elt: FoundDecl);
6389 }
6390 }
6391
6392 if (!ConflictingDecls.empty()) {
6393 ExpectedName NameOrErr = Importer.HandleNameConflict(
6394 Name, DC, IDNS: Decl::IDNS_Ordinary, Decls: ConflictingDecls.data(),
6395 NumDecls: ConflictingDecls.size());
6396 if (NameOrErr)
6397 Name = NameOrErr.get();
6398 else
6399 return NameOrErr.takeError();
6400 }
6401
6402 VarDecl *DTemplated = D->getTemplatedDecl();
6403
6404 // Import the type.
6405 // FIXME: Value not used?
6406 ExpectedType TypeOrErr = import(DTemplated->getType());
6407 if (!TypeOrErr)
6408 return TypeOrErr.takeError();
6409
6410 // Create the declaration that is being templated.
6411 VarDecl *ToTemplated;
6412 if (Error Err = importInto(To&: ToTemplated, From: DTemplated))
6413 return std::move(Err);
6414
6415 // Create the variable template declaration itself.
6416 auto TemplateParamsOrErr = import(D->getTemplateParameters());
6417 if (!TemplateParamsOrErr)
6418 return TemplateParamsOrErr.takeError();
6419
6420 VarTemplateDecl *ToVarTD;
6421 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
6422 Name, *TemplateParamsOrErr, ToTemplated))
6423 return ToVarTD;
6424
6425 ToTemplated->setDescribedVarTemplate(ToVarTD);
6426
6427 ToVarTD->setAccess(D->getAccess());
6428 ToVarTD->setLexicalDeclContext(LexicalDC);
6429 LexicalDC->addDeclInternal(ToVarTD);
6430 if (DC != Importer.getToContext().getTranslationUnitDecl())
6431 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
6432
6433 if (FoundByLookup) {
6434 auto *Recent =
6435 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6436 if (!ToTemplated->getPreviousDecl()) {
6437 auto *PrevTemplated =
6438 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6439 if (ToTemplated != PrevTemplated)
6440 ToTemplated->setPreviousDecl(PrevTemplated);
6441 }
6442 ToVarTD->setPreviousDecl(Recent);
6443 }
6444
6445 return ToVarTD;
6446}
6447
6448ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
6449 VarTemplateSpecializationDecl *D) {
6450 // A VarTemplateSpecializationDecl inherits from VarDecl, the import is done
6451 // in an analog way (but specialized for this case).
6452
6453 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
6454 auto RedeclIt = Redecls.begin();
6455 // Import the first part of the decl chain. I.e. import all previous
6456 // declarations starting from the canonical decl.
6457 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
6458 ExpectedDecl RedeclOrErr = import(*RedeclIt);
6459 if (!RedeclOrErr)
6460 return RedeclOrErr.takeError();
6461 }
6462 assert(*RedeclIt == D);
6463
6464 VarTemplateDecl *VarTemplate = nullptr;
6465 if (Error Err = importInto(To&: VarTemplate, From: D->getSpecializedTemplate()))
6466 return std::move(Err);
6467
6468 // Import the context of this declaration.
6469 DeclContext *DC, *LexicalDC;
6470 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6471 return std::move(Err);
6472
6473 // Import the location of this declaration.
6474 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6475 if (!BeginLocOrErr)
6476 return BeginLocOrErr.takeError();
6477
6478 auto IdLocOrErr = import(D->getLocation());
6479 if (!IdLocOrErr)
6480 return IdLocOrErr.takeError();
6481
6482 // Import template arguments.
6483 SmallVector<TemplateArgument, 2> TemplateArgs;
6484 if (Error Err =
6485 ImportTemplateArguments(FromArgs: D->getTemplateArgs().asArray(), ToArgs&: TemplateArgs))
6486 return std::move(Err);
6487
6488 // Try to find an existing specialization with these template arguments.
6489 void *InsertPos = nullptr;
6490 VarTemplateSpecializationDecl *FoundSpecialization =
6491 VarTemplate->findSpecialization(Args: TemplateArgs, InsertPos);
6492 if (FoundSpecialization) {
6493 if (IsStructuralMatch(D, FoundSpecialization)) {
6494 VarDecl *FoundDef = FoundSpecialization->getDefinition();
6495 if (D->getDeclContext()->isRecord()) {
6496 // In a record, it is allowed only to have one optional declaration and
6497 // one definition of the (static or constexpr) variable template.
6498 assert(
6499 FoundSpecialization->getDeclContext()->isRecord() &&
6500 "Member variable template specialization imported as non-member, "
6501 "inconsistent imported AST?");
6502 if (FoundDef)
6503 return Importer.MapImported(D, FoundDef);
6504 if (!D->isThisDeclarationADefinition())
6505 return Importer.MapImported(D, FoundSpecialization);
6506 } else {
6507 // If definition is imported and there is already one, map to it.
6508 // Otherwise create a new variable and link it to the existing.
6509 if (FoundDef && D->isThisDeclarationADefinition())
6510 return Importer.MapImported(D, FoundDef);
6511 }
6512 } else {
6513 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
6514 }
6515 }
6516
6517 VarTemplateSpecializationDecl *D2 = nullptr;
6518
6519 TemplateArgumentListInfo ToTAInfo;
6520 if (const ASTTemplateArgumentListInfo *Args = D->getTemplateArgsInfo()) {
6521 if (Error Err = ImportTemplateArgumentListInfo(Container: *Args, ToTAInfo))
6522 return std::move(Err);
6523 }
6524
6525 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
6526 // Create a new specialization.
6527 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(Val: D)) {
6528 // Import TemplateArgumentListInfo
6529 TemplateArgumentListInfo ArgInfos;
6530 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
6531 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
6532 if (Error Err =
6533 ImportTemplateArgumentListInfo(Container: *FromTAArgsAsWritten, ToTAInfo&: ArgInfos))
6534 return std::move(Err);
6535
6536 auto ToTPListOrErr = import(From: FromPartial->getTemplateParameters());
6537 if (!ToTPListOrErr)
6538 return ToTPListOrErr.takeError();
6539
6540 PartVarSpecDecl *ToPartial;
6541 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
6542 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
6543 VarTemplate, QualType(), nullptr,
6544 D->getStorageClass(), TemplateArgs, ArgInfos))
6545 return ToPartial;
6546
6547 if (Expected<PartVarSpecDecl *> ToInstOrErr =
6548 import(From: FromPartial->getInstantiatedFromMember()))
6549 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
6550 else
6551 return ToInstOrErr.takeError();
6552
6553 if (FromPartial->isMemberSpecialization())
6554 ToPartial->setMemberSpecialization();
6555
6556 D2 = ToPartial;
6557
6558 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
6559 // to adopt template parameters.
6560 // updateLookupTableForTemplateParameters(**ToTPListOrErr);
6561 } else { // Full specialization
6562 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
6563 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
6564 QualType(), nullptr, D->getStorageClass(),
6565 TemplateArgs))
6566 return D2;
6567 }
6568
6569 QualType T;
6570 if (Error Err = importInto(T, D->getType()))
6571 return std::move(Err);
6572 D2->setType(T);
6573
6574 auto TInfoOrErr = import(D->getTypeSourceInfo());
6575 if (!TInfoOrErr)
6576 return TInfoOrErr.takeError();
6577 D2->setTypeSourceInfo(*TInfoOrErr);
6578
6579 if (D->getPointOfInstantiation().isValid()) {
6580 if (ExpectedSLoc POIOrErr = import(From: D->getPointOfInstantiation()))
6581 D2->setPointOfInstantiation(*POIOrErr);
6582 else
6583 return POIOrErr.takeError();
6584 }
6585
6586 D2->setSpecializationKind(D->getSpecializationKind());
6587 D2->setTemplateArgsInfo(ToTAInfo);
6588
6589 if (auto LocOrErr = import(D->getQualifierLoc()))
6590 D2->setQualifierInfo(*LocOrErr);
6591 else
6592 return LocOrErr.takeError();
6593
6594 if (D->isConstexpr())
6595 D2->setConstexpr(true);
6596
6597 D2->setAccess(D->getAccess());
6598
6599 if (Error Err = ImportInitializer(D, D2))
6600 return std::move(Err);
6601
6602 if (FoundSpecialization)
6603 D2->setPreviousDecl(FoundSpecialization->getMostRecentDecl());
6604
6605 VarTemplate->AddSpecialization(D: D2, InsertPos);
6606
6607 addDeclToContexts(D, D2);
6608
6609 // Import the rest of the chain. I.e. import all subsequent declarations.
6610 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
6611 ExpectedDecl RedeclOrErr = import(*RedeclIt);
6612 if (!RedeclOrErr)
6613 return RedeclOrErr.takeError();
6614 }
6615
6616 return D2;
6617}
6618
6619ExpectedDecl
6620ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
6621 DeclContext *DC, *LexicalDC;
6622 DeclarationName Name;
6623 SourceLocation Loc;
6624 NamedDecl *ToD;
6625
6626 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6627 return std::move(Err);
6628
6629 if (ToD)
6630 return ToD;
6631
6632 const FunctionTemplateDecl *FoundByLookup = nullptr;
6633
6634 // Try to find a function in our own ("to") context with the same name, same
6635 // type, and in the same context as the function we're importing.
6636 // FIXME Split this into a separate function.
6637 if (!LexicalDC->isFunctionOrMethod()) {
6638 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
6639 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6640 for (auto *FoundDecl : FoundDecls) {
6641 if (!FoundDecl->isInIdentifierNamespace(IDNS))
6642 continue;
6643
6644 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(Val: FoundDecl)) {
6645 if (!hasSameVisibilityContextAndLinkage(Found: FoundTemplate, From: D))
6646 continue;
6647 if (IsStructuralMatch(D, FoundTemplate)) {
6648 FunctionTemplateDecl *TemplateWithDef =
6649 getTemplateDefinition(D: FoundTemplate);
6650 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6651 return Importer.MapImported(D, TemplateWithDef);
6652
6653 FoundByLookup = FoundTemplate;
6654 break;
6655 // TODO: handle conflicting names
6656 }
6657 }
6658 }
6659 }
6660
6661 auto ParamsOrErr = import(D->getTemplateParameters());
6662 if (!ParamsOrErr)
6663 return ParamsOrErr.takeError();
6664 TemplateParameterList *Params = *ParamsOrErr;
6665
6666 FunctionDecl *TemplatedFD;
6667 if (Error Err = importInto(To&: TemplatedFD, From: D->getTemplatedDecl()))
6668 return std::move(Err);
6669
6670 // At creation of the template the template parameters are "adopted"
6671 // (DeclContext is changed). After this possible change the lookup table
6672 // must be updated.
6673 // At deduction guides the DeclContext of the template parameters may be
6674 // different from what we would expect, it may be the class template, or a
6675 // probably different CXXDeductionGuideDecl. This may come from the fact that
6676 // the template parameter objects may be shared between deduction guides or
6677 // the class template, and at creation of multiple FunctionTemplateDecl
6678 // objects (for deduction guides) the same parameters are re-used. The
6679 // "adoption" happens multiple times with different parent, even recursively
6680 // for TemplateTemplateParmDecl. The same happens at import when the
6681 // FunctionTemplateDecl objects are created, but in different order.
6682 // In this way the DeclContext of these template parameters is not necessarily
6683 // the same as in the "from" context.
6684 SmallVector<DeclContext *, 2> OldParamDC;
6685 OldParamDC.reserve(N: Params->size());
6686 llvm::transform(Range&: *Params, d_first: std::back_inserter(x&: OldParamDC),
6687 F: [](NamedDecl *ND) { return ND->getDeclContext(); });
6688
6689 FunctionTemplateDecl *ToFunc;
6690 if (GetImportedOrCreateDecl(ToD&: ToFunc, FromD: D, args&: Importer.getToContext(), args&: DC, args&: Loc, args&: Name,
6691 args&: Params, args&: TemplatedFD))
6692 return ToFunc;
6693
6694 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6695
6696 ToFunc->setAccess(D->getAccess());
6697 ToFunc->setLexicalDeclContext(LexicalDC);
6698 addDeclToContexts(D, ToFunc);
6699
6700 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
6701 if (LT && !OldParamDC.empty()) {
6702 for (unsigned int I = 0; I < OldParamDC.size(); ++I)
6703 LT->updateForced(ND: Params->getParam(Idx: I), OldDC: OldParamDC[I]);
6704 }
6705
6706 if (FoundByLookup) {
6707 auto *Recent =
6708 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6709 if (!TemplatedFD->getPreviousDecl()) {
6710 assert(FoundByLookup->getTemplatedDecl() &&
6711 "Found decl must have its templated decl set");
6712 auto *PrevTemplated =
6713 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6714 if (TemplatedFD != PrevTemplated)
6715 TemplatedFD->setPreviousDecl(PrevTemplated);
6716 }
6717 ToFunc->setPreviousDecl(Recent);
6718 }
6719
6720 return ToFunc;
6721}
6722
6723//----------------------------------------------------------------------------
6724// Import Statements
6725//----------------------------------------------------------------------------
6726
6727ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
6728 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
6729 << S->getStmtClassName();
6730 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
6731}
6732
6733
6734ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
6735 if (Importer.returnWithErrorInTest())
6736 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
6737 SmallVector<IdentifierInfo *, 4> Names;
6738 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6739 IdentifierInfo *ToII = Importer.Import(FromId: S->getOutputIdentifier(i: I));
6740 // ToII is nullptr when no symbolic name is given for output operand
6741 // see ParseStmtAsm::ParseAsmOperandsOpt
6742 Names.push_back(Elt: ToII);
6743 }
6744
6745 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6746 IdentifierInfo *ToII = Importer.Import(FromId: S->getInputIdentifier(i: I));
6747 // ToII is nullptr when no symbolic name is given for input operand
6748 // see ParseStmtAsm::ParseAsmOperandsOpt
6749 Names.push_back(Elt: ToII);
6750 }
6751
6752 SmallVector<StringLiteral *, 4> Clobbers;
6753 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
6754 if (auto ClobberOrErr = import(From: S->getClobberStringLiteral(i: I)))
6755 Clobbers.push_back(Elt: *ClobberOrErr);
6756 else
6757 return ClobberOrErr.takeError();
6758
6759 }
6760
6761 SmallVector<StringLiteral *, 4> Constraints;
6762 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6763 if (auto OutputOrErr = import(From: S->getOutputConstraintLiteral(i: I)))
6764 Constraints.push_back(Elt: *OutputOrErr);
6765 else
6766 return OutputOrErr.takeError();
6767 }
6768
6769 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6770 if (auto InputOrErr = import(From: S->getInputConstraintLiteral(i: I)))
6771 Constraints.push_back(Elt: *InputOrErr);
6772 else
6773 return InputOrErr.takeError();
6774 }
6775
6776 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6777 S->getNumLabels());
6778 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
6779 return std::move(Err);
6780
6781 if (Error Err =
6782 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
6783 return std::move(Err);
6784
6785 if (Error Err = ImportArrayChecked(
6786 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6787 return std::move(Err);
6788
6789 ExpectedSLoc AsmLocOrErr = import(From: S->getAsmLoc());
6790 if (!AsmLocOrErr)
6791 return AsmLocOrErr.takeError();
6792 auto AsmStrOrErr = import(From: S->getAsmString());
6793 if (!AsmStrOrErr)
6794 return AsmStrOrErr.takeError();
6795 ExpectedSLoc RParenLocOrErr = import(From: S->getRParenLoc());
6796 if (!RParenLocOrErr)
6797 return RParenLocOrErr.takeError();
6798
6799 return new (Importer.getToContext()) GCCAsmStmt(
6800 Importer.getToContext(),
6801 *AsmLocOrErr,
6802 S->isSimple(),
6803 S->isVolatile(),
6804 S->getNumOutputs(),
6805 S->getNumInputs(),
6806 Names.data(),
6807 Constraints.data(),
6808 Exprs.data(),
6809 *AsmStrOrErr,
6810 S->getNumClobbers(),
6811 Clobbers.data(),
6812 S->getNumLabels(),
6813 *RParenLocOrErr);
6814}
6815
6816ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
6817
6818 Error Err = Error::success();
6819 auto ToDG = importChecked(Err, From: S->getDeclGroup());
6820 auto ToBeginLoc = importChecked(Err, From: S->getBeginLoc());
6821 auto ToEndLoc = importChecked(Err, From: S->getEndLoc());
6822 if (Err)
6823 return std::move(Err);
6824 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
6825}
6826
6827ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
6828 ExpectedSLoc ToSemiLocOrErr = import(From: S->getSemiLoc());
6829 if (!ToSemiLocOrErr)
6830 return ToSemiLocOrErr.takeError();
6831 return new (Importer.getToContext()) NullStmt(
6832 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
6833}
6834
6835ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
6836 SmallVector<Stmt *, 8> ToStmts(S->size());
6837
6838 if (Error Err = ImportContainerChecked(InContainer: S->body(), OutContainer&: ToStmts))
6839 return std::move(Err);
6840
6841 ExpectedSLoc ToLBracLocOrErr = import(From: S->getLBracLoc());
6842 if (!ToLBracLocOrErr)
6843 return ToLBracLocOrErr.takeError();
6844
6845 ExpectedSLoc ToRBracLocOrErr = import(From: S->getRBracLoc());
6846 if (!ToRBracLocOrErr)
6847 return ToRBracLocOrErr.takeError();
6848
6849 FPOptionsOverride FPO =
6850 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride();
6851 return CompoundStmt::Create(C: Importer.getToContext(), Stmts: ToStmts, FPFeatures: FPO,
6852 LB: *ToLBracLocOrErr, RB: *ToRBracLocOrErr);
6853}
6854
6855ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
6856
6857 Error Err = Error::success();
6858 auto ToLHS = importChecked(Err, From: S->getLHS());
6859 auto ToRHS = importChecked(Err, From: S->getRHS());
6860 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6861 auto ToCaseLoc = importChecked(Err, From: S->getCaseLoc());
6862 auto ToEllipsisLoc = importChecked(Err, From: S->getEllipsisLoc());
6863 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6864 if (Err)
6865 return std::move(Err);
6866
6867 auto *ToStmt = CaseStmt::Create(Ctx: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS,
6868 caseLoc: ToCaseLoc, ellipsisLoc: ToEllipsisLoc, colonLoc: ToColonLoc);
6869 ToStmt->setSubStmt(ToSubStmt);
6870
6871 return ToStmt;
6872}
6873
6874ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
6875
6876 Error Err = Error::success();
6877 auto ToDefaultLoc = importChecked(Err, From: S->getDefaultLoc());
6878 auto ToColonLoc = importChecked(Err, From: S->getColonLoc());
6879 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6880 if (Err)
6881 return std::move(Err);
6882
6883 return new (Importer.getToContext()) DefaultStmt(
6884 ToDefaultLoc, ToColonLoc, ToSubStmt);
6885}
6886
6887ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
6888
6889 Error Err = Error::success();
6890 auto ToIdentLoc = importChecked(Err, From: S->getIdentLoc());
6891 auto ToLabelDecl = importChecked(Err, From: S->getDecl());
6892 auto ToSubStmt = importChecked(Err, From: S->getSubStmt());
6893 if (Err)
6894 return std::move(Err);
6895
6896 return new (Importer.getToContext()) LabelStmt(
6897 ToIdentLoc, ToLabelDecl, ToSubStmt);
6898}
6899
6900ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
6901 ExpectedSLoc ToAttrLocOrErr = import(From: S->getAttrLoc());
6902 if (!ToAttrLocOrErr)
6903 return ToAttrLocOrErr.takeError();
6904 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
6905 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
6906 if (Error Err = ImportContainerChecked(InContainer: FromAttrs, OutContainer&: ToAttrs))
6907 return std::move(Err);
6908 ExpectedStmt ToSubStmtOrErr = import(From: S->getSubStmt());
6909 if (!ToSubStmtOrErr)
6910 return ToSubStmtOrErr.takeError();
6911
6912 return AttributedStmt::Create(
6913 C: Importer.getToContext(), Loc: *ToAttrLocOrErr, Attrs: ToAttrs, SubStmt: *ToSubStmtOrErr);
6914}
6915
6916ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
6917
6918 Error Err = Error::success();
6919 auto ToIfLoc = importChecked(Err, From: S->getIfLoc());
6920 auto ToInit = importChecked(Err, From: S->getInit());
6921 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6922 auto ToCond = importChecked(Err, From: S->getCond());
6923 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6924 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6925 auto ToThen = importChecked(Err, From: S->getThen());
6926 auto ToElseLoc = importChecked(Err, From: S->getElseLoc());
6927 auto ToElse = importChecked(Err, From: S->getElse());
6928 if (Err)
6929 return std::move(Err);
6930
6931 return IfStmt::Create(Ctx: Importer.getToContext(), IL: ToIfLoc, Kind: S->getStatementKind(),
6932 Init: ToInit, Var: ToConditionVariable, Cond: ToCond, LPL: ToLParenLoc,
6933 RPL: ToRParenLoc, Then: ToThen, EL: ToElseLoc, Else: ToElse);
6934}
6935
6936ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
6937
6938 Error Err = Error::success();
6939 auto ToInit = importChecked(Err, From: S->getInit());
6940 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6941 auto ToCond = importChecked(Err, From: S->getCond());
6942 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6943 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6944 auto ToBody = importChecked(Err, From: S->getBody());
6945 auto ToSwitchLoc = importChecked(Err, From: S->getSwitchLoc());
6946 if (Err)
6947 return std::move(Err);
6948
6949 auto *ToStmt =
6950 SwitchStmt::Create(Ctx: Importer.getToContext(), Init: ToInit, Var: ToConditionVariable,
6951 Cond: ToCond, LParenLoc: ToLParenLoc, RParenLoc: ToRParenLoc);
6952 ToStmt->setBody(ToBody);
6953 ToStmt->setSwitchLoc(ToSwitchLoc);
6954
6955 // Now we have to re-chain the cases.
6956 SwitchCase *LastChainedSwitchCase = nullptr;
6957 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
6958 SC = SC->getNextSwitchCase()) {
6959 Expected<SwitchCase *> ToSCOrErr = import(From: SC);
6960 if (!ToSCOrErr)
6961 return ToSCOrErr.takeError();
6962 if (LastChainedSwitchCase)
6963 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
6964 else
6965 ToStmt->setSwitchCaseList(*ToSCOrErr);
6966 LastChainedSwitchCase = *ToSCOrErr;
6967 }
6968
6969 return ToStmt;
6970}
6971
6972ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
6973
6974 Error Err = Error::success();
6975 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
6976 auto ToCond = importChecked(Err, From: S->getCond());
6977 auto ToBody = importChecked(Err, From: S->getBody());
6978 auto ToWhileLoc = importChecked(Err, From: S->getWhileLoc());
6979 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
6980 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6981 if (Err)
6982 return std::move(Err);
6983
6984 return WhileStmt::Create(Ctx: Importer.getToContext(), Var: ToConditionVariable, Cond: ToCond,
6985 Body: ToBody, WL: ToWhileLoc, LParenLoc: ToLParenLoc, RParenLoc: ToRParenLoc);
6986}
6987
6988ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
6989
6990 Error Err = Error::success();
6991 auto ToBody = importChecked(Err, From: S->getBody());
6992 auto ToCond = importChecked(Err, From: S->getCond());
6993 auto ToDoLoc = importChecked(Err, From: S->getDoLoc());
6994 auto ToWhileLoc = importChecked(Err, From: S->getWhileLoc());
6995 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
6996 if (Err)
6997 return std::move(Err);
6998
6999 return new (Importer.getToContext()) DoStmt(
7000 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
7001}
7002
7003ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
7004
7005 Error Err = Error::success();
7006 auto ToInit = importChecked(Err, From: S->getInit());
7007 auto ToCond = importChecked(Err, From: S->getCond());
7008 auto ToConditionVariable = importChecked(Err, From: S->getConditionVariable());
7009 auto ToInc = importChecked(Err, From: S->getInc());
7010 auto ToBody = importChecked(Err, From: S->getBody());
7011 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7012 auto ToLParenLoc = importChecked(Err, From: S->getLParenLoc());
7013 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7014 if (Err)
7015 return std::move(Err);
7016
7017 return new (Importer.getToContext()) ForStmt(
7018 Importer.getToContext(),
7019 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
7020 ToRParenLoc);
7021}
7022
7023ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
7024
7025 Error Err = Error::success();
7026 auto ToLabel = importChecked(Err, From: S->getLabel());
7027 auto ToGotoLoc = importChecked(Err, From: S->getGotoLoc());
7028 auto ToLabelLoc = importChecked(Err, From: S->getLabelLoc());
7029 if (Err)
7030 return std::move(Err);
7031
7032 return new (Importer.getToContext()) GotoStmt(
7033 ToLabel, ToGotoLoc, ToLabelLoc);
7034}
7035
7036ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
7037
7038 Error Err = Error::success();
7039 auto ToGotoLoc = importChecked(Err, From: S->getGotoLoc());
7040 auto ToStarLoc = importChecked(Err, From: S->getStarLoc());
7041 auto ToTarget = importChecked(Err, From: S->getTarget());
7042 if (Err)
7043 return std::move(Err);
7044
7045 return new (Importer.getToContext()) IndirectGotoStmt(
7046 ToGotoLoc, ToStarLoc, ToTarget);
7047}
7048
7049ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
7050 ExpectedSLoc ToContinueLocOrErr = import(From: S->getContinueLoc());
7051 if (!ToContinueLocOrErr)
7052 return ToContinueLocOrErr.takeError();
7053 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
7054}
7055
7056ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
7057 auto ToBreakLocOrErr = import(From: S->getBreakLoc());
7058 if (!ToBreakLocOrErr)
7059 return ToBreakLocOrErr.takeError();
7060 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
7061}
7062
7063ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
7064
7065 Error Err = Error::success();
7066 auto ToReturnLoc = importChecked(Err, From: S->getReturnLoc());
7067 auto ToRetValue = importChecked(Err, From: S->getRetValue());
7068 auto ToNRVOCandidate = importChecked(Err, From: S->getNRVOCandidate());
7069 if (Err)
7070 return std::move(Err);
7071
7072 return ReturnStmt::Create(Ctx: Importer.getToContext(), RL: ToReturnLoc, E: ToRetValue,
7073 NRVOCandidate: ToNRVOCandidate);
7074}
7075
7076ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
7077
7078 Error Err = Error::success();
7079 auto ToCatchLoc = importChecked(Err, From: S->getCatchLoc());
7080 auto ToExceptionDecl = importChecked(Err, From: S->getExceptionDecl());
7081 auto ToHandlerBlock = importChecked(Err, From: S->getHandlerBlock());
7082 if (Err)
7083 return std::move(Err);
7084
7085 return new (Importer.getToContext()) CXXCatchStmt (
7086 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
7087}
7088
7089ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
7090 ExpectedSLoc ToTryLocOrErr = import(From: S->getTryLoc());
7091 if (!ToTryLocOrErr)
7092 return ToTryLocOrErr.takeError();
7093
7094 ExpectedStmt ToTryBlockOrErr = import(From: S->getTryBlock());
7095 if (!ToTryBlockOrErr)
7096 return ToTryBlockOrErr.takeError();
7097
7098 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
7099 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
7100 CXXCatchStmt *FromHandler = S->getHandler(i: HI);
7101 if (auto ToHandlerOrErr = import(From: FromHandler))
7102 ToHandlers[HI] = *ToHandlerOrErr;
7103 else
7104 return ToHandlerOrErr.takeError();
7105 }
7106
7107 return CXXTryStmt::Create(C: Importer.getToContext(), tryLoc: *ToTryLocOrErr,
7108 tryBlock: cast<CompoundStmt>(Val: *ToTryBlockOrErr), handlers: ToHandlers);
7109}
7110
7111ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
7112
7113 Error Err = Error::success();
7114 auto ToInit = importChecked(Err, From: S->getInit());
7115 auto ToRangeStmt = importChecked(Err, From: S->getRangeStmt());
7116 auto ToBeginStmt = importChecked(Err, From: S->getBeginStmt());
7117 auto ToEndStmt = importChecked(Err, From: S->getEndStmt());
7118 auto ToCond = importChecked(Err, From: S->getCond());
7119 auto ToInc = importChecked(Err, From: S->getInc());
7120 auto ToLoopVarStmt = importChecked(Err, From: S->getLoopVarStmt());
7121 auto ToBody = importChecked(Err, From: S->getBody());
7122 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7123 auto ToCoawaitLoc = importChecked(Err, From: S->getCoawaitLoc());
7124 auto ToColonLoc = importChecked(Err, From: S->getColonLoc());
7125 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7126 if (Err)
7127 return std::move(Err);
7128
7129 return new (Importer.getToContext()) CXXForRangeStmt(
7130 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
7131 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
7132}
7133
7134ExpectedStmt
7135ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
7136 Error Err = Error::success();
7137 auto ToElement = importChecked(Err, From: S->getElement());
7138 auto ToCollection = importChecked(Err, From: S->getCollection());
7139 auto ToBody = importChecked(Err, From: S->getBody());
7140 auto ToForLoc = importChecked(Err, From: S->getForLoc());
7141 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7142 if (Err)
7143 return std::move(Err);
7144
7145 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
7146 ToCollection,
7147 ToBody,
7148 ToForLoc,
7149 ToRParenLoc);
7150}
7151
7152ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
7153
7154 Error Err = Error::success();
7155 auto ToAtCatchLoc = importChecked(Err, From: S->getAtCatchLoc());
7156 auto ToRParenLoc = importChecked(Err, From: S->getRParenLoc());
7157 auto ToCatchParamDecl = importChecked(Err, From: S->getCatchParamDecl());
7158 auto ToCatchBody = importChecked(Err, From: S->getCatchBody());
7159 if (Err)
7160 return std::move(Err);
7161
7162 return new (Importer.getToContext()) ObjCAtCatchStmt (
7163 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
7164}
7165
7166ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
7167 ExpectedSLoc ToAtFinallyLocOrErr = import(From: S->getAtFinallyLoc());
7168 if (!ToAtFinallyLocOrErr)
7169 return ToAtFinallyLocOrErr.takeError();
7170 ExpectedStmt ToAtFinallyStmtOrErr = import(From: S->getFinallyBody());
7171 if (!ToAtFinallyStmtOrErr)
7172 return ToAtFinallyStmtOrErr.takeError();
7173 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
7174 *ToAtFinallyStmtOrErr);
7175}
7176
7177ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
7178
7179 Error Err = Error::success();
7180 auto ToAtTryLoc = importChecked(Err, From: S->getAtTryLoc());
7181 auto ToTryBody = importChecked(Err, From: S->getTryBody());
7182 auto ToFinallyStmt = importChecked(Err, From: S->getFinallyStmt());
7183 if (Err)
7184 return std::move(Err);
7185
7186 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
7187 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
7188 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(I: CI);
7189 if (ExpectedStmt ToCatchStmtOrErr = import(From: FromCatchStmt))
7190 ToCatchStmts[CI] = *ToCatchStmtOrErr;
7191 else
7192 return ToCatchStmtOrErr.takeError();
7193 }
7194
7195 return ObjCAtTryStmt::Create(Context: Importer.getToContext(),
7196 atTryLoc: ToAtTryLoc, atTryStmt: ToTryBody,
7197 CatchStmts: ToCatchStmts.begin(), NumCatchStmts: ToCatchStmts.size(),
7198 atFinallyStmt: ToFinallyStmt);
7199}
7200
7201ExpectedStmt
7202ASTNodeImporter::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
7203
7204 Error Err = Error::success();
7205 auto ToAtSynchronizedLoc = importChecked(Err, From: S->getAtSynchronizedLoc());
7206 auto ToSynchExpr = importChecked(Err, From: S->getSynchExpr());
7207 auto ToSynchBody = importChecked(Err, From: S->getSynchBody());
7208 if (Err)
7209 return std::move(Err);
7210
7211 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
7212 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
7213}
7214
7215ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
7216 ExpectedSLoc ToThrowLocOrErr = import(From: S->getThrowLoc());
7217 if (!ToThrowLocOrErr)
7218 return ToThrowLocOrErr.takeError();
7219 ExpectedExpr ToThrowExprOrErr = import(From: S->getThrowExpr());
7220 if (!ToThrowExprOrErr)
7221 return ToThrowExprOrErr.takeError();
7222 return new (Importer.getToContext()) ObjCAtThrowStmt(
7223 *ToThrowLocOrErr, *ToThrowExprOrErr);
7224}
7225
7226ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
7227 ObjCAutoreleasePoolStmt *S) {
7228 ExpectedSLoc ToAtLocOrErr = import(From: S->getAtLoc());
7229 if (!ToAtLocOrErr)
7230 return ToAtLocOrErr.takeError();
7231 ExpectedStmt ToSubStmtOrErr = import(From: S->getSubStmt());
7232 if (!ToSubStmtOrErr)
7233 return ToSubStmtOrErr.takeError();
7234 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
7235 *ToSubStmtOrErr);
7236}
7237
7238//----------------------------------------------------------------------------
7239// Import Expressions
7240//----------------------------------------------------------------------------
7241ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
7242 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
7243 << E->getStmtClassName();
7244 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
7245}
7246
7247ExpectedStmt ASTNodeImporter::VisitSourceLocExpr(SourceLocExpr *E) {
7248 Error Err = Error::success();
7249 auto ToType = importChecked(Err, E->getType());
7250 auto BLoc = importChecked(Err, From: E->getBeginLoc());
7251 auto RParenLoc = importChecked(Err, From: E->getEndLoc());
7252 if (Err)
7253 return std::move(Err);
7254 auto ParentContextOrErr = Importer.ImportContext(FromDC: E->getParentContext());
7255 if (!ParentContextOrErr)
7256 return ParentContextOrErr.takeError();
7257
7258 return new (Importer.getToContext())
7259 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc,
7260 RParenLoc, *ParentContextOrErr);
7261}
7262
7263ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
7264
7265 Error Err = Error::success();
7266 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7267 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7268 auto ToWrittenTypeInfo = importChecked(Err, From: E->getWrittenTypeInfo());
7269 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7270 auto ToType = importChecked(Err, E->getType());
7271 if (Err)
7272 return std::move(Err);
7273
7274 return new (Importer.getToContext()) VAArgExpr(
7275 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
7276 E->isMicrosoftABI());
7277}
7278
7279ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
7280
7281 Error Err = Error::success();
7282 auto ToCond = importChecked(Err, From: E->getCond());
7283 auto ToLHS = importChecked(Err, From: E->getLHS());
7284 auto ToRHS = importChecked(Err, From: E->getRHS());
7285 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7286 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7287 auto ToType = importChecked(Err, E->getType());
7288 if (Err)
7289 return std::move(Err);
7290
7291 ExprValueKind VK = E->getValueKind();
7292 ExprObjectKind OK = E->getObjectKind();
7293
7294 // The value of CondIsTrue only matters if the value is not
7295 // condition-dependent.
7296 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
7297
7298 return new (Importer.getToContext())
7299 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
7300 ToRParenLoc, CondIsTrue);
7301}
7302
7303ExpectedStmt ASTNodeImporter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
7304 Error Err = Error::success();
7305 auto *ToSrcExpr = importChecked(Err, From: E->getSrcExpr());
7306 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7307 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7308 auto ToType = importChecked(Err, E->getType());
7309 auto *ToTSI = importChecked(Err, From: E->getTypeSourceInfo());
7310 if (Err)
7311 return std::move(Err);
7312
7313 return new (Importer.getToContext())
7314 ConvertVectorExpr(ToSrcExpr, ToTSI, ToType, E->getValueKind(),
7315 E->getObjectKind(), ToBuiltinLoc, ToRParenLoc);
7316}
7317
7318ExpectedStmt ASTNodeImporter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
7319 Error Err = Error::success();
7320 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7321 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7322 auto ToType = importChecked(Err, E->getType());
7323 const unsigned NumSubExprs = E->getNumSubExprs();
7324
7325 llvm::SmallVector<Expr *, 8> ToSubExprs;
7326 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs);
7327 ToSubExprs.resize(N: NumSubExprs);
7328
7329 if ((Err = ImportContainerChecked(InContainer: FromSubExprs, OutContainer&: ToSubExprs)))
7330 return std::move(Err);
7331
7332 return new (Importer.getToContext()) ShuffleVectorExpr(
7333 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc);
7334}
7335
7336ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
7337 ExpectedType TypeOrErr = import(E->getType());
7338 if (!TypeOrErr)
7339 return TypeOrErr.takeError();
7340
7341 ExpectedSLoc BeginLocOrErr = import(From: E->getBeginLoc());
7342 if (!BeginLocOrErr)
7343 return BeginLocOrErr.takeError();
7344
7345 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
7346}
7347
7348ExpectedStmt
7349ASTNodeImporter::VisitGenericSelectionExpr(GenericSelectionExpr *E) {
7350 Error Err = Error::success();
7351 auto ToGenericLoc = importChecked(Err, From: E->getGenericLoc());
7352 Expr *ToControllingExpr = nullptr;
7353 TypeSourceInfo *ToControllingType = nullptr;
7354 if (E->isExprPredicate())
7355 ToControllingExpr = importChecked(Err, From: E->getControllingExpr());
7356 else
7357 ToControllingType = importChecked(Err, From: E->getControllingType());
7358 assert((ToControllingExpr || ToControllingType) &&
7359 "Either the controlling expr or type must be nonnull");
7360 auto ToDefaultLoc = importChecked(Err, From: E->getDefaultLoc());
7361 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7362 if (Err)
7363 return std::move(Err);
7364
7365 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
7366 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
7367 if (Error Err = ImportContainerChecked(InContainer: FromAssocTypes, OutContainer&: ToAssocTypes))
7368 return std::move(Err);
7369
7370 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
7371 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
7372 if (Error Err = ImportContainerChecked(InContainer: FromAssocExprs, OutContainer&: ToAssocExprs))
7373 return std::move(Err);
7374
7375 const ASTContext &ToCtx = Importer.getToContext();
7376 if (E->isResultDependent()) {
7377 if (ToControllingExpr) {
7378 return GenericSelectionExpr::Create(
7379 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7380 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7381 E->containsUnexpandedParameterPack());
7382 }
7383 return GenericSelectionExpr::Create(
7384 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7385 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7386 E->containsUnexpandedParameterPack());
7387 }
7388
7389 if (ToControllingExpr) {
7390 return GenericSelectionExpr::Create(
7391 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7392 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7393 E->containsUnexpandedParameterPack(), E->getResultIndex());
7394 }
7395 return GenericSelectionExpr::Create(
7396 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7397 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7398 E->containsUnexpandedParameterPack(), E->getResultIndex());
7399}
7400
7401ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
7402
7403 Error Err = Error::success();
7404 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7405 auto ToType = importChecked(Err, E->getType());
7406 auto ToFunctionName = importChecked(Err, From: E->getFunctionName());
7407 if (Err)
7408 return std::move(Err);
7409
7410 return PredefinedExpr::Create(Ctx: Importer.getToContext(), L: ToBeginLoc, FNTy: ToType,
7411 IK: E->getIdentKind(), IsTransparent: E->isTransparent(),
7412 SL: ToFunctionName);
7413}
7414
7415ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
7416
7417 Error Err = Error::success();
7418 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
7419 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
7420 auto ToDecl = importChecked(Err, From: E->getDecl());
7421 auto ToLocation = importChecked(Err, From: E->getLocation());
7422 auto ToType = importChecked(Err, E->getType());
7423 if (Err)
7424 return std::move(Err);
7425
7426 NamedDecl *ToFoundD = nullptr;
7427 if (E->getDecl() != E->getFoundDecl()) {
7428 auto FoundDOrErr = import(From: E->getFoundDecl());
7429 if (!FoundDOrErr)
7430 return FoundDOrErr.takeError();
7431 ToFoundD = *FoundDOrErr;
7432 }
7433
7434 TemplateArgumentListInfo ToTAInfo;
7435 TemplateArgumentListInfo *ToResInfo = nullptr;
7436 if (E->hasExplicitTemplateArgs()) {
7437 if (Error Err =
7438 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
7439 Container: E->template_arguments(), Result&: ToTAInfo))
7440 return std::move(Err);
7441 ToResInfo = &ToTAInfo;
7442 }
7443
7444 auto *ToE = DeclRefExpr::Create(
7445 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
7446 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
7447 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
7448 if (E->hadMultipleCandidates())
7449 ToE->setHadMultipleCandidates(true);
7450 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
7451 return ToE;
7452}
7453
7454ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
7455 ExpectedType TypeOrErr = import(E->getType());
7456 if (!TypeOrErr)
7457 return TypeOrErr.takeError();
7458
7459 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
7460}
7461
7462ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
7463 ExpectedExpr ToInitOrErr = import(From: E->getInit());
7464 if (!ToInitOrErr)
7465 return ToInitOrErr.takeError();
7466
7467 ExpectedSLoc ToEqualOrColonLocOrErr = import(From: E->getEqualOrColonLoc());
7468 if (!ToEqualOrColonLocOrErr)
7469 return ToEqualOrColonLocOrErr.takeError();
7470
7471 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
7472 // List elements from the second, the first is Init itself
7473 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
7474 if (ExpectedExpr ToArgOrErr = import(From: E->getSubExpr(Idx: I)))
7475 ToIndexExprs[I - 1] = *ToArgOrErr;
7476 else
7477 return ToArgOrErr.takeError();
7478 }
7479
7480 SmallVector<Designator, 4> ToDesignators(E->size());
7481 if (Error Err = ImportContainerChecked(InContainer: E->designators(), OutContainer&: ToDesignators))
7482 return std::move(Err);
7483
7484 return DesignatedInitExpr::Create(
7485 C: Importer.getToContext(), Designators: ToDesignators,
7486 IndexExprs: ToIndexExprs, EqualOrColonLoc: *ToEqualOrColonLocOrErr,
7487 GNUSyntax: E->usesGNUSyntax(), Init: *ToInitOrErr);
7488}
7489
7490ExpectedStmt
7491ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
7492 ExpectedType ToTypeOrErr = import(E->getType());
7493 if (!ToTypeOrErr)
7494 return ToTypeOrErr.takeError();
7495
7496 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7497 if (!ToLocationOrErr)
7498 return ToLocationOrErr.takeError();
7499
7500 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
7501 *ToTypeOrErr, *ToLocationOrErr);
7502}
7503
7504ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
7505 ExpectedType ToTypeOrErr = import(E->getType());
7506 if (!ToTypeOrErr)
7507 return ToTypeOrErr.takeError();
7508
7509 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7510 if (!ToLocationOrErr)
7511 return ToLocationOrErr.takeError();
7512
7513 return IntegerLiteral::Create(
7514 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
7515}
7516
7517
7518ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
7519 ExpectedType ToTypeOrErr = import(E->getType());
7520 if (!ToTypeOrErr)
7521 return ToTypeOrErr.takeError();
7522
7523 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7524 if (!ToLocationOrErr)
7525 return ToLocationOrErr.takeError();
7526
7527 return FloatingLiteral::Create(
7528 C: Importer.getToContext(), V: E->getValue(), isexact: E->isExact(),
7529 Type: *ToTypeOrErr, L: *ToLocationOrErr);
7530}
7531
7532ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
7533 auto ToTypeOrErr = import(E->getType());
7534 if (!ToTypeOrErr)
7535 return ToTypeOrErr.takeError();
7536
7537 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
7538 if (!ToSubExprOrErr)
7539 return ToSubExprOrErr.takeError();
7540
7541 return new (Importer.getToContext()) ImaginaryLiteral(
7542 *ToSubExprOrErr, *ToTypeOrErr);
7543}
7544
7545ExpectedStmt ASTNodeImporter::VisitFixedPointLiteral(FixedPointLiteral *E) {
7546 auto ToTypeOrErr = import(E->getType());
7547 if (!ToTypeOrErr)
7548 return ToTypeOrErr.takeError();
7549
7550 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7551 if (!ToLocationOrErr)
7552 return ToLocationOrErr.takeError();
7553
7554 return new (Importer.getToContext()) FixedPointLiteral(
7555 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
7556 Importer.getToContext().getFixedPointScale(Ty: *ToTypeOrErr));
7557}
7558
7559ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
7560 ExpectedType ToTypeOrErr = import(E->getType());
7561 if (!ToTypeOrErr)
7562 return ToTypeOrErr.takeError();
7563
7564 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
7565 if (!ToLocationOrErr)
7566 return ToLocationOrErr.takeError();
7567
7568 return new (Importer.getToContext()) CharacterLiteral(
7569 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
7570}
7571
7572ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
7573 ExpectedType ToTypeOrErr = import(E->getType());
7574 if (!ToTypeOrErr)
7575 return ToTypeOrErr.takeError();
7576
7577 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
7578 if (Error Err = ImportArrayChecked(
7579 Ibegin: E->tokloc_begin(), Iend: E->tokloc_end(), Obegin: ToLocations.begin()))
7580 return std::move(Err);
7581
7582 return StringLiteral::Create(
7583 Ctx: Importer.getToContext(), Str: E->getBytes(), Kind: E->getKind(), Pascal: E->isPascal(),
7584 Ty: *ToTypeOrErr, Loc: ToLocations.data(), NumConcatenated: ToLocations.size());
7585}
7586
7587ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
7588
7589 Error Err = Error::success();
7590 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
7591 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
7592 auto ToType = importChecked(Err, E->getType());
7593 auto ToInitializer = importChecked(Err, From: E->getInitializer());
7594 if (Err)
7595 return std::move(Err);
7596
7597 return new (Importer.getToContext()) CompoundLiteralExpr(
7598 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
7599 ToInitializer, E->isFileScope());
7600}
7601
7602ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
7603
7604 Error Err = Error::success();
7605 auto ToBuiltinLoc = importChecked(Err, From: E->getBuiltinLoc());
7606 auto ToType = importChecked(Err, E->getType());
7607 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7608 if (Err)
7609 return std::move(Err);
7610
7611 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
7612 if (Error Err = ImportArrayChecked(
7613 Ibegin: E->getSubExprs(), Iend: E->getSubExprs() + E->getNumSubExprs(),
7614 Obegin: ToExprs.begin()))
7615 return std::move(Err);
7616
7617 return new (Importer.getToContext()) AtomicExpr(
7618
7619 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
7620}
7621
7622ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
7623 Error Err = Error::success();
7624 auto ToAmpAmpLoc = importChecked(Err, From: E->getAmpAmpLoc());
7625 auto ToLabelLoc = importChecked(Err, From: E->getLabelLoc());
7626 auto ToLabel = importChecked(Err, From: E->getLabel());
7627 auto ToType = importChecked(Err, E->getType());
7628 if (Err)
7629 return std::move(Err);
7630
7631 return new (Importer.getToContext()) AddrLabelExpr(
7632 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
7633}
7634ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
7635 Error Err = Error::success();
7636 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7637 auto ToResult = importChecked(Err, From: E->getAPValueResult());
7638 if (Err)
7639 return std::move(Err);
7640
7641 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult);
7642}
7643ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
7644 Error Err = Error::success();
7645 auto ToLParen = importChecked(Err, From: E->getLParen());
7646 auto ToRParen = importChecked(Err, From: E->getRParen());
7647 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7648 if (Err)
7649 return std::move(Err);
7650
7651 return new (Importer.getToContext())
7652 ParenExpr(ToLParen, ToRParen, ToSubExpr);
7653}
7654
7655ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
7656 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
7657 if (Error Err = ImportContainerChecked(InContainer: E->exprs(), OutContainer&: ToExprs))
7658 return std::move(Err);
7659
7660 ExpectedSLoc ToLParenLocOrErr = import(From: E->getLParenLoc());
7661 if (!ToLParenLocOrErr)
7662 return ToLParenLocOrErr.takeError();
7663
7664 ExpectedSLoc ToRParenLocOrErr = import(From: E->getRParenLoc());
7665 if (!ToRParenLocOrErr)
7666 return ToRParenLocOrErr.takeError();
7667
7668 return ParenListExpr::Create(Ctx: Importer.getToContext(), LParenLoc: *ToLParenLocOrErr,
7669 Exprs: ToExprs, RParenLoc: *ToRParenLocOrErr);
7670}
7671
7672ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
7673 Error Err = Error::success();
7674 auto ToSubStmt = importChecked(Err, From: E->getSubStmt());
7675 auto ToType = importChecked(Err, E->getType());
7676 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
7677 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7678 if (Err)
7679 return std::move(Err);
7680
7681 return new (Importer.getToContext())
7682 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
7683 E->getTemplateDepth());
7684}
7685
7686ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
7687 Error Err = Error::success();
7688 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
7689 auto ToType = importChecked(Err, E->getType());
7690 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7691 if (Err)
7692 return std::move(Err);
7693
7694 auto *UO = UnaryOperator::CreateEmpty(C: Importer.getToContext(),
7695 hasFPFeatures: E->hasStoredFPFeatures());
7696 UO->setType(ToType);
7697 UO->setSubExpr(ToSubExpr);
7698 UO->setOpcode(E->getOpcode());
7699 UO->setOperatorLoc(ToOperatorLoc);
7700 UO->setCanOverflow(E->canOverflow());
7701 if (E->hasStoredFPFeatures())
7702 UO->setStoredFPFeatures(E->getStoredFPFeatures());
7703
7704 return UO;
7705}
7706
7707ExpectedStmt
7708
7709ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
7710 Error Err = Error::success();
7711 auto ToType = importChecked(Err, E->getType());
7712 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7713 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
7714 if (Err)
7715 return std::move(Err);
7716
7717 if (E->isArgumentType()) {
7718 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
7719 import(From: E->getArgumentTypeInfo());
7720 if (!ToArgumentTypeInfoOrErr)
7721 return ToArgumentTypeInfoOrErr.takeError();
7722
7723 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7724 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
7725 ToRParenLoc);
7726 }
7727
7728 ExpectedExpr ToArgumentExprOrErr = import(From: E->getArgumentExpr());
7729 if (!ToArgumentExprOrErr)
7730 return ToArgumentExprOrErr.takeError();
7731
7732 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7733 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
7734}
7735
7736ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
7737 Error Err = Error::success();
7738 auto ToLHS = importChecked(Err, From: E->getLHS());
7739 auto ToRHS = importChecked(Err, From: E->getRHS());
7740 auto ToType = importChecked(Err, E->getType());
7741 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
7742 if (Err)
7743 return std::move(Err);
7744
7745 return BinaryOperator::Create(
7746 C: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS, opc: E->getOpcode(), ResTy: ToType,
7747 VK: E->getValueKind(), OK: E->getObjectKind(), opLoc: ToOperatorLoc,
7748 FPFeatures: E->getFPFeatures());
7749}
7750
7751ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
7752 Error Err = Error::success();
7753 auto ToCond = importChecked(Err, From: E->getCond());
7754 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7755 auto ToLHS = importChecked(Err, From: E->getLHS());
7756 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7757 auto ToRHS = importChecked(Err, From: E->getRHS());
7758 auto ToType = importChecked(Err, E->getType());
7759 if (Err)
7760 return std::move(Err);
7761
7762 return new (Importer.getToContext()) ConditionalOperator(
7763 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
7764 E->getValueKind(), E->getObjectKind());
7765}
7766
7767ExpectedStmt
7768ASTNodeImporter::VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
7769 Error Err = Error::success();
7770 auto ToCommon = importChecked(Err, From: E->getCommon());
7771 auto ToOpaqueValue = importChecked(Err, From: E->getOpaqueValue());
7772 auto ToCond = importChecked(Err, From: E->getCond());
7773 auto ToTrueExpr = importChecked(Err, From: E->getTrueExpr());
7774 auto ToFalseExpr = importChecked(Err, From: E->getFalseExpr());
7775 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7776 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7777 auto ToType = importChecked(Err, E->getType());
7778 if (Err)
7779 return std::move(Err);
7780
7781 return new (Importer.getToContext()) BinaryConditionalOperator(
7782 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
7783 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
7784 E->getObjectKind());
7785}
7786
7787ExpectedStmt ASTNodeImporter::VisitCXXRewrittenBinaryOperator(
7788 CXXRewrittenBinaryOperator *E) {
7789 Error Err = Error::success();
7790 auto ToSemanticForm = importChecked(Err, From: E->getSemanticForm());
7791 if (Err)
7792 return std::move(Err);
7793
7794 return new (Importer.getToContext())
7795 CXXRewrittenBinaryOperator(ToSemanticForm, E->isReversed());
7796}
7797
7798ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
7799 Error Err = Error::success();
7800 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7801 auto ToQueriedTypeSourceInfo =
7802 importChecked(Err, From: E->getQueriedTypeSourceInfo());
7803 auto ToDimensionExpression = importChecked(Err, From: E->getDimensionExpression());
7804 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
7805 auto ToType = importChecked(Err, E->getType());
7806 if (Err)
7807 return std::move(Err);
7808
7809 return new (Importer.getToContext()) ArrayTypeTraitExpr(
7810 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
7811 ToDimensionExpression, ToEndLoc, ToType);
7812}
7813
7814ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
7815 Error Err = Error::success();
7816 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
7817 auto ToQueriedExpression = importChecked(Err, From: E->getQueriedExpression());
7818 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
7819 auto ToType = importChecked(Err, E->getType());
7820 if (Err)
7821 return std::move(Err);
7822
7823 return new (Importer.getToContext()) ExpressionTraitExpr(
7824 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
7825 ToEndLoc, ToType);
7826}
7827
7828ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
7829 Error Err = Error::success();
7830 auto ToLocation = importChecked(Err, From: E->getLocation());
7831 auto ToType = importChecked(Err, E->getType());
7832 auto ToSourceExpr = importChecked(Err, From: E->getSourceExpr());
7833 if (Err)
7834 return std::move(Err);
7835
7836 return new (Importer.getToContext()) OpaqueValueExpr(
7837 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
7838}
7839
7840ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
7841 Error Err = Error::success();
7842 auto ToLHS = importChecked(Err, From: E->getLHS());
7843 auto ToRHS = importChecked(Err, From: E->getRHS());
7844 auto ToType = importChecked(Err, E->getType());
7845 auto ToRBracketLoc = importChecked(Err, From: E->getRBracketLoc());
7846 if (Err)
7847 return std::move(Err);
7848
7849 return new (Importer.getToContext()) ArraySubscriptExpr(
7850 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
7851 ToRBracketLoc);
7852}
7853
7854ExpectedStmt
7855ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
7856 Error Err = Error::success();
7857 auto ToLHS = importChecked(Err, E->getLHS());
7858 auto ToRHS = importChecked(Err, E->getRHS());
7859 auto ToType = importChecked(Err, E->getType());
7860 auto ToComputationLHSType = importChecked(Err, From: E->getComputationLHSType());
7861 auto ToComputationResultType =
7862 importChecked(Err, From: E->getComputationResultType());
7863 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7864 if (Err)
7865 return std::move(Err);
7866
7867 return CompoundAssignOperator::Create(
7868 C: Importer.getToContext(), lhs: ToLHS, rhs: ToRHS, opc: E->getOpcode(), ResTy: ToType,
7869 VK: E->getValueKind(), OK: E->getObjectKind(), opLoc: ToOperatorLoc,
7870 FPFeatures: E->getFPFeatures(),
7871 CompLHSType: ToComputationLHSType, CompResultType: ToComputationResultType);
7872}
7873
7874Expected<CXXCastPath>
7875ASTNodeImporter::ImportCastPath(CastExpr *CE) {
7876 CXXCastPath Path;
7877 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
7878 if (auto SpecOrErr = import(From: *I))
7879 Path.push_back(Elt: *SpecOrErr);
7880 else
7881 return SpecOrErr.takeError();
7882 }
7883 return Path;
7884}
7885
7886ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
7887 ExpectedType ToTypeOrErr = import(E->getType());
7888 if (!ToTypeOrErr)
7889 return ToTypeOrErr.takeError();
7890
7891 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7892 if (!ToSubExprOrErr)
7893 return ToSubExprOrErr.takeError();
7894
7895 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7896 if (!ToBasePathOrErr)
7897 return ToBasePathOrErr.takeError();
7898
7899 return ImplicitCastExpr::Create(
7900 Context: Importer.getToContext(), T: *ToTypeOrErr, Kind: E->getCastKind(), Operand: *ToSubExprOrErr,
7901 BasePath: &(*ToBasePathOrErr), Cat: E->getValueKind(), FPO: E->getFPFeatures());
7902}
7903
7904ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
7905 Error Err = Error::success();
7906 auto ToType = importChecked(Err, E->getType());
7907 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7908 auto ToTypeInfoAsWritten = importChecked(Err, From: E->getTypeInfoAsWritten());
7909 if (Err)
7910 return std::move(Err);
7911
7912 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7913 if (!ToBasePathOrErr)
7914 return ToBasePathOrErr.takeError();
7915 CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
7916
7917 switch (E->getStmtClass()) {
7918 case Stmt::CStyleCastExprClass: {
7919 auto *CCE = cast<CStyleCastExpr>(Val: E);
7920 ExpectedSLoc ToLParenLocOrErr = import(From: CCE->getLParenLoc());
7921 if (!ToLParenLocOrErr)
7922 return ToLParenLocOrErr.takeError();
7923 ExpectedSLoc ToRParenLocOrErr = import(From: CCE->getRParenLoc());
7924 if (!ToRParenLocOrErr)
7925 return ToRParenLocOrErr.takeError();
7926 return CStyleCastExpr::Create(
7927 Context: Importer.getToContext(), T: ToType, VK: E->getValueKind(), K: E->getCastKind(),
7928 Op: ToSubExpr, BasePath: ToBasePath, FPO: CCE->getFPFeatures(), WrittenTy: ToTypeInfoAsWritten,
7929 L: *ToLParenLocOrErr, R: *ToRParenLocOrErr);
7930 }
7931
7932 case Stmt::CXXFunctionalCastExprClass: {
7933 auto *FCE = cast<CXXFunctionalCastExpr>(Val: E);
7934 ExpectedSLoc ToLParenLocOrErr = import(From: FCE->getLParenLoc());
7935 if (!ToLParenLocOrErr)
7936 return ToLParenLocOrErr.takeError();
7937 ExpectedSLoc ToRParenLocOrErr = import(From: FCE->getRParenLoc());
7938 if (!ToRParenLocOrErr)
7939 return ToRParenLocOrErr.takeError();
7940 return CXXFunctionalCastExpr::Create(
7941 Context: Importer.getToContext(), T: ToType, VK: E->getValueKind(), Written: ToTypeInfoAsWritten,
7942 Kind: E->getCastKind(), Op: ToSubExpr, Path: ToBasePath, FPO: FCE->getFPFeatures(),
7943 LPLoc: *ToLParenLocOrErr, RPLoc: *ToRParenLocOrErr);
7944 }
7945
7946 case Stmt::ObjCBridgedCastExprClass: {
7947 auto *OCE = cast<ObjCBridgedCastExpr>(Val: E);
7948 ExpectedSLoc ToLParenLocOrErr = import(From: OCE->getLParenLoc());
7949 if (!ToLParenLocOrErr)
7950 return ToLParenLocOrErr.takeError();
7951 ExpectedSLoc ToBridgeKeywordLocOrErr = import(From: OCE->getBridgeKeywordLoc());
7952 if (!ToBridgeKeywordLocOrErr)
7953 return ToBridgeKeywordLocOrErr.takeError();
7954 return new (Importer.getToContext()) ObjCBridgedCastExpr(
7955 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
7956 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
7957 }
7958 case Stmt::BuiltinBitCastExprClass: {
7959 auto *BBC = cast<BuiltinBitCastExpr>(Val: E);
7960 ExpectedSLoc ToKWLocOrErr = import(From: BBC->getBeginLoc());
7961 if (!ToKWLocOrErr)
7962 return ToKWLocOrErr.takeError();
7963 ExpectedSLoc ToRParenLocOrErr = import(From: BBC->getEndLoc());
7964 if (!ToRParenLocOrErr)
7965 return ToRParenLocOrErr.takeError();
7966 return new (Importer.getToContext()) BuiltinBitCastExpr(
7967 ToType, E->getValueKind(), E->getCastKind(), ToSubExpr,
7968 ToTypeInfoAsWritten, *ToKWLocOrErr, *ToRParenLocOrErr);
7969 }
7970 default:
7971 llvm_unreachable("Cast expression of unsupported type!");
7972 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
7973 }
7974}
7975
7976ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) {
7977 SmallVector<OffsetOfNode, 4> ToNodes;
7978 for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
7979 const OffsetOfNode &FromNode = E->getComponent(Idx: I);
7980
7981 SourceLocation ToBeginLoc, ToEndLoc;
7982
7983 if (FromNode.getKind() != OffsetOfNode::Base) {
7984 Error Err = Error::success();
7985 ToBeginLoc = importChecked(Err, From: FromNode.getBeginLoc());
7986 ToEndLoc = importChecked(Err, From: FromNode.getEndLoc());
7987 if (Err)
7988 return std::move(Err);
7989 }
7990
7991 switch (FromNode.getKind()) {
7992 case OffsetOfNode::Array:
7993 ToNodes.push_back(
7994 Elt: OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
7995 break;
7996 case OffsetOfNode::Base: {
7997 auto ToBSOrErr = import(From: FromNode.getBase());
7998 if (!ToBSOrErr)
7999 return ToBSOrErr.takeError();
8000 ToNodes.push_back(Elt: OffsetOfNode(*ToBSOrErr));
8001 break;
8002 }
8003 case OffsetOfNode::Field: {
8004 auto ToFieldOrErr = import(From: FromNode.getField());
8005 if (!ToFieldOrErr)
8006 return ToFieldOrErr.takeError();
8007 ToNodes.push_back(Elt: OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
8008 break;
8009 }
8010 case OffsetOfNode::Identifier: {
8011 IdentifierInfo *ToII = Importer.Import(FromId: FromNode.getFieldName());
8012 ToNodes.push_back(Elt: OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
8013 break;
8014 }
8015 }
8016 }
8017
8018 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
8019 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
8020 ExpectedExpr ToIndexExprOrErr = import(From: E->getIndexExpr(Idx: I));
8021 if (!ToIndexExprOrErr)
8022 return ToIndexExprOrErr.takeError();
8023 ToExprs[I] = *ToIndexExprOrErr;
8024 }
8025
8026 Error Err = Error::success();
8027 auto ToType = importChecked(Err, E->getType());
8028 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8029 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8030 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8031 if (Err)
8032 return std::move(Err);
8033
8034 return OffsetOfExpr::Create(
8035 C: Importer.getToContext(), type: ToType, OperatorLoc: ToOperatorLoc, tsi: ToTypeSourceInfo, comps: ToNodes,
8036 exprs: ToExprs, RParenLoc: ToRParenLoc);
8037}
8038
8039ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
8040 Error Err = Error::success();
8041 auto ToType = importChecked(Err, E->getType());
8042 auto ToOperand = importChecked(Err, From: E->getOperand());
8043 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8044 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8045 if (Err)
8046 return std::move(Err);
8047
8048 CanThrowResult ToCanThrow;
8049 if (E->isValueDependent())
8050 ToCanThrow = CT_Dependent;
8051 else
8052 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
8053
8054 return new (Importer.getToContext()) CXXNoexceptExpr(
8055 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
8056}
8057
8058ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
8059 Error Err = Error::success();
8060 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
8061 auto ToType = importChecked(Err, E->getType());
8062 auto ToThrowLoc = importChecked(Err, From: E->getThrowLoc());
8063 if (Err)
8064 return std::move(Err);
8065
8066 return new (Importer.getToContext()) CXXThrowExpr(
8067 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
8068}
8069
8070ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
8071 ExpectedSLoc ToUsedLocOrErr = import(From: E->getUsedLocation());
8072 if (!ToUsedLocOrErr)
8073 return ToUsedLocOrErr.takeError();
8074
8075 auto ToParamOrErr = import(From: E->getParam());
8076 if (!ToParamOrErr)
8077 return ToParamOrErr.takeError();
8078
8079 auto UsedContextOrErr = Importer.ImportContext(FromDC: E->getUsedContext());
8080 if (!UsedContextOrErr)
8081 return UsedContextOrErr.takeError();
8082
8083 // Import the default arg if it was not imported yet.
8084 // This is needed because it can happen that during the import of the
8085 // default expression (from VisitParmVarDecl) the same ParmVarDecl is
8086 // encountered here. The default argument for a ParmVarDecl is set in the
8087 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
8088 // see VisitParmVarDecl).
8089 ParmVarDecl *ToParam = *ToParamOrErr;
8090 if (!ToParam->getDefaultArg()) {
8091 std::optional<ParmVarDecl *> FromParam =
8092 Importer.getImportedFromDecl(ToD: ToParam);
8093 assert(FromParam && "ParmVarDecl was not imported?");
8094
8095 if (Error Err = ImportDefaultArgOfParmVarDecl(FromParam: *FromParam, ToParam))
8096 return std::move(Err);
8097 }
8098 Expr *RewrittenInit = nullptr;
8099 if (E->hasRewrittenInit()) {
8100 ExpectedExpr ExprOrErr = import(From: E->getRewrittenExpr());
8101 if (!ExprOrErr)
8102 return ExprOrErr.takeError();
8103 RewrittenInit = ExprOrErr.get();
8104 }
8105 return CXXDefaultArgExpr::Create(C: Importer.getToContext(), Loc: *ToUsedLocOrErr,
8106 Param: *ToParamOrErr, RewrittenExpr: RewrittenInit,
8107 UsedContext: *UsedContextOrErr);
8108}
8109
8110ExpectedStmt
8111ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
8112 Error Err = Error::success();
8113 auto ToType = importChecked(Err, E->getType());
8114 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8115 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8116 if (Err)
8117 return std::move(Err);
8118
8119 return new (Importer.getToContext()) CXXScalarValueInitExpr(
8120 ToType, ToTypeSourceInfo, ToRParenLoc);
8121}
8122
8123ExpectedStmt
8124ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
8125 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
8126 if (!ToSubExprOrErr)
8127 return ToSubExprOrErr.takeError();
8128
8129 auto ToDtorOrErr = import(From: E->getTemporary()->getDestructor());
8130 if (!ToDtorOrErr)
8131 return ToDtorOrErr.takeError();
8132
8133 ASTContext &ToCtx = Importer.getToContext();
8134 CXXTemporary *Temp = CXXTemporary::Create(C: ToCtx, Destructor: *ToDtorOrErr);
8135 return CXXBindTemporaryExpr::Create(C: ToCtx, Temp, SubExpr: *ToSubExprOrErr);
8136}
8137
8138ExpectedStmt
8139
8140ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) {
8141 Error Err = Error::success();
8142 auto ToConstructor = importChecked(Err, E->getConstructor());
8143 auto ToType = importChecked(Err, E->getType());
8144 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8145 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
8146 if (Err)
8147 return std::move(Err);
8148
8149 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8150 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8151 return std::move(Err);
8152
8153 return CXXTemporaryObjectExpr::Create(
8154 Ctx: Importer.getToContext(), Cons: ToConstructor, Ty: ToType, TSI: ToTypeSourceInfo, Args: ToArgs,
8155 ParenOrBraceRange: ToParenOrBraceRange, HadMultipleCandidates: E->hadMultipleCandidates(),
8156 ListInitialization: E->isListInitialization(), StdInitListInitialization: E->isStdInitListInitialization(),
8157 ZeroInitialization: E->requiresZeroInitialization());
8158}
8159
8160ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl(
8161 LifetimeExtendedTemporaryDecl *D) {
8162 DeclContext *DC, *LexicalDC;
8163 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
8164 return std::move(Err);
8165
8166 Error Err = Error::success();
8167 auto Temporary = importChecked(Err, From: D->getTemporaryExpr());
8168 auto ExtendingDecl = importChecked(Err, From: D->getExtendingDecl());
8169 if (Err)
8170 return std::move(Err);
8171 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
8172
8173 LifetimeExtendedTemporaryDecl *To;
8174 if (GetImportedOrCreateDecl(ToD&: To, FromD: D, args&: Temporary, args&: ExtendingDecl,
8175 args: D->getManglingNumber()))
8176 return To;
8177
8178 To->setLexicalDeclContext(LexicalDC);
8179 LexicalDC->addDeclInternal(To);
8180 return To;
8181}
8182
8183ExpectedStmt
8184ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
8185 Error Err = Error::success();
8186 auto ToType = importChecked(Err, E->getType());
8187 Expr *ToTemporaryExpr = importChecked(
8188 Err, From: E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
8189 auto ToMaterializedDecl =
8190 importChecked(Err, From: E->getLifetimeExtendedTemporaryDecl());
8191 if (Err)
8192 return std::move(Err);
8193
8194 if (!ToTemporaryExpr)
8195 ToTemporaryExpr = cast<Expr>(Val: ToMaterializedDecl->getTemporaryExpr());
8196
8197 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
8198 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
8199 ToMaterializedDecl);
8200
8201 return ToMTE;
8202}
8203
8204ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
8205 Error Err = Error::success();
8206 auto ToType = importChecked(Err, E->getType());
8207 auto ToPattern = importChecked(Err, From: E->getPattern());
8208 auto ToEllipsisLoc = importChecked(Err, From: E->getEllipsisLoc());
8209 if (Err)
8210 return std::move(Err);
8211
8212 return new (Importer.getToContext()) PackExpansionExpr(
8213 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
8214}
8215
8216ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
8217 Error Err = Error::success();
8218 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8219 auto ToPack = importChecked(Err, From: E->getPack());
8220 auto ToPackLoc = importChecked(Err, From: E->getPackLoc());
8221 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8222 if (Err)
8223 return std::move(Err);
8224
8225 std::optional<unsigned> Length;
8226 if (!E->isValueDependent())
8227 Length = E->getPackLength();
8228
8229 SmallVector<TemplateArgument, 8> ToPartialArguments;
8230 if (E->isPartiallySubstituted()) {
8231 if (Error Err = ImportTemplateArguments(FromArgs: E->getPartialArguments(),
8232 ToArgs&: ToPartialArguments))
8233 return std::move(Err);
8234 }
8235
8236 return SizeOfPackExpr::Create(
8237 Context&: Importer.getToContext(), OperatorLoc: ToOperatorLoc, Pack: ToPack, PackLoc: ToPackLoc, RParenLoc: ToRParenLoc,
8238 Length, PartialArgs: ToPartialArguments);
8239}
8240
8241
8242ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) {
8243 Error Err = Error::success();
8244 auto ToOperatorNew = importChecked(Err, From: E->getOperatorNew());
8245 auto ToOperatorDelete = importChecked(Err, From: E->getOperatorDelete());
8246 auto ToTypeIdParens = importChecked(Err, From: E->getTypeIdParens());
8247 auto ToArraySize = importChecked(Err, From: E->getArraySize());
8248 auto ToInitializer = importChecked(Err, From: E->getInitializer());
8249 auto ToType = importChecked(Err, E->getType());
8250 auto ToAllocatedTypeSourceInfo =
8251 importChecked(Err, From: E->getAllocatedTypeSourceInfo());
8252 auto ToSourceRange = importChecked(Err, From: E->getSourceRange());
8253 auto ToDirectInitRange = importChecked(Err, From: E->getDirectInitRange());
8254 if (Err)
8255 return std::move(Err);
8256
8257 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
8258 if (Error Err =
8259 ImportContainerChecked(InContainer: E->placement_arguments(), OutContainer&: ToPlacementArgs))
8260 return std::move(Err);
8261
8262 return CXXNewExpr::Create(
8263 Ctx: Importer.getToContext(), IsGlobalNew: E->isGlobalNew(), OperatorNew: ToOperatorNew,
8264 OperatorDelete: ToOperatorDelete, ShouldPassAlignment: E->passAlignment(), UsualArrayDeleteWantsSize: E->doesUsualArrayDeleteWantSize(),
8265 PlacementArgs: ToPlacementArgs, TypeIdParens: ToTypeIdParens, ArraySize: ToArraySize, InitializationStyle: E->getInitializationStyle(),
8266 Initializer: ToInitializer, Ty: ToType, AllocatedTypeInfo: ToAllocatedTypeSourceInfo, Range: ToSourceRange,
8267 DirectInitRange: ToDirectInitRange);
8268}
8269
8270ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
8271 Error Err = Error::success();
8272 auto ToType = importChecked(Err, E->getType());
8273 auto ToOperatorDelete = importChecked(Err, From: E->getOperatorDelete());
8274 auto ToArgument = importChecked(Err, From: E->getArgument());
8275 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8276 if (Err)
8277 return std::move(Err);
8278
8279 return new (Importer.getToContext()) CXXDeleteExpr(
8280 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
8281 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
8282 ToBeginLoc);
8283}
8284
8285ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
8286 Error Err = Error::success();
8287 auto ToType = importChecked(Err, E->getType());
8288 auto ToLocation = importChecked(Err, From: E->getLocation());
8289 auto ToConstructor = importChecked(Err, From: E->getConstructor());
8290 auto ToParenOrBraceRange = importChecked(Err, From: E->getParenOrBraceRange());
8291 if (Err)
8292 return std::move(Err);
8293
8294 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
8295 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8296 return std::move(Err);
8297
8298 CXXConstructExpr *ToE = CXXConstructExpr::Create(
8299 Ctx: Importer.getToContext(), Ty: ToType, Loc: ToLocation, Ctor: ToConstructor,
8300 Elidable: E->isElidable(), Args: ToArgs, HadMultipleCandidates: E->hadMultipleCandidates(),
8301 ListInitialization: E->isListInitialization(), StdInitListInitialization: E->isStdInitListInitialization(),
8302 ZeroInitialization: E->requiresZeroInitialization(), ConstructKind: E->getConstructionKind(),
8303 ParenOrBraceRange: ToParenOrBraceRange);
8304 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
8305 return ToE;
8306}
8307
8308ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) {
8309 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8310 if (!ToSubExprOrErr)
8311 return ToSubExprOrErr.takeError();
8312
8313 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
8314 if (Error Err = ImportContainerChecked(InContainer: E->getObjects(), OutContainer&: ToObjects))
8315 return std::move(Err);
8316
8317 return ExprWithCleanups::Create(
8318 C: Importer.getToContext(), subexpr: *ToSubExprOrErr, CleanupsHaveSideEffects: E->cleanupsHaveSideEffects(),
8319 objects: ToObjects);
8320}
8321
8322ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
8323 Error Err = Error::success();
8324 auto ToCallee = importChecked(Err, E->getCallee());
8325 auto ToType = importChecked(Err, E->getType());
8326 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8327 if (Err)
8328 return std::move(Err);
8329
8330 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
8331 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8332 return std::move(Err);
8333
8334 return CXXMemberCallExpr::Create(Ctx: Importer.getToContext(), Fn: ToCallee, Args: ToArgs,
8335 Ty: ToType, VK: E->getValueKind(), RP: ToRParenLoc,
8336 FPFeatures: E->getFPFeatures());
8337}
8338
8339ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
8340 ExpectedType ToTypeOrErr = import(E->getType());
8341 if (!ToTypeOrErr)
8342 return ToTypeOrErr.takeError();
8343
8344 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
8345 if (!ToLocationOrErr)
8346 return ToLocationOrErr.takeError();
8347
8348 return CXXThisExpr::Create(Ctx: Importer.getToContext(), L: *ToLocationOrErr,
8349 Ty: *ToTypeOrErr, IsImplicit: E->isImplicit());
8350}
8351
8352ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
8353 ExpectedType ToTypeOrErr = import(E->getType());
8354 if (!ToTypeOrErr)
8355 return ToTypeOrErr.takeError();
8356
8357 ExpectedSLoc ToLocationOrErr = import(From: E->getLocation());
8358 if (!ToLocationOrErr)
8359 return ToLocationOrErr.takeError();
8360
8361 return CXXBoolLiteralExpr::Create(C: Importer.getToContext(), Val: E->getValue(),
8362 Ty: *ToTypeOrErr, Loc: *ToLocationOrErr);
8363}
8364
8365ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
8366 Error Err = Error::success();
8367 auto ToBase = importChecked(Err, From: E->getBase());
8368 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8369 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8370 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8371 auto ToMemberDecl = importChecked(Err, From: E->getMemberDecl());
8372 auto ToType = importChecked(Err, E->getType());
8373 auto ToDecl = importChecked(Err, From: E->getFoundDecl().getDecl());
8374 auto ToName = importChecked(Err, From: E->getMemberNameInfo().getName());
8375 auto ToLoc = importChecked(Err, From: E->getMemberNameInfo().getLoc());
8376 if (Err)
8377 return std::move(Err);
8378
8379 DeclAccessPair ToFoundDecl =
8380 DeclAccessPair::make(D: ToDecl, AS: E->getFoundDecl().getAccess());
8381
8382 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
8383
8384 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8385 if (E->hasExplicitTemplateArgs()) {
8386 if (Error Err =
8387 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
8388 Container: E->template_arguments(), Result&: ToTAInfo))
8389 return std::move(Err);
8390 ResInfo = &ToTAInfo;
8391 }
8392
8393 return MemberExpr::Create(C: Importer.getToContext(), Base: ToBase, IsArrow: E->isArrow(),
8394 OperatorLoc: ToOperatorLoc, QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8395 MemberDecl: ToMemberDecl, FoundDecl: ToFoundDecl, MemberNameInfo: ToMemberNameInfo,
8396 TemplateArgs: ResInfo, T: ToType, VK: E->getValueKind(),
8397 OK: E->getObjectKind(), NOUR: E->isNonOdrUse());
8398}
8399
8400ExpectedStmt
8401ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) {
8402 Error Err = Error::success();
8403 auto ToBase = importChecked(Err, From: E->getBase());
8404 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8405 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8406 auto ToScopeTypeInfo = importChecked(Err, From: E->getScopeTypeInfo());
8407 auto ToColonColonLoc = importChecked(Err, From: E->getColonColonLoc());
8408 auto ToTildeLoc = importChecked(Err, From: E->getTildeLoc());
8409 if (Err)
8410 return std::move(Err);
8411
8412 PseudoDestructorTypeStorage Storage;
8413 if (const IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
8414 const IdentifierInfo *ToII = Importer.Import(FromId: FromII);
8415 ExpectedSLoc ToDestroyedTypeLocOrErr = import(From: E->getDestroyedTypeLoc());
8416 if (!ToDestroyedTypeLocOrErr)
8417 return ToDestroyedTypeLocOrErr.takeError();
8418 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
8419 } else {
8420 if (auto ToTIOrErr = import(From: E->getDestroyedTypeInfo()))
8421 Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
8422 else
8423 return ToTIOrErr.takeError();
8424 }
8425
8426 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
8427 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
8428 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
8429}
8430
8431ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
8432 CXXDependentScopeMemberExpr *E) {
8433 Error Err = Error::success();
8434 auto ToType = importChecked(Err, E->getType());
8435 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8436 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8437 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8438 auto ToFirstQualifierFoundInScope =
8439 importChecked(Err, From: E->getFirstQualifierFoundInScope());
8440 if (Err)
8441 return std::move(Err);
8442
8443 Expr *ToBase = nullptr;
8444 if (!E->isImplicitAccess()) {
8445 if (ExpectedExpr ToBaseOrErr = import(From: E->getBase()))
8446 ToBase = *ToBaseOrErr;
8447 else
8448 return ToBaseOrErr.takeError();
8449 }
8450
8451 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8452
8453 if (E->hasExplicitTemplateArgs()) {
8454 if (Error Err =
8455 ImportTemplateArgumentListInfo(FromLAngleLoc: E->getLAngleLoc(), FromRAngleLoc: E->getRAngleLoc(),
8456 Container: E->template_arguments(), Result&: ToTAInfo))
8457 return std::move(Err);
8458 ResInfo = &ToTAInfo;
8459 }
8460 auto ToMember = importChecked(Err, From: E->getMember());
8461 auto ToMemberLoc = importChecked(Err, From: E->getMemberLoc());
8462 if (Err)
8463 return std::move(Err);
8464 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
8465
8466 // Import additional name location/type info.
8467 if (Error Err =
8468 ImportDeclarationNameLoc(From: E->getMemberNameInfo(), To&: ToMemberNameInfo))
8469 return std::move(Err);
8470
8471 return CXXDependentScopeMemberExpr::Create(
8472 Ctx: Importer.getToContext(), Base: ToBase, BaseType: ToType, IsArrow: E->isArrow(), OperatorLoc: ToOperatorLoc,
8473 QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc, FirstQualifierFoundInScope: ToFirstQualifierFoundInScope,
8474 MemberNameInfo: ToMemberNameInfo, TemplateArgs: ResInfo);
8475}
8476
8477ExpectedStmt
8478ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) {
8479 Error Err = Error::success();
8480 auto ToQualifierLoc = importChecked(Err, From: E->getQualifierLoc());
8481 auto ToTemplateKeywordLoc = importChecked(Err, From: E->getTemplateKeywordLoc());
8482 auto ToDeclName = importChecked(Err, From: E->getDeclName());
8483 auto ToNameLoc = importChecked(Err, From: E->getNameInfo().getLoc());
8484 auto ToLAngleLoc = importChecked(Err, From: E->getLAngleLoc());
8485 auto ToRAngleLoc = importChecked(Err, From: E->getRAngleLoc());
8486 if (Err)
8487 return std::move(Err);
8488
8489 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
8490 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8491 return std::move(Err);
8492
8493 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
8494 TemplateArgumentListInfo *ResInfo = nullptr;
8495 if (E->hasExplicitTemplateArgs()) {
8496 if (Error Err =
8497 ImportTemplateArgumentListInfo(Container: E->template_arguments(), ToTAInfo))
8498 return std::move(Err);
8499 ResInfo = &ToTAInfo;
8500 }
8501
8502 return DependentScopeDeclRefExpr::Create(
8503 Context: Importer.getToContext(), QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8504 NameInfo: ToNameInfo, TemplateArgs: ResInfo);
8505}
8506
8507ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
8508 CXXUnresolvedConstructExpr *E) {
8509 Error Err = Error::success();
8510 auto ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
8511 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8512 auto ToType = importChecked(Err, E->getType());
8513 auto ToTypeSourceInfo = importChecked(Err, From: E->getTypeSourceInfo());
8514 if (Err)
8515 return std::move(Err);
8516
8517 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8518 if (Error Err =
8519 ImportArrayChecked(Ibegin: E->arg_begin(), Iend: E->arg_end(), Obegin: ToArgs.begin()))
8520 return std::move(Err);
8521
8522 return CXXUnresolvedConstructExpr::Create(
8523 Context: Importer.getToContext(), T: ToType, TSI: ToTypeSourceInfo, LParenLoc: ToLParenLoc,
8524 Args: llvm::ArrayRef(ToArgs), RParenLoc: ToRParenLoc, IsListInit: E->isListInitialization());
8525}
8526
8527ExpectedStmt
8528ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
8529 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(From: E->getNamingClass());
8530 if (!ToNamingClassOrErr)
8531 return ToNamingClassOrErr.takeError();
8532
8533 auto ToQualifierLocOrErr = import(E->getQualifierLoc());
8534 if (!ToQualifierLocOrErr)
8535 return ToQualifierLocOrErr.takeError();
8536
8537 Error Err = Error::success();
8538 auto ToName = importChecked(Err, E->getName());
8539 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8540 if (Err)
8541 return std::move(Err);
8542 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8543
8544 // Import additional name location/type info.
8545 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8546 return std::move(Err);
8547
8548 UnresolvedSet<8> ToDecls;
8549 for (auto *D : E->decls())
8550 if (auto ToDOrErr = import(D))
8551 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8552 else
8553 return ToDOrErr.takeError();
8554
8555 if (E->hasExplicitTemplateArgs()) {
8556 TemplateArgumentListInfo ToTAInfo;
8557 if (Error Err = ImportTemplateArgumentListInfo(
8558 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
8559 ToTAInfo))
8560 return std::move(Err);
8561
8562 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
8563 if (!ToTemplateKeywordLocOrErr)
8564 return ToTemplateKeywordLocOrErr.takeError();
8565
8566 const bool KnownDependent =
8567 (E->getDependence() & ExprDependence::TypeValue) ==
8568 ExprDependence::TypeValue;
8569 return UnresolvedLookupExpr::Create(
8570 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8571 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
8572 ToDecls.begin(), ToDecls.end(), KnownDependent);
8573 }
8574
8575 return UnresolvedLookupExpr::Create(
8576 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8577 ToNameInfo, E->requiresADL(), ToDecls.begin(), ToDecls.end(),
8578 /*KnownDependent=*/E->isTypeDependent());
8579}
8580
8581ExpectedStmt
8582ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) {
8583 Error Err = Error::success();
8584 auto ToType = importChecked(Err, E->getType());
8585 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8586 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8587 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8588 auto ToName = importChecked(Err, E->getName());
8589 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8590 if (Err)
8591 return std::move(Err);
8592
8593 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8594 // Import additional name location/type info.
8595 if (Error Err = ImportDeclarationNameLoc(From: E->getNameInfo(), To&: ToNameInfo))
8596 return std::move(Err);
8597
8598 UnresolvedSet<8> ToDecls;
8599 for (Decl *D : E->decls())
8600 if (auto ToDOrErr = import(D))
8601 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8602 else
8603 return ToDOrErr.takeError();
8604
8605 TemplateArgumentListInfo ToTAInfo;
8606 TemplateArgumentListInfo *ResInfo = nullptr;
8607 if (E->hasExplicitTemplateArgs()) {
8608 TemplateArgumentListInfo FromTAInfo;
8609 E->copyTemplateArgumentsInto(FromTAInfo);
8610 if (Error Err = ImportTemplateArgumentListInfo(Container: FromTAInfo, ToTAInfo))
8611 return std::move(Err);
8612 ResInfo = &ToTAInfo;
8613 }
8614
8615 Expr *ToBase = nullptr;
8616 if (!E->isImplicitAccess()) {
8617 if (ExpectedExpr ToBaseOrErr = import(From: E->getBase()))
8618 ToBase = *ToBaseOrErr;
8619 else
8620 return ToBaseOrErr.takeError();
8621 }
8622
8623 return UnresolvedMemberExpr::Create(
8624 Context: Importer.getToContext(), HasUnresolvedUsing: E->hasUnresolvedUsing(), Base: ToBase, BaseType: ToType,
8625 IsArrow: E->isArrow(), OperatorLoc: ToOperatorLoc, QualifierLoc: ToQualifierLoc, TemplateKWLoc: ToTemplateKeywordLoc,
8626 MemberNameInfo: ToNameInfo, TemplateArgs: ResInfo, Begin: ToDecls.begin(), End: ToDecls.end());
8627}
8628
8629ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) {
8630 Error Err = Error::success();
8631 auto ToCallee = importChecked(Err, From: E->getCallee());
8632 auto ToType = importChecked(Err, E->getType());
8633 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8634 if (Err)
8635 return std::move(Err);
8636
8637 unsigned NumArgs = E->getNumArgs();
8638 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
8639 if (Error Err = ImportContainerChecked(InContainer: E->arguments(), OutContainer&: ToArgs))
8640 return std::move(Err);
8641
8642 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(Val: E)) {
8643 return CXXOperatorCallExpr::Create(
8644 Ctx: Importer.getToContext(), OpKind: OCE->getOperator(), Fn: ToCallee, Args: ToArgs, Ty: ToType,
8645 VK: OCE->getValueKind(), OperatorLoc: ToRParenLoc, FPFeatures: OCE->getFPFeatures(),
8646 UsesADL: OCE->getADLCallKind());
8647 }
8648
8649 return CallExpr::Create(Ctx: Importer.getToContext(), Fn: ToCallee, Args: ToArgs, Ty: ToType,
8650 VK: E->getValueKind(), RParenLoc: ToRParenLoc, FPFeatures: E->getFPFeatures(),
8651 /*MinNumArgs=*/0, UsesADL: E->getADLCallKind());
8652}
8653
8654ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) {
8655 CXXRecordDecl *FromClass = E->getLambdaClass();
8656 auto ToClassOrErr = import(From: FromClass);
8657 if (!ToClassOrErr)
8658 return ToClassOrErr.takeError();
8659 CXXRecordDecl *ToClass = *ToClassOrErr;
8660
8661 auto ToCallOpOrErr = import(From: E->getCallOperator());
8662 if (!ToCallOpOrErr)
8663 return ToCallOpOrErr.takeError();
8664
8665 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
8666 if (Error Err = ImportContainerChecked(InContainer: E->capture_inits(), OutContainer&: ToCaptureInits))
8667 return std::move(Err);
8668
8669 Error Err = Error::success();
8670 auto ToIntroducerRange = importChecked(Err, From: E->getIntroducerRange());
8671 auto ToCaptureDefaultLoc = importChecked(Err, From: E->getCaptureDefaultLoc());
8672 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8673 if (Err)
8674 return std::move(Err);
8675
8676 return LambdaExpr::Create(C: Importer.getToContext(), Class: ToClass, IntroducerRange: ToIntroducerRange,
8677 CaptureDefault: E->getCaptureDefault(), CaptureDefaultLoc: ToCaptureDefaultLoc,
8678 ExplicitParams: E->hasExplicitParameters(),
8679 ExplicitResultType: E->hasExplicitResultType(), CaptureInits: ToCaptureInits,
8680 ClosingBrace: ToEndLoc, ContainsUnexpandedParameterPack: E->containsUnexpandedParameterPack());
8681}
8682
8683
8684ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) {
8685 Error Err = Error::success();
8686 auto ToLBraceLoc = importChecked(Err, From: E->getLBraceLoc());
8687 auto ToRBraceLoc = importChecked(Err, From: E->getRBraceLoc());
8688 auto ToType = importChecked(Err, E->getType());
8689 if (Err)
8690 return std::move(Err);
8691
8692 SmallVector<Expr *, 4> ToExprs(E->getNumInits());
8693 if (Error Err = ImportContainerChecked(InContainer: E->inits(), OutContainer&: ToExprs))
8694 return std::move(Err);
8695
8696 ASTContext &ToCtx = Importer.getToContext();
8697 InitListExpr *To = new (ToCtx) InitListExpr(
8698 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
8699 To->setType(ToType);
8700
8701 if (E->hasArrayFiller()) {
8702 if (ExpectedExpr ToFillerOrErr = import(From: E->getArrayFiller()))
8703 To->setArrayFiller(*ToFillerOrErr);
8704 else
8705 return ToFillerOrErr.takeError();
8706 }
8707
8708 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
8709 if (auto ToFDOrErr = import(From: FromFD))
8710 To->setInitializedFieldInUnion(*ToFDOrErr);
8711 else
8712 return ToFDOrErr.takeError();
8713 }
8714
8715 if (InitListExpr *SyntForm = E->getSyntacticForm()) {
8716 if (auto ToSyntFormOrErr = import(From: SyntForm))
8717 To->setSyntacticForm(*ToSyntFormOrErr);
8718 else
8719 return ToSyntFormOrErr.takeError();
8720 }
8721
8722 // Copy InitListExprBitfields, which are not handled in the ctor of
8723 // InitListExpr.
8724 To->sawArrayRangeDesignator(ARD: E->hadArrayRangeDesignator());
8725
8726 return To;
8727}
8728
8729ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr(
8730 CXXStdInitializerListExpr *E) {
8731 ExpectedType ToTypeOrErr = import(E->getType());
8732 if (!ToTypeOrErr)
8733 return ToTypeOrErr.takeError();
8734
8735 ExpectedExpr ToSubExprOrErr = import(From: E->getSubExpr());
8736 if (!ToSubExprOrErr)
8737 return ToSubExprOrErr.takeError();
8738
8739 return new (Importer.getToContext()) CXXStdInitializerListExpr(
8740 *ToTypeOrErr, *ToSubExprOrErr);
8741}
8742
8743ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr(
8744 CXXInheritedCtorInitExpr *E) {
8745 Error Err = Error::success();
8746 auto ToLocation = importChecked(Err, From: E->getLocation());
8747 auto ToType = importChecked(Err, E->getType());
8748 auto ToConstructor = importChecked(Err, From: E->getConstructor());
8749 if (Err)
8750 return std::move(Err);
8751
8752 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
8753 ToLocation, ToType, ToConstructor, E->constructsVBase(),
8754 E->inheritedFromVBase());
8755}
8756
8757ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
8758 Error Err = Error::success();
8759 auto ToType = importChecked(Err, E->getType());
8760 auto ToCommonExpr = importChecked(Err, From: E->getCommonExpr());
8761 auto ToSubExpr = importChecked(Err, From: E->getSubExpr());
8762 if (Err)
8763 return std::move(Err);
8764
8765 return new (Importer.getToContext()) ArrayInitLoopExpr(
8766 ToType, ToCommonExpr, ToSubExpr);
8767}
8768
8769ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
8770 ExpectedType ToTypeOrErr = import(E->getType());
8771 if (!ToTypeOrErr)
8772 return ToTypeOrErr.takeError();
8773 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
8774}
8775
8776ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
8777 ExpectedSLoc ToBeginLocOrErr = import(From: E->getBeginLoc());
8778 if (!ToBeginLocOrErr)
8779 return ToBeginLocOrErr.takeError();
8780
8781 auto ToFieldOrErr = import(From: E->getField());
8782 if (!ToFieldOrErr)
8783 return ToFieldOrErr.takeError();
8784
8785 auto UsedContextOrErr = Importer.ImportContext(FromDC: E->getUsedContext());
8786 if (!UsedContextOrErr)
8787 return UsedContextOrErr.takeError();
8788
8789 FieldDecl *ToField = *ToFieldOrErr;
8790 assert(ToField->hasInClassInitializer() &&
8791 "Field should have in-class initializer if there is a default init "
8792 "expression that uses it.");
8793 if (!ToField->getInClassInitializer()) {
8794 // The in-class initializer may be not yet set in "To" AST even if the
8795 // field is already there. This must be set here to make construction of
8796 // CXXDefaultInitExpr work.
8797 auto ToInClassInitializerOrErr =
8798 import(From: E->getField()->getInClassInitializer());
8799 if (!ToInClassInitializerOrErr)
8800 return ToInClassInitializerOrErr.takeError();
8801 ToField->setInClassInitializer(*ToInClassInitializerOrErr);
8802 }
8803
8804 Expr *RewrittenInit = nullptr;
8805 if (E->hasRewrittenInit()) {
8806 ExpectedExpr ExprOrErr = import(From: E->getRewrittenExpr());
8807 if (!ExprOrErr)
8808 return ExprOrErr.takeError();
8809 RewrittenInit = ExprOrErr.get();
8810 }
8811
8812 return CXXDefaultInitExpr::Create(Ctx: Importer.getToContext(), Loc: *ToBeginLocOrErr,
8813 Field: ToField, UsedContext: *UsedContextOrErr, RewrittenInitExpr: RewrittenInit);
8814}
8815
8816ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
8817 Error Err = Error::success();
8818 auto ToType = importChecked(Err, E->getType());
8819 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8820 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
8821 auto ToOperatorLoc = importChecked(Err, From: E->getOperatorLoc());
8822 auto ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8823 auto ToAngleBrackets = importChecked(Err, From: E->getAngleBrackets());
8824 if (Err)
8825 return std::move(Err);
8826
8827 ExprValueKind VK = E->getValueKind();
8828 CastKind CK = E->getCastKind();
8829 auto ToBasePathOrErr = ImportCastPath(E);
8830 if (!ToBasePathOrErr)
8831 return ToBasePathOrErr.takeError();
8832
8833 if (auto CCE = dyn_cast<CXXStaticCastExpr>(Val: E)) {
8834 return CXXStaticCastExpr::Create(
8835 Context: Importer.getToContext(), T: ToType, VK, K: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8836 Written: ToTypeInfoAsWritten, FPO: CCE->getFPFeatures(), L: ToOperatorLoc, RParenLoc: ToRParenLoc,
8837 AngleBrackets: ToAngleBrackets);
8838 } else if (isa<CXXDynamicCastExpr>(Val: E)) {
8839 return CXXDynamicCastExpr::Create(
8840 Context: Importer.getToContext(), T: ToType, VK, Kind: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8841 Written: ToTypeInfoAsWritten, L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8842 } else if (isa<CXXReinterpretCastExpr>(Val: E)) {
8843 return CXXReinterpretCastExpr::Create(
8844 Context: Importer.getToContext(), T: ToType, VK, Kind: CK, Op: ToSubExpr, Path: &(*ToBasePathOrErr),
8845 WrittenTy: ToTypeInfoAsWritten, L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8846 } else if (isa<CXXConstCastExpr>(Val: E)) {
8847 return CXXConstCastExpr::Create(
8848 Context: Importer.getToContext(), T: ToType, VK, Op: ToSubExpr, WrittenTy: ToTypeInfoAsWritten,
8849 L: ToOperatorLoc, RParenLoc: ToRParenLoc, AngleBrackets: ToAngleBrackets);
8850 } else {
8851 llvm_unreachable("Unknown cast type");
8852 return make_error<ASTImportError>();
8853 }
8854}
8855
8856ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
8857 SubstNonTypeTemplateParmExpr *E) {
8858 Error Err = Error::success();
8859 auto ToType = importChecked(Err, E->getType());
8860 auto ToExprLoc = importChecked(Err, E->getExprLoc());
8861 auto ToAssociatedDecl = importChecked(Err, From: E->getAssociatedDecl());
8862 auto ToReplacement = importChecked(Err, From: E->getReplacement());
8863 if (Err)
8864 return std::move(Err);
8865
8866 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
8867 ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl,
8868 E->getIndex(), E->getPackIndex(), E->isReferenceParameter());
8869}
8870
8871ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
8872 Error Err = Error::success();
8873 auto ToType = importChecked(Err, E->getType());
8874 auto ToBeginLoc = importChecked(Err, From: E->getBeginLoc());
8875 auto ToEndLoc = importChecked(Err, From: E->getEndLoc());
8876 if (Err)
8877 return std::move(Err);
8878
8879 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
8880 if (Error Err = ImportContainerChecked(InContainer: E->getArgs(), OutContainer&: ToArgs))
8881 return std::move(Err);
8882
8883 // According to Sema::BuildTypeTrait(), if E is value-dependent,
8884 // Value is always false.
8885 bool ToValue = (E->isValueDependent() ? false : E->getValue());
8886
8887 return TypeTraitExpr::Create(
8888 C: Importer.getToContext(), T: ToType, Loc: ToBeginLoc, Kind: E->getTrait(), Args: ToArgs,
8889 RParenLoc: ToEndLoc, Value: ToValue);
8890}
8891
8892ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
8893 ExpectedType ToTypeOrErr = import(E->getType());
8894 if (!ToTypeOrErr)
8895 return ToTypeOrErr.takeError();
8896
8897 auto ToSourceRangeOrErr = import(From: E->getSourceRange());
8898 if (!ToSourceRangeOrErr)
8899 return ToSourceRangeOrErr.takeError();
8900
8901 if (E->isTypeOperand()) {
8902 if (auto ToTSIOrErr = import(From: E->getTypeOperandSourceInfo()))
8903 return new (Importer.getToContext()) CXXTypeidExpr(
8904 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
8905 else
8906 return ToTSIOrErr.takeError();
8907 }
8908
8909 ExpectedExpr ToExprOperandOrErr = import(From: E->getExprOperand());
8910 if (!ToExprOperandOrErr)
8911 return ToExprOperandOrErr.takeError();
8912
8913 return new (Importer.getToContext()) CXXTypeidExpr(
8914 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
8915}
8916
8917ExpectedStmt ASTNodeImporter::VisitCXXFoldExpr(CXXFoldExpr *E) {
8918 Error Err = Error::success();
8919
8920 QualType ToType = importChecked(Err, E->getType());
8921 UnresolvedLookupExpr *ToCallee = importChecked(Err, From: E->getCallee());
8922 SourceLocation ToLParenLoc = importChecked(Err, From: E->getLParenLoc());
8923 Expr *ToLHS = importChecked(Err, From: E->getLHS());
8924 SourceLocation ToEllipsisLoc = importChecked(Err, From: E->getEllipsisLoc());
8925 Expr *ToRHS = importChecked(Err, From: E->getRHS());
8926 SourceLocation ToRParenLoc = importChecked(Err, From: E->getRParenLoc());
8927
8928 if (Err)
8929 return std::move(Err);
8930
8931 return new (Importer.getToContext())
8932 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
8933 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
8934}
8935
8936Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod,
8937 CXXMethodDecl *FromMethod) {
8938 Error ImportErrors = Error::success();
8939 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
8940 if (auto ImportedOrErr = import(From: FromOverriddenMethod))
8941 ToMethod->getCanonicalDecl()->addOverriddenMethod(MD: cast<CXXMethodDecl>(
8942 Val: (*ImportedOrErr)->getCanonicalDecl()));
8943 else
8944 ImportErrors =
8945 joinErrors(E1: std::move(ImportErrors), E2: ImportedOrErr.takeError());
8946 }
8947 return ImportErrors;
8948}
8949
8950ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
8951 ASTContext &FromContext, FileManager &FromFileManager,
8952 bool MinimalImport,
8953 std::shared_ptr<ASTImporterSharedState> SharedState)
8954 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
8955 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
8956 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
8957
8958 // Create a default state without the lookup table: LLDB case.
8959 if (!SharedState) {
8960 this->SharedState = std::make_shared<ASTImporterSharedState>();
8961 }
8962
8963 ImportedDecls[FromContext.getTranslationUnitDecl()] =
8964 ToContext.getTranslationUnitDecl();
8965}
8966
8967ASTImporter::~ASTImporter() = default;
8968
8969std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
8970 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
8971 "Try to get field index for non-field.");
8972
8973 auto *Owner = dyn_cast<RecordDecl>(Val: F->getDeclContext());
8974 if (!Owner)
8975 return std::nullopt;
8976
8977 unsigned Index = 0;
8978 for (const auto *D : Owner->decls()) {
8979 if (D == F)
8980 return Index;
8981
8982 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
8983 ++Index;
8984 }
8985
8986 llvm_unreachable("Field was not found in its parent context.");
8987
8988 return std::nullopt;
8989}
8990
8991ASTImporter::FoundDeclsTy
8992ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
8993 // We search in the redecl context because of transparent contexts.
8994 // E.g. a simple C language enum is a transparent context:
8995 // enum E { A, B };
8996 // Now if we had a global variable in the TU
8997 // int A;
8998 // then the enum constant 'A' and the variable 'A' violates ODR.
8999 // We can diagnose this only if we search in the redecl context.
9000 DeclContext *ReDC = DC->getRedeclContext();
9001 if (SharedState->getLookupTable()) {
9002 ASTImporterLookupTable::LookupResult LookupResult =
9003 SharedState->getLookupTable()->lookup(DC: ReDC, Name);
9004 return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
9005 } else {
9006 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
9007 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
9008 // We must search by the slow case of localUncachedLookup because that is
9009 // working even if there is no LookupPtr for the DC. We could use
9010 // DC::buildLookup() to create the LookupPtr, but that would load external
9011 // decls again, we must avoid that case.
9012 // Also, even if we had the LookupPtr, we must find Decls which are not
9013 // in the LookupPtr, so we need the slow case.
9014 // These cases are handled in ASTImporterLookupTable, but we cannot use
9015 // that with LLDB since that traverses through the AST which initiates the
9016 // load of external decls again via DC::decls(). And again, we must avoid
9017 // loading external decls during the import.
9018 if (Result.empty())
9019 ReDC->localUncachedLookup(Name, Results&: Result);
9020 return Result;
9021 }
9022}
9023
9024void ASTImporter::AddToLookupTable(Decl *ToD) {
9025 SharedState->addDeclToLookup(D: ToD);
9026}
9027
9028Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) {
9029 // Import the decl using ASTNodeImporter.
9030 ASTNodeImporter Importer(*this);
9031 return Importer.Visit(FromD);
9032}
9033
9034void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) {
9035 MapImported(From: FromD, To: ToD);
9036}
9037
9038llvm::Expected<ExprWithCleanups::CleanupObject>
9039ASTImporter::Import(ExprWithCleanups::CleanupObject From) {
9040 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
9041 if (Expected<Expr *> R = Import(From: CLE))
9042 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(Val: *R));
9043 }
9044
9045 // FIXME: Handle BlockDecl when we implement importing BlockExpr in
9046 // ASTNodeImporter.
9047 return make_error<ASTImportError>(Args: ASTImportError::UnsupportedConstruct);
9048}
9049
9050ExpectedTypePtr ASTImporter::Import(const Type *FromT) {
9051 if (!FromT)
9052 return FromT;
9053
9054 // Check whether we've already imported this type.
9055 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
9056 ImportedTypes.find(Val: FromT);
9057 if (Pos != ImportedTypes.end())
9058 return Pos->second;
9059
9060 // Import the type.
9061 ASTNodeImporter Importer(*this);
9062 ExpectedType ToTOrErr = Importer.Visit(T: FromT);
9063 if (!ToTOrErr)
9064 return ToTOrErr.takeError();
9065
9066 // Record the imported type.
9067 ImportedTypes[FromT] = ToTOrErr->getTypePtr();
9068
9069 return ToTOrErr->getTypePtr();
9070}
9071
9072Expected<QualType> ASTImporter::Import(QualType FromT) {
9073 if (FromT.isNull())
9074 return QualType{};
9075
9076 ExpectedTypePtr ToTyOrErr = Import(FromT: FromT.getTypePtr());
9077 if (!ToTyOrErr)
9078 return ToTyOrErr.takeError();
9079
9080 return ToContext.getQualifiedType(T: *ToTyOrErr, Qs: FromT.getLocalQualifiers());
9081}
9082
9083Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) {
9084 if (!FromTSI)
9085 return FromTSI;
9086
9087 // FIXME: For now we just create a "trivial" type source info based
9088 // on the type and a single location. Implement a real version of this.
9089 ExpectedType TOrErr = Import(FromT: FromTSI->getType());
9090 if (!TOrErr)
9091 return TOrErr.takeError();
9092 ExpectedSLoc BeginLocOrErr = Import(FromLoc: FromTSI->getTypeLoc().getBeginLoc());
9093 if (!BeginLocOrErr)
9094 return BeginLocOrErr.takeError();
9095
9096 return ToContext.getTrivialTypeSourceInfo(T: *TOrErr, Loc: *BeginLocOrErr);
9097}
9098
9099namespace {
9100// To use this object, it should be created before the new attribute is created,
9101// and destructed after it is created. The construction already performs the
9102// import of the data.
9103template <typename T> struct AttrArgImporter {
9104 AttrArgImporter(const AttrArgImporter<T> &) = delete;
9105 AttrArgImporter(AttrArgImporter<T> &&) = default;
9106 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete;
9107 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default;
9108
9109 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From)
9110 : To(I.importChecked(Err, From)) {}
9111
9112 const T &value() { return To; }
9113
9114private:
9115 T To;
9116};
9117
9118// To use this object, it should be created before the new attribute is created,
9119// and destructed after it is created. The construction already performs the
9120// import of the data. The array data is accessible in a pointer form, this form
9121// is used by the attribute classes. This object should be created once for the
9122// array data to be imported (the array size is not imported, just copied).
9123template <typename T> struct AttrArgArrayImporter {
9124 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete;
9125 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default;
9126 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete;
9127 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default;
9128
9129 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err,
9130 const llvm::iterator_range<T *> &From,
9131 unsigned ArraySize) {
9132 if (Err)
9133 return;
9134 To.reserve(ArraySize);
9135 Err = I.ImportContainerChecked(From, To);
9136 }
9137
9138 T *value() { return To.data(); }
9139
9140private:
9141 llvm::SmallVector<T, 2> To;
9142};
9143
9144class AttrImporter {
9145 Error Err{Error::success()};
9146 Attr *ToAttr = nullptr;
9147 ASTImporter &Importer;
9148 ASTNodeImporter NImporter;
9149
9150public:
9151 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {}
9152
9153 // Useful for accessing the imported attribute.
9154 template <typename T> T *castAttrAs() { return cast<T>(ToAttr); }
9155 template <typename T> const T *castAttrAs() const { return cast<T>(ToAttr); }
9156
9157 // Create an "importer" for an attribute parameter.
9158 // Result of the 'value()' of that object is to be passed to the function
9159 // 'importAttr', in the order that is expected by the attribute class.
9160 template <class T> AttrArgImporter<T> importArg(const T &From) {
9161 return AttrArgImporter<T>(NImporter, Err, From);
9162 }
9163
9164 // Create an "importer" for an attribute parameter that has array type.
9165 // Result of the 'value()' of that object is to be passed to the function
9166 // 'importAttr', then the size of the array as next argument.
9167 template <typename T>
9168 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From,
9169 unsigned ArraySize) {
9170 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize);
9171 }
9172
9173 // Create an attribute object with the specified arguments.
9174 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg'
9175 // should be values that are passed to the 'Create' function of the attribute.
9176 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is
9177 // used here.) As much data is copied or imported from the old attribute
9178 // as possible. The passed arguments should be already imported.
9179 // If an import error happens, the internal error is set to it, and any
9180 // further import attempt is ignored.
9181 template <typename T, typename... Arg>
9182 void importAttr(const T *FromAttr, Arg &&...ImportedArg) {
9183 static_assert(std::is_base_of<Attr, T>::value,
9184 "T should be subclass of Attr.");
9185 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9186
9187 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName());
9188 const IdentifierInfo *ToScopeName =
9189 Importer.Import(FromAttr->getScopeName());
9190 SourceRange ToAttrRange =
9191 NImporter.importChecked(Err, FromAttr->getRange());
9192 SourceLocation ToScopeLoc =
9193 NImporter.importChecked(Err, FromAttr->getScopeLoc());
9194
9195 if (Err)
9196 return;
9197
9198 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc,
9199 FromAttr->getParsedKind(), FromAttr->getForm());
9200 // The "SemanticSpelling" is not needed to be passed to the constructor.
9201 // That value is recalculated from the SpellingListIndex if needed.
9202 ToAttr = T::Create(Importer.getToContext(),
9203 std::forward<Arg>(ImportedArg)..., ToI);
9204
9205 ToAttr->setImplicit(FromAttr->isImplicit());
9206 ToAttr->setPackExpansion(FromAttr->isPackExpansion());
9207 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(Val: ToAttr))
9208 ToInheritableAttr->setInherited(FromAttr->isInherited());
9209 }
9210
9211 // Create a clone of the 'FromAttr' and import its source range only.
9212 // This causes objects with invalid references to be created if the 'FromAttr'
9213 // contains other data that should be imported.
9214 void cloneAttr(const Attr *FromAttr) {
9215 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9216
9217 SourceRange ToRange = NImporter.importChecked(Err, From: FromAttr->getRange());
9218 if (Err)
9219 return;
9220
9221 ToAttr = FromAttr->clone(C&: Importer.getToContext());
9222 ToAttr->setRange(ToRange);
9223 ToAttr->setAttrName(Importer.Import(FromId: FromAttr->getAttrName()));
9224 }
9225
9226 // Get the result of the previous import attempt (can be used only once).
9227 llvm::Expected<Attr *> getResult() && {
9228 if (Err)
9229 return std::move(Err);
9230 assert(ToAttr && "Attribute should be created.");
9231 return ToAttr;
9232 }
9233};
9234} // namespace
9235
9236Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) {
9237 AttrImporter AI(*this);
9238
9239 // FIXME: Is there some kind of AttrVisitor to use here?
9240 switch (FromAttr->getKind()) {
9241 case attr::Aligned: {
9242 auto *From = cast<AlignedAttr>(FromAttr);
9243 if (From->isAlignmentExpr())
9244 AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value());
9245 else
9246 AI.importAttr(From, false,
9247 AI.importArg(From->getAlignmentType()).value());
9248 break;
9249 }
9250
9251 case attr::AlignValue: {
9252 auto *From = cast<AlignValueAttr>(FromAttr);
9253 AI.importAttr(From, AI.importArg(From->getAlignment()).value());
9254 break;
9255 }
9256
9257 case attr::Format: {
9258 const auto *From = cast<FormatAttr>(FromAttr);
9259 AI.importAttr(From, Import(From->getType()), From->getFormatIdx(),
9260 From->getFirstArg());
9261 break;
9262 }
9263
9264 case attr::EnableIf: {
9265 const auto *From = cast<EnableIfAttr>(FromAttr);
9266 AI.importAttr(From, AI.importArg(From->getCond()).value(),
9267 From->getMessage());
9268 break;
9269 }
9270
9271 case attr::AssertCapability: {
9272 const auto *From = cast<AssertCapabilityAttr>(FromAttr);
9273 AI.importAttr(From,
9274 AI.importArrayArg(From->args(), From->args_size()).value(),
9275 From->args_size());
9276 break;
9277 }
9278 case attr::AcquireCapability: {
9279 const auto *From = cast<AcquireCapabilityAttr>(FromAttr);
9280 AI.importAttr(From,
9281 AI.importArrayArg(From->args(), From->args_size()).value(),
9282 From->args_size());
9283 break;
9284 }
9285 case attr::TryAcquireCapability: {
9286 const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr);
9287 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9288 AI.importArrayArg(From->args(), From->args_size()).value(),
9289 From->args_size());
9290 break;
9291 }
9292 case attr::ReleaseCapability: {
9293 const auto *From = cast<ReleaseCapabilityAttr>(FromAttr);
9294 AI.importAttr(From,
9295 AI.importArrayArg(From->args(), From->args_size()).value(),
9296 From->args_size());
9297 break;
9298 }
9299 case attr::RequiresCapability: {
9300 const auto *From = cast<RequiresCapabilityAttr>(FromAttr);
9301 AI.importAttr(From,
9302 AI.importArrayArg(From->args(), From->args_size()).value(),
9303 From->args_size());
9304 break;
9305 }
9306 case attr::GuardedBy: {
9307 const auto *From = cast<GuardedByAttr>(FromAttr);
9308 AI.importAttr(From, AI.importArg(From->getArg()).value());
9309 break;
9310 }
9311 case attr::PtGuardedBy: {
9312 const auto *From = cast<PtGuardedByAttr>(FromAttr);
9313 AI.importAttr(From, AI.importArg(From->getArg()).value());
9314 break;
9315 }
9316 case attr::AcquiredAfter: {
9317 const auto *From = cast<AcquiredAfterAttr>(FromAttr);
9318 AI.importAttr(From,
9319 AI.importArrayArg(From->args(), From->args_size()).value(),
9320 From->args_size());
9321 break;
9322 }
9323 case attr::AcquiredBefore: {
9324 const auto *From = cast<AcquiredBeforeAttr>(FromAttr);
9325 AI.importAttr(From,
9326 AI.importArrayArg(From->args(), From->args_size()).value(),
9327 From->args_size());
9328 break;
9329 }
9330 case attr::AssertExclusiveLock: {
9331 const auto *From = cast<AssertExclusiveLockAttr>(FromAttr);
9332 AI.importAttr(From,
9333 AI.importArrayArg(From->args(), From->args_size()).value(),
9334 From->args_size());
9335 break;
9336 }
9337 case attr::AssertSharedLock: {
9338 const auto *From = cast<AssertSharedLockAttr>(FromAttr);
9339 AI.importAttr(From,
9340 AI.importArrayArg(From->args(), From->args_size()).value(),
9341 From->args_size());
9342 break;
9343 }
9344 case attr::ExclusiveTrylockFunction: {
9345 const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr);
9346 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9347 AI.importArrayArg(From->args(), From->args_size()).value(),
9348 From->args_size());
9349 break;
9350 }
9351 case attr::SharedTrylockFunction: {
9352 const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr);
9353 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9354 AI.importArrayArg(From->args(), From->args_size()).value(),
9355 From->args_size());
9356 break;
9357 }
9358 case attr::LockReturned: {
9359 const auto *From = cast<LockReturnedAttr>(FromAttr);
9360 AI.importAttr(From, AI.importArg(From->getArg()).value());
9361 break;
9362 }
9363 case attr::LocksExcluded: {
9364 const auto *From = cast<LocksExcludedAttr>(FromAttr);
9365 AI.importAttr(From,
9366 AI.importArrayArg(From->args(), From->args_size()).value(),
9367 From->args_size());
9368 break;
9369 }
9370 default: {
9371 // The default branch works for attributes that have no arguments to import.
9372 // FIXME: Handle every attribute type that has arguments of type to import
9373 // (most often Expr* or Decl* or type) in the switch above.
9374 AI.cloneAttr(FromAttr);
9375 break;
9376 }
9377 }
9378
9379 return std::move(AI).getResult();
9380}
9381
9382Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const {
9383 return ImportedDecls.lookup(Val: FromD);
9384}
9385
9386TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) {
9387 auto FromDPos = ImportedFromDecls.find(Val: ToD);
9388 if (FromDPos == ImportedFromDecls.end())
9389 return nullptr;
9390 return FromDPos->second->getTranslationUnitDecl();
9391}
9392
9393Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) {
9394 if (!FromD->hasAttrs() || ToD->hasAttrs())
9395 return Error::success();
9396 for (const Attr *FromAttr : FromD->getAttrs()) {
9397 auto ToAttrOrErr = Import(FromAttr);
9398 if (ToAttrOrErr)
9399 ToD->addAttr(A: *ToAttrOrErr);
9400 else
9401 return ToAttrOrErr.takeError();
9402 }
9403 return Error::success();
9404}
9405
9406Expected<Decl *> ASTImporter::Import(Decl *FromD) {
9407 if (!FromD)
9408 return nullptr;
9409
9410 // Push FromD to the stack, and remove that when we return.
9411 ImportPath.push(D: FromD);
9412 auto ImportPathBuilder =
9413 llvm::make_scope_exit(F: [this]() { ImportPath.pop(); });
9414
9415 // Check whether there was a previous failed import.
9416 // If yes return the existing error.
9417 if (auto Error = getImportDeclErrorIfAny(FromD))
9418 return make_error<ASTImportError>(Args&: *Error);
9419
9420 // Check whether we've already imported this declaration.
9421 Decl *ToD = GetAlreadyImportedOrNull(FromD);
9422 if (ToD) {
9423 // Already imported (possibly from another TU) and with an error.
9424 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9425 setImportDeclError(From: FromD, Error: *Error);
9426 return make_error<ASTImportError>(Args&: *Error);
9427 }
9428
9429 // If FromD has some updated flags after last import, apply it.
9430 updateFlags(From: FromD, To: ToD);
9431 // If we encounter a cycle during an import then we save the relevant part
9432 // of the import path associated to the Decl.
9433 if (ImportPath.hasCycleAtBack())
9434 SavedImportPaths[FromD].push_back(Elt: ImportPath.copyCycleAtBack());
9435 return ToD;
9436 }
9437
9438 // Import the declaration.
9439 ExpectedDecl ToDOrErr = ImportImpl(FromD);
9440 if (!ToDOrErr) {
9441 // Failed to import.
9442
9443 auto Pos = ImportedDecls.find(Val: FromD);
9444 if (Pos != ImportedDecls.end()) {
9445 // Import failed after the object was created.
9446 // Remove all references to it.
9447 auto *ToD = Pos->second;
9448 ImportedDecls.erase(I: Pos);
9449
9450 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
9451 // (e.g. with namespaces) that several decls from the 'from' context are
9452 // mapped to the same decl in the 'to' context. If we removed entries
9453 // from the LookupTable here then we may end up removing them multiple
9454 // times.
9455
9456 // The Lookuptable contains decls only which are in the 'to' context.
9457 // Remove from the Lookuptable only if it is *imported* into the 'to'
9458 // context (and do not remove it if it was added during the initial
9459 // traverse of the 'to' context).
9460 auto PosF = ImportedFromDecls.find(Val: ToD);
9461 if (PosF != ImportedFromDecls.end()) {
9462 // In the case of TypedefNameDecl we create the Decl first and only
9463 // then we import and set its DeclContext. So, the DC might not be set
9464 // when we reach here.
9465 if (ToD->getDeclContext())
9466 SharedState->removeDeclFromLookup(D: ToD);
9467 ImportedFromDecls.erase(I: PosF);
9468 }
9469
9470 // FIXME: AST may contain remaining references to the failed object.
9471 // However, the ImportDeclErrors in the shared state contains all the
9472 // failed objects together with their error.
9473 }
9474
9475 // Error encountered for the first time.
9476 // After takeError the error is not usable any more in ToDOrErr.
9477 // Get a copy of the error object (any more simple solution for this?).
9478 ASTImportError ErrOut;
9479 handleAllErrors(E: ToDOrErr.takeError(),
9480 Handlers: [&ErrOut](const ASTImportError &E) { ErrOut = E; });
9481 setImportDeclError(From: FromD, Error: ErrOut);
9482 // Set the error for the mapped to Decl, which is in the "to" context.
9483 if (Pos != ImportedDecls.end())
9484 SharedState->setImportDeclError(To: Pos->second, Error: ErrOut);
9485
9486 // Set the error for all nodes which have been created before we
9487 // recognized the error.
9488 for (const auto &Path : SavedImportPaths[FromD]) {
9489 // The import path contains import-dependency nodes first.
9490 // Save the node that was imported as dependency of the current node.
9491 Decl *PrevFromDi = FromD;
9492 for (Decl *FromDi : Path) {
9493 // Begin and end of the path equals 'FromD', skip it.
9494 if (FromDi == FromD)
9495 continue;
9496 // We should not set import error on a node and all following nodes in
9497 // the path if child import errors are ignored.
9498 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent(
9499 FromChildD: PrevFromDi))
9500 break;
9501 PrevFromDi = FromDi;
9502 setImportDeclError(From: FromDi, Error: ErrOut);
9503 //FIXME Should we remove these Decls from ImportedDecls?
9504 // Set the error for the mapped to Decl, which is in the "to" context.
9505 auto Ii = ImportedDecls.find(Val: FromDi);
9506 if (Ii != ImportedDecls.end())
9507 SharedState->setImportDeclError(To: Ii->second, Error: ErrOut);
9508 // FIXME Should we remove these Decls from the LookupTable,
9509 // and from ImportedFromDecls?
9510 }
9511 }
9512 SavedImportPaths.erase(Val: FromD);
9513
9514 // Do not return ToDOrErr, error was taken out of it.
9515 return make_error<ASTImportError>(Args&: ErrOut);
9516 }
9517
9518 ToD = *ToDOrErr;
9519
9520 // FIXME: Handle the "already imported with error" case. We can get here
9521 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
9522 // previously failed create was requested).
9523 // Later GetImportedOrCreateDecl can be updated to return the error.
9524 if (!ToD) {
9525 auto Err = getImportDeclErrorIfAny(FromD);
9526 assert(Err);
9527 return make_error<ASTImportError>(Args&: *Err);
9528 }
9529
9530 // We could import from the current TU without error. But previously we
9531 // already had imported a Decl as `ToD` from another TU (with another
9532 // ASTImporter object) and with an error.
9533 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9534 setImportDeclError(From: FromD, Error: *Error);
9535 return make_error<ASTImportError>(Args&: *Error);
9536 }
9537 // Make sure that ImportImpl registered the imported decl.
9538 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
9539 if (auto Error = ImportAttrs(ToD, FromD))
9540 return std::move(Error);
9541
9542 // Notify subclasses.
9543 Imported(From: FromD, To: ToD);
9544
9545 updateFlags(From: FromD, To: ToD);
9546 SavedImportPaths.erase(Val: FromD);
9547 return ToDOrErr;
9548}
9549
9550llvm::Expected<InheritedConstructor>
9551ASTImporter::Import(const InheritedConstructor &From) {
9552 return ASTNodeImporter(*this).ImportInheritedConstructor(From);
9553}
9554
9555Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) {
9556 if (!FromDC)
9557 return FromDC;
9558
9559 ExpectedDecl ToDCOrErr = Import(FromD: cast<Decl>(Val: FromDC));
9560 if (!ToDCOrErr)
9561 return ToDCOrErr.takeError();
9562 auto *ToDC = cast<DeclContext>(Val: *ToDCOrErr);
9563
9564 // When we're using a record/enum/Objective-C class/protocol as a context, we
9565 // need it to have a definition.
9566 if (auto *ToRecord = dyn_cast<RecordDecl>(Val: ToDC)) {
9567 auto *FromRecord = cast<RecordDecl>(Val: FromDC);
9568 if (ToRecord->isCompleteDefinition())
9569 return ToDC;
9570
9571 // If FromRecord is not defined we need to force it to be.
9572 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases
9573 // it will start the definition but we never finish it.
9574 // If there are base classes they won't be imported and we will
9575 // be missing anything that we inherit from those bases.
9576 if (FromRecord->getASTContext().getExternalSource() &&
9577 !FromRecord->isCompleteDefinition())
9578 FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord);
9579
9580 if (FromRecord->isCompleteDefinition())
9581 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9582 From: FromRecord, To: ToRecord, Kind: ASTNodeImporter::IDK_Basic))
9583 return std::move(Err);
9584 } else if (auto *ToEnum = dyn_cast<EnumDecl>(Val: ToDC)) {
9585 auto *FromEnum = cast<EnumDecl>(Val: FromDC);
9586 if (ToEnum->isCompleteDefinition()) {
9587 // Do nothing.
9588 } else if (FromEnum->isCompleteDefinition()) {
9589 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9590 From: FromEnum, To: ToEnum, Kind: ASTNodeImporter::IDK_Basic))
9591 return std::move(Err);
9592 } else {
9593 CompleteDecl(ToEnum);
9594 }
9595 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(Val: ToDC)) {
9596 auto *FromClass = cast<ObjCInterfaceDecl>(Val: FromDC);
9597 if (ToClass->getDefinition()) {
9598 // Do nothing.
9599 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
9600 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9601 From: FromDef, To: ToClass, Kind: ASTNodeImporter::IDK_Basic))
9602 return std::move(Err);
9603 } else {
9604 CompleteDecl(ToClass);
9605 }
9606 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(Val: ToDC)) {
9607 auto *FromProto = cast<ObjCProtocolDecl>(Val: FromDC);
9608 if (ToProto->getDefinition()) {
9609 // Do nothing.
9610 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
9611 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9612 From: FromDef, To: ToProto, Kind: ASTNodeImporter::IDK_Basic))
9613 return std::move(Err);
9614 } else {
9615 CompleteDecl(ToProto);
9616 }
9617 }
9618
9619 return ToDC;
9620}
9621
9622Expected<Expr *> ASTImporter::Import(Expr *FromE) {
9623 if (ExpectedStmt ToSOrErr = Import(FromS: cast_or_null<Stmt>(Val: FromE)))
9624 return cast_or_null<Expr>(Val: *ToSOrErr);
9625 else
9626 return ToSOrErr.takeError();
9627}
9628
9629Expected<Stmt *> ASTImporter::Import(Stmt *FromS) {
9630 if (!FromS)
9631 return nullptr;
9632
9633 // Check whether we've already imported this statement.
9634 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(Val: FromS);
9635 if (Pos != ImportedStmts.end())
9636 return Pos->second;
9637
9638 // Import the statement.
9639 ASTNodeImporter Importer(*this);
9640 ExpectedStmt ToSOrErr = Importer.Visit(FromS);
9641 if (!ToSOrErr)
9642 return ToSOrErr;
9643
9644 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
9645 auto *FromE = cast<Expr>(Val: FromS);
9646 // Copy ExprBitfields, which may not be handled in Expr subclasses
9647 // constructors.
9648 ToE->setValueKind(FromE->getValueKind());
9649 ToE->setObjectKind(FromE->getObjectKind());
9650 ToE->setDependence(FromE->getDependence());
9651 }
9652
9653 // Record the imported statement object.
9654 ImportedStmts[FromS] = *ToSOrErr;
9655 return ToSOrErr;
9656}
9657
9658Expected<NestedNameSpecifier *>
9659ASTImporter::Import(NestedNameSpecifier *FromNNS) {
9660 if (!FromNNS)
9661 return nullptr;
9662
9663 NestedNameSpecifier *Prefix = nullptr;
9664 if (Error Err = importInto(To&: Prefix, From: FromNNS->getPrefix()))
9665 return std::move(Err);
9666
9667 switch (FromNNS->getKind()) {
9668 case NestedNameSpecifier::Identifier:
9669 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
9670 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9671 II: Import(FromId: FromNNS->getAsIdentifier()));
9672
9673 case NestedNameSpecifier::Namespace:
9674 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
9675 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9676 NS: cast<NamespaceDecl>(Val: *NSOrErr));
9677 } else
9678 return NSOrErr.takeError();
9679
9680 case NestedNameSpecifier::NamespaceAlias:
9681 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
9682 return NestedNameSpecifier::Create(Context: ToContext, Prefix,
9683 Alias: cast<NamespaceAliasDecl>(Val: *NSADOrErr));
9684 else
9685 return NSADOrErr.takeError();
9686
9687 case NestedNameSpecifier::Global:
9688 return NestedNameSpecifier::GlobalSpecifier(Context: ToContext);
9689
9690 case NestedNameSpecifier::Super:
9691 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
9692 return NestedNameSpecifier::SuperSpecifier(Context: ToContext,
9693 RD: cast<CXXRecordDecl>(Val: *RDOrErr));
9694 else
9695 return RDOrErr.takeError();
9696
9697 case NestedNameSpecifier::TypeSpec:
9698 case NestedNameSpecifier::TypeSpecWithTemplate:
9699 if (ExpectedTypePtr TyOrErr = Import(FromT: FromNNS->getAsType())) {
9700 bool TSTemplate =
9701 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate;
9702 return NestedNameSpecifier::Create(Context: ToContext, Prefix, Template: TSTemplate,
9703 T: *TyOrErr);
9704 } else {
9705 return TyOrErr.takeError();
9706 }
9707 }
9708
9709 llvm_unreachable("Invalid nested name specifier kind");
9710}
9711
9712Expected<NestedNameSpecifierLoc>
9713ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
9714 // Copied from NestedNameSpecifier mostly.
9715 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
9716 NestedNameSpecifierLoc NNS = FromNNS;
9717
9718 // Push each of the nested-name-specifiers's onto a stack for
9719 // serialization in reverse order.
9720 while (NNS) {
9721 NestedNames.push_back(Elt: NNS);
9722 NNS = NNS.getPrefix();
9723 }
9724
9725 NestedNameSpecifierLocBuilder Builder;
9726
9727 while (!NestedNames.empty()) {
9728 NNS = NestedNames.pop_back_val();
9729 NestedNameSpecifier *Spec = nullptr;
9730 if (Error Err = importInto(To&: Spec, From: NNS.getNestedNameSpecifier()))
9731 return std::move(Err);
9732
9733 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
9734
9735 SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
9736 if (Kind != NestedNameSpecifier::Super) {
9737 if (Error Err = importInto(To&: ToLocalBeginLoc, From: NNS.getLocalBeginLoc()))
9738 return std::move(Err);
9739
9740 if (Kind != NestedNameSpecifier::Global)
9741 if (Error Err = importInto(To&: ToLocalEndLoc, From: NNS.getLocalEndLoc()))
9742 return std::move(Err);
9743 }
9744
9745 switch (Kind) {
9746 case NestedNameSpecifier::Identifier:
9747 Builder.Extend(Context&: getToContext(), Identifier: Spec->getAsIdentifier(), IdentifierLoc: ToLocalBeginLoc,
9748 ColonColonLoc: ToLocalEndLoc);
9749 break;
9750
9751 case NestedNameSpecifier::Namespace:
9752 Builder.Extend(Context&: getToContext(), Namespace: Spec->getAsNamespace(), NamespaceLoc: ToLocalBeginLoc,
9753 ColonColonLoc: ToLocalEndLoc);
9754 break;
9755
9756 case NestedNameSpecifier::NamespaceAlias:
9757 Builder.Extend(Context&: getToContext(), Alias: Spec->getAsNamespaceAlias(),
9758 AliasLoc: ToLocalBeginLoc, ColonColonLoc: ToLocalEndLoc);
9759 break;
9760
9761 case NestedNameSpecifier::TypeSpec:
9762 case NestedNameSpecifier::TypeSpecWithTemplate: {
9763 SourceLocation ToTLoc;
9764 if (Error Err = importInto(To&: ToTLoc, From: NNS.getTypeLoc().getBeginLoc()))
9765 return std::move(Err);
9766 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
9767 T: QualType(Spec->getAsType(), 0), Loc: ToTLoc);
9768 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate)
9769 // ToLocalBeginLoc is here the location of the 'template' keyword.
9770 Builder.Extend(Context&: getToContext(), TemplateKWLoc: ToLocalBeginLoc, TL: TSI->getTypeLoc(),
9771 ColonColonLoc: ToLocalEndLoc);
9772 else
9773 // No location for 'template' keyword here.
9774 Builder.Extend(Context&: getToContext(), TemplateKWLoc: SourceLocation{}, TL: TSI->getTypeLoc(),
9775 ColonColonLoc: ToLocalEndLoc);
9776 break;
9777 }
9778
9779 case NestedNameSpecifier::Global:
9780 Builder.MakeGlobal(Context&: getToContext(), ColonColonLoc: ToLocalBeginLoc);
9781 break;
9782
9783 case NestedNameSpecifier::Super: {
9784 auto ToSourceRangeOrErr = Import(FromRange: NNS.getSourceRange());
9785 if (!ToSourceRangeOrErr)
9786 return ToSourceRangeOrErr.takeError();
9787
9788 Builder.MakeSuper(Context&: getToContext(), RD: Spec->getAsRecordDecl(),
9789 SuperLoc: ToSourceRangeOrErr->getBegin(),
9790 ColonColonLoc: ToSourceRangeOrErr->getEnd());
9791 }
9792 }
9793 }
9794
9795 return Builder.getWithLocInContext(Context&: getToContext());
9796}
9797
9798Expected<TemplateName> ASTImporter::Import(TemplateName From) {
9799 switch (From.getKind()) {
9800 case TemplateName::Template:
9801 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
9802 return TemplateName(cast<TemplateDecl>(Val: (*ToTemplateOrErr)->getCanonicalDecl()));
9803 else
9804 return ToTemplateOrErr.takeError();
9805
9806 case TemplateName::OverloadedTemplate: {
9807 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
9808 UnresolvedSet<2> ToTemplates;
9809 for (auto *I : *FromStorage) {
9810 if (auto ToOrErr = Import(I))
9811 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
9812 else
9813 return ToOrErr.takeError();
9814 }
9815 return ToContext.getOverloadedTemplateName(Begin: ToTemplates.begin(),
9816 End: ToTemplates.end());
9817 }
9818
9819 case TemplateName::AssumedTemplate: {
9820 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName();
9821 auto DeclNameOrErr = Import(FromName: FromStorage->getDeclName());
9822 if (!DeclNameOrErr)
9823 return DeclNameOrErr.takeError();
9824 return ToContext.getAssumedTemplateName(Name: *DeclNameOrErr);
9825 }
9826
9827 case TemplateName::QualifiedTemplate: {
9828 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
9829 auto QualifierOrErr = Import(FromNNS: QTN->getQualifier());
9830 if (!QualifierOrErr)
9831 return QualifierOrErr.takeError();
9832 auto TNOrErr = Import(From: QTN->getUnderlyingTemplate());
9833 if (!TNOrErr)
9834 return TNOrErr.takeError();
9835 return ToContext.getQualifiedTemplateName(
9836 NNS: *QualifierOrErr, TemplateKeyword: QTN->hasTemplateKeyword(), Template: *TNOrErr);
9837 }
9838
9839 case TemplateName::DependentTemplate: {
9840 DependentTemplateName *DTN = From.getAsDependentTemplateName();
9841 auto QualifierOrErr = Import(FromNNS: DTN->getQualifier());
9842 if (!QualifierOrErr)
9843 return QualifierOrErr.takeError();
9844
9845 if (DTN->isIdentifier()) {
9846 return ToContext.getDependentTemplateName(NNS: *QualifierOrErr,
9847 Name: Import(FromId: DTN->getIdentifier()));
9848 }
9849
9850 return ToContext.getDependentTemplateName(NNS: *QualifierOrErr,
9851 Operator: DTN->getOperator());
9852 }
9853
9854 case TemplateName::SubstTemplateTemplateParm: {
9855 SubstTemplateTemplateParmStorage *Subst =
9856 From.getAsSubstTemplateTemplateParm();
9857 auto ReplacementOrErr = Import(From: Subst->getReplacement());
9858 if (!ReplacementOrErr)
9859 return ReplacementOrErr.takeError();
9860
9861 auto AssociatedDeclOrErr = Import(FromD: Subst->getAssociatedDecl());
9862 if (!AssociatedDeclOrErr)
9863 return AssociatedDeclOrErr.takeError();
9864
9865 return ToContext.getSubstTemplateTemplateParm(
9866 replacement: *ReplacementOrErr, AssociatedDecl: *AssociatedDeclOrErr, Index: Subst->getIndex(),
9867 PackIndex: Subst->getPackIndex());
9868 }
9869
9870 case TemplateName::SubstTemplateTemplateParmPack: {
9871 SubstTemplateTemplateParmPackStorage *SubstPack =
9872 From.getAsSubstTemplateTemplateParmPack();
9873 ASTNodeImporter Importer(*this);
9874 auto ArgPackOrErr =
9875 Importer.ImportTemplateArgument(From: SubstPack->getArgumentPack());
9876 if (!ArgPackOrErr)
9877 return ArgPackOrErr.takeError();
9878
9879 auto AssociatedDeclOrErr = Import(FromD: SubstPack->getAssociatedDecl());
9880 if (!AssociatedDeclOrErr)
9881 return AssociatedDeclOrErr.takeError();
9882
9883 return ToContext.getSubstTemplateTemplateParmPack(
9884 ArgPack: *ArgPackOrErr, AssociatedDecl: *AssociatedDeclOrErr, Index: SubstPack->getIndex(),
9885 Final: SubstPack->getFinal());
9886 }
9887 case TemplateName::UsingTemplate: {
9888 auto UsingOrError = Import(From.getAsUsingShadowDecl());
9889 if (!UsingOrError)
9890 return UsingOrError.takeError();
9891 return TemplateName(cast<UsingShadowDecl>(*UsingOrError));
9892 }
9893 }
9894
9895 llvm_unreachable("Invalid template name kind");
9896}
9897
9898Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) {
9899 if (FromLoc.isInvalid())
9900 return SourceLocation{};
9901
9902 SourceManager &FromSM = FromContext.getSourceManager();
9903 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(Loc: FromLoc);
9904
9905 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(Loc: FromLoc);
9906 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
9907 if (!ToFileIDOrErr)
9908 return ToFileIDOrErr.takeError();
9909 SourceManager &ToSM = ToContext.getSourceManager();
9910 return ToSM.getComposedLoc(FID: *ToFileIDOrErr, Offset: Decomposed.second);
9911}
9912
9913Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) {
9914 SourceLocation ToBegin, ToEnd;
9915 if (Error Err = importInto(To&: ToBegin, From: FromRange.getBegin()))
9916 return std::move(Err);
9917 if (Error Err = importInto(To&: ToEnd, From: FromRange.getEnd()))
9918 return std::move(Err);
9919
9920 return SourceRange(ToBegin, ToEnd);
9921}
9922
9923Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) {
9924 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(Val: FromID);
9925 if (Pos != ImportedFileIDs.end())
9926 return Pos->second;
9927
9928 SourceManager &FromSM = FromContext.getSourceManager();
9929 SourceManager &ToSM = ToContext.getSourceManager();
9930 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FID: FromID);
9931
9932 // Map the FromID to the "to" source manager.
9933 FileID ToID;
9934 if (FromSLoc.isExpansion()) {
9935 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
9936 ExpectedSLoc ToSpLoc = Import(FromLoc: FromEx.getSpellingLoc());
9937 if (!ToSpLoc)
9938 return ToSpLoc.takeError();
9939 ExpectedSLoc ToExLocS = Import(FromLoc: FromEx.getExpansionLocStart());
9940 if (!ToExLocS)
9941 return ToExLocS.takeError();
9942 unsigned ExLength = FromSM.getFileIDSize(FID: FromID);
9943 SourceLocation MLoc;
9944 if (FromEx.isMacroArgExpansion()) {
9945 MLoc = ToSM.createMacroArgExpansionLoc(SpellingLoc: *ToSpLoc, ExpansionLoc: *ToExLocS, Length: ExLength);
9946 } else {
9947 if (ExpectedSLoc ToExLocE = Import(FromLoc: FromEx.getExpansionLocEnd()))
9948 MLoc = ToSM.createExpansionLoc(SpellingLoc: *ToSpLoc, ExpansionLocStart: *ToExLocS, ExpansionLocEnd: *ToExLocE, Length: ExLength,
9949 ExpansionIsTokenRange: FromEx.isExpansionTokenRange());
9950 else
9951 return ToExLocE.takeError();
9952 }
9953 ToID = ToSM.getFileID(SpellingLoc: MLoc);
9954 } else {
9955 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
9956
9957 if (!IsBuiltin && !Cache->BufferOverridden) {
9958 // Include location of this file.
9959 ExpectedSLoc ToIncludeLoc = Import(FromLoc: FromSLoc.getFile().getIncludeLoc());
9960 if (!ToIncludeLoc)
9961 return ToIncludeLoc.takeError();
9962
9963 // Every FileID that is not the main FileID needs to have a valid include
9964 // location so that the include chain points to the main FileID. When
9965 // importing the main FileID (which has no include location), we need to
9966 // create a fake include location in the main file to keep this property
9967 // intact.
9968 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
9969 if (FromID == FromSM.getMainFileID())
9970 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(FID: ToSM.getMainFileID());
9971
9972 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
9973 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
9974 // disk again
9975 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
9976 // than mmap the files several times.
9977 auto Entry =
9978 ToFileManager.getOptionalFileRef(Filename: Cache->OrigEntry->getName());
9979 // FIXME: The filename may be a virtual name that does probably not
9980 // point to a valid file and we get no Entry here. In this case try with
9981 // the memory buffer below.
9982 if (Entry)
9983 ToID = ToSM.createFileID(SourceFile: *Entry, IncludePos: ToIncludeLocOrFakeLoc,
9984 FileCharacter: FromSLoc.getFile().getFileCharacteristic());
9985 }
9986 }
9987
9988 if (ToID.isInvalid() || IsBuiltin) {
9989 // FIXME: We want to re-use the existing MemoryBuffer!
9990 std::optional<llvm::MemoryBufferRef> FromBuf =
9991 Cache->getBufferOrNone(Diag&: FromContext.getDiagnostics(),
9992 FM&: FromSM.getFileManager(), Loc: SourceLocation{});
9993 if (!FromBuf)
9994 return llvm::make_error<ASTImportError>(Args: ASTImportError::Unknown);
9995
9996 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
9997 llvm::MemoryBuffer::getMemBufferCopy(InputData: FromBuf->getBuffer(),
9998 BufferName: FromBuf->getBufferIdentifier());
9999 ToID = ToSM.createFileID(Buffer: std::move(ToBuf),
10000 FileCharacter: FromSLoc.getFile().getFileCharacteristic());
10001 }
10002 }
10003
10004 assert(ToID.isValid() && "Unexpected invalid fileID was created.");
10005
10006 ImportedFileIDs[FromID] = ToID;
10007 return ToID;
10008}
10009
10010Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) {
10011 ExpectedExpr ToExprOrErr = Import(FromE: From->getInit());
10012 if (!ToExprOrErr)
10013 return ToExprOrErr.takeError();
10014
10015 auto LParenLocOrErr = Import(FromLoc: From->getLParenLoc());
10016 if (!LParenLocOrErr)
10017 return LParenLocOrErr.takeError();
10018
10019 auto RParenLocOrErr = Import(FromLoc: From->getRParenLoc());
10020 if (!RParenLocOrErr)
10021 return RParenLocOrErr.takeError();
10022
10023 if (From->isBaseInitializer()) {
10024 auto ToTInfoOrErr = Import(FromTSI: From->getTypeSourceInfo());
10025 if (!ToTInfoOrErr)
10026 return ToTInfoOrErr.takeError();
10027
10028 SourceLocation EllipsisLoc;
10029 if (From->isPackExpansion())
10030 if (Error Err = importInto(To&: EllipsisLoc, From: From->getEllipsisLoc()))
10031 return std::move(Err);
10032
10033 return new (ToContext) CXXCtorInitializer(
10034 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
10035 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
10036 } else if (From->isMemberInitializer()) {
10037 ExpectedDecl ToFieldOrErr = Import(From->getMember());
10038 if (!ToFieldOrErr)
10039 return ToFieldOrErr.takeError();
10040
10041 auto MemberLocOrErr = Import(FromLoc: From->getMemberLocation());
10042 if (!MemberLocOrErr)
10043 return MemberLocOrErr.takeError();
10044
10045 return new (ToContext) CXXCtorInitializer(
10046 ToContext, cast_or_null<FieldDecl>(Val: *ToFieldOrErr), *MemberLocOrErr,
10047 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10048 } else if (From->isIndirectMemberInitializer()) {
10049 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
10050 if (!ToIFieldOrErr)
10051 return ToIFieldOrErr.takeError();
10052
10053 auto MemberLocOrErr = Import(FromLoc: From->getMemberLocation());
10054 if (!MemberLocOrErr)
10055 return MemberLocOrErr.takeError();
10056
10057 return new (ToContext) CXXCtorInitializer(
10058 ToContext, cast_or_null<IndirectFieldDecl>(Val: *ToIFieldOrErr),
10059 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10060 } else if (From->isDelegatingInitializer()) {
10061 auto ToTInfoOrErr = Import(FromTSI: From->getTypeSourceInfo());
10062 if (!ToTInfoOrErr)
10063 return ToTInfoOrErr.takeError();
10064
10065 return new (ToContext)
10066 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
10067 *ToExprOrErr, *RParenLocOrErr);
10068 } else {
10069 // FIXME: assert?
10070 return make_error<ASTImportError>();
10071 }
10072}
10073
10074Expected<CXXBaseSpecifier *>
10075ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
10076 auto Pos = ImportedCXXBaseSpecifiers.find(Val: BaseSpec);
10077 if (Pos != ImportedCXXBaseSpecifiers.end())
10078 return Pos->second;
10079
10080 Expected<SourceRange> ToSourceRange = Import(FromRange: BaseSpec->getSourceRange());
10081 if (!ToSourceRange)
10082 return ToSourceRange.takeError();
10083 Expected<TypeSourceInfo *> ToTSI = Import(FromTSI: BaseSpec->getTypeSourceInfo());
10084 if (!ToTSI)
10085 return ToTSI.takeError();
10086 ExpectedSLoc ToEllipsisLoc = Import(FromLoc: BaseSpec->getEllipsisLoc());
10087 if (!ToEllipsisLoc)
10088 return ToEllipsisLoc.takeError();
10089 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
10090 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
10091 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
10092 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
10093 return Imported;
10094}
10095
10096llvm::Expected<APValue> ASTImporter::Import(const APValue &FromValue) {
10097 ASTNodeImporter Importer(*this);
10098 return Importer.ImportAPValue(FromValue);
10099}
10100
10101Error ASTImporter::ImportDefinition(Decl *From) {
10102 ExpectedDecl ToOrErr = Import(FromD: From);
10103 if (!ToOrErr)
10104 return ToOrErr.takeError();
10105 Decl *To = *ToOrErr;
10106
10107 auto *FromDC = cast<DeclContext>(Val: From);
10108 ASTNodeImporter Importer(*this);
10109
10110 if (auto *ToRecord = dyn_cast<RecordDecl>(Val: To)) {
10111 if (!ToRecord->getDefinition()) {
10112 return Importer.ImportDefinition(
10113 From: cast<RecordDecl>(Val: FromDC), To: ToRecord,
10114 Kind: ASTNodeImporter::IDK_Everything);
10115 }
10116 }
10117
10118 if (auto *ToEnum = dyn_cast<EnumDecl>(Val: To)) {
10119 if (!ToEnum->getDefinition()) {
10120 return Importer.ImportDefinition(
10121 From: cast<EnumDecl>(Val: FromDC), To: ToEnum, Kind: ASTNodeImporter::IDK_Everything);
10122 }
10123 }
10124
10125 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(Val: To)) {
10126 if (!ToIFace->getDefinition()) {
10127 return Importer.ImportDefinition(
10128 From: cast<ObjCInterfaceDecl>(Val: FromDC), To: ToIFace,
10129 Kind: ASTNodeImporter::IDK_Everything);
10130 }
10131 }
10132
10133 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(Val: To)) {
10134 if (!ToProto->getDefinition()) {
10135 return Importer.ImportDefinition(
10136 From: cast<ObjCProtocolDecl>(Val: FromDC), To: ToProto,
10137 Kind: ASTNodeImporter::IDK_Everything);
10138 }
10139 }
10140
10141 return Importer.ImportDeclContext(FromDC, ForceImport: true);
10142}
10143
10144Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) {
10145 if (!FromName)
10146 return DeclarationName{};
10147
10148 switch (FromName.getNameKind()) {
10149 case DeclarationName::Identifier:
10150 return DeclarationName(Import(FromId: FromName.getAsIdentifierInfo()));
10151
10152 case DeclarationName::ObjCZeroArgSelector:
10153 case DeclarationName::ObjCOneArgSelector:
10154 case DeclarationName::ObjCMultiArgSelector:
10155 if (auto ToSelOrErr = Import(FromSel: FromName.getObjCSelector()))
10156 return DeclarationName(*ToSelOrErr);
10157 else
10158 return ToSelOrErr.takeError();
10159
10160 case DeclarationName::CXXConstructorName: {
10161 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10162 return ToContext.DeclarationNames.getCXXConstructorName(
10163 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10164 else
10165 return ToTyOrErr.takeError();
10166 }
10167
10168 case DeclarationName::CXXDestructorName: {
10169 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10170 return ToContext.DeclarationNames.getCXXDestructorName(
10171 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10172 else
10173 return ToTyOrErr.takeError();
10174 }
10175
10176 case DeclarationName::CXXDeductionGuideName: {
10177 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
10178 return ToContext.DeclarationNames.getCXXDeductionGuideName(
10179 TD: cast<TemplateDecl>(*ToTemplateOrErr));
10180 else
10181 return ToTemplateOrErr.takeError();
10182 }
10183
10184 case DeclarationName::CXXConversionFunctionName: {
10185 if (auto ToTyOrErr = Import(FromT: FromName.getCXXNameType()))
10186 return ToContext.DeclarationNames.getCXXConversionFunctionName(
10187 Ty: ToContext.getCanonicalType(T: *ToTyOrErr));
10188 else
10189 return ToTyOrErr.takeError();
10190 }
10191
10192 case DeclarationName::CXXOperatorName:
10193 return ToContext.DeclarationNames.getCXXOperatorName(
10194 Op: FromName.getCXXOverloadedOperator());
10195
10196 case DeclarationName::CXXLiteralOperatorName:
10197 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
10198 II: Import(FromId: FromName.getCXXLiteralIdentifier()));
10199
10200 case DeclarationName::CXXUsingDirective:
10201 // FIXME: STATICS!
10202 return DeclarationName::getUsingDirectiveName();
10203 }
10204
10205 llvm_unreachable("Invalid DeclarationName Kind!");
10206}
10207
10208IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
10209 if (!FromId)
10210 return nullptr;
10211
10212 IdentifierInfo *ToId = &ToContext.Idents.get(Name: FromId->getName());
10213
10214 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
10215 ToId->setBuiltinID(FromId->getBuiltinID());
10216
10217 return ToId;
10218}
10219
10220Expected<Selector> ASTImporter::Import(Selector FromSel) {
10221 if (FromSel.isNull())
10222 return Selector{};
10223
10224 SmallVector<const IdentifierInfo *, 4> Idents;
10225 Idents.push_back(Elt: Import(FromId: FromSel.getIdentifierInfoForSlot(argIndex: 0)));
10226 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
10227 Idents.push_back(Elt: Import(FromId: FromSel.getIdentifierInfoForSlot(argIndex: I)));
10228 return ToContext.Selectors.getSelector(NumArgs: FromSel.getNumArgs(), IIV: Idents.data());
10229}
10230
10231llvm::Expected<APValue>
10232ASTNodeImporter::ImportAPValue(const APValue &FromValue) {
10233 APValue Result;
10234 llvm::Error Err = llvm::Error::success();
10235 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
10236 for (unsigned Idx = 0; Idx < Size; Idx++) {
10237 APValue Tmp = importChecked(Err, From: From[Idx]);
10238 To[Idx] = Tmp;
10239 }
10240 };
10241 switch (FromValue.getKind()) {
10242 case APValue::None:
10243 case APValue::Indeterminate:
10244 case APValue::Int:
10245 case APValue::Float:
10246 case APValue::FixedPoint:
10247 case APValue::ComplexInt:
10248 case APValue::ComplexFloat:
10249 Result = FromValue;
10250 break;
10251 case APValue::Vector: {
10252 Result.MakeVector();
10253 MutableArrayRef<APValue> Elts =
10254 Result.setVectorUninit(FromValue.getVectorLength());
10255 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
10256 Elts.data(), FromValue.getVectorLength());
10257 break;
10258 }
10259 case APValue::Array:
10260 Result.MakeArray(InitElts: FromValue.getArrayInitializedElts(),
10261 Size: FromValue.getArraySize());
10262 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
10263 ((const APValue::Arr *)(const char *)&Result.Data)->Elts,
10264 FromValue.getArrayInitializedElts());
10265 break;
10266 case APValue::Struct:
10267 Result.MakeStruct(B: FromValue.getStructNumBases(),
10268 M: FromValue.getStructNumFields());
10269 ImportLoop(
10270 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
10271 ((const APValue::StructData *)(const char *)&Result.Data)->Elts,
10272 FromValue.getStructNumBases() + FromValue.getStructNumFields());
10273 break;
10274 case APValue::Union: {
10275 Result.MakeUnion();
10276 const Decl *ImpFDecl = importChecked(Err, From: FromValue.getUnionField());
10277 APValue ImpValue = importChecked(Err, From: FromValue.getUnionValue());
10278 if (Err)
10279 return std::move(Err);
10280 Result.setUnion(Field: cast<FieldDecl>(Val: ImpFDecl), Value: ImpValue);
10281 break;
10282 }
10283 case APValue::AddrLabelDiff: {
10284 Result.MakeAddrLabelDiff();
10285 const Expr *ImpLHS = importChecked(Err, From: FromValue.getAddrLabelDiffLHS());
10286 const Expr *ImpRHS = importChecked(Err, From: FromValue.getAddrLabelDiffRHS());
10287 if (Err)
10288 return std::move(Err);
10289 Result.setAddrLabelDiff(LHSExpr: cast<AddrLabelExpr>(Val: ImpLHS),
10290 RHSExpr: cast<AddrLabelExpr>(Val: ImpRHS));
10291 break;
10292 }
10293 case APValue::MemberPointer: {
10294 const Decl *ImpMemPtrDecl =
10295 importChecked(Err, From: FromValue.getMemberPointerDecl());
10296 if (Err)
10297 return std::move(Err);
10298 MutableArrayRef<const CXXRecordDecl *> ToPath =
10299 Result.setMemberPointerUninit(
10300 Member: cast<const ValueDecl>(Val: ImpMemPtrDecl),
10301 IsDerivedMember: FromValue.isMemberPointerToDerivedMember(),
10302 Size: FromValue.getMemberPointerPath().size());
10303 llvm::ArrayRef<const CXXRecordDecl *> FromPath =
10304 Result.getMemberPointerPath();
10305 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
10306 Idx++) {
10307 const Decl *ImpDecl = importChecked(Err, From: FromPath[Idx]);
10308 if (Err)
10309 return std::move(Err);
10310 ToPath[Idx] = cast<const CXXRecordDecl>(Val: ImpDecl->getCanonicalDecl());
10311 }
10312 break;
10313 }
10314 case APValue::LValue:
10315 APValue::LValueBase Base;
10316 QualType FromElemTy;
10317 if (FromValue.getLValueBase()) {
10318 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
10319 "in C++20 dynamic allocation are transient so they shouldn't "
10320 "appear in the AST");
10321 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
10322 if (const auto *E =
10323 FromValue.getLValueBase().dyn_cast<const Expr *>()) {
10324 FromElemTy = E->getType();
10325 const Expr *ImpExpr = importChecked(Err, From: E);
10326 if (Err)
10327 return std::move(Err);
10328 Base = APValue::LValueBase(ImpExpr,
10329 FromValue.getLValueBase().getCallIndex(),
10330 FromValue.getLValueBase().getVersion());
10331 } else {
10332 FromElemTy =
10333 FromValue.getLValueBase().get<const ValueDecl *>()->getType();
10334 const Decl *ImpDecl = importChecked(
10335 Err, From: FromValue.getLValueBase().get<const ValueDecl *>());
10336 if (Err)
10337 return std::move(Err);
10338 Base = APValue::LValueBase(cast<ValueDecl>(Val: ImpDecl),
10339 FromValue.getLValueBase().getCallIndex(),
10340 FromValue.getLValueBase().getVersion());
10341 }
10342 } else {
10343 FromElemTy = FromValue.getLValueBase().getTypeInfoType();
10344 const Type *ImpTypeInfo = importChecked(
10345 Err, From: FromValue.getLValueBase().get<TypeInfoLValue>().getType());
10346 QualType ImpType =
10347 importChecked(Err, From: FromValue.getLValueBase().getTypeInfoType());
10348 if (Err)
10349 return std::move(Err);
10350 Base = APValue::LValueBase::getTypeInfo(LV: TypeInfoLValue(ImpTypeInfo),
10351 TypeInfo: ImpType);
10352 }
10353 }
10354 CharUnits Offset = FromValue.getLValueOffset();
10355 unsigned PathLength = FromValue.getLValuePath().size();
10356 Result.MakeLValue();
10357 if (FromValue.hasLValuePath()) {
10358 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
10359 B: Base, O: Offset, Size: PathLength, OnePastTheEnd: FromValue.isLValueOnePastTheEnd(),
10360 IsNullPtr: FromValue.isNullPointer());
10361 llvm::ArrayRef<APValue::LValuePathEntry> FromPath =
10362 FromValue.getLValuePath();
10363 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
10364 if (FromElemTy->isRecordType()) {
10365 const Decl *FromDecl =
10366 FromPath[LoopIdx].getAsBaseOrMember().getPointer();
10367 const Decl *ImpDecl = importChecked(Err, From: FromDecl);
10368 if (Err)
10369 return std::move(Err);
10370 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: FromDecl))
10371 FromElemTy = Importer.FromContext.getRecordType(RD);
10372 else
10373 FromElemTy = cast<ValueDecl>(Val: FromDecl)->getType();
10374 ToPath[LoopIdx] = APValue::LValuePathEntry(APValue::BaseOrMemberType(
10375 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
10376 } else {
10377 FromElemTy =
10378 Importer.FromContext.getAsArrayType(T: FromElemTy)->getElementType();
10379 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
10380 Index: FromPath[LoopIdx].getAsArrayIndex());
10381 }
10382 }
10383 } else
10384 Result.setLValue(B: Base, O: Offset, APValue::NoLValuePath{},
10385 IsNullPtr: FromValue.isNullPointer());
10386 }
10387 if (Err)
10388 return std::move(Err);
10389 return Result;
10390}
10391
10392Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name,
10393 DeclContext *DC,
10394 unsigned IDNS,
10395 NamedDecl **Decls,
10396 unsigned NumDecls) {
10397 if (ODRHandling == ODRHandlingType::Conservative)
10398 // Report error at any name conflict.
10399 return make_error<ASTImportError>(Args: ASTImportError::NameConflict);
10400 else
10401 // Allow to create the new Decl with the same name.
10402 return Name;
10403}
10404
10405DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
10406 if (LastDiagFromFrom)
10407 ToContext.getDiagnostics().notePriorDiagnosticFrom(
10408 Other: FromContext.getDiagnostics());
10409 LastDiagFromFrom = false;
10410 return ToContext.getDiagnostics().Report(Loc, DiagID);
10411}
10412
10413DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
10414 if (!LastDiagFromFrom)
10415 FromContext.getDiagnostics().notePriorDiagnosticFrom(
10416 Other: ToContext.getDiagnostics());
10417 LastDiagFromFrom = true;
10418 return FromContext.getDiagnostics().Report(Loc, DiagID);
10419}
10420
10421void ASTImporter::CompleteDecl (Decl *D) {
10422 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(Val: D)) {
10423 if (!ID->getDefinition())
10424 ID->startDefinition();
10425 }
10426 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(Val: D)) {
10427 if (!PD->getDefinition())
10428 PD->startDefinition();
10429 }
10430 else if (auto *TD = dyn_cast<TagDecl>(Val: D)) {
10431 if (!TD->getDefinition() && !TD->isBeingDefined()) {
10432 TD->startDefinition();
10433 TD->setCompleteDefinition(true);
10434 }
10435 }
10436 else {
10437 assert(0 && "CompleteDecl called on a Decl that can't be completed");
10438 }
10439}
10440
10441Decl *ASTImporter::MapImported(Decl *From, Decl *To) {
10442 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(Val: From);
10443 assert((Pos == ImportedDecls.end() || Pos->second == To) &&
10444 "Try to import an already imported Decl");
10445 if (Pos != ImportedDecls.end())
10446 return Pos->second;
10447 ImportedDecls[From] = To;
10448 // This mapping should be maintained only in this function. Therefore do not
10449 // check for additional consistency.
10450 ImportedFromDecls[To] = From;
10451 // In the case of TypedefNameDecl we create the Decl first and only then we
10452 // import and set its DeclContext. So, the DC is still not set when we reach
10453 // here from GetImportedOrCreateDecl.
10454 if (To->getDeclContext())
10455 AddToLookupTable(ToD: To);
10456 return To;
10457}
10458
10459std::optional<ASTImportError>
10460ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const {
10461 auto Pos = ImportDeclErrors.find(Val: FromD);
10462 if (Pos != ImportDeclErrors.end())
10463 return Pos->second;
10464 else
10465 return std::nullopt;
10466}
10467
10468void ASTImporter::setImportDeclError(Decl *From, ASTImportError Error) {
10469 auto InsertRes = ImportDeclErrors.insert(KV: {From, Error});
10470 (void)InsertRes;
10471 // Either we set the error for the first time, or we already had set one and
10472 // now we want to set the same error.
10473 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
10474}
10475
10476bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
10477 bool Complain) {
10478 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
10479 ImportedTypes.find(Val: From.getTypePtr());
10480 if (Pos != ImportedTypes.end()) {
10481 if (ExpectedType ToFromOrErr = Import(FromT: From)) {
10482 if (ToContext.hasSameType(T1: *ToFromOrErr, T2: To))
10483 return true;
10484 } else {
10485 llvm::consumeError(Err: ToFromOrErr.takeError());
10486 }
10487 }
10488
10489 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
10490 getStructuralEquivalenceKind(Importer: *this), false,
10491 Complain);
10492 return Ctx.IsEquivalent(T1: From, T2: To);
10493}
10494

source code of clang/lib/AST/ASTImporter.cpp