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