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