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