]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ASTImporter.cpp
MFV r307859:
[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/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include <deque>
26
27 namespace clang {
28   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29                           public DeclVisitor<ASTNodeImporter, Decl *>,
30                           public StmtVisitor<ASTNodeImporter, Stmt *> {
31     ASTImporter &Importer;
32     
33   public:
34     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
35     
36     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
39
40     // Importing types
41     QualType VisitType(const Type *T);
42     QualType VisitBuiltinType(const BuiltinType *T);
43     QualType VisitComplexType(const ComplexType *T);
44     QualType VisitPointerType(const PointerType *T);
45     QualType VisitBlockPointerType(const BlockPointerType *T);
46     QualType VisitLValueReferenceType(const LValueReferenceType *T);
47     QualType VisitRValueReferenceType(const RValueReferenceType *T);
48     QualType VisitMemberPointerType(const MemberPointerType *T);
49     QualType VisitConstantArrayType(const ConstantArrayType *T);
50     QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
51     QualType VisitVariableArrayType(const VariableArrayType *T);
52     // FIXME: DependentSizedArrayType
53     // FIXME: DependentSizedExtVectorType
54     QualType VisitVectorType(const VectorType *T);
55     QualType VisitExtVectorType(const ExtVectorType *T);
56     QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
57     QualType VisitFunctionProtoType(const FunctionProtoType *T);
58     // FIXME: UnresolvedUsingType
59     QualType VisitParenType(const ParenType *T);
60     QualType VisitTypedefType(const TypedefType *T);
61     QualType VisitTypeOfExprType(const TypeOfExprType *T);
62     // FIXME: DependentTypeOfExprType
63     QualType VisitTypeOfType(const TypeOfType *T);
64     QualType VisitDecltypeType(const DecltypeType *T);
65     QualType VisitUnaryTransformType(const UnaryTransformType *T);
66     QualType VisitAutoType(const AutoType *T);
67     // FIXME: DependentDecltypeType
68     QualType VisitRecordType(const RecordType *T);
69     QualType VisitEnumType(const EnumType *T);
70     QualType VisitAttributedType(const AttributedType *T);
71     // FIXME: TemplateTypeParmType
72     // FIXME: SubstTemplateTypeParmType
73     QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
74     QualType VisitElaboratedType(const ElaboratedType *T);
75     // FIXME: DependentNameType
76     // FIXME: DependentTemplateSpecializationType
77     QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
78     QualType VisitObjCObjectType(const ObjCObjectType *T);
79     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80                             
81     // Importing declarations                            
82     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
83                          DeclContext *&LexicalDC, DeclarationName &Name, 
84                          NamedDecl *&ToD, SourceLocation &Loc);
85     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
86     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87                                   DeclarationNameInfo& To);
88     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89                         
90     /// \brief What we should import from the definition.
91     enum ImportDefinitionKind { 
92       /// \brief Import the default subset of the definition, which might be
93       /// nothing (if minimal import is set) or might be everything (if minimal
94       /// import is not set).
95       IDK_Default,
96       /// \brief Import everything.
97       IDK_Everything,
98       /// \brief Import only the bare bones needed to establish a valid
99       /// DeclContext.
100       IDK_Basic
101     };
102
103     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104       return IDK == IDK_Everything ||
105              (IDK == IDK_Default && !Importer.isMinimalImport());
106     }
107
108     bool ImportDefinition(RecordDecl *From, RecordDecl *To, 
109                           ImportDefinitionKind Kind = IDK_Default);
110     bool ImportDefinition(VarDecl *From, VarDecl *To,
111                           ImportDefinitionKind Kind = IDK_Default);
112     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
113                           ImportDefinitionKind Kind = IDK_Default);
114     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
115                           ImportDefinitionKind Kind = IDK_Default);
116     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
117                           ImportDefinitionKind Kind = IDK_Default);
118     TemplateParameterList *ImportTemplateParameterList(
119                                                  TemplateParameterList *Params);
120     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
121     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
122                                  unsigned NumFromArgs,
123                                SmallVectorImpl<TemplateArgument> &ToArgs);
124     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
125                            bool Complain = true);
126     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
127                            bool Complain = true);
128     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
129     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
130     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
131     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
132     Decl *VisitDecl(Decl *D);
133     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
134     Decl *VisitNamespaceDecl(NamespaceDecl *D);
135     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
136     Decl *VisitTypedefDecl(TypedefDecl *D);
137     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
138     Decl *VisitEnumDecl(EnumDecl *D);
139     Decl *VisitRecordDecl(RecordDecl *D);
140     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
141     Decl *VisitFunctionDecl(FunctionDecl *D);
142     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
143     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
144     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
145     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
146     Decl *VisitFieldDecl(FieldDecl *D);
147     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
148     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
149     Decl *VisitVarDecl(VarDecl *D);
150     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
151     Decl *VisitParmVarDecl(ParmVarDecl *D);
152     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
153     Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
154     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
155     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
156     Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
157
158     ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
159     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
160     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
161     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
162     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
163     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
164     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
165     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
166     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
167     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
168     Decl *VisitClassTemplateSpecializationDecl(
169                                             ClassTemplateSpecializationDecl *D);
170     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
171     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
172
173     // Importing statements
174     DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
175
176     Stmt *VisitStmt(Stmt *S);
177     Stmt *VisitDeclStmt(DeclStmt *S);
178     Stmt *VisitNullStmt(NullStmt *S);
179     Stmt *VisitCompoundStmt(CompoundStmt *S);
180     Stmt *VisitCaseStmt(CaseStmt *S);
181     Stmt *VisitDefaultStmt(DefaultStmt *S);
182     Stmt *VisitLabelStmt(LabelStmt *S);
183     Stmt *VisitAttributedStmt(AttributedStmt *S);
184     Stmt *VisitIfStmt(IfStmt *S);
185     Stmt *VisitSwitchStmt(SwitchStmt *S);
186     Stmt *VisitWhileStmt(WhileStmt *S);
187     Stmt *VisitDoStmt(DoStmt *S);
188     Stmt *VisitForStmt(ForStmt *S);
189     Stmt *VisitGotoStmt(GotoStmt *S);
190     Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
191     Stmt *VisitContinueStmt(ContinueStmt *S);
192     Stmt *VisitBreakStmt(BreakStmt *S);
193     Stmt *VisitReturnStmt(ReturnStmt *S);
194     // FIXME: GCCAsmStmt
195     // FIXME: MSAsmStmt
196     // FIXME: SEHExceptStmt
197     // FIXME: SEHFinallyStmt
198     // FIXME: SEHTryStmt
199     // FIXME: SEHLeaveStmt
200     // FIXME: CapturedStmt
201     Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
202     Stmt *VisitCXXTryStmt(CXXTryStmt *S);
203     Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
204     // FIXME: MSDependentExistsStmt
205     Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
206     Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
207     Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
208     Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
209     Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
210     Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
211     Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
212
213     // Importing expressions
214     Expr *VisitExpr(Expr *E);
215     Expr *VisitDeclRefExpr(DeclRefExpr *E);
216     Expr *VisitIntegerLiteral(IntegerLiteral *E);
217     Expr *VisitCharacterLiteral(CharacterLiteral *E);
218     Expr *VisitParenExpr(ParenExpr *E);
219     Expr *VisitUnaryOperator(UnaryOperator *E);
220     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
221     Expr *VisitBinaryOperator(BinaryOperator *E);
222     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
223     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
224     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
225     Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
226     Expr *VisitMemberExpr(MemberExpr *E);
227     Expr *VisitCallExpr(CallExpr *E);
228   };
229 }
230 using namespace clang;
231
232 //----------------------------------------------------------------------------
233 // Structural Equivalence
234 //----------------------------------------------------------------------------
235
236 namespace {
237   struct StructuralEquivalenceContext {
238     /// \brief AST contexts for which we are checking structural equivalence.
239     ASTContext &C1, &C2;
240     
241     /// \brief The set of "tentative" equivalences between two canonical 
242     /// declarations, mapping from a declaration in the first context to the
243     /// declaration in the second context that we believe to be equivalent.
244     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
245     
246     /// \brief Queue of declarations in the first context whose equivalence
247     /// with a declaration in the second context still needs to be verified.
248     std::deque<Decl *> DeclsToCheck;
249     
250     /// \brief Declaration (from, to) pairs that are known not to be equivalent
251     /// (which we have already complained about).
252     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
253     
254     /// \brief Whether we're being strict about the spelling of types when 
255     /// unifying two types.
256     bool StrictTypeSpelling;
257
258     /// \brief Whether to complain about failures.
259     bool Complain;
260
261     /// \brief \c true if the last diagnostic came from C2.
262     bool LastDiagFromC2;
263
264     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
265                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
266                                  bool StrictTypeSpelling = false,
267                                  bool Complain = true)
268       : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
269         StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
270         LastDiagFromC2(false) {}
271
272     /// \brief Determine whether the two declarations are structurally
273     /// equivalent.
274     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
275     
276     /// \brief Determine whether the two types are structurally equivalent.
277     bool IsStructurallyEquivalent(QualType T1, QualType T2);
278
279   private:
280     /// \brief Finish checking all of the structural equivalences.
281     ///
282     /// \returns true if an error occurred, false otherwise.
283     bool Finish();
284     
285   public:
286     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
287       assert(Complain && "Not allowed to complain");
288       if (LastDiagFromC2)
289         C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
290       LastDiagFromC2 = false;
291       return C1.getDiagnostics().Report(Loc, DiagID);
292     }
293
294     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
295       assert(Complain && "Not allowed to complain");
296       if (!LastDiagFromC2)
297         C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
298       LastDiagFromC2 = true;
299       return C2.getDiagnostics().Report(Loc, DiagID);
300     }
301   };
302 }
303
304 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
305                                      QualType T1, QualType T2);
306 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
307                                      Decl *D1, Decl *D2);
308
309 /// \brief Determine structural equivalence of two expressions.
310 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
311                                      Expr *E1, Expr *E2) {
312   if (!E1 || !E2)
313     return E1 == E2;
314   
315   // FIXME: Actually perform a structural comparison!
316   return true;
317 }
318
319 /// \brief Determine whether two identifiers are equivalent.
320 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
321                                      const IdentifierInfo *Name2) {
322   if (!Name1 || !Name2)
323     return Name1 == Name2;
324   
325   return Name1->getName() == Name2->getName();
326 }
327
328 /// \brief Determine whether two nested-name-specifiers are equivalent.
329 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
330                                      NestedNameSpecifier *NNS1,
331                                      NestedNameSpecifier *NNS2) {
332   // FIXME: Implement!
333   return true;
334 }
335
336 /// \brief Determine whether two template arguments are equivalent.
337 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
338                                      const TemplateArgument &Arg1,
339                                      const TemplateArgument &Arg2) {
340   if (Arg1.getKind() != Arg2.getKind())
341     return false;
342
343   switch (Arg1.getKind()) {
344   case TemplateArgument::Null:
345     return true;
346       
347   case TemplateArgument::Type:
348     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
349
350   case TemplateArgument::Integral:
351     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(), 
352                                           Arg2.getIntegralType()))
353       return false;
354     
355     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
356       
357   case TemplateArgument::Declaration:
358     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
359
360   case TemplateArgument::NullPtr:
361     return true; // FIXME: Is this correct?
362
363   case TemplateArgument::Template:
364     return IsStructurallyEquivalent(Context, 
365                                     Arg1.getAsTemplate(), 
366                                     Arg2.getAsTemplate());
367
368   case TemplateArgument::TemplateExpansion:
369     return IsStructurallyEquivalent(Context, 
370                                     Arg1.getAsTemplateOrTemplatePattern(), 
371                                     Arg2.getAsTemplateOrTemplatePattern());
372
373   case TemplateArgument::Expression:
374     return IsStructurallyEquivalent(Context, 
375                                     Arg1.getAsExpr(), Arg2.getAsExpr());
376       
377   case TemplateArgument::Pack:
378     if (Arg1.pack_size() != Arg2.pack_size())
379       return false;
380       
381     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
382       if (!IsStructurallyEquivalent(Context, 
383                                     Arg1.pack_begin()[I],
384                                     Arg2.pack_begin()[I]))
385         return false;
386       
387     return true;
388   }
389   
390   llvm_unreachable("Invalid template argument kind");
391 }
392
393 /// \brief Determine structural equivalence for the common part of array 
394 /// types.
395 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
396                                           const ArrayType *Array1, 
397                                           const ArrayType *Array2) {
398   if (!IsStructurallyEquivalent(Context, 
399                                 Array1->getElementType(), 
400                                 Array2->getElementType()))
401     return false;
402   if (Array1->getSizeModifier() != Array2->getSizeModifier())
403     return false;
404   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
405     return false;
406   
407   return true;
408 }
409
410 /// \brief Determine structural equivalence of two types.
411 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
412                                      QualType T1, QualType T2) {
413   if (T1.isNull() || T2.isNull())
414     return T1.isNull() && T2.isNull();
415   
416   if (!Context.StrictTypeSpelling) {
417     // We aren't being strict about token-to-token equivalence of types,
418     // so map down to the canonical type.
419     T1 = Context.C1.getCanonicalType(T1);
420     T2 = Context.C2.getCanonicalType(T2);
421   }
422   
423   if (T1.getQualifiers() != T2.getQualifiers())
424     return false;
425   
426   Type::TypeClass TC = T1->getTypeClass();
427   
428   if (T1->getTypeClass() != T2->getTypeClass()) {
429     // Compare function types with prototypes vs. without prototypes as if
430     // both did not have prototypes.
431     if (T1->getTypeClass() == Type::FunctionProto &&
432         T2->getTypeClass() == Type::FunctionNoProto)
433       TC = Type::FunctionNoProto;
434     else if (T1->getTypeClass() == Type::FunctionNoProto &&
435              T2->getTypeClass() == Type::FunctionProto)
436       TC = Type::FunctionNoProto;
437     else
438       return false;
439   }
440   
441   switch (TC) {
442   case Type::Builtin:
443     // FIXME: Deal with Char_S/Char_U. 
444     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
445       return false;
446     break;
447   
448   case Type::Complex:
449     if (!IsStructurallyEquivalent(Context,
450                                   cast<ComplexType>(T1)->getElementType(),
451                                   cast<ComplexType>(T2)->getElementType()))
452       return false;
453     break;
454   
455   case Type::Adjusted:
456   case Type::Decayed:
457     if (!IsStructurallyEquivalent(Context,
458                                   cast<AdjustedType>(T1)->getOriginalType(),
459                                   cast<AdjustedType>(T2)->getOriginalType()))
460       return false;
461     break;
462
463   case Type::Pointer:
464     if (!IsStructurallyEquivalent(Context,
465                                   cast<PointerType>(T1)->getPointeeType(),
466                                   cast<PointerType>(T2)->getPointeeType()))
467       return false;
468     break;
469
470   case Type::BlockPointer:
471     if (!IsStructurallyEquivalent(Context,
472                                   cast<BlockPointerType>(T1)->getPointeeType(),
473                                   cast<BlockPointerType>(T2)->getPointeeType()))
474       return false;
475     break;
476
477   case Type::LValueReference:
478   case Type::RValueReference: {
479     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
480     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
481     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
482       return false;
483     if (Ref1->isInnerRef() != Ref2->isInnerRef())
484       return false;
485     if (!IsStructurallyEquivalent(Context,
486                                   Ref1->getPointeeTypeAsWritten(),
487                                   Ref2->getPointeeTypeAsWritten()))
488       return false;
489     break;
490   }
491       
492   case Type::MemberPointer: {
493     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
494     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
495     if (!IsStructurallyEquivalent(Context,
496                                   MemPtr1->getPointeeType(),
497                                   MemPtr2->getPointeeType()))
498       return false;
499     if (!IsStructurallyEquivalent(Context,
500                                   QualType(MemPtr1->getClass(), 0),
501                                   QualType(MemPtr2->getClass(), 0)))
502       return false;
503     break;
504   }
505       
506   case Type::ConstantArray: {
507     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
508     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
509     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
510       return false;
511     
512     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
513       return false;
514     break;
515   }
516
517   case Type::IncompleteArray:
518     if (!IsArrayStructurallyEquivalent(Context, 
519                                        cast<ArrayType>(T1), 
520                                        cast<ArrayType>(T2)))
521       return false;
522     break;
523       
524   case Type::VariableArray: {
525     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
526     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
527     if (!IsStructurallyEquivalent(Context, 
528                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
529       return false;
530     
531     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
532       return false;
533     
534     break;
535   }
536   
537   case Type::DependentSizedArray: {
538     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
539     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
540     if (!IsStructurallyEquivalent(Context, 
541                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
542       return false;
543     
544     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
545       return false;
546     
547     break;
548   }
549       
550   case Type::DependentSizedExtVector: {
551     const DependentSizedExtVectorType *Vec1
552       = cast<DependentSizedExtVectorType>(T1);
553     const DependentSizedExtVectorType *Vec2
554       = cast<DependentSizedExtVectorType>(T2);
555     if (!IsStructurallyEquivalent(Context, 
556                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
557       return false;
558     if (!IsStructurallyEquivalent(Context, 
559                                   Vec1->getElementType(), 
560                                   Vec2->getElementType()))
561       return false;
562     break;
563   }
564    
565   case Type::Vector: 
566   case Type::ExtVector: {
567     const VectorType *Vec1 = cast<VectorType>(T1);
568     const VectorType *Vec2 = cast<VectorType>(T2);
569     if (!IsStructurallyEquivalent(Context, 
570                                   Vec1->getElementType(),
571                                   Vec2->getElementType()))
572       return false;
573     if (Vec1->getNumElements() != Vec2->getNumElements())
574       return false;
575     if (Vec1->getVectorKind() != Vec2->getVectorKind())
576       return false;
577     break;
578   }
579
580   case Type::FunctionProto: {
581     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
582     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
583     if (Proto1->getNumParams() != Proto2->getNumParams())
584       return false;
585     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
586       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
587                                     Proto2->getParamType(I)))
588         return false;
589     }
590     if (Proto1->isVariadic() != Proto2->isVariadic())
591       return false;
592     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
593       return false;
594     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
595       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
596         return false;
597       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
598         if (!IsStructurallyEquivalent(Context,
599                                       Proto1->getExceptionType(I),
600                                       Proto2->getExceptionType(I)))
601           return false;
602       }
603     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
604       if (!IsStructurallyEquivalent(Context,
605                                     Proto1->getNoexceptExpr(),
606                                     Proto2->getNoexceptExpr()))
607         return false;
608     }
609     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
610       return false;
611     
612     // Fall through to check the bits common with FunctionNoProtoType.
613   }
614       
615   case Type::FunctionNoProto: {
616     const FunctionType *Function1 = cast<FunctionType>(T1);
617     const FunctionType *Function2 = cast<FunctionType>(T2);
618     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
619                                   Function2->getReturnType()))
620       return false;
621       if (Function1->getExtInfo() != Function2->getExtInfo())
622         return false;
623     break;
624   }
625    
626   case Type::UnresolvedUsing:
627     if (!IsStructurallyEquivalent(Context,
628                                   cast<UnresolvedUsingType>(T1)->getDecl(),
629                                   cast<UnresolvedUsingType>(T2)->getDecl()))
630       return false;
631       
632     break;
633
634   case Type::Attributed:
635     if (!IsStructurallyEquivalent(Context,
636                                   cast<AttributedType>(T1)->getModifiedType(),
637                                   cast<AttributedType>(T2)->getModifiedType()))
638       return false;
639     if (!IsStructurallyEquivalent(Context,
640                                 cast<AttributedType>(T1)->getEquivalentType(),
641                                 cast<AttributedType>(T2)->getEquivalentType()))
642       return false;
643     break;
644       
645   case Type::Paren:
646     if (!IsStructurallyEquivalent(Context,
647                                   cast<ParenType>(T1)->getInnerType(),
648                                   cast<ParenType>(T2)->getInnerType()))
649       return false;
650     break;
651
652   case Type::Typedef:
653     if (!IsStructurallyEquivalent(Context,
654                                   cast<TypedefType>(T1)->getDecl(),
655                                   cast<TypedefType>(T2)->getDecl()))
656       return false;
657     break;
658       
659   case Type::TypeOfExpr:
660     if (!IsStructurallyEquivalent(Context,
661                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
662                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
663       return false;
664     break;
665       
666   case Type::TypeOf:
667     if (!IsStructurallyEquivalent(Context,
668                                   cast<TypeOfType>(T1)->getUnderlyingType(),
669                                   cast<TypeOfType>(T2)->getUnderlyingType()))
670       return false;
671     break;
672
673   case Type::UnaryTransform:
674     if (!IsStructurallyEquivalent(Context,
675                              cast<UnaryTransformType>(T1)->getUnderlyingType(),
676                              cast<UnaryTransformType>(T1)->getUnderlyingType()))
677       return false;
678     break;
679
680   case Type::Decltype:
681     if (!IsStructurallyEquivalent(Context,
682                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
683                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
684       return false;
685     break;
686
687   case Type::Auto:
688     if (!IsStructurallyEquivalent(Context,
689                                   cast<AutoType>(T1)->getDeducedType(),
690                                   cast<AutoType>(T2)->getDeducedType()))
691       return false;
692     break;
693
694   case Type::Record:
695   case Type::Enum:
696     if (!IsStructurallyEquivalent(Context,
697                                   cast<TagType>(T1)->getDecl(),
698                                   cast<TagType>(T2)->getDecl()))
699       return false;
700     break;
701
702   case Type::TemplateTypeParm: {
703     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
704     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
705     if (Parm1->getDepth() != Parm2->getDepth())
706       return false;
707     if (Parm1->getIndex() != Parm2->getIndex())
708       return false;
709     if (Parm1->isParameterPack() != Parm2->isParameterPack())
710       return false;
711     
712     // Names of template type parameters are never significant.
713     break;
714   }
715       
716   case Type::SubstTemplateTypeParm: {
717     const SubstTemplateTypeParmType *Subst1
718       = cast<SubstTemplateTypeParmType>(T1);
719     const SubstTemplateTypeParmType *Subst2
720       = cast<SubstTemplateTypeParmType>(T2);
721     if (!IsStructurallyEquivalent(Context,
722                                   QualType(Subst1->getReplacedParameter(), 0),
723                                   QualType(Subst2->getReplacedParameter(), 0)))
724       return false;
725     if (!IsStructurallyEquivalent(Context, 
726                                   Subst1->getReplacementType(),
727                                   Subst2->getReplacementType()))
728       return false;
729     break;
730   }
731
732   case Type::SubstTemplateTypeParmPack: {
733     const SubstTemplateTypeParmPackType *Subst1
734       = cast<SubstTemplateTypeParmPackType>(T1);
735     const SubstTemplateTypeParmPackType *Subst2
736       = cast<SubstTemplateTypeParmPackType>(T2);
737     if (!IsStructurallyEquivalent(Context,
738                                   QualType(Subst1->getReplacedParameter(), 0),
739                                   QualType(Subst2->getReplacedParameter(), 0)))
740       return false;
741     if (!IsStructurallyEquivalent(Context, 
742                                   Subst1->getArgumentPack(),
743                                   Subst2->getArgumentPack()))
744       return false;
745     break;
746   }
747   case Type::TemplateSpecialization: {
748     const TemplateSpecializationType *Spec1
749       = cast<TemplateSpecializationType>(T1);
750     const TemplateSpecializationType *Spec2
751       = cast<TemplateSpecializationType>(T2);
752     if (!IsStructurallyEquivalent(Context,
753                                   Spec1->getTemplateName(),
754                                   Spec2->getTemplateName()))
755       return false;
756     if (Spec1->getNumArgs() != Spec2->getNumArgs())
757       return false;
758     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
759       if (!IsStructurallyEquivalent(Context, 
760                                     Spec1->getArg(I), Spec2->getArg(I)))
761         return false;
762     }
763     break;
764   }
765       
766   case Type::Elaborated: {
767     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
768     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
769     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
770     if (Elab1->getKeyword() != Elab2->getKeyword())
771       return false;
772     if (!IsStructurallyEquivalent(Context, 
773                                   Elab1->getQualifier(), 
774                                   Elab2->getQualifier()))
775       return false;
776     if (!IsStructurallyEquivalent(Context,
777                                   Elab1->getNamedType(),
778                                   Elab2->getNamedType()))
779       return false;
780     break;
781   }
782
783   case Type::InjectedClassName: {
784     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
785     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
786     if (!IsStructurallyEquivalent(Context,
787                                   Inj1->getInjectedSpecializationType(),
788                                   Inj2->getInjectedSpecializationType()))
789       return false;
790     break;
791   }
792
793   case Type::DependentName: {
794     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
795     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
796     if (!IsStructurallyEquivalent(Context, 
797                                   Typename1->getQualifier(),
798                                   Typename2->getQualifier()))
799       return false;
800     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
801                                   Typename2->getIdentifier()))
802       return false;
803     
804     break;
805   }
806   
807   case Type::DependentTemplateSpecialization: {
808     const DependentTemplateSpecializationType *Spec1 =
809       cast<DependentTemplateSpecializationType>(T1);
810     const DependentTemplateSpecializationType *Spec2 =
811       cast<DependentTemplateSpecializationType>(T2);
812     if (!IsStructurallyEquivalent(Context, 
813                                   Spec1->getQualifier(),
814                                   Spec2->getQualifier()))
815       return false;
816     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
817                                   Spec2->getIdentifier()))
818       return false;
819     if (Spec1->getNumArgs() != Spec2->getNumArgs())
820       return false;
821     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
822       if (!IsStructurallyEquivalent(Context,
823                                     Spec1->getArg(I), Spec2->getArg(I)))
824         return false;
825     }
826     break;
827   }
828
829   case Type::PackExpansion:
830     if (!IsStructurallyEquivalent(Context,
831                                   cast<PackExpansionType>(T1)->getPattern(),
832                                   cast<PackExpansionType>(T2)->getPattern()))
833       return false;
834     break;
835
836   case Type::ObjCInterface: {
837     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
838     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
839     if (!IsStructurallyEquivalent(Context, 
840                                   Iface1->getDecl(), Iface2->getDecl()))
841       return false;
842     break;
843   }
844
845   case Type::ObjCObject: {
846     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
847     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
848     if (!IsStructurallyEquivalent(Context,
849                                   Obj1->getBaseType(),
850                                   Obj2->getBaseType()))
851       return false;
852     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
853       return false;
854     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
855       if (!IsStructurallyEquivalent(Context,
856                                     Obj1->getProtocol(I),
857                                     Obj2->getProtocol(I)))
858         return false;
859     }
860     break;
861   }
862
863   case Type::ObjCObjectPointer: {
864     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
865     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
866     if (!IsStructurallyEquivalent(Context, 
867                                   Ptr1->getPointeeType(),
868                                   Ptr2->getPointeeType()))
869       return false;
870     break;
871   }
872
873   case Type::Atomic: {
874     if (!IsStructurallyEquivalent(Context,
875                                   cast<AtomicType>(T1)->getValueType(),
876                                   cast<AtomicType>(T2)->getValueType()))
877       return false;
878     break;
879   }
880
881   case Type::Pipe: {
882     if (!IsStructurallyEquivalent(Context,
883                                   cast<PipeType>(T1)->getElementType(),
884                                   cast<PipeType>(T2)->getElementType()))
885       return false;
886     break;
887   }
888
889   } // end switch
890
891   return true;
892 }
893
894 /// \brief Determine structural equivalence of two fields.
895 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
896                                      FieldDecl *Field1, FieldDecl *Field2) {
897   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
898
899   // For anonymous structs/unions, match up the anonymous struct/union type
900   // declarations directly, so that we don't go off searching for anonymous
901   // types
902   if (Field1->isAnonymousStructOrUnion() &&
903       Field2->isAnonymousStructOrUnion()) {
904     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
905     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
906     return IsStructurallyEquivalent(Context, D1, D2);
907   }
908     
909   // Check for equivalent field names.
910   IdentifierInfo *Name1 = Field1->getIdentifier();
911   IdentifierInfo *Name2 = Field2->getIdentifier();
912   if (!::IsStructurallyEquivalent(Name1, Name2))
913     return false;
914
915   if (!IsStructurallyEquivalent(Context,
916                                 Field1->getType(), Field2->getType())) {
917     if (Context.Complain) {
918       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
919         << Context.C2.getTypeDeclType(Owner2);
920       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
921         << Field2->getDeclName() << Field2->getType();
922       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
923         << Field1->getDeclName() << Field1->getType();
924     }
925     return false;
926   }
927   
928   if (Field1->isBitField() != Field2->isBitField()) {
929     if (Context.Complain) {
930       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
931         << Context.C2.getTypeDeclType(Owner2);
932       if (Field1->isBitField()) {
933         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
934         << Field1->getDeclName() << Field1->getType()
935         << Field1->getBitWidthValue(Context.C1);
936         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
937         << Field2->getDeclName();
938       } else {
939         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
940         << Field2->getDeclName() << Field2->getType()
941         << Field2->getBitWidthValue(Context.C2);
942         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
943         << Field1->getDeclName();
944       }
945     }
946     return false;
947   }
948   
949   if (Field1->isBitField()) {
950     // Make sure that the bit-fields are the same length.
951     unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
952     unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
953     
954     if (Bits1 != Bits2) {
955       if (Context.Complain) {
956         Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
957           << Context.C2.getTypeDeclType(Owner2);
958         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
959           << Field2->getDeclName() << Field2->getType() << Bits2;
960         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
961           << Field1->getDeclName() << Field1->getType() << Bits1;
962       }
963       return false;
964     }
965   }
966
967   return true;
968 }
969
970 /// \brief Find the index of the given anonymous struct/union within its
971 /// context.
972 ///
973 /// \returns Returns the index of this anonymous struct/union in its context,
974 /// including the next assigned index (if none of them match). Returns an
975 /// empty option if the context is not a record, i.e.. if the anonymous
976 /// struct/union is at namespace or block scope.
977 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
978   ASTContext &Context = Anon->getASTContext();
979   QualType AnonTy = Context.getRecordType(Anon);
980
981   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
982   if (!Owner)
983     return None;
984
985   unsigned Index = 0;
986   for (const auto *D : Owner->noload_decls()) {
987     const auto *F = dyn_cast<FieldDecl>(D);
988     if (!F || !F->isAnonymousStructOrUnion())
989       continue;
990
991     if (Context.hasSameType(F->getType(), AnonTy))
992       break;
993
994     ++Index;
995   }
996
997   return Index;
998 }
999
1000 /// \brief Determine structural equivalence of two records.
1001 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1002                                      RecordDecl *D1, RecordDecl *D2) {
1003   if (D1->isUnion() != D2->isUnion()) {
1004     if (Context.Complain) {
1005       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1006         << Context.C2.getTypeDeclType(D2);
1007       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1008         << D1->getDeclName() << (unsigned)D1->getTagKind();
1009     }
1010     return false;
1011   }
1012
1013   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1014     // If both anonymous structs/unions are in a record context, make sure
1015     // they occur in the same location in the context records.
1016     if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
1017       if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
1018         if (*Index1 != *Index2)
1019           return false;
1020       }
1021     }
1022   }
1023
1024   // If both declarations are class template specializations, we know
1025   // the ODR applies, so check the template and template arguments.
1026   ClassTemplateSpecializationDecl *Spec1
1027     = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1028   ClassTemplateSpecializationDecl *Spec2
1029     = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1030   if (Spec1 && Spec2) {
1031     // Check that the specialized templates are the same.
1032     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1033                                   Spec2->getSpecializedTemplate()))
1034       return false;
1035     
1036     // Check that the template arguments are the same.
1037     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1038       return false;
1039     
1040     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1041       if (!IsStructurallyEquivalent(Context, 
1042                                     Spec1->getTemplateArgs().get(I),
1043                                     Spec2->getTemplateArgs().get(I)))
1044         return false;
1045   }  
1046   // If one is a class template specialization and the other is not, these
1047   // structures are different.
1048   else if (Spec1 || Spec2)
1049     return false;
1050
1051   // Compare the definitions of these two records. If either or both are
1052   // incomplete, we assume that they are equivalent.
1053   D1 = D1->getDefinition();
1054   D2 = D2->getDefinition();
1055   if (!D1 || !D2)
1056     return true;
1057   
1058   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1059     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1060       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1061         if (Context.Complain) {
1062           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1063             << Context.C2.getTypeDeclType(D2);
1064           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1065             << D2CXX->getNumBases();
1066           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1067             << D1CXX->getNumBases();
1068         }
1069         return false;
1070       }
1071       
1072       // Check the base classes. 
1073       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), 
1074                                            BaseEnd1 = D1CXX->bases_end(),
1075                                                 Base2 = D2CXX->bases_begin();
1076            Base1 != BaseEnd1;
1077            ++Base1, ++Base2) {        
1078         if (!IsStructurallyEquivalent(Context, 
1079                                       Base1->getType(), Base2->getType())) {
1080           if (Context.Complain) {
1081             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1082               << Context.C2.getTypeDeclType(D2);
1083             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1084               << Base2->getType()
1085               << Base2->getSourceRange();
1086             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1087               << Base1->getType()
1088               << Base1->getSourceRange();
1089           }
1090           return false;
1091         }
1092         
1093         // Check virtual vs. non-virtual inheritance mismatch.
1094         if (Base1->isVirtual() != Base2->isVirtual()) {
1095           if (Context.Complain) {
1096             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1097               << Context.C2.getTypeDeclType(D2);
1098             Context.Diag2(Base2->getLocStart(),
1099                           diag::note_odr_virtual_base)
1100               << Base2->isVirtual() << Base2->getSourceRange();
1101             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1102               << Base1->isVirtual()
1103               << Base1->getSourceRange();
1104           }
1105           return false;
1106         }
1107       }
1108     } else if (D1CXX->getNumBases() > 0) {
1109       if (Context.Complain) {
1110         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1111           << Context.C2.getTypeDeclType(D2);
1112         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1113         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1114           << Base1->getType()
1115           << Base1->getSourceRange();
1116         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1117       }
1118       return false;
1119     }
1120   }
1121   
1122   // Check the fields for consistency.
1123   RecordDecl::field_iterator Field2 = D2->field_begin(),
1124                              Field2End = D2->field_end();
1125   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1126                                   Field1End = D1->field_end();
1127        Field1 != Field1End;
1128        ++Field1, ++Field2) {
1129     if (Field2 == Field2End) {
1130       if (Context.Complain) {
1131         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1132           << Context.C2.getTypeDeclType(D2);
1133         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1134           << Field1->getDeclName() << Field1->getType();
1135         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1136       }
1137       return false;
1138     }
1139     
1140     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1141       return false;    
1142   }
1143   
1144   if (Field2 != Field2End) {
1145     if (Context.Complain) {
1146       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1147         << Context.C2.getTypeDeclType(D2);
1148       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1149         << Field2->getDeclName() << Field2->getType();
1150       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1151     }
1152     return false;
1153   }
1154   
1155   return true;
1156 }
1157      
1158 /// \brief Determine structural equivalence of two enums.
1159 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1160                                      EnumDecl *D1, EnumDecl *D2) {
1161   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1162                              EC2End = D2->enumerator_end();
1163   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1164                                   EC1End = D1->enumerator_end();
1165        EC1 != EC1End; ++EC1, ++EC2) {
1166     if (EC2 == EC2End) {
1167       if (Context.Complain) {
1168         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1169           << Context.C2.getTypeDeclType(D2);
1170         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1171           << EC1->getDeclName() 
1172           << EC1->getInitVal().toString(10);
1173         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1174       }
1175       return false;
1176     }
1177     
1178     llvm::APSInt Val1 = EC1->getInitVal();
1179     llvm::APSInt Val2 = EC2->getInitVal();
1180     if (!llvm::APSInt::isSameValue(Val1, Val2) || 
1181         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1182       if (Context.Complain) {
1183         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1184           << Context.C2.getTypeDeclType(D2);
1185         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1186           << EC2->getDeclName() 
1187           << EC2->getInitVal().toString(10);
1188         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1189           << EC1->getDeclName() 
1190           << EC1->getInitVal().toString(10);
1191       }
1192       return false;
1193     }
1194   }
1195   
1196   if (EC2 != EC2End) {
1197     if (Context.Complain) {
1198       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1199         << Context.C2.getTypeDeclType(D2);
1200       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1201         << EC2->getDeclName() 
1202         << EC2->getInitVal().toString(10);
1203       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1204     }
1205     return false;
1206   }
1207   
1208   return true;
1209 }
1210
1211 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1212                                      TemplateParameterList *Params1,
1213                                      TemplateParameterList *Params2) {
1214   if (Params1->size() != Params2->size()) {
1215     if (Context.Complain) {
1216       Context.Diag2(Params2->getTemplateLoc(), 
1217                     diag::err_odr_different_num_template_parameters)
1218         << Params1->size() << Params2->size();
1219       Context.Diag1(Params1->getTemplateLoc(), 
1220                     diag::note_odr_template_parameter_list);
1221     }
1222     return false;
1223   }
1224   
1225   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1226     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1227       if (Context.Complain) {
1228         Context.Diag2(Params2->getParam(I)->getLocation(), 
1229                       diag::err_odr_different_template_parameter_kind);
1230         Context.Diag1(Params1->getParam(I)->getLocation(),
1231                       diag::note_odr_template_parameter_here);
1232       }
1233       return false;
1234     }
1235     
1236     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1237                                           Params2->getParam(I))) {
1238       
1239       return false;
1240     }
1241   }
1242   
1243   return true;
1244 }
1245
1246 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1247                                      TemplateTypeParmDecl *D1,
1248                                      TemplateTypeParmDecl *D2) {
1249   if (D1->isParameterPack() != D2->isParameterPack()) {
1250     if (Context.Complain) {
1251       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1252         << D2->isParameterPack();
1253       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1254         << D1->isParameterPack();
1255     }
1256     return false;
1257   }
1258   
1259   return true;
1260 }
1261
1262 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1263                                      NonTypeTemplateParmDecl *D1,
1264                                      NonTypeTemplateParmDecl *D2) {
1265   if (D1->isParameterPack() != D2->isParameterPack()) {
1266     if (Context.Complain) {
1267       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1268         << D2->isParameterPack();
1269       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1270         << D1->isParameterPack();
1271     }
1272     return false;
1273   }
1274   
1275   // Check types.
1276   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1277     if (Context.Complain) {
1278       Context.Diag2(D2->getLocation(),
1279                     diag::err_odr_non_type_parameter_type_inconsistent)
1280         << D2->getType() << D1->getType();
1281       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1282         << D1->getType();
1283     }
1284     return false;
1285   }
1286   
1287   return true;
1288 }
1289
1290 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1291                                      TemplateTemplateParmDecl *D1,
1292                                      TemplateTemplateParmDecl *D2) {
1293   if (D1->isParameterPack() != D2->isParameterPack()) {
1294     if (Context.Complain) {
1295       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1296         << D2->isParameterPack();
1297       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1298         << D1->isParameterPack();
1299     }
1300     return false;
1301   }
1302
1303   // Check template parameter lists.
1304   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1305                                   D2->getTemplateParameters());
1306 }
1307
1308 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1309                                      ClassTemplateDecl *D1, 
1310                                      ClassTemplateDecl *D2) {
1311   // Check template parameters.
1312   if (!IsStructurallyEquivalent(Context,
1313                                 D1->getTemplateParameters(),
1314                                 D2->getTemplateParameters()))
1315     return false;
1316   
1317   // Check the templated declaration.
1318   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(), 
1319                                           D2->getTemplatedDecl());
1320 }
1321
1322 /// \brief Determine structural equivalence of two declarations.
1323 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1324                                      Decl *D1, Decl *D2) {
1325   // FIXME: Check for known structural equivalences via a callback of some sort.
1326   
1327   // Check whether we already know that these two declarations are not
1328   // structurally equivalent.
1329   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1330                                                       D2->getCanonicalDecl())))
1331     return false;
1332   
1333   // Determine whether we've already produced a tentative equivalence for D1.
1334   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1335   if (EquivToD1)
1336     return EquivToD1 == D2->getCanonicalDecl();
1337   
1338   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1339   EquivToD1 = D2->getCanonicalDecl();
1340   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1341   return true;
1342 }
1343
1344 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1, 
1345                                                             Decl *D2) {
1346   if (!::IsStructurallyEquivalent(*this, D1, D2))
1347     return false;
1348   
1349   return !Finish();
1350 }
1351
1352 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1, 
1353                                                             QualType T2) {
1354   if (!::IsStructurallyEquivalent(*this, T1, T2))
1355     return false;
1356   
1357   return !Finish();
1358 }
1359
1360 bool StructuralEquivalenceContext::Finish() {
1361   while (!DeclsToCheck.empty()) {
1362     // Check the next declaration.
1363     Decl *D1 = DeclsToCheck.front();
1364     DeclsToCheck.pop_front();
1365     
1366     Decl *D2 = TentativeEquivalences[D1];
1367     assert(D2 && "Unrecorded tentative equivalence?");
1368     
1369     bool Equivalent = true;
1370     
1371     // FIXME: Switch on all declaration kinds. For now, we're just going to
1372     // check the obvious ones.
1373     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1374       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1375         // Check for equivalent structure names.
1376         IdentifierInfo *Name1 = Record1->getIdentifier();
1377         if (!Name1 && Record1->getTypedefNameForAnonDecl())
1378           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1379         IdentifierInfo *Name2 = Record2->getIdentifier();
1380         if (!Name2 && Record2->getTypedefNameForAnonDecl())
1381           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1382         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1383             !::IsStructurallyEquivalent(*this, Record1, Record2))
1384           Equivalent = false;
1385       } else {
1386         // Record/non-record mismatch.
1387         Equivalent = false;
1388       }
1389     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1390       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1391         // Check for equivalent enum names.
1392         IdentifierInfo *Name1 = Enum1->getIdentifier();
1393         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1394           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1395         IdentifierInfo *Name2 = Enum2->getIdentifier();
1396         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1397           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1398         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1399             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1400           Equivalent = false;
1401       } else {
1402         // Enum/non-enum mismatch
1403         Equivalent = false;
1404       }
1405     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1406       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1407         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1408                                         Typedef2->getIdentifier()) ||
1409             !::IsStructurallyEquivalent(*this,
1410                                         Typedef1->getUnderlyingType(),
1411                                         Typedef2->getUnderlyingType()))
1412           Equivalent = false;
1413       } else {
1414         // Typedef/non-typedef mismatch.
1415         Equivalent = false;
1416       }
1417     } else if (ClassTemplateDecl *ClassTemplate1 
1418                                            = dyn_cast<ClassTemplateDecl>(D1)) {
1419       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1420         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1421                                         ClassTemplate2->getIdentifier()) ||
1422             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1423           Equivalent = false;
1424       } else {
1425         // Class template/non-class-template mismatch.
1426         Equivalent = false;
1427       }
1428     } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1429       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1430         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1431           Equivalent = false;
1432       } else {
1433         // Kind mismatch.
1434         Equivalent = false;
1435       }
1436     } else if (NonTypeTemplateParmDecl *NTTP1
1437                                      = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1438       if (NonTypeTemplateParmDecl *NTTP2
1439                                       = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1440         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1441           Equivalent = false;
1442       } else {
1443         // Kind mismatch.
1444         Equivalent = false;
1445       }
1446     } else if (TemplateTemplateParmDecl *TTP1
1447                                   = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1448       if (TemplateTemplateParmDecl *TTP2
1449                                     = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1450         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1451           Equivalent = false;
1452       } else {
1453         // Kind mismatch.
1454         Equivalent = false;
1455       }
1456     }
1457     
1458     if (!Equivalent) {
1459       // Note that these two declarations are not equivalent (and we already
1460       // know about it).
1461       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1462                                                D2->getCanonicalDecl()));
1463       return true;
1464     }
1465     // FIXME: Check other declaration kinds!
1466   }
1467   
1468   return false;
1469 }
1470
1471 //----------------------------------------------------------------------------
1472 // Import Types
1473 //----------------------------------------------------------------------------
1474
1475 QualType ASTNodeImporter::VisitType(const Type *T) {
1476   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1477     << T->getTypeClassName();
1478   return QualType();
1479 }
1480
1481 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1482   switch (T->getKind()) {
1483 #define SHARED_SINGLETON_TYPE(Expansion)
1484 #define BUILTIN_TYPE(Id, SingletonId) \
1485   case BuiltinType::Id: return Importer.getToContext().SingletonId;
1486 #include "clang/AST/BuiltinTypes.def"
1487
1488   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1489   // context supports C++.
1490
1491   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1492   // context supports ObjC.
1493
1494   case BuiltinType::Char_U:
1495     // The context we're importing from has an unsigned 'char'. If we're 
1496     // importing into a context with a signed 'char', translate to 
1497     // 'unsigned char' instead.
1498     if (Importer.getToContext().getLangOpts().CharIsSigned)
1499       return Importer.getToContext().UnsignedCharTy;
1500     
1501     return Importer.getToContext().CharTy;
1502
1503   case BuiltinType::Char_S:
1504     // The context we're importing from has an unsigned 'char'. If we're 
1505     // importing into a context with a signed 'char', translate to 
1506     // 'unsigned char' instead.
1507     if (!Importer.getToContext().getLangOpts().CharIsSigned)
1508       return Importer.getToContext().SignedCharTy;
1509     
1510     return Importer.getToContext().CharTy;
1511
1512   case BuiltinType::WChar_S:
1513   case BuiltinType::WChar_U:
1514     // FIXME: If not in C++, shall we translate to the C equivalent of
1515     // wchar_t?
1516     return Importer.getToContext().WCharTy;
1517   }
1518
1519   llvm_unreachable("Invalid BuiltinType Kind!");
1520 }
1521
1522 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1523   QualType ToElementType = Importer.Import(T->getElementType());
1524   if (ToElementType.isNull())
1525     return QualType();
1526   
1527   return Importer.getToContext().getComplexType(ToElementType);
1528 }
1529
1530 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1531   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1532   if (ToPointeeType.isNull())
1533     return QualType();
1534   
1535   return Importer.getToContext().getPointerType(ToPointeeType);
1536 }
1537
1538 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1539   // FIXME: Check for blocks support in "to" context.
1540   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1541   if (ToPointeeType.isNull())
1542     return QualType();
1543   
1544   return Importer.getToContext().getBlockPointerType(ToPointeeType);
1545 }
1546
1547 QualType
1548 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1549   // FIXME: Check for C++ support in "to" context.
1550   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1551   if (ToPointeeType.isNull())
1552     return QualType();
1553   
1554   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1555 }
1556
1557 QualType
1558 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1559   // FIXME: Check for C++0x support in "to" context.
1560   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1561   if (ToPointeeType.isNull())
1562     return QualType();
1563   
1564   return Importer.getToContext().getRValueReferenceType(ToPointeeType);  
1565 }
1566
1567 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1568   // FIXME: Check for C++ support in "to" context.
1569   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1570   if (ToPointeeType.isNull())
1571     return QualType();
1572   
1573   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1574   return Importer.getToContext().getMemberPointerType(ToPointeeType, 
1575                                                       ClassType.getTypePtr());
1576 }
1577
1578 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1579   QualType ToElementType = Importer.Import(T->getElementType());
1580   if (ToElementType.isNull())
1581     return QualType();
1582   
1583   return Importer.getToContext().getConstantArrayType(ToElementType, 
1584                                                       T->getSize(),
1585                                                       T->getSizeModifier(),
1586                                                T->getIndexTypeCVRQualifiers());
1587 }
1588
1589 QualType
1590 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1591   QualType ToElementType = Importer.Import(T->getElementType());
1592   if (ToElementType.isNull())
1593     return QualType();
1594   
1595   return Importer.getToContext().getIncompleteArrayType(ToElementType, 
1596                                                         T->getSizeModifier(),
1597                                                 T->getIndexTypeCVRQualifiers());
1598 }
1599
1600 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1601   QualType ToElementType = Importer.Import(T->getElementType());
1602   if (ToElementType.isNull())
1603     return QualType();
1604
1605   Expr *Size = Importer.Import(T->getSizeExpr());
1606   if (!Size)
1607     return QualType();
1608   
1609   SourceRange Brackets = Importer.Import(T->getBracketsRange());
1610   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1611                                                       T->getSizeModifier(),
1612                                                 T->getIndexTypeCVRQualifiers(),
1613                                                       Brackets);
1614 }
1615
1616 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1617   QualType ToElementType = Importer.Import(T->getElementType());
1618   if (ToElementType.isNull())
1619     return QualType();
1620   
1621   return Importer.getToContext().getVectorType(ToElementType, 
1622                                                T->getNumElements(),
1623                                                T->getVectorKind());
1624 }
1625
1626 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1627   QualType ToElementType = Importer.Import(T->getElementType());
1628   if (ToElementType.isNull())
1629     return QualType();
1630   
1631   return Importer.getToContext().getExtVectorType(ToElementType, 
1632                                                   T->getNumElements());
1633 }
1634
1635 QualType
1636 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1637   // FIXME: What happens if we're importing a function without a prototype 
1638   // into C++? Should we make it variadic?
1639   QualType ToResultType = Importer.Import(T->getReturnType());
1640   if (ToResultType.isNull())
1641     return QualType();
1642
1643   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1644                                                         T->getExtInfo());
1645 }
1646
1647 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1648   QualType ToResultType = Importer.Import(T->getReturnType());
1649   if (ToResultType.isNull())
1650     return QualType();
1651   
1652   // Import argument types
1653   SmallVector<QualType, 4> ArgTypes;
1654   for (const auto &A : T->param_types()) {
1655     QualType ArgType = Importer.Import(A);
1656     if (ArgType.isNull())
1657       return QualType();
1658     ArgTypes.push_back(ArgType);
1659   }
1660   
1661   // Import exception types
1662   SmallVector<QualType, 4> ExceptionTypes;
1663   for (const auto &E : T->exceptions()) {
1664     QualType ExceptionType = Importer.Import(E);
1665     if (ExceptionType.isNull())
1666       return QualType();
1667     ExceptionTypes.push_back(ExceptionType);
1668   }
1669
1670   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1671   FunctionProtoType::ExtProtoInfo ToEPI;
1672
1673   ToEPI.ExtInfo = FromEPI.ExtInfo;
1674   ToEPI.Variadic = FromEPI.Variadic;
1675   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1676   ToEPI.TypeQuals = FromEPI.TypeQuals;
1677   ToEPI.RefQualifier = FromEPI.RefQualifier;
1678   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1679   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1680   ToEPI.ExceptionSpec.NoexceptExpr =
1681       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1682   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1683       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1684   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1685       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1686
1687   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1688 }
1689
1690 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1691   QualType ToInnerType = Importer.Import(T->getInnerType());
1692   if (ToInnerType.isNull())
1693     return QualType();
1694     
1695   return Importer.getToContext().getParenType(ToInnerType);
1696 }
1697
1698 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1699   TypedefNameDecl *ToDecl
1700              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1701   if (!ToDecl)
1702     return QualType();
1703   
1704   return Importer.getToContext().getTypeDeclType(ToDecl);
1705 }
1706
1707 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1708   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1709   if (!ToExpr)
1710     return QualType();
1711   
1712   return Importer.getToContext().getTypeOfExprType(ToExpr);
1713 }
1714
1715 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1716   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1717   if (ToUnderlyingType.isNull())
1718     return QualType();
1719   
1720   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1721 }
1722
1723 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1724   // FIXME: Make sure that the "to" context supports C++0x!
1725   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1726   if (!ToExpr)
1727     return QualType();
1728   
1729   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1730   if (UnderlyingType.isNull())
1731     return QualType();
1732
1733   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1734 }
1735
1736 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1737   QualType ToBaseType = Importer.Import(T->getBaseType());
1738   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1739   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1740     return QualType();
1741
1742   return Importer.getToContext().getUnaryTransformType(ToBaseType,
1743                                                        ToUnderlyingType,
1744                                                        T->getUTTKind());
1745 }
1746
1747 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1748   // FIXME: Make sure that the "to" context supports C++11!
1749   QualType FromDeduced = T->getDeducedType();
1750   QualType ToDeduced;
1751   if (!FromDeduced.isNull()) {
1752     ToDeduced = Importer.Import(FromDeduced);
1753     if (ToDeduced.isNull())
1754       return QualType();
1755   }
1756   
1757   return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1758                                              /*IsDependent*/false);
1759 }
1760
1761 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1762   RecordDecl *ToDecl
1763     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1764   if (!ToDecl)
1765     return QualType();
1766
1767   return Importer.getToContext().getTagDeclType(ToDecl);
1768 }
1769
1770 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1771   EnumDecl *ToDecl
1772     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1773   if (!ToDecl)
1774     return QualType();
1775
1776   return Importer.getToContext().getTagDeclType(ToDecl);
1777 }
1778
1779 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1780   QualType FromModifiedType = T->getModifiedType();
1781   QualType FromEquivalentType = T->getEquivalentType();
1782   QualType ToModifiedType;
1783   QualType ToEquivalentType;
1784
1785   if (!FromModifiedType.isNull()) {
1786     ToModifiedType = Importer.Import(FromModifiedType);
1787     if (ToModifiedType.isNull())
1788       return QualType();
1789   }
1790   if (!FromEquivalentType.isNull()) {
1791     ToEquivalentType = Importer.Import(FromEquivalentType);
1792     if (ToEquivalentType.isNull())
1793       return QualType();
1794   }
1795
1796   return Importer.getToContext().getAttributedType(T->getAttrKind(),
1797     ToModifiedType, ToEquivalentType);
1798 }
1799
1800 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1801                                        const TemplateSpecializationType *T) {
1802   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1803   if (ToTemplate.isNull())
1804     return QualType();
1805   
1806   SmallVector<TemplateArgument, 2> ToTemplateArgs;
1807   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1808     return QualType();
1809   
1810   QualType ToCanonType;
1811   if (!QualType(T, 0).isCanonical()) {
1812     QualType FromCanonType 
1813       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1814     ToCanonType =Importer.Import(FromCanonType);
1815     if (ToCanonType.isNull())
1816       return QualType();
1817   }
1818   return Importer.getToContext().getTemplateSpecializationType(ToTemplate, 
1819                                                          ToTemplateArgs.data(), 
1820                                                          ToTemplateArgs.size(),
1821                                                                ToCanonType);
1822 }
1823
1824 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1825   NestedNameSpecifier *ToQualifier = nullptr;
1826   // Note: the qualifier in an ElaboratedType is optional.
1827   if (T->getQualifier()) {
1828     ToQualifier = Importer.Import(T->getQualifier());
1829     if (!ToQualifier)
1830       return QualType();
1831   }
1832
1833   QualType ToNamedType = Importer.Import(T->getNamedType());
1834   if (ToNamedType.isNull())
1835     return QualType();
1836
1837   return Importer.getToContext().getElaboratedType(T->getKeyword(),
1838                                                    ToQualifier, ToNamedType);
1839 }
1840
1841 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1842   ObjCInterfaceDecl *Class
1843     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1844   if (!Class)
1845     return QualType();
1846
1847   return Importer.getToContext().getObjCInterfaceType(Class);
1848 }
1849
1850 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1851   QualType ToBaseType = Importer.Import(T->getBaseType());
1852   if (ToBaseType.isNull())
1853     return QualType();
1854
1855   SmallVector<QualType, 4> TypeArgs;
1856   for (auto TypeArg : T->getTypeArgsAsWritten()) {
1857     QualType ImportedTypeArg = Importer.Import(TypeArg);
1858     if (ImportedTypeArg.isNull())
1859       return QualType();
1860
1861     TypeArgs.push_back(ImportedTypeArg);
1862   }
1863
1864   SmallVector<ObjCProtocolDecl *, 4> Protocols;
1865   for (auto *P : T->quals()) {
1866     ObjCProtocolDecl *Protocol
1867       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1868     if (!Protocol)
1869       return QualType();
1870     Protocols.push_back(Protocol);
1871   }
1872
1873   return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1874                                                    Protocols,
1875                                                    T->isKindOfTypeAsWritten());
1876 }
1877
1878 QualType
1879 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1880   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1881   if (ToPointeeType.isNull())
1882     return QualType();
1883
1884   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1885 }
1886
1887 //----------------------------------------------------------------------------
1888 // Import Declarations
1889 //----------------------------------------------------------------------------
1890 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
1891                                       DeclContext *&LexicalDC, 
1892                                       DeclarationName &Name, 
1893                                       NamedDecl *&ToD,
1894                                       SourceLocation &Loc) {
1895   // Import the context of this declaration.
1896   DC = Importer.ImportContext(D->getDeclContext());
1897   if (!DC)
1898     return true;
1899   
1900   LexicalDC = DC;
1901   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1902     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1903     if (!LexicalDC)
1904       return true;
1905   }
1906   
1907   // Import the name of this declaration.
1908   Name = Importer.Import(D->getDeclName());
1909   if (D->getDeclName() && !Name)
1910     return true;
1911   
1912   // Import the location of this declaration.
1913   Loc = Importer.Import(D->getLocation());
1914   ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1915   return false;
1916 }
1917
1918 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1919   if (!FromD)
1920     return;
1921   
1922   if (!ToD) {
1923     ToD = Importer.Import(FromD);
1924     if (!ToD)
1925       return;
1926   }
1927   
1928   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1929     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1930       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1931         ImportDefinition(FromRecord, ToRecord);
1932       }
1933     }
1934     return;
1935   }
1936
1937   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1938     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1939       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1940         ImportDefinition(FromEnum, ToEnum);
1941       }
1942     }
1943     return;
1944   }
1945 }
1946
1947 void
1948 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1949                                           DeclarationNameInfo& To) {
1950   // NOTE: To.Name and To.Loc are already imported.
1951   // We only have to import To.LocInfo.
1952   switch (To.getName().getNameKind()) {
1953   case DeclarationName::Identifier:
1954   case DeclarationName::ObjCZeroArgSelector:
1955   case DeclarationName::ObjCOneArgSelector:
1956   case DeclarationName::ObjCMultiArgSelector:
1957   case DeclarationName::CXXUsingDirective:
1958     return;
1959
1960   case DeclarationName::CXXOperatorName: {
1961     SourceRange Range = From.getCXXOperatorNameRange();
1962     To.setCXXOperatorNameRange(Importer.Import(Range));
1963     return;
1964   }
1965   case DeclarationName::CXXLiteralOperatorName: {
1966     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1967     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1968     return;
1969   }
1970   case DeclarationName::CXXConstructorName:
1971   case DeclarationName::CXXDestructorName:
1972   case DeclarationName::CXXConversionFunctionName: {
1973     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1974     To.setNamedTypeInfo(Importer.Import(FromTInfo));
1975     return;
1976   }
1977   }
1978   llvm_unreachable("Unknown name kind.");
1979 }
1980
1981 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {  
1982   if (Importer.isMinimalImport() && !ForceImport) {
1983     Importer.ImportContext(FromDC);
1984     return;
1985   }
1986   
1987   for (auto *From : FromDC->decls())
1988     Importer.Import(From);
1989 }
1990
1991 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, 
1992                                        ImportDefinitionKind Kind) {
1993   if (To->getDefinition() || To->isBeingDefined()) {
1994     if (Kind == IDK_Everything)
1995       ImportDeclContext(From, /*ForceImport=*/true);
1996     
1997     return false;
1998   }
1999   
2000   To->startDefinition();
2001   
2002   // Add base classes.
2003   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
2004     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
2005
2006     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2007     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2008     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2009     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2010     ToData.Aggregate = FromData.Aggregate;
2011     ToData.PlainOldData = FromData.PlainOldData;
2012     ToData.Empty = FromData.Empty;
2013     ToData.Polymorphic = FromData.Polymorphic;
2014     ToData.Abstract = FromData.Abstract;
2015     ToData.IsStandardLayout = FromData.IsStandardLayout;
2016     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2017     ToData.HasPrivateFields = FromData.HasPrivateFields;
2018     ToData.HasProtectedFields = FromData.HasProtectedFields;
2019     ToData.HasPublicFields = FromData.HasPublicFields;
2020     ToData.HasMutableFields = FromData.HasMutableFields;
2021     ToData.HasVariantMembers = FromData.HasVariantMembers;
2022     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2023     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2024     ToData.HasUninitializedReferenceMember
2025       = FromData.HasUninitializedReferenceMember;
2026     ToData.NeedOverloadResolutionForMoveConstructor
2027       = FromData.NeedOverloadResolutionForMoveConstructor;
2028     ToData.NeedOverloadResolutionForMoveAssignment
2029       = FromData.NeedOverloadResolutionForMoveAssignment;
2030     ToData.NeedOverloadResolutionForDestructor
2031       = FromData.NeedOverloadResolutionForDestructor;
2032     ToData.DefaultedMoveConstructorIsDeleted
2033       = FromData.DefaultedMoveConstructorIsDeleted;
2034     ToData.DefaultedMoveAssignmentIsDeleted
2035       = FromData.DefaultedMoveAssignmentIsDeleted;
2036     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2037     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2038     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2039     ToData.HasConstexprNonCopyMoveConstructor
2040       = FromData.HasConstexprNonCopyMoveConstructor;
2041     ToData.DefaultedDefaultConstructorIsConstexpr
2042       = FromData.DefaultedDefaultConstructorIsConstexpr;
2043     ToData.HasConstexprDefaultConstructor
2044       = FromData.HasConstexprDefaultConstructor;
2045     ToData.HasNonLiteralTypeFieldsOrBases
2046       = FromData.HasNonLiteralTypeFieldsOrBases;
2047     // ComputedVisibleConversions not imported.
2048     ToData.UserProvidedDefaultConstructor
2049       = FromData.UserProvidedDefaultConstructor;
2050     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2051     ToData.ImplicitCopyConstructorHasConstParam
2052       = FromData.ImplicitCopyConstructorHasConstParam;
2053     ToData.ImplicitCopyAssignmentHasConstParam
2054       = FromData.ImplicitCopyAssignmentHasConstParam;
2055     ToData.HasDeclaredCopyConstructorWithConstParam
2056       = FromData.HasDeclaredCopyConstructorWithConstParam;
2057     ToData.HasDeclaredCopyAssignmentWithConstParam
2058       = FromData.HasDeclaredCopyAssignmentWithConstParam;
2059     ToData.IsLambda = FromData.IsLambda;
2060
2061     SmallVector<CXXBaseSpecifier *, 4> Bases;
2062     for (const auto &Base1 : FromCXX->bases()) {
2063       QualType T = Importer.Import(Base1.getType());
2064       if (T.isNull())
2065         return true;
2066
2067       SourceLocation EllipsisLoc;
2068       if (Base1.isPackExpansion())
2069         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2070
2071       // Ensure that we have a definition for the base.
2072       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2073         
2074       Bases.push_back(
2075                     new (Importer.getToContext()) 
2076                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2077                                        Base1.isVirtual(),
2078                                        Base1.isBaseOfClass(),
2079                                        Base1.getAccessSpecifierAsWritten(),
2080                                    Importer.Import(Base1.getTypeSourceInfo()),
2081                                        EllipsisLoc));
2082     }
2083     if (!Bases.empty())
2084       ToCXX->setBases(Bases.data(), Bases.size());
2085   }
2086   
2087   if (shouldForceImportDeclContext(Kind))
2088     ImportDeclContext(From, /*ForceImport=*/true);
2089   
2090   To->completeDefinition();
2091   return false;
2092 }
2093
2094 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2095                                        ImportDefinitionKind Kind) {
2096   if (To->getAnyInitializer())
2097     return false;
2098
2099   // FIXME: Can we really import any initializer? Alternatively, we could force
2100   // ourselves to import every declaration of a variable and then only use
2101   // getInit() here.
2102   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2103
2104   // FIXME: Other bits to merge?
2105
2106   return false;
2107 }
2108
2109 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, 
2110                                        ImportDefinitionKind Kind) {
2111   if (To->getDefinition() || To->isBeingDefined()) {
2112     if (Kind == IDK_Everything)
2113       ImportDeclContext(From, /*ForceImport=*/true);
2114     return false;
2115   }
2116   
2117   To->startDefinition();
2118
2119   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2120   if (T.isNull())
2121     return true;
2122   
2123   QualType ToPromotionType = Importer.Import(From->getPromotionType());
2124   if (ToPromotionType.isNull())
2125     return true;
2126
2127   if (shouldForceImportDeclContext(Kind))
2128     ImportDeclContext(From, /*ForceImport=*/true);
2129   
2130   // FIXME: we might need to merge the number of positive or negative bits
2131   // if the enumerator lists don't match.
2132   To->completeDefinition(T, ToPromotionType,
2133                          From->getNumPositiveBits(),
2134                          From->getNumNegativeBits());
2135   return false;
2136 }
2137
2138 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2139                                                 TemplateParameterList *Params) {
2140   SmallVector<NamedDecl *, 4> ToParams;
2141   ToParams.reserve(Params->size());
2142   for (TemplateParameterList::iterator P = Params->begin(), 
2143                                     PEnd = Params->end();
2144        P != PEnd; ++P) {
2145     Decl *To = Importer.Import(*P);
2146     if (!To)
2147       return nullptr;
2148
2149     ToParams.push_back(cast<NamedDecl>(To));
2150   }
2151   
2152   return TemplateParameterList::Create(Importer.getToContext(),
2153                                        Importer.Import(Params->getTemplateLoc()),
2154                                        Importer.Import(Params->getLAngleLoc()),
2155                                        ToParams,
2156                                        Importer.Import(Params->getRAngleLoc()));
2157 }
2158
2159 TemplateArgument 
2160 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2161   switch (From.getKind()) {
2162   case TemplateArgument::Null:
2163     return TemplateArgument();
2164      
2165   case TemplateArgument::Type: {
2166     QualType ToType = Importer.Import(From.getAsType());
2167     if (ToType.isNull())
2168       return TemplateArgument();
2169     return TemplateArgument(ToType);
2170   }
2171       
2172   case TemplateArgument::Integral: {
2173     QualType ToType = Importer.Import(From.getIntegralType());
2174     if (ToType.isNull())
2175       return TemplateArgument();
2176     return TemplateArgument(From, ToType);
2177   }
2178
2179   case TemplateArgument::Declaration: {
2180     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2181     QualType ToType = Importer.Import(From.getParamTypeForDecl());
2182     if (!To || ToType.isNull())
2183       return TemplateArgument();
2184     return TemplateArgument(To, ToType);
2185   }
2186
2187   case TemplateArgument::NullPtr: {
2188     QualType ToType = Importer.Import(From.getNullPtrType());
2189     if (ToType.isNull())
2190       return TemplateArgument();
2191     return TemplateArgument(ToType, /*isNullPtr*/true);
2192   }
2193
2194   case TemplateArgument::Template: {
2195     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2196     if (ToTemplate.isNull())
2197       return TemplateArgument();
2198     
2199     return TemplateArgument(ToTemplate);
2200   }
2201
2202   case TemplateArgument::TemplateExpansion: {
2203     TemplateName ToTemplate 
2204       = Importer.Import(From.getAsTemplateOrTemplatePattern());
2205     if (ToTemplate.isNull())
2206       return TemplateArgument();
2207     
2208     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2209   }
2210
2211   case TemplateArgument::Expression:
2212     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2213       return TemplateArgument(ToExpr);
2214     return TemplateArgument();
2215       
2216   case TemplateArgument::Pack: {
2217     SmallVector<TemplateArgument, 2> ToPack;
2218     ToPack.reserve(From.pack_size());
2219     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2220       return TemplateArgument();
2221
2222     return TemplateArgument(
2223         llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2224   }
2225   }
2226   
2227   llvm_unreachable("Invalid template argument kind");
2228 }
2229
2230 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2231                                               unsigned NumFromArgs,
2232                               SmallVectorImpl<TemplateArgument> &ToArgs) {
2233   for (unsigned I = 0; I != NumFromArgs; ++I) {
2234     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2235     if (To.isNull() && !FromArgs[I].isNull())
2236       return true;
2237     
2238     ToArgs.push_back(To);
2239   }
2240   
2241   return false;
2242 }
2243
2244 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, 
2245                                         RecordDecl *ToRecord, bool Complain) {
2246   // Eliminate a potential failure point where we attempt to re-import
2247   // something we're trying to import while completing ToRecord.
2248   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2249   if (ToOrigin) {
2250     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2251     if (ToOriginRecord)
2252       ToRecord = ToOriginRecord;
2253   }
2254
2255   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2256                                    ToRecord->getASTContext(),
2257                                    Importer.getNonEquivalentDecls(),
2258                                    false, Complain);
2259   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2260 }
2261
2262 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2263                                         bool Complain) {
2264   StructuralEquivalenceContext Ctx(
2265       Importer.getFromContext(), Importer.getToContext(),
2266       Importer.getNonEquivalentDecls(), false, Complain);
2267   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2268 }
2269
2270 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2271   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2272                                    Importer.getToContext(),
2273                                    Importer.getNonEquivalentDecls());
2274   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2275 }
2276
2277 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2278                                         EnumConstantDecl *ToEC)
2279 {
2280   const llvm::APSInt &FromVal = FromEC->getInitVal();
2281   const llvm::APSInt &ToVal = ToEC->getInitVal();
2282
2283   return FromVal.isSigned() == ToVal.isSigned() &&
2284          FromVal.getBitWidth() == ToVal.getBitWidth() &&
2285          FromVal == ToVal;
2286 }
2287
2288 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2289                                         ClassTemplateDecl *To) {
2290   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2291                                    Importer.getToContext(),
2292                                    Importer.getNonEquivalentDecls());
2293   return Ctx.IsStructurallyEquivalent(From, To);  
2294 }
2295
2296 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2297                                         VarTemplateDecl *To) {
2298   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2299                                    Importer.getToContext(),
2300                                    Importer.getNonEquivalentDecls());
2301   return Ctx.IsStructurallyEquivalent(From, To);
2302 }
2303
2304 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2305   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2306     << D->getDeclKindName();
2307   return nullptr;
2308 }
2309
2310 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2311   TranslationUnitDecl *ToD = 
2312     Importer.getToContext().getTranslationUnitDecl();
2313     
2314   Importer.Imported(D, ToD);
2315     
2316   return ToD;
2317 }
2318
2319 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2320   // Import the major distinguishing characteristics of this namespace.
2321   DeclContext *DC, *LexicalDC;
2322   DeclarationName Name;
2323   SourceLocation Loc;
2324   NamedDecl *ToD;
2325   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2326     return nullptr;
2327   if (ToD)
2328     return ToD;
2329
2330   NamespaceDecl *MergeWithNamespace = nullptr;
2331   if (!Name) {
2332     // This is an anonymous namespace. Adopt an existing anonymous
2333     // namespace if we can.
2334     // FIXME: Not testable.
2335     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2336       MergeWithNamespace = TU->getAnonymousNamespace();
2337     else
2338       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2339   } else {
2340     SmallVector<NamedDecl *, 4> ConflictingDecls;
2341     SmallVector<NamedDecl *, 2> FoundDecls;
2342     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2343     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2344       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2345         continue;
2346       
2347       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2348         MergeWithNamespace = FoundNS;
2349         ConflictingDecls.clear();
2350         break;
2351       }
2352       
2353       ConflictingDecls.push_back(FoundDecls[I]);
2354     }
2355     
2356     if (!ConflictingDecls.empty()) {
2357       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2358                                          ConflictingDecls.data(), 
2359                                          ConflictingDecls.size());
2360     }
2361   }
2362   
2363   // Create the "to" namespace, if needed.
2364   NamespaceDecl *ToNamespace = MergeWithNamespace;
2365   if (!ToNamespace) {
2366     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2367                                         D->isInline(),
2368                                         Importer.Import(D->getLocStart()),
2369                                         Loc, Name.getAsIdentifierInfo(),
2370                                         /*PrevDecl=*/nullptr);
2371     ToNamespace->setLexicalDeclContext(LexicalDC);
2372     LexicalDC->addDeclInternal(ToNamespace);
2373     
2374     // If this is an anonymous namespace, register it as the anonymous
2375     // namespace within its context.
2376     if (!Name) {
2377       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2378         TU->setAnonymousNamespace(ToNamespace);
2379       else
2380         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2381     }
2382   }
2383   Importer.Imported(D, ToNamespace);
2384   
2385   ImportDeclContext(D);
2386   
2387   return ToNamespace;
2388 }
2389
2390 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2391   // Import the major distinguishing characteristics of this typedef.
2392   DeclContext *DC, *LexicalDC;
2393   DeclarationName Name;
2394   SourceLocation Loc;
2395   NamedDecl *ToD;
2396   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2397     return nullptr;
2398   if (ToD)
2399     return ToD;
2400
2401   // If this typedef is not in block scope, determine whether we've
2402   // seen a typedef with the same name (that we can merge with) or any
2403   // other entity by that name (which name lookup could conflict with).
2404   if (!DC->isFunctionOrMethod()) {
2405     SmallVector<NamedDecl *, 4> ConflictingDecls;
2406     unsigned IDNS = Decl::IDNS_Ordinary;
2407     SmallVector<NamedDecl *, 2> FoundDecls;
2408     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2409     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2410       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2411         continue;
2412       if (TypedefNameDecl *FoundTypedef =
2413             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2414         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2415                                             FoundTypedef->getUnderlyingType()))
2416           return Importer.Imported(D, FoundTypedef);
2417       }
2418       
2419       ConflictingDecls.push_back(FoundDecls[I]);
2420     }
2421     
2422     if (!ConflictingDecls.empty()) {
2423       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2424                                          ConflictingDecls.data(), 
2425                                          ConflictingDecls.size());
2426       if (!Name)
2427         return nullptr;
2428     }
2429   }
2430   
2431   // Import the underlying type of this typedef;
2432   QualType T = Importer.Import(D->getUnderlyingType());
2433   if (T.isNull())
2434     return nullptr;
2435
2436   // Create the new typedef node.
2437   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2438   SourceLocation StartL = Importer.Import(D->getLocStart());
2439   TypedefNameDecl *ToTypedef;
2440   if (IsAlias)
2441     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2442                                       StartL, Loc,
2443                                       Name.getAsIdentifierInfo(),
2444                                       TInfo);
2445   else
2446     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2447                                     StartL, Loc,
2448                                     Name.getAsIdentifierInfo(),
2449                                     TInfo);
2450   
2451   ToTypedef->setAccess(D->getAccess());
2452   ToTypedef->setLexicalDeclContext(LexicalDC);
2453   Importer.Imported(D, ToTypedef);
2454   LexicalDC->addDeclInternal(ToTypedef);
2455   
2456   return ToTypedef;
2457 }
2458
2459 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2460   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2461 }
2462
2463 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2464   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2465 }
2466
2467 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2468   // Import the major distinguishing characteristics of this enum.
2469   DeclContext *DC, *LexicalDC;
2470   DeclarationName Name;
2471   SourceLocation Loc;
2472   NamedDecl *ToD;
2473   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2474     return nullptr;
2475   if (ToD)
2476     return ToD;
2477
2478   // Figure out what enum name we're looking for.
2479   unsigned IDNS = Decl::IDNS_Tag;
2480   DeclarationName SearchName = Name;
2481   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2482     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2483     IDNS = Decl::IDNS_Ordinary;
2484   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2485     IDNS |= Decl::IDNS_Ordinary;
2486   
2487   // We may already have an enum of the same name; try to find and match it.
2488   if (!DC->isFunctionOrMethod() && SearchName) {
2489     SmallVector<NamedDecl *, 4> ConflictingDecls;
2490     SmallVector<NamedDecl *, 2> FoundDecls;
2491     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2492     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2493       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2494         continue;
2495       
2496       Decl *Found = FoundDecls[I];
2497       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2498         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2499           Found = Tag->getDecl();
2500       }
2501       
2502       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2503         if (IsStructuralMatch(D, FoundEnum))
2504           return Importer.Imported(D, FoundEnum);
2505       }
2506       
2507       ConflictingDecls.push_back(FoundDecls[I]);
2508     }
2509     
2510     if (!ConflictingDecls.empty()) {
2511       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2512                                          ConflictingDecls.data(), 
2513                                          ConflictingDecls.size());
2514     }
2515   }
2516   
2517   // Create the enum declaration.
2518   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2519                                   Importer.Import(D->getLocStart()),
2520                                   Loc, Name.getAsIdentifierInfo(), nullptr,
2521                                   D->isScoped(), D->isScopedUsingClassTag(),
2522                                   D->isFixed());
2523   // Import the qualifier, if any.
2524   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2525   D2->setAccess(D->getAccess());
2526   D2->setLexicalDeclContext(LexicalDC);
2527   Importer.Imported(D, D2);
2528   LexicalDC->addDeclInternal(D2);
2529
2530   // Import the integer type.
2531   QualType ToIntegerType = Importer.Import(D->getIntegerType());
2532   if (ToIntegerType.isNull())
2533     return nullptr;
2534   D2->setIntegerType(ToIntegerType);
2535   
2536   // Import the definition
2537   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2538     return nullptr;
2539
2540   return D2;
2541 }
2542
2543 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2544   // If this record has a definition in the translation unit we're coming from,
2545   // but this particular declaration is not that definition, import the
2546   // definition and map to that.
2547   TagDecl *Definition = D->getDefinition();
2548   if (Definition && Definition != D) {
2549     Decl *ImportedDef = Importer.Import(Definition);
2550     if (!ImportedDef)
2551       return nullptr;
2552
2553     return Importer.Imported(D, ImportedDef);
2554   }
2555   
2556   // Import the major distinguishing characteristics of this record.
2557   DeclContext *DC, *LexicalDC;
2558   DeclarationName Name;
2559   SourceLocation Loc;
2560   NamedDecl *ToD;
2561   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2562     return nullptr;
2563   if (ToD)
2564     return ToD;
2565
2566   // Figure out what structure name we're looking for.
2567   unsigned IDNS = Decl::IDNS_Tag;
2568   DeclarationName SearchName = Name;
2569   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2570     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2571     IDNS = Decl::IDNS_Ordinary;
2572   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2573     IDNS |= Decl::IDNS_Ordinary;
2574
2575   // We may already have a record of the same name; try to find and match it.
2576   RecordDecl *AdoptDecl = nullptr;
2577   if (!DC->isFunctionOrMethod()) {
2578     SmallVector<NamedDecl *, 4> ConflictingDecls;
2579     SmallVector<NamedDecl *, 2> FoundDecls;
2580     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2581     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2582       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2583         continue;
2584       
2585       Decl *Found = FoundDecls[I];
2586       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2587         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2588           Found = Tag->getDecl();
2589       }
2590       
2591       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2592         if (D->isAnonymousStructOrUnion() && 
2593             FoundRecord->isAnonymousStructOrUnion()) {
2594           // If both anonymous structs/unions are in a record context, make sure
2595           // they occur in the same location in the context records.
2596           if (Optional<unsigned> Index1
2597               = findAnonymousStructOrUnionIndex(D)) {
2598             if (Optional<unsigned> Index2 =
2599                     findAnonymousStructOrUnionIndex(FoundRecord)) {
2600               if (*Index1 != *Index2)
2601                 continue;
2602             }
2603           }
2604         }
2605
2606         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2607           if ((SearchName && !D->isCompleteDefinition())
2608               || (D->isCompleteDefinition() &&
2609                   D->isAnonymousStructOrUnion()
2610                     == FoundDef->isAnonymousStructOrUnion() &&
2611                   IsStructuralMatch(D, FoundDef))) {
2612             // The record types structurally match, or the "from" translation
2613             // unit only had a forward declaration anyway; call it the same
2614             // function.
2615             // FIXME: For C++, we should also merge methods here.
2616             return Importer.Imported(D, FoundDef);
2617           }
2618         } else if (!D->isCompleteDefinition()) {
2619           // We have a forward declaration of this type, so adopt that forward
2620           // declaration rather than building a new one.
2621             
2622           // If one or both can be completed from external storage then try one
2623           // last time to complete and compare them before doing this.
2624             
2625           if (FoundRecord->hasExternalLexicalStorage() &&
2626               !FoundRecord->isCompleteDefinition())
2627             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2628           if (D->hasExternalLexicalStorage())
2629             D->getASTContext().getExternalSource()->CompleteType(D);
2630             
2631           if (FoundRecord->isCompleteDefinition() &&
2632               D->isCompleteDefinition() &&
2633               !IsStructuralMatch(D, FoundRecord))
2634             continue;
2635               
2636           AdoptDecl = FoundRecord;
2637           continue;
2638         } else if (!SearchName) {
2639           continue;
2640         }
2641       }
2642       
2643       ConflictingDecls.push_back(FoundDecls[I]);
2644     }
2645     
2646     if (!ConflictingDecls.empty() && SearchName) {
2647       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2648                                          ConflictingDecls.data(), 
2649                                          ConflictingDecls.size());
2650     }
2651   }
2652   
2653   // Create the record declaration.
2654   RecordDecl *D2 = AdoptDecl;
2655   SourceLocation StartLoc = Importer.Import(D->getLocStart());
2656   if (!D2) {
2657     if (isa<CXXRecordDecl>(D)) {
2658       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(), 
2659                                                    D->getTagKind(),
2660                                                    DC, StartLoc, Loc,
2661                                                    Name.getAsIdentifierInfo());
2662       D2 = D2CXX;
2663       D2->setAccess(D->getAccess());
2664     } else {
2665       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2666                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2667     }
2668     
2669     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2670     D2->setLexicalDeclContext(LexicalDC);
2671     LexicalDC->addDeclInternal(D2);
2672     if (D->isAnonymousStructOrUnion())
2673       D2->setAnonymousStructOrUnion(true);
2674   }
2675   
2676   Importer.Imported(D, D2);
2677
2678   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2679     return nullptr;
2680
2681   return D2;
2682 }
2683
2684 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2685   // Import the major distinguishing characteristics of this enumerator.
2686   DeclContext *DC, *LexicalDC;
2687   DeclarationName Name;
2688   SourceLocation Loc;
2689   NamedDecl *ToD;
2690   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2691     return nullptr;
2692   if (ToD)
2693     return ToD;
2694
2695   QualType T = Importer.Import(D->getType());
2696   if (T.isNull())
2697     return nullptr;
2698
2699   // Determine whether there are any other declarations with the same name and 
2700   // in the same context.
2701   if (!LexicalDC->isFunctionOrMethod()) {
2702     SmallVector<NamedDecl *, 4> ConflictingDecls;
2703     unsigned IDNS = Decl::IDNS_Ordinary;
2704     SmallVector<NamedDecl *, 2> FoundDecls;
2705     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2706     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2707       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2708         continue;
2709
2710       if (EnumConstantDecl *FoundEnumConstant
2711             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2712         if (IsStructuralMatch(D, FoundEnumConstant))
2713           return Importer.Imported(D, FoundEnumConstant);
2714       }
2715
2716       ConflictingDecls.push_back(FoundDecls[I]);
2717     }
2718     
2719     if (!ConflictingDecls.empty()) {
2720       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2721                                          ConflictingDecls.data(), 
2722                                          ConflictingDecls.size());
2723       if (!Name)
2724         return nullptr;
2725     }
2726   }
2727   
2728   Expr *Init = Importer.Import(D->getInitExpr());
2729   if (D->getInitExpr() && !Init)
2730     return nullptr;
2731
2732   EnumConstantDecl *ToEnumerator
2733     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc, 
2734                                Name.getAsIdentifierInfo(), T, 
2735                                Init, D->getInitVal());
2736   ToEnumerator->setAccess(D->getAccess());
2737   ToEnumerator->setLexicalDeclContext(LexicalDC);
2738   Importer.Imported(D, ToEnumerator);
2739   LexicalDC->addDeclInternal(ToEnumerator);
2740   return ToEnumerator;
2741 }
2742
2743 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2744   // Import the major distinguishing characteristics of this function.
2745   DeclContext *DC, *LexicalDC;
2746   DeclarationName Name;
2747   SourceLocation Loc;
2748   NamedDecl *ToD;
2749   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2750     return nullptr;
2751   if (ToD)
2752     return ToD;
2753
2754   // Try to find a function in our own ("to") context with the same name, same
2755   // type, and in the same context as the function we're importing.
2756   if (!LexicalDC->isFunctionOrMethod()) {
2757     SmallVector<NamedDecl *, 4> ConflictingDecls;
2758     unsigned IDNS = Decl::IDNS_Ordinary;
2759     SmallVector<NamedDecl *, 2> FoundDecls;
2760     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2761     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2762       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2763         continue;
2764     
2765       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2766         if (FoundFunction->hasExternalFormalLinkage() &&
2767             D->hasExternalFormalLinkage()) {
2768           if (Importer.IsStructurallyEquivalent(D->getType(), 
2769                                                 FoundFunction->getType())) {
2770             // FIXME: Actually try to merge the body and other attributes.
2771             return Importer.Imported(D, FoundFunction);
2772           }
2773         
2774           // FIXME: Check for overloading more carefully, e.g., by boosting
2775           // Sema::IsOverload out to the AST library.
2776           
2777           // Function overloading is okay in C++.
2778           if (Importer.getToContext().getLangOpts().CPlusPlus)
2779             continue;
2780           
2781           // Complain about inconsistent function types.
2782           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2783             << Name << D->getType() << FoundFunction->getType();
2784           Importer.ToDiag(FoundFunction->getLocation(), 
2785                           diag::note_odr_value_here)
2786             << FoundFunction->getType();
2787         }
2788       }
2789       
2790       ConflictingDecls.push_back(FoundDecls[I]);
2791     }
2792     
2793     if (!ConflictingDecls.empty()) {
2794       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2795                                          ConflictingDecls.data(), 
2796                                          ConflictingDecls.size());
2797       if (!Name)
2798         return nullptr;
2799     }    
2800   }
2801
2802   DeclarationNameInfo NameInfo(Name, Loc);
2803   // Import additional name location/type info.
2804   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2805
2806   QualType FromTy = D->getType();
2807   bool usedDifferentExceptionSpec = false;
2808
2809   if (const FunctionProtoType *
2810         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2811     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2812     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2813     // FunctionDecl that we are importing the FunctionProtoType for.
2814     // To avoid an infinite recursion when importing, create the FunctionDecl
2815     // with a simplified function type and update it afterwards.
2816     if (FromEPI.ExceptionSpec.SourceDecl ||
2817         FromEPI.ExceptionSpec.SourceTemplate ||
2818         FromEPI.ExceptionSpec.NoexceptExpr) {
2819       FunctionProtoType::ExtProtoInfo DefaultEPI;
2820       FromTy = Importer.getFromContext().getFunctionType(
2821           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2822       usedDifferentExceptionSpec = true;
2823     }
2824   }
2825
2826   // Import the type.
2827   QualType T = Importer.Import(FromTy);
2828   if (T.isNull())
2829     return nullptr;
2830
2831   // Import the function parameters.
2832   SmallVector<ParmVarDecl *, 8> Parameters;
2833   for (auto P : D->params()) {
2834     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2835     if (!ToP)
2836       return nullptr;
2837
2838     Parameters.push_back(ToP);
2839   }
2840   
2841   // Create the imported function.
2842   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2843   FunctionDecl *ToFunction = nullptr;
2844   SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2845   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2846     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2847                                             cast<CXXRecordDecl>(DC),
2848                                             InnerLocStart,
2849                                             NameInfo, T, TInfo, 
2850                                             FromConstructor->isExplicit(),
2851                                             D->isInlineSpecified(), 
2852                                             D->isImplicit(),
2853                                             D->isConstexpr());
2854   } else if (isa<CXXDestructorDecl>(D)) {
2855     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2856                                            cast<CXXRecordDecl>(DC),
2857                                            InnerLocStart,
2858                                            NameInfo, T, TInfo,
2859                                            D->isInlineSpecified(),
2860                                            D->isImplicit());
2861   } else if (CXXConversionDecl *FromConversion
2862                                            = dyn_cast<CXXConversionDecl>(D)) {
2863     ToFunction = CXXConversionDecl::Create(Importer.getToContext(), 
2864                                            cast<CXXRecordDecl>(DC),
2865                                            InnerLocStart,
2866                                            NameInfo, T, TInfo,
2867                                            D->isInlineSpecified(),
2868                                            FromConversion->isExplicit(),
2869                                            D->isConstexpr(),
2870                                            Importer.Import(D->getLocEnd()));
2871   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2872     ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
2873                                        cast<CXXRecordDecl>(DC),
2874                                        InnerLocStart,
2875                                        NameInfo, T, TInfo,
2876                                        Method->getStorageClass(),
2877                                        Method->isInlineSpecified(),
2878                                        D->isConstexpr(),
2879                                        Importer.Import(D->getLocEnd()));
2880   } else {
2881     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2882                                       InnerLocStart,
2883                                       NameInfo, T, TInfo, D->getStorageClass(),
2884                                       D->isInlineSpecified(),
2885                                       D->hasWrittenPrototype(),
2886                                       D->isConstexpr());
2887   }
2888
2889   // Import the qualifier, if any.
2890   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2891   ToFunction->setAccess(D->getAccess());
2892   ToFunction->setLexicalDeclContext(LexicalDC);
2893   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2894   ToFunction->setTrivial(D->isTrivial());
2895   ToFunction->setPure(D->isPure());
2896   Importer.Imported(D, ToFunction);
2897
2898   // Set the parameters.
2899   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2900     Parameters[I]->setOwningFunction(ToFunction);
2901     ToFunction->addDeclInternal(Parameters[I]);
2902   }
2903   ToFunction->setParams(Parameters);
2904
2905   if (usedDifferentExceptionSpec) {
2906     // Update FunctionProtoType::ExtProtoInfo.
2907     QualType T = Importer.Import(D->getType());
2908     if (T.isNull())
2909       return nullptr;
2910     ToFunction->setType(T);
2911   }
2912
2913   // Import the body, if any.
2914   if (Stmt *FromBody = D->getBody()) {
2915     if (Stmt *ToBody = Importer.Import(FromBody)) {
2916       ToFunction->setBody(ToBody);
2917     }
2918   }
2919
2920   // FIXME: Other bits to merge?
2921
2922   // Add this function to the lexical context.
2923   LexicalDC->addDeclInternal(ToFunction);
2924
2925   return ToFunction;
2926 }
2927
2928 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2929   return VisitFunctionDecl(D);
2930 }
2931
2932 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2933   return VisitCXXMethodDecl(D);
2934 }
2935
2936 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2937   return VisitCXXMethodDecl(D);
2938 }
2939
2940 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2941   return VisitCXXMethodDecl(D);
2942 }
2943
2944 static unsigned getFieldIndex(Decl *F) {
2945   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2946   if (!Owner)
2947     return 0;
2948
2949   unsigned Index = 1;
2950   for (const auto *D : Owner->noload_decls()) {
2951     if (D == F)
2952       return Index;
2953
2954     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2955       ++Index;
2956   }
2957
2958   return Index;
2959 }
2960
2961 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2962   // Import the major distinguishing characteristics of a variable.
2963   DeclContext *DC, *LexicalDC;
2964   DeclarationName Name;
2965   SourceLocation Loc;
2966   NamedDecl *ToD;
2967   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2968     return nullptr;
2969   if (ToD)
2970     return ToD;
2971
2972   // Determine whether we've already imported this field. 
2973   SmallVector<NamedDecl *, 2> FoundDecls;
2974   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2975   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2976     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2977       // For anonymous fields, match up by index.
2978       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2979         continue;
2980
2981       if (Importer.IsStructurallyEquivalent(D->getType(), 
2982                                             FoundField->getType())) {
2983         Importer.Imported(D, FoundField);
2984         return FoundField;
2985       }
2986       
2987       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2988         << Name << D->getType() << FoundField->getType();
2989       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2990         << FoundField->getType();
2991       return nullptr;
2992     }
2993   }
2994
2995   // Import the type.
2996   QualType T = Importer.Import(D->getType());
2997   if (T.isNull())
2998     return nullptr;
2999
3000   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3001   Expr *BitWidth = Importer.Import(D->getBitWidth());
3002   if (!BitWidth && D->getBitWidth())
3003     return nullptr;
3004
3005   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
3006                                          Importer.Import(D->getInnerLocStart()),
3007                                          Loc, Name.getAsIdentifierInfo(),
3008                                          T, TInfo, BitWidth, D->isMutable(),
3009                                          D->getInClassInitStyle());
3010   ToField->setAccess(D->getAccess());
3011   ToField->setLexicalDeclContext(LexicalDC);
3012   if (ToField->hasInClassInitializer())
3013     ToField->setInClassInitializer(D->getInClassInitializer());
3014   ToField->setImplicit(D->isImplicit());
3015   Importer.Imported(D, ToField);
3016   LexicalDC->addDeclInternal(ToField);
3017   return ToField;
3018 }
3019
3020 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3021   // Import the major distinguishing characteristics of a variable.
3022   DeclContext *DC, *LexicalDC;
3023   DeclarationName Name;
3024   SourceLocation Loc;
3025   NamedDecl *ToD;
3026   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3027     return nullptr;
3028   if (ToD)
3029     return ToD;
3030
3031   // Determine whether we've already imported this field. 
3032   SmallVector<NamedDecl *, 2> FoundDecls;
3033   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3034   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3035     if (IndirectFieldDecl *FoundField 
3036                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3037       // For anonymous indirect fields, match up by index.
3038       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3039         continue;
3040
3041       if (Importer.IsStructurallyEquivalent(D->getType(), 
3042                                             FoundField->getType(),
3043                                             !Name.isEmpty())) {
3044         Importer.Imported(D, FoundField);
3045         return FoundField;
3046       }
3047
3048       // If there are more anonymous fields to check, continue.
3049       if (!Name && I < N-1)
3050         continue;
3051
3052       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3053         << Name << D->getType() << FoundField->getType();
3054       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3055         << FoundField->getType();
3056       return nullptr;
3057     }
3058   }
3059
3060   // Import the type.
3061   QualType T = Importer.Import(D->getType());
3062   if (T.isNull())
3063     return nullptr;
3064
3065   NamedDecl **NamedChain =
3066     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3067
3068   unsigned i = 0;
3069   for (auto *PI : D->chain()) {
3070     Decl *D = Importer.Import(PI);
3071     if (!D)
3072       return nullptr;
3073     NamedChain[i++] = cast<NamedDecl>(D);
3074   }
3075
3076   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3077       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3078       NamedChain, D->getChainingSize());
3079
3080   for (const auto *Attr : D->attrs())
3081     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3082
3083   ToIndirectField->setAccess(D->getAccess());
3084   ToIndirectField->setLexicalDeclContext(LexicalDC);
3085   Importer.Imported(D, ToIndirectField);
3086   LexicalDC->addDeclInternal(ToIndirectField);
3087   return ToIndirectField;
3088 }
3089
3090 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3091   // Import the major distinguishing characteristics of an ivar.
3092   DeclContext *DC, *LexicalDC;
3093   DeclarationName Name;
3094   SourceLocation Loc;
3095   NamedDecl *ToD;
3096   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3097     return nullptr;
3098   if (ToD)
3099     return ToD;
3100
3101   // Determine whether we've already imported this ivar 
3102   SmallVector<NamedDecl *, 2> FoundDecls;
3103   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3104   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3105     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3106       if (Importer.IsStructurallyEquivalent(D->getType(), 
3107                                             FoundIvar->getType())) {
3108         Importer.Imported(D, FoundIvar);
3109         return FoundIvar;
3110       }
3111
3112       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3113         << Name << D->getType() << FoundIvar->getType();
3114       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3115         << FoundIvar->getType();
3116       return nullptr;
3117     }
3118   }
3119
3120   // Import the type.
3121   QualType T = Importer.Import(D->getType());
3122   if (T.isNull())
3123     return nullptr;
3124
3125   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3126   Expr *BitWidth = Importer.Import(D->getBitWidth());
3127   if (!BitWidth && D->getBitWidth())
3128     return nullptr;
3129
3130   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3131                                               cast<ObjCContainerDecl>(DC),
3132                                        Importer.Import(D->getInnerLocStart()),
3133                                               Loc, Name.getAsIdentifierInfo(),
3134                                               T, TInfo, D->getAccessControl(),
3135                                               BitWidth, D->getSynthesize());
3136   ToIvar->setLexicalDeclContext(LexicalDC);
3137   Importer.Imported(D, ToIvar);
3138   LexicalDC->addDeclInternal(ToIvar);
3139   return ToIvar;
3140   
3141 }
3142
3143 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3144   // Import the major distinguishing characteristics of a variable.
3145   DeclContext *DC, *LexicalDC;
3146   DeclarationName Name;
3147   SourceLocation Loc;
3148   NamedDecl *ToD;
3149   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3150     return nullptr;
3151   if (ToD)
3152     return ToD;
3153
3154   // Try to find a variable in our own ("to") context with the same name and
3155   // in the same context as the variable we're importing.
3156   if (D->isFileVarDecl()) {
3157     VarDecl *MergeWithVar = nullptr;
3158     SmallVector<NamedDecl *, 4> ConflictingDecls;
3159     unsigned IDNS = Decl::IDNS_Ordinary;
3160     SmallVector<NamedDecl *, 2> FoundDecls;
3161     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3162     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3163       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3164         continue;
3165       
3166       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3167         // We have found a variable that we may need to merge with. Check it.
3168         if (FoundVar->hasExternalFormalLinkage() &&
3169             D->hasExternalFormalLinkage()) {
3170           if (Importer.IsStructurallyEquivalent(D->getType(), 
3171                                                 FoundVar->getType())) {
3172             MergeWithVar = FoundVar;
3173             break;
3174           }
3175
3176           const ArrayType *FoundArray
3177             = Importer.getToContext().getAsArrayType(FoundVar->getType());
3178           const ArrayType *TArray
3179             = Importer.getToContext().getAsArrayType(D->getType());
3180           if (FoundArray && TArray) {
3181             if (isa<IncompleteArrayType>(FoundArray) &&
3182                 isa<ConstantArrayType>(TArray)) {
3183               // Import the type.
3184               QualType T = Importer.Import(D->getType());
3185               if (T.isNull())
3186                 return nullptr;
3187
3188               FoundVar->setType(T);
3189               MergeWithVar = FoundVar;
3190               break;
3191             } else if (isa<IncompleteArrayType>(TArray) &&
3192                        isa<ConstantArrayType>(FoundArray)) {
3193               MergeWithVar = FoundVar;
3194               break;
3195             }
3196           }
3197
3198           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3199             << Name << D->getType() << FoundVar->getType();
3200           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3201             << FoundVar->getType();
3202         }
3203       }
3204       
3205       ConflictingDecls.push_back(FoundDecls[I]);
3206     }
3207
3208     if (MergeWithVar) {
3209       // An equivalent variable with external linkage has been found. Link 
3210       // the two declarations, then merge them.
3211       Importer.Imported(D, MergeWithVar);
3212       
3213       if (VarDecl *DDef = D->getDefinition()) {
3214         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3215           Importer.ToDiag(ExistingDef->getLocation(), 
3216                           diag::err_odr_variable_multiple_def)
3217             << Name;
3218           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3219         } else {
3220           Expr *Init = Importer.Import(DDef->getInit());
3221           MergeWithVar->setInit(Init);
3222           if (DDef->isInitKnownICE()) {
3223             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3224             Eval->CheckedICE = true;
3225             Eval->IsICE = DDef->isInitICE();
3226           }
3227         }
3228       }
3229       
3230       return MergeWithVar;
3231     }
3232     
3233     if (!ConflictingDecls.empty()) {
3234       Name = Importer.HandleNameConflict(Name, DC, IDNS,
3235                                          ConflictingDecls.data(), 
3236                                          ConflictingDecls.size());
3237       if (!Name)
3238         return nullptr;
3239     }
3240   }
3241     
3242   // Import the type.
3243   QualType T = Importer.Import(D->getType());
3244   if (T.isNull())
3245     return nullptr;
3246
3247   // Create the imported variable.
3248   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3249   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3250                                    Importer.Import(D->getInnerLocStart()),
3251                                    Loc, Name.getAsIdentifierInfo(),
3252                                    T, TInfo,
3253                                    D->getStorageClass());
3254   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3255   ToVar->setAccess(D->getAccess());
3256   ToVar->setLexicalDeclContext(LexicalDC);
3257   Importer.Imported(D, ToVar);
3258   LexicalDC->addDeclInternal(ToVar);
3259
3260   if (!D->isFileVarDecl() &&
3261       D->isUsed())
3262     ToVar->setIsUsed();
3263
3264   // Merge the initializer.
3265   if (ImportDefinition(D, ToVar))
3266     return nullptr;
3267
3268   return ToVar;
3269 }
3270
3271 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3272   // Parameters are created in the translation unit's context, then moved
3273   // into the function declaration's context afterward.
3274   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3275   
3276   // Import the name of this declaration.
3277   DeclarationName Name = Importer.Import(D->getDeclName());
3278   if (D->getDeclName() && !Name)
3279     return nullptr;
3280
3281   // Import the location of this declaration.
3282   SourceLocation Loc = Importer.Import(D->getLocation());
3283   
3284   // Import the parameter's type.
3285   QualType T = Importer.Import(D->getType());
3286   if (T.isNull())
3287     return nullptr;
3288
3289   // Create the imported parameter.
3290   ImplicitParamDecl *ToParm
3291     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3292                                 Loc, Name.getAsIdentifierInfo(),
3293                                 T);
3294   return Importer.Imported(D, ToParm);
3295 }
3296
3297 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3298   // Parameters are created in the translation unit's context, then moved
3299   // into the function declaration's context afterward.
3300   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3301   
3302   // Import the name of this declaration.
3303   DeclarationName Name = Importer.Import(D->getDeclName());
3304   if (D->getDeclName() && !Name)
3305     return nullptr;
3306
3307   // Import the location of this declaration.
3308   SourceLocation Loc = Importer.Import(D->getLocation());
3309   
3310   // Import the parameter's type.
3311   QualType T = Importer.Import(D->getType());
3312   if (T.isNull())
3313     return nullptr;
3314
3315   // Create the imported parameter.
3316   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3317   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3318                                      Importer.Import(D->getInnerLocStart()),
3319                                             Loc, Name.getAsIdentifierInfo(),
3320                                             T, TInfo, D->getStorageClass(),
3321                                             /*FIXME: Default argument*/nullptr);
3322   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3323
3324   if (D->isUsed())
3325     ToParm->setIsUsed();
3326
3327   return Importer.Imported(D, ToParm);
3328 }
3329
3330 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3331   // Import the major distinguishing characteristics of a method.
3332   DeclContext *DC, *LexicalDC;
3333   DeclarationName Name;
3334   SourceLocation Loc;
3335   NamedDecl *ToD;
3336   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3337     return nullptr;
3338   if (ToD)
3339     return ToD;
3340
3341   SmallVector<NamedDecl *, 2> FoundDecls;
3342   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3343   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3344     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3345       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3346         continue;
3347
3348       // Check return types.
3349       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3350                                              FoundMethod->getReturnType())) {
3351         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3352             << D->isInstanceMethod() << Name << D->getReturnType()
3353             << FoundMethod->getReturnType();
3354         Importer.ToDiag(FoundMethod->getLocation(), 
3355                         diag::note_odr_objc_method_here)
3356           << D->isInstanceMethod() << Name;
3357         return nullptr;
3358       }
3359
3360       // Check the number of parameters.
3361       if (D->param_size() != FoundMethod->param_size()) {
3362         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3363           << D->isInstanceMethod() << Name
3364           << D->param_size() << FoundMethod->param_size();
3365         Importer.ToDiag(FoundMethod->getLocation(), 
3366                         diag::note_odr_objc_method_here)
3367           << D->isInstanceMethod() << Name;
3368         return nullptr;
3369       }
3370
3371       // Check parameter types.
3372       for (ObjCMethodDecl::param_iterator P = D->param_begin(), 
3373              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3374            P != PEnd; ++P, ++FoundP) {
3375         if (!Importer.IsStructurallyEquivalent((*P)->getType(), 
3376                                                (*FoundP)->getType())) {
3377           Importer.FromDiag((*P)->getLocation(), 
3378                             diag::err_odr_objc_method_param_type_inconsistent)
3379             << D->isInstanceMethod() << Name
3380             << (*P)->getType() << (*FoundP)->getType();
3381           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3382             << (*FoundP)->getType();
3383           return nullptr;
3384         }
3385       }
3386
3387       // Check variadic/non-variadic.
3388       // Check the number of parameters.
3389       if (D->isVariadic() != FoundMethod->isVariadic()) {
3390         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3391           << D->isInstanceMethod() << Name;
3392         Importer.ToDiag(FoundMethod->getLocation(), 
3393                         diag::note_odr_objc_method_here)
3394           << D->isInstanceMethod() << Name;
3395         return nullptr;
3396       }
3397
3398       // FIXME: Any other bits we need to merge?
3399       return Importer.Imported(D, FoundMethod);
3400     }
3401   }
3402
3403   // Import the result type.
3404   QualType ResultTy = Importer.Import(D->getReturnType());
3405   if (ResultTy.isNull())
3406     return nullptr;
3407
3408   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3409
3410   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3411       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3412       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3413       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3414       D->getImplementationControl(), D->hasRelatedResultType());
3415
3416   // FIXME: When we decide to merge method definitions, we'll need to
3417   // deal with implicit parameters.
3418
3419   // Import the parameters
3420   SmallVector<ParmVarDecl *, 5> ToParams;
3421   for (auto *FromP : D->params()) {
3422     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3423     if (!ToP)
3424       return nullptr;
3425
3426     ToParams.push_back(ToP);
3427   }
3428   
3429   // Set the parameters.
3430   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3431     ToParams[I]->setOwningFunction(ToMethod);
3432     ToMethod->addDeclInternal(ToParams[I]);
3433   }
3434   SmallVector<SourceLocation, 12> SelLocs;
3435   D->getSelectorLocs(SelLocs);
3436   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs); 
3437
3438   ToMethod->setLexicalDeclContext(LexicalDC);
3439   Importer.Imported(D, ToMethod);
3440   LexicalDC->addDeclInternal(ToMethod);
3441   return ToMethod;
3442 }
3443
3444 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3445   // Import the major distinguishing characteristics of a category.
3446   DeclContext *DC, *LexicalDC;
3447   DeclarationName Name;
3448   SourceLocation Loc;
3449   NamedDecl *ToD;
3450   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3451     return nullptr;
3452   if (ToD)
3453     return ToD;
3454
3455   TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3456   if (!BoundInfo)
3457     return nullptr;
3458
3459   ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3460                                 Importer.getToContext(), DC,
3461                                 D->getVariance(),
3462                                 Importer.Import(D->getVarianceLoc()),
3463                                 D->getIndex(),
3464                                 Importer.Import(D->getLocation()),
3465                                 Name.getAsIdentifierInfo(),
3466                                 Importer.Import(D->getColonLoc()),
3467                                 BoundInfo);
3468   Importer.Imported(D, Result);
3469   Result->setLexicalDeclContext(LexicalDC);
3470   return Result;
3471 }
3472
3473 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3474   // Import the major distinguishing characteristics of a category.
3475   DeclContext *DC, *LexicalDC;
3476   DeclarationName Name;
3477   SourceLocation Loc;
3478   NamedDecl *ToD;
3479   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3480     return nullptr;
3481   if (ToD)
3482     return ToD;
3483
3484   ObjCInterfaceDecl *ToInterface
3485     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3486   if (!ToInterface)
3487     return nullptr;
3488
3489   // Determine if we've already encountered this category.
3490   ObjCCategoryDecl *MergeWithCategory
3491     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3492   ObjCCategoryDecl *ToCategory = MergeWithCategory;
3493   if (!ToCategory) {
3494     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3495                                           Importer.Import(D->getAtStartLoc()),
3496                                           Loc, 
3497                                        Importer.Import(D->getCategoryNameLoc()), 
3498                                           Name.getAsIdentifierInfo(),
3499                                           ToInterface,
3500                                           /*TypeParamList=*/nullptr,
3501                                        Importer.Import(D->getIvarLBraceLoc()),
3502                                        Importer.Import(D->getIvarRBraceLoc()));
3503     ToCategory->setLexicalDeclContext(LexicalDC);
3504     LexicalDC->addDeclInternal(ToCategory);
3505     Importer.Imported(D, ToCategory);
3506     // Import the type parameter list after calling Imported, to avoid
3507     // loops when bringing in their DeclContext.
3508     ToCategory->setTypeParamList(ImportObjCTypeParamList(
3509                                    D->getTypeParamList()));
3510     
3511     // Import protocols
3512     SmallVector<ObjCProtocolDecl *, 4> Protocols;
3513     SmallVector<SourceLocation, 4> ProtocolLocs;
3514     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3515       = D->protocol_loc_begin();
3516     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3517                                           FromProtoEnd = D->protocol_end();
3518          FromProto != FromProtoEnd;
3519          ++FromProto, ++FromProtoLoc) {
3520       ObjCProtocolDecl *ToProto
3521         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3522       if (!ToProto)
3523         return nullptr;
3524       Protocols.push_back(ToProto);
3525       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3526     }
3527     
3528     // FIXME: If we're merging, make sure that the protocol list is the same.
3529     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3530                                 ProtocolLocs.data(), Importer.getToContext());
3531     
3532   } else {
3533     Importer.Imported(D, ToCategory);
3534   }
3535   
3536   // Import all of the members of this category.
3537   ImportDeclContext(D);
3538  
3539   // If we have an implementation, import it as well.
3540   if (D->getImplementation()) {
3541     ObjCCategoryImplDecl *Impl
3542       = cast_or_null<ObjCCategoryImplDecl>(
3543                                        Importer.Import(D->getImplementation()));
3544     if (!Impl)
3545       return nullptr;
3546
3547     ToCategory->setImplementation(Impl);
3548   }
3549   
3550   return ToCategory;
3551 }
3552
3553 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, 
3554                                        ObjCProtocolDecl *To,
3555                                        ImportDefinitionKind Kind) {
3556   if (To->getDefinition()) {
3557     if (shouldForceImportDeclContext(Kind))
3558       ImportDeclContext(From);
3559     return false;
3560   }
3561
3562   // Start the protocol definition
3563   To->startDefinition();
3564   
3565   // Import protocols
3566   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3567   SmallVector<SourceLocation, 4> ProtocolLocs;
3568   ObjCProtocolDecl::protocol_loc_iterator 
3569   FromProtoLoc = From->protocol_loc_begin();
3570   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3571                                         FromProtoEnd = From->protocol_end();
3572        FromProto != FromProtoEnd;
3573        ++FromProto, ++FromProtoLoc) {
3574     ObjCProtocolDecl *ToProto
3575       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3576     if (!ToProto)
3577       return true;
3578     Protocols.push_back(ToProto);
3579     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3580   }
3581   
3582   // FIXME: If we're merging, make sure that the protocol list is the same.
3583   To->setProtocolList(Protocols.data(), Protocols.size(),
3584                       ProtocolLocs.data(), Importer.getToContext());
3585
3586   if (shouldForceImportDeclContext(Kind)) {
3587     // Import all of the members of this protocol.
3588     ImportDeclContext(From, /*ForceImport=*/true);
3589   }
3590   return false;
3591 }
3592
3593 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3594   // If this protocol has a definition in the translation unit we're coming 
3595   // from, but this particular declaration is not that definition, import the
3596   // definition and map to that.
3597   ObjCProtocolDecl *Definition = D->getDefinition();
3598   if (Definition && Definition != D) {
3599     Decl *ImportedDef = Importer.Import(Definition);
3600     if (!ImportedDef)
3601       return nullptr;
3602
3603     return Importer.Imported(D, ImportedDef);
3604   }
3605
3606   // Import the major distinguishing characteristics of a protocol.
3607   DeclContext *DC, *LexicalDC;
3608   DeclarationName Name;
3609   SourceLocation Loc;
3610   NamedDecl *ToD;
3611   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3612     return nullptr;
3613   if (ToD)
3614     return ToD;
3615
3616   ObjCProtocolDecl *MergeWithProtocol = nullptr;
3617   SmallVector<NamedDecl *, 2> FoundDecls;
3618   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3619   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3620     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3621       continue;
3622     
3623     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3624       break;
3625   }
3626   
3627   ObjCProtocolDecl *ToProto = MergeWithProtocol;
3628   if (!ToProto) {
3629     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3630                                        Name.getAsIdentifierInfo(), Loc,
3631                                        Importer.Import(D->getAtStartLoc()),
3632                                        /*PrevDecl=*/nullptr);
3633     ToProto->setLexicalDeclContext(LexicalDC);
3634     LexicalDC->addDeclInternal(ToProto);
3635   }
3636     
3637   Importer.Imported(D, ToProto);
3638
3639   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3640     return nullptr;
3641
3642   return ToProto;
3643 }
3644
3645 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3646   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3647   DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3648
3649   SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3650   SourceLocation LangLoc = Importer.Import(D->getLocation());
3651
3652   bool HasBraces = D->hasBraces();
3653  
3654   LinkageSpecDecl *ToLinkageSpec =
3655     LinkageSpecDecl::Create(Importer.getToContext(),
3656                             DC,
3657                             ExternLoc,
3658                             LangLoc,
3659                             D->getLanguage(),
3660                             HasBraces);
3661
3662   if (HasBraces) {
3663     SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3664     ToLinkageSpec->setRBraceLoc(RBraceLoc);
3665   }
3666
3667   ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3668   LexicalDC->addDeclInternal(ToLinkageSpec);
3669
3670   Importer.Imported(D, ToLinkageSpec);
3671
3672   return ToLinkageSpec;
3673 }
3674
3675 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, 
3676                                        ObjCInterfaceDecl *To,
3677                                        ImportDefinitionKind Kind) {
3678   if (To->getDefinition()) {
3679     // Check consistency of superclass.
3680     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3681     if (FromSuper) {
3682       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3683       if (!FromSuper)
3684         return true;
3685     }
3686     
3687     ObjCInterfaceDecl *ToSuper = To->getSuperClass();    
3688     if ((bool)FromSuper != (bool)ToSuper ||
3689         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3690       Importer.ToDiag(To->getLocation(), 
3691                       diag::err_odr_objc_superclass_inconsistent)
3692         << To->getDeclName();
3693       if (ToSuper)
3694         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3695           << To->getSuperClass()->getDeclName();
3696       else
3697         Importer.ToDiag(To->getLocation(), 
3698                         diag::note_odr_objc_missing_superclass);
3699       if (From->getSuperClass())
3700         Importer.FromDiag(From->getSuperClassLoc(), 
3701                           diag::note_odr_objc_superclass)
3702         << From->getSuperClass()->getDeclName();
3703       else
3704         Importer.FromDiag(From->getLocation(), 
3705                           diag::note_odr_objc_missing_superclass);        
3706     }
3707     
3708     if (shouldForceImportDeclContext(Kind))
3709       ImportDeclContext(From);
3710     return false;
3711   }
3712   
3713   // Start the definition.
3714   To->startDefinition();
3715   
3716   // If this class has a superclass, import it.
3717   if (From->getSuperClass()) {
3718     TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3719     if (!SuperTInfo)
3720       return true;
3721
3722     To->setSuperClass(SuperTInfo);
3723   }
3724   
3725   // Import protocols
3726   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3727   SmallVector<SourceLocation, 4> ProtocolLocs;
3728   ObjCInterfaceDecl::protocol_loc_iterator 
3729   FromProtoLoc = From->protocol_loc_begin();
3730   
3731   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3732                                          FromProtoEnd = From->protocol_end();
3733        FromProto != FromProtoEnd;
3734        ++FromProto, ++FromProtoLoc) {
3735     ObjCProtocolDecl *ToProto
3736       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3737     if (!ToProto)
3738       return true;
3739     Protocols.push_back(ToProto);
3740     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3741   }
3742   
3743   // FIXME: If we're merging, make sure that the protocol list is the same.
3744   To->setProtocolList(Protocols.data(), Protocols.size(),
3745                       ProtocolLocs.data(), Importer.getToContext());
3746   
3747   // Import categories. When the categories themselves are imported, they'll
3748   // hook themselves into this interface.
3749   for (auto *Cat : From->known_categories())
3750     Importer.Import(Cat);
3751   
3752   // If we have an @implementation, import it as well.
3753   if (From->getImplementation()) {
3754     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3755                                      Importer.Import(From->getImplementation()));
3756     if (!Impl)
3757       return true;
3758     
3759     To->setImplementation(Impl);
3760   }
3761
3762   if (shouldForceImportDeclContext(Kind)) {
3763     // Import all of the members of this class.
3764     ImportDeclContext(From, /*ForceImport=*/true);
3765   }
3766   return false;
3767 }
3768
3769 ObjCTypeParamList *
3770 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3771   if (!list)
3772     return nullptr;
3773
3774   SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3775   for (auto fromTypeParam : *list) {
3776     auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3777                          Importer.Import(fromTypeParam));
3778     if (!toTypeParam)
3779       return nullptr;
3780
3781     toTypeParams.push_back(toTypeParam);
3782   }
3783
3784   return ObjCTypeParamList::create(Importer.getToContext(),
3785                                    Importer.Import(list->getLAngleLoc()),
3786                                    toTypeParams,
3787                                    Importer.Import(list->getRAngleLoc()));
3788 }
3789
3790 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3791   // If this class has a definition in the translation unit we're coming from,
3792   // but this particular declaration is not that definition, import the
3793   // definition and map to that.
3794   ObjCInterfaceDecl *Definition = D->getDefinition();
3795   if (Definition && Definition != D) {
3796     Decl *ImportedDef = Importer.Import(Definition);
3797     if (!ImportedDef)
3798       return nullptr;
3799
3800     return Importer.Imported(D, ImportedDef);
3801   }
3802
3803   // Import the major distinguishing characteristics of an @interface.
3804   DeclContext *DC, *LexicalDC;
3805   DeclarationName Name;
3806   SourceLocation Loc;
3807   NamedDecl *ToD;
3808   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3809     return nullptr;
3810   if (ToD)
3811     return ToD;
3812
3813   // Look for an existing interface with the same name.
3814   ObjCInterfaceDecl *MergeWithIface = nullptr;
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     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3822       break;
3823   }
3824   
3825   // Create an interface declaration, if one does not already exist.
3826   ObjCInterfaceDecl *ToIface = MergeWithIface;
3827   if (!ToIface) {
3828     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3829                                         Importer.Import(D->getAtStartLoc()),
3830                                         Name.getAsIdentifierInfo(),
3831                                         /*TypeParamList=*/nullptr,
3832                                         /*PrevDecl=*/nullptr, Loc,
3833                                         D->isImplicitInterfaceDecl());
3834     ToIface->setLexicalDeclContext(LexicalDC);
3835     LexicalDC->addDeclInternal(ToIface);
3836   }
3837   Importer.Imported(D, ToIface);
3838   // Import the type parameter list after calling Imported, to avoid
3839   // loops when bringing in their DeclContext.
3840   ToIface->setTypeParamList(ImportObjCTypeParamList(
3841                               D->getTypeParamListAsWritten()));
3842   
3843   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3844     return nullptr;
3845
3846   return ToIface;
3847 }
3848
3849 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3850   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3851                                         Importer.Import(D->getCategoryDecl()));
3852   if (!Category)
3853     return nullptr;
3854
3855   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3856   if (!ToImpl) {
3857     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3858     if (!DC)
3859       return nullptr;
3860
3861     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3862     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3863                                           Importer.Import(D->getIdentifier()),
3864                                           Category->getClassInterface(),
3865                                           Importer.Import(D->getLocation()),
3866                                           Importer.Import(D->getAtStartLoc()),
3867                                           CategoryNameLoc);
3868     
3869     DeclContext *LexicalDC = DC;
3870     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3871       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3872       if (!LexicalDC)
3873         return nullptr;
3874
3875       ToImpl->setLexicalDeclContext(LexicalDC);
3876     }
3877     
3878     LexicalDC->addDeclInternal(ToImpl);
3879     Category->setImplementation(ToImpl);
3880   }
3881   
3882   Importer.Imported(D, ToImpl);
3883   ImportDeclContext(D);
3884   return ToImpl;
3885 }
3886
3887 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3888   // Find the corresponding interface.
3889   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3890                                        Importer.Import(D->getClassInterface()));
3891   if (!Iface)
3892     return nullptr;
3893
3894   // Import the superclass, if any.
3895   ObjCInterfaceDecl *Super = nullptr;
3896   if (D->getSuperClass()) {
3897     Super = cast_or_null<ObjCInterfaceDecl>(
3898                                           Importer.Import(D->getSuperClass()));
3899     if (!Super)
3900       return nullptr;
3901   }
3902
3903   ObjCImplementationDecl *Impl = Iface->getImplementation();
3904   if (!Impl) {
3905     // We haven't imported an implementation yet. Create a new @implementation
3906     // now.
3907     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3908                                   Importer.ImportContext(D->getDeclContext()),
3909                                           Iface, Super,
3910                                           Importer.Import(D->getLocation()),
3911                                           Importer.Import(D->getAtStartLoc()),
3912                                           Importer.Import(D->getSuperClassLoc()),
3913                                           Importer.Import(D->getIvarLBraceLoc()),
3914                                           Importer.Import(D->getIvarRBraceLoc()));
3915     
3916     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3917       DeclContext *LexicalDC
3918         = Importer.ImportContext(D->getLexicalDeclContext());
3919       if (!LexicalDC)
3920         return nullptr;
3921       Impl->setLexicalDeclContext(LexicalDC);
3922     }
3923     
3924     // Associate the implementation with the class it implements.
3925     Iface->setImplementation(Impl);
3926     Importer.Imported(D, Iface->getImplementation());
3927   } else {
3928     Importer.Imported(D, Iface->getImplementation());
3929
3930     // Verify that the existing @implementation has the same superclass.
3931     if ((Super && !Impl->getSuperClass()) ||
3932         (!Super && Impl->getSuperClass()) ||
3933         (Super && Impl->getSuperClass() &&
3934          !declaresSameEntity(Super->getCanonicalDecl(),
3935                              Impl->getSuperClass()))) {
3936       Importer.ToDiag(Impl->getLocation(),
3937                       diag::err_odr_objc_superclass_inconsistent)
3938         << Iface->getDeclName();
3939       // FIXME: It would be nice to have the location of the superclass
3940       // below.
3941       if (Impl->getSuperClass())
3942         Importer.ToDiag(Impl->getLocation(),
3943                         diag::note_odr_objc_superclass)
3944         << Impl->getSuperClass()->getDeclName();
3945       else
3946         Importer.ToDiag(Impl->getLocation(),
3947                         diag::note_odr_objc_missing_superclass);
3948       if (D->getSuperClass())
3949         Importer.FromDiag(D->getLocation(),
3950                           diag::note_odr_objc_superclass)
3951         << D->getSuperClass()->getDeclName();
3952       else
3953         Importer.FromDiag(D->getLocation(),
3954                           diag::note_odr_objc_missing_superclass);
3955       return nullptr;
3956     }
3957   }
3958     
3959   // Import all of the members of this @implementation.
3960   ImportDeclContext(D);
3961
3962   return Impl;
3963 }
3964
3965 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3966   // Import the major distinguishing characteristics of an @property.
3967   DeclContext *DC, *LexicalDC;
3968   DeclarationName Name;
3969   SourceLocation Loc;
3970   NamedDecl *ToD;
3971   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3972     return nullptr;
3973   if (ToD)
3974     return ToD;
3975
3976   // Check whether we have already imported this property.
3977   SmallVector<NamedDecl *, 2> FoundDecls;
3978   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3979   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3980     if (ObjCPropertyDecl *FoundProp
3981                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3982       // Check property types.
3983       if (!Importer.IsStructurallyEquivalent(D->getType(), 
3984                                              FoundProp->getType())) {
3985         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3986           << Name << D->getType() << FoundProp->getType();
3987         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3988           << FoundProp->getType();
3989         return nullptr;
3990       }
3991
3992       // FIXME: Check property attributes, getters, setters, etc.?
3993
3994       // Consider these properties to be equivalent.
3995       Importer.Imported(D, FoundProp);
3996       return FoundProp;
3997     }
3998   }
3999
4000   // Import the type.
4001   TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4002   if (!TSI)
4003     return nullptr;
4004
4005   // Create the new property.
4006   ObjCPropertyDecl *ToProperty
4007     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4008                                Name.getAsIdentifierInfo(), 
4009                                Importer.Import(D->getAtLoc()),
4010                                Importer.Import(D->getLParenLoc()),
4011                                Importer.Import(D->getType()),
4012                                TSI,
4013                                D->getPropertyImplementation());
4014   Importer.Imported(D, ToProperty);
4015   ToProperty->setLexicalDeclContext(LexicalDC);
4016   LexicalDC->addDeclInternal(ToProperty);
4017
4018   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4019   ToProperty->setPropertyAttributesAsWritten(
4020                                       D->getPropertyAttributesAsWritten());
4021   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4022   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4023   ToProperty->setGetterMethodDecl(
4024      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4025   ToProperty->setSetterMethodDecl(
4026      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4027   ToProperty->setPropertyIvarDecl(
4028        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4029   return ToProperty;
4030 }
4031
4032 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4033   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4034                                         Importer.Import(D->getPropertyDecl()));
4035   if (!Property)
4036     return nullptr;
4037
4038   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4039   if (!DC)
4040     return nullptr;
4041
4042   // Import the lexical declaration context.
4043   DeclContext *LexicalDC = DC;
4044   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4045     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4046     if (!LexicalDC)
4047       return nullptr;
4048   }
4049
4050   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4051   if (!InImpl)
4052     return nullptr;
4053
4054   // Import the ivar (for an @synthesize).
4055   ObjCIvarDecl *Ivar = nullptr;
4056   if (D->getPropertyIvarDecl()) {
4057     Ivar = cast_or_null<ObjCIvarDecl>(
4058                                     Importer.Import(D->getPropertyIvarDecl()));
4059     if (!Ivar)
4060       return nullptr;
4061   }
4062
4063   ObjCPropertyImplDecl *ToImpl
4064     = InImpl->FindPropertyImplDecl(Property->getIdentifier());
4065   if (!ToImpl) {    
4066     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4067                                           Importer.Import(D->getLocStart()),
4068                                           Importer.Import(D->getLocation()),
4069                                           Property,
4070                                           D->getPropertyImplementation(),
4071                                           Ivar, 
4072                                   Importer.Import(D->getPropertyIvarDeclLoc()));
4073     ToImpl->setLexicalDeclContext(LexicalDC);
4074     Importer.Imported(D, ToImpl);
4075     LexicalDC->addDeclInternal(ToImpl);
4076   } else {
4077     // Check that we have the same kind of property implementation (@synthesize
4078     // vs. @dynamic).
4079     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4080       Importer.ToDiag(ToImpl->getLocation(), 
4081                       diag::err_odr_objc_property_impl_kind_inconsistent)
4082         << Property->getDeclName() 
4083         << (ToImpl->getPropertyImplementation() 
4084                                               == ObjCPropertyImplDecl::Dynamic);
4085       Importer.FromDiag(D->getLocation(),
4086                         diag::note_odr_objc_property_impl_kind)
4087         << D->getPropertyDecl()->getDeclName()
4088         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4089       return nullptr;
4090     }
4091     
4092     // For @synthesize, check that we have the same 
4093     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4094         Ivar != ToImpl->getPropertyIvarDecl()) {
4095       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 
4096                       diag::err_odr_objc_synthesize_ivar_inconsistent)
4097         << Property->getDeclName()
4098         << ToImpl->getPropertyIvarDecl()->getDeclName()
4099         << Ivar->getDeclName();
4100       Importer.FromDiag(D->getPropertyIvarDeclLoc(), 
4101                         diag::note_odr_objc_synthesize_ivar_here)
4102         << D->getPropertyIvarDecl()->getDeclName();
4103       return nullptr;
4104     }
4105     
4106     // Merge the existing implementation with the new implementation.
4107     Importer.Imported(D, ToImpl);
4108   }
4109   
4110   return ToImpl;
4111 }
4112
4113 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4114   // For template arguments, we adopt the translation unit as our declaration
4115   // context. This context will be fixed when the actual template declaration
4116   // is created.
4117   
4118   // FIXME: Import default argument.
4119   return TemplateTypeParmDecl::Create(Importer.getToContext(),
4120                               Importer.getToContext().getTranslationUnitDecl(),
4121                                       Importer.Import(D->getLocStart()),
4122                                       Importer.Import(D->getLocation()),
4123                                       D->getDepth(),
4124                                       D->getIndex(), 
4125                                       Importer.Import(D->getIdentifier()),
4126                                       D->wasDeclaredWithTypename(),
4127                                       D->isParameterPack());
4128 }
4129
4130 Decl *
4131 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4132   // Import the name of this declaration.
4133   DeclarationName Name = Importer.Import(D->getDeclName());
4134   if (D->getDeclName() && !Name)
4135     return nullptr;
4136
4137   // Import the location of this declaration.
4138   SourceLocation Loc = Importer.Import(D->getLocation());
4139
4140   // Import the type of this declaration.
4141   QualType T = Importer.Import(D->getType());
4142   if (T.isNull())
4143     return nullptr;
4144
4145   // Import type-source information.
4146   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4147   if (D->getTypeSourceInfo() && !TInfo)
4148     return nullptr;
4149
4150   // FIXME: Import default argument.
4151   
4152   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4153                                Importer.getToContext().getTranslationUnitDecl(),
4154                                          Importer.Import(D->getInnerLocStart()),
4155                                          Loc, D->getDepth(), D->getPosition(),
4156                                          Name.getAsIdentifierInfo(),
4157                                          T, D->isParameterPack(), TInfo);
4158 }
4159
4160 Decl *
4161 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4162   // Import the name of this declaration.
4163   DeclarationName Name = Importer.Import(D->getDeclName());
4164   if (D->getDeclName() && !Name)
4165     return nullptr;
4166
4167   // Import the location of this declaration.
4168   SourceLocation Loc = Importer.Import(D->getLocation());
4169   
4170   // Import template parameters.
4171   TemplateParameterList *TemplateParams
4172     = ImportTemplateParameterList(D->getTemplateParameters());
4173   if (!TemplateParams)
4174     return nullptr;
4175
4176   // FIXME: Import default argument.
4177   
4178   return TemplateTemplateParmDecl::Create(Importer.getToContext(), 
4179                               Importer.getToContext().getTranslationUnitDecl(), 
4180                                           Loc, D->getDepth(), D->getPosition(),
4181                                           D->isParameterPack(),
4182                                           Name.getAsIdentifierInfo(), 
4183                                           TemplateParams);
4184 }
4185
4186 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4187   // If this record has a definition in the translation unit we're coming from,
4188   // but this particular declaration is not that definition, import the
4189   // definition and map to that.
4190   CXXRecordDecl *Definition 
4191     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4192   if (Definition && Definition != D->getTemplatedDecl()) {
4193     Decl *ImportedDef
4194       = Importer.Import(Definition->getDescribedClassTemplate());
4195     if (!ImportedDef)
4196       return nullptr;
4197
4198     return Importer.Imported(D, ImportedDef);
4199   }
4200   
4201   // Import the major distinguishing characteristics of this class template.
4202   DeclContext *DC, *LexicalDC;
4203   DeclarationName Name;
4204   SourceLocation Loc;
4205   NamedDecl *ToD;
4206   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4207     return nullptr;
4208   if (ToD)
4209     return ToD;
4210
4211   // We may already have a template of the same name; try to find and match it.
4212   if (!DC->isFunctionOrMethod()) {
4213     SmallVector<NamedDecl *, 4> ConflictingDecls;
4214     SmallVector<NamedDecl *, 2> FoundDecls;
4215     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4216     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4217       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4218         continue;
4219       
4220       Decl *Found = FoundDecls[I];
4221       if (ClassTemplateDecl *FoundTemplate 
4222                                         = dyn_cast<ClassTemplateDecl>(Found)) {
4223         if (IsStructuralMatch(D, FoundTemplate)) {
4224           // The class templates structurally match; call it the same template.
4225           // FIXME: We may be filling in a forward declaration here. Handle
4226           // this case!
4227           Importer.Imported(D->getTemplatedDecl(), 
4228                             FoundTemplate->getTemplatedDecl());
4229           return Importer.Imported(D, FoundTemplate);
4230         }         
4231       }
4232       
4233       ConflictingDecls.push_back(FoundDecls[I]);
4234     }
4235     
4236     if (!ConflictingDecls.empty()) {
4237       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4238                                          ConflictingDecls.data(), 
4239                                          ConflictingDecls.size());
4240     }
4241     
4242     if (!Name)
4243       return nullptr;
4244   }
4245
4246   CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4247   
4248   // Create the declaration that is being templated.
4249   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4250   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4251   CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4252                                                      DTemplated->getTagKind(),
4253                                                      DC, StartLoc, IdLoc,
4254                                                    Name.getAsIdentifierInfo());
4255   D2Templated->setAccess(DTemplated->getAccess());
4256   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4257   D2Templated->setLexicalDeclContext(LexicalDC);
4258   
4259   // Create the class template declaration itself.
4260   TemplateParameterList *TemplateParams
4261     = ImportTemplateParameterList(D->getTemplateParameters());
4262   if (!TemplateParams)
4263     return nullptr;
4264
4265   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC, 
4266                                                     Loc, Name, TemplateParams, 
4267                                                     D2Templated, 
4268                                                     /*PrevDecl=*/nullptr);
4269   D2Templated->setDescribedClassTemplate(D2);    
4270   
4271   D2->setAccess(D->getAccess());
4272   D2->setLexicalDeclContext(LexicalDC);
4273   LexicalDC->addDeclInternal(D2);
4274   
4275   // Note the relationship between the class templates.
4276   Importer.Imported(D, D2);
4277   Importer.Imported(DTemplated, D2Templated);
4278
4279   if (DTemplated->isCompleteDefinition() &&
4280       !D2Templated->isCompleteDefinition()) {
4281     // FIXME: Import definition!
4282   }
4283   
4284   return D2;
4285 }
4286
4287 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4288                                           ClassTemplateSpecializationDecl *D) {
4289   // If this record has a definition in the translation unit we're coming from,
4290   // but this particular declaration is not that definition, import the
4291   // definition and map to that.
4292   TagDecl *Definition = D->getDefinition();
4293   if (Definition && Definition != D) {
4294     Decl *ImportedDef = Importer.Import(Definition);
4295     if (!ImportedDef)
4296       return nullptr;
4297
4298     return Importer.Imported(D, ImportedDef);
4299   }
4300
4301   ClassTemplateDecl *ClassTemplate
4302     = cast_or_null<ClassTemplateDecl>(Importer.Import(
4303                                                  D->getSpecializedTemplate()));
4304   if (!ClassTemplate)
4305     return nullptr;
4306
4307   // Import the context of this declaration.
4308   DeclContext *DC = ClassTemplate->getDeclContext();
4309   if (!DC)
4310     return nullptr;
4311
4312   DeclContext *LexicalDC = DC;
4313   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4314     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4315     if (!LexicalDC)
4316       return nullptr;
4317   }
4318   
4319   // Import the location of this declaration.
4320   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4321   SourceLocation IdLoc = Importer.Import(D->getLocation());
4322
4323   // Import template arguments.
4324   SmallVector<TemplateArgument, 2> TemplateArgs;
4325   if (ImportTemplateArguments(D->getTemplateArgs().data(), 
4326                               D->getTemplateArgs().size(),
4327                               TemplateArgs))
4328     return nullptr;
4329
4330   // Try to find an existing specialization with these template arguments.
4331   void *InsertPos = nullptr;
4332   ClassTemplateSpecializationDecl *D2
4333     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4334   if (D2) {
4335     // We already have a class template specialization with these template
4336     // arguments.
4337     
4338     // FIXME: Check for specialization vs. instantiation errors.
4339     
4340     if (RecordDecl *FoundDef = D2->getDefinition()) {
4341       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4342         // The record types structurally match, or the "from" translation
4343         // unit only had a forward declaration anyway; call it the same
4344         // function.
4345         return Importer.Imported(D, FoundDef);
4346       }
4347     }
4348   } else {
4349     // Create a new specialization.
4350     D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(), 
4351                                                  D->getTagKind(), DC, 
4352                                                  StartLoc, IdLoc,
4353                                                  ClassTemplate,
4354                                                  TemplateArgs.data(), 
4355                                                  TemplateArgs.size(), 
4356                                                  /*PrevDecl=*/nullptr);
4357     D2->setSpecializationKind(D->getSpecializationKind());
4358
4359     // Add this specialization to the class template.
4360     ClassTemplate->AddSpecialization(D2, InsertPos);
4361     
4362     // Import the qualifier, if any.
4363     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4364     
4365     // Add the specialization to this context.
4366     D2->setLexicalDeclContext(LexicalDC);
4367     LexicalDC->addDeclInternal(D2);
4368   }
4369   Importer.Imported(D, D2);
4370   
4371   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4372     return nullptr;
4373
4374   return D2;
4375 }
4376
4377 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4378   // If this variable has a definition in the translation unit we're coming
4379   // from,
4380   // but this particular declaration is not that definition, import the
4381   // definition and map to that.
4382   VarDecl *Definition =
4383       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4384   if (Definition && Definition != D->getTemplatedDecl()) {
4385     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4386     if (!ImportedDef)
4387       return nullptr;
4388
4389     return Importer.Imported(D, ImportedDef);
4390   }
4391
4392   // Import the major distinguishing characteristics of this variable template.
4393   DeclContext *DC, *LexicalDC;
4394   DeclarationName Name;
4395   SourceLocation Loc;
4396   NamedDecl *ToD;
4397   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4398     return nullptr;
4399   if (ToD)
4400     return ToD;
4401
4402   // We may already have a template of the same name; try to find and match it.
4403   assert(!DC->isFunctionOrMethod() &&
4404          "Variable templates cannot be declared at function scope");
4405   SmallVector<NamedDecl *, 4> ConflictingDecls;
4406   SmallVector<NamedDecl *, 2> FoundDecls;
4407   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4408   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4409     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4410       continue;
4411
4412     Decl *Found = FoundDecls[I];
4413     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4414       if (IsStructuralMatch(D, FoundTemplate)) {
4415         // The variable templates structurally match; call it the same template.
4416         Importer.Imported(D->getTemplatedDecl(),
4417                           FoundTemplate->getTemplatedDecl());
4418         return Importer.Imported(D, FoundTemplate);
4419       }
4420     }
4421
4422     ConflictingDecls.push_back(FoundDecls[I]);
4423   }
4424
4425   if (!ConflictingDecls.empty()) {
4426     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4427                                        ConflictingDecls.data(),
4428                                        ConflictingDecls.size());
4429   }
4430
4431   if (!Name)
4432     return nullptr;
4433
4434   VarDecl *DTemplated = D->getTemplatedDecl();
4435
4436   // Import the type.
4437   QualType T = Importer.Import(DTemplated->getType());
4438   if (T.isNull())
4439     return nullptr;
4440
4441   // Create the declaration that is being templated.
4442   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4443   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4444   TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4445   VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4446                                          IdLoc, Name.getAsIdentifierInfo(), T,
4447                                          TInfo, DTemplated->getStorageClass());
4448   D2Templated->setAccess(DTemplated->getAccess());
4449   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4450   D2Templated->setLexicalDeclContext(LexicalDC);
4451
4452   // Importer.Imported(DTemplated, D2Templated);
4453   // LexicalDC->addDeclInternal(D2Templated);
4454
4455   // Merge the initializer.
4456   if (ImportDefinition(DTemplated, D2Templated))
4457     return nullptr;
4458
4459   // Create the variable template declaration itself.
4460   TemplateParameterList *TemplateParams =
4461       ImportTemplateParameterList(D->getTemplateParameters());
4462   if (!TemplateParams)
4463     return nullptr;
4464
4465   VarTemplateDecl *D2 = VarTemplateDecl::Create(
4466       Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4467   D2Templated->setDescribedVarTemplate(D2);
4468
4469   D2->setAccess(D->getAccess());
4470   D2->setLexicalDeclContext(LexicalDC);
4471   LexicalDC->addDeclInternal(D2);
4472
4473   // Note the relationship between the variable templates.
4474   Importer.Imported(D, D2);
4475   Importer.Imported(DTemplated, D2Templated);
4476
4477   if (DTemplated->isThisDeclarationADefinition() &&
4478       !D2Templated->isThisDeclarationADefinition()) {
4479     // FIXME: Import definition!
4480   }
4481
4482   return D2;
4483 }
4484
4485 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4486     VarTemplateSpecializationDecl *D) {
4487   // If this record has a definition in the translation unit we're coming from,
4488   // but this particular declaration is not that definition, import the
4489   // definition and map to that.
4490   VarDecl *Definition = D->getDefinition();
4491   if (Definition && Definition != D) {
4492     Decl *ImportedDef = Importer.Import(Definition);
4493     if (!ImportedDef)
4494       return nullptr;
4495
4496     return Importer.Imported(D, ImportedDef);
4497   }
4498
4499   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4500       Importer.Import(D->getSpecializedTemplate()));
4501   if (!VarTemplate)
4502     return nullptr;
4503
4504   // Import the context of this declaration.
4505   DeclContext *DC = VarTemplate->getDeclContext();
4506   if (!DC)
4507     return nullptr;
4508
4509   DeclContext *LexicalDC = DC;
4510   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4511     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4512     if (!LexicalDC)
4513       return nullptr;
4514   }
4515
4516   // Import the location of this declaration.
4517   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4518   SourceLocation IdLoc = Importer.Import(D->getLocation());
4519
4520   // Import template arguments.
4521   SmallVector<TemplateArgument, 2> TemplateArgs;
4522   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4523                               D->getTemplateArgs().size(), TemplateArgs))
4524     return nullptr;
4525
4526   // Try to find an existing specialization with these template arguments.
4527   void *InsertPos = nullptr;
4528   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4529       TemplateArgs, InsertPos);
4530   if (D2) {
4531     // We already have a variable template specialization with these template
4532     // arguments.
4533
4534     // FIXME: Check for specialization vs. instantiation errors.
4535
4536     if (VarDecl *FoundDef = D2->getDefinition()) {
4537       if (!D->isThisDeclarationADefinition() ||
4538           IsStructuralMatch(D, FoundDef)) {
4539         // The record types structurally match, or the "from" translation
4540         // unit only had a forward declaration anyway; call it the same
4541         // variable.
4542         return Importer.Imported(D, FoundDef);
4543       }
4544     }
4545   } else {
4546
4547     // Import the type.
4548     QualType T = Importer.Import(D->getType());
4549     if (T.isNull())
4550       return nullptr;
4551     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4552
4553     // Create a new specialization.
4554     D2 = VarTemplateSpecializationDecl::Create(
4555         Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4556         D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4557     D2->setSpecializationKind(D->getSpecializationKind());
4558     D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4559
4560     // Add this specialization to the class template.
4561     VarTemplate->AddSpecialization(D2, InsertPos);
4562
4563     // Import the qualifier, if any.
4564     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4565
4566     // Add the specialization to this context.
4567     D2->setLexicalDeclContext(LexicalDC);
4568     LexicalDC->addDeclInternal(D2);
4569   }
4570   Importer.Imported(D, D2);
4571
4572   if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4573     return nullptr;
4574
4575   return D2;
4576 }
4577
4578 //----------------------------------------------------------------------------
4579 // Import Statements
4580 //----------------------------------------------------------------------------
4581
4582 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4583   if (DG.isNull())
4584     return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4585   size_t NumDecls = DG.end() - DG.begin();
4586   SmallVector<Decl *, 1> ToDecls(NumDecls);
4587   auto &_Importer = this->Importer;
4588   std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4589     [&_Importer](Decl *D) -> Decl * {
4590       return _Importer.Import(D);
4591     });
4592   return DeclGroupRef::Create(Importer.getToContext(),
4593                               ToDecls.begin(),
4594                               NumDecls);
4595 }
4596
4597  Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4598    Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4599      << S->getStmtClassName();
4600    return nullptr;
4601  }
4602  
4603 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4604   DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4605   for (Decl *ToD : ToDG) {
4606     if (!ToD)
4607       return nullptr;
4608   }
4609   SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4610   SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4611   return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4612 }
4613
4614 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4615   SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4616   return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4617                                                 S->hasLeadingEmptyMacro());
4618 }
4619
4620 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4621   SmallVector<Stmt *, 4> ToStmts(S->size());
4622   auto &_Importer = this->Importer;
4623   std::transform(S->body_begin(), S->body_end(), ToStmts.begin(),
4624     [&_Importer](Stmt *CS) -> Stmt * {
4625       return _Importer.Import(CS);
4626     });
4627   for (Stmt *ToS : ToStmts) {
4628     if (!ToS)
4629       return nullptr;
4630   }
4631   SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4632   SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4633   return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4634                                                     ToStmts,
4635                                                     ToLBraceLoc, ToRBraceLoc);
4636 }
4637
4638 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4639   Expr *ToLHS = Importer.Import(S->getLHS());
4640   if (!ToLHS)
4641     return nullptr;
4642   Expr *ToRHS = Importer.Import(S->getRHS());
4643   if (!ToRHS && S->getRHS())
4644     return nullptr;
4645   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4646   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4647   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4648   return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4649                                                 ToCaseLoc, ToEllipsisLoc,
4650                                                 ToColonLoc);
4651 }
4652
4653 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4654   SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4655   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4656   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4657   if (!ToSubStmt && S->getSubStmt())
4658     return nullptr;
4659   return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4660                                                    ToSubStmt);
4661 }
4662
4663 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4664   SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4665   LabelDecl *ToLabelDecl =
4666     cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4667   if (!ToLabelDecl && S->getDecl())
4668     return nullptr;
4669   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4670   if (!ToSubStmt && S->getSubStmt())
4671     return nullptr;
4672   return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4673                                                  ToSubStmt);
4674 }
4675
4676 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4677   SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4678   ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4679   SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4680   ASTContext &_ToContext = Importer.getToContext();
4681   std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4682     [&_ToContext](const Attr *A) -> const Attr * {
4683       return A->clone(_ToContext);
4684     });
4685   for (const Attr *ToA : ToAttrs) {
4686     if (!ToA)
4687       return nullptr;
4688   }
4689   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4690   if (!ToSubStmt && S->getSubStmt())
4691     return nullptr;
4692   return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4693                                 ToAttrs, ToSubStmt);
4694 }
4695
4696 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4697   SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4698   VarDecl *ToConditionVariable = nullptr;
4699   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4700     ToConditionVariable =
4701       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4702     if (!ToConditionVariable)
4703       return nullptr;
4704   }
4705   Expr *ToCondition = Importer.Import(S->getCond());
4706   if (!ToCondition && S->getCond())
4707     return nullptr;
4708   Stmt *ToThenStmt = Importer.Import(S->getThen());
4709   if (!ToThenStmt && S->getThen())
4710     return nullptr;
4711   SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4712   Stmt *ToElseStmt = Importer.Import(S->getElse());
4713   if (!ToElseStmt && S->getElse())
4714     return nullptr;
4715   return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4716                                               ToIfLoc, ToConditionVariable,
4717                                               ToCondition, ToThenStmt,
4718                                               ToElseLoc, ToElseStmt);
4719 }
4720
4721 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4722   VarDecl *ToConditionVariable = nullptr;
4723   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4724     ToConditionVariable =
4725       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4726     if (!ToConditionVariable)
4727       return nullptr;
4728   }
4729   Expr *ToCondition = Importer.Import(S->getCond());
4730   if (!ToCondition && S->getCond())
4731     return nullptr;
4732   SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4733                          Importer.getToContext(), ToConditionVariable,
4734                          ToCondition);
4735   Stmt *ToBody = Importer.Import(S->getBody());
4736   if (!ToBody && S->getBody())
4737     return nullptr;
4738   ToStmt->setBody(ToBody);
4739   ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4740   // Now we have to re-chain the cases.
4741   SwitchCase *LastChainedSwitchCase = nullptr;
4742   for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4743        SC = SC->getNextSwitchCase()) {
4744     SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4745     if (!ToSC)
4746       return nullptr;
4747     if (LastChainedSwitchCase)
4748       LastChainedSwitchCase->setNextSwitchCase(ToSC);
4749     else
4750       ToStmt->setSwitchCaseList(ToSC);
4751     LastChainedSwitchCase = ToSC;
4752   }
4753   return ToStmt;
4754 }
4755
4756 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4757   VarDecl *ToConditionVariable = nullptr;
4758   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4759     ToConditionVariable =
4760       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4761     if (!ToConditionVariable)
4762       return nullptr;
4763   }
4764   Expr *ToCondition = Importer.Import(S->getCond());
4765   if (!ToCondition && S->getCond())
4766     return nullptr;
4767   Stmt *ToBody = Importer.Import(S->getBody());
4768   if (!ToBody && S->getBody())
4769     return nullptr;
4770   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4771   return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4772                                                  ToConditionVariable,
4773                                                  ToCondition, ToBody,
4774                                                  ToWhileLoc);
4775 }
4776
4777 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4778   Stmt *ToBody = Importer.Import(S->getBody());
4779   if (!ToBody && S->getBody())
4780     return nullptr;
4781   Expr *ToCondition = Importer.Import(S->getCond());
4782   if (!ToCondition && S->getCond())
4783     return nullptr;
4784   SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4785   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4786   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4787   return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4788                                               ToDoLoc, ToWhileLoc,
4789                                               ToRParenLoc);
4790 }
4791
4792 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4793   Stmt *ToInit = Importer.Import(S->getInit());
4794   if (!ToInit && S->getInit())
4795     return nullptr;
4796   Expr *ToCondition = Importer.Import(S->getCond());
4797   if (!ToCondition && S->getCond())
4798     return nullptr;
4799   VarDecl *ToConditionVariable = nullptr;
4800   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4801     ToConditionVariable =
4802       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4803     if (!ToConditionVariable)
4804       return nullptr;
4805   }
4806   Expr *ToInc = Importer.Import(S->getInc());
4807   if (!ToInc && S->getInc())
4808     return nullptr;
4809   Stmt *ToBody = Importer.Import(S->getBody());
4810   if (!ToBody && S->getBody())
4811     return nullptr;
4812   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4813   SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4814   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4815   return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4816                                                ToInit, ToCondition,
4817                                                ToConditionVariable,
4818                                                ToInc, ToBody,
4819                                                ToForLoc, ToLParenLoc,
4820                                                ToRParenLoc);
4821 }
4822
4823 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4824   LabelDecl *ToLabel = nullptr;
4825   if (LabelDecl *FromLabel = S->getLabel()) {
4826     ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4827     if (!ToLabel)
4828       return nullptr;
4829   }
4830   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4831   SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4832   return new (Importer.getToContext()) GotoStmt(ToLabel,
4833                                                 ToGotoLoc, ToLabelLoc);
4834 }
4835
4836 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4837   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4838   SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4839   Expr *ToTarget = Importer.Import(S->getTarget());
4840   if (!ToTarget && S->getTarget())
4841     return nullptr;
4842   return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4843                                                         ToTarget);
4844 }
4845
4846 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4847   SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4848   return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4849 }
4850
4851 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4852   SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4853   return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4854 }
4855
4856 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4857   SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4858   Expr *ToRetExpr = Importer.Import(S->getRetValue());
4859   if (!ToRetExpr && S->getRetValue())
4860     return nullptr;
4861   VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4862   VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4863   if (!ToNRVOCandidate && NRVOCandidate)
4864     return nullptr;
4865   return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4866                                                   ToNRVOCandidate);
4867 }
4868
4869 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4870   SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4871   VarDecl *ToExceptionDecl = nullptr;
4872   if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4873     ToExceptionDecl =
4874       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4875     if (!ToExceptionDecl)
4876       return nullptr;
4877   }
4878   Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4879   if (!ToHandlerBlock && S->getHandlerBlock())
4880     return nullptr;
4881   return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4882                                                     ToExceptionDecl,
4883                                                     ToHandlerBlock);
4884 }
4885
4886 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4887   SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4888   Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4889   if (!ToTryBlock && S->getTryBlock())
4890     return nullptr;
4891   SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4892   for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4893     CXXCatchStmt *FromHandler = S->getHandler(HI);
4894     if (Stmt *ToHandler = Importer.Import(FromHandler))
4895       ToHandlers[HI] = ToHandler;
4896     else
4897       return nullptr;
4898   }
4899   return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4900                             ToHandlers);
4901 }
4902
4903 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4904   DeclStmt *ToRange =
4905     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4906   if (!ToRange && S->getRangeStmt())
4907     return nullptr;
4908   DeclStmt *ToBeginEnd =
4909     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginEndStmt()));
4910   if (!ToBeginEnd && S->getBeginEndStmt())
4911     return nullptr;
4912   Expr *ToCond = Importer.Import(S->getCond());
4913   if (!ToCond && S->getCond())
4914     return nullptr;
4915   Expr *ToInc = Importer.Import(S->getInc());
4916   if (!ToInc && S->getInc())
4917     return nullptr;
4918   DeclStmt *ToLoopVar =
4919     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4920   if (!ToLoopVar && S->getLoopVarStmt())
4921     return nullptr;
4922   Stmt *ToBody = Importer.Import(S->getBody());
4923   if (!ToBody && S->getBody())
4924     return nullptr;
4925   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4926   SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
4927   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4928   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4929   return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBeginEnd,
4930                                                        ToCond, ToInc,
4931                                                        ToLoopVar, ToBody,
4932                                                        ToForLoc, ToCoawaitLoc,
4933                                                        ToColonLoc, ToRParenLoc);
4934 }
4935
4936 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4937   Stmt *ToElem = Importer.Import(S->getElement());
4938   if (!ToElem && S->getElement())
4939     return nullptr;
4940   Expr *ToCollect = Importer.Import(S->getCollection());
4941   if (!ToCollect && S->getCollection())
4942     return nullptr;
4943   Stmt *ToBody = Importer.Import(S->getBody());
4944   if (!ToBody && S->getBody())
4945     return nullptr;
4946   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4947   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4948   return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4949                                                              ToCollect,
4950                                                              ToBody, ToForLoc,
4951                                                              ToRParenLoc);
4952 }
4953
4954 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4955   SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4956   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4957   VarDecl *ToExceptionDecl = nullptr;
4958   if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4959     ToExceptionDecl =
4960       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4961     if (!ToExceptionDecl)
4962       return nullptr;
4963   }
4964   Stmt *ToBody = Importer.Import(S->getCatchBody());
4965   if (!ToBody && S->getCatchBody())
4966     return nullptr;
4967   return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
4968                                                        ToRParenLoc,
4969                                                        ToExceptionDecl,
4970                                                        ToBody);
4971 }
4972
4973 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4974   SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
4975   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
4976   if (!ToAtFinallyStmt && S->getFinallyBody())
4977     return nullptr;
4978   return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
4979                                                          ToAtFinallyStmt);
4980 }
4981
4982 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
4983   SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
4984   Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
4985   if (!ToAtTryStmt && S->getTryBody())
4986     return nullptr;
4987   SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
4988   for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
4989     ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
4990     if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
4991       ToCatchStmts[CI] = ToCatchStmt;
4992     else
4993       return nullptr;
4994   }
4995   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
4996   if (!ToAtFinallyStmt && S->getFinallyStmt())
4997     return nullptr;
4998   return ObjCAtTryStmt::Create(Importer.getToContext(),
4999                                ToAtTryLoc, ToAtTryStmt,
5000                                ToCatchStmts.begin(), ToCatchStmts.size(),
5001                                ToAtFinallyStmt);
5002 }
5003
5004 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5005   (ObjCAtSynchronizedStmt *S) {
5006   SourceLocation ToAtSynchronizedLoc =
5007     Importer.Import(S->getAtSynchronizedLoc());
5008   Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5009   if (!ToSynchExpr && S->getSynchExpr())
5010     return nullptr;
5011   Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5012   if (!ToSynchBody && S->getSynchBody())
5013     return nullptr;
5014   return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5015     ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5016 }
5017
5018 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5019   SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5020   Expr *ToThrow = Importer.Import(S->getThrowExpr());
5021   if (!ToThrow && S->getThrowExpr())
5022     return nullptr;
5023   return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5024 }
5025
5026 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5027   (ObjCAutoreleasePoolStmt *S) {
5028   SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5029   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5030   if (!ToSubStmt && S->getSubStmt())
5031     return nullptr;
5032   return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5033                                                                ToSubStmt);
5034 }
5035
5036 //----------------------------------------------------------------------------
5037 // Import Expressions
5038 //----------------------------------------------------------------------------
5039 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5040   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5041     << E->getStmtClassName();
5042   return nullptr;
5043 }
5044
5045 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5046   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5047   if (!ToD)
5048     return nullptr;
5049
5050   NamedDecl *FoundD = nullptr;
5051   if (E->getDecl() != E->getFoundDecl()) {
5052     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5053     if (!FoundD)
5054       return nullptr;
5055   }
5056   
5057   QualType T = Importer.Import(E->getType());
5058   if (T.isNull())
5059     return nullptr;
5060
5061   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), 
5062                                          Importer.Import(E->getQualifierLoc()),
5063                                    Importer.Import(E->getTemplateKeywordLoc()),
5064                                          ToD,
5065                                         E->refersToEnclosingVariableOrCapture(),
5066                                          Importer.Import(E->getLocation()),
5067                                          T, E->getValueKind(),
5068                                          FoundD,
5069                                          /*FIXME:TemplateArgs=*/nullptr);
5070   if (E->hadMultipleCandidates())
5071     DRE->setHadMultipleCandidates(true);
5072   return DRE;
5073 }
5074
5075 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5076   QualType T = Importer.Import(E->getType());
5077   if (T.isNull())
5078     return nullptr;
5079
5080   return IntegerLiteral::Create(Importer.getToContext(), 
5081                                 E->getValue(), T,
5082                                 Importer.Import(E->getLocation()));
5083 }
5084
5085 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5086   QualType T = Importer.Import(E->getType());
5087   if (T.isNull())
5088     return nullptr;
5089
5090   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5091                                                         E->getKind(), T,
5092                                           Importer.Import(E->getLocation()));
5093 }
5094
5095 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5096   Expr *SubExpr = Importer.Import(E->getSubExpr());
5097   if (!SubExpr)
5098     return nullptr;
5099
5100   return new (Importer.getToContext()) 
5101                                   ParenExpr(Importer.Import(E->getLParen()),
5102                                             Importer.Import(E->getRParen()),
5103                                             SubExpr);
5104 }
5105
5106 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5107   QualType T = Importer.Import(E->getType());
5108   if (T.isNull())
5109     return nullptr;
5110
5111   Expr *SubExpr = Importer.Import(E->getSubExpr());
5112   if (!SubExpr)
5113     return nullptr;
5114
5115   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5116                                                      T, E->getValueKind(),
5117                                                      E->getObjectKind(),
5118                                          Importer.Import(E->getOperatorLoc()));                                        
5119 }
5120
5121 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5122                                             UnaryExprOrTypeTraitExpr *E) {
5123   QualType ResultType = Importer.Import(E->getType());
5124   
5125   if (E->isArgumentType()) {
5126     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5127     if (!TInfo)
5128       return nullptr;
5129
5130     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5131                                            TInfo, ResultType,
5132                                            Importer.Import(E->getOperatorLoc()),
5133                                            Importer.Import(E->getRParenLoc()));
5134   }
5135   
5136   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5137   if (!SubExpr)
5138     return nullptr;
5139
5140   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5141                                           SubExpr, ResultType,
5142                                           Importer.Import(E->getOperatorLoc()),
5143                                           Importer.Import(E->getRParenLoc()));
5144 }
5145
5146 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5147   QualType T = Importer.Import(E->getType());
5148   if (T.isNull())
5149     return nullptr;
5150
5151   Expr *LHS = Importer.Import(E->getLHS());
5152   if (!LHS)
5153     return nullptr;
5154
5155   Expr *RHS = Importer.Import(E->getRHS());
5156   if (!RHS)
5157     return nullptr;
5158
5159   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5160                                                       T, E->getValueKind(),
5161                                                       E->getObjectKind(),
5162                                            Importer.Import(E->getOperatorLoc()),
5163                                                       E->isFPContractable());
5164 }
5165
5166 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5167   QualType T = Importer.Import(E->getType());
5168   if (T.isNull())
5169     return nullptr;
5170
5171   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5172   if (CompLHSType.isNull())
5173     return nullptr;
5174
5175   QualType CompResultType = Importer.Import(E->getComputationResultType());
5176   if (CompResultType.isNull())
5177     return nullptr;
5178
5179   Expr *LHS = Importer.Import(E->getLHS());
5180   if (!LHS)
5181     return nullptr;
5182
5183   Expr *RHS = Importer.Import(E->getRHS());
5184   if (!RHS)
5185     return nullptr;
5186
5187   return new (Importer.getToContext()) 
5188                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5189                                                T, E->getValueKind(),
5190                                                E->getObjectKind(),
5191                                                CompLHSType, CompResultType,
5192                                            Importer.Import(E->getOperatorLoc()),
5193                                                E->isFPContractable());
5194 }
5195
5196 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5197   if (E->path_empty()) return false;
5198
5199   // TODO: import cast paths
5200   return true;
5201 }
5202
5203 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5204   QualType T = Importer.Import(E->getType());
5205   if (T.isNull())
5206     return nullptr;
5207
5208   Expr *SubExpr = Importer.Import(E->getSubExpr());
5209   if (!SubExpr)
5210     return nullptr;
5211
5212   CXXCastPath BasePath;
5213   if (ImportCastPath(E, BasePath))
5214     return nullptr;
5215
5216   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5217                                   SubExpr, &BasePath, E->getValueKind());
5218 }
5219
5220 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5221   QualType T = Importer.Import(E->getType());
5222   if (T.isNull())
5223     return nullptr;
5224
5225   Expr *SubExpr = Importer.Import(E->getSubExpr());
5226   if (!SubExpr)
5227     return nullptr;
5228
5229   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5230   if (!TInfo && E->getTypeInfoAsWritten())
5231     return nullptr;
5232
5233   CXXCastPath BasePath;
5234   if (ImportCastPath(E, BasePath))
5235     return nullptr;
5236
5237   return CStyleCastExpr::Create(Importer.getToContext(), T,
5238                                 E->getValueKind(), E->getCastKind(),
5239                                 SubExpr, &BasePath, TInfo,
5240                                 Importer.Import(E->getLParenLoc()),
5241                                 Importer.Import(E->getRParenLoc()));
5242 }
5243
5244 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5245   QualType T = Importer.Import(E->getType());
5246   if (T.isNull())
5247     return nullptr;
5248
5249   CXXConstructorDecl *ToCCD =
5250     dyn_cast<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5251   if (!ToCCD && E->getConstructor())
5252     return nullptr;
5253
5254   size_t NumArgs = E->getNumArgs();
5255   SmallVector<Expr *, 1> ToArgs(NumArgs);
5256   ASTImporter &_Importer = Importer;
5257   std::transform(E->arg_begin(), E->arg_end(), ToArgs.begin(),
5258     [&_Importer](Expr *AE) -> Expr * {
5259       return _Importer.Import(AE);
5260     });
5261   for (Expr *ToA : ToArgs) {
5262     if (!ToA)
5263       return nullptr;
5264   }
5265
5266   return CXXConstructExpr::Create(Importer.getToContext(), T,
5267                                   Importer.Import(E->getLocation()),
5268                                   ToCCD, E->isElidable(),
5269                                   ToArgs, E->hadMultipleCandidates(),
5270                                   E->isListInitialization(),
5271                                   E->isStdInitListInitialization(),
5272                                   E->requiresZeroInitialization(),
5273                                   E->getConstructionKind(),
5274                                   Importer.Import(E->getParenOrBraceRange()));
5275 }
5276
5277 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5278   QualType T = Importer.Import(E->getType());
5279   if (T.isNull())
5280     return nullptr;
5281
5282   Expr *ToBase = Importer.Import(E->getBase());
5283   if (!ToBase && E->getBase())
5284     return nullptr;
5285
5286   ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5287   if (!ToMember && E->getMemberDecl())
5288     return nullptr;
5289
5290   DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5291     dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5292     E->getFoundDecl().getAccess());
5293
5294   DeclarationNameInfo ToMemberNameInfo(
5295     Importer.Import(E->getMemberNameInfo().getName()),
5296     Importer.Import(E->getMemberNameInfo().getLoc()));
5297
5298   if (E->hasExplicitTemplateArgs()) {
5299     return nullptr; // FIXME: handle template arguments
5300   }
5301
5302   return MemberExpr::Create(Importer.getToContext(), ToBase,
5303                             E->isArrow(),
5304                             Importer.Import(E->getOperatorLoc()),
5305                             Importer.Import(E->getQualifierLoc()),
5306                             Importer.Import(E->getTemplateKeywordLoc()),
5307                             ToMember, ToFoundDecl, ToMemberNameInfo,
5308                             nullptr, T, E->getValueKind(),
5309                             E->getObjectKind());
5310 }
5311
5312 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5313   QualType T = Importer.Import(E->getType());
5314   if (T.isNull())
5315     return nullptr;
5316
5317   Expr *ToCallee = Importer.Import(E->getCallee());
5318   if (!ToCallee && E->getCallee())
5319     return nullptr;
5320
5321   unsigned NumArgs = E->getNumArgs();
5322
5323   llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5324
5325   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5326     Expr *FromArg = E->getArg(ai);
5327     Expr *ToArg = Importer.Import(FromArg);
5328     if (!ToArg)
5329       return nullptr;
5330     ToArgs[ai] = ToArg;
5331   }
5332
5333   Expr **ToArgs_Copied = new (Importer.getToContext()) 
5334     Expr*[NumArgs];
5335
5336   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5337     ToArgs_Copied[ai] = ToArgs[ai];
5338
5339   return new (Importer.getToContext())
5340     CallExpr(Importer.getToContext(), ToCallee, 
5341              llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5342              Importer.Import(E->getRParenLoc()));
5343 }
5344
5345 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
5346                          ASTContext &FromContext, FileManager &FromFileManager,
5347                          bool MinimalImport)
5348   : ToContext(ToContext), FromContext(FromContext),
5349     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
5350     Minimal(MinimalImport), LastDiagFromFrom(false)
5351 {
5352   ImportedDecls[FromContext.getTranslationUnitDecl()]
5353     = ToContext.getTranslationUnitDecl();
5354 }
5355
5356 ASTImporter::~ASTImporter() { }
5357
5358 QualType ASTImporter::Import(QualType FromT) {
5359   if (FromT.isNull())
5360     return QualType();
5361
5362   const Type *fromTy = FromT.getTypePtr();
5363   
5364   // Check whether we've already imported this type.  
5365   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5366     = ImportedTypes.find(fromTy);
5367   if (Pos != ImportedTypes.end())
5368     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
5369   
5370   // Import the type
5371   ASTNodeImporter Importer(*this);
5372   QualType ToT = Importer.Visit(fromTy);
5373   if (ToT.isNull())
5374     return ToT;
5375   
5376   // Record the imported type.
5377   ImportedTypes[fromTy] = ToT.getTypePtr();
5378   
5379   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
5380 }
5381
5382 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
5383   if (!FromTSI)
5384     return FromTSI;
5385
5386   // FIXME: For now we just create a "trivial" type source info based
5387   // on the type and a single location. Implement a real version of this.
5388   QualType T = Import(FromTSI->getType());
5389   if (T.isNull())
5390     return nullptr;
5391
5392   return ToContext.getTrivialTypeSourceInfo(T, 
5393            Import(FromTSI->getTypeLoc().getLocStart()));
5394 }
5395
5396 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
5397   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5398   if (Pos != ImportedDecls.end()) {
5399     Decl *ToD = Pos->second;
5400     ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
5401     return ToD;
5402   } else {
5403     return nullptr;
5404   }
5405 }
5406
5407 Decl *ASTImporter::Import(Decl *FromD) {
5408   if (!FromD)
5409     return nullptr;
5410
5411   ASTNodeImporter Importer(*this);
5412
5413   // Check whether we've already imported this declaration.  
5414   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5415   if (Pos != ImportedDecls.end()) {
5416     Decl *ToD = Pos->second;
5417     Importer.ImportDefinitionIfNeeded(FromD, ToD);
5418     return ToD;
5419   }
5420   
5421   // Import the type
5422   Decl *ToD = Importer.Visit(FromD);
5423   if (!ToD)
5424     return nullptr;
5425
5426   // Record the imported declaration.
5427   ImportedDecls[FromD] = ToD;
5428   
5429   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
5430     // Keep track of anonymous tags that have an associated typedef.
5431     if (FromTag->getTypedefNameForAnonDecl())
5432       AnonTagsWithPendingTypedefs.push_back(FromTag);
5433   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
5434     // When we've finished transforming a typedef, see whether it was the
5435     // typedef for an anonymous tag.
5436     for (SmallVectorImpl<TagDecl *>::iterator
5437                FromTag = AnonTagsWithPendingTypedefs.begin(), 
5438             FromTagEnd = AnonTagsWithPendingTypedefs.end();
5439          FromTag != FromTagEnd; ++FromTag) {
5440       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
5441         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
5442           // We found the typedef for an anonymous tag; link them.
5443           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
5444           AnonTagsWithPendingTypedefs.erase(FromTag);
5445           break;
5446         }
5447       }
5448     }
5449   }
5450   
5451   return ToD;
5452 }
5453
5454 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
5455   if (!FromDC)
5456     return FromDC;
5457
5458   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
5459   if (!ToDC)
5460     return nullptr;
5461
5462   // When we're using a record/enum/Objective-C class/protocol as a context, we 
5463   // need it to have a definition.
5464   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
5465     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
5466     if (ToRecord->isCompleteDefinition()) {
5467       // Do nothing.
5468     } else if (FromRecord->isCompleteDefinition()) {
5469       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
5470                                               ASTNodeImporter::IDK_Basic);
5471     } else {
5472       CompleteDecl(ToRecord);
5473     }
5474   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
5475     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
5476     if (ToEnum->isCompleteDefinition()) {
5477       // Do nothing.
5478     } else if (FromEnum->isCompleteDefinition()) {
5479       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
5480                                               ASTNodeImporter::IDK_Basic);
5481     } else {
5482       CompleteDecl(ToEnum);
5483     }    
5484   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
5485     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
5486     if (ToClass->getDefinition()) {
5487       // Do nothing.
5488     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
5489       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
5490                                               ASTNodeImporter::IDK_Basic);
5491     } else {
5492       CompleteDecl(ToClass);
5493     }
5494   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
5495     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
5496     if (ToProto->getDefinition()) {
5497       // Do nothing.
5498     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
5499       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
5500                                               ASTNodeImporter::IDK_Basic);
5501     } else {
5502       CompleteDecl(ToProto);
5503     }    
5504   }
5505   
5506   return ToDC;
5507 }
5508
5509 Expr *ASTImporter::Import(Expr *FromE) {
5510   if (!FromE)
5511     return nullptr;
5512
5513   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
5514 }
5515
5516 Stmt *ASTImporter::Import(Stmt *FromS) {
5517   if (!FromS)
5518     return nullptr;
5519
5520   // Check whether we've already imported this declaration.  
5521   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
5522   if (Pos != ImportedStmts.end())
5523     return Pos->second;
5524   
5525   // Import the type
5526   ASTNodeImporter Importer(*this);
5527   Stmt *ToS = Importer.Visit(FromS);
5528   if (!ToS)
5529     return nullptr;
5530
5531   // Record the imported declaration.
5532   ImportedStmts[FromS] = ToS;
5533   return ToS;
5534 }
5535
5536 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
5537   if (!FromNNS)
5538     return nullptr;
5539
5540   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
5541
5542   switch (FromNNS->getKind()) {
5543   case NestedNameSpecifier::Identifier:
5544     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
5545       return NestedNameSpecifier::Create(ToContext, prefix, II);
5546     }
5547     return nullptr;
5548
5549   case NestedNameSpecifier::Namespace:
5550     if (NamespaceDecl *NS = 
5551           cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
5552       return NestedNameSpecifier::Create(ToContext, prefix, NS);
5553     }
5554     return nullptr;
5555
5556   case NestedNameSpecifier::NamespaceAlias:
5557     if (NamespaceAliasDecl *NSAD = 
5558           cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
5559       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
5560     }
5561     return nullptr;
5562
5563   case NestedNameSpecifier::Global:
5564     return NestedNameSpecifier::GlobalSpecifier(ToContext);
5565
5566   case NestedNameSpecifier::Super:
5567     if (CXXRecordDecl *RD =
5568             cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
5569       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
5570     }
5571     return nullptr;
5572
5573   case NestedNameSpecifier::TypeSpec:
5574   case NestedNameSpecifier::TypeSpecWithTemplate: {
5575       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
5576       if (!T.isNull()) {
5577         bool bTemplate = FromNNS->getKind() == 
5578                          NestedNameSpecifier::TypeSpecWithTemplate;
5579         return NestedNameSpecifier::Create(ToContext, prefix, 
5580                                            bTemplate, T.getTypePtr());
5581       }
5582     }
5583       return nullptr;
5584   }
5585
5586   llvm_unreachable("Invalid nested name specifier kind");
5587 }
5588
5589 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
5590   // FIXME: Implement!
5591   return NestedNameSpecifierLoc();
5592 }
5593
5594 TemplateName ASTImporter::Import(TemplateName From) {
5595   switch (From.getKind()) {
5596   case TemplateName::Template:
5597     if (TemplateDecl *ToTemplate
5598                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5599       return TemplateName(ToTemplate);
5600       
5601     return TemplateName();
5602       
5603   case TemplateName::OverloadedTemplate: {
5604     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
5605     UnresolvedSet<2> ToTemplates;
5606     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
5607                                              E = FromStorage->end();
5608          I != E; ++I) {
5609       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I))) 
5610         ToTemplates.addDecl(To);
5611       else
5612         return TemplateName();
5613     }
5614     return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 
5615                                                ToTemplates.end());
5616   }
5617       
5618   case TemplateName::QualifiedTemplate: {
5619     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
5620     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
5621     if (!Qualifier)
5622       return TemplateName();
5623     
5624     if (TemplateDecl *ToTemplate
5625         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5626       return ToContext.getQualifiedTemplateName(Qualifier, 
5627                                                 QTN->hasTemplateKeyword(), 
5628                                                 ToTemplate);
5629     
5630     return TemplateName();
5631   }
5632   
5633   case TemplateName::DependentTemplate: {
5634     DependentTemplateName *DTN = From.getAsDependentTemplateName();
5635     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
5636     if (!Qualifier)
5637       return TemplateName();
5638     
5639     if (DTN->isIdentifier()) {
5640       return ToContext.getDependentTemplateName(Qualifier, 
5641                                                 Import(DTN->getIdentifier()));
5642     }
5643     
5644     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
5645   }
5646
5647   case TemplateName::SubstTemplateTemplateParm: {
5648     SubstTemplateTemplateParmStorage *subst
5649       = From.getAsSubstTemplateTemplateParm();
5650     TemplateTemplateParmDecl *param
5651       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
5652     if (!param)
5653       return TemplateName();
5654
5655     TemplateName replacement = Import(subst->getReplacement());
5656     if (replacement.isNull()) return TemplateName();
5657     
5658     return ToContext.getSubstTemplateTemplateParm(param, replacement);
5659   }
5660       
5661   case TemplateName::SubstTemplateTemplateParmPack: {
5662     SubstTemplateTemplateParmPackStorage *SubstPack
5663       = From.getAsSubstTemplateTemplateParmPack();
5664     TemplateTemplateParmDecl *Param
5665       = cast_or_null<TemplateTemplateParmDecl>(
5666                                         Import(SubstPack->getParameterPack()));
5667     if (!Param)
5668       return TemplateName();
5669     
5670     ASTNodeImporter Importer(*this);
5671     TemplateArgument ArgPack 
5672       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
5673     if (ArgPack.isNull())
5674       return TemplateName();
5675     
5676     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
5677   }
5678   }
5679   
5680   llvm_unreachable("Invalid template name kind");
5681 }
5682
5683 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
5684   if (FromLoc.isInvalid())
5685     return SourceLocation();
5686
5687   SourceManager &FromSM = FromContext.getSourceManager();
5688   
5689   // For now, map everything down to its spelling location, so that we
5690   // don't have to import macro expansions.
5691   // FIXME: Import macro expansions!
5692   FromLoc = FromSM.getSpellingLoc(FromLoc);
5693   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
5694   SourceManager &ToSM = ToContext.getSourceManager();
5695   FileID ToFileID = Import(Decomposed.first);
5696   if (ToFileID.isInvalid())
5697     return SourceLocation();
5698   SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
5699                            .getLocWithOffset(Decomposed.second);
5700   return ret;
5701 }
5702
5703 SourceRange ASTImporter::Import(SourceRange FromRange) {
5704   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
5705 }
5706
5707 FileID ASTImporter::Import(FileID FromID) {
5708   llvm::DenseMap<FileID, FileID>::iterator Pos
5709     = ImportedFileIDs.find(FromID);
5710   if (Pos != ImportedFileIDs.end())
5711     return Pos->second;
5712   
5713   SourceManager &FromSM = FromContext.getSourceManager();
5714   SourceManager &ToSM = ToContext.getSourceManager();
5715   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
5716   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
5717   
5718   // Include location of this file.
5719   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
5720   
5721   // Map the FileID for to the "to" source manager.
5722   FileID ToID;
5723   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
5724   if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
5725     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
5726     // disk again
5727     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
5728     // than mmap the files several times.
5729     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
5730     if (!Entry)
5731       return FileID();
5732     ToID = ToSM.createFileID(Entry, ToIncludeLoc, 
5733                              FromSLoc.getFile().getFileCharacteristic());
5734   } else {
5735     // FIXME: We want to re-use the existing MemoryBuffer!
5736     const llvm::MemoryBuffer *
5737         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
5738     std::unique_ptr<llvm::MemoryBuffer> ToBuf
5739       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
5740                                              FromBuf->getBufferIdentifier());
5741     ToID = ToSM.createFileID(std::move(ToBuf),
5742                              FromSLoc.getFile().getFileCharacteristic());
5743   }
5744   
5745   
5746   ImportedFileIDs[FromID] = ToID;
5747   return ToID;
5748 }
5749
5750 void ASTImporter::ImportDefinition(Decl *From) {
5751   Decl *To = Import(From);
5752   if (!To)
5753     return;
5754   
5755   if (DeclContext *FromDC = cast<DeclContext>(From)) {
5756     ASTNodeImporter Importer(*this);
5757       
5758     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
5759       if (!ToRecord->getDefinition()) {
5760         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, 
5761                                   ASTNodeImporter::IDK_Everything);
5762         return;
5763       }      
5764     }
5765
5766     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
5767       if (!ToEnum->getDefinition()) {
5768         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, 
5769                                   ASTNodeImporter::IDK_Everything);
5770         return;
5771       }      
5772     }
5773     
5774     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
5775       if (!ToIFace->getDefinition()) {
5776         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
5777                                   ASTNodeImporter::IDK_Everything);
5778         return;
5779       }
5780     }
5781
5782     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
5783       if (!ToProto->getDefinition()) {
5784         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
5785                                   ASTNodeImporter::IDK_Everything);
5786         return;
5787       }
5788     }
5789     
5790     Importer.ImportDeclContext(FromDC, true);
5791   }
5792 }
5793
5794 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5795   if (!FromName)
5796     return DeclarationName();
5797
5798   switch (FromName.getNameKind()) {
5799   case DeclarationName::Identifier:
5800     return Import(FromName.getAsIdentifierInfo());
5801
5802   case DeclarationName::ObjCZeroArgSelector:
5803   case DeclarationName::ObjCOneArgSelector:
5804   case DeclarationName::ObjCMultiArgSelector:
5805     return Import(FromName.getObjCSelector());
5806
5807   case DeclarationName::CXXConstructorName: {
5808     QualType T = Import(FromName.getCXXNameType());
5809     if (T.isNull())
5810       return DeclarationName();
5811
5812     return ToContext.DeclarationNames.getCXXConstructorName(
5813                                                ToContext.getCanonicalType(T));
5814   }
5815
5816   case DeclarationName::CXXDestructorName: {
5817     QualType T = Import(FromName.getCXXNameType());
5818     if (T.isNull())
5819       return DeclarationName();
5820
5821     return ToContext.DeclarationNames.getCXXDestructorName(
5822                                                ToContext.getCanonicalType(T));
5823   }
5824
5825   case DeclarationName::CXXConversionFunctionName: {
5826     QualType T = Import(FromName.getCXXNameType());
5827     if (T.isNull())
5828       return DeclarationName();
5829
5830     return ToContext.DeclarationNames.getCXXConversionFunctionName(
5831                                                ToContext.getCanonicalType(T));
5832   }
5833
5834   case DeclarationName::CXXOperatorName:
5835     return ToContext.DeclarationNames.getCXXOperatorName(
5836                                           FromName.getCXXOverloadedOperator());
5837
5838   case DeclarationName::CXXLiteralOperatorName:
5839     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5840                                    Import(FromName.getCXXLiteralIdentifier()));
5841
5842   case DeclarationName::CXXUsingDirective:
5843     // FIXME: STATICS!
5844     return DeclarationName::getUsingDirectiveName();
5845   }
5846
5847   llvm_unreachable("Invalid DeclarationName Kind!");
5848 }
5849
5850 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5851   if (!FromId)
5852     return nullptr;
5853
5854   return &ToContext.Idents.get(FromId->getName());
5855 }
5856
5857 Selector ASTImporter::Import(Selector FromSel) {
5858   if (FromSel.isNull())
5859     return Selector();
5860
5861   SmallVector<IdentifierInfo *, 4> Idents;
5862   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5863   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5864     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5865   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5866 }
5867
5868 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5869                                                 DeclContext *DC,
5870                                                 unsigned IDNS,
5871                                                 NamedDecl **Decls,
5872                                                 unsigned NumDecls) {
5873   return Name;
5874 }
5875
5876 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5877   if (LastDiagFromFrom)
5878     ToContext.getDiagnostics().notePriorDiagnosticFrom(
5879       FromContext.getDiagnostics());
5880   LastDiagFromFrom = false;
5881   return ToContext.getDiagnostics().Report(Loc, DiagID);
5882 }
5883
5884 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5885   if (!LastDiagFromFrom)
5886     FromContext.getDiagnostics().notePriorDiagnosticFrom(
5887       ToContext.getDiagnostics());
5888   LastDiagFromFrom = true;
5889   return FromContext.getDiagnostics().Report(Loc, DiagID);
5890 }
5891
5892 void ASTImporter::CompleteDecl (Decl *D) {
5893   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5894     if (!ID->getDefinition())
5895       ID->startDefinition();
5896   }
5897   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5898     if (!PD->getDefinition())
5899       PD->startDefinition();
5900   }
5901   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5902     if (!TD->getDefinition() && !TD->isBeingDefined()) {
5903       TD->startDefinition();
5904       TD->setCompleteDefinition(true);
5905     }
5906   }
5907   else {
5908     assert (0 && "CompleteDecl called on a Decl that can't be completed");
5909   }
5910 }
5911
5912 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5913   ImportedDecls[From] = To;
5914   return To;
5915 }
5916
5917 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5918                                            bool Complain) {
5919   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5920    = ImportedTypes.find(From.getTypePtr());
5921   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5922     return true;
5923       
5924   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5925                                    false, Complain);
5926   return Ctx.IsStructurallyEquivalent(From, To);
5927 }