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