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