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