1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTImporter class which imports AST nodes from one
11 //  context into another context.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTStructuralEquivalence.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "llvm/Support/MemoryBuffer.h"
26 
27 namespace clang {
28   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29                           public DeclVisitor<ASTNodeImporter, Decl *>,
30                           public StmtVisitor<ASTNodeImporter, Stmt *> {
31     ASTImporter &Importer;
32 
33   public:
34     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
35 
36     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
39 
40     // Importing types
41     QualType VisitType(const Type *T);
42     QualType VisitAtomicType(const AtomicType *T);
43     QualType VisitBuiltinType(const BuiltinType *T);
44     QualType VisitDecayedType(const DecayedType *T);
45     QualType VisitComplexType(const ComplexType *T);
46     QualType VisitPointerType(const PointerType *T);
47     QualType VisitBlockPointerType(const BlockPointerType *T);
48     QualType VisitLValueReferenceType(const LValueReferenceType *T);
49     QualType VisitRValueReferenceType(const RValueReferenceType *T);
50     QualType VisitMemberPointerType(const MemberPointerType *T);
51     QualType VisitConstantArrayType(const ConstantArrayType *T);
52     QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
53     QualType VisitVariableArrayType(const VariableArrayType *T);
54     QualType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
55     // FIXME: DependentSizedExtVectorType
56     QualType VisitVectorType(const VectorType *T);
57     QualType VisitExtVectorType(const ExtVectorType *T);
58     QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
59     QualType VisitFunctionProtoType(const FunctionProtoType *T);
60     QualType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
61     QualType VisitParenType(const ParenType *T);
62     QualType VisitTypedefType(const TypedefType *T);
63     QualType VisitTypeOfExprType(const TypeOfExprType *T);
64     // FIXME: DependentTypeOfExprType
65     QualType VisitTypeOfType(const TypeOfType *T);
66     QualType VisitDecltypeType(const DecltypeType *T);
67     QualType VisitUnaryTransformType(const UnaryTransformType *T);
68     QualType VisitAutoType(const AutoType *T);
69     QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
70     // FIXME: DependentDecltypeType
71     QualType VisitRecordType(const RecordType *T);
72     QualType VisitEnumType(const EnumType *T);
73     QualType VisitAttributedType(const AttributedType *T);
74     QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
75     QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T);
76     QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
77     QualType VisitElaboratedType(const ElaboratedType *T);
78     // FIXME: DependentNameType
79     QualType VisitPackExpansionType(const PackExpansionType *T);
80     QualType VisitDependentTemplateSpecializationType(
81         const DependentTemplateSpecializationType *T);
82     QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
83     QualType VisitObjCObjectType(const ObjCObjectType *T);
84     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
85 
86     // Importing declarations
87     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
88                          DeclContext *&LexicalDC, DeclarationName &Name,
89                          NamedDecl *&ToD, SourceLocation &Loc);
90     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
91     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
92                                   DeclarationNameInfo& To);
93     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
94 
95     bool ImportCastPath(CastExpr *E, CXXCastPath &Path);
96 
97     typedef DesignatedInitExpr::Designator Designator;
98     Designator ImportDesignator(const Designator &D);
99 
100     Optional<LambdaCapture> ImportLambdaCapture(const LambdaCapture &From);
101 
102 
103     /// \brief What we should import from the definition.
104     enum ImportDefinitionKind {
105       /// \brief Import the default subset of the definition, which might be
106       /// nothing (if minimal import is set) or might be everything (if minimal
107       /// import is not set).
108       IDK_Default,
109       /// \brief Import everything.
110       IDK_Everything,
111       /// \brief Import only the bare bones needed to establish a valid
112       /// DeclContext.
113       IDK_Basic
114     };
115 
116     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
117       return IDK == IDK_Everything ||
118              (IDK == IDK_Default && !Importer.isMinimalImport());
119     }
120 
121     bool ImportDefinition(RecordDecl *From, RecordDecl *To,
122                           ImportDefinitionKind Kind = IDK_Default);
123     bool ImportDefinition(VarDecl *From, VarDecl *To,
124                           ImportDefinitionKind Kind = IDK_Default);
125     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
126                           ImportDefinitionKind Kind = IDK_Default);
127     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
128                           ImportDefinitionKind Kind = IDK_Default);
129     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
130                           ImportDefinitionKind Kind = IDK_Default);
131     TemplateParameterList *ImportTemplateParameterList(
132         TemplateParameterList *Params);
133     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
134     Optional<TemplateArgumentLoc> ImportTemplateArgumentLoc(
135         const TemplateArgumentLoc &TALoc);
136     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
137                                  unsigned NumFromArgs,
138                                  SmallVectorImpl<TemplateArgument> &ToArgs);
139 
140     template <typename InContainerTy>
141     bool ImportTemplateArgumentListInfo(const InContainerTy &Container,
142                                         TemplateArgumentListInfo &ToTAInfo);
143 
144     template<typename InContainerTy>
145     bool ImportTemplateArgumentListInfo(SourceLocation FromLAngleLoc,
146                                         SourceLocation FromRAngleLoc,
147                                         const InContainerTy &Container,
148                                         TemplateArgumentListInfo &Result);
149 
150     bool ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
151 
152     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
153                            bool Complain = true);
154     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
155                            bool Complain = true);
156     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
157     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
158     bool IsStructuralMatch(FunctionTemplateDecl *From,
159                            FunctionTemplateDecl *To);
160     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
161     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
162     Decl *VisitDecl(Decl *D);
163     Decl *VisitEmptyDecl(EmptyDecl *D);
164     Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
165     Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
166     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
167     Decl *VisitNamespaceDecl(NamespaceDecl *D);
168     Decl *VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
169     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
170     Decl *VisitTypedefDecl(TypedefDecl *D);
171     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
172     Decl *VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
173     Decl *VisitLabelDecl(LabelDecl *D);
174     Decl *VisitEnumDecl(EnumDecl *D);
175     Decl *VisitRecordDecl(RecordDecl *D);
176     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
177     Decl *VisitFunctionDecl(FunctionDecl *D);
178     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
179     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
180     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
181     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
182     Decl *VisitFieldDecl(FieldDecl *D);
183     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
184     Decl *VisitFriendDecl(FriendDecl *D);
185     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
186     Decl *VisitVarDecl(VarDecl *D);
187     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
188     Decl *VisitParmVarDecl(ParmVarDecl *D);
189     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
190     Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
191     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
192     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
193     Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
194     Decl *VisitUsingDecl(UsingDecl *D);
195     Decl *VisitUsingShadowDecl(UsingShadowDecl *D);
196     Decl *VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
197     Decl *VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
198     Decl *VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
199 
200 
201     ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
202     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
203     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
204     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
205     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
206     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
207     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
208     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
209     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
210     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
211     Decl *VisitClassTemplateSpecializationDecl(
212                                             ClassTemplateSpecializationDecl *D);
213     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
214     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
215     Decl *VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
216 
217     // Importing statements
218     DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
219 
220     Stmt *VisitStmt(Stmt *S);
221     Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
222     Stmt *VisitDeclStmt(DeclStmt *S);
223     Stmt *VisitNullStmt(NullStmt *S);
224     Stmt *VisitCompoundStmt(CompoundStmt *S);
225     Stmt *VisitCaseStmt(CaseStmt *S);
226     Stmt *VisitDefaultStmt(DefaultStmt *S);
227     Stmt *VisitLabelStmt(LabelStmt *S);
228     Stmt *VisitAttributedStmt(AttributedStmt *S);
229     Stmt *VisitIfStmt(IfStmt *S);
230     Stmt *VisitSwitchStmt(SwitchStmt *S);
231     Stmt *VisitWhileStmt(WhileStmt *S);
232     Stmt *VisitDoStmt(DoStmt *S);
233     Stmt *VisitForStmt(ForStmt *S);
234     Stmt *VisitGotoStmt(GotoStmt *S);
235     Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
236     Stmt *VisitContinueStmt(ContinueStmt *S);
237     Stmt *VisitBreakStmt(BreakStmt *S);
238     Stmt *VisitReturnStmt(ReturnStmt *S);
239     // FIXME: MSAsmStmt
240     // FIXME: SEHExceptStmt
241     // FIXME: SEHFinallyStmt
242     // FIXME: SEHTryStmt
243     // FIXME: SEHLeaveStmt
244     // FIXME: CapturedStmt
245     Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
246     Stmt *VisitCXXTryStmt(CXXTryStmt *S);
247     Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
248     // FIXME: MSDependentExistsStmt
249     Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
250     Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
251     Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
252     Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
253     Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
254     Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
255     Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
256 
257     // Importing expressions
258     Expr *VisitExpr(Expr *E);
259     Expr *VisitVAArgExpr(VAArgExpr *E);
260     Expr *VisitGNUNullExpr(GNUNullExpr *E);
261     Expr *VisitPredefinedExpr(PredefinedExpr *E);
262     Expr *VisitDeclRefExpr(DeclRefExpr *E);
263     Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
264     Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
265     Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
266     Expr *VisitIntegerLiteral(IntegerLiteral *E);
267     Expr *VisitFloatingLiteral(FloatingLiteral *E);
268     Expr *VisitCharacterLiteral(CharacterLiteral *E);
269     Expr *VisitStringLiteral(StringLiteral *E);
270     Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
271     Expr *VisitAtomicExpr(AtomicExpr *E);
272     Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
273     Expr *VisitParenExpr(ParenExpr *E);
274     Expr *VisitParenListExpr(ParenListExpr *E);
275     Expr *VisitStmtExpr(StmtExpr *E);
276     Expr *VisitUnaryOperator(UnaryOperator *E);
277     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
278     Expr *VisitBinaryOperator(BinaryOperator *E);
279     Expr *VisitConditionalOperator(ConditionalOperator *E);
280     Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
281     Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
282     Expr *VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
283     Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E);
284     Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
285     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
286     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
287     Expr *VisitExplicitCastExpr(ExplicitCastExpr *E);
288     Expr *VisitOffsetOfExpr(OffsetOfExpr *OE);
289     Expr *VisitCXXThrowExpr(CXXThrowExpr *E);
290     Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
291     Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
292     Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
293     Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
294     Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
295     Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
296     Expr *VisitPackExpansionExpr(PackExpansionExpr *E);
297     Expr *VisitSizeOfPackExpr(SizeOfPackExpr *E);
298     Expr *VisitCXXNewExpr(CXXNewExpr *CE);
299     Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
300     Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
301     Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
302     Expr *VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
303     Expr *VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *CE);
304     Expr *VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
305     Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
306     Expr *VisitCXXThisExpr(CXXThisExpr *E);
307     Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
308     Expr *VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
309     Expr *VisitMemberExpr(MemberExpr *E);
310     Expr *VisitCallExpr(CallExpr *E);
311     Expr *VisitLambdaExpr(LambdaExpr *LE);
312     Expr *VisitInitListExpr(InitListExpr *E);
313     Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
314     Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
315     Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
316     Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
317     Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
318     Expr *VisitTypeTraitExpr(TypeTraitExpr *E);
319     Expr *VisitCXXTypeidExpr(CXXTypeidExpr *E);
320 
321 
322     template<typename IIter, typename OIter>
323     void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
324       typedef typename std::remove_reference<decltype(*Obegin)>::type ItemT;
325       ASTImporter &ImporterRef = Importer;
326       std::transform(Ibegin, Iend, Obegin,
327                      [&ImporterRef](ItemT From) -> ItemT {
328                        return ImporterRef.Import(From);
329                      });
330     }
331 
332     template<typename IIter, typename OIter>
333     bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
334       typedef typename std::remove_reference<decltype(**Obegin)>::type ItemT;
335       ASTImporter &ImporterRef = Importer;
336       bool Failed = false;
337       std::transform(Ibegin, Iend, Obegin,
338                      [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
339                        ItemT *To = cast_or_null<ItemT>(
340                              ImporterRef.Import(From));
341                        if (!To && From)
342                          Failed = true;
343                        return To;
344                      });
345       return Failed;
346     }
347 
348     template<typename InContainerTy, typename OutContainerTy>
349     bool ImportContainerChecked(const InContainerTy &InContainer,
350                                 OutContainerTy &OutContainer) {
351       return ImportArrayChecked(InContainer.begin(), InContainer.end(),
352                                 OutContainer.begin());
353     }
354 
355     template<typename InContainerTy, typename OIter>
356     bool ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
357       return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
358     }
359 
360     // Importing overrides.
361     void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
362   };
363 
364 
365 template <typename InContainerTy>
366 bool ASTNodeImporter::ImportTemplateArgumentListInfo(
367     SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
368     const InContainerTy &Container, TemplateArgumentListInfo &Result) {
369   TemplateArgumentListInfo ToTAInfo(Importer.Import(FromLAngleLoc),
370                                     Importer.Import(FromRAngleLoc));
371   if (ImportTemplateArgumentListInfo(Container, ToTAInfo))
372     return true;
373   Result = ToTAInfo;
374   return false;
375 }
376 
377 template <>
378 bool ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
379     const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
380   return ImportTemplateArgumentListInfo(
381       From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
382 }
383 
384 template <>
385 bool ASTNodeImporter::ImportTemplateArgumentListInfo<
386     ASTTemplateArgumentListInfo>(const ASTTemplateArgumentListInfo &From,
387                                  TemplateArgumentListInfo &Result) {
388   return ImportTemplateArgumentListInfo(From.LAngleLoc, From.RAngleLoc,
389                                         From.arguments(), Result);
390 }
391 
392 } // end namespace clang
393 
394 //----------------------------------------------------------------------------
395 // Import Types
396 //----------------------------------------------------------------------------
397 
398 using namespace clang;
399 
400 QualType ASTNodeImporter::VisitType(const Type *T) {
401   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
402     << T->getTypeClassName();
403   return QualType();
404 }
405 
406 QualType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
407   QualType UnderlyingType = Importer.Import(T->getValueType());
408   if(UnderlyingType.isNull())
409     return QualType();
410 
411   return Importer.getToContext().getAtomicType(UnderlyingType);
412 }
413 
414 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
415   switch (T->getKind()) {
416 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
417   case BuiltinType::Id: \
418     return Importer.getToContext().SingletonId;
419 #include "clang/Basic/OpenCLImageTypes.def"
420 #define SHARED_SINGLETON_TYPE(Expansion)
421 #define BUILTIN_TYPE(Id, SingletonId) \
422   case BuiltinType::Id: return Importer.getToContext().SingletonId;
423 #include "clang/AST/BuiltinTypes.def"
424 
425   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
426   // context supports C++.
427 
428   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
429   // context supports ObjC.
430 
431   case BuiltinType::Char_U:
432     // The context we're importing from has an unsigned 'char'. If we're
433     // importing into a context with a signed 'char', translate to
434     // 'unsigned char' instead.
435     if (Importer.getToContext().getLangOpts().CharIsSigned)
436       return Importer.getToContext().UnsignedCharTy;
437 
438     return Importer.getToContext().CharTy;
439 
440   case BuiltinType::Char_S:
441     // The context we're importing from has an unsigned 'char'. If we're
442     // importing into a context with a signed 'char', translate to
443     // 'unsigned char' instead.
444     if (!Importer.getToContext().getLangOpts().CharIsSigned)
445       return Importer.getToContext().SignedCharTy;
446 
447     return Importer.getToContext().CharTy;
448 
449   case BuiltinType::WChar_S:
450   case BuiltinType::WChar_U:
451     // FIXME: If not in C++, shall we translate to the C equivalent of
452     // wchar_t?
453     return Importer.getToContext().WCharTy;
454   }
455 
456   llvm_unreachable("Invalid BuiltinType Kind!");
457 }
458 
459 QualType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
460   QualType OrigT = Importer.Import(T->getOriginalType());
461   if (OrigT.isNull())
462     return QualType();
463 
464   return Importer.getToContext().getDecayedType(OrigT);
465 }
466 
467 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
468   QualType ToElementType = Importer.Import(T->getElementType());
469   if (ToElementType.isNull())
470     return QualType();
471 
472   return Importer.getToContext().getComplexType(ToElementType);
473 }
474 
475 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
476   QualType ToPointeeType = Importer.Import(T->getPointeeType());
477   if (ToPointeeType.isNull())
478     return QualType();
479 
480   return Importer.getToContext().getPointerType(ToPointeeType);
481 }
482 
483 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
484   // FIXME: Check for blocks support in "to" context.
485   QualType ToPointeeType = Importer.Import(T->getPointeeType());
486   if (ToPointeeType.isNull())
487     return QualType();
488 
489   return Importer.getToContext().getBlockPointerType(ToPointeeType);
490 }
491 
492 QualType
493 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
494   // FIXME: Check for C++ support in "to" context.
495   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
496   if (ToPointeeType.isNull())
497     return QualType();
498 
499   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
500 }
501 
502 QualType
503 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
504   // FIXME: Check for C++0x support in "to" context.
505   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
506   if (ToPointeeType.isNull())
507     return QualType();
508 
509   return Importer.getToContext().getRValueReferenceType(ToPointeeType);
510 }
511 
512 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
513   // FIXME: Check for C++ support in "to" context.
514   QualType ToPointeeType = Importer.Import(T->getPointeeType());
515   if (ToPointeeType.isNull())
516     return QualType();
517 
518   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
519   return Importer.getToContext().getMemberPointerType(ToPointeeType,
520                                                       ClassType.getTypePtr());
521 }
522 
523 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
524   QualType ToElementType = Importer.Import(T->getElementType());
525   if (ToElementType.isNull())
526     return QualType();
527 
528   return Importer.getToContext().getConstantArrayType(ToElementType,
529                                                       T->getSize(),
530                                                       T->getSizeModifier(),
531                                                T->getIndexTypeCVRQualifiers());
532 }
533 
534 QualType
535 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
536   QualType ToElementType = Importer.Import(T->getElementType());
537   if (ToElementType.isNull())
538     return QualType();
539 
540   return Importer.getToContext().getIncompleteArrayType(ToElementType,
541                                                         T->getSizeModifier(),
542                                                 T->getIndexTypeCVRQualifiers());
543 }
544 
545 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
546   QualType ToElementType = Importer.Import(T->getElementType());
547   if (ToElementType.isNull())
548     return QualType();
549 
550   Expr *Size = Importer.Import(T->getSizeExpr());
551   if (!Size)
552     return QualType();
553 
554   SourceRange Brackets = Importer.Import(T->getBracketsRange());
555   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
556                                                       T->getSizeModifier(),
557                                                 T->getIndexTypeCVRQualifiers(),
558                                                       Brackets);
559 }
560 
561 QualType ASTNodeImporter::VisitDependentSizedArrayType(
562     const DependentSizedArrayType *T) {
563   QualType ToElementType = Importer.Import(T->getElementType());
564   if (ToElementType.isNull())
565     return QualType();
566 
567   // SizeExpr may be null if size is not specified directly.
568   // For example, 'int a[]'.
569   Expr *Size = Importer.Import(T->getSizeExpr());
570   if (!Size && T->getSizeExpr())
571     return QualType();
572 
573   SourceRange Brackets = Importer.Import(T->getBracketsRange());
574   return Importer.getToContext().getDependentSizedArrayType(
575       ToElementType, Size, T->getSizeModifier(), T->getIndexTypeCVRQualifiers(),
576       Brackets);
577 }
578 
579 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
580   QualType ToElementType = Importer.Import(T->getElementType());
581   if (ToElementType.isNull())
582     return QualType();
583 
584   return Importer.getToContext().getVectorType(ToElementType,
585                                                T->getNumElements(),
586                                                T->getVectorKind());
587 }
588 
589 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
590   QualType ToElementType = Importer.Import(T->getElementType());
591   if (ToElementType.isNull())
592     return QualType();
593 
594   return Importer.getToContext().getExtVectorType(ToElementType,
595                                                   T->getNumElements());
596 }
597 
598 QualType
599 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
600   // FIXME: What happens if we're importing a function without a prototype
601   // into C++? Should we make it variadic?
602   QualType ToResultType = Importer.Import(T->getReturnType());
603   if (ToResultType.isNull())
604     return QualType();
605 
606   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
607                                                         T->getExtInfo());
608 }
609 
610 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
611   QualType ToResultType = Importer.Import(T->getReturnType());
612   if (ToResultType.isNull())
613     return QualType();
614 
615   // Import argument types
616   SmallVector<QualType, 4> ArgTypes;
617   for (const auto &A : T->param_types()) {
618     QualType ArgType = Importer.Import(A);
619     if (ArgType.isNull())
620       return QualType();
621     ArgTypes.push_back(ArgType);
622   }
623 
624   // Import exception types
625   SmallVector<QualType, 4> ExceptionTypes;
626   for (const auto &E : T->exceptions()) {
627     QualType ExceptionType = Importer.Import(E);
628     if (ExceptionType.isNull())
629       return QualType();
630     ExceptionTypes.push_back(ExceptionType);
631   }
632 
633   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
634   FunctionProtoType::ExtProtoInfo ToEPI;
635 
636   ToEPI.ExtInfo = FromEPI.ExtInfo;
637   ToEPI.Variadic = FromEPI.Variadic;
638   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
639   ToEPI.TypeQuals = FromEPI.TypeQuals;
640   ToEPI.RefQualifier = FromEPI.RefQualifier;
641   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
642   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
643   ToEPI.ExceptionSpec.NoexceptExpr =
644       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
645   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
646       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
647   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
648       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
649 
650   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
651 }
652 
653 QualType ASTNodeImporter::VisitUnresolvedUsingType(
654     const UnresolvedUsingType *T) {
655   UnresolvedUsingTypenameDecl *ToD = cast_or_null<UnresolvedUsingTypenameDecl>(
656         Importer.Import(T->getDecl()));
657   if (!ToD)
658     return QualType();
659 
660   UnresolvedUsingTypenameDecl *ToPrevD =
661       cast_or_null<UnresolvedUsingTypenameDecl>(
662         Importer.Import(T->getDecl()->getPreviousDecl()));
663   if (!ToPrevD && T->getDecl()->getPreviousDecl())
664     return QualType();
665 
666   return Importer.getToContext().getTypeDeclType(ToD, ToPrevD);
667 }
668 
669 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
670   QualType ToInnerType = Importer.Import(T->getInnerType());
671   if (ToInnerType.isNull())
672     return QualType();
673 
674   return Importer.getToContext().getParenType(ToInnerType);
675 }
676 
677 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
678   TypedefNameDecl *ToDecl
679              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
680   if (!ToDecl)
681     return QualType();
682 
683   return Importer.getToContext().getTypeDeclType(ToDecl);
684 }
685 
686 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
687   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
688   if (!ToExpr)
689     return QualType();
690 
691   return Importer.getToContext().getTypeOfExprType(ToExpr);
692 }
693 
694 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
695   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
696   if (ToUnderlyingType.isNull())
697     return QualType();
698 
699   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
700 }
701 
702 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
703   // FIXME: Make sure that the "to" context supports C++0x!
704   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
705   if (!ToExpr)
706     return QualType();
707 
708   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
709   if (UnderlyingType.isNull())
710     return QualType();
711 
712   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
713 }
714 
715 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
716   QualType ToBaseType = Importer.Import(T->getBaseType());
717   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
718   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
719     return QualType();
720 
721   return Importer.getToContext().getUnaryTransformType(ToBaseType,
722                                                        ToUnderlyingType,
723                                                        T->getUTTKind());
724 }
725 
726 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
727   // FIXME: Make sure that the "to" context supports C++11!
728   QualType FromDeduced = T->getDeducedType();
729   QualType ToDeduced;
730   if (!FromDeduced.isNull()) {
731     ToDeduced = Importer.Import(FromDeduced);
732     if (ToDeduced.isNull())
733       return QualType();
734   }
735 
736   return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
737                                              /*IsDependent*/false);
738 }
739 
740 QualType ASTNodeImporter::VisitInjectedClassNameType(
741     const InjectedClassNameType *T) {
742   CXXRecordDecl *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
743   if (!D)
744     return QualType();
745 
746   QualType InjType = Importer.Import(T->getInjectedSpecializationType());
747   if (InjType.isNull())
748     return QualType();
749 
750   // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
751   // See comments in InjectedClassNameType definition for details
752   // return Importer.getToContext().getInjectedClassNameType(D, InjType);
753   enum {
754     TypeAlignmentInBits = 4,
755     TypeAlignment = 1 << TypeAlignmentInBits
756   };
757 
758   return QualType(new (Importer.getToContext(), TypeAlignment)
759                   InjectedClassNameType(D, InjType), 0);
760 }
761 
762 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
763   RecordDecl *ToDecl
764     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
765   if (!ToDecl)
766     return QualType();
767 
768   return Importer.getToContext().getTagDeclType(ToDecl);
769 }
770 
771 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
772   EnumDecl *ToDecl
773     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
774   if (!ToDecl)
775     return QualType();
776 
777   return Importer.getToContext().getTagDeclType(ToDecl);
778 }
779 
780 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
781   QualType FromModifiedType = T->getModifiedType();
782   QualType FromEquivalentType = T->getEquivalentType();
783   QualType ToModifiedType;
784   QualType ToEquivalentType;
785 
786   if (!FromModifiedType.isNull()) {
787     ToModifiedType = Importer.Import(FromModifiedType);
788     if (ToModifiedType.isNull())
789       return QualType();
790   }
791   if (!FromEquivalentType.isNull()) {
792     ToEquivalentType = Importer.Import(FromEquivalentType);
793     if (ToEquivalentType.isNull())
794       return QualType();
795   }
796 
797   return Importer.getToContext().getAttributedType(T->getAttrKind(),
798     ToModifiedType, ToEquivalentType);
799 }
800 
801 
802 QualType ASTNodeImporter::VisitTemplateTypeParmType(
803     const TemplateTypeParmType *T) {
804   TemplateTypeParmDecl *ParmDecl =
805       cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
806   if (!ParmDecl && T->getDecl())
807     return QualType();
808 
809   return Importer.getToContext().getTemplateTypeParmType(
810         T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
811 }
812 
813 QualType ASTNodeImporter::VisitSubstTemplateTypeParmType(
814     const SubstTemplateTypeParmType *T) {
815   const TemplateTypeParmType *Replaced =
816       cast_or_null<TemplateTypeParmType>(Importer.Import(
817         QualType(T->getReplacedParameter(), 0)).getTypePtr());
818   if (!Replaced)
819     return QualType();
820 
821   QualType Replacement = Importer.Import(T->getReplacementType());
822   if (Replacement.isNull())
823     return QualType();
824   Replacement = Replacement.getCanonicalType();
825 
826   return Importer.getToContext().getSubstTemplateTypeParmType(
827         Replaced, Replacement);
828 }
829 
830 QualType ASTNodeImporter::VisitTemplateSpecializationType(
831                                        const TemplateSpecializationType *T) {
832   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
833   if (ToTemplate.isNull())
834     return QualType();
835 
836   SmallVector<TemplateArgument, 2> ToTemplateArgs;
837   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
838     return QualType();
839 
840   QualType ToCanonType;
841   if (!QualType(T, 0).isCanonical()) {
842     QualType FromCanonType
843       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
844     ToCanonType =Importer.Import(FromCanonType);
845     if (ToCanonType.isNull())
846       return QualType();
847   }
848   return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
849                                                                ToTemplateArgs,
850                                                                ToCanonType);
851 }
852 
853 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
854   NestedNameSpecifier *ToQualifier = nullptr;
855   // Note: the qualifier in an ElaboratedType is optional.
856   if (T->getQualifier()) {
857     ToQualifier = Importer.Import(T->getQualifier());
858     if (!ToQualifier)
859       return QualType();
860   }
861 
862   QualType ToNamedType = Importer.Import(T->getNamedType());
863   if (ToNamedType.isNull())
864     return QualType();
865 
866   return Importer.getToContext().getElaboratedType(T->getKeyword(),
867                                                    ToQualifier, ToNamedType);
868 }
869 
870 QualType ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
871   QualType Pattern = Importer.Import(T->getPattern());
872   if (Pattern.isNull())
873     return QualType();
874 
875   return Importer.getToContext().getPackExpansionType(Pattern,
876                                                       T->getNumExpansions());
877 }
878 
879 QualType ASTNodeImporter::VisitDependentTemplateSpecializationType(
880     const DependentTemplateSpecializationType *T) {
881   NestedNameSpecifier *Qualifier = Importer.Import(T->getQualifier());
882   if (!Qualifier && T->getQualifier())
883     return QualType();
884 
885   IdentifierInfo *Name = Importer.Import(T->getIdentifier());
886   if (!Name && T->getIdentifier())
887     return QualType();
888 
889   SmallVector<TemplateArgument, 2> ToPack;
890   ToPack.reserve(T->getNumArgs());
891   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToPack))
892     return QualType();
893 
894   return Importer.getToContext().getDependentTemplateSpecializationType(
895         T->getKeyword(), Qualifier, Name, ToPack);
896 }
897 
898 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
899   ObjCInterfaceDecl *Class
900     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
901   if (!Class)
902     return QualType();
903 
904   return Importer.getToContext().getObjCInterfaceType(Class);
905 }
906 
907 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
908   QualType ToBaseType = Importer.Import(T->getBaseType());
909   if (ToBaseType.isNull())
910     return QualType();
911 
912   SmallVector<QualType, 4> TypeArgs;
913   for (auto TypeArg : T->getTypeArgsAsWritten()) {
914     QualType ImportedTypeArg = Importer.Import(TypeArg);
915     if (ImportedTypeArg.isNull())
916       return QualType();
917 
918     TypeArgs.push_back(ImportedTypeArg);
919   }
920 
921   SmallVector<ObjCProtocolDecl *, 4> Protocols;
922   for (auto *P : T->quals()) {
923     ObjCProtocolDecl *Protocol
924       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
925     if (!Protocol)
926       return QualType();
927     Protocols.push_back(Protocol);
928   }
929 
930   return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
931                                                    Protocols,
932                                                    T->isKindOfTypeAsWritten());
933 }
934 
935 QualType
936 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
937   QualType ToPointeeType = Importer.Import(T->getPointeeType());
938   if (ToPointeeType.isNull())
939     return QualType();
940 
941   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
942 }
943 
944 //----------------------------------------------------------------------------
945 // Import Declarations
946 //----------------------------------------------------------------------------
947 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
948                                       DeclContext *&LexicalDC,
949                                       DeclarationName &Name,
950                                       NamedDecl *&ToD,
951                                       SourceLocation &Loc) {
952   // Import the context of this declaration.
953   DC = Importer.ImportContext(D->getDeclContext());
954   if (!DC)
955     return true;
956 
957   LexicalDC = DC;
958   if (D->getDeclContext() != D->getLexicalDeclContext()) {
959     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
960     if (!LexicalDC)
961       return true;
962   }
963 
964   // Import the name of this declaration.
965   Name = Importer.Import(D->getDeclName());
966   if (D->getDeclName() && !Name)
967     return true;
968 
969   // Import the location of this declaration.
970   Loc = Importer.Import(D->getLocation());
971   ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
972   return false;
973 }
974 
975 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
976   if (!FromD)
977     return;
978 
979   if (!ToD) {
980     ToD = Importer.Import(FromD);
981     if (!ToD)
982       return;
983   }
984 
985   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
986     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
987       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
988         ImportDefinition(FromRecord, ToRecord);
989       }
990     }
991     return;
992   }
993 
994   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
995     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
996       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
997         ImportDefinition(FromEnum, ToEnum);
998       }
999     }
1000     return;
1001   }
1002 }
1003 
1004 void
1005 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1006                                           DeclarationNameInfo& To) {
1007   // NOTE: To.Name and To.Loc are already imported.
1008   // We only have to import To.LocInfo.
1009   switch (To.getName().getNameKind()) {
1010   case DeclarationName::Identifier:
1011   case DeclarationName::ObjCZeroArgSelector:
1012   case DeclarationName::ObjCOneArgSelector:
1013   case DeclarationName::ObjCMultiArgSelector:
1014   case DeclarationName::CXXUsingDirective:
1015   case DeclarationName::CXXDeductionGuideName:
1016     return;
1017 
1018   case DeclarationName::CXXOperatorName: {
1019     SourceRange Range = From.getCXXOperatorNameRange();
1020     To.setCXXOperatorNameRange(Importer.Import(Range));
1021     return;
1022   }
1023   case DeclarationName::CXXLiteralOperatorName: {
1024     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1025     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1026     return;
1027   }
1028   case DeclarationName::CXXConstructorName:
1029   case DeclarationName::CXXDestructorName:
1030   case DeclarationName::CXXConversionFunctionName: {
1031     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1032     To.setNamedTypeInfo(Importer.Import(FromTInfo));
1033     return;
1034   }
1035   }
1036   llvm_unreachable("Unknown name kind.");
1037 }
1038 
1039 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1040   if (Importer.isMinimalImport() && !ForceImport) {
1041     Importer.ImportContext(FromDC);
1042     return;
1043   }
1044 
1045   for (auto *From : FromDC->decls())
1046     Importer.Import(From);
1047 }
1048 
1049 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1050                                        ImportDefinitionKind Kind) {
1051   if (To->getDefinition() || To->isBeingDefined()) {
1052     if (Kind == IDK_Everything)
1053       ImportDeclContext(From, /*ForceImport=*/true);
1054 
1055     return false;
1056   }
1057 
1058   To->startDefinition();
1059 
1060   // Add base classes.
1061   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1062     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1063 
1064     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1065     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1066     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1067     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1068     ToData.Aggregate = FromData.Aggregate;
1069     ToData.PlainOldData = FromData.PlainOldData;
1070     ToData.Empty = FromData.Empty;
1071     ToData.Polymorphic = FromData.Polymorphic;
1072     ToData.Abstract = FromData.Abstract;
1073     ToData.IsStandardLayout = FromData.IsStandardLayout;
1074     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1075     ToData.HasPrivateFields = FromData.HasPrivateFields;
1076     ToData.HasProtectedFields = FromData.HasProtectedFields;
1077     ToData.HasPublicFields = FromData.HasPublicFields;
1078     ToData.HasMutableFields = FromData.HasMutableFields;
1079     ToData.HasVariantMembers = FromData.HasVariantMembers;
1080     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1081     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1082     ToData.HasUninitializedReferenceMember
1083       = FromData.HasUninitializedReferenceMember;
1084     ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1085     ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1086     ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1087     ToData.NeedOverloadResolutionForCopyConstructor
1088       = FromData.NeedOverloadResolutionForCopyConstructor;
1089     ToData.NeedOverloadResolutionForMoveConstructor
1090       = FromData.NeedOverloadResolutionForMoveConstructor;
1091     ToData.NeedOverloadResolutionForMoveAssignment
1092       = FromData.NeedOverloadResolutionForMoveAssignment;
1093     ToData.NeedOverloadResolutionForDestructor
1094       = FromData.NeedOverloadResolutionForDestructor;
1095     ToData.DefaultedCopyConstructorIsDeleted
1096       = FromData.DefaultedCopyConstructorIsDeleted;
1097     ToData.DefaultedMoveConstructorIsDeleted
1098       = FromData.DefaultedMoveConstructorIsDeleted;
1099     ToData.DefaultedMoveAssignmentIsDeleted
1100       = FromData.DefaultedMoveAssignmentIsDeleted;
1101     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1102     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1103     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1104     ToData.HasConstexprNonCopyMoveConstructor
1105       = FromData.HasConstexprNonCopyMoveConstructor;
1106     ToData.HasDefaultedDefaultConstructor
1107       = FromData.HasDefaultedDefaultConstructor;
1108     ToData.DefaultedDefaultConstructorIsConstexpr
1109       = FromData.DefaultedDefaultConstructorIsConstexpr;
1110     ToData.HasConstexprDefaultConstructor
1111       = FromData.HasConstexprDefaultConstructor;
1112     ToData.HasNonLiteralTypeFieldsOrBases
1113       = FromData.HasNonLiteralTypeFieldsOrBases;
1114     // ComputedVisibleConversions not imported.
1115     ToData.UserProvidedDefaultConstructor
1116       = FromData.UserProvidedDefaultConstructor;
1117     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1118     ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1119       = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1120     ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1121       = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1122     ToData.ImplicitCopyAssignmentHasConstParam
1123       = FromData.ImplicitCopyAssignmentHasConstParam;
1124     ToData.HasDeclaredCopyConstructorWithConstParam
1125       = FromData.HasDeclaredCopyConstructorWithConstParam;
1126     ToData.HasDeclaredCopyAssignmentWithConstParam
1127       = FromData.HasDeclaredCopyAssignmentWithConstParam;
1128 
1129     SmallVector<CXXBaseSpecifier *, 4> Bases;
1130     for (const auto &Base1 : FromCXX->bases()) {
1131       QualType T = Importer.Import(Base1.getType());
1132       if (T.isNull())
1133         return true;
1134 
1135       SourceLocation EllipsisLoc;
1136       if (Base1.isPackExpansion())
1137         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
1138 
1139       // Ensure that we have a definition for the base.
1140       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
1141 
1142       Bases.push_back(
1143                     new (Importer.getToContext())
1144                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
1145                                        Base1.isVirtual(),
1146                                        Base1.isBaseOfClass(),
1147                                        Base1.getAccessSpecifierAsWritten(),
1148                                    Importer.Import(Base1.getTypeSourceInfo()),
1149                                        EllipsisLoc));
1150     }
1151     if (!Bases.empty())
1152       ToCXX->setBases(Bases.data(), Bases.size());
1153   }
1154 
1155   if (shouldForceImportDeclContext(Kind))
1156     ImportDeclContext(From, /*ForceImport=*/true);
1157 
1158   To->completeDefinition();
1159   return false;
1160 }
1161 
1162 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
1163                                        ImportDefinitionKind Kind) {
1164   if (To->getAnyInitializer())
1165     return false;
1166 
1167   // FIXME: Can we really import any initializer? Alternatively, we could force
1168   // ourselves to import every declaration of a variable and then only use
1169   // getInit() here.
1170   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
1171 
1172   // FIXME: Other bits to merge?
1173 
1174   return false;
1175 }
1176 
1177 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
1178                                        ImportDefinitionKind Kind) {
1179   if (To->getDefinition() || To->isBeingDefined()) {
1180     if (Kind == IDK_Everything)
1181       ImportDeclContext(From, /*ForceImport=*/true);
1182     return false;
1183   }
1184 
1185   To->startDefinition();
1186 
1187   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
1188   if (T.isNull())
1189     return true;
1190 
1191   QualType ToPromotionType = Importer.Import(From->getPromotionType());
1192   if (ToPromotionType.isNull())
1193     return true;
1194 
1195   if (shouldForceImportDeclContext(Kind))
1196     ImportDeclContext(From, /*ForceImport=*/true);
1197 
1198   // FIXME: we might need to merge the number of positive or negative bits
1199   // if the enumerator lists don't match.
1200   To->completeDefinition(T, ToPromotionType,
1201                          From->getNumPositiveBits(),
1202                          From->getNumNegativeBits());
1203   return false;
1204 }
1205 
1206 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
1207                                                 TemplateParameterList *Params) {
1208   SmallVector<NamedDecl *, 4> ToParams(Params->size());
1209   if (ImportContainerChecked(*Params, ToParams))
1210     return nullptr;
1211 
1212   Expr *ToRequiresClause;
1213   if (Expr *const R = Params->getRequiresClause()) {
1214     ToRequiresClause = Importer.Import(R);
1215     if (!ToRequiresClause)
1216       return nullptr;
1217   } else {
1218     ToRequiresClause = nullptr;
1219   }
1220 
1221   return TemplateParameterList::Create(Importer.getToContext(),
1222                                        Importer.Import(Params->getTemplateLoc()),
1223                                        Importer.Import(Params->getLAngleLoc()),
1224                                        ToParams,
1225                                        Importer.Import(Params->getRAngleLoc()),
1226                                        ToRequiresClause);
1227 }
1228 
1229 TemplateArgument
1230 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1231   switch (From.getKind()) {
1232   case TemplateArgument::Null:
1233     return TemplateArgument();
1234 
1235   case TemplateArgument::Type: {
1236     QualType ToType = Importer.Import(From.getAsType());
1237     if (ToType.isNull())
1238       return TemplateArgument();
1239     return TemplateArgument(ToType);
1240   }
1241 
1242   case TemplateArgument::Integral: {
1243     QualType ToType = Importer.Import(From.getIntegralType());
1244     if (ToType.isNull())
1245       return TemplateArgument();
1246     return TemplateArgument(From, ToType);
1247   }
1248 
1249   case TemplateArgument::Declaration: {
1250     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
1251     QualType ToType = Importer.Import(From.getParamTypeForDecl());
1252     if (!To || ToType.isNull())
1253       return TemplateArgument();
1254     return TemplateArgument(To, ToType);
1255   }
1256 
1257   case TemplateArgument::NullPtr: {
1258     QualType ToType = Importer.Import(From.getNullPtrType());
1259     if (ToType.isNull())
1260       return TemplateArgument();
1261     return TemplateArgument(ToType, /*isNullPtr*/true);
1262   }
1263 
1264   case TemplateArgument::Template: {
1265     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
1266     if (ToTemplate.isNull())
1267       return TemplateArgument();
1268 
1269     return TemplateArgument(ToTemplate);
1270   }
1271 
1272   case TemplateArgument::TemplateExpansion: {
1273     TemplateName ToTemplate
1274       = Importer.Import(From.getAsTemplateOrTemplatePattern());
1275     if (ToTemplate.isNull())
1276       return TemplateArgument();
1277 
1278     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
1279   }
1280 
1281   case TemplateArgument::Expression:
1282     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
1283       return TemplateArgument(ToExpr);
1284     return TemplateArgument();
1285 
1286   case TemplateArgument::Pack: {
1287     SmallVector<TemplateArgument, 2> ToPack;
1288     ToPack.reserve(From.pack_size());
1289     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
1290       return TemplateArgument();
1291 
1292     return TemplateArgument(
1293         llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
1294   }
1295   }
1296 
1297   llvm_unreachable("Invalid template argument kind");
1298 }
1299 
1300 Optional<TemplateArgumentLoc>
1301 ASTNodeImporter::ImportTemplateArgumentLoc(const TemplateArgumentLoc &TALoc) {
1302   TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument());
1303   TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
1304   TemplateArgumentLocInfo ToInfo;
1305   if (Arg.getKind() == TemplateArgument::Expression) {
1306     Expr *E = Importer.Import(FromInfo.getAsExpr());
1307     ToInfo = TemplateArgumentLocInfo(E);
1308     if (!E)
1309       return None;
1310   } else if (Arg.getKind() == TemplateArgument::Type) {
1311     if (TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()))
1312       ToInfo = TemplateArgumentLocInfo(TSI);
1313     else
1314       return None;
1315   } else {
1316     ToInfo = TemplateArgumentLocInfo(
1317           Importer.Import(FromInfo.getTemplateQualifierLoc()),
1318           Importer.Import(FromInfo.getTemplateNameLoc()),
1319           Importer.Import(FromInfo.getTemplateEllipsisLoc()));
1320   }
1321   return TemplateArgumentLoc(Arg, ToInfo);
1322 }
1323 
1324 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
1325                                               unsigned NumFromArgs,
1326                               SmallVectorImpl<TemplateArgument> &ToArgs) {
1327   for (unsigned I = 0; I != NumFromArgs; ++I) {
1328     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
1329     if (To.isNull() && !FromArgs[I].isNull())
1330       return true;
1331 
1332     ToArgs.push_back(To);
1333   }
1334 
1335   return false;
1336 }
1337 
1338 // We cannot use Optional<> pattern here and below because
1339 // TemplateArgumentListInfo's operator new is declared as deleted so it cannot
1340 // be stored in Optional.
1341 template <typename InContainerTy>
1342 bool ASTNodeImporter::ImportTemplateArgumentListInfo(
1343     const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1344   for (const auto &FromLoc : Container) {
1345     if (auto ToLoc = ImportTemplateArgumentLoc(FromLoc))
1346       ToTAInfo.addArgument(*ToLoc);
1347     else
1348       return true;
1349   }
1350   return false;
1351 }
1352 
1353 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1354                                         RecordDecl *ToRecord, bool Complain) {
1355   // Eliminate a potential failure point where we attempt to re-import
1356   // something we're trying to import while completing ToRecord.
1357   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1358   if (ToOrigin) {
1359     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1360     if (ToOriginRecord)
1361       ToRecord = ToOriginRecord;
1362   }
1363 
1364   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1365                                    ToRecord->getASTContext(),
1366                                    Importer.getNonEquivalentDecls(),
1367                                    false, Complain);
1368   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
1369 }
1370 
1371 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
1372                                         bool Complain) {
1373   StructuralEquivalenceContext Ctx(
1374       Importer.getFromContext(), Importer.getToContext(),
1375       Importer.getNonEquivalentDecls(), false, Complain);
1376   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
1377 }
1378 
1379 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1380   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1381                                    Importer.getToContext(),
1382                                    Importer.getNonEquivalentDecls());
1383   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
1384 }
1385 
1386 bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
1387                                         FunctionTemplateDecl *To) {
1388   StructuralEquivalenceContext Ctx(
1389       Importer.getFromContext(), Importer.getToContext(),
1390       Importer.getNonEquivalentDecls(), false, false);
1391   return Ctx.IsStructurallyEquivalent(From, To);
1392 }
1393 
1394 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
1395                                         EnumConstantDecl *ToEC)
1396 {
1397   const llvm::APSInt &FromVal = FromEC->getInitVal();
1398   const llvm::APSInt &ToVal = ToEC->getInitVal();
1399 
1400   return FromVal.isSigned() == ToVal.isSigned() &&
1401          FromVal.getBitWidth() == ToVal.getBitWidth() &&
1402          FromVal == ToVal;
1403 }
1404 
1405 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
1406                                         ClassTemplateDecl *To) {
1407   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1408                                    Importer.getToContext(),
1409                                    Importer.getNonEquivalentDecls());
1410   return Ctx.IsStructurallyEquivalent(From, To);
1411 }
1412 
1413 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
1414                                         VarTemplateDecl *To) {
1415   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1416                                    Importer.getToContext(),
1417                                    Importer.getNonEquivalentDecls());
1418   return Ctx.IsStructurallyEquivalent(From, To);
1419 }
1420 
1421 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1422   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1423     << D->getDeclKindName();
1424   return nullptr;
1425 }
1426 
1427 Decl *ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
1428   // Import the context of this declaration.
1429   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1430   if (!DC)
1431     return nullptr;
1432 
1433   DeclContext *LexicalDC = DC;
1434   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1435     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1436     if (!LexicalDC)
1437       return nullptr;
1438   }
1439 
1440   // Import the location of this declaration.
1441   SourceLocation Loc = Importer.Import(D->getLocation());
1442 
1443   EmptyDecl *ToD = EmptyDecl::Create(Importer.getToContext(), DC, Loc);
1444   ToD->setLexicalDeclContext(LexicalDC);
1445   Importer.Imported(D, ToD);
1446   LexicalDC->addDeclInternal(ToD);
1447   return ToD;
1448 }
1449 
1450 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1451   TranslationUnitDecl *ToD =
1452     Importer.getToContext().getTranslationUnitDecl();
1453 
1454   Importer.Imported(D, ToD);
1455 
1456   return ToD;
1457 }
1458 
1459 Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1460 
1461   SourceLocation Loc = Importer.Import(D->getLocation());
1462   SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
1463 
1464   // Import the context of this declaration.
1465   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1466   if (!DC)
1467     return nullptr;
1468 
1469   AccessSpecDecl *accessSpecDecl
1470     = AccessSpecDecl::Create(Importer.getToContext(), D->getAccess(),
1471                              DC, Loc, ColonLoc);
1472 
1473   if (!accessSpecDecl)
1474     return nullptr;
1475 
1476   // Lexical DeclContext and Semantic DeclContext
1477   // is always the same for the accessSpec.
1478   accessSpecDecl->setLexicalDeclContext(DC);
1479   DC->addDeclInternal(accessSpecDecl);
1480 
1481   return accessSpecDecl;
1482 }
1483 
1484 Decl *ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1485   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1486   if (!DC)
1487     return nullptr;
1488 
1489   DeclContext *LexicalDC = DC;
1490 
1491   // Import the location of this declaration.
1492   SourceLocation Loc = Importer.Import(D->getLocation());
1493 
1494   Expr *AssertExpr = Importer.Import(D->getAssertExpr());
1495   if (!AssertExpr)
1496     return nullptr;
1497 
1498   StringLiteral *FromMsg = D->getMessage();
1499   StringLiteral *ToMsg = cast_or_null<StringLiteral>(Importer.Import(FromMsg));
1500   if (!ToMsg && FromMsg)
1501     return nullptr;
1502 
1503   StaticAssertDecl *ToD = StaticAssertDecl::Create(
1504         Importer.getToContext(), DC, Loc, AssertExpr, ToMsg,
1505         Importer.Import(D->getRParenLoc()), D->isFailed());
1506 
1507   ToD->setLexicalDeclContext(LexicalDC);
1508   LexicalDC->addDeclInternal(ToD);
1509   Importer.Imported(D, ToD);
1510   return ToD;
1511 }
1512 
1513 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1514   // Import the major distinguishing characteristics of this namespace.
1515   DeclContext *DC, *LexicalDC;
1516   DeclarationName Name;
1517   SourceLocation Loc;
1518   NamedDecl *ToD;
1519   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1520     return nullptr;
1521   if (ToD)
1522     return ToD;
1523 
1524   NamespaceDecl *MergeWithNamespace = nullptr;
1525   if (!Name) {
1526     // This is an anonymous namespace. Adopt an existing anonymous
1527     // namespace if we can.
1528     // FIXME: Not testable.
1529     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1530       MergeWithNamespace = TU->getAnonymousNamespace();
1531     else
1532       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1533   } else {
1534     SmallVector<NamedDecl *, 4> ConflictingDecls;
1535     SmallVector<NamedDecl *, 2> FoundDecls;
1536     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1537     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1538       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
1539         continue;
1540 
1541       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
1542         MergeWithNamespace = FoundNS;
1543         ConflictingDecls.clear();
1544         break;
1545       }
1546 
1547       ConflictingDecls.push_back(FoundDecls[I]);
1548     }
1549 
1550     if (!ConflictingDecls.empty()) {
1551       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
1552                                          ConflictingDecls.data(),
1553                                          ConflictingDecls.size());
1554     }
1555   }
1556 
1557   // Create the "to" namespace, if needed.
1558   NamespaceDecl *ToNamespace = MergeWithNamespace;
1559   if (!ToNamespace) {
1560     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
1561                                         D->isInline(),
1562                                         Importer.Import(D->getLocStart()),
1563                                         Loc, Name.getAsIdentifierInfo(),
1564                                         /*PrevDecl=*/nullptr);
1565     ToNamespace->setLexicalDeclContext(LexicalDC);
1566     LexicalDC->addDeclInternal(ToNamespace);
1567 
1568     // If this is an anonymous namespace, register it as the anonymous
1569     // namespace within its context.
1570     if (!Name) {
1571       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1572         TU->setAnonymousNamespace(ToNamespace);
1573       else
1574         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1575     }
1576   }
1577   Importer.Imported(D, ToNamespace);
1578 
1579   ImportDeclContext(D);
1580 
1581   return ToNamespace;
1582 }
1583 
1584 Decl *ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1585   // Import the major distinguishing characteristics of this namespace.
1586   DeclContext *DC, *LexicalDC;
1587   DeclarationName Name;
1588   SourceLocation Loc;
1589   NamedDecl *LookupD;
1590   if (ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
1591     return nullptr;
1592   if (LookupD)
1593     return LookupD;
1594 
1595   // NOTE: No conflict resolution is done for namespace aliases now.
1596 
1597   NamespaceDecl *TargetDecl = cast_or_null<NamespaceDecl>(
1598         Importer.Import(D->getNamespace()));
1599   if (!TargetDecl)
1600     return nullptr;
1601 
1602   IdentifierInfo *ToII = Importer.Import(D->getIdentifier());
1603   if (!ToII)
1604     return nullptr;
1605 
1606   NestedNameSpecifierLoc ToQLoc = Importer.Import(D->getQualifierLoc());
1607   if (D->getQualifierLoc() && !ToQLoc)
1608     return nullptr;
1609 
1610   NamespaceAliasDecl *ToD = NamespaceAliasDecl::Create(
1611         Importer.getToContext(), DC, Importer.Import(D->getNamespaceLoc()),
1612         Importer.Import(D->getAliasLoc()), ToII, ToQLoc,
1613         Importer.Import(D->getTargetNameLoc()), TargetDecl);
1614 
1615   ToD->setLexicalDeclContext(LexicalDC);
1616   Importer.Imported(D, ToD);
1617   LexicalDC->addDeclInternal(ToD);
1618 
1619   return ToD;
1620 }
1621 
1622 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
1623   // Import the major distinguishing characteristics of this typedef.
1624   DeclContext *DC, *LexicalDC;
1625   DeclarationName Name;
1626   SourceLocation Loc;
1627   NamedDecl *ToD;
1628   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1629     return nullptr;
1630   if (ToD)
1631     return ToD;
1632 
1633   // If this typedef is not in block scope, determine whether we've
1634   // seen a typedef with the same name (that we can merge with) or any
1635   // other entity by that name (which name lookup could conflict with).
1636   if (!DC->isFunctionOrMethod()) {
1637     SmallVector<NamedDecl *, 4> ConflictingDecls;
1638     unsigned IDNS = Decl::IDNS_Ordinary;
1639     SmallVector<NamedDecl *, 2> FoundDecls;
1640     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1641     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1642       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1643         continue;
1644       if (TypedefNameDecl *FoundTypedef =
1645             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
1646         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1647                                             FoundTypedef->getUnderlyingType()))
1648           return Importer.Imported(D, FoundTypedef);
1649       }
1650 
1651       ConflictingDecls.push_back(FoundDecls[I]);
1652     }
1653 
1654     if (!ConflictingDecls.empty()) {
1655       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1656                                          ConflictingDecls.data(),
1657                                          ConflictingDecls.size());
1658       if (!Name)
1659         return nullptr;
1660     }
1661   }
1662 
1663   // Import the underlying type of this typedef;
1664   QualType T = Importer.Import(D->getUnderlyingType());
1665   if (T.isNull())
1666     return nullptr;
1667 
1668   // Create the new typedef node.
1669   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1670   SourceLocation StartL = Importer.Import(D->getLocStart());
1671   TypedefNameDecl *ToTypedef;
1672   if (IsAlias)
1673     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC, StartL, Loc,
1674                                       Name.getAsIdentifierInfo(), TInfo);
1675   else
1676     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
1677                                     StartL, Loc,
1678                                     Name.getAsIdentifierInfo(),
1679                                     TInfo);
1680 
1681   ToTypedef->setAccess(D->getAccess());
1682   ToTypedef->setLexicalDeclContext(LexicalDC);
1683   Importer.Imported(D, ToTypedef);
1684 
1685   // Templated declarations should not appear in DeclContext.
1686   TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
1687   if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
1688     LexicalDC->addDeclInternal(ToTypedef);
1689 
1690   return ToTypedef;
1691 }
1692 
1693 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
1694   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
1695 }
1696 
1697 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
1698   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
1699 }
1700 
1701 Decl *ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1702   // Import the major distinguishing characteristics of this typedef.
1703   DeclContext *DC, *LexicalDC;
1704   DeclarationName Name;
1705   SourceLocation Loc;
1706   NamedDecl *FoundD;
1707   if (ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
1708     return nullptr;
1709   if (FoundD)
1710     return FoundD;
1711 
1712   // If this typedef is not in block scope, determine whether we've
1713   // seen a typedef with the same name (that we can merge with) or any
1714   // other entity by that name (which name lookup could conflict with).
1715   if (!DC->isFunctionOrMethod()) {
1716     SmallVector<NamedDecl *, 4> ConflictingDecls;
1717     unsigned IDNS = Decl::IDNS_Ordinary;
1718     SmallVector<NamedDecl *, 2> FoundDecls;
1719     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1720     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1721       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1722         continue;
1723       if (auto *FoundAlias =
1724             dyn_cast<TypeAliasTemplateDecl>(FoundDecls[I]))
1725           return Importer.Imported(D, FoundAlias);
1726       ConflictingDecls.push_back(FoundDecls[I]);
1727     }
1728 
1729     if (!ConflictingDecls.empty()) {
1730       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1731                                          ConflictingDecls.data(),
1732                                          ConflictingDecls.size());
1733       if (!Name)
1734         return nullptr;
1735     }
1736   }
1737 
1738   TemplateParameterList *Params = ImportTemplateParameterList(
1739         D->getTemplateParameters());
1740   if (!Params)
1741     return nullptr;
1742 
1743   auto *TemplDecl = cast_or_null<TypeAliasDecl>(
1744         Importer.Import(D->getTemplatedDecl()));
1745   if (!TemplDecl)
1746     return nullptr;
1747 
1748   TypeAliasTemplateDecl *ToAlias = TypeAliasTemplateDecl::Create(
1749         Importer.getToContext(), DC, Loc, Name, Params, TemplDecl);
1750 
1751   TemplDecl->setDescribedAliasTemplate(ToAlias);
1752 
1753   ToAlias->setAccess(D->getAccess());
1754   ToAlias->setLexicalDeclContext(LexicalDC);
1755   Importer.Imported(D, ToAlias);
1756   LexicalDC->addDeclInternal(ToAlias);
1757   return ToAlias;
1758 }
1759 
1760 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
1761   // Import the major distinguishing characteristics of this label.
1762   DeclContext *DC, *LexicalDC;
1763   DeclarationName Name;
1764   SourceLocation Loc;
1765   NamedDecl *ToD;
1766   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1767     return nullptr;
1768   if (ToD)
1769     return ToD;
1770 
1771   assert(LexicalDC->isFunctionOrMethod());
1772 
1773   LabelDecl *ToLabel = D->isGnuLocal()
1774       ? LabelDecl::Create(Importer.getToContext(),
1775                           DC, Importer.Import(D->getLocation()),
1776                           Name.getAsIdentifierInfo(),
1777                           Importer.Import(D->getLocStart()))
1778       : LabelDecl::Create(Importer.getToContext(),
1779                           DC, Importer.Import(D->getLocation()),
1780                           Name.getAsIdentifierInfo());
1781   Importer.Imported(D, ToLabel);
1782 
1783   LabelStmt *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
1784   if (!Label)
1785     return nullptr;
1786 
1787   ToLabel->setStmt(Label);
1788   ToLabel->setLexicalDeclContext(LexicalDC);
1789   LexicalDC->addDeclInternal(ToLabel);
1790   return ToLabel;
1791 }
1792 
1793 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
1794   // Import the major distinguishing characteristics of this enum.
1795   DeclContext *DC, *LexicalDC;
1796   DeclarationName Name;
1797   SourceLocation Loc;
1798   NamedDecl *ToD;
1799   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1800     return nullptr;
1801   if (ToD)
1802     return ToD;
1803 
1804   // Figure out what enum name we're looking for.
1805   unsigned IDNS = Decl::IDNS_Tag;
1806   DeclarationName SearchName = Name;
1807   if (!SearchName && D->getTypedefNameForAnonDecl()) {
1808     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
1809     IDNS = Decl::IDNS_Ordinary;
1810   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
1811     IDNS |= Decl::IDNS_Ordinary;
1812 
1813   // We may already have an enum of the same name; try to find and match it.
1814   if (!DC->isFunctionOrMethod() && SearchName) {
1815     SmallVector<NamedDecl *, 4> ConflictingDecls;
1816     SmallVector<NamedDecl *, 2> FoundDecls;
1817     DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
1818     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1819       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1820         continue;
1821 
1822       Decl *Found = FoundDecls[I];
1823       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
1824         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1825           Found = Tag->getDecl();
1826       }
1827 
1828       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
1829         if (IsStructuralMatch(D, FoundEnum))
1830           return Importer.Imported(D, FoundEnum);
1831       }
1832 
1833       ConflictingDecls.push_back(FoundDecls[I]);
1834     }
1835 
1836     if (!ConflictingDecls.empty()) {
1837       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1838                                          ConflictingDecls.data(),
1839                                          ConflictingDecls.size());
1840     }
1841   }
1842 
1843   // Create the enum declaration.
1844   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
1845                                   Importer.Import(D->getLocStart()),
1846                                   Loc, Name.getAsIdentifierInfo(), nullptr,
1847                                   D->isScoped(), D->isScopedUsingClassTag(),
1848                                   D->isFixed());
1849   // Import the qualifier, if any.
1850   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
1851   D2->setAccess(D->getAccess());
1852   D2->setLexicalDeclContext(LexicalDC);
1853   Importer.Imported(D, D2);
1854   LexicalDC->addDeclInternal(D2);
1855 
1856   // Import the integer type.
1857   QualType ToIntegerType = Importer.Import(D->getIntegerType());
1858   if (ToIntegerType.isNull())
1859     return nullptr;
1860   D2->setIntegerType(ToIntegerType);
1861 
1862   // Import the definition
1863   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
1864     return nullptr;
1865 
1866   return D2;
1867 }
1868 
1869 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
1870   // If this record has a definition in the translation unit we're coming from,
1871   // but this particular declaration is not that definition, import the
1872   // definition and map to that.
1873   TagDecl *Definition = D->getDefinition();
1874   if (Definition && Definition != D) {
1875     Decl *ImportedDef = Importer.Import(Definition);
1876     if (!ImportedDef)
1877       return nullptr;
1878 
1879     return Importer.Imported(D, ImportedDef);
1880   }
1881 
1882   // Import the major distinguishing characteristics of this record.
1883   DeclContext *DC, *LexicalDC;
1884   DeclarationName Name;
1885   SourceLocation Loc;
1886   NamedDecl *ToD;
1887   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1888     return nullptr;
1889   if (ToD)
1890     return ToD;
1891 
1892   // Figure out what structure name we're looking for.
1893   unsigned IDNS = Decl::IDNS_Tag;
1894   DeclarationName SearchName = Name;
1895   if (!SearchName && D->getTypedefNameForAnonDecl()) {
1896     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
1897     IDNS = Decl::IDNS_Ordinary;
1898   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
1899     IDNS |= Decl::IDNS_Ordinary;
1900 
1901   // We may already have a record of the same name; try to find and match it.
1902   RecordDecl *AdoptDecl = nullptr;
1903   RecordDecl *PrevDecl = nullptr;
1904   if (!DC->isFunctionOrMethod()) {
1905     SmallVector<NamedDecl *, 4> ConflictingDecls;
1906     SmallVector<NamedDecl *, 2> FoundDecls;
1907     DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
1908 
1909     if (!FoundDecls.empty()) {
1910       // We're going to have to compare D against potentially conflicting Decls, so complete it.
1911       if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
1912         D->getASTContext().getExternalSource()->CompleteType(D);
1913     }
1914 
1915     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1916       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1917         continue;
1918 
1919       Decl *Found = FoundDecls[I];
1920       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
1921         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1922           Found = Tag->getDecl();
1923       }
1924 
1925       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
1926         if (D->isAnonymousStructOrUnion() &&
1927             FoundRecord->isAnonymousStructOrUnion()) {
1928           // If both anonymous structs/unions are in a record context, make sure
1929           // they occur in the same location in the context records.
1930           if (Optional<unsigned> Index1 =
1931                   StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(
1932                       D)) {
1933             if (Optional<unsigned> Index2 = StructuralEquivalenceContext::
1934                     findUntaggedStructOrUnionIndex(FoundRecord)) {
1935               if (*Index1 != *Index2)
1936                 continue;
1937             }
1938           }
1939         }
1940 
1941         PrevDecl = FoundRecord;
1942 
1943         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
1944           if ((SearchName && !D->isCompleteDefinition())
1945               || (D->isCompleteDefinition() &&
1946                   D->isAnonymousStructOrUnion()
1947                     == FoundDef->isAnonymousStructOrUnion() &&
1948                   IsStructuralMatch(D, FoundDef))) {
1949             // The record types structurally match, or the "from" translation
1950             // unit only had a forward declaration anyway; call it the same
1951             // function.
1952             // FIXME: For C++, we should also merge methods here.
1953             return Importer.Imported(D, FoundDef);
1954           }
1955         } else if (!D->isCompleteDefinition()) {
1956           // We have a forward declaration of this type, so adopt that forward
1957           // declaration rather than building a new one.
1958 
1959           // If one or both can be completed from external storage then try one
1960           // last time to complete and compare them before doing this.
1961 
1962           if (FoundRecord->hasExternalLexicalStorage() &&
1963               !FoundRecord->isCompleteDefinition())
1964             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
1965           if (D->hasExternalLexicalStorage())
1966             D->getASTContext().getExternalSource()->CompleteType(D);
1967 
1968           if (FoundRecord->isCompleteDefinition() &&
1969               D->isCompleteDefinition() &&
1970               !IsStructuralMatch(D, FoundRecord))
1971             continue;
1972 
1973           AdoptDecl = FoundRecord;
1974           continue;
1975         } else if (!SearchName) {
1976           continue;
1977         }
1978       }
1979 
1980       ConflictingDecls.push_back(FoundDecls[I]);
1981     }
1982 
1983     if (!ConflictingDecls.empty() && SearchName) {
1984       Name = Importer.HandleNameConflict(Name, DC, IDNS,
1985                                          ConflictingDecls.data(),
1986                                          ConflictingDecls.size());
1987     }
1988   }
1989 
1990   // Create the record declaration.
1991   RecordDecl *D2 = AdoptDecl;
1992   SourceLocation StartLoc = Importer.Import(D->getLocStart());
1993   if (!D2) {
1994     CXXRecordDecl *D2CXX = nullptr;
1995     if (CXXRecordDecl *DCXX = llvm::dyn_cast<CXXRecordDecl>(D)) {
1996       if (DCXX->isLambda()) {
1997         TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
1998         D2CXX = CXXRecordDecl::CreateLambda(Importer.getToContext(),
1999                                             DC, TInfo, Loc,
2000                                             DCXX->isDependentLambda(),
2001                                             DCXX->isGenericLambda(),
2002                                             DCXX->getLambdaCaptureDefault());
2003         Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2004         if (DCXX->getLambdaContextDecl() && !CDecl)
2005           return nullptr;
2006         D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2007       } else if (DCXX->isInjectedClassName()) {
2008         // We have to be careful to do a similar dance to the one in
2009         // Sema::ActOnStartCXXMemberDeclarations
2010         CXXRecordDecl *const PrevDecl = nullptr;
2011         const bool DelayTypeCreation = true;
2012         D2CXX = CXXRecordDecl::Create(
2013             Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc,
2014             Name.getAsIdentifierInfo(), PrevDecl, DelayTypeCreation);
2015         Importer.getToContext().getTypeDeclType(
2016             D2CXX, llvm::dyn_cast<CXXRecordDecl>(DC));
2017       } else {
2018         D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2019                                       D->getTagKind(),
2020                                       DC, StartLoc, Loc,
2021                                       Name.getAsIdentifierInfo());
2022       }
2023       D2 = D2CXX;
2024       D2->setAccess(D->getAccess());
2025       D2->setLexicalDeclContext(LexicalDC);
2026       if (!DCXX->getDescribedClassTemplate())
2027         LexicalDC->addDeclInternal(D2);
2028 
2029       Importer.Imported(D, D2);
2030 
2031       if (ClassTemplateDecl *FromDescribed =
2032           DCXX->getDescribedClassTemplate()) {
2033         ClassTemplateDecl *ToDescribed = cast_or_null<ClassTemplateDecl>(
2034               Importer.Import(FromDescribed));
2035         if (!ToDescribed)
2036           return nullptr;
2037         D2CXX->setDescribedClassTemplate(ToDescribed);
2038 
2039       } else if (MemberSpecializationInfo *MemberInfo =
2040                    DCXX->getMemberSpecializationInfo()) {
2041         TemplateSpecializationKind SK =
2042             MemberInfo->getTemplateSpecializationKind();
2043         CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2044         CXXRecordDecl *ToInst =
2045             cast_or_null<CXXRecordDecl>(Importer.Import(FromInst));
2046         if (FromInst && !ToInst)
2047           return nullptr;
2048         D2CXX->setInstantiationOfMemberClass(ToInst, SK);
2049         D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2050               Importer.Import(MemberInfo->getPointOfInstantiation()));
2051       }
2052 
2053     } else {
2054       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2055                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2056       D2->setLexicalDeclContext(LexicalDC);
2057       LexicalDC->addDeclInternal(D2);
2058     }
2059 
2060     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2061     if (D->isAnonymousStructOrUnion())
2062       D2->setAnonymousStructOrUnion(true);
2063     if (PrevDecl) {
2064       // FIXME: do this for all Redeclarables, not just RecordDecls.
2065       D2->setPreviousDecl(PrevDecl);
2066     }
2067   }
2068 
2069   Importer.Imported(D, D2);
2070 
2071   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2072     return nullptr;
2073 
2074   return D2;
2075 }
2076 
2077 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2078   // Import the major distinguishing characteristics of this enumerator.
2079   DeclContext *DC, *LexicalDC;
2080   DeclarationName Name;
2081   SourceLocation Loc;
2082   NamedDecl *ToD;
2083   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2084     return nullptr;
2085   if (ToD)
2086     return ToD;
2087 
2088   QualType T = Importer.Import(D->getType());
2089   if (T.isNull())
2090     return nullptr;
2091 
2092   // Determine whether there are any other declarations with the same name and
2093   // in the same context.
2094   if (!LexicalDC->isFunctionOrMethod()) {
2095     SmallVector<NamedDecl *, 4> ConflictingDecls;
2096     unsigned IDNS = Decl::IDNS_Ordinary;
2097     SmallVector<NamedDecl *, 2> FoundDecls;
2098     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2099     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2100       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2101         continue;
2102 
2103       if (EnumConstantDecl *FoundEnumConstant
2104             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2105         if (IsStructuralMatch(D, FoundEnumConstant))
2106           return Importer.Imported(D, FoundEnumConstant);
2107       }
2108 
2109       ConflictingDecls.push_back(FoundDecls[I]);
2110     }
2111 
2112     if (!ConflictingDecls.empty()) {
2113       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2114                                          ConflictingDecls.data(),
2115                                          ConflictingDecls.size());
2116       if (!Name)
2117         return nullptr;
2118     }
2119   }
2120 
2121   Expr *Init = Importer.Import(D->getInitExpr());
2122   if (D->getInitExpr() && !Init)
2123     return nullptr;
2124 
2125   EnumConstantDecl *ToEnumerator
2126     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2127                                Name.getAsIdentifierInfo(), T,
2128                                Init, D->getInitVal());
2129   ToEnumerator->setAccess(D->getAccess());
2130   ToEnumerator->setLexicalDeclContext(LexicalDC);
2131   Importer.Imported(D, ToEnumerator);
2132   LexicalDC->addDeclInternal(ToEnumerator);
2133   return ToEnumerator;
2134 }
2135 
2136 bool ASTNodeImporter::ImportTemplateInformation(FunctionDecl *FromFD,
2137                                                 FunctionDecl *ToFD) {
2138   switch (FromFD->getTemplatedKind()) {
2139   case FunctionDecl::TK_NonTemplate:
2140   case FunctionDecl::TK_FunctionTemplate:
2141     return false;
2142 
2143   case FunctionDecl::TK_MemberSpecialization: {
2144     auto *InstFD = cast_or_null<FunctionDecl>(
2145           Importer.Import(FromFD->getInstantiatedFromMemberFunction()));
2146     if (!InstFD)
2147       return true;
2148 
2149     TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
2150     SourceLocation POI = Importer.Import(
2151           FromFD->getMemberSpecializationInfo()->getPointOfInstantiation());
2152     ToFD->setInstantiationOfMemberFunction(InstFD, TSK);
2153     ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
2154     return false;
2155   }
2156 
2157   case FunctionDecl::TK_FunctionTemplateSpecialization: {
2158     auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2159     auto *Template = cast_or_null<FunctionTemplateDecl>(
2160         Importer.Import(FTSInfo->getTemplate()));
2161     if (!Template)
2162       return true;
2163     TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2164 
2165     // Import template arguments.
2166     auto TemplArgs = FTSInfo->TemplateArguments->asArray();
2167     SmallVector<TemplateArgument, 8> ToTemplArgs;
2168     if (ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
2169                                 ToTemplArgs))
2170       return true;
2171 
2172     TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
2173           Importer.getToContext(), ToTemplArgs);
2174 
2175     TemplateArgumentListInfo ToTAInfo;
2176     const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2177     if (FromTAArgsAsWritten)
2178       if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
2179         return true;
2180 
2181     SourceLocation POI = Importer.Import(FTSInfo->getPointOfInstantiation());
2182 
2183     ToFD->setFunctionTemplateSpecialization(
2184         Template, ToTAList, /* InsertPos= */ nullptr,
2185         TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, POI);
2186     return false;
2187   }
2188 
2189   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
2190     auto *FromInfo = FromFD->getDependentSpecializationInfo();
2191     UnresolvedSet<8> TemplDecls;
2192     unsigned NumTemplates = FromInfo->getNumTemplates();
2193     for (unsigned I = 0; I < NumTemplates; I++) {
2194       if (auto *ToFTD = cast_or_null<FunctionTemplateDecl>(
2195               Importer.Import(FromInfo->getTemplate(I))))
2196         TemplDecls.addDecl(ToFTD);
2197       else
2198         return true;
2199     }
2200 
2201     // Import TemplateArgumentListInfo.
2202     TemplateArgumentListInfo ToTAInfo;
2203     if (ImportTemplateArgumentListInfo(
2204             FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2205             llvm::makeArrayRef(FromInfo->getTemplateArgs(),
2206                                FromInfo->getNumTemplateArgs()),
2207             ToTAInfo))
2208       return true;
2209 
2210     ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2211                                              TemplDecls, ToTAInfo);
2212     return false;
2213   }
2214   }
2215   llvm_unreachable("All cases should be covered!");
2216 }
2217 
2218 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2219   // Import the major distinguishing characteristics of this function.
2220   DeclContext *DC, *LexicalDC;
2221   DeclarationName Name;
2222   SourceLocation Loc;
2223   NamedDecl *ToD;
2224   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2225     return nullptr;
2226   if (ToD)
2227     return ToD;
2228 
2229   const FunctionDecl *FoundWithoutBody = nullptr;
2230 
2231   // Try to find a function in our own ("to") context with the same name, same
2232   // type, and in the same context as the function we're importing.
2233   if (!LexicalDC->isFunctionOrMethod()) {
2234     SmallVector<NamedDecl *, 4> ConflictingDecls;
2235     unsigned IDNS = Decl::IDNS_Ordinary;
2236     SmallVector<NamedDecl *, 2> FoundDecls;
2237     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2238     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2239       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2240         continue;
2241 
2242       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2243         if (FoundFunction->hasExternalFormalLinkage() &&
2244             D->hasExternalFormalLinkage()) {
2245           if (Importer.IsStructurallyEquivalent(D->getType(),
2246                                                 FoundFunction->getType())) {
2247             // FIXME: Actually try to merge the body and other attributes.
2248             const FunctionDecl *FromBodyDecl = nullptr;
2249             D->hasBody(FromBodyDecl);
2250             if (D == FromBodyDecl && !FoundFunction->hasBody()) {
2251               // This function is needed to merge completely.
2252               FoundWithoutBody = FoundFunction;
2253               break;
2254             }
2255             return Importer.Imported(D, FoundFunction);
2256           }
2257 
2258           // FIXME: Check for overloading more carefully, e.g., by boosting
2259           // Sema::IsOverload out to the AST library.
2260 
2261           // Function overloading is okay in C++.
2262           if (Importer.getToContext().getLangOpts().CPlusPlus)
2263             continue;
2264 
2265           // Complain about inconsistent function types.
2266           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2267             << Name << D->getType() << FoundFunction->getType();
2268           Importer.ToDiag(FoundFunction->getLocation(),
2269                           diag::note_odr_value_here)
2270             << FoundFunction->getType();
2271         }
2272       }
2273 
2274       ConflictingDecls.push_back(FoundDecls[I]);
2275     }
2276 
2277     if (!ConflictingDecls.empty()) {
2278       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2279                                          ConflictingDecls.data(),
2280                                          ConflictingDecls.size());
2281       if (!Name)
2282         return nullptr;
2283     }
2284   }
2285 
2286   DeclarationNameInfo NameInfo(Name, Loc);
2287   // Import additional name location/type info.
2288   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2289 
2290   QualType FromTy = D->getType();
2291   bool usedDifferentExceptionSpec = false;
2292 
2293   if (const FunctionProtoType *
2294         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2295     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2296     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2297     // FunctionDecl that we are importing the FunctionProtoType for.
2298     // To avoid an infinite recursion when importing, create the FunctionDecl
2299     // with a simplified function type and update it afterwards.
2300     if (FromEPI.ExceptionSpec.SourceDecl ||
2301         FromEPI.ExceptionSpec.SourceTemplate ||
2302         FromEPI.ExceptionSpec.NoexceptExpr) {
2303       FunctionProtoType::ExtProtoInfo DefaultEPI;
2304       FromTy = Importer.getFromContext().getFunctionType(
2305           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2306       usedDifferentExceptionSpec = true;
2307     }
2308   }
2309 
2310   // Import the type.
2311   QualType T = Importer.Import(FromTy);
2312   if (T.isNull())
2313     return nullptr;
2314 
2315   // Import the function parameters.
2316   SmallVector<ParmVarDecl *, 8> Parameters;
2317   for (auto P : D->parameters()) {
2318     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2319     if (!ToP)
2320       return nullptr;
2321 
2322     Parameters.push_back(ToP);
2323   }
2324 
2325   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2326   if (D->getTypeSourceInfo() && !TInfo)
2327     return nullptr;
2328 
2329   // Create the imported function.
2330   FunctionDecl *ToFunction = nullptr;
2331   SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2332   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2333     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2334                                             cast<CXXRecordDecl>(DC),
2335                                             InnerLocStart,
2336                                             NameInfo, T, TInfo,
2337                                             FromConstructor->isExplicit(),
2338                                             D->isInlineSpecified(),
2339                                             D->isImplicit(),
2340                                             D->isConstexpr());
2341     if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
2342       SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
2343       for (CXXCtorInitializer *I : FromConstructor->inits()) {
2344         CXXCtorInitializer *ToI =
2345             cast_or_null<CXXCtorInitializer>(Importer.Import(I));
2346         if (!ToI && I)
2347           return nullptr;
2348         CtorInitializers.push_back(ToI);
2349       }
2350       CXXCtorInitializer **Memory =
2351           new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
2352       std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
2353       CXXConstructorDecl *ToCtor = llvm::cast<CXXConstructorDecl>(ToFunction);
2354       ToCtor->setCtorInitializers(Memory);
2355       ToCtor->setNumCtorInitializers(NumInitializers);
2356     }
2357   } else if (isa<CXXDestructorDecl>(D)) {
2358     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2359                                            cast<CXXRecordDecl>(DC),
2360                                            InnerLocStart,
2361                                            NameInfo, T, TInfo,
2362                                            D->isInlineSpecified(),
2363                                            D->isImplicit());
2364   } else if (CXXConversionDecl *FromConversion
2365                                            = dyn_cast<CXXConversionDecl>(D)) {
2366     ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2367                                            cast<CXXRecordDecl>(DC),
2368                                            InnerLocStart,
2369                                            NameInfo, T, TInfo,
2370                                            D->isInlineSpecified(),
2371                                            FromConversion->isExplicit(),
2372                                            D->isConstexpr(),
2373                                            Importer.Import(D->getLocEnd()));
2374   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2375     ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2376                                        cast<CXXRecordDecl>(DC),
2377                                        InnerLocStart,
2378                                        NameInfo, T, TInfo,
2379                                        Method->getStorageClass(),
2380                                        Method->isInlineSpecified(),
2381                                        D->isConstexpr(),
2382                                        Importer.Import(D->getLocEnd()));
2383   } else {
2384     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2385                                       InnerLocStart,
2386                                       NameInfo, T, TInfo, D->getStorageClass(),
2387                                       D->isInlineSpecified(),
2388                                       D->hasWrittenPrototype(),
2389                                       D->isConstexpr());
2390   }
2391 
2392   // Import the qualifier, if any.
2393   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2394   ToFunction->setAccess(D->getAccess());
2395   ToFunction->setLexicalDeclContext(LexicalDC);
2396   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2397   ToFunction->setTrivial(D->isTrivial());
2398   ToFunction->setPure(D->isPure());
2399   Importer.Imported(D, ToFunction);
2400 
2401   // Set the parameters.
2402   for (ParmVarDecl *Param : Parameters) {
2403     Param->setOwningFunction(ToFunction);
2404     ToFunction->addDeclInternal(Param);
2405   }
2406   ToFunction->setParams(Parameters);
2407 
2408   if (FoundWithoutBody) {
2409     auto *Recent = const_cast<FunctionDecl *>(
2410           FoundWithoutBody->getMostRecentDecl());
2411     ToFunction->setPreviousDecl(Recent);
2412   }
2413 
2414   // We need to complete creation of FunctionProtoTypeLoc manually with setting
2415   // params it refers to.
2416   if (TInfo) {
2417     if (auto ProtoLoc =
2418         TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2419       for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
2420         ProtoLoc.setParam(I, Parameters[I]);
2421     }
2422   }
2423 
2424   if (usedDifferentExceptionSpec) {
2425     // Update FunctionProtoType::ExtProtoInfo.
2426     QualType T = Importer.Import(D->getType());
2427     if (T.isNull())
2428       return nullptr;
2429     ToFunction->setType(T);
2430   }
2431 
2432   // Import the body, if any.
2433   if (Stmt *FromBody = D->getBody()) {
2434     if (Stmt *ToBody = Importer.Import(FromBody)) {
2435       ToFunction->setBody(ToBody);
2436     }
2437   }
2438 
2439   // FIXME: Other bits to merge?
2440 
2441   // If it is a template, import all related things.
2442   if (ImportTemplateInformation(D, ToFunction))
2443     return nullptr;
2444 
2445   // Add this function to the lexical context.
2446   // NOTE: If the function is templated declaration, it should be not added into
2447   // LexicalDC. But described template is imported during import of
2448   // FunctionTemplateDecl (it happens later). So, we use source declaration
2449   // to determine if we should add the result function.
2450   if (!D->getDescribedFunctionTemplate())
2451     LexicalDC->addDeclInternal(ToFunction);
2452 
2453   if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
2454     ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
2455 
2456   return ToFunction;
2457 }
2458 
2459 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2460   return VisitFunctionDecl(D);
2461 }
2462 
2463 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2464   return VisitCXXMethodDecl(D);
2465 }
2466 
2467 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2468   return VisitCXXMethodDecl(D);
2469 }
2470 
2471 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2472   return VisitCXXMethodDecl(D);
2473 }
2474 
2475 static unsigned getFieldIndex(Decl *F) {
2476   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2477   if (!Owner)
2478     return 0;
2479 
2480   unsigned Index = 1;
2481   for (const auto *D : Owner->noload_decls()) {
2482     if (D == F)
2483       return Index;
2484 
2485     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2486       ++Index;
2487   }
2488 
2489   return Index;
2490 }
2491 
2492 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2493   // Import the major distinguishing characteristics of a variable.
2494   DeclContext *DC, *LexicalDC;
2495   DeclarationName Name;
2496   SourceLocation Loc;
2497   NamedDecl *ToD;
2498   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2499     return nullptr;
2500   if (ToD)
2501     return ToD;
2502 
2503   // Determine whether we've already imported this field.
2504   SmallVector<NamedDecl *, 2> FoundDecls;
2505   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2506   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2507     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2508       // For anonymous fields, match up by index.
2509       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2510         continue;
2511 
2512       if (Importer.IsStructurallyEquivalent(D->getType(),
2513                                             FoundField->getType())) {
2514         Importer.Imported(D, FoundField);
2515         return FoundField;
2516       }
2517 
2518       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2519         << Name << D->getType() << FoundField->getType();
2520       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2521         << FoundField->getType();
2522       return nullptr;
2523     }
2524   }
2525 
2526   // Import the type.
2527   QualType T = Importer.Import(D->getType());
2528   if (T.isNull())
2529     return nullptr;
2530 
2531   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2532   Expr *BitWidth = Importer.Import(D->getBitWidth());
2533   if (!BitWidth && D->getBitWidth())
2534     return nullptr;
2535 
2536   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2537                                          Importer.Import(D->getInnerLocStart()),
2538                                          Loc, Name.getAsIdentifierInfo(),
2539                                          T, TInfo, BitWidth, D->isMutable(),
2540                                          D->getInClassInitStyle());
2541   ToField->setAccess(D->getAccess());
2542   ToField->setLexicalDeclContext(LexicalDC);
2543   if (Expr *FromInitializer = D->getInClassInitializer()) {
2544     Expr *ToInitializer = Importer.Import(FromInitializer);
2545     if (ToInitializer)
2546       ToField->setInClassInitializer(ToInitializer);
2547     else
2548       return nullptr;
2549   }
2550   ToField->setImplicit(D->isImplicit());
2551   Importer.Imported(D, ToField);
2552   LexicalDC->addDeclInternal(ToField);
2553   return ToField;
2554 }
2555 
2556 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2557   // Import the major distinguishing characteristics of a variable.
2558   DeclContext *DC, *LexicalDC;
2559   DeclarationName Name;
2560   SourceLocation Loc;
2561   NamedDecl *ToD;
2562   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2563     return nullptr;
2564   if (ToD)
2565     return ToD;
2566 
2567   // Determine whether we've already imported this field.
2568   SmallVector<NamedDecl *, 2> FoundDecls;
2569   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2570   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2571     if (IndirectFieldDecl *FoundField
2572                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2573       // For anonymous indirect fields, match up by index.
2574       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2575         continue;
2576 
2577       if (Importer.IsStructurallyEquivalent(D->getType(),
2578                                             FoundField->getType(),
2579                                             !Name.isEmpty())) {
2580         Importer.Imported(D, FoundField);
2581         return FoundField;
2582       }
2583 
2584       // If there are more anonymous fields to check, continue.
2585       if (!Name && I < N-1)
2586         continue;
2587 
2588       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2589         << Name << D->getType() << FoundField->getType();
2590       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2591         << FoundField->getType();
2592       return nullptr;
2593     }
2594   }
2595 
2596   // Import the type.
2597   QualType T = Importer.Import(D->getType());
2598   if (T.isNull())
2599     return nullptr;
2600 
2601   NamedDecl **NamedChain =
2602     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2603 
2604   unsigned i = 0;
2605   for (auto *PI : D->chain()) {
2606     Decl *D = Importer.Import(PI);
2607     if (!D)
2608       return nullptr;
2609     NamedChain[i++] = cast<NamedDecl>(D);
2610   }
2611 
2612   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2613       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
2614       {NamedChain, D->getChainingSize()});
2615 
2616   for (const auto *Attr : D->attrs())
2617     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
2618 
2619   ToIndirectField->setAccess(D->getAccess());
2620   ToIndirectField->setLexicalDeclContext(LexicalDC);
2621   Importer.Imported(D, ToIndirectField);
2622   LexicalDC->addDeclInternal(ToIndirectField);
2623   return ToIndirectField;
2624 }
2625 
2626 Decl *ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
2627   // Import the major distinguishing characteristics of a declaration.
2628   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2629   DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext()
2630       ? DC : Importer.ImportContext(D->getLexicalDeclContext());
2631   if (!DC || !LexicalDC)
2632     return nullptr;
2633 
2634   // Determine whether we've already imported this decl.
2635   // FriendDecl is not a NamedDecl so we cannot use localUncachedLookup.
2636   auto *RD = cast<CXXRecordDecl>(DC);
2637   FriendDecl *ImportedFriend = RD->getFirstFriend();
2638   StructuralEquivalenceContext Context(
2639       Importer.getFromContext(), Importer.getToContext(),
2640       Importer.getNonEquivalentDecls(), false, false);
2641 
2642   while (ImportedFriend) {
2643     if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
2644       if (Context.IsStructurallyEquivalent(D->getFriendDecl(),
2645                                            ImportedFriend->getFriendDecl()))
2646         return Importer.Imported(D, ImportedFriend);
2647 
2648     } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
2649       if (Importer.IsStructurallyEquivalent(
2650             D->getFriendType()->getType(),
2651             ImportedFriend->getFriendType()->getType(), true))
2652         return Importer.Imported(D, ImportedFriend);
2653     }
2654     ImportedFriend = ImportedFriend->getNextFriend();
2655   }
2656 
2657   // Not found. Create it.
2658   FriendDecl::FriendUnion ToFU;
2659   if (NamedDecl *FriendD = D->getFriendDecl())
2660     ToFU = cast_or_null<NamedDecl>(Importer.Import(FriendD));
2661   else
2662     ToFU = Importer.Import(D->getFriendType());
2663   if (!ToFU)
2664     return nullptr;
2665 
2666   SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
2667   TemplateParameterList **FromTPLists =
2668       D->getTrailingObjects<TemplateParameterList *>();
2669   for (unsigned I = 0; I < D->NumTPLists; I++) {
2670     TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[I]);
2671     if (!List)
2672       return nullptr;
2673     ToTPLists[I] = List;
2674   }
2675 
2676   FriendDecl *FrD = FriendDecl::Create(Importer.getToContext(), DC,
2677                                        Importer.Import(D->getLocation()),
2678                                        ToFU, Importer.Import(D->getFriendLoc()),
2679                                        ToTPLists);
2680 
2681   Importer.Imported(D, FrD);
2682   RD->pushFriendDecl(FrD);
2683 
2684   FrD->setAccess(D->getAccess());
2685   FrD->setLexicalDeclContext(LexicalDC);
2686   LexicalDC->addDeclInternal(FrD);
2687   return FrD;
2688 }
2689 
2690 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2691   // Import the major distinguishing characteristics of an ivar.
2692   DeclContext *DC, *LexicalDC;
2693   DeclarationName Name;
2694   SourceLocation Loc;
2695   NamedDecl *ToD;
2696   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2697     return nullptr;
2698   if (ToD)
2699     return ToD;
2700 
2701   // Determine whether we've already imported this ivar
2702   SmallVector<NamedDecl *, 2> FoundDecls;
2703   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2704   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2705     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
2706       if (Importer.IsStructurallyEquivalent(D->getType(),
2707                                             FoundIvar->getType())) {
2708         Importer.Imported(D, FoundIvar);
2709         return FoundIvar;
2710       }
2711 
2712       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2713         << Name << D->getType() << FoundIvar->getType();
2714       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2715         << FoundIvar->getType();
2716       return nullptr;
2717     }
2718   }
2719 
2720   // Import the type.
2721   QualType T = Importer.Import(D->getType());
2722   if (T.isNull())
2723     return nullptr;
2724 
2725   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2726   Expr *BitWidth = Importer.Import(D->getBitWidth());
2727   if (!BitWidth && D->getBitWidth())
2728     return nullptr;
2729 
2730   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
2731                                               cast<ObjCContainerDecl>(DC),
2732                                        Importer.Import(D->getInnerLocStart()),
2733                                               Loc, Name.getAsIdentifierInfo(),
2734                                               T, TInfo, D->getAccessControl(),
2735                                               BitWidth, D->getSynthesize());
2736   ToIvar->setLexicalDeclContext(LexicalDC);
2737   Importer.Imported(D, ToIvar);
2738   LexicalDC->addDeclInternal(ToIvar);
2739   return ToIvar;
2740 
2741 }
2742 
2743 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2744   // Import the major distinguishing characteristics of a variable.
2745   DeclContext *DC, *LexicalDC;
2746   DeclarationName Name;
2747   SourceLocation Loc;
2748   NamedDecl *ToD;
2749   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2750     return nullptr;
2751   if (ToD)
2752     return ToD;
2753 
2754   // Try to find a variable in our own ("to") context with the same name and
2755   // in the same context as the variable we're importing.
2756   if (D->isFileVarDecl()) {
2757     VarDecl *MergeWithVar = nullptr;
2758     SmallVector<NamedDecl *, 4> ConflictingDecls;
2759     unsigned IDNS = Decl::IDNS_Ordinary;
2760     SmallVector<NamedDecl *, 2> FoundDecls;
2761     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2762     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2763       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2764         continue;
2765 
2766       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
2767         // We have found a variable that we may need to merge with. Check it.
2768         if (FoundVar->hasExternalFormalLinkage() &&
2769             D->hasExternalFormalLinkage()) {
2770           if (Importer.IsStructurallyEquivalent(D->getType(),
2771                                                 FoundVar->getType())) {
2772             MergeWithVar = FoundVar;
2773             break;
2774           }
2775 
2776           const ArrayType *FoundArray
2777             = Importer.getToContext().getAsArrayType(FoundVar->getType());
2778           const ArrayType *TArray
2779             = Importer.getToContext().getAsArrayType(D->getType());
2780           if (FoundArray && TArray) {
2781             if (isa<IncompleteArrayType>(FoundArray) &&
2782                 isa<ConstantArrayType>(TArray)) {
2783               // Import the type.
2784               QualType T = Importer.Import(D->getType());
2785               if (T.isNull())
2786                 return nullptr;
2787 
2788               FoundVar->setType(T);
2789               MergeWithVar = FoundVar;
2790               break;
2791             } else if (isa<IncompleteArrayType>(TArray) &&
2792                        isa<ConstantArrayType>(FoundArray)) {
2793               MergeWithVar = FoundVar;
2794               break;
2795             }
2796           }
2797 
2798           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2799             << Name << D->getType() << FoundVar->getType();
2800           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2801             << FoundVar->getType();
2802         }
2803       }
2804 
2805       ConflictingDecls.push_back(FoundDecls[I]);
2806     }
2807 
2808     if (MergeWithVar) {
2809       // An equivalent variable with external linkage has been found. Link
2810       // the two declarations, then merge them.
2811       Importer.Imported(D, MergeWithVar);
2812 
2813       if (VarDecl *DDef = D->getDefinition()) {
2814         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2815           Importer.ToDiag(ExistingDef->getLocation(),
2816                           diag::err_odr_variable_multiple_def)
2817             << Name;
2818           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2819         } else {
2820           Expr *Init = Importer.Import(DDef->getInit());
2821           MergeWithVar->setInit(Init);
2822           if (DDef->isInitKnownICE()) {
2823             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
2824             Eval->CheckedICE = true;
2825             Eval->IsICE = DDef->isInitICE();
2826           }
2827         }
2828       }
2829 
2830       return MergeWithVar;
2831     }
2832 
2833     if (!ConflictingDecls.empty()) {
2834       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2835                                          ConflictingDecls.data(),
2836                                          ConflictingDecls.size());
2837       if (!Name)
2838         return nullptr;
2839     }
2840   }
2841 
2842   // Import the type.
2843   QualType T = Importer.Import(D->getType());
2844   if (T.isNull())
2845     return nullptr;
2846 
2847   // Create the imported variable.
2848   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2849   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
2850                                    Importer.Import(D->getInnerLocStart()),
2851                                    Loc, Name.getAsIdentifierInfo(),
2852                                    T, TInfo,
2853                                    D->getStorageClass());
2854   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2855   ToVar->setAccess(D->getAccess());
2856   ToVar->setLexicalDeclContext(LexicalDC);
2857   Importer.Imported(D, ToVar);
2858 
2859   // Templated declarations should never appear in the enclosing DeclContext.
2860   if (!D->getDescribedVarTemplate())
2861     LexicalDC->addDeclInternal(ToVar);
2862 
2863   if (!D->isFileVarDecl() &&
2864       D->isUsed())
2865     ToVar->setIsUsed();
2866 
2867   // Merge the initializer.
2868   if (ImportDefinition(D, ToVar))
2869     return nullptr;
2870 
2871   if (D->isConstexpr())
2872     ToVar->setConstexpr(true);
2873 
2874   return ToVar;
2875 }
2876 
2877 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2878   // Parameters are created in the translation unit's context, then moved
2879   // into the function declaration's context afterward.
2880   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2881 
2882   // Import the name of this declaration.
2883   DeclarationName Name = Importer.Import(D->getDeclName());
2884   if (D->getDeclName() && !Name)
2885     return nullptr;
2886 
2887   // Import the location of this declaration.
2888   SourceLocation Loc = Importer.Import(D->getLocation());
2889 
2890   // Import the parameter's type.
2891   QualType T = Importer.Import(D->getType());
2892   if (T.isNull())
2893     return nullptr;
2894 
2895   // Create the imported parameter.
2896   auto *ToParm = ImplicitParamDecl::Create(Importer.getToContext(), DC, Loc,
2897                                            Name.getAsIdentifierInfo(), T,
2898                                            D->getParameterKind());
2899   return Importer.Imported(D, ToParm);
2900 }
2901 
2902 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2903   // Parameters are created in the translation unit's context, then moved
2904   // into the function declaration's context afterward.
2905   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2906 
2907   // Import the name of this declaration.
2908   DeclarationName Name = Importer.Import(D->getDeclName());
2909   if (D->getDeclName() && !Name)
2910     return nullptr;
2911 
2912   // Import the location of this declaration.
2913   SourceLocation Loc = Importer.Import(D->getLocation());
2914 
2915   // Import the parameter's type.
2916   QualType T = Importer.Import(D->getType());
2917   if (T.isNull())
2918     return nullptr;
2919 
2920   // Create the imported parameter.
2921   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2922   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2923                                      Importer.Import(D->getInnerLocStart()),
2924                                             Loc, Name.getAsIdentifierInfo(),
2925                                             T, TInfo, D->getStorageClass(),
2926                                             /*DefaultArg*/ nullptr);
2927 
2928   // Set the default argument.
2929   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
2930   ToParm->setKNRPromoted(D->isKNRPromoted());
2931 
2932   Expr *ToDefArg = nullptr;
2933   Expr *FromDefArg = nullptr;
2934   if (D->hasUninstantiatedDefaultArg()) {
2935     FromDefArg = D->getUninstantiatedDefaultArg();
2936     ToDefArg = Importer.Import(FromDefArg);
2937     ToParm->setUninstantiatedDefaultArg(ToDefArg);
2938   } else if (D->hasUnparsedDefaultArg()) {
2939     ToParm->setUnparsedDefaultArg();
2940   } else if (D->hasDefaultArg()) {
2941     FromDefArg = D->getDefaultArg();
2942     ToDefArg = Importer.Import(FromDefArg);
2943     ToParm->setDefaultArg(ToDefArg);
2944   }
2945   if (FromDefArg && !ToDefArg)
2946     return nullptr;
2947 
2948   if (D->isObjCMethodParameter()) {
2949     ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
2950     ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
2951   } else {
2952     ToParm->setScopeInfo(D->getFunctionScopeDepth(),
2953                          D->getFunctionScopeIndex());
2954   }
2955 
2956   if (D->isUsed())
2957     ToParm->setIsUsed();
2958 
2959   return Importer.Imported(D, ToParm);
2960 }
2961 
2962 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2963   // Import the major distinguishing characteristics of a method.
2964   DeclContext *DC, *LexicalDC;
2965   DeclarationName Name;
2966   SourceLocation Loc;
2967   NamedDecl *ToD;
2968   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2969     return nullptr;
2970   if (ToD)
2971     return ToD;
2972 
2973   SmallVector<NamedDecl *, 2> FoundDecls;
2974   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2975   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2976     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
2977       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2978         continue;
2979 
2980       // Check return types.
2981       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
2982                                              FoundMethod->getReturnType())) {
2983         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2984             << D->isInstanceMethod() << Name << D->getReturnType()
2985             << FoundMethod->getReturnType();
2986         Importer.ToDiag(FoundMethod->getLocation(),
2987                         diag::note_odr_objc_method_here)
2988           << D->isInstanceMethod() << Name;
2989         return nullptr;
2990       }
2991 
2992       // Check the number of parameters.
2993       if (D->param_size() != FoundMethod->param_size()) {
2994         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2995           << D->isInstanceMethod() << Name
2996           << D->param_size() << FoundMethod->param_size();
2997         Importer.ToDiag(FoundMethod->getLocation(),
2998                         diag::note_odr_objc_method_here)
2999           << D->isInstanceMethod() << Name;
3000         return nullptr;
3001       }
3002 
3003       // Check parameter types.
3004       for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3005              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3006            P != PEnd; ++P, ++FoundP) {
3007         if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3008                                                (*FoundP)->getType())) {
3009           Importer.FromDiag((*P)->getLocation(),
3010                             diag::err_odr_objc_method_param_type_inconsistent)
3011             << D->isInstanceMethod() << Name
3012             << (*P)->getType() << (*FoundP)->getType();
3013           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3014             << (*FoundP)->getType();
3015           return nullptr;
3016         }
3017       }
3018 
3019       // Check variadic/non-variadic.
3020       // Check the number of parameters.
3021       if (D->isVariadic() != FoundMethod->isVariadic()) {
3022         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3023           << D->isInstanceMethod() << Name;
3024         Importer.ToDiag(FoundMethod->getLocation(),
3025                         diag::note_odr_objc_method_here)
3026           << D->isInstanceMethod() << Name;
3027         return nullptr;
3028       }
3029 
3030       // FIXME: Any other bits we need to merge?
3031       return Importer.Imported(D, FoundMethod);
3032     }
3033   }
3034 
3035   // Import the result type.
3036   QualType ResultTy = Importer.Import(D->getReturnType());
3037   if (ResultTy.isNull())
3038     return nullptr;
3039 
3040   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3041 
3042   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3043       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3044       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3045       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3046       D->getImplementationControl(), D->hasRelatedResultType());
3047 
3048   // FIXME: When we decide to merge method definitions, we'll need to
3049   // deal with implicit parameters.
3050 
3051   // Import the parameters
3052   SmallVector<ParmVarDecl *, 5> ToParams;
3053   for (auto *FromP : D->parameters()) {
3054     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3055     if (!ToP)
3056       return nullptr;
3057 
3058     ToParams.push_back(ToP);
3059   }
3060 
3061   // Set the parameters.
3062   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3063     ToParams[I]->setOwningFunction(ToMethod);
3064     ToMethod->addDeclInternal(ToParams[I]);
3065   }
3066 
3067   SmallVector<SourceLocation, 12> SelLocs;
3068   D->getSelectorLocs(SelLocs);
3069   for (SourceLocation &Loc : SelLocs)
3070     Loc = Importer.Import(Loc);
3071 
3072   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3073 
3074   ToMethod->setLexicalDeclContext(LexicalDC);
3075   Importer.Imported(D, ToMethod);
3076   LexicalDC->addDeclInternal(ToMethod);
3077   return ToMethod;
3078 }
3079 
3080 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3081   // Import the major distinguishing characteristics of a category.
3082   DeclContext *DC, *LexicalDC;
3083   DeclarationName Name;
3084   SourceLocation Loc;
3085   NamedDecl *ToD;
3086   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3087     return nullptr;
3088   if (ToD)
3089     return ToD;
3090 
3091   TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3092   if (!BoundInfo)
3093     return nullptr;
3094 
3095   ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3096                                 Importer.getToContext(), DC,
3097                                 D->getVariance(),
3098                                 Importer.Import(D->getVarianceLoc()),
3099                                 D->getIndex(),
3100                                 Importer.Import(D->getLocation()),
3101                                 Name.getAsIdentifierInfo(),
3102                                 Importer.Import(D->getColonLoc()),
3103                                 BoundInfo);
3104   Importer.Imported(D, Result);
3105   Result->setLexicalDeclContext(LexicalDC);
3106   return Result;
3107 }
3108 
3109 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3110   // Import the major distinguishing characteristics of a category.
3111   DeclContext *DC, *LexicalDC;
3112   DeclarationName Name;
3113   SourceLocation Loc;
3114   NamedDecl *ToD;
3115   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3116     return nullptr;
3117   if (ToD)
3118     return ToD;
3119 
3120   ObjCInterfaceDecl *ToInterface
3121     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3122   if (!ToInterface)
3123     return nullptr;
3124 
3125   // Determine if we've already encountered this category.
3126   ObjCCategoryDecl *MergeWithCategory
3127     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3128   ObjCCategoryDecl *ToCategory = MergeWithCategory;
3129   if (!ToCategory) {
3130     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3131                                           Importer.Import(D->getAtStartLoc()),
3132                                           Loc,
3133                                        Importer.Import(D->getCategoryNameLoc()),
3134                                           Name.getAsIdentifierInfo(),
3135                                           ToInterface,
3136                                           /*TypeParamList=*/nullptr,
3137                                        Importer.Import(D->getIvarLBraceLoc()),
3138                                        Importer.Import(D->getIvarRBraceLoc()));
3139     ToCategory->setLexicalDeclContext(LexicalDC);
3140     LexicalDC->addDeclInternal(ToCategory);
3141     Importer.Imported(D, ToCategory);
3142     // Import the type parameter list after calling Imported, to avoid
3143     // loops when bringing in their DeclContext.
3144     ToCategory->setTypeParamList(ImportObjCTypeParamList(
3145                                    D->getTypeParamList()));
3146 
3147     // Import protocols
3148     SmallVector<ObjCProtocolDecl *, 4> Protocols;
3149     SmallVector<SourceLocation, 4> ProtocolLocs;
3150     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3151       = D->protocol_loc_begin();
3152     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3153                                           FromProtoEnd = D->protocol_end();
3154          FromProto != FromProtoEnd;
3155          ++FromProto, ++FromProtoLoc) {
3156       ObjCProtocolDecl *ToProto
3157         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3158       if (!ToProto)
3159         return nullptr;
3160       Protocols.push_back(ToProto);
3161       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3162     }
3163 
3164     // FIXME: If we're merging, make sure that the protocol list is the same.
3165     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3166                                 ProtocolLocs.data(), Importer.getToContext());
3167 
3168   } else {
3169     Importer.Imported(D, ToCategory);
3170   }
3171 
3172   // Import all of the members of this category.
3173   ImportDeclContext(D);
3174 
3175   // If we have an implementation, import it as well.
3176   if (D->getImplementation()) {
3177     ObjCCategoryImplDecl *Impl
3178       = cast_or_null<ObjCCategoryImplDecl>(
3179                                        Importer.Import(D->getImplementation()));
3180     if (!Impl)
3181       return nullptr;
3182 
3183     ToCategory->setImplementation(Impl);
3184   }
3185 
3186   return ToCategory;
3187 }
3188 
3189 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3190                                        ObjCProtocolDecl *To,
3191                                        ImportDefinitionKind Kind) {
3192   if (To->getDefinition()) {
3193     if (shouldForceImportDeclContext(Kind))
3194       ImportDeclContext(From);
3195     return false;
3196   }
3197 
3198   // Start the protocol definition
3199   To->startDefinition();
3200 
3201   // Import protocols
3202   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3203   SmallVector<SourceLocation, 4> ProtocolLocs;
3204   ObjCProtocolDecl::protocol_loc_iterator
3205   FromProtoLoc = From->protocol_loc_begin();
3206   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3207                                         FromProtoEnd = From->protocol_end();
3208        FromProto != FromProtoEnd;
3209        ++FromProto, ++FromProtoLoc) {
3210     ObjCProtocolDecl *ToProto
3211       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3212     if (!ToProto)
3213       return true;
3214     Protocols.push_back(ToProto);
3215     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3216   }
3217 
3218   // FIXME: If we're merging, make sure that the protocol list is the same.
3219   To->setProtocolList(Protocols.data(), Protocols.size(),
3220                       ProtocolLocs.data(), Importer.getToContext());
3221 
3222   if (shouldForceImportDeclContext(Kind)) {
3223     // Import all of the members of this protocol.
3224     ImportDeclContext(From, /*ForceImport=*/true);
3225   }
3226   return false;
3227 }
3228 
3229 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3230   // If this protocol has a definition in the translation unit we're coming
3231   // from, but this particular declaration is not that definition, import the
3232   // definition and map to that.
3233   ObjCProtocolDecl *Definition = D->getDefinition();
3234   if (Definition && Definition != D) {
3235     Decl *ImportedDef = Importer.Import(Definition);
3236     if (!ImportedDef)
3237       return nullptr;
3238 
3239     return Importer.Imported(D, ImportedDef);
3240   }
3241 
3242   // Import the major distinguishing characteristics of a protocol.
3243   DeclContext *DC, *LexicalDC;
3244   DeclarationName Name;
3245   SourceLocation Loc;
3246   NamedDecl *ToD;
3247   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3248     return nullptr;
3249   if (ToD)
3250     return ToD;
3251 
3252   ObjCProtocolDecl *MergeWithProtocol = nullptr;
3253   SmallVector<NamedDecl *, 2> FoundDecls;
3254   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3255   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3256     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3257       continue;
3258 
3259     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3260       break;
3261   }
3262 
3263   ObjCProtocolDecl *ToProto = MergeWithProtocol;
3264   if (!ToProto) {
3265     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3266                                        Name.getAsIdentifierInfo(), Loc,
3267                                        Importer.Import(D->getAtStartLoc()),
3268                                        /*PrevDecl=*/nullptr);
3269     ToProto->setLexicalDeclContext(LexicalDC);
3270     LexicalDC->addDeclInternal(ToProto);
3271   }
3272 
3273   Importer.Imported(D, ToProto);
3274 
3275   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3276     return nullptr;
3277 
3278   return ToProto;
3279 }
3280 
3281 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3282   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3283   DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3284 
3285   SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3286   SourceLocation LangLoc = Importer.Import(D->getLocation());
3287 
3288   bool HasBraces = D->hasBraces();
3289 
3290   LinkageSpecDecl *ToLinkageSpec =
3291     LinkageSpecDecl::Create(Importer.getToContext(),
3292                             DC,
3293                             ExternLoc,
3294                             LangLoc,
3295                             D->getLanguage(),
3296                             HasBraces);
3297 
3298   if (HasBraces) {
3299     SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3300     ToLinkageSpec->setRBraceLoc(RBraceLoc);
3301   }
3302 
3303   ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3304   LexicalDC->addDeclInternal(ToLinkageSpec);
3305 
3306   Importer.Imported(D, ToLinkageSpec);
3307 
3308   return ToLinkageSpec;
3309 }
3310 
3311 Decl *ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
3312   DeclContext *DC, *LexicalDC;
3313   DeclarationName Name;
3314   SourceLocation Loc;
3315   NamedDecl *ToD = nullptr;
3316   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3317     return nullptr;
3318   if (ToD)
3319     return ToD;
3320 
3321   DeclarationNameInfo NameInfo(Name,
3322                                Importer.Import(D->getNameInfo().getLoc()));
3323   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3324 
3325   UsingDecl *ToUsing = UsingDecl::Create(Importer.getToContext(), DC,
3326                                          Importer.Import(D->getUsingLoc()),
3327                                          Importer.Import(D->getQualifierLoc()),
3328                                          NameInfo, D->hasTypename());
3329   ToUsing->setLexicalDeclContext(LexicalDC);
3330   LexicalDC->addDeclInternal(ToUsing);
3331   Importer.Imported(D, ToUsing);
3332 
3333   if (NamedDecl *FromPattern =
3334       Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
3335     if (NamedDecl *ToPattern =
3336         dyn_cast_or_null<NamedDecl>(Importer.Import(FromPattern)))
3337       Importer.getToContext().setInstantiatedFromUsingDecl(ToUsing, ToPattern);
3338     else
3339       return nullptr;
3340   }
3341 
3342   for (UsingShadowDecl *FromShadow : D->shadows()) {
3343     if (UsingShadowDecl *ToShadow =
3344         dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromShadow)))
3345       ToUsing->addShadowDecl(ToShadow);
3346     else
3347       // FIXME: We return a nullptr here but the definition is already created
3348       // and available with lookups. How to fix this?..
3349       return nullptr;
3350   }
3351   return ToUsing;
3352 }
3353 
3354 Decl *ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
3355   DeclContext *DC, *LexicalDC;
3356   DeclarationName Name;
3357   SourceLocation Loc;
3358   NamedDecl *ToD = nullptr;
3359   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3360     return nullptr;
3361   if (ToD)
3362     return ToD;
3363 
3364   UsingDecl *ToUsing = dyn_cast_or_null<UsingDecl>(
3365         Importer.Import(D->getUsingDecl()));
3366   if (!ToUsing)
3367     return nullptr;
3368 
3369   NamedDecl *ToTarget = dyn_cast_or_null<NamedDecl>(
3370         Importer.Import(D->getTargetDecl()));
3371   if (!ToTarget)
3372     return nullptr;
3373 
3374   UsingShadowDecl *ToShadow = UsingShadowDecl::Create(
3375         Importer.getToContext(), DC, Loc, ToUsing, ToTarget);
3376 
3377   ToShadow->setLexicalDeclContext(LexicalDC);
3378   ToShadow->setAccess(D->getAccess());
3379   Importer.Imported(D, ToShadow);
3380 
3381   if (UsingShadowDecl *FromPattern =
3382       Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
3383     if (UsingShadowDecl *ToPattern =
3384         dyn_cast_or_null<UsingShadowDecl>(Importer.Import(FromPattern)))
3385       Importer.getToContext().setInstantiatedFromUsingShadowDecl(ToShadow,
3386                                                                  ToPattern);
3387     else
3388       // FIXME: We return a nullptr here but the definition is already created
3389       // and available with lookups. How to fix this?..
3390       return nullptr;
3391   }
3392 
3393   LexicalDC->addDeclInternal(ToShadow);
3394 
3395   return ToShadow;
3396 }
3397 
3398 
3399 Decl *ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3400   DeclContext *DC, *LexicalDC;
3401   DeclarationName Name;
3402   SourceLocation Loc;
3403   NamedDecl *ToD = nullptr;
3404   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3405     return nullptr;
3406   if (ToD)
3407     return ToD;
3408 
3409   DeclContext *ToComAncestor = Importer.ImportContext(D->getCommonAncestor());
3410   if (!ToComAncestor)
3411     return nullptr;
3412 
3413   NamespaceDecl *ToNominated = cast_or_null<NamespaceDecl>(
3414         Importer.Import(D->getNominatedNamespace()));
3415   if (!ToNominated)
3416     return nullptr;
3417 
3418   UsingDirectiveDecl *ToUsingDir = UsingDirectiveDecl::Create(
3419         Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()),
3420         Importer.Import(D->getNamespaceKeyLocation()),
3421         Importer.Import(D->getQualifierLoc()),
3422         Importer.Import(D->getIdentLocation()), ToNominated, ToComAncestor);
3423   ToUsingDir->setLexicalDeclContext(LexicalDC);
3424   LexicalDC->addDeclInternal(ToUsingDir);
3425   Importer.Imported(D, ToUsingDir);
3426 
3427   return ToUsingDir;
3428 }
3429 
3430 Decl *ASTNodeImporter::VisitUnresolvedUsingValueDecl(
3431     UnresolvedUsingValueDecl *D) {
3432   DeclContext *DC, *LexicalDC;
3433   DeclarationName Name;
3434   SourceLocation Loc;
3435   NamedDecl *ToD = nullptr;
3436   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3437     return nullptr;
3438   if (ToD)
3439     return ToD;
3440 
3441   DeclarationNameInfo NameInfo(Name, Importer.Import(D->getNameInfo().getLoc()));
3442   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3443 
3444   UnresolvedUsingValueDecl *ToUsingValue = UnresolvedUsingValueDecl::Create(
3445         Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()),
3446         Importer.Import(D->getQualifierLoc()), NameInfo,
3447         Importer.Import(D->getEllipsisLoc()));
3448 
3449   Importer.Imported(D, ToUsingValue);
3450   ToUsingValue->setAccess(D->getAccess());
3451   ToUsingValue->setLexicalDeclContext(LexicalDC);
3452   LexicalDC->addDeclInternal(ToUsingValue);
3453 
3454   return ToUsingValue;
3455 }
3456 
3457 Decl *ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
3458     UnresolvedUsingTypenameDecl *D) {
3459   DeclContext *DC, *LexicalDC;
3460   DeclarationName Name;
3461   SourceLocation Loc;
3462   NamedDecl *ToD = nullptr;
3463   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3464     return nullptr;
3465   if (ToD)
3466     return ToD;
3467 
3468   UnresolvedUsingTypenameDecl *ToUsing = UnresolvedUsingTypenameDecl::Create(
3469         Importer.getToContext(), DC, Importer.Import(D->getUsingLoc()),
3470         Importer.Import(D->getTypenameLoc()),
3471         Importer.Import(D->getQualifierLoc()), Loc, Name,
3472         Importer.Import(D->getEllipsisLoc()));
3473 
3474   Importer.Imported(D, ToUsing);
3475   ToUsing->setAccess(D->getAccess());
3476   ToUsing->setLexicalDeclContext(LexicalDC);
3477   LexicalDC->addDeclInternal(ToUsing);
3478 
3479   return ToUsing;
3480 }
3481 
3482 
3483 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3484                                        ObjCInterfaceDecl *To,
3485                                        ImportDefinitionKind Kind) {
3486   if (To->getDefinition()) {
3487     // Check consistency of superclass.
3488     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3489     if (FromSuper) {
3490       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3491       if (!FromSuper)
3492         return true;
3493     }
3494 
3495     ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3496     if ((bool)FromSuper != (bool)ToSuper ||
3497         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3498       Importer.ToDiag(To->getLocation(),
3499                       diag::err_odr_objc_superclass_inconsistent)
3500         << To->getDeclName();
3501       if (ToSuper)
3502         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3503           << To->getSuperClass()->getDeclName();
3504       else
3505         Importer.ToDiag(To->getLocation(),
3506                         diag::note_odr_objc_missing_superclass);
3507       if (From->getSuperClass())
3508         Importer.FromDiag(From->getSuperClassLoc(),
3509                           diag::note_odr_objc_superclass)
3510         << From->getSuperClass()->getDeclName();
3511       else
3512         Importer.FromDiag(From->getLocation(),
3513                           diag::note_odr_objc_missing_superclass);
3514     }
3515 
3516     if (shouldForceImportDeclContext(Kind))
3517       ImportDeclContext(From);
3518     return false;
3519   }
3520 
3521   // Start the definition.
3522   To->startDefinition();
3523 
3524   // If this class has a superclass, import it.
3525   if (From->getSuperClass()) {
3526     TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3527     if (!SuperTInfo)
3528       return true;
3529 
3530     To->setSuperClass(SuperTInfo);
3531   }
3532 
3533   // Import protocols
3534   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3535   SmallVector<SourceLocation, 4> ProtocolLocs;
3536   ObjCInterfaceDecl::protocol_loc_iterator
3537   FromProtoLoc = From->protocol_loc_begin();
3538 
3539   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3540                                          FromProtoEnd = From->protocol_end();
3541        FromProto != FromProtoEnd;
3542        ++FromProto, ++FromProtoLoc) {
3543     ObjCProtocolDecl *ToProto
3544       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3545     if (!ToProto)
3546       return true;
3547     Protocols.push_back(ToProto);
3548     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3549   }
3550 
3551   // FIXME: If we're merging, make sure that the protocol list is the same.
3552   To->setProtocolList(Protocols.data(), Protocols.size(),
3553                       ProtocolLocs.data(), Importer.getToContext());
3554 
3555   // Import categories. When the categories themselves are imported, they'll
3556   // hook themselves into this interface.
3557   for (auto *Cat : From->known_categories())
3558     Importer.Import(Cat);
3559 
3560   // If we have an @implementation, import it as well.
3561   if (From->getImplementation()) {
3562     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3563                                      Importer.Import(From->getImplementation()));
3564     if (!Impl)
3565       return true;
3566 
3567     To->setImplementation(Impl);
3568   }
3569 
3570   if (shouldForceImportDeclContext(Kind)) {
3571     // Import all of the members of this class.
3572     ImportDeclContext(From, /*ForceImport=*/true);
3573   }
3574   return false;
3575 }
3576 
3577 ObjCTypeParamList *
3578 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3579   if (!list)
3580     return nullptr;
3581 
3582   SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3583   for (auto fromTypeParam : *list) {
3584     auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3585                          Importer.Import(fromTypeParam));
3586     if (!toTypeParam)
3587       return nullptr;
3588 
3589     toTypeParams.push_back(toTypeParam);
3590   }
3591 
3592   return ObjCTypeParamList::create(Importer.getToContext(),
3593                                    Importer.Import(list->getLAngleLoc()),
3594                                    toTypeParams,
3595                                    Importer.Import(list->getRAngleLoc()));
3596 }
3597 
3598 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3599   // If this class has a definition in the translation unit we're coming from,
3600   // but this particular declaration is not that definition, import the
3601   // definition and map to that.
3602   ObjCInterfaceDecl *Definition = D->getDefinition();
3603   if (Definition && Definition != D) {
3604     Decl *ImportedDef = Importer.Import(Definition);
3605     if (!ImportedDef)
3606       return nullptr;
3607 
3608     return Importer.Imported(D, ImportedDef);
3609   }
3610 
3611   // Import the major distinguishing characteristics of an @interface.
3612   DeclContext *DC, *LexicalDC;
3613   DeclarationName Name;
3614   SourceLocation Loc;
3615   NamedDecl *ToD;
3616   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3617     return nullptr;
3618   if (ToD)
3619     return ToD;
3620 
3621   // Look for an existing interface with the same name.
3622   ObjCInterfaceDecl *MergeWithIface = nullptr;
3623   SmallVector<NamedDecl *, 2> FoundDecls;
3624   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3625   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3626     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3627       continue;
3628 
3629     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3630       break;
3631   }
3632 
3633   // Create an interface declaration, if one does not already exist.
3634   ObjCInterfaceDecl *ToIface = MergeWithIface;
3635   if (!ToIface) {
3636     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3637                                         Importer.Import(D->getAtStartLoc()),
3638                                         Name.getAsIdentifierInfo(),
3639                                         /*TypeParamList=*/nullptr,
3640                                         /*PrevDecl=*/nullptr, Loc,
3641                                         D->isImplicitInterfaceDecl());
3642     ToIface->setLexicalDeclContext(LexicalDC);
3643     LexicalDC->addDeclInternal(ToIface);
3644   }
3645   Importer.Imported(D, ToIface);
3646   // Import the type parameter list after calling Imported, to avoid
3647   // loops when bringing in their DeclContext.
3648   ToIface->setTypeParamList(ImportObjCTypeParamList(
3649                               D->getTypeParamListAsWritten()));
3650 
3651   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3652     return nullptr;
3653 
3654   return ToIface;
3655 }
3656 
3657 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3658   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3659                                         Importer.Import(D->getCategoryDecl()));
3660   if (!Category)
3661     return nullptr;
3662 
3663   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3664   if (!ToImpl) {
3665     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3666     if (!DC)
3667       return nullptr;
3668 
3669     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3670     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3671                                           Importer.Import(D->getIdentifier()),
3672                                           Category->getClassInterface(),
3673                                           Importer.Import(D->getLocation()),
3674                                           Importer.Import(D->getAtStartLoc()),
3675                                           CategoryNameLoc);
3676 
3677     DeclContext *LexicalDC = DC;
3678     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3679       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3680       if (!LexicalDC)
3681         return nullptr;
3682 
3683       ToImpl->setLexicalDeclContext(LexicalDC);
3684     }
3685 
3686     LexicalDC->addDeclInternal(ToImpl);
3687     Category->setImplementation(ToImpl);
3688   }
3689 
3690   Importer.Imported(D, ToImpl);
3691   ImportDeclContext(D);
3692   return ToImpl;
3693 }
3694 
3695 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3696   // Find the corresponding interface.
3697   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3698                                        Importer.Import(D->getClassInterface()));
3699   if (!Iface)
3700     return nullptr;
3701 
3702   // Import the superclass, if any.
3703   ObjCInterfaceDecl *Super = nullptr;
3704   if (D->getSuperClass()) {
3705     Super = cast_or_null<ObjCInterfaceDecl>(
3706                                           Importer.Import(D->getSuperClass()));
3707     if (!Super)
3708       return nullptr;
3709   }
3710 
3711   ObjCImplementationDecl *Impl = Iface->getImplementation();
3712   if (!Impl) {
3713     // We haven't imported an implementation yet. Create a new @implementation
3714     // now.
3715     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3716                                   Importer.ImportContext(D->getDeclContext()),
3717                                           Iface, Super,
3718                                           Importer.Import(D->getLocation()),
3719                                           Importer.Import(D->getAtStartLoc()),
3720                                           Importer.Import(D->getSuperClassLoc()),
3721                                           Importer.Import(D->getIvarLBraceLoc()),
3722                                           Importer.Import(D->getIvarRBraceLoc()));
3723 
3724     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3725       DeclContext *LexicalDC
3726         = Importer.ImportContext(D->getLexicalDeclContext());
3727       if (!LexicalDC)
3728         return nullptr;
3729       Impl->setLexicalDeclContext(LexicalDC);
3730     }
3731 
3732     // Associate the implementation with the class it implements.
3733     Iface->setImplementation(Impl);
3734     Importer.Imported(D, Iface->getImplementation());
3735   } else {
3736     Importer.Imported(D, Iface->getImplementation());
3737 
3738     // Verify that the existing @implementation has the same superclass.
3739     if ((Super && !Impl->getSuperClass()) ||
3740         (!Super && Impl->getSuperClass()) ||
3741         (Super && Impl->getSuperClass() &&
3742          !declaresSameEntity(Super->getCanonicalDecl(),
3743                              Impl->getSuperClass()))) {
3744       Importer.ToDiag(Impl->getLocation(),
3745                       diag::err_odr_objc_superclass_inconsistent)
3746         << Iface->getDeclName();
3747       // FIXME: It would be nice to have the location of the superclass
3748       // below.
3749       if (Impl->getSuperClass())
3750         Importer.ToDiag(Impl->getLocation(),
3751                         diag::note_odr_objc_superclass)
3752         << Impl->getSuperClass()->getDeclName();
3753       else
3754         Importer.ToDiag(Impl->getLocation(),
3755                         diag::note_odr_objc_missing_superclass);
3756       if (D->getSuperClass())
3757         Importer.FromDiag(D->getLocation(),
3758                           diag::note_odr_objc_superclass)
3759         << D->getSuperClass()->getDeclName();
3760       else
3761         Importer.FromDiag(D->getLocation(),
3762                           diag::note_odr_objc_missing_superclass);
3763       return nullptr;
3764     }
3765   }
3766 
3767   // Import all of the members of this @implementation.
3768   ImportDeclContext(D);
3769 
3770   return Impl;
3771 }
3772 
3773 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3774   // Import the major distinguishing characteristics of an @property.
3775   DeclContext *DC, *LexicalDC;
3776   DeclarationName Name;
3777   SourceLocation Loc;
3778   NamedDecl *ToD;
3779   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3780     return nullptr;
3781   if (ToD)
3782     return ToD;
3783 
3784   // Check whether we have already imported this property.
3785   SmallVector<NamedDecl *, 2> FoundDecls;
3786   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3787   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3788     if (ObjCPropertyDecl *FoundProp
3789                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3790       // Check property types.
3791       if (!Importer.IsStructurallyEquivalent(D->getType(),
3792                                              FoundProp->getType())) {
3793         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3794           << Name << D->getType() << FoundProp->getType();
3795         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3796           << FoundProp->getType();
3797         return nullptr;
3798       }
3799 
3800       // FIXME: Check property attributes, getters, setters, etc.?
3801 
3802       // Consider these properties to be equivalent.
3803       Importer.Imported(D, FoundProp);
3804       return FoundProp;
3805     }
3806   }
3807 
3808   // Import the type.
3809   TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
3810   if (!TSI)
3811     return nullptr;
3812 
3813   // Create the new property.
3814   ObjCPropertyDecl *ToProperty
3815     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3816                                Name.getAsIdentifierInfo(),
3817                                Importer.Import(D->getAtLoc()),
3818                                Importer.Import(D->getLParenLoc()),
3819                                Importer.Import(D->getType()),
3820                                TSI,
3821                                D->getPropertyImplementation());
3822   Importer.Imported(D, ToProperty);
3823   ToProperty->setLexicalDeclContext(LexicalDC);
3824   LexicalDC->addDeclInternal(ToProperty);
3825 
3826   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3827   ToProperty->setPropertyAttributesAsWritten(
3828                                       D->getPropertyAttributesAsWritten());
3829   ToProperty->setGetterName(Importer.Import(D->getGetterName()),
3830                             Importer.Import(D->getGetterNameLoc()));
3831   ToProperty->setSetterName(Importer.Import(D->getSetterName()),
3832                             Importer.Import(D->getSetterNameLoc()));
3833   ToProperty->setGetterMethodDecl(
3834      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3835   ToProperty->setSetterMethodDecl(
3836      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3837   ToProperty->setPropertyIvarDecl(
3838        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3839   return ToProperty;
3840 }
3841 
3842 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3843   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3844                                         Importer.Import(D->getPropertyDecl()));
3845   if (!Property)
3846     return nullptr;
3847 
3848   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3849   if (!DC)
3850     return nullptr;
3851 
3852   // Import the lexical declaration context.
3853   DeclContext *LexicalDC = DC;
3854   if (D->getDeclContext() != D->getLexicalDeclContext()) {
3855     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3856     if (!LexicalDC)
3857       return nullptr;
3858   }
3859 
3860   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3861   if (!InImpl)
3862     return nullptr;
3863 
3864   // Import the ivar (for an @synthesize).
3865   ObjCIvarDecl *Ivar = nullptr;
3866   if (D->getPropertyIvarDecl()) {
3867     Ivar = cast_or_null<ObjCIvarDecl>(
3868                                     Importer.Import(D->getPropertyIvarDecl()));
3869     if (!Ivar)
3870       return nullptr;
3871   }
3872 
3873   ObjCPropertyImplDecl *ToImpl
3874     = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
3875                                    Property->getQueryKind());
3876   if (!ToImpl) {
3877     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3878                                           Importer.Import(D->getLocStart()),
3879                                           Importer.Import(D->getLocation()),
3880                                           Property,
3881                                           D->getPropertyImplementation(),
3882                                           Ivar,
3883                                   Importer.Import(D->getPropertyIvarDeclLoc()));
3884     ToImpl->setLexicalDeclContext(LexicalDC);
3885     Importer.Imported(D, ToImpl);
3886     LexicalDC->addDeclInternal(ToImpl);
3887   } else {
3888     // Check that we have the same kind of property implementation (@synthesize
3889     // vs. @dynamic).
3890     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3891       Importer.ToDiag(ToImpl->getLocation(),
3892                       diag::err_odr_objc_property_impl_kind_inconsistent)
3893         << Property->getDeclName()
3894         << (ToImpl->getPropertyImplementation()
3895                                               == ObjCPropertyImplDecl::Dynamic);
3896       Importer.FromDiag(D->getLocation(),
3897                         diag::note_odr_objc_property_impl_kind)
3898         << D->getPropertyDecl()->getDeclName()
3899         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3900       return nullptr;
3901     }
3902 
3903     // For @synthesize, check that we have the same
3904     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3905         Ivar != ToImpl->getPropertyIvarDecl()) {
3906       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3907                       diag::err_odr_objc_synthesize_ivar_inconsistent)
3908         << Property->getDeclName()
3909         << ToImpl->getPropertyIvarDecl()->getDeclName()
3910         << Ivar->getDeclName();
3911       Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3912                         diag::note_odr_objc_synthesize_ivar_here)
3913         << D->getPropertyIvarDecl()->getDeclName();
3914       return nullptr;
3915     }
3916 
3917     // Merge the existing implementation with the new implementation.
3918     Importer.Imported(D, ToImpl);
3919   }
3920 
3921   return ToImpl;
3922 }
3923 
3924 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3925   // For template arguments, we adopt the translation unit as our declaration
3926   // context. This context will be fixed when the actual template declaration
3927   // is created.
3928 
3929   // FIXME: Import default argument.
3930   return TemplateTypeParmDecl::Create(Importer.getToContext(),
3931                               Importer.getToContext().getTranslationUnitDecl(),
3932                                       Importer.Import(D->getLocStart()),
3933                                       Importer.Import(D->getLocation()),
3934                                       D->getDepth(),
3935                                       D->getIndex(),
3936                                       Importer.Import(D->getIdentifier()),
3937                                       D->wasDeclaredWithTypename(),
3938                                       D->isParameterPack());
3939 }
3940 
3941 Decl *
3942 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3943   // Import the name of this declaration.
3944   DeclarationName Name = Importer.Import(D->getDeclName());
3945   if (D->getDeclName() && !Name)
3946     return nullptr;
3947 
3948   // Import the location of this declaration.
3949   SourceLocation Loc = Importer.Import(D->getLocation());
3950 
3951   // Import the type of this declaration.
3952   QualType T = Importer.Import(D->getType());
3953   if (T.isNull())
3954     return nullptr;
3955 
3956   // Import type-source information.
3957   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3958   if (D->getTypeSourceInfo() && !TInfo)
3959     return nullptr;
3960 
3961   // FIXME: Import default argument.
3962 
3963   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3964                                Importer.getToContext().getTranslationUnitDecl(),
3965                                          Importer.Import(D->getInnerLocStart()),
3966                                          Loc, D->getDepth(), D->getPosition(),
3967                                          Name.getAsIdentifierInfo(),
3968                                          T, D->isParameterPack(), TInfo);
3969 }
3970 
3971 Decl *
3972 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3973   // Import the name of this declaration.
3974   DeclarationName Name = Importer.Import(D->getDeclName());
3975   if (D->getDeclName() && !Name)
3976     return nullptr;
3977 
3978   // Import the location of this declaration.
3979   SourceLocation Loc = Importer.Import(D->getLocation());
3980 
3981   // Import template parameters.
3982   TemplateParameterList *TemplateParams
3983     = ImportTemplateParameterList(D->getTemplateParameters());
3984   if (!TemplateParams)
3985     return nullptr;
3986 
3987   // FIXME: Import default argument.
3988 
3989   return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3990                               Importer.getToContext().getTranslationUnitDecl(),
3991                                           Loc, D->getDepth(), D->getPosition(),
3992                                           D->isParameterPack(),
3993                                           Name.getAsIdentifierInfo(),
3994                                           TemplateParams);
3995 }
3996 
3997 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3998   // If this record has a definition in the translation unit we're coming from,
3999   // but this particular declaration is not that definition, import the
4000   // definition and map to that.
4001   CXXRecordDecl *Definition
4002     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4003   if (Definition && Definition != D->getTemplatedDecl()) {
4004     Decl *ImportedDef
4005       = Importer.Import(Definition->getDescribedClassTemplate());
4006     if (!ImportedDef)
4007       return nullptr;
4008 
4009     return Importer.Imported(D, ImportedDef);
4010   }
4011 
4012   // Import the major distinguishing characteristics of this class template.
4013   DeclContext *DC, *LexicalDC;
4014   DeclarationName Name;
4015   SourceLocation Loc;
4016   NamedDecl *ToD;
4017   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4018     return nullptr;
4019   if (ToD)
4020     return ToD;
4021 
4022   // We may already have a template of the same name; try to find and match it.
4023   if (!DC->isFunctionOrMethod()) {
4024     SmallVector<NamedDecl *, 4> ConflictingDecls;
4025     SmallVector<NamedDecl *, 2> FoundDecls;
4026     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4027     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4028       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4029         continue;
4030 
4031       Decl *Found = FoundDecls[I];
4032       if (ClassTemplateDecl *FoundTemplate
4033                                         = dyn_cast<ClassTemplateDecl>(Found)) {
4034         if (IsStructuralMatch(D, FoundTemplate)) {
4035           // The class templates structurally match; call it the same template.
4036           // FIXME: We may be filling in a forward declaration here. Handle
4037           // this case!
4038           Importer.Imported(D->getTemplatedDecl(),
4039                             FoundTemplate->getTemplatedDecl());
4040           return Importer.Imported(D, FoundTemplate);
4041         }
4042       }
4043 
4044       ConflictingDecls.push_back(FoundDecls[I]);
4045     }
4046 
4047     if (!ConflictingDecls.empty()) {
4048       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4049                                          ConflictingDecls.data(),
4050                                          ConflictingDecls.size());
4051     }
4052 
4053     if (!Name)
4054       return nullptr;
4055   }
4056 
4057   CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
4058 
4059   // Create the declaration that is being templated.
4060   CXXRecordDecl *ToTemplated = cast_or_null<CXXRecordDecl>(
4061         Importer.Import(FromTemplated));
4062   if (!ToTemplated)
4063     return nullptr;
4064 
4065   // Resolve possible cyclic import.
4066   if (Decl *AlreadyImported = Importer.GetAlreadyImportedOrNull(D))
4067     return AlreadyImported;
4068 
4069   // Create the class template declaration itself.
4070   TemplateParameterList *TemplateParams =
4071       ImportTemplateParameterList(D->getTemplateParameters());
4072   if (!TemplateParams)
4073     return nullptr;
4074 
4075   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4076                                                     Loc, Name, TemplateParams,
4077                                                     ToTemplated);
4078   ToTemplated->setDescribedClassTemplate(D2);
4079 
4080   D2->setAccess(D->getAccess());
4081   D2->setLexicalDeclContext(LexicalDC);
4082   LexicalDC->addDeclInternal(D2);
4083 
4084   // Note the relationship between the class templates.
4085   Importer.Imported(D, D2);
4086   Importer.Imported(FromTemplated, ToTemplated);
4087 
4088   if (FromTemplated->isCompleteDefinition() &&
4089       !ToTemplated->isCompleteDefinition()) {
4090     // FIXME: Import definition!
4091   }
4092 
4093   return D2;
4094 }
4095 
4096 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4097                                           ClassTemplateSpecializationDecl *D) {
4098   // If this record has a definition in the translation unit we're coming from,
4099   // but this particular declaration is not that definition, import the
4100   // definition and map to that.
4101   TagDecl *Definition = D->getDefinition();
4102   if (Definition && Definition != D) {
4103     Decl *ImportedDef = Importer.Import(Definition);
4104     if (!ImportedDef)
4105       return nullptr;
4106 
4107     return Importer.Imported(D, ImportedDef);
4108   }
4109 
4110   ClassTemplateDecl *ClassTemplate
4111     = cast_or_null<ClassTemplateDecl>(Importer.Import(
4112                                                  D->getSpecializedTemplate()));
4113   if (!ClassTemplate)
4114     return nullptr;
4115 
4116   // Import the context of this declaration.
4117   DeclContext *DC = ClassTemplate->getDeclContext();
4118   if (!DC)
4119     return nullptr;
4120 
4121   DeclContext *LexicalDC = DC;
4122   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4123     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4124     if (!LexicalDC)
4125       return nullptr;
4126   }
4127 
4128   // Import the location of this declaration.
4129   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4130   SourceLocation IdLoc = Importer.Import(D->getLocation());
4131 
4132   // Import template arguments.
4133   SmallVector<TemplateArgument, 2> TemplateArgs;
4134   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4135                               D->getTemplateArgs().size(),
4136                               TemplateArgs))
4137     return nullptr;
4138 
4139   // Try to find an existing specialization with these template arguments.
4140   void *InsertPos = nullptr;
4141   ClassTemplateSpecializationDecl *D2
4142     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4143   if (D2) {
4144     // We already have a class template specialization with these template
4145     // arguments.
4146 
4147     // FIXME: Check for specialization vs. instantiation errors.
4148 
4149     if (RecordDecl *FoundDef = D2->getDefinition()) {
4150       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4151         // The record types structurally match, or the "from" translation
4152         // unit only had a forward declaration anyway; call it the same
4153         // function.
4154         return Importer.Imported(D, FoundDef);
4155       }
4156     }
4157   } else {
4158     // Create a new specialization.
4159     if (ClassTemplatePartialSpecializationDecl *PartialSpec =
4160         dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
4161 
4162       // Import TemplateArgumentListInfo
4163       TemplateArgumentListInfo ToTAInfo;
4164       const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
4165       if (ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
4166         return nullptr;
4167 
4168       QualType CanonInjType = Importer.Import(
4169             PartialSpec->getInjectedSpecializationType());
4170       if (CanonInjType.isNull())
4171         return nullptr;
4172       CanonInjType = CanonInjType.getCanonicalType();
4173 
4174       TemplateParameterList *ToTPList = ImportTemplateParameterList(
4175             PartialSpec->getTemplateParameters());
4176       if (!ToTPList && PartialSpec->getTemplateParameters())
4177         return nullptr;
4178 
4179       D2 = ClassTemplatePartialSpecializationDecl::Create(
4180             Importer.getToContext(), D->getTagKind(), DC, StartLoc, IdLoc,
4181             ToTPList, ClassTemplate,
4182             llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
4183             ToTAInfo, CanonInjType, nullptr);
4184 
4185     } else {
4186       D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4187                                                    D->getTagKind(), DC,
4188                                                    StartLoc, IdLoc,
4189                                                    ClassTemplate,
4190                                                    TemplateArgs,
4191                                                    /*PrevDecl=*/nullptr);
4192     }
4193 
4194     D2->setSpecializationKind(D->getSpecializationKind());
4195 
4196     // Add this specialization to the class template.
4197     ClassTemplate->AddSpecialization(D2, InsertPos);
4198 
4199     // Import the qualifier, if any.
4200     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4201 
4202     Importer.Imported(D, D2);
4203 
4204     if (auto *TSI = D->getTypeAsWritten()) {
4205       TypeSourceInfo *TInfo = Importer.Import(TSI);
4206       if (!TInfo)
4207         return nullptr;
4208       D2->setTypeAsWritten(TInfo);
4209       D2->setTemplateKeywordLoc(Importer.Import(D->getTemplateKeywordLoc()));
4210       D2->setExternLoc(Importer.Import(D->getExternLoc()));
4211     }
4212 
4213     SourceLocation POI = Importer.Import(D->getPointOfInstantiation());
4214     if (POI.isValid())
4215       D2->setPointOfInstantiation(POI);
4216     else if (D->getPointOfInstantiation().isValid())
4217       return nullptr;
4218 
4219     D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
4220 
4221     // Add the specialization to this context.
4222     D2->setLexicalDeclContext(LexicalDC);
4223     LexicalDC->addDeclInternal(D2);
4224   }
4225   Importer.Imported(D, D2);
4226   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4227     return nullptr;
4228 
4229   return D2;
4230 }
4231 
4232 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4233   // If this variable has a definition in the translation unit we're coming
4234   // from,
4235   // but this particular declaration is not that definition, import the
4236   // definition and map to that.
4237   VarDecl *Definition =
4238       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4239   if (Definition && Definition != D->getTemplatedDecl()) {
4240     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4241     if (!ImportedDef)
4242       return nullptr;
4243 
4244     return Importer.Imported(D, ImportedDef);
4245   }
4246 
4247   // Import the major distinguishing characteristics of this variable template.
4248   DeclContext *DC, *LexicalDC;
4249   DeclarationName Name;
4250   SourceLocation Loc;
4251   NamedDecl *ToD;
4252   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4253     return nullptr;
4254   if (ToD)
4255     return ToD;
4256 
4257   // We may already have a template of the same name; try to find and match it.
4258   assert(!DC->isFunctionOrMethod() &&
4259          "Variable templates cannot be declared at function scope");
4260   SmallVector<NamedDecl *, 4> ConflictingDecls;
4261   SmallVector<NamedDecl *, 2> FoundDecls;
4262   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4263   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4264     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4265       continue;
4266 
4267     Decl *Found = FoundDecls[I];
4268     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4269       if (IsStructuralMatch(D, FoundTemplate)) {
4270         // The variable templates structurally match; call it the same template.
4271         Importer.Imported(D->getTemplatedDecl(),
4272                           FoundTemplate->getTemplatedDecl());
4273         return Importer.Imported(D, FoundTemplate);
4274       }
4275     }
4276 
4277     ConflictingDecls.push_back(FoundDecls[I]);
4278   }
4279 
4280   if (!ConflictingDecls.empty()) {
4281     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4282                                        ConflictingDecls.data(),
4283                                        ConflictingDecls.size());
4284   }
4285 
4286   if (!Name)
4287     return nullptr;
4288 
4289   VarDecl *DTemplated = D->getTemplatedDecl();
4290 
4291   // Import the type.
4292   QualType T = Importer.Import(DTemplated->getType());
4293   if (T.isNull())
4294     return nullptr;
4295 
4296   // Create the declaration that is being templated.
4297   auto *ToTemplated = dyn_cast_or_null<VarDecl>(Importer.Import(DTemplated));
4298   if (!ToTemplated)
4299     return nullptr;
4300 
4301   // Create the variable template declaration itself.
4302   TemplateParameterList *TemplateParams =
4303       ImportTemplateParameterList(D->getTemplateParameters());
4304   if (!TemplateParams)
4305     return nullptr;
4306 
4307   VarTemplateDecl *ToVarTD = VarTemplateDecl::Create(
4308       Importer.getToContext(), DC, Loc, Name, TemplateParams, ToTemplated);
4309   ToTemplated->setDescribedVarTemplate(ToVarTD);
4310 
4311   ToVarTD->setAccess(D->getAccess());
4312   ToVarTD->setLexicalDeclContext(LexicalDC);
4313   LexicalDC->addDeclInternal(ToVarTD);
4314 
4315   // Note the relationship between the variable templates.
4316   Importer.Imported(D, ToVarTD);
4317   Importer.Imported(DTemplated, ToTemplated);
4318 
4319   if (DTemplated->isThisDeclarationADefinition() &&
4320       !ToTemplated->isThisDeclarationADefinition()) {
4321     // FIXME: Import definition!
4322   }
4323 
4324   return ToVarTD;
4325 }
4326 
4327 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4328     VarTemplateSpecializationDecl *D) {
4329   // If this record has a definition in the translation unit we're coming from,
4330   // but this particular declaration is not that definition, import the
4331   // definition and map to that.
4332   VarDecl *Definition = D->getDefinition();
4333   if (Definition && Definition != D) {
4334     Decl *ImportedDef = Importer.Import(Definition);
4335     if (!ImportedDef)
4336       return nullptr;
4337 
4338     return Importer.Imported(D, ImportedDef);
4339   }
4340 
4341   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4342       Importer.Import(D->getSpecializedTemplate()));
4343   if (!VarTemplate)
4344     return nullptr;
4345 
4346   // Import the context of this declaration.
4347   DeclContext *DC = VarTemplate->getDeclContext();
4348   if (!DC)
4349     return nullptr;
4350 
4351   DeclContext *LexicalDC = DC;
4352   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4353     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4354     if (!LexicalDC)
4355       return nullptr;
4356   }
4357 
4358   // Import the location of this declaration.
4359   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4360   SourceLocation IdLoc = Importer.Import(D->getLocation());
4361 
4362   // Import template arguments.
4363   SmallVector<TemplateArgument, 2> TemplateArgs;
4364   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4365                               D->getTemplateArgs().size(), TemplateArgs))
4366     return nullptr;
4367 
4368   // Try to find an existing specialization with these template arguments.
4369   void *InsertPos = nullptr;
4370   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4371       TemplateArgs, InsertPos);
4372   if (D2) {
4373     // We already have a variable template specialization with these template
4374     // arguments.
4375 
4376     // FIXME: Check for specialization vs. instantiation errors.
4377 
4378     if (VarDecl *FoundDef = D2->getDefinition()) {
4379       if (!D->isThisDeclarationADefinition() ||
4380           IsStructuralMatch(D, FoundDef)) {
4381         // The record types structurally match, or the "from" translation
4382         // unit only had a forward declaration anyway; call it the same
4383         // variable.
4384         return Importer.Imported(D, FoundDef);
4385       }
4386     }
4387   } else {
4388 
4389     // Import the type.
4390     QualType T = Importer.Import(D->getType());
4391     if (T.isNull())
4392       return nullptr;
4393 
4394     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4395     if (D->getTypeSourceInfo() && !TInfo)
4396       return nullptr;
4397 
4398     TemplateArgumentListInfo ToTAInfo;
4399     if (ImportTemplateArgumentListInfo(D->getTemplateArgsInfo(), ToTAInfo))
4400       return nullptr;
4401 
4402     using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
4403     // Create a new specialization.
4404     if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
4405       // Import TemplateArgumentListInfo
4406       TemplateArgumentListInfo ArgInfos;
4407       const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
4408       // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
4409       if (ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ArgInfos))
4410         return nullptr;
4411 
4412       TemplateParameterList *ToTPList = ImportTemplateParameterList(
4413             FromPartial->getTemplateParameters());
4414       if (!ToTPList)
4415         return nullptr;
4416 
4417       auto *ToPartial = PartVarSpecDecl::Create(
4418           Importer.getToContext(), DC, StartLoc, IdLoc, ToTPList, VarTemplate,
4419           T, TInfo, D->getStorageClass(), TemplateArgs, ArgInfos);
4420 
4421       auto *FromInst = FromPartial->getInstantiatedFromMember();
4422       auto *ToInst = cast_or_null<PartVarSpecDecl>(Importer.Import(FromInst));
4423       if (FromInst && !ToInst)
4424         return nullptr;
4425 
4426       ToPartial->setInstantiatedFromMember(ToInst);
4427       if (FromPartial->isMemberSpecialization())
4428         ToPartial->setMemberSpecialization();
4429 
4430       D2 = ToPartial;
4431 
4432     } else { // Full specialization
4433       D2 = VarTemplateSpecializationDecl::Create(
4434           Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4435           D->getStorageClass(), TemplateArgs);
4436     }
4437 
4438     SourceLocation POI = D->getPointOfInstantiation();
4439     if (POI.isValid())
4440       D2->setPointOfInstantiation(Importer.Import(POI));
4441 
4442     D2->setSpecializationKind(D->getSpecializationKind());
4443     D2->setTemplateArgsInfo(ToTAInfo);
4444 
4445     // Add this specialization to the class template.
4446     VarTemplate->AddSpecialization(D2, InsertPos);
4447 
4448     // Import the qualifier, if any.
4449     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4450 
4451     if (D->isConstexpr())
4452       D2->setConstexpr(true);
4453 
4454     // Add the specialization to this context.
4455     D2->setLexicalDeclContext(LexicalDC);
4456     LexicalDC->addDeclInternal(D2);
4457 
4458     D2->setAccess(D->getAccess());
4459   }
4460 
4461   Importer.Imported(D, D2);
4462 
4463   // NOTE: isThisDeclarationADefinition() can return DeclarationOnly even if
4464   // declaration has initializer. Should this be fixed in the AST?.. Anyway,
4465   // we have to check the declaration for initializer - otherwise, it won't be
4466   // imported.
4467   if ((D->isThisDeclarationADefinition() || D->hasInit()) &&
4468       ImportDefinition(D, D2))
4469     return nullptr;
4470 
4471   return D2;
4472 }
4473 
4474 Decl *ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
4475   DeclContext *DC, *LexicalDC;
4476   DeclarationName Name;
4477   SourceLocation Loc;
4478   NamedDecl *ToD;
4479 
4480   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4481     return nullptr;
4482 
4483   if (ToD)
4484     return ToD;
4485 
4486   // Try to find a function in our own ("to") context with the same name, same
4487   // type, and in the same context as the function we're importing.
4488   if (!LexicalDC->isFunctionOrMethod()) {
4489     unsigned IDNS = Decl::IDNS_Ordinary;
4490     SmallVector<NamedDecl *, 2> FoundDecls;
4491     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4492     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4493       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
4494         continue;
4495 
4496       if (FunctionTemplateDecl *FoundFunction =
4497               dyn_cast<FunctionTemplateDecl>(FoundDecls[I])) {
4498         if (FoundFunction->hasExternalFormalLinkage() &&
4499             D->hasExternalFormalLinkage()) {
4500           if (IsStructuralMatch(D, FoundFunction)) {
4501             Importer.Imported(D, FoundFunction);
4502             // FIXME: Actually try to merge the body and other attributes.
4503             return FoundFunction;
4504           }
4505         }
4506       }
4507     }
4508   }
4509 
4510   TemplateParameterList *Params =
4511       ImportTemplateParameterList(D->getTemplateParameters());
4512   if (!Params)
4513     return nullptr;
4514 
4515   FunctionDecl *TemplatedFD =
4516       cast_or_null<FunctionDecl>(Importer.Import(D->getTemplatedDecl()));
4517   if (!TemplatedFD)
4518     return nullptr;
4519 
4520   FunctionTemplateDecl *ToFunc = FunctionTemplateDecl::Create(
4521       Importer.getToContext(), DC, Loc, Name, Params, TemplatedFD);
4522 
4523   TemplatedFD->setDescribedFunctionTemplate(ToFunc);
4524   ToFunc->setAccess(D->getAccess());
4525   ToFunc->setLexicalDeclContext(LexicalDC);
4526   Importer.Imported(D, ToFunc);
4527 
4528   LexicalDC->addDeclInternal(ToFunc);
4529   return ToFunc;
4530 }
4531 
4532 //----------------------------------------------------------------------------
4533 // Import Statements
4534 //----------------------------------------------------------------------------
4535 
4536 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4537   if (DG.isNull())
4538     return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4539   size_t NumDecls = DG.end() - DG.begin();
4540   SmallVector<Decl *, 1> ToDecls(NumDecls);
4541   auto &_Importer = this->Importer;
4542   std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4543     [&_Importer](Decl *D) -> Decl * {
4544       return _Importer.Import(D);
4545     });
4546   return DeclGroupRef::Create(Importer.getToContext(),
4547                               ToDecls.begin(),
4548                               NumDecls);
4549 }
4550 
4551  Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4552    Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4553      << S->getStmtClassName();
4554    return nullptr;
4555  }
4556 
4557 
4558 Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
4559   SmallVector<IdentifierInfo *, 4> Names;
4560   for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4561     IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
4562     // ToII is nullptr when no symbolic name is given for output operand
4563     // see ParseStmtAsm::ParseAsmOperandsOpt
4564     if (!ToII && S->getOutputIdentifier(I))
4565       return nullptr;
4566     Names.push_back(ToII);
4567   }
4568   for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4569     IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
4570     // ToII is nullptr when no symbolic name is given for input operand
4571     // see ParseStmtAsm::ParseAsmOperandsOpt
4572     if (!ToII && S->getInputIdentifier(I))
4573       return nullptr;
4574     Names.push_back(ToII);
4575   }
4576 
4577   SmallVector<StringLiteral *, 4> Clobbers;
4578   for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
4579     StringLiteral *Clobber = cast_or_null<StringLiteral>(
4580           Importer.Import(S->getClobberStringLiteral(I)));
4581     if (!Clobber)
4582       return nullptr;
4583     Clobbers.push_back(Clobber);
4584   }
4585 
4586   SmallVector<StringLiteral *, 4> Constraints;
4587   for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4588     StringLiteral *Output = cast_or_null<StringLiteral>(
4589           Importer.Import(S->getOutputConstraintLiteral(I)));
4590     if (!Output)
4591       return nullptr;
4592     Constraints.push_back(Output);
4593   }
4594 
4595   for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4596     StringLiteral *Input = cast_or_null<StringLiteral>(
4597           Importer.Import(S->getInputConstraintLiteral(I)));
4598     if (!Input)
4599       return nullptr;
4600     Constraints.push_back(Input);
4601   }
4602 
4603   SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
4604   if (ImportContainerChecked(S->outputs(), Exprs))
4605     return nullptr;
4606 
4607   if (ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
4608     return nullptr;
4609 
4610   StringLiteral *AsmStr = cast_or_null<StringLiteral>(
4611         Importer.Import(S->getAsmString()));
4612   if (!AsmStr)
4613     return nullptr;
4614 
4615   return new (Importer.getToContext()) GCCAsmStmt(
4616         Importer.getToContext(),
4617         Importer.Import(S->getAsmLoc()),
4618         S->isSimple(),
4619         S->isVolatile(),
4620         S->getNumOutputs(),
4621         S->getNumInputs(),
4622         Names.data(),
4623         Constraints.data(),
4624         Exprs.data(),
4625         AsmStr,
4626         S->getNumClobbers(),
4627         Clobbers.data(),
4628         Importer.Import(S->getRParenLoc()));
4629 }
4630 
4631 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4632   DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4633   for (Decl *ToD : ToDG) {
4634     if (!ToD)
4635       return nullptr;
4636   }
4637   SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4638   SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4639   return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4640 }
4641 
4642 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4643   SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4644   return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4645                                                 S->hasLeadingEmptyMacro());
4646 }
4647 
4648 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4649   llvm::SmallVector<Stmt *, 8> ToStmts(S->size());
4650 
4651   if (ImportContainerChecked(S->body(), ToStmts))
4652     return nullptr;
4653 
4654   SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4655   SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4656   return CompoundStmt::Create(Importer.getToContext(), ToStmts, ToLBraceLoc,
4657                               ToRBraceLoc);
4658 }
4659 
4660 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4661   Expr *ToLHS = Importer.Import(S->getLHS());
4662   if (!ToLHS)
4663     return nullptr;
4664   Expr *ToRHS = Importer.Import(S->getRHS());
4665   if (!ToRHS && S->getRHS())
4666     return nullptr;
4667   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4668   if (!ToSubStmt && S->getSubStmt())
4669     return nullptr;
4670   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4671   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4672   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4673   CaseStmt *ToStmt = new (Importer.getToContext())
4674       CaseStmt(ToLHS, ToRHS, ToCaseLoc, ToEllipsisLoc, ToColonLoc);
4675   ToStmt->setSubStmt(ToSubStmt);
4676   return ToStmt;
4677 }
4678 
4679 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4680   SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4681   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4682   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4683   if (!ToSubStmt && S->getSubStmt())
4684     return nullptr;
4685   return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4686                                                    ToSubStmt);
4687 }
4688 
4689 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4690   SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4691   LabelDecl *ToLabelDecl =
4692     cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4693   if (!ToLabelDecl && S->getDecl())
4694     return nullptr;
4695   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4696   if (!ToSubStmt && S->getSubStmt())
4697     return nullptr;
4698   return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4699                                                  ToSubStmt);
4700 }
4701 
4702 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4703   SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4704   ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4705   SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4706   ASTContext &_ToContext = Importer.getToContext();
4707   std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4708     [&_ToContext](const Attr *A) -> const Attr * {
4709       return A->clone(_ToContext);
4710     });
4711   for (const Attr *ToA : ToAttrs) {
4712     if (!ToA)
4713       return nullptr;
4714   }
4715   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4716   if (!ToSubStmt && S->getSubStmt())
4717     return nullptr;
4718   return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4719                                 ToAttrs, ToSubStmt);
4720 }
4721 
4722 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4723   SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4724   Stmt *ToInit = Importer.Import(S->getInit());
4725   if (!ToInit && S->getInit())
4726     return nullptr;
4727   VarDecl *ToConditionVariable = nullptr;
4728   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4729     ToConditionVariable =
4730       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4731     if (!ToConditionVariable)
4732       return nullptr;
4733   }
4734   Expr *ToCondition = Importer.Import(S->getCond());
4735   if (!ToCondition && S->getCond())
4736     return nullptr;
4737   Stmt *ToThenStmt = Importer.Import(S->getThen());
4738   if (!ToThenStmt && S->getThen())
4739     return nullptr;
4740   SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4741   Stmt *ToElseStmt = Importer.Import(S->getElse());
4742   if (!ToElseStmt && S->getElse())
4743     return nullptr;
4744   return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4745                                               ToIfLoc, S->isConstexpr(),
4746                                               ToInit,
4747                                               ToConditionVariable,
4748                                               ToCondition, ToThenStmt,
4749                                               ToElseLoc, ToElseStmt);
4750 }
4751 
4752 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4753   Stmt *ToInit = Importer.Import(S->getInit());
4754   if (!ToInit && S->getInit())
4755     return nullptr;
4756   VarDecl *ToConditionVariable = nullptr;
4757   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4758     ToConditionVariable =
4759       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4760     if (!ToConditionVariable)
4761       return nullptr;
4762   }
4763   Expr *ToCondition = Importer.Import(S->getCond());
4764   if (!ToCondition && S->getCond())
4765     return nullptr;
4766   SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4767                          Importer.getToContext(), ToInit,
4768                          ToConditionVariable, ToCondition);
4769   Stmt *ToBody = Importer.Import(S->getBody());
4770   if (!ToBody && S->getBody())
4771     return nullptr;
4772   ToStmt->setBody(ToBody);
4773   ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4774   // Now we have to re-chain the cases.
4775   SwitchCase *LastChainedSwitchCase = nullptr;
4776   for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4777        SC = SC->getNextSwitchCase()) {
4778     SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4779     if (!ToSC)
4780       return nullptr;
4781     if (LastChainedSwitchCase)
4782       LastChainedSwitchCase->setNextSwitchCase(ToSC);
4783     else
4784       ToStmt->setSwitchCaseList(ToSC);
4785     LastChainedSwitchCase = ToSC;
4786   }
4787   return ToStmt;
4788 }
4789 
4790 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4791   VarDecl *ToConditionVariable = nullptr;
4792   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4793     ToConditionVariable =
4794       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4795     if (!ToConditionVariable)
4796       return nullptr;
4797   }
4798   Expr *ToCondition = Importer.Import(S->getCond());
4799   if (!ToCondition && S->getCond())
4800     return nullptr;
4801   Stmt *ToBody = Importer.Import(S->getBody());
4802   if (!ToBody && S->getBody())
4803     return nullptr;
4804   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4805   return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4806                                                  ToConditionVariable,
4807                                                  ToCondition, ToBody,
4808                                                  ToWhileLoc);
4809 }
4810 
4811 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4812   Stmt *ToBody = Importer.Import(S->getBody());
4813   if (!ToBody && S->getBody())
4814     return nullptr;
4815   Expr *ToCondition = Importer.Import(S->getCond());
4816   if (!ToCondition && S->getCond())
4817     return nullptr;
4818   SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4819   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4820   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4821   return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4822                                               ToDoLoc, ToWhileLoc,
4823                                               ToRParenLoc);
4824 }
4825 
4826 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4827   Stmt *ToInit = Importer.Import(S->getInit());
4828   if (!ToInit && S->getInit())
4829     return nullptr;
4830   Expr *ToCondition = Importer.Import(S->getCond());
4831   if (!ToCondition && S->getCond())
4832     return nullptr;
4833   VarDecl *ToConditionVariable = nullptr;
4834   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4835     ToConditionVariable =
4836       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4837     if (!ToConditionVariable)
4838       return nullptr;
4839   }
4840   Expr *ToInc = Importer.Import(S->getInc());
4841   if (!ToInc && S->getInc())
4842     return nullptr;
4843   Stmt *ToBody = Importer.Import(S->getBody());
4844   if (!ToBody && S->getBody())
4845     return nullptr;
4846   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4847   SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4848   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4849   return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4850                                                ToInit, ToCondition,
4851                                                ToConditionVariable,
4852                                                ToInc, ToBody,
4853                                                ToForLoc, ToLParenLoc,
4854                                                ToRParenLoc);
4855 }
4856 
4857 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4858   LabelDecl *ToLabel = nullptr;
4859   if (LabelDecl *FromLabel = S->getLabel()) {
4860     ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4861     if (!ToLabel)
4862       return nullptr;
4863   }
4864   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4865   SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4866   return new (Importer.getToContext()) GotoStmt(ToLabel,
4867                                                 ToGotoLoc, ToLabelLoc);
4868 }
4869 
4870 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4871   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4872   SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4873   Expr *ToTarget = Importer.Import(S->getTarget());
4874   if (!ToTarget && S->getTarget())
4875     return nullptr;
4876   return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4877                                                         ToTarget);
4878 }
4879 
4880 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4881   SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4882   return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4883 }
4884 
4885 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4886   SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4887   return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4888 }
4889 
4890 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4891   SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4892   Expr *ToRetExpr = Importer.Import(S->getRetValue());
4893   if (!ToRetExpr && S->getRetValue())
4894     return nullptr;
4895   VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4896   VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4897   if (!ToNRVOCandidate && NRVOCandidate)
4898     return nullptr;
4899   return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4900                                                   ToNRVOCandidate);
4901 }
4902 
4903 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4904   SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4905   VarDecl *ToExceptionDecl = nullptr;
4906   if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4907     ToExceptionDecl =
4908       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4909     if (!ToExceptionDecl)
4910       return nullptr;
4911   }
4912   Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4913   if (!ToHandlerBlock && S->getHandlerBlock())
4914     return nullptr;
4915   return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4916                                                     ToExceptionDecl,
4917                                                     ToHandlerBlock);
4918 }
4919 
4920 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4921   SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4922   Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4923   if (!ToTryBlock && S->getTryBlock())
4924     return nullptr;
4925   SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4926   for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4927     CXXCatchStmt *FromHandler = S->getHandler(HI);
4928     if (Stmt *ToHandler = Importer.Import(FromHandler))
4929       ToHandlers[HI] = ToHandler;
4930     else
4931       return nullptr;
4932   }
4933   return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4934                             ToHandlers);
4935 }
4936 
4937 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4938   DeclStmt *ToRange =
4939     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4940   if (!ToRange && S->getRangeStmt())
4941     return nullptr;
4942   DeclStmt *ToBegin =
4943     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
4944   if (!ToBegin && S->getBeginStmt())
4945     return nullptr;
4946   DeclStmt *ToEnd =
4947     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
4948   if (!ToEnd && S->getEndStmt())
4949     return nullptr;
4950   Expr *ToCond = Importer.Import(S->getCond());
4951   if (!ToCond && S->getCond())
4952     return nullptr;
4953   Expr *ToInc = Importer.Import(S->getInc());
4954   if (!ToInc && S->getInc())
4955     return nullptr;
4956   DeclStmt *ToLoopVar =
4957     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4958   if (!ToLoopVar && S->getLoopVarStmt())
4959     return nullptr;
4960   Stmt *ToBody = Importer.Import(S->getBody());
4961   if (!ToBody && S->getBody())
4962     return nullptr;
4963   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4964   SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
4965   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4966   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4967   return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
4968                                                        ToCond, ToInc,
4969                                                        ToLoopVar, ToBody,
4970                                                        ToForLoc, ToCoawaitLoc,
4971                                                        ToColonLoc, ToRParenLoc);
4972 }
4973 
4974 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4975   Stmt *ToElem = Importer.Import(S->getElement());
4976   if (!ToElem && S->getElement())
4977     return nullptr;
4978   Expr *ToCollect = Importer.Import(S->getCollection());
4979   if (!ToCollect && S->getCollection())
4980     return nullptr;
4981   Stmt *ToBody = Importer.Import(S->getBody());
4982   if (!ToBody && S->getBody())
4983     return nullptr;
4984   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4985   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4986   return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4987                                                              ToCollect,
4988                                                              ToBody, ToForLoc,
4989                                                              ToRParenLoc);
4990 }
4991 
4992 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4993   SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4994   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4995   VarDecl *ToExceptionDecl = nullptr;
4996   if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4997     ToExceptionDecl =
4998       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4999     if (!ToExceptionDecl)
5000       return nullptr;
5001   }
5002   Stmt *ToBody = Importer.Import(S->getCatchBody());
5003   if (!ToBody && S->getCatchBody())
5004     return nullptr;
5005   return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5006                                                        ToRParenLoc,
5007                                                        ToExceptionDecl,
5008                                                        ToBody);
5009 }
5010 
5011 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5012   SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5013   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5014   if (!ToAtFinallyStmt && S->getFinallyBody())
5015     return nullptr;
5016   return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5017                                                          ToAtFinallyStmt);
5018 }
5019 
5020 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
5021   SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5022   Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5023   if (!ToAtTryStmt && S->getTryBody())
5024     return nullptr;
5025   SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5026   for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5027     ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5028     if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5029       ToCatchStmts[CI] = ToCatchStmt;
5030     else
5031       return nullptr;
5032   }
5033   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5034   if (!ToAtFinallyStmt && S->getFinallyStmt())
5035     return nullptr;
5036   return ObjCAtTryStmt::Create(Importer.getToContext(),
5037                                ToAtTryLoc, ToAtTryStmt,
5038                                ToCatchStmts.begin(), ToCatchStmts.size(),
5039                                ToAtFinallyStmt);
5040 }
5041 
5042 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5043   (ObjCAtSynchronizedStmt *S) {
5044   SourceLocation ToAtSynchronizedLoc =
5045     Importer.Import(S->getAtSynchronizedLoc());
5046   Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5047   if (!ToSynchExpr && S->getSynchExpr())
5048     return nullptr;
5049   Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5050   if (!ToSynchBody && S->getSynchBody())
5051     return nullptr;
5052   return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5053     ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5054 }
5055 
5056 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5057   SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5058   Expr *ToThrow = Importer.Import(S->getThrowExpr());
5059   if (!ToThrow && S->getThrowExpr())
5060     return nullptr;
5061   return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5062 }
5063 
5064 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5065   (ObjCAutoreleasePoolStmt *S) {
5066   SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5067   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5068   if (!ToSubStmt && S->getSubStmt())
5069     return nullptr;
5070   return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5071                                                                ToSubStmt);
5072 }
5073 
5074 //----------------------------------------------------------------------------
5075 // Import Expressions
5076 //----------------------------------------------------------------------------
5077 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5078   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5079     << E->getStmtClassName();
5080   return nullptr;
5081 }
5082 
5083 Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
5084   QualType T = Importer.Import(E->getType());
5085   if (T.isNull())
5086     return nullptr;
5087 
5088   Expr *SubExpr = Importer.Import(E->getSubExpr());
5089   if (!SubExpr && E->getSubExpr())
5090     return nullptr;
5091 
5092   TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5093   if (!TInfo)
5094     return nullptr;
5095 
5096   return new (Importer.getToContext()) VAArgExpr(
5097         Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5098         Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5099 }
5100 
5101 
5102 Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
5103   QualType T = Importer.Import(E->getType());
5104   if (T.isNull())
5105     return nullptr;
5106 
5107   return new (Importer.getToContext()) GNUNullExpr(
5108         T, Importer.Import(E->getLocStart()));
5109 }
5110 
5111 Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
5112   QualType T = Importer.Import(E->getType());
5113   if (T.isNull())
5114     return nullptr;
5115 
5116   StringLiteral *SL = cast_or_null<StringLiteral>(
5117         Importer.Import(E->getFunctionName()));
5118   if (!SL && E->getFunctionName())
5119     return nullptr;
5120 
5121   return new (Importer.getToContext()) PredefinedExpr(
5122         Importer.Import(E->getLocStart()), T, E->getIdentType(), SL);
5123 }
5124 
5125 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5126   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5127   if (!ToD)
5128     return nullptr;
5129 
5130   NamedDecl *FoundD = nullptr;
5131   if (E->getDecl() != E->getFoundDecl()) {
5132     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5133     if (!FoundD)
5134       return nullptr;
5135   }
5136 
5137   QualType T = Importer.Import(E->getType());
5138   if (T.isNull())
5139     return nullptr;
5140 
5141 
5142   TemplateArgumentListInfo ToTAInfo;
5143   TemplateArgumentListInfo *ResInfo = nullptr;
5144   if (E->hasExplicitTemplateArgs()) {
5145     if (ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
5146       return nullptr;
5147     ResInfo = &ToTAInfo;
5148   }
5149 
5150   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5151                                          Importer.Import(E->getQualifierLoc()),
5152                                    Importer.Import(E->getTemplateKeywordLoc()),
5153                                          ToD,
5154                                         E->refersToEnclosingVariableOrCapture(),
5155                                          Importer.Import(E->getLocation()),
5156                                          T, E->getValueKind(),
5157                                          FoundD, ResInfo);
5158   if (E->hadMultipleCandidates())
5159     DRE->setHadMultipleCandidates(true);
5160   return DRE;
5161 }
5162 
5163 Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5164   QualType T = Importer.Import(E->getType());
5165   if (T.isNull())
5166     return nullptr;
5167 
5168   return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5169 }
5170 
5171 ASTNodeImporter::Designator
5172 ASTNodeImporter::ImportDesignator(const Designator &D) {
5173   if (D.isFieldDesignator()) {
5174     IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5175     // Caller checks for import error
5176     return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5177                       Importer.Import(D.getFieldLoc()));
5178   }
5179   if (D.isArrayDesignator())
5180     return Designator(D.getFirstExprIndex(),
5181                       Importer.Import(D.getLBracketLoc()),
5182                       Importer.Import(D.getRBracketLoc()));
5183 
5184   assert(D.isArrayRangeDesignator());
5185   return Designator(D.getFirstExprIndex(),
5186                     Importer.Import(D.getLBracketLoc()),
5187                     Importer.Import(D.getEllipsisLoc()),
5188                     Importer.Import(D.getRBracketLoc()));
5189 }
5190 
5191 
5192 Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
5193   Expr *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
5194   if (!Init)
5195     return nullptr;
5196 
5197   SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
5198   // List elements from the second, the first is Init itself
5199   for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
5200     if (Expr *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
5201       IndexExprs[I - 1] = Arg;
5202     else
5203       return nullptr;
5204   }
5205 
5206   SmallVector<Designator, 4> Designators(DIE->size());
5207   llvm::transform(DIE->designators(), Designators.begin(),
5208                   [this](const Designator &D) -> Designator {
5209                     return ImportDesignator(D);
5210                   });
5211 
5212   for (const Designator &D : DIE->designators())
5213     if (D.isFieldDesignator() && !D.getFieldName())
5214       return nullptr;
5215 
5216   return DesignatedInitExpr::Create(
5217         Importer.getToContext(), Designators,
5218         IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
5219         DIE->usesGNUSyntax(), Init);
5220 }
5221 
5222 Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
5223   QualType T = Importer.Import(E->getType());
5224   if (T.isNull())
5225     return nullptr;
5226 
5227   return new (Importer.getToContext())
5228       CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
5229 }
5230 
5231 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5232   QualType T = Importer.Import(E->getType());
5233   if (T.isNull())
5234     return nullptr;
5235 
5236   return IntegerLiteral::Create(Importer.getToContext(),
5237                                 E->getValue(), T,
5238                                 Importer.Import(E->getLocation()));
5239 }
5240 
5241 Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
5242   QualType T = Importer.Import(E->getType());
5243   if (T.isNull())
5244     return nullptr;
5245 
5246   return FloatingLiteral::Create(Importer.getToContext(),
5247                                 E->getValue(), E->isExact(), T,
5248                                 Importer.Import(E->getLocation()));
5249 }
5250 
5251 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5252   QualType T = Importer.Import(E->getType());
5253   if (T.isNull())
5254     return nullptr;
5255 
5256   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5257                                                         E->getKind(), T,
5258                                           Importer.Import(E->getLocation()));
5259 }
5260 
5261 Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
5262   QualType T = Importer.Import(E->getType());
5263   if (T.isNull())
5264     return nullptr;
5265 
5266   SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
5267   ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
5268 
5269   return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
5270                                E->getKind(), E->isPascal(), T,
5271                                Locations.data(), Locations.size());
5272 }
5273 
5274 Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
5275   QualType T = Importer.Import(E->getType());
5276   if (T.isNull())
5277     return nullptr;
5278 
5279   TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
5280   if (!TInfo)
5281     return nullptr;
5282 
5283   Expr *Init = Importer.Import(E->getInitializer());
5284   if (!Init)
5285     return nullptr;
5286 
5287   return new (Importer.getToContext()) CompoundLiteralExpr(
5288         Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
5289         Init, E->isFileScope());
5290 }
5291 
5292 Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
5293   QualType T = Importer.Import(E->getType());
5294   if (T.isNull())
5295     return nullptr;
5296 
5297   SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
5298   if (ImportArrayChecked(
5299         E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
5300         Exprs.begin()))
5301     return nullptr;
5302 
5303   return new (Importer.getToContext()) AtomicExpr(
5304         Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
5305         Importer.Import(E->getRParenLoc()));
5306 }
5307 
5308 Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
5309   QualType T = Importer.Import(E->getType());
5310   if (T.isNull())
5311     return nullptr;
5312 
5313   LabelDecl *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
5314   if (!ToLabel)
5315     return nullptr;
5316 
5317   return new (Importer.getToContext()) AddrLabelExpr(
5318         Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
5319         ToLabel, T);
5320 }
5321 
5322 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5323   Expr *SubExpr = Importer.Import(E->getSubExpr());
5324   if (!SubExpr)
5325     return nullptr;
5326 
5327   return new (Importer.getToContext())
5328                                   ParenExpr(Importer.Import(E->getLParen()),
5329                                             Importer.Import(E->getRParen()),
5330                                             SubExpr);
5331 }
5332 
5333 Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
5334   SmallVector<Expr *, 4> Exprs(E->getNumExprs());
5335   if (ImportContainerChecked(E->exprs(), Exprs))
5336     return nullptr;
5337 
5338   return new (Importer.getToContext()) ParenListExpr(
5339         Importer.getToContext(), Importer.Import(E->getLParenLoc()),
5340         Exprs, Importer.Import(E->getLParenLoc()));
5341 }
5342 
5343 Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
5344   QualType T = Importer.Import(E->getType());
5345   if (T.isNull())
5346     return nullptr;
5347 
5348   CompoundStmt *ToSubStmt = cast_or_null<CompoundStmt>(
5349         Importer.Import(E->getSubStmt()));
5350   if (!ToSubStmt && E->getSubStmt())
5351     return nullptr;
5352 
5353   return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
5354         Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
5355 }
5356 
5357 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5358   QualType T = Importer.Import(E->getType());
5359   if (T.isNull())
5360     return nullptr;
5361 
5362   Expr *SubExpr = Importer.Import(E->getSubExpr());
5363   if (!SubExpr)
5364     return nullptr;
5365 
5366   return new (Importer.getToContext()) UnaryOperator(
5367       SubExpr, E->getOpcode(), T, E->getValueKind(), E->getObjectKind(),
5368       Importer.Import(E->getOperatorLoc()), E->canOverflow());
5369 }
5370 
5371 Expr *
5372 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) {
5373   QualType ResultType = Importer.Import(E->getType());
5374 
5375   if (E->isArgumentType()) {
5376     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5377     if (!TInfo)
5378       return nullptr;
5379 
5380     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5381                                            TInfo, ResultType,
5382                                            Importer.Import(E->getOperatorLoc()),
5383                                            Importer.Import(E->getRParenLoc()));
5384   }
5385 
5386   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5387   if (!SubExpr)
5388     return nullptr;
5389 
5390   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5391                                           SubExpr, ResultType,
5392                                           Importer.Import(E->getOperatorLoc()),
5393                                           Importer.Import(E->getRParenLoc()));
5394 }
5395 
5396 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5397   QualType T = Importer.Import(E->getType());
5398   if (T.isNull())
5399     return nullptr;
5400 
5401   Expr *LHS = Importer.Import(E->getLHS());
5402   if (!LHS)
5403     return nullptr;
5404 
5405   Expr *RHS = Importer.Import(E->getRHS());
5406   if (!RHS)
5407     return nullptr;
5408 
5409   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5410                                                       T, E->getValueKind(),
5411                                                       E->getObjectKind(),
5412                                            Importer.Import(E->getOperatorLoc()),
5413                                                       E->getFPFeatures());
5414 }
5415 
5416 Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
5417   QualType T = Importer.Import(E->getType());
5418   if (T.isNull())
5419     return nullptr;
5420 
5421   Expr *ToLHS = Importer.Import(E->getLHS());
5422   if (!ToLHS)
5423     return nullptr;
5424 
5425   Expr *ToRHS = Importer.Import(E->getRHS());
5426   if (!ToRHS)
5427     return nullptr;
5428 
5429   Expr *ToCond = Importer.Import(E->getCond());
5430   if (!ToCond)
5431     return nullptr;
5432 
5433   return new (Importer.getToContext()) ConditionalOperator(
5434         ToCond, Importer.Import(E->getQuestionLoc()),
5435         ToLHS, Importer.Import(E->getColonLoc()),
5436         ToRHS, T, E->getValueKind(), E->getObjectKind());
5437 }
5438 
5439 Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
5440     BinaryConditionalOperator *E) {
5441   QualType T = Importer.Import(E->getType());
5442   if (T.isNull())
5443     return nullptr;
5444 
5445   Expr *Common = Importer.Import(E->getCommon());
5446   if (!Common)
5447     return nullptr;
5448 
5449   Expr *Cond = Importer.Import(E->getCond());
5450   if (!Cond)
5451     return nullptr;
5452 
5453   OpaqueValueExpr *OpaqueValue = cast_or_null<OpaqueValueExpr>(
5454         Importer.Import(E->getOpaqueValue()));
5455   if (!OpaqueValue)
5456     return nullptr;
5457 
5458   Expr *TrueExpr = Importer.Import(E->getTrueExpr());
5459   if (!TrueExpr)
5460     return nullptr;
5461 
5462   Expr *FalseExpr = Importer.Import(E->getFalseExpr());
5463   if (!FalseExpr)
5464     return nullptr;
5465 
5466   return new (Importer.getToContext()) BinaryConditionalOperator(
5467         Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
5468         Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
5469         T, E->getValueKind(), E->getObjectKind());
5470 }
5471 
5472 Expr *ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
5473   QualType T = Importer.Import(E->getType());
5474   if (T.isNull())
5475     return nullptr;
5476 
5477   TypeSourceInfo *ToQueried = Importer.Import(E->getQueriedTypeSourceInfo());
5478   if (!ToQueried)
5479     return nullptr;
5480 
5481   Expr *Dim = Importer.Import(E->getDimensionExpression());
5482   if (!Dim && E->getDimensionExpression())
5483     return nullptr;
5484 
5485   return new (Importer.getToContext()) ArrayTypeTraitExpr(
5486         Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5487         E->getValue(), Dim, Importer.Import(E->getLocEnd()), T);
5488 }
5489 
5490 Expr *ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
5491   QualType T = Importer.Import(E->getType());
5492   if (T.isNull())
5493     return nullptr;
5494 
5495   Expr *ToQueried = Importer.Import(E->getQueriedExpression());
5496   if (!ToQueried)
5497     return nullptr;
5498 
5499   return new (Importer.getToContext()) ExpressionTraitExpr(
5500         Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
5501         E->getValue(), Importer.Import(E->getLocEnd()), T);
5502 }
5503 
5504 Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
5505   QualType T = Importer.Import(E->getType());
5506   if (T.isNull())
5507     return nullptr;
5508 
5509   Expr *SourceExpr = Importer.Import(E->getSourceExpr());
5510   if (!SourceExpr && E->getSourceExpr())
5511     return nullptr;
5512 
5513   return new (Importer.getToContext()) OpaqueValueExpr(
5514         Importer.Import(E->getLocation()), T, E->getValueKind(),
5515         E->getObjectKind(), SourceExpr);
5516 }
5517 
5518 Expr *ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
5519   QualType T = Importer.Import(E->getType());
5520   if (T.isNull())
5521     return nullptr;
5522 
5523   Expr *ToLHS = Importer.Import(E->getLHS());
5524   if (!ToLHS)
5525     return nullptr;
5526 
5527   Expr *ToRHS = Importer.Import(E->getRHS());
5528   if (!ToRHS)
5529     return nullptr;
5530 
5531   return new (Importer.getToContext()) ArraySubscriptExpr(
5532         ToLHS, ToRHS, T, E->getValueKind(), E->getObjectKind(),
5533         Importer.Import(E->getRBracketLoc()));
5534 }
5535 
5536 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5537   QualType T = Importer.Import(E->getType());
5538   if (T.isNull())
5539     return nullptr;
5540 
5541   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5542   if (CompLHSType.isNull())
5543     return nullptr;
5544 
5545   QualType CompResultType = Importer.Import(E->getComputationResultType());
5546   if (CompResultType.isNull())
5547     return nullptr;
5548 
5549   Expr *LHS = Importer.Import(E->getLHS());
5550   if (!LHS)
5551     return nullptr;
5552 
5553   Expr *RHS = Importer.Import(E->getRHS());
5554   if (!RHS)
5555     return nullptr;
5556 
5557   return new (Importer.getToContext())
5558                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5559                                                T, E->getValueKind(),
5560                                                E->getObjectKind(),
5561                                                CompLHSType, CompResultType,
5562                                            Importer.Import(E->getOperatorLoc()),
5563                                                E->getFPFeatures());
5564 }
5565 
5566 bool ASTNodeImporter::ImportCastPath(CastExpr *CE, CXXCastPath &Path) {
5567   for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
5568     if (CXXBaseSpecifier *Spec = Importer.Import(*I))
5569       Path.push_back(Spec);
5570     else
5571       return true;
5572   }
5573   return false;
5574 }
5575 
5576 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5577   QualType T = Importer.Import(E->getType());
5578   if (T.isNull())
5579     return nullptr;
5580 
5581   Expr *SubExpr = Importer.Import(E->getSubExpr());
5582   if (!SubExpr)
5583     return nullptr;
5584 
5585   CXXCastPath BasePath;
5586   if (ImportCastPath(E, BasePath))
5587     return nullptr;
5588 
5589   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5590                                   SubExpr, &BasePath, E->getValueKind());
5591 }
5592 
5593 Expr *ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
5594   QualType T = Importer.Import(E->getType());
5595   if (T.isNull())
5596     return nullptr;
5597 
5598   Expr *SubExpr = Importer.Import(E->getSubExpr());
5599   if (!SubExpr)
5600     return nullptr;
5601 
5602   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5603   if (!TInfo && E->getTypeInfoAsWritten())
5604     return nullptr;
5605 
5606   CXXCastPath BasePath;
5607   if (ImportCastPath(E, BasePath))
5608     return nullptr;
5609 
5610   switch (E->getStmtClass()) {
5611   case Stmt::CStyleCastExprClass: {
5612     CStyleCastExpr *CCE = cast<CStyleCastExpr>(E);
5613     return CStyleCastExpr::Create(Importer.getToContext(), T,
5614                                   E->getValueKind(), E->getCastKind(),
5615                                   SubExpr, &BasePath, TInfo,
5616                                   Importer.Import(CCE->getLParenLoc()),
5617                                   Importer.Import(CCE->getRParenLoc()));
5618   }
5619 
5620   case Stmt::CXXFunctionalCastExprClass: {
5621     CXXFunctionalCastExpr *FCE = cast<CXXFunctionalCastExpr>(E);
5622     return CXXFunctionalCastExpr::Create(Importer.getToContext(), T,
5623                                          E->getValueKind(), TInfo,
5624                                          E->getCastKind(), SubExpr, &BasePath,
5625                                          Importer.Import(FCE->getLParenLoc()),
5626                                          Importer.Import(FCE->getRParenLoc()));
5627   }
5628 
5629   case Stmt::ObjCBridgedCastExprClass: {
5630       ObjCBridgedCastExpr *OCE = cast<ObjCBridgedCastExpr>(E);
5631       return new (Importer.getToContext()) ObjCBridgedCastExpr(
5632             Importer.Import(OCE->getLParenLoc()), OCE->getBridgeKind(),
5633             E->getCastKind(), Importer.Import(OCE->getBridgeKeywordLoc()),
5634             TInfo, SubExpr);
5635   }
5636   default:
5637     break; // just fall through
5638   }
5639 
5640   CXXNamedCastExpr *Named = cast<CXXNamedCastExpr>(E);
5641   SourceLocation ExprLoc = Importer.Import(Named->getOperatorLoc()),
5642       RParenLoc = Importer.Import(Named->getRParenLoc());
5643   SourceRange Brackets = Importer.Import(Named->getAngleBrackets());
5644 
5645   switch (E->getStmtClass()) {
5646   case Stmt::CXXStaticCastExprClass:
5647     return CXXStaticCastExpr::Create(Importer.getToContext(), T,
5648                                      E->getValueKind(), E->getCastKind(),
5649                                      SubExpr, &BasePath, TInfo,
5650                                      ExprLoc, RParenLoc, Brackets);
5651 
5652   case Stmt::CXXDynamicCastExprClass:
5653     return CXXDynamicCastExpr::Create(Importer.getToContext(), T,
5654                                       E->getValueKind(), E->getCastKind(),
5655                                       SubExpr, &BasePath, TInfo,
5656                                       ExprLoc, RParenLoc, Brackets);
5657 
5658   case Stmt::CXXReinterpretCastExprClass:
5659     return CXXReinterpretCastExpr::Create(Importer.getToContext(), T,
5660                                           E->getValueKind(), E->getCastKind(),
5661                                           SubExpr, &BasePath, TInfo,
5662                                           ExprLoc, RParenLoc, Brackets);
5663 
5664   case Stmt::CXXConstCastExprClass:
5665     return CXXConstCastExpr::Create(Importer.getToContext(), T,
5666                                     E->getValueKind(), SubExpr, TInfo, ExprLoc,
5667                                     RParenLoc, Brackets);
5668   default:
5669     llvm_unreachable("Cast expression of unsupported type!");
5670     return nullptr;
5671   }
5672 }
5673 
5674 Expr *ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *OE) {
5675   QualType T = Importer.Import(OE->getType());
5676   if (T.isNull())
5677     return nullptr;
5678 
5679   SmallVector<OffsetOfNode, 4> Nodes;
5680   for (int I = 0, E = OE->getNumComponents(); I < E; ++I) {
5681     const OffsetOfNode &Node = OE->getComponent(I);
5682 
5683     switch (Node.getKind()) {
5684     case OffsetOfNode::Array:
5685       Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()),
5686                                    Node.getArrayExprIndex(),
5687                                    Importer.Import(Node.getLocEnd())));
5688       break;
5689 
5690     case OffsetOfNode::Base: {
5691       CXXBaseSpecifier *BS = Importer.Import(Node.getBase());
5692       if (!BS && Node.getBase())
5693         return nullptr;
5694       Nodes.push_back(OffsetOfNode(BS));
5695       break;
5696     }
5697     case OffsetOfNode::Field: {
5698       FieldDecl *FD = cast_or_null<FieldDecl>(Importer.Import(Node.getField()));
5699       if (!FD)
5700         return nullptr;
5701       Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), FD,
5702                                    Importer.Import(Node.getLocEnd())));
5703       break;
5704     }
5705     case OffsetOfNode::Identifier: {
5706       IdentifierInfo *ToII = Importer.Import(Node.getFieldName());
5707       if (!ToII)
5708         return nullptr;
5709       Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), ToII,
5710                                    Importer.Import(Node.getLocEnd())));
5711       break;
5712     }
5713     }
5714   }
5715 
5716   SmallVector<Expr *, 4> Exprs(OE->getNumExpressions());
5717   for (int I = 0, E = OE->getNumExpressions(); I < E; ++I) {
5718     Expr *ToIndexExpr = Importer.Import(OE->getIndexExpr(I));
5719     if (!ToIndexExpr)
5720       return nullptr;
5721     Exprs[I] = ToIndexExpr;
5722   }
5723 
5724   TypeSourceInfo *TInfo = Importer.Import(OE->getTypeSourceInfo());
5725   if (!TInfo && OE->getTypeSourceInfo())
5726     return nullptr;
5727 
5728   return OffsetOfExpr::Create(Importer.getToContext(), T,
5729                               Importer.Import(OE->getOperatorLoc()),
5730                               TInfo, Nodes, Exprs,
5731                               Importer.Import(OE->getRParenLoc()));
5732 }
5733 
5734 Expr *ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
5735   QualType T = Importer.Import(E->getType());
5736   if (T.isNull())
5737     return nullptr;
5738 
5739   Expr *Operand = Importer.Import(E->getOperand());
5740   if (!Operand)
5741     return nullptr;
5742 
5743   CanThrowResult CanThrow;
5744   if (E->isValueDependent())
5745     CanThrow = CT_Dependent;
5746   else
5747     CanThrow = E->getValue() ? CT_Can : CT_Cannot;
5748 
5749   return new (Importer.getToContext()) CXXNoexceptExpr(
5750         T, Operand, CanThrow,
5751         Importer.Import(E->getLocStart()), Importer.Import(E->getLocEnd()));
5752 }
5753 
5754 Expr *ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
5755   QualType T = Importer.Import(E->getType());
5756   if (T.isNull())
5757     return nullptr;
5758 
5759   Expr *SubExpr = Importer.Import(E->getSubExpr());
5760   if (!SubExpr && E->getSubExpr())
5761     return nullptr;
5762 
5763   return new (Importer.getToContext()) CXXThrowExpr(
5764         SubExpr, T, Importer.Import(E->getThrowLoc()),
5765         E->isThrownVariableInScope());
5766 }
5767 
5768 Expr *ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5769   ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
5770         Importer.Import(E->getParam()));
5771   if (!Param)
5772     return nullptr;
5773 
5774   return CXXDefaultArgExpr::Create(
5775         Importer.getToContext(), Importer.Import(E->getUsedLocation()), Param);
5776 }
5777 
5778 Expr *ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
5779   QualType T = Importer.Import(E->getType());
5780   if (T.isNull())
5781     return nullptr;
5782 
5783   TypeSourceInfo *TypeInfo = Importer.Import(E->getTypeSourceInfo());
5784   if (!TypeInfo)
5785     return nullptr;
5786 
5787   return new (Importer.getToContext()) CXXScalarValueInitExpr(
5788         T, TypeInfo, Importer.Import(E->getRParenLoc()));
5789 }
5790 
5791 Expr *ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5792   Expr *SubExpr = Importer.Import(E->getSubExpr());
5793   if (!SubExpr)
5794     return nullptr;
5795 
5796   auto *Dtor = cast_or_null<CXXDestructorDecl>(
5797         Importer.Import(const_cast<CXXDestructorDecl *>(
5798                           E->getTemporary()->getDestructor())));
5799   if (!Dtor)
5800     return nullptr;
5801 
5802   ASTContext &ToCtx = Importer.getToContext();
5803   CXXTemporary *Temp = CXXTemporary::Create(ToCtx, Dtor);
5804   return CXXBindTemporaryExpr::Create(ToCtx, Temp, SubExpr);
5805 }
5806 
5807 Expr *ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE) {
5808   QualType T = Importer.Import(CE->getType());
5809   if (T.isNull())
5810     return nullptr;
5811 
5812 
5813   TypeSourceInfo *TInfo = Importer.Import(CE->getTypeSourceInfo());
5814   if (!TInfo)
5815     return nullptr;
5816 
5817   SmallVector<Expr *, 8> Args(CE->getNumArgs());
5818   if (ImportContainerChecked(CE->arguments(), Args))
5819     return nullptr;
5820 
5821   auto *Ctor = cast_or_null<CXXConstructorDecl>(
5822         Importer.Import(CE->getConstructor()));
5823   if (!Ctor)
5824     return nullptr;
5825 
5826   return new (Importer.getToContext()) CXXTemporaryObjectExpr(
5827       Importer.getToContext(), Ctor, T, TInfo, Args,
5828       Importer.Import(CE->getParenOrBraceRange()), CE->hadMultipleCandidates(),
5829       CE->isListInitialization(), CE->isStdInitListInitialization(),
5830       CE->requiresZeroInitialization());
5831 }
5832 
5833 Expr *
5834 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
5835   QualType T = Importer.Import(E->getType());
5836   if (T.isNull())
5837     return nullptr;
5838 
5839   Expr *TempE = Importer.Import(E->GetTemporaryExpr());
5840   if (!TempE)
5841     return nullptr;
5842 
5843   ValueDecl *ExtendedBy = cast_or_null<ValueDecl>(
5844         Importer.Import(const_cast<ValueDecl *>(E->getExtendingDecl())));
5845   if (!ExtendedBy && E->getExtendingDecl())
5846     return nullptr;
5847 
5848   auto *ToMTE =  new (Importer.getToContext()) MaterializeTemporaryExpr(
5849         T, TempE, E->isBoundToLvalueReference());
5850 
5851   // FIXME: Should ManglingNumber get numbers associated with 'to' context?
5852   ToMTE->setExtendingDecl(ExtendedBy, E->getManglingNumber());
5853   return ToMTE;
5854 }
5855 
5856 Expr *ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) {
5857   QualType T = Importer.Import(E->getType());
5858   if (T.isNull())
5859     return nullptr;
5860 
5861   Expr *Pattern = Importer.Import(E->getPattern());
5862   if (!Pattern)
5863     return nullptr;
5864 
5865   return new (Importer.getToContext()) PackExpansionExpr(
5866         T, Pattern, Importer.Import(E->getEllipsisLoc()),
5867         E->getNumExpansions());
5868 }
5869 
5870 Expr *ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) {
5871   auto *Pack = cast_or_null<NamedDecl>(Importer.Import(E->getPack()));
5872   if (!Pack)
5873     return nullptr;
5874 
5875   Optional<unsigned> Length;
5876 
5877   if (!E->isValueDependent())
5878     Length = E->getPackLength();
5879 
5880   SmallVector<TemplateArgument, 8> PartialArguments;
5881   if (E->isPartiallySubstituted()) {
5882     if (ImportTemplateArguments(E->getPartialArguments().data(),
5883                                 E->getPartialArguments().size(),
5884                                 PartialArguments))
5885       return nullptr;
5886   }
5887 
5888   return SizeOfPackExpr::Create(
5889       Importer.getToContext(), Importer.Import(E->getOperatorLoc()), Pack,
5890       Importer.Import(E->getPackLoc()), Importer.Import(E->getRParenLoc()),
5891       Length, PartialArguments);
5892 }
5893 
5894 
5895 Expr *ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *CE) {
5896   QualType T = Importer.Import(CE->getType());
5897   if (T.isNull())
5898     return nullptr;
5899 
5900   SmallVector<Expr *, 4> PlacementArgs(CE->getNumPlacementArgs());
5901   if (ImportContainerChecked(CE->placement_arguments(), PlacementArgs))
5902     return nullptr;
5903 
5904   FunctionDecl *OperatorNewDecl = cast_or_null<FunctionDecl>(
5905         Importer.Import(CE->getOperatorNew()));
5906   if (!OperatorNewDecl && CE->getOperatorNew())
5907     return nullptr;
5908 
5909   FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
5910         Importer.Import(CE->getOperatorDelete()));
5911   if (!OperatorDeleteDecl && CE->getOperatorDelete())
5912     return nullptr;
5913 
5914   Expr *ToInit = Importer.Import(CE->getInitializer());
5915   if (!ToInit && CE->getInitializer())
5916     return nullptr;
5917 
5918   TypeSourceInfo *TInfo = Importer.Import(CE->getAllocatedTypeSourceInfo());
5919   if (!TInfo)
5920     return nullptr;
5921 
5922   Expr *ToArrSize = Importer.Import(CE->getArraySize());
5923   if (!ToArrSize && CE->getArraySize())
5924     return nullptr;
5925 
5926   return new (Importer.getToContext()) CXXNewExpr(
5927         Importer.getToContext(),
5928         CE->isGlobalNew(),
5929         OperatorNewDecl, OperatorDeleteDecl,
5930         CE->passAlignment(),
5931         CE->doesUsualArrayDeleteWantSize(),
5932         PlacementArgs,
5933         Importer.Import(CE->getTypeIdParens()),
5934         ToArrSize, CE->getInitializationStyle(), ToInit, T, TInfo,
5935         Importer.Import(CE->getSourceRange()),
5936         Importer.Import(CE->getDirectInitRange()));
5937 }
5938 
5939 Expr *ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
5940   QualType T = Importer.Import(E->getType());
5941   if (T.isNull())
5942     return nullptr;
5943 
5944   FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
5945         Importer.Import(E->getOperatorDelete()));
5946   if (!OperatorDeleteDecl && E->getOperatorDelete())
5947     return nullptr;
5948 
5949   Expr *ToArg = Importer.Import(E->getArgument());
5950   if (!ToArg && E->getArgument())
5951     return nullptr;
5952 
5953   return new (Importer.getToContext()) CXXDeleteExpr(
5954         T, E->isGlobalDelete(),
5955         E->isArrayForm(),
5956         E->isArrayFormAsWritten(),
5957         E->doesUsualArrayDeleteWantSize(),
5958         OperatorDeleteDecl,
5959         ToArg,
5960         Importer.Import(E->getLocStart()));
5961 }
5962 
5963 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5964   QualType T = Importer.Import(E->getType());
5965   if (T.isNull())
5966     return nullptr;
5967 
5968   CXXConstructorDecl *ToCCD =
5969     dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5970   if (!ToCCD)
5971     return nullptr;
5972 
5973   SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
5974   if (ImportContainerChecked(E->arguments(), ToArgs))
5975     return nullptr;
5976 
5977   return CXXConstructExpr::Create(Importer.getToContext(), T,
5978                                   Importer.Import(E->getLocation()),
5979                                   ToCCD, E->isElidable(),
5980                                   ToArgs, E->hadMultipleCandidates(),
5981                                   E->isListInitialization(),
5982                                   E->isStdInitListInitialization(),
5983                                   E->requiresZeroInitialization(),
5984                                   E->getConstructionKind(),
5985                                   Importer.Import(E->getParenOrBraceRange()));
5986 }
5987 
5988 Expr *ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *EWC) {
5989   Expr *SubExpr = Importer.Import(EWC->getSubExpr());
5990   if (!SubExpr && EWC->getSubExpr())
5991     return nullptr;
5992 
5993   SmallVector<ExprWithCleanups::CleanupObject, 8> Objs(EWC->getNumObjects());
5994   for (unsigned I = 0, E = EWC->getNumObjects(); I < E; I++)
5995     if (ExprWithCleanups::CleanupObject Obj =
5996         cast_or_null<BlockDecl>(Importer.Import(EWC->getObject(I))))
5997       Objs[I] = Obj;
5998     else
5999       return nullptr;
6000 
6001   return ExprWithCleanups::Create(Importer.getToContext(),
6002                                   SubExpr, EWC->cleanupsHaveSideEffects(),
6003                                   Objs);
6004 }
6005 
6006 Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
6007   QualType T = Importer.Import(E->getType());
6008   if (T.isNull())
6009     return nullptr;
6010 
6011   Expr *ToFn = Importer.Import(E->getCallee());
6012   if (!ToFn)
6013     return nullptr;
6014 
6015   SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
6016   if (ImportContainerChecked(E->arguments(), ToArgs))
6017     return nullptr;
6018 
6019   return new (Importer.getToContext()) CXXMemberCallExpr(
6020         Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
6021         Importer.Import(E->getRParenLoc()));
6022 }
6023 
6024 Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
6025   QualType T = Importer.Import(E->getType());
6026   if (T.isNull())
6027     return nullptr;
6028 
6029   return new (Importer.getToContext())
6030   CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
6031 }
6032 
6033 Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
6034   QualType T = Importer.Import(E->getType());
6035   if (T.isNull())
6036     return nullptr;
6037 
6038   return new (Importer.getToContext())
6039   CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
6040 }
6041 
6042 
6043 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
6044   QualType T = Importer.Import(E->getType());
6045   if (T.isNull())
6046     return nullptr;
6047 
6048   Expr *ToBase = Importer.Import(E->getBase());
6049   if (!ToBase && E->getBase())
6050     return nullptr;
6051 
6052   ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
6053   if (!ToMember && E->getMemberDecl())
6054     return nullptr;
6055 
6056   DeclAccessPair ToFoundDecl = DeclAccessPair::make(
6057     dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
6058     E->getFoundDecl().getAccess());
6059 
6060   DeclarationNameInfo ToMemberNameInfo(
6061     Importer.Import(E->getMemberNameInfo().getName()),
6062     Importer.Import(E->getMemberNameInfo().getLoc()));
6063 
6064   if (E->hasExplicitTemplateArgs()) {
6065     return nullptr; // FIXME: handle template arguments
6066   }
6067 
6068   return MemberExpr::Create(Importer.getToContext(), ToBase,
6069                             E->isArrow(),
6070                             Importer.Import(E->getOperatorLoc()),
6071                             Importer.Import(E->getQualifierLoc()),
6072                             Importer.Import(E->getTemplateKeywordLoc()),
6073                             ToMember, ToFoundDecl, ToMemberNameInfo,
6074                             nullptr, T, E->getValueKind(),
6075                             E->getObjectKind());
6076 }
6077 
6078 Expr *ASTNodeImporter::VisitCXXPseudoDestructorExpr(
6079     CXXPseudoDestructorExpr *E) {
6080 
6081   Expr *BaseE = Importer.Import(E->getBase());
6082   if (!BaseE)
6083     return nullptr;
6084 
6085   TypeSourceInfo *ScopeInfo = Importer.Import(E->getScopeTypeInfo());
6086   if (!ScopeInfo && E->getScopeTypeInfo())
6087     return nullptr;
6088 
6089   PseudoDestructorTypeStorage Storage;
6090   if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
6091     IdentifierInfo *ToII = Importer.Import(FromII);
6092     if (!ToII)
6093       return nullptr;
6094     Storage = PseudoDestructorTypeStorage(
6095           ToII, Importer.Import(E->getDestroyedTypeLoc()));
6096   } else {
6097     TypeSourceInfo *TI = Importer.Import(E->getDestroyedTypeInfo());
6098     if (!TI)
6099       return nullptr;
6100     Storage = PseudoDestructorTypeStorage(TI);
6101   }
6102 
6103   return new (Importer.getToContext()) CXXPseudoDestructorExpr(
6104         Importer.getToContext(), BaseE, E->isArrow(),
6105         Importer.Import(E->getOperatorLoc()),
6106         Importer.Import(E->getQualifierLoc()),
6107         ScopeInfo, Importer.Import(E->getColonColonLoc()),
6108         Importer.Import(E->getTildeLoc()), Storage);
6109 }
6110 
6111 Expr *ASTNodeImporter::VisitCXXDependentScopeMemberExpr(
6112     CXXDependentScopeMemberExpr *E) {
6113   Expr *Base = nullptr;
6114   if (!E->isImplicitAccess()) {
6115     Base = Importer.Import(E->getBase());
6116     if (!Base)
6117       return nullptr;
6118   }
6119 
6120   QualType BaseType = Importer.Import(E->getBaseType());
6121   if (BaseType.isNull())
6122     return nullptr;
6123 
6124   TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
6125   if (E->hasExplicitTemplateArgs()) {
6126     if (ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
6127                                        E->template_arguments(), ToTAInfo))
6128       return nullptr;
6129     ResInfo = &ToTAInfo;
6130   }
6131 
6132   DeclarationName Name = Importer.Import(E->getMember());
6133   if (!E->getMember().isEmpty() && Name.isEmpty())
6134     return nullptr;
6135 
6136   DeclarationNameInfo MemberNameInfo(Name, Importer.Import(E->getMemberLoc()));
6137   // Import additional name location/type info.
6138   ImportDeclarationNameLoc(E->getMemberNameInfo(), MemberNameInfo);
6139   auto ToFQ = Importer.Import(E->getFirstQualifierFoundInScope());
6140   if (!ToFQ && E->getFirstQualifierFoundInScope())
6141     return nullptr;
6142 
6143   return CXXDependentScopeMemberExpr::Create(
6144       Importer.getToContext(), Base, BaseType, E->isArrow(),
6145       Importer.Import(E->getOperatorLoc()),
6146       Importer.Import(E->getQualifierLoc()),
6147       Importer.Import(E->getTemplateKeywordLoc()),
6148       cast_or_null<NamedDecl>(ToFQ), MemberNameInfo, ResInfo);
6149 }
6150 
6151 Expr *ASTNodeImporter::VisitCXXUnresolvedConstructExpr(
6152     CXXUnresolvedConstructExpr *CE) {
6153 
6154   unsigned NumArgs = CE->arg_size();
6155 
6156   llvm::SmallVector<Expr *, 8> ToArgs(NumArgs);
6157   if (ImportArrayChecked(CE->arg_begin(), CE->arg_end(), ToArgs.begin()))
6158     return nullptr;
6159 
6160   return CXXUnresolvedConstructExpr::Create(
6161       Importer.getToContext(), Importer.Import(CE->getTypeSourceInfo()),
6162       Importer.Import(CE->getLParenLoc()), llvm::makeArrayRef(ToArgs),
6163       Importer.Import(CE->getRParenLoc()));
6164 }
6165 
6166 Expr *ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
6167   CXXRecordDecl *NamingClass =
6168       cast_or_null<CXXRecordDecl>(Importer.Import(E->getNamingClass()));
6169   if (E->getNamingClass() && !NamingClass)
6170     return nullptr;
6171 
6172   DeclarationName Name = Importer.Import(E->getName());
6173   if (E->getName() && !Name)
6174     return nullptr;
6175 
6176   DeclarationNameInfo NameInfo(Name, Importer.Import(E->getNameLoc()));
6177   // Import additional name location/type info.
6178   ImportDeclarationNameLoc(E->getNameInfo(), NameInfo);
6179 
6180   UnresolvedSet<8> ToDecls;
6181   for (Decl *D : E->decls()) {
6182     if (NamedDecl *To = cast_or_null<NamedDecl>(Importer.Import(D)))
6183       ToDecls.addDecl(To);
6184     else
6185       return nullptr;
6186   }
6187 
6188   TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
6189   if (E->hasExplicitTemplateArgs()) {
6190     if (ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
6191                                        E->template_arguments(), ToTAInfo))
6192       return nullptr;
6193     ResInfo = &ToTAInfo;
6194   }
6195 
6196   if (ResInfo || E->getTemplateKeywordLoc().isValid())
6197     return UnresolvedLookupExpr::Create(
6198         Importer.getToContext(), NamingClass,
6199         Importer.Import(E->getQualifierLoc()),
6200         Importer.Import(E->getTemplateKeywordLoc()), NameInfo, E->requiresADL(),
6201         ResInfo, ToDecls.begin(), ToDecls.end());
6202 
6203   return UnresolvedLookupExpr::Create(
6204       Importer.getToContext(), NamingClass,
6205       Importer.Import(E->getQualifierLoc()), NameInfo, E->requiresADL(),
6206       E->isOverloaded(), ToDecls.begin(), ToDecls.end());
6207 }
6208 
6209 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
6210   QualType T = Importer.Import(E->getType());
6211   if (T.isNull())
6212     return nullptr;
6213 
6214   Expr *ToCallee = Importer.Import(E->getCallee());
6215   if (!ToCallee && E->getCallee())
6216     return nullptr;
6217 
6218   unsigned NumArgs = E->getNumArgs();
6219   llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
6220   if (ImportContainerChecked(E->arguments(), ToArgs))
6221      return nullptr;
6222 
6223   Expr **ToArgs_Copied = new (Importer.getToContext())
6224     Expr*[NumArgs];
6225 
6226   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
6227     ToArgs_Copied[ai] = ToArgs[ai];
6228 
6229   if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
6230     return new (Importer.getToContext()) CXXOperatorCallExpr(
6231           Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, T,
6232           OCE->getValueKind(), Importer.Import(OCE->getRParenLoc()),
6233           OCE->getFPFeatures());
6234   }
6235 
6236   return new (Importer.getToContext())
6237     CallExpr(Importer.getToContext(), ToCallee,
6238              llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
6239              Importer.Import(E->getRParenLoc()));
6240 }
6241 
6242 Optional<LambdaCapture>
6243 ASTNodeImporter::ImportLambdaCapture(const LambdaCapture &From) {
6244   VarDecl *Var = nullptr;
6245   if (From.capturesVariable()) {
6246     Var = cast_or_null<VarDecl>(Importer.Import(From.getCapturedVar()));
6247     if (!Var)
6248       return None;
6249   }
6250 
6251   return LambdaCapture(Importer.Import(From.getLocation()), From.isImplicit(),
6252                        From.getCaptureKind(), Var,
6253                        From.isPackExpansion()
6254                          ? Importer.Import(From.getEllipsisLoc())
6255                          : SourceLocation());
6256 }
6257 
6258 Expr *ASTNodeImporter::VisitLambdaExpr(LambdaExpr *LE) {
6259   CXXRecordDecl *FromClass = LE->getLambdaClass();
6260   auto *ToClass = dyn_cast_or_null<CXXRecordDecl>(Importer.Import(FromClass));
6261   if (!ToClass)
6262     return nullptr;
6263 
6264   // NOTE: lambda classes are created with BeingDefined flag set up.
6265   // It means that ImportDefinition doesn't work for them and we should fill it
6266   // manually.
6267   if (ToClass->isBeingDefined()) {
6268     for (auto FromField : FromClass->fields()) {
6269       auto *ToField = cast_or_null<FieldDecl>(Importer.Import(FromField));
6270       if (!ToField)
6271         return nullptr;
6272     }
6273   }
6274 
6275   auto *ToCallOp = dyn_cast_or_null<CXXMethodDecl>(
6276         Importer.Import(LE->getCallOperator()));
6277   if (!ToCallOp)
6278     return nullptr;
6279 
6280   ToClass->completeDefinition();
6281 
6282   unsigned NumCaptures = LE->capture_size();
6283   SmallVector<LambdaCapture, 8> Captures;
6284   Captures.reserve(NumCaptures);
6285   for (const auto &FromCapture : LE->captures()) {
6286     if (auto ToCapture = ImportLambdaCapture(FromCapture))
6287       Captures.push_back(*ToCapture);
6288     else
6289       return nullptr;
6290   }
6291 
6292   SmallVector<Expr *, 8> InitCaptures(NumCaptures);
6293   if (ImportContainerChecked(LE->capture_inits(), InitCaptures))
6294     return nullptr;
6295 
6296   return LambdaExpr::Create(Importer.getToContext(), ToClass,
6297                             Importer.Import(LE->getIntroducerRange()),
6298                             LE->getCaptureDefault(),
6299                             Importer.Import(LE->getCaptureDefaultLoc()),
6300                             Captures,
6301                             LE->hasExplicitParameters(),
6302                             LE->hasExplicitResultType(),
6303                             InitCaptures,
6304                             Importer.Import(LE->getLocEnd()),
6305                             LE->containsUnexpandedParameterPack());
6306 }
6307 
6308 
6309 Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
6310   QualType T = Importer.Import(ILE->getType());
6311   if (T.isNull())
6312     return nullptr;
6313 
6314   llvm::SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
6315   if (ImportContainerChecked(ILE->inits(), Exprs))
6316     return nullptr;
6317 
6318   ASTContext &ToCtx = Importer.getToContext();
6319   InitListExpr *To = new (ToCtx) InitListExpr(
6320         ToCtx, Importer.Import(ILE->getLBraceLoc()),
6321         Exprs, Importer.Import(ILE->getLBraceLoc()));
6322   To->setType(T);
6323 
6324   if (ILE->hasArrayFiller()) {
6325     Expr *Filler = Importer.Import(ILE->getArrayFiller());
6326     if (!Filler)
6327       return nullptr;
6328     To->setArrayFiller(Filler);
6329   }
6330 
6331   if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
6332     FieldDecl *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
6333     if (!ToFD)
6334       return nullptr;
6335     To->setInitializedFieldInUnion(ToFD);
6336   }
6337 
6338   if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
6339     InitListExpr *ToSyntForm = cast_or_null<InitListExpr>(
6340           Importer.Import(SyntForm));
6341     if (!ToSyntForm)
6342       return nullptr;
6343     To->setSyntacticForm(ToSyntForm);
6344   }
6345 
6346   To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
6347   To->setValueDependent(ILE->isValueDependent());
6348   To->setInstantiationDependent(ILE->isInstantiationDependent());
6349 
6350   return To;
6351 }
6352 
6353 Expr *ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
6354   QualType ToType = Importer.Import(E->getType());
6355   if (ToType.isNull())
6356     return nullptr;
6357 
6358   Expr *ToCommon = Importer.Import(E->getCommonExpr());
6359   if (!ToCommon && E->getCommonExpr())
6360     return nullptr;
6361 
6362   Expr *ToSubExpr = Importer.Import(E->getSubExpr());
6363   if (!ToSubExpr && E->getSubExpr())
6364     return nullptr;
6365 
6366   return new (Importer.getToContext())
6367       ArrayInitLoopExpr(ToType, ToCommon, ToSubExpr);
6368 }
6369 
6370 Expr *ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
6371   QualType ToType = Importer.Import(E->getType());
6372   if (ToType.isNull())
6373     return nullptr;
6374   return new (Importer.getToContext()) ArrayInitIndexExpr(ToType);
6375 }
6376 
6377 Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
6378   FieldDecl *ToField = llvm::dyn_cast_or_null<FieldDecl>(
6379       Importer.Import(DIE->getField()));
6380   if (!ToField && DIE->getField())
6381     return nullptr;
6382 
6383   return CXXDefaultInitExpr::Create(
6384       Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
6385 }
6386 
6387 Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
6388   QualType ToType = Importer.Import(E->getType());
6389   if (ToType.isNull() && !E->getType().isNull())
6390     return nullptr;
6391   ExprValueKind VK = E->getValueKind();
6392   CastKind CK = E->getCastKind();
6393   Expr *ToOp = Importer.Import(E->getSubExpr());
6394   if (!ToOp && E->getSubExpr())
6395     return nullptr;
6396   CXXCastPath BasePath;
6397   if (ImportCastPath(E, BasePath))
6398     return nullptr;
6399   TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
6400   SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
6401   SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
6402   SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
6403 
6404   if (isa<CXXStaticCastExpr>(E)) {
6405     return CXXStaticCastExpr::Create(
6406         Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6407         ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6408   } else if (isa<CXXDynamicCastExpr>(E)) {
6409     return CXXDynamicCastExpr::Create(
6410         Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6411         ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6412   } else if (isa<CXXReinterpretCastExpr>(E)) {
6413     return CXXReinterpretCastExpr::Create(
6414         Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6415         ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6416   } else {
6417     return nullptr;
6418   }
6419 }
6420 
6421 
6422 Expr *ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
6423     SubstNonTypeTemplateParmExpr *E) {
6424   QualType T = Importer.Import(E->getType());
6425   if (T.isNull())
6426     return nullptr;
6427 
6428   NonTypeTemplateParmDecl *Param = cast_or_null<NonTypeTemplateParmDecl>(
6429         Importer.Import(E->getParameter()));
6430   if (!Param)
6431     return nullptr;
6432 
6433   Expr *Replacement = Importer.Import(E->getReplacement());
6434   if (!Replacement)
6435     return nullptr;
6436 
6437   return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
6438         T, E->getValueKind(), Importer.Import(E->getExprLoc()), Param,
6439         Replacement);
6440 }
6441 
6442 Expr *ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) {
6443   QualType ToType = Importer.Import(E->getType());
6444   if (ToType.isNull())
6445     return nullptr;
6446 
6447   SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
6448   if (ImportContainerChecked(E->getArgs(), ToArgs))
6449     return nullptr;
6450 
6451   // According to Sema::BuildTypeTrait(), if E is value-dependent,
6452   // Value is always false.
6453   bool ToValue = false;
6454   if (!E->isValueDependent())
6455     ToValue = E->getValue();
6456 
6457   return TypeTraitExpr::Create(
6458       Importer.getToContext(), ToType, Importer.Import(E->getLocStart()),
6459       E->getTrait(), ToArgs, Importer.Import(E->getLocEnd()), ToValue);
6460 }
6461 
6462 Expr *ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) {
6463   QualType ToType = Importer.Import(E->getType());
6464   if (ToType.isNull())
6465     return nullptr;
6466 
6467   if (E->isTypeOperand()) {
6468     TypeSourceInfo *TSI = Importer.Import(E->getTypeOperandSourceInfo());
6469     if (!TSI)
6470       return nullptr;
6471 
6472     return new (Importer.getToContext())
6473         CXXTypeidExpr(ToType, TSI, Importer.Import(E->getSourceRange()));
6474   }
6475 
6476   Expr *Op = Importer.Import(E->getExprOperand());
6477   if (!Op)
6478     return nullptr;
6479 
6480   return new (Importer.getToContext())
6481       CXXTypeidExpr(ToType, Op, Importer.Import(E->getSourceRange()));
6482 }
6483 
6484 void ASTNodeImporter::ImportOverrides(CXXMethodDecl *ToMethod,
6485                                       CXXMethodDecl *FromMethod) {
6486   for (auto *FromOverriddenMethod : FromMethod->overridden_methods())
6487     ToMethod->addOverriddenMethod(
6488       cast<CXXMethodDecl>(Importer.Import(const_cast<CXXMethodDecl*>(
6489                                             FromOverriddenMethod))));
6490 }
6491 
6492 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
6493                          ASTContext &FromContext, FileManager &FromFileManager,
6494                          bool MinimalImport)
6495   : ToContext(ToContext), FromContext(FromContext),
6496     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
6497     Minimal(MinimalImport), LastDiagFromFrom(false)
6498 {
6499   ImportedDecls[FromContext.getTranslationUnitDecl()]
6500     = ToContext.getTranslationUnitDecl();
6501 }
6502 
6503 ASTImporter::~ASTImporter() { }
6504 
6505 QualType ASTImporter::Import(QualType FromT) {
6506   if (FromT.isNull())
6507     return QualType();
6508 
6509   const Type *fromTy = FromT.getTypePtr();
6510 
6511   // Check whether we've already imported this type.
6512   llvm::DenseMap<const Type *, const Type *>::iterator Pos
6513     = ImportedTypes.find(fromTy);
6514   if (Pos != ImportedTypes.end())
6515     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
6516 
6517   // Import the type
6518   ASTNodeImporter Importer(*this);
6519   QualType ToT = Importer.Visit(fromTy);
6520   if (ToT.isNull())
6521     return ToT;
6522 
6523   // Record the imported type.
6524   ImportedTypes[fromTy] = ToT.getTypePtr();
6525 
6526   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
6527 }
6528 
6529 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
6530   if (!FromTSI)
6531     return FromTSI;
6532 
6533   // FIXME: For now we just create a "trivial" type source info based
6534   // on the type and a single location. Implement a real version of this.
6535   QualType T = Import(FromTSI->getType());
6536   if (T.isNull())
6537     return nullptr;
6538 
6539   return ToContext.getTrivialTypeSourceInfo(T,
6540            Import(FromTSI->getTypeLoc().getLocStart()));
6541 }
6542 
6543 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
6544   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6545   if (Pos != ImportedDecls.end()) {
6546     Decl *ToD = Pos->second;
6547     ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
6548     return ToD;
6549   } else {
6550     return nullptr;
6551   }
6552 }
6553 
6554 Decl *ASTImporter::Import(Decl *FromD) {
6555   if (!FromD)
6556     return nullptr;
6557 
6558   ASTNodeImporter Importer(*this);
6559 
6560   // Check whether we've already imported this declaration.
6561   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6562   if (Pos != ImportedDecls.end()) {
6563     Decl *ToD = Pos->second;
6564     Importer.ImportDefinitionIfNeeded(FromD, ToD);
6565     return ToD;
6566   }
6567 
6568   // Import the type
6569   Decl *ToD = Importer.Visit(FromD);
6570   if (!ToD)
6571     return nullptr;
6572 
6573   // Record the imported declaration.
6574   ImportedDecls[FromD] = ToD;
6575 
6576   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
6577     // Keep track of anonymous tags that have an associated typedef.
6578     if (FromTag->getTypedefNameForAnonDecl())
6579       AnonTagsWithPendingTypedefs.push_back(FromTag);
6580   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
6581     // When we've finished transforming a typedef, see whether it was the
6582     // typedef for an anonymous tag.
6583     for (SmallVectorImpl<TagDecl *>::iterator
6584                FromTag = AnonTagsWithPendingTypedefs.begin(),
6585             FromTagEnd = AnonTagsWithPendingTypedefs.end();
6586          FromTag != FromTagEnd; ++FromTag) {
6587       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
6588         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
6589           // We found the typedef for an anonymous tag; link them.
6590           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
6591           AnonTagsWithPendingTypedefs.erase(FromTag);
6592           break;
6593         }
6594       }
6595     }
6596   }
6597 
6598   return ToD;
6599 }
6600 
6601 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
6602   if (!FromDC)
6603     return FromDC;
6604 
6605   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
6606   if (!ToDC)
6607     return nullptr;
6608 
6609   // When we're using a record/enum/Objective-C class/protocol as a context, we
6610   // need it to have a definition.
6611   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
6612     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
6613     if (ToRecord->isCompleteDefinition()) {
6614       // Do nothing.
6615     } else if (FromRecord->isCompleteDefinition()) {
6616       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
6617                                               ASTNodeImporter::IDK_Basic);
6618     } else {
6619       CompleteDecl(ToRecord);
6620     }
6621   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
6622     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
6623     if (ToEnum->isCompleteDefinition()) {
6624       // Do nothing.
6625     } else if (FromEnum->isCompleteDefinition()) {
6626       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
6627                                               ASTNodeImporter::IDK_Basic);
6628     } else {
6629       CompleteDecl(ToEnum);
6630     }
6631   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
6632     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
6633     if (ToClass->getDefinition()) {
6634       // Do nothing.
6635     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
6636       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
6637                                               ASTNodeImporter::IDK_Basic);
6638     } else {
6639       CompleteDecl(ToClass);
6640     }
6641   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
6642     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
6643     if (ToProto->getDefinition()) {
6644       // Do nothing.
6645     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
6646       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
6647                                               ASTNodeImporter::IDK_Basic);
6648     } else {
6649       CompleteDecl(ToProto);
6650     }
6651   }
6652 
6653   return ToDC;
6654 }
6655 
6656 Expr *ASTImporter::Import(Expr *FromE) {
6657   if (!FromE)
6658     return nullptr;
6659 
6660   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
6661 }
6662 
6663 Stmt *ASTImporter::Import(Stmt *FromS) {
6664   if (!FromS)
6665     return nullptr;
6666 
6667   // Check whether we've already imported this declaration.
6668   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
6669   if (Pos != ImportedStmts.end())
6670     return Pos->second;
6671 
6672   // Import the type
6673   ASTNodeImporter Importer(*this);
6674   Stmt *ToS = Importer.Visit(FromS);
6675   if (!ToS)
6676     return nullptr;
6677 
6678   // Record the imported declaration.
6679   ImportedStmts[FromS] = ToS;
6680   return ToS;
6681 }
6682 
6683 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
6684   if (!FromNNS)
6685     return nullptr;
6686 
6687   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
6688 
6689   switch (FromNNS->getKind()) {
6690   case NestedNameSpecifier::Identifier:
6691     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
6692       return NestedNameSpecifier::Create(ToContext, prefix, II);
6693     }
6694     return nullptr;
6695 
6696   case NestedNameSpecifier::Namespace:
6697     if (NamespaceDecl *NS =
6698           cast_or_null<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
6699       return NestedNameSpecifier::Create(ToContext, prefix, NS);
6700     }
6701     return nullptr;
6702 
6703   case NestedNameSpecifier::NamespaceAlias:
6704     if (NamespaceAliasDecl *NSAD =
6705           cast_or_null<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
6706       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
6707     }
6708     return nullptr;
6709 
6710   case NestedNameSpecifier::Global:
6711     return NestedNameSpecifier::GlobalSpecifier(ToContext);
6712 
6713   case NestedNameSpecifier::Super:
6714     if (CXXRecordDecl *RD =
6715             cast_or_null<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
6716       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
6717     }
6718     return nullptr;
6719 
6720   case NestedNameSpecifier::TypeSpec:
6721   case NestedNameSpecifier::TypeSpecWithTemplate: {
6722       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
6723       if (!T.isNull()) {
6724         bool bTemplate = FromNNS->getKind() ==
6725                          NestedNameSpecifier::TypeSpecWithTemplate;
6726         return NestedNameSpecifier::Create(ToContext, prefix,
6727                                            bTemplate, T.getTypePtr());
6728       }
6729     }
6730       return nullptr;
6731   }
6732 
6733   llvm_unreachable("Invalid nested name specifier kind");
6734 }
6735 
6736 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
6737   // Copied from NestedNameSpecifier mostly.
6738   SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
6739   NestedNameSpecifierLoc NNS = FromNNS;
6740 
6741   // Push each of the nested-name-specifiers's onto a stack for
6742   // serialization in reverse order.
6743   while (NNS) {
6744     NestedNames.push_back(NNS);
6745     NNS = NNS.getPrefix();
6746   }
6747 
6748   NestedNameSpecifierLocBuilder Builder;
6749 
6750   while (!NestedNames.empty()) {
6751     NNS = NestedNames.pop_back_val();
6752     NestedNameSpecifier *Spec = Import(NNS.getNestedNameSpecifier());
6753     if (!Spec)
6754       return NestedNameSpecifierLoc();
6755 
6756     NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
6757     switch (Kind) {
6758     case NestedNameSpecifier::Identifier:
6759       Builder.Extend(getToContext(),
6760                      Spec->getAsIdentifier(),
6761                      Import(NNS.getLocalBeginLoc()),
6762                      Import(NNS.getLocalEndLoc()));
6763       break;
6764 
6765     case NestedNameSpecifier::Namespace:
6766       Builder.Extend(getToContext(),
6767                      Spec->getAsNamespace(),
6768                      Import(NNS.getLocalBeginLoc()),
6769                      Import(NNS.getLocalEndLoc()));
6770       break;
6771 
6772     case NestedNameSpecifier::NamespaceAlias:
6773       Builder.Extend(getToContext(),
6774                      Spec->getAsNamespaceAlias(),
6775                      Import(NNS.getLocalBeginLoc()),
6776                      Import(NNS.getLocalEndLoc()));
6777       break;
6778 
6779     case NestedNameSpecifier::TypeSpec:
6780     case NestedNameSpecifier::TypeSpecWithTemplate: {
6781       TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
6782             QualType(Spec->getAsType(), 0));
6783       Builder.Extend(getToContext(),
6784                      Import(NNS.getLocalBeginLoc()),
6785                      TSI->getTypeLoc(),
6786                      Import(NNS.getLocalEndLoc()));
6787       break;
6788     }
6789 
6790     case NestedNameSpecifier::Global:
6791       Builder.MakeGlobal(getToContext(), Import(NNS.getLocalBeginLoc()));
6792       break;
6793 
6794     case NestedNameSpecifier::Super: {
6795       SourceRange ToRange = Import(NNS.getSourceRange());
6796       Builder.MakeSuper(getToContext(),
6797                         Spec->getAsRecordDecl(),
6798                         ToRange.getBegin(),
6799                         ToRange.getEnd());
6800     }
6801   }
6802   }
6803 
6804   return Builder.getWithLocInContext(getToContext());
6805 }
6806 
6807 TemplateName ASTImporter::Import(TemplateName From) {
6808   switch (From.getKind()) {
6809   case TemplateName::Template:
6810     if (TemplateDecl *ToTemplate
6811                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6812       return TemplateName(ToTemplate);
6813 
6814     return TemplateName();
6815 
6816   case TemplateName::OverloadedTemplate: {
6817     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
6818     UnresolvedSet<2> ToTemplates;
6819     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
6820                                              E = FromStorage->end();
6821          I != E; ++I) {
6822       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
6823         ToTemplates.addDecl(To);
6824       else
6825         return TemplateName();
6826     }
6827     return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
6828                                                ToTemplates.end());
6829   }
6830 
6831   case TemplateName::QualifiedTemplate: {
6832     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
6833     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
6834     if (!Qualifier)
6835       return TemplateName();
6836 
6837     if (TemplateDecl *ToTemplate
6838         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6839       return ToContext.getQualifiedTemplateName(Qualifier,
6840                                                 QTN->hasTemplateKeyword(),
6841                                                 ToTemplate);
6842 
6843     return TemplateName();
6844   }
6845 
6846   case TemplateName::DependentTemplate: {
6847     DependentTemplateName *DTN = From.getAsDependentTemplateName();
6848     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
6849     if (!Qualifier)
6850       return TemplateName();
6851 
6852     if (DTN->isIdentifier()) {
6853       return ToContext.getDependentTemplateName(Qualifier,
6854                                                 Import(DTN->getIdentifier()));
6855     }
6856 
6857     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
6858   }
6859 
6860   case TemplateName::SubstTemplateTemplateParm: {
6861     SubstTemplateTemplateParmStorage *subst
6862       = From.getAsSubstTemplateTemplateParm();
6863     TemplateTemplateParmDecl *param
6864       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
6865     if (!param)
6866       return TemplateName();
6867 
6868     TemplateName replacement = Import(subst->getReplacement());
6869     if (replacement.isNull()) return TemplateName();
6870 
6871     return ToContext.getSubstTemplateTemplateParm(param, replacement);
6872   }
6873 
6874   case TemplateName::SubstTemplateTemplateParmPack: {
6875     SubstTemplateTemplateParmPackStorage *SubstPack
6876       = From.getAsSubstTemplateTemplateParmPack();
6877     TemplateTemplateParmDecl *Param
6878       = cast_or_null<TemplateTemplateParmDecl>(
6879                                         Import(SubstPack->getParameterPack()));
6880     if (!Param)
6881       return TemplateName();
6882 
6883     ASTNodeImporter Importer(*this);
6884     TemplateArgument ArgPack
6885       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
6886     if (ArgPack.isNull())
6887       return TemplateName();
6888 
6889     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
6890   }
6891   }
6892 
6893   llvm_unreachable("Invalid template name kind");
6894 }
6895 
6896 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
6897   if (FromLoc.isInvalid())
6898     return SourceLocation();
6899 
6900   SourceManager &FromSM = FromContext.getSourceManager();
6901 
6902   // For now, map everything down to its file location, so that we
6903   // don't have to import macro expansions.
6904   // FIXME: Import macro expansions!
6905   FromLoc = FromSM.getFileLoc(FromLoc);
6906   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
6907   SourceManager &ToSM = ToContext.getSourceManager();
6908   FileID ToFileID = Import(Decomposed.first);
6909   if (ToFileID.isInvalid())
6910     return SourceLocation();
6911   SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
6912                            .getLocWithOffset(Decomposed.second);
6913   return ret;
6914 }
6915 
6916 SourceRange ASTImporter::Import(SourceRange FromRange) {
6917   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
6918 }
6919 
6920 FileID ASTImporter::Import(FileID FromID) {
6921   llvm::DenseMap<FileID, FileID>::iterator Pos
6922     = ImportedFileIDs.find(FromID);
6923   if (Pos != ImportedFileIDs.end())
6924     return Pos->second;
6925 
6926   SourceManager &FromSM = FromContext.getSourceManager();
6927   SourceManager &ToSM = ToContext.getSourceManager();
6928   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
6929   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
6930 
6931   // Include location of this file.
6932   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
6933 
6934   // Map the FileID for to the "to" source manager.
6935   FileID ToID;
6936   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
6937   if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
6938     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
6939     // disk again
6940     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
6941     // than mmap the files several times.
6942     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
6943     if (!Entry)
6944       return FileID();
6945     ToID = ToSM.createFileID(Entry, ToIncludeLoc,
6946                              FromSLoc.getFile().getFileCharacteristic());
6947   } else {
6948     // FIXME: We want to re-use the existing MemoryBuffer!
6949     const llvm::MemoryBuffer *
6950         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
6951     std::unique_ptr<llvm::MemoryBuffer> ToBuf
6952       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
6953                                              FromBuf->getBufferIdentifier());
6954     ToID = ToSM.createFileID(std::move(ToBuf),
6955                              FromSLoc.getFile().getFileCharacteristic());
6956   }
6957 
6958 
6959   ImportedFileIDs[FromID] = ToID;
6960   return ToID;
6961 }
6962 
6963 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
6964   Expr *ToExpr = Import(From->getInit());
6965   if (!ToExpr && From->getInit())
6966     return nullptr;
6967 
6968   if (From->isBaseInitializer()) {
6969     TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6970     if (!ToTInfo && From->getTypeSourceInfo())
6971       return nullptr;
6972 
6973     return new (ToContext) CXXCtorInitializer(
6974         ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
6975         ToExpr, Import(From->getRParenLoc()),
6976         From->isPackExpansion() ? Import(From->getEllipsisLoc())
6977                                 : SourceLocation());
6978   } else if (From->isMemberInitializer()) {
6979     FieldDecl *ToField =
6980         llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
6981     if (!ToField && From->getMember())
6982       return nullptr;
6983 
6984     return new (ToContext) CXXCtorInitializer(
6985         ToContext, ToField, Import(From->getMemberLocation()),
6986         Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6987   } else if (From->isIndirectMemberInitializer()) {
6988     IndirectFieldDecl *ToIField = llvm::cast_or_null<IndirectFieldDecl>(
6989         Import(From->getIndirectMember()));
6990     if (!ToIField && From->getIndirectMember())
6991       return nullptr;
6992 
6993     return new (ToContext) CXXCtorInitializer(
6994         ToContext, ToIField, Import(From->getMemberLocation()),
6995         Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6996   } else if (From->isDelegatingInitializer()) {
6997     TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6998     if (!ToTInfo && From->getTypeSourceInfo())
6999       return nullptr;
7000 
7001     return new (ToContext)
7002         CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
7003                            ToExpr, Import(From->getRParenLoc()));
7004   } else {
7005     return nullptr;
7006   }
7007 }
7008 
7009 
7010 CXXBaseSpecifier *ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
7011   auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
7012   if (Pos != ImportedCXXBaseSpecifiers.end())
7013     return Pos->second;
7014 
7015   CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
7016         Import(BaseSpec->getSourceRange()),
7017         BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
7018         BaseSpec->getAccessSpecifierAsWritten(),
7019         Import(BaseSpec->getTypeSourceInfo()),
7020         Import(BaseSpec->getEllipsisLoc()));
7021   ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
7022   return Imported;
7023 }
7024 
7025 void ASTImporter::ImportDefinition(Decl *From) {
7026   Decl *To = Import(From);
7027   if (!To)
7028     return;
7029 
7030   if (DeclContext *FromDC = cast<DeclContext>(From)) {
7031     ASTNodeImporter Importer(*this);
7032 
7033     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
7034       if (!ToRecord->getDefinition()) {
7035         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
7036                                   ASTNodeImporter::IDK_Everything);
7037         return;
7038       }
7039     }
7040 
7041     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
7042       if (!ToEnum->getDefinition()) {
7043         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
7044                                   ASTNodeImporter::IDK_Everything);
7045         return;
7046       }
7047     }
7048 
7049     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
7050       if (!ToIFace->getDefinition()) {
7051         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
7052                                   ASTNodeImporter::IDK_Everything);
7053         return;
7054       }
7055     }
7056 
7057     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
7058       if (!ToProto->getDefinition()) {
7059         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
7060                                   ASTNodeImporter::IDK_Everything);
7061         return;
7062       }
7063     }
7064 
7065     Importer.ImportDeclContext(FromDC, true);
7066   }
7067 }
7068 
7069 DeclarationName ASTImporter::Import(DeclarationName FromName) {
7070   if (!FromName)
7071     return DeclarationName();
7072 
7073   switch (FromName.getNameKind()) {
7074   case DeclarationName::Identifier:
7075     return Import(FromName.getAsIdentifierInfo());
7076 
7077   case DeclarationName::ObjCZeroArgSelector:
7078   case DeclarationName::ObjCOneArgSelector:
7079   case DeclarationName::ObjCMultiArgSelector:
7080     return Import(FromName.getObjCSelector());
7081 
7082   case DeclarationName::CXXConstructorName: {
7083     QualType T = Import(FromName.getCXXNameType());
7084     if (T.isNull())
7085       return DeclarationName();
7086 
7087     return ToContext.DeclarationNames.getCXXConstructorName(
7088                                                ToContext.getCanonicalType(T));
7089   }
7090 
7091   case DeclarationName::CXXDestructorName: {
7092     QualType T = Import(FromName.getCXXNameType());
7093     if (T.isNull())
7094       return DeclarationName();
7095 
7096     return ToContext.DeclarationNames.getCXXDestructorName(
7097                                                ToContext.getCanonicalType(T));
7098   }
7099 
7100   case DeclarationName::CXXDeductionGuideName: {
7101     TemplateDecl *Template = cast_or_null<TemplateDecl>(
7102         Import(FromName.getCXXDeductionGuideTemplate()));
7103     if (!Template)
7104       return DeclarationName();
7105     return ToContext.DeclarationNames.getCXXDeductionGuideName(Template);
7106   }
7107 
7108   case DeclarationName::CXXConversionFunctionName: {
7109     QualType T = Import(FromName.getCXXNameType());
7110     if (T.isNull())
7111       return DeclarationName();
7112 
7113     return ToContext.DeclarationNames.getCXXConversionFunctionName(
7114                                                ToContext.getCanonicalType(T));
7115   }
7116 
7117   case DeclarationName::CXXOperatorName:
7118     return ToContext.DeclarationNames.getCXXOperatorName(
7119                                           FromName.getCXXOverloadedOperator());
7120 
7121   case DeclarationName::CXXLiteralOperatorName:
7122     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
7123                                    Import(FromName.getCXXLiteralIdentifier()));
7124 
7125   case DeclarationName::CXXUsingDirective:
7126     // FIXME: STATICS!
7127     return DeclarationName::getUsingDirectiveName();
7128   }
7129 
7130   llvm_unreachable("Invalid DeclarationName Kind!");
7131 }
7132 
7133 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
7134   if (!FromId)
7135     return nullptr;
7136 
7137   IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
7138 
7139   if (!ToId->getBuiltinID() && FromId->getBuiltinID())
7140     ToId->setBuiltinID(FromId->getBuiltinID());
7141 
7142   return ToId;
7143 }
7144 
7145 Selector ASTImporter::Import(Selector FromSel) {
7146   if (FromSel.isNull())
7147     return Selector();
7148 
7149   SmallVector<IdentifierInfo *, 4> Idents;
7150   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
7151   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
7152     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
7153   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
7154 }
7155 
7156 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
7157                                                 DeclContext *DC,
7158                                                 unsigned IDNS,
7159                                                 NamedDecl **Decls,
7160                                                 unsigned NumDecls) {
7161   return Name;
7162 }
7163 
7164 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
7165   if (LastDiagFromFrom)
7166     ToContext.getDiagnostics().notePriorDiagnosticFrom(
7167       FromContext.getDiagnostics());
7168   LastDiagFromFrom = false;
7169   return ToContext.getDiagnostics().Report(Loc, DiagID);
7170 }
7171 
7172 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
7173   if (!LastDiagFromFrom)
7174     FromContext.getDiagnostics().notePriorDiagnosticFrom(
7175       ToContext.getDiagnostics());
7176   LastDiagFromFrom = true;
7177   return FromContext.getDiagnostics().Report(Loc, DiagID);
7178 }
7179 
7180 void ASTImporter::CompleteDecl (Decl *D) {
7181   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
7182     if (!ID->getDefinition())
7183       ID->startDefinition();
7184   }
7185   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
7186     if (!PD->getDefinition())
7187       PD->startDefinition();
7188   }
7189   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7190     if (!TD->getDefinition() && !TD->isBeingDefined()) {
7191       TD->startDefinition();
7192       TD->setCompleteDefinition(true);
7193     }
7194   }
7195   else {
7196     assert (0 && "CompleteDecl called on a Decl that can't be completed");
7197   }
7198 }
7199 
7200 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
7201   if (From->hasAttrs()) {
7202     for (Attr *FromAttr : From->getAttrs())
7203       To->addAttr(FromAttr->clone(To->getASTContext()));
7204   }
7205   if (From->isUsed()) {
7206     To->setIsUsed();
7207   }
7208   if (From->isImplicit()) {
7209     To->setImplicit();
7210   }
7211   ImportedDecls[From] = To;
7212   return To;
7213 }
7214 
7215 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
7216                                            bool Complain) {
7217   llvm::DenseMap<const Type *, const Type *>::iterator Pos
7218    = ImportedTypes.find(From.getTypePtr());
7219   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
7220     return true;
7221 
7222   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
7223                                    false, Complain);
7224   return Ctx.IsStructurallyEquivalent(From, To);
7225 }
7226