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