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