clang API Documentation

ASTImporter.cpp
Go to the documentation of this file.
00001 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file defines the ASTImporter class which imports AST nodes from one
00011 //  context into another context.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 #include "clang/AST/ASTImporter.h"
00015 #include "clang/AST/ASTContext.h"
00016 #include "clang/AST/ASTDiagnostic.h"
00017 #include "clang/AST/DeclCXX.h"
00018 #include "clang/AST/DeclObjC.h"
00019 #include "clang/AST/DeclVisitor.h"
00020 #include "clang/AST/StmtVisitor.h"
00021 #include "clang/AST/TypeVisitor.h"
00022 #include "clang/Basic/FileManager.h"
00023 #include "clang/Basic/SourceManager.h"
00024 #include "llvm/Support/MemoryBuffer.h"
00025 #include <deque>
00026 
00027 namespace clang {
00028   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
00029                           public DeclVisitor<ASTNodeImporter, Decl *>,
00030                           public StmtVisitor<ASTNodeImporter, Stmt *> {
00031     ASTImporter &Importer;
00032     
00033   public:
00034     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
00035     
00036     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
00037     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
00038     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
00039 
00040     // Importing types
00041     QualType VisitType(const Type *T);
00042     QualType VisitBuiltinType(const BuiltinType *T);
00043     QualType VisitComplexType(const ComplexType *T);
00044     QualType VisitPointerType(const PointerType *T);
00045     QualType VisitBlockPointerType(const BlockPointerType *T);
00046     QualType VisitLValueReferenceType(const LValueReferenceType *T);
00047     QualType VisitRValueReferenceType(const RValueReferenceType *T);
00048     QualType VisitMemberPointerType(const MemberPointerType *T);
00049     QualType VisitConstantArrayType(const ConstantArrayType *T);
00050     QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
00051     QualType VisitVariableArrayType(const VariableArrayType *T);
00052     // FIXME: DependentSizedArrayType
00053     // FIXME: DependentSizedExtVectorType
00054     QualType VisitVectorType(const VectorType *T);
00055     QualType VisitExtVectorType(const ExtVectorType *T);
00056     QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
00057     QualType VisitFunctionProtoType(const FunctionProtoType *T);
00058     // FIXME: UnresolvedUsingType
00059     QualType VisitParenType(const ParenType *T);
00060     QualType VisitTypedefType(const TypedefType *T);
00061     QualType VisitTypeOfExprType(const TypeOfExprType *T);
00062     // FIXME: DependentTypeOfExprType
00063     QualType VisitTypeOfType(const TypeOfType *T);
00064     QualType VisitDecltypeType(const DecltypeType *T);
00065     QualType VisitUnaryTransformType(const UnaryTransformType *T);
00066     QualType VisitAutoType(const AutoType *T);
00067     // FIXME: DependentDecltypeType
00068     QualType VisitRecordType(const RecordType *T);
00069     QualType VisitEnumType(const EnumType *T);
00070     // FIXME: TemplateTypeParmType
00071     // FIXME: SubstTemplateTypeParmType
00072     QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
00073     QualType VisitElaboratedType(const ElaboratedType *T);
00074     // FIXME: DependentNameType
00075     // FIXME: DependentTemplateSpecializationType
00076     QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
00077     QualType VisitObjCObjectType(const ObjCObjectType *T);
00078     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
00079                             
00080     // Importing declarations                            
00081     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
00082                          DeclContext *&LexicalDC, DeclarationName &Name, 
00083                          SourceLocation &Loc);
00084     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
00085     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
00086                                   DeclarationNameInfo& To);
00087     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
00088                         
00089     /// \brief What we should import from the definition.
00090     enum ImportDefinitionKind { 
00091       /// \brief Import the default subset of the definition, which might be
00092       /// nothing (if minimal import is set) or might be everything (if minimal
00093       /// import is not set).
00094       IDK_Default,
00095       /// \brief Import everything.
00096       IDK_Everything,
00097       /// \brief Import only the bare bones needed to establish a valid
00098       /// DeclContext.
00099       IDK_Basic
00100     };
00101 
00102     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
00103       return IDK == IDK_Everything ||
00104              (IDK == IDK_Default && !Importer.isMinimalImport());
00105     }
00106 
00107     bool ImportDefinition(RecordDecl *From, RecordDecl *To, 
00108                           ImportDefinitionKind Kind = IDK_Default);
00109     bool ImportDefinition(VarDecl *From, VarDecl *To,
00110                           ImportDefinitionKind Kind = IDK_Default);
00111     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
00112                           ImportDefinitionKind Kind = IDK_Default);
00113     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
00114                           ImportDefinitionKind Kind = IDK_Default);
00115     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
00116                           ImportDefinitionKind Kind = IDK_Default);
00117     TemplateParameterList *ImportTemplateParameterList(
00118                                                  TemplateParameterList *Params);
00119     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
00120     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
00121                                  unsigned NumFromArgs,
00122                                SmallVectorImpl<TemplateArgument> &ToArgs);
00123     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
00124                            bool Complain = true);
00125     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
00126                            bool Complain = true);
00127     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
00128     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
00129     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
00130     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
00131     Decl *VisitDecl(Decl *D);
00132     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
00133     Decl *VisitNamespaceDecl(NamespaceDecl *D);
00134     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
00135     Decl *VisitTypedefDecl(TypedefDecl *D);
00136     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
00137     Decl *VisitEnumDecl(EnumDecl *D);
00138     Decl *VisitRecordDecl(RecordDecl *D);
00139     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
00140     Decl *VisitFunctionDecl(FunctionDecl *D);
00141     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
00142     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
00143     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
00144     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
00145     Decl *VisitFieldDecl(FieldDecl *D);
00146     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
00147     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
00148     Decl *VisitVarDecl(VarDecl *D);
00149     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
00150     Decl *VisitParmVarDecl(ParmVarDecl *D);
00151     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
00152     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
00153     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
00154     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
00155     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
00156     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
00157     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
00158     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
00159     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
00160     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
00161     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
00162     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
00163     Decl *VisitClassTemplateSpecializationDecl(
00164                                             ClassTemplateSpecializationDecl *D);
00165     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
00166     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
00167 
00168     // Importing statements
00169     Stmt *VisitStmt(Stmt *S);
00170 
00171     // Importing expressions
00172     Expr *VisitExpr(Expr *E);
00173     Expr *VisitDeclRefExpr(DeclRefExpr *E);
00174     Expr *VisitIntegerLiteral(IntegerLiteral *E);
00175     Expr *VisitCharacterLiteral(CharacterLiteral *E);
00176     Expr *VisitParenExpr(ParenExpr *E);
00177     Expr *VisitUnaryOperator(UnaryOperator *E);
00178     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
00179     Expr *VisitBinaryOperator(BinaryOperator *E);
00180     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
00181     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
00182     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
00183   };
00184 }
00185 using namespace clang;
00186 
00187 //----------------------------------------------------------------------------
00188 // Structural Equivalence
00189 //----------------------------------------------------------------------------
00190 
00191 namespace {
00192   struct StructuralEquivalenceContext {
00193     /// \brief AST contexts for which we are checking structural equivalence.
00194     ASTContext &C1, &C2;
00195     
00196     /// \brief The set of "tentative" equivalences between two canonical 
00197     /// declarations, mapping from a declaration in the first context to the
00198     /// declaration in the second context that we believe to be equivalent.
00199     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
00200     
00201     /// \brief Queue of declarations in the first context whose equivalence
00202     /// with a declaration in the second context still needs to be verified.
00203     std::deque<Decl *> DeclsToCheck;
00204     
00205     /// \brief Declaration (from, to) pairs that are known not to be equivalent
00206     /// (which we have already complained about).
00207     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
00208     
00209     /// \brief Whether we're being strict about the spelling of types when 
00210     /// unifying two types.
00211     bool StrictTypeSpelling;
00212 
00213     /// \brief Whether to complain about failures.
00214     bool Complain;
00215 
00216     /// \brief \c true if the last diagnostic came from C2.
00217     bool LastDiagFromC2;
00218 
00219     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
00220                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
00221                                  bool StrictTypeSpelling = false,
00222                                  bool Complain = true)
00223       : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
00224         StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
00225         LastDiagFromC2(false) {}
00226 
00227     /// \brief Determine whether the two declarations are structurally
00228     /// equivalent.
00229     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
00230     
00231     /// \brief Determine whether the two types are structurally equivalent.
00232     bool IsStructurallyEquivalent(QualType T1, QualType T2);
00233 
00234   private:
00235     /// \brief Finish checking all of the structural equivalences.
00236     ///
00237     /// \returns true if an error occurred, false otherwise.
00238     bool Finish();
00239     
00240   public:
00241     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
00242       assert(Complain && "Not allowed to complain");
00243       if (LastDiagFromC2)
00244         C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
00245       LastDiagFromC2 = false;
00246       return C1.getDiagnostics().Report(Loc, DiagID);
00247     }
00248 
00249     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
00250       assert(Complain && "Not allowed to complain");
00251       if (!LastDiagFromC2)
00252         C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
00253       LastDiagFromC2 = true;
00254       return C2.getDiagnostics().Report(Loc, DiagID);
00255     }
00256   };
00257 }
00258 
00259 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00260                                      QualType T1, QualType T2);
00261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00262                                      Decl *D1, Decl *D2);
00263 
00264 /// \brief Determine structural equivalence of two expressions.
00265 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00266                                      Expr *E1, Expr *E2) {
00267   if (!E1 || !E2)
00268     return E1 == E2;
00269   
00270   // FIXME: Actually perform a structural comparison!
00271   return true;
00272 }
00273 
00274 /// \brief Determine whether two identifiers are equivalent.
00275 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
00276                                      const IdentifierInfo *Name2) {
00277   if (!Name1 || !Name2)
00278     return Name1 == Name2;
00279   
00280   return Name1->getName() == Name2->getName();
00281 }
00282 
00283 /// \brief Determine whether two nested-name-specifiers are equivalent.
00284 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00285                                      NestedNameSpecifier *NNS1,
00286                                      NestedNameSpecifier *NNS2) {
00287   // FIXME: Implement!
00288   return true;
00289 }
00290 
00291 /// \brief Determine whether two template arguments are equivalent.
00292 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00293                                      const TemplateArgument &Arg1,
00294                                      const TemplateArgument &Arg2) {
00295   if (Arg1.getKind() != Arg2.getKind())
00296     return false;
00297 
00298   switch (Arg1.getKind()) {
00299   case TemplateArgument::Null:
00300     return true;
00301       
00302   case TemplateArgument::Type:
00303     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
00304 
00305   case TemplateArgument::Integral:
00306     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(), 
00307                                           Arg2.getIntegralType()))
00308       return false;
00309     
00310     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
00311       
00312   case TemplateArgument::Declaration:
00313     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
00314 
00315   case TemplateArgument::NullPtr:
00316     return true; // FIXME: Is this correct?
00317 
00318   case TemplateArgument::Template:
00319     return IsStructurallyEquivalent(Context, 
00320                                     Arg1.getAsTemplate(), 
00321                                     Arg2.getAsTemplate());
00322 
00323   case TemplateArgument::TemplateExpansion:
00324     return IsStructurallyEquivalent(Context, 
00325                                     Arg1.getAsTemplateOrTemplatePattern(), 
00326                                     Arg2.getAsTemplateOrTemplatePattern());
00327 
00328   case TemplateArgument::Expression:
00329     return IsStructurallyEquivalent(Context, 
00330                                     Arg1.getAsExpr(), Arg2.getAsExpr());
00331       
00332   case TemplateArgument::Pack:
00333     if (Arg1.pack_size() != Arg2.pack_size())
00334       return false;
00335       
00336     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
00337       if (!IsStructurallyEquivalent(Context, 
00338                                     Arg1.pack_begin()[I],
00339                                     Arg2.pack_begin()[I]))
00340         return false;
00341       
00342     return true;
00343   }
00344   
00345   llvm_unreachable("Invalid template argument kind");
00346 }
00347 
00348 /// \brief Determine structural equivalence for the common part of array 
00349 /// types.
00350 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
00351                                           const ArrayType *Array1, 
00352                                           const ArrayType *Array2) {
00353   if (!IsStructurallyEquivalent(Context, 
00354                                 Array1->getElementType(), 
00355                                 Array2->getElementType()))
00356     return false;
00357   if (Array1->getSizeModifier() != Array2->getSizeModifier())
00358     return false;
00359   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
00360     return false;
00361   
00362   return true;
00363 }
00364 
00365 /// \brief Determine structural equivalence of two types.
00366 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00367                                      QualType T1, QualType T2) {
00368   if (T1.isNull() || T2.isNull())
00369     return T1.isNull() && T2.isNull();
00370   
00371   if (!Context.StrictTypeSpelling) {
00372     // We aren't being strict about token-to-token equivalence of types,
00373     // so map down to the canonical type.
00374     T1 = Context.C1.getCanonicalType(T1);
00375     T2 = Context.C2.getCanonicalType(T2);
00376   }
00377   
00378   if (T1.getQualifiers() != T2.getQualifiers())
00379     return false;
00380   
00381   Type::TypeClass TC = T1->getTypeClass();
00382   
00383   if (T1->getTypeClass() != T2->getTypeClass()) {
00384     // Compare function types with prototypes vs. without prototypes as if
00385     // both did not have prototypes.
00386     if (T1->getTypeClass() == Type::FunctionProto &&
00387         T2->getTypeClass() == Type::FunctionNoProto)
00388       TC = Type::FunctionNoProto;
00389     else if (T1->getTypeClass() == Type::FunctionNoProto &&
00390              T2->getTypeClass() == Type::FunctionProto)
00391       TC = Type::FunctionNoProto;
00392     else
00393       return false;
00394   }
00395   
00396   switch (TC) {
00397   case Type::Builtin:
00398     // FIXME: Deal with Char_S/Char_U. 
00399     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
00400       return false;
00401     break;
00402   
00403   case Type::Complex:
00404     if (!IsStructurallyEquivalent(Context,
00405                                   cast<ComplexType>(T1)->getElementType(),
00406                                   cast<ComplexType>(T2)->getElementType()))
00407       return false;
00408     break;
00409   
00410   case Type::Adjusted:
00411   case Type::Decayed:
00412     if (!IsStructurallyEquivalent(Context,
00413                                   cast<AdjustedType>(T1)->getOriginalType(),
00414                                   cast<AdjustedType>(T2)->getOriginalType()))
00415       return false;
00416     break;
00417 
00418   case Type::Pointer:
00419     if (!IsStructurallyEquivalent(Context,
00420                                   cast<PointerType>(T1)->getPointeeType(),
00421                                   cast<PointerType>(T2)->getPointeeType()))
00422       return false;
00423     break;
00424 
00425   case Type::BlockPointer:
00426     if (!IsStructurallyEquivalent(Context,
00427                                   cast<BlockPointerType>(T1)->getPointeeType(),
00428                                   cast<BlockPointerType>(T2)->getPointeeType()))
00429       return false;
00430     break;
00431 
00432   case Type::LValueReference:
00433   case Type::RValueReference: {
00434     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
00435     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
00436     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
00437       return false;
00438     if (Ref1->isInnerRef() != Ref2->isInnerRef())
00439       return false;
00440     if (!IsStructurallyEquivalent(Context,
00441                                   Ref1->getPointeeTypeAsWritten(),
00442                                   Ref2->getPointeeTypeAsWritten()))
00443       return false;
00444     break;
00445   }
00446       
00447   case Type::MemberPointer: {
00448     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
00449     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
00450     if (!IsStructurallyEquivalent(Context,
00451                                   MemPtr1->getPointeeType(),
00452                                   MemPtr2->getPointeeType()))
00453       return false;
00454     if (!IsStructurallyEquivalent(Context,
00455                                   QualType(MemPtr1->getClass(), 0),
00456                                   QualType(MemPtr2->getClass(), 0)))
00457       return false;
00458     break;
00459   }
00460       
00461   case Type::ConstantArray: {
00462     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
00463     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
00464     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
00465       return false;
00466     
00467     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
00468       return false;
00469     break;
00470   }
00471 
00472   case Type::IncompleteArray:
00473     if (!IsArrayStructurallyEquivalent(Context, 
00474                                        cast<ArrayType>(T1), 
00475                                        cast<ArrayType>(T2)))
00476       return false;
00477     break;
00478       
00479   case Type::VariableArray: {
00480     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
00481     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
00482     if (!IsStructurallyEquivalent(Context, 
00483                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
00484       return false;
00485     
00486     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
00487       return false;
00488     
00489     break;
00490   }
00491   
00492   case Type::DependentSizedArray: {
00493     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
00494     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
00495     if (!IsStructurallyEquivalent(Context, 
00496                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
00497       return false;
00498     
00499     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
00500       return false;
00501     
00502     break;
00503   }
00504       
00505   case Type::DependentSizedExtVector: {
00506     const DependentSizedExtVectorType *Vec1
00507       = cast<DependentSizedExtVectorType>(T1);
00508     const DependentSizedExtVectorType *Vec2
00509       = cast<DependentSizedExtVectorType>(T2);
00510     if (!IsStructurallyEquivalent(Context, 
00511                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
00512       return false;
00513     if (!IsStructurallyEquivalent(Context, 
00514                                   Vec1->getElementType(), 
00515                                   Vec2->getElementType()))
00516       return false;
00517     break;
00518   }
00519    
00520   case Type::Vector: 
00521   case Type::ExtVector: {
00522     const VectorType *Vec1 = cast<VectorType>(T1);
00523     const VectorType *Vec2 = cast<VectorType>(T2);
00524     if (!IsStructurallyEquivalent(Context, 
00525                                   Vec1->getElementType(),
00526                                   Vec2->getElementType()))
00527       return false;
00528     if (Vec1->getNumElements() != Vec2->getNumElements())
00529       return false;
00530     if (Vec1->getVectorKind() != Vec2->getVectorKind())
00531       return false;
00532     break;
00533   }
00534 
00535   case Type::FunctionProto: {
00536     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
00537     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
00538     if (Proto1->getNumParams() != Proto2->getNumParams())
00539       return false;
00540     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
00541       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
00542                                     Proto2->getParamType(I)))
00543         return false;
00544     }
00545     if (Proto1->isVariadic() != Proto2->isVariadic())
00546       return false;
00547     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
00548       return false;
00549     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
00550       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
00551         return false;
00552       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
00553         if (!IsStructurallyEquivalent(Context,
00554                                       Proto1->getExceptionType(I),
00555                                       Proto2->getExceptionType(I)))
00556           return false;
00557       }
00558     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
00559       if (!IsStructurallyEquivalent(Context,
00560                                     Proto1->getNoexceptExpr(),
00561                                     Proto2->getNoexceptExpr()))
00562         return false;
00563     }
00564     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
00565       return false;
00566     
00567     // Fall through to check the bits common with FunctionNoProtoType.
00568   }
00569       
00570   case Type::FunctionNoProto: {
00571     const FunctionType *Function1 = cast<FunctionType>(T1);
00572     const FunctionType *Function2 = cast<FunctionType>(T2);
00573     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
00574                                   Function2->getReturnType()))
00575       return false;
00576       if (Function1->getExtInfo() != Function2->getExtInfo())
00577         return false;
00578     break;
00579   }
00580    
00581   case Type::UnresolvedUsing:
00582     if (!IsStructurallyEquivalent(Context,
00583                                   cast<UnresolvedUsingType>(T1)->getDecl(),
00584                                   cast<UnresolvedUsingType>(T2)->getDecl()))
00585       return false;
00586       
00587     break;
00588 
00589   case Type::Attributed:
00590     if (!IsStructurallyEquivalent(Context,
00591                                   cast<AttributedType>(T1)->getModifiedType(),
00592                                   cast<AttributedType>(T2)->getModifiedType()))
00593       return false;
00594     if (!IsStructurallyEquivalent(Context,
00595                                 cast<AttributedType>(T1)->getEquivalentType(),
00596                                 cast<AttributedType>(T2)->getEquivalentType()))
00597       return false;
00598     break;
00599       
00600   case Type::Paren:
00601     if (!IsStructurallyEquivalent(Context,
00602                                   cast<ParenType>(T1)->getInnerType(),
00603                                   cast<ParenType>(T2)->getInnerType()))
00604       return false;
00605     break;
00606 
00607   case Type::Typedef:
00608     if (!IsStructurallyEquivalent(Context,
00609                                   cast<TypedefType>(T1)->getDecl(),
00610                                   cast<TypedefType>(T2)->getDecl()))
00611       return false;
00612     break;
00613       
00614   case Type::TypeOfExpr:
00615     if (!IsStructurallyEquivalent(Context,
00616                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
00617                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
00618       return false;
00619     break;
00620       
00621   case Type::TypeOf:
00622     if (!IsStructurallyEquivalent(Context,
00623                                   cast<TypeOfType>(T1)->getUnderlyingType(),
00624                                   cast<TypeOfType>(T2)->getUnderlyingType()))
00625       return false;
00626     break;
00627 
00628   case Type::UnaryTransform:
00629     if (!IsStructurallyEquivalent(Context,
00630                              cast<UnaryTransformType>(T1)->getUnderlyingType(),
00631                              cast<UnaryTransformType>(T1)->getUnderlyingType()))
00632       return false;
00633     break;
00634 
00635   case Type::Decltype:
00636     if (!IsStructurallyEquivalent(Context,
00637                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
00638                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
00639       return false;
00640     break;
00641 
00642   case Type::Auto:
00643     if (!IsStructurallyEquivalent(Context,
00644                                   cast<AutoType>(T1)->getDeducedType(),
00645                                   cast<AutoType>(T2)->getDeducedType()))
00646       return false;
00647     break;
00648 
00649   case Type::Record:
00650   case Type::Enum:
00651     if (!IsStructurallyEquivalent(Context,
00652                                   cast<TagType>(T1)->getDecl(),
00653                                   cast<TagType>(T2)->getDecl()))
00654       return false;
00655     break;
00656 
00657   case Type::TemplateTypeParm: {
00658     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
00659     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
00660     if (Parm1->getDepth() != Parm2->getDepth())
00661       return false;
00662     if (Parm1->getIndex() != Parm2->getIndex())
00663       return false;
00664     if (Parm1->isParameterPack() != Parm2->isParameterPack())
00665       return false;
00666     
00667     // Names of template type parameters are never significant.
00668     break;
00669   }
00670       
00671   case Type::SubstTemplateTypeParm: {
00672     const SubstTemplateTypeParmType *Subst1
00673       = cast<SubstTemplateTypeParmType>(T1);
00674     const SubstTemplateTypeParmType *Subst2
00675       = cast<SubstTemplateTypeParmType>(T2);
00676     if (!IsStructurallyEquivalent(Context,
00677                                   QualType(Subst1->getReplacedParameter(), 0),
00678                                   QualType(Subst2->getReplacedParameter(), 0)))
00679       return false;
00680     if (!IsStructurallyEquivalent(Context, 
00681                                   Subst1->getReplacementType(),
00682                                   Subst2->getReplacementType()))
00683       return false;
00684     break;
00685   }
00686 
00687   case Type::SubstTemplateTypeParmPack: {
00688     const SubstTemplateTypeParmPackType *Subst1
00689       = cast<SubstTemplateTypeParmPackType>(T1);
00690     const SubstTemplateTypeParmPackType *Subst2
00691       = cast<SubstTemplateTypeParmPackType>(T2);
00692     if (!IsStructurallyEquivalent(Context,
00693                                   QualType(Subst1->getReplacedParameter(), 0),
00694                                   QualType(Subst2->getReplacedParameter(), 0)))
00695       return false;
00696     if (!IsStructurallyEquivalent(Context, 
00697                                   Subst1->getArgumentPack(),
00698                                   Subst2->getArgumentPack()))
00699       return false;
00700     break;
00701   }
00702   case Type::TemplateSpecialization: {
00703     const TemplateSpecializationType *Spec1
00704       = cast<TemplateSpecializationType>(T1);
00705     const TemplateSpecializationType *Spec2
00706       = cast<TemplateSpecializationType>(T2);
00707     if (!IsStructurallyEquivalent(Context,
00708                                   Spec1->getTemplateName(),
00709                                   Spec2->getTemplateName()))
00710       return false;
00711     if (Spec1->getNumArgs() != Spec2->getNumArgs())
00712       return false;
00713     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
00714       if (!IsStructurallyEquivalent(Context, 
00715                                     Spec1->getArg(I), Spec2->getArg(I)))
00716         return false;
00717     }
00718     break;
00719   }
00720       
00721   case Type::Elaborated: {
00722     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
00723     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
00724     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
00725     if (Elab1->getKeyword() != Elab2->getKeyword())
00726       return false;
00727     if (!IsStructurallyEquivalent(Context, 
00728                                   Elab1->getQualifier(), 
00729                                   Elab2->getQualifier()))
00730       return false;
00731     if (!IsStructurallyEquivalent(Context,
00732                                   Elab1->getNamedType(),
00733                                   Elab2->getNamedType()))
00734       return false;
00735     break;
00736   }
00737 
00738   case Type::InjectedClassName: {
00739     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
00740     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
00741     if (!IsStructurallyEquivalent(Context,
00742                                   Inj1->getInjectedSpecializationType(),
00743                                   Inj2->getInjectedSpecializationType()))
00744       return false;
00745     break;
00746   }
00747 
00748   case Type::DependentName: {
00749     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
00750     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
00751     if (!IsStructurallyEquivalent(Context, 
00752                                   Typename1->getQualifier(),
00753                                   Typename2->getQualifier()))
00754       return false;
00755     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
00756                                   Typename2->getIdentifier()))
00757       return false;
00758     
00759     break;
00760   }
00761   
00762   case Type::DependentTemplateSpecialization: {
00763     const DependentTemplateSpecializationType *Spec1 =
00764       cast<DependentTemplateSpecializationType>(T1);
00765     const DependentTemplateSpecializationType *Spec2 =
00766       cast<DependentTemplateSpecializationType>(T2);
00767     if (!IsStructurallyEquivalent(Context, 
00768                                   Spec1->getQualifier(),
00769                                   Spec2->getQualifier()))
00770       return false;
00771     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
00772                                   Spec2->getIdentifier()))
00773       return false;
00774     if (Spec1->getNumArgs() != Spec2->getNumArgs())
00775       return false;
00776     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
00777       if (!IsStructurallyEquivalent(Context,
00778                                     Spec1->getArg(I), Spec2->getArg(I)))
00779         return false;
00780     }
00781     break;
00782   }
00783 
00784   case Type::PackExpansion:
00785     if (!IsStructurallyEquivalent(Context,
00786                                   cast<PackExpansionType>(T1)->getPattern(),
00787                                   cast<PackExpansionType>(T2)->getPattern()))
00788       return false;
00789     break;
00790 
00791   case Type::ObjCInterface: {
00792     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
00793     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
00794     if (!IsStructurallyEquivalent(Context, 
00795                                   Iface1->getDecl(), Iface2->getDecl()))
00796       return false;
00797     break;
00798   }
00799 
00800   case Type::ObjCObject: {
00801     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
00802     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
00803     if (!IsStructurallyEquivalent(Context,
00804                                   Obj1->getBaseType(),
00805                                   Obj2->getBaseType()))
00806       return false;
00807     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
00808       return false;
00809     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
00810       if (!IsStructurallyEquivalent(Context,
00811                                     Obj1->getProtocol(I),
00812                                     Obj2->getProtocol(I)))
00813         return false;
00814     }
00815     break;
00816   }
00817 
00818   case Type::ObjCObjectPointer: {
00819     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
00820     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
00821     if (!IsStructurallyEquivalent(Context, 
00822                                   Ptr1->getPointeeType(),
00823                                   Ptr2->getPointeeType()))
00824       return false;
00825     break;
00826   }
00827 
00828   case Type::Atomic: {
00829     if (!IsStructurallyEquivalent(Context,
00830                                   cast<AtomicType>(T1)->getValueType(),
00831                                   cast<AtomicType>(T2)->getValueType()))
00832       return false;
00833     break;
00834   }
00835 
00836   } // end switch
00837 
00838   return true;
00839 }
00840 
00841 /// \brief Determine structural equivalence of two fields.
00842 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00843                                      FieldDecl *Field1, FieldDecl *Field2) {
00844   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
00845 
00846   // For anonymous structs/unions, match up the anonymous struct/union type
00847   // declarations directly, so that we don't go off searching for anonymous
00848   // types
00849   if (Field1->isAnonymousStructOrUnion() &&
00850       Field2->isAnonymousStructOrUnion()) {
00851     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
00852     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
00853     return IsStructurallyEquivalent(Context, D1, D2);
00854   }
00855     
00856   // Check for equivalent field names.
00857   IdentifierInfo *Name1 = Field1->getIdentifier();
00858   IdentifierInfo *Name2 = Field2->getIdentifier();
00859   if (!::IsStructurallyEquivalent(Name1, Name2))
00860     return false;
00861 
00862   if (!IsStructurallyEquivalent(Context,
00863                                 Field1->getType(), Field2->getType())) {
00864     if (Context.Complain) {
00865       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
00866         << Context.C2.getTypeDeclType(Owner2);
00867       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
00868         << Field2->getDeclName() << Field2->getType();
00869       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
00870         << Field1->getDeclName() << Field1->getType();
00871     }
00872     return false;
00873   }
00874   
00875   if (Field1->isBitField() != Field2->isBitField()) {
00876     if (Context.Complain) {
00877       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
00878         << Context.C2.getTypeDeclType(Owner2);
00879       if (Field1->isBitField()) {
00880         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
00881         << Field1->getDeclName() << Field1->getType()
00882         << Field1->getBitWidthValue(Context.C1);
00883         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
00884         << Field2->getDeclName();
00885       } else {
00886         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
00887         << Field2->getDeclName() << Field2->getType()
00888         << Field2->getBitWidthValue(Context.C2);
00889         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
00890         << Field1->getDeclName();
00891       }
00892     }
00893     return false;
00894   }
00895   
00896   if (Field1->isBitField()) {
00897     // Make sure that the bit-fields are the same length.
00898     unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
00899     unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
00900     
00901     if (Bits1 != Bits2) {
00902       if (Context.Complain) {
00903         Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
00904           << Context.C2.getTypeDeclType(Owner2);
00905         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
00906           << Field2->getDeclName() << Field2->getType() << Bits2;
00907         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
00908           << Field1->getDeclName() << Field1->getType() << Bits1;
00909       }
00910       return false;
00911     }
00912   }
00913 
00914   return true;
00915 }
00916 
00917 /// \brief Find the index of the given anonymous struct/union within its
00918 /// context.
00919 ///
00920 /// \returns Returns the index of this anonymous struct/union in its context,
00921 /// including the next assigned index (if none of them match). Returns an
00922 /// empty option if the context is not a record, i.e.. if the anonymous
00923 /// struct/union is at namespace or block scope.
00924 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
00925   ASTContext &Context = Anon->getASTContext();
00926   QualType AnonTy = Context.getRecordType(Anon);
00927 
00928   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
00929   if (!Owner)
00930     return None;
00931 
00932   unsigned Index = 0;
00933   for (const auto *D : Owner->noload_decls()) {
00934     const auto *F = dyn_cast<FieldDecl>(D);
00935     if (!F || !F->isAnonymousStructOrUnion())
00936       continue;
00937 
00938     if (Context.hasSameType(F->getType(), AnonTy))
00939       break;
00940 
00941     ++Index;
00942   }
00943 
00944   return Index;
00945 }
00946 
00947 /// \brief Determine structural equivalence of two records.
00948 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
00949                                      RecordDecl *D1, RecordDecl *D2) {
00950   if (D1->isUnion() != D2->isUnion()) {
00951     if (Context.Complain) {
00952       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
00953         << Context.C2.getTypeDeclType(D2);
00954       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
00955         << D1->getDeclName() << (unsigned)D1->getTagKind();
00956     }
00957     return false;
00958   }
00959 
00960   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
00961     // If both anonymous structs/unions are in a record context, make sure
00962     // they occur in the same location in the context records.
00963     if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
00964       if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
00965         if (*Index1 != *Index2)
00966           return false;
00967       }
00968     }
00969   }
00970 
00971   // If both declarations are class template specializations, we know
00972   // the ODR applies, so check the template and template arguments.
00973   ClassTemplateSpecializationDecl *Spec1
00974     = dyn_cast<ClassTemplateSpecializationDecl>(D1);
00975   ClassTemplateSpecializationDecl *Spec2
00976     = dyn_cast<ClassTemplateSpecializationDecl>(D2);
00977   if (Spec1 && Spec2) {
00978     // Check that the specialized templates are the same.
00979     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
00980                                   Spec2->getSpecializedTemplate()))
00981       return false;
00982     
00983     // Check that the template arguments are the same.
00984     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
00985       return false;
00986     
00987     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
00988       if (!IsStructurallyEquivalent(Context, 
00989                                     Spec1->getTemplateArgs().get(I),
00990                                     Spec2->getTemplateArgs().get(I)))
00991         return false;
00992   }  
00993   // If one is a class template specialization and the other is not, these
00994   // structures are different.
00995   else if (Spec1 || Spec2)
00996     return false;
00997 
00998   // Compare the definitions of these two records. If either or both are
00999   // incomplete, we assume that they are equivalent.
01000   D1 = D1->getDefinition();
01001   D2 = D2->getDefinition();
01002   if (!D1 || !D2)
01003     return true;
01004   
01005   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
01006     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
01007       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
01008         if (Context.Complain) {
01009           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01010             << Context.C2.getTypeDeclType(D2);
01011           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
01012             << D2CXX->getNumBases();
01013           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
01014             << D1CXX->getNumBases();
01015         }
01016         return false;
01017       }
01018       
01019       // Check the base classes. 
01020       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(), 
01021                                            BaseEnd1 = D1CXX->bases_end(),
01022                                                 Base2 = D2CXX->bases_begin();
01023            Base1 != BaseEnd1;
01024            ++Base1, ++Base2) {        
01025         if (!IsStructurallyEquivalent(Context, 
01026                                       Base1->getType(), Base2->getType())) {
01027           if (Context.Complain) {
01028             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01029               << Context.C2.getTypeDeclType(D2);
01030             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
01031               << Base2->getType()
01032               << Base2->getSourceRange();
01033             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
01034               << Base1->getType()
01035               << Base1->getSourceRange();
01036           }
01037           return false;
01038         }
01039         
01040         // Check virtual vs. non-virtual inheritance mismatch.
01041         if (Base1->isVirtual() != Base2->isVirtual()) {
01042           if (Context.Complain) {
01043             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01044               << Context.C2.getTypeDeclType(D2);
01045             Context.Diag2(Base2->getLocStart(),
01046                           diag::note_odr_virtual_base)
01047               << Base2->isVirtual() << Base2->getSourceRange();
01048             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
01049               << Base1->isVirtual()
01050               << Base1->getSourceRange();
01051           }
01052           return false;
01053         }
01054       }
01055     } else if (D1CXX->getNumBases() > 0) {
01056       if (Context.Complain) {
01057         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01058           << Context.C2.getTypeDeclType(D2);
01059         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
01060         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
01061           << Base1->getType()
01062           << Base1->getSourceRange();
01063         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
01064       }
01065       return false;
01066     }
01067   }
01068   
01069   // Check the fields for consistency.
01070   RecordDecl::field_iterator Field2 = D2->field_begin(),
01071                              Field2End = D2->field_end();
01072   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
01073                                   Field1End = D1->field_end();
01074        Field1 != Field1End;
01075        ++Field1, ++Field2) {
01076     if (Field2 == Field2End) {
01077       if (Context.Complain) {
01078         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01079           << Context.C2.getTypeDeclType(D2);
01080         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
01081           << Field1->getDeclName() << Field1->getType();
01082         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
01083       }
01084       return false;
01085     }
01086     
01087     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
01088       return false;    
01089   }
01090   
01091   if (Field2 != Field2End) {
01092     if (Context.Complain) {
01093       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01094         << Context.C2.getTypeDeclType(D2);
01095       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
01096         << Field2->getDeclName() << Field2->getType();
01097       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
01098     }
01099     return false;
01100   }
01101   
01102   return true;
01103 }
01104      
01105 /// \brief Determine structural equivalence of two enums.
01106 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01107                                      EnumDecl *D1, EnumDecl *D2) {
01108   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
01109                              EC2End = D2->enumerator_end();
01110   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
01111                                   EC1End = D1->enumerator_end();
01112        EC1 != EC1End; ++EC1, ++EC2) {
01113     if (EC2 == EC2End) {
01114       if (Context.Complain) {
01115         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01116           << Context.C2.getTypeDeclType(D2);
01117         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
01118           << EC1->getDeclName() 
01119           << EC1->getInitVal().toString(10);
01120         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
01121       }
01122       return false;
01123     }
01124     
01125     llvm::APSInt Val1 = EC1->getInitVal();
01126     llvm::APSInt Val2 = EC2->getInitVal();
01127     if (!llvm::APSInt::isSameValue(Val1, Val2) || 
01128         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
01129       if (Context.Complain) {
01130         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01131           << Context.C2.getTypeDeclType(D2);
01132         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
01133           << EC2->getDeclName() 
01134           << EC2->getInitVal().toString(10);
01135         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
01136           << EC1->getDeclName() 
01137           << EC1->getInitVal().toString(10);
01138       }
01139       return false;
01140     }
01141   }
01142   
01143   if (EC2 != EC2End) {
01144     if (Context.Complain) {
01145       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
01146         << Context.C2.getTypeDeclType(D2);
01147       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
01148         << EC2->getDeclName() 
01149         << EC2->getInitVal().toString(10);
01150       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
01151     }
01152     return false;
01153   }
01154   
01155   return true;
01156 }
01157 
01158 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01159                                      TemplateParameterList *Params1,
01160                                      TemplateParameterList *Params2) {
01161   if (Params1->size() != Params2->size()) {
01162     if (Context.Complain) {
01163       Context.Diag2(Params2->getTemplateLoc(), 
01164                     diag::err_odr_different_num_template_parameters)
01165         << Params1->size() << Params2->size();
01166       Context.Diag1(Params1->getTemplateLoc(), 
01167                     diag::note_odr_template_parameter_list);
01168     }
01169     return false;
01170   }
01171   
01172   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
01173     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
01174       if (Context.Complain) {
01175         Context.Diag2(Params2->getParam(I)->getLocation(), 
01176                       diag::err_odr_different_template_parameter_kind);
01177         Context.Diag1(Params1->getParam(I)->getLocation(),
01178                       diag::note_odr_template_parameter_here);
01179       }
01180       return false;
01181     }
01182     
01183     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
01184                                           Params2->getParam(I))) {
01185       
01186       return false;
01187     }
01188   }
01189   
01190   return true;
01191 }
01192 
01193 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01194                                      TemplateTypeParmDecl *D1,
01195                                      TemplateTypeParmDecl *D2) {
01196   if (D1->isParameterPack() != D2->isParameterPack()) {
01197     if (Context.Complain) {
01198       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
01199         << D2->isParameterPack();
01200       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
01201         << D1->isParameterPack();
01202     }
01203     return false;
01204   }
01205   
01206   return true;
01207 }
01208 
01209 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01210                                      NonTypeTemplateParmDecl *D1,
01211                                      NonTypeTemplateParmDecl *D2) {
01212   if (D1->isParameterPack() != D2->isParameterPack()) {
01213     if (Context.Complain) {
01214       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
01215         << D2->isParameterPack();
01216       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
01217         << D1->isParameterPack();
01218     }
01219     return false;
01220   }
01221   
01222   // Check types.
01223   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
01224     if (Context.Complain) {
01225       Context.Diag2(D2->getLocation(),
01226                     diag::err_odr_non_type_parameter_type_inconsistent)
01227         << D2->getType() << D1->getType();
01228       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
01229         << D1->getType();
01230     }
01231     return false;
01232   }
01233   
01234   return true;
01235 }
01236 
01237 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01238                                      TemplateTemplateParmDecl *D1,
01239                                      TemplateTemplateParmDecl *D2) {
01240   if (D1->isParameterPack() != D2->isParameterPack()) {
01241     if (Context.Complain) {
01242       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
01243         << D2->isParameterPack();
01244       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
01245         << D1->isParameterPack();
01246     }
01247     return false;
01248   }
01249 
01250   // Check template parameter lists.
01251   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
01252                                   D2->getTemplateParameters());
01253 }
01254 
01255 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01256                                      ClassTemplateDecl *D1, 
01257                                      ClassTemplateDecl *D2) {
01258   // Check template parameters.
01259   if (!IsStructurallyEquivalent(Context,
01260                                 D1->getTemplateParameters(),
01261                                 D2->getTemplateParameters()))
01262     return false;
01263   
01264   // Check the templated declaration.
01265   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(), 
01266                                           D2->getTemplatedDecl());
01267 }
01268 
01269 /// \brief Determine structural equivalence of two declarations.
01270 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
01271                                      Decl *D1, Decl *D2) {
01272   // FIXME: Check for known structural equivalences via a callback of some sort.
01273   
01274   // Check whether we already know that these two declarations are not
01275   // structurally equivalent.
01276   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
01277                                                       D2->getCanonicalDecl())))
01278     return false;
01279   
01280   // Determine whether we've already produced a tentative equivalence for D1.
01281   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
01282   if (EquivToD1)
01283     return EquivToD1 == D2->getCanonicalDecl();
01284   
01285   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
01286   EquivToD1 = D2->getCanonicalDecl();
01287   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
01288   return true;
01289 }
01290 
01291 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1, 
01292                                                             Decl *D2) {
01293   if (!::IsStructurallyEquivalent(*this, D1, D2))
01294     return false;
01295   
01296   return !Finish();
01297 }
01298 
01299 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1, 
01300                                                             QualType T2) {
01301   if (!::IsStructurallyEquivalent(*this, T1, T2))
01302     return false;
01303   
01304   return !Finish();
01305 }
01306 
01307 bool StructuralEquivalenceContext::Finish() {
01308   while (!DeclsToCheck.empty()) {
01309     // Check the next declaration.
01310     Decl *D1 = DeclsToCheck.front();
01311     DeclsToCheck.pop_front();
01312     
01313     Decl *D2 = TentativeEquivalences[D1];
01314     assert(D2 && "Unrecorded tentative equivalence?");
01315     
01316     bool Equivalent = true;
01317     
01318     // FIXME: Switch on all declaration kinds. For now, we're just going to
01319     // check the obvious ones.
01320     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
01321       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
01322         // Check for equivalent structure names.
01323         IdentifierInfo *Name1 = Record1->getIdentifier();
01324         if (!Name1 && Record1->getTypedefNameForAnonDecl())
01325           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
01326         IdentifierInfo *Name2 = Record2->getIdentifier();
01327         if (!Name2 && Record2->getTypedefNameForAnonDecl())
01328           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
01329         if (!::IsStructurallyEquivalent(Name1, Name2) ||
01330             !::IsStructurallyEquivalent(*this, Record1, Record2))
01331           Equivalent = false;
01332       } else {
01333         // Record/non-record mismatch.
01334         Equivalent = false;
01335       }
01336     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
01337       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
01338         // Check for equivalent enum names.
01339         IdentifierInfo *Name1 = Enum1->getIdentifier();
01340         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
01341           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
01342         IdentifierInfo *Name2 = Enum2->getIdentifier();
01343         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
01344           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
01345         if (!::IsStructurallyEquivalent(Name1, Name2) ||
01346             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
01347           Equivalent = false;
01348       } else {
01349         // Enum/non-enum mismatch
01350         Equivalent = false;
01351       }
01352     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
01353       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
01354         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
01355                                         Typedef2->getIdentifier()) ||
01356             !::IsStructurallyEquivalent(*this,
01357                                         Typedef1->getUnderlyingType(),
01358                                         Typedef2->getUnderlyingType()))
01359           Equivalent = false;
01360       } else {
01361         // Typedef/non-typedef mismatch.
01362         Equivalent = false;
01363       }
01364     } else if (ClassTemplateDecl *ClassTemplate1 
01365                                            = dyn_cast<ClassTemplateDecl>(D1)) {
01366       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
01367         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
01368                                         ClassTemplate2->getIdentifier()) ||
01369             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
01370           Equivalent = false;
01371       } else {
01372         // Class template/non-class-template mismatch.
01373         Equivalent = false;
01374       }
01375     } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
01376       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
01377         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
01378           Equivalent = false;
01379       } else {
01380         // Kind mismatch.
01381         Equivalent = false;
01382       }
01383     } else if (NonTypeTemplateParmDecl *NTTP1
01384                                      = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
01385       if (NonTypeTemplateParmDecl *NTTP2
01386                                       = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
01387         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
01388           Equivalent = false;
01389       } else {
01390         // Kind mismatch.
01391         Equivalent = false;
01392       }
01393     } else if (TemplateTemplateParmDecl *TTP1
01394                                   = dyn_cast<TemplateTemplateParmDecl>(D1)) {
01395       if (TemplateTemplateParmDecl *TTP2
01396                                     = dyn_cast<TemplateTemplateParmDecl>(D2)) {
01397         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
01398           Equivalent = false;
01399       } else {
01400         // Kind mismatch.
01401         Equivalent = false;
01402       }
01403     }
01404     
01405     if (!Equivalent) {
01406       // Note that these two declarations are not equivalent (and we already
01407       // know about it).
01408       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
01409                                                D2->getCanonicalDecl()));
01410       return true;
01411     }
01412     // FIXME: Check other declaration kinds!
01413   }
01414   
01415   return false;
01416 }
01417 
01418 //----------------------------------------------------------------------------
01419 // Import Types
01420 //----------------------------------------------------------------------------
01421 
01422 QualType ASTNodeImporter::VisitType(const Type *T) {
01423   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
01424     << T->getTypeClassName();
01425   return QualType();
01426 }
01427 
01428 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
01429   switch (T->getKind()) {
01430 #define SHARED_SINGLETON_TYPE(Expansion)
01431 #define BUILTIN_TYPE(Id, SingletonId) \
01432   case BuiltinType::Id: return Importer.getToContext().SingletonId;
01433 #include "clang/AST/BuiltinTypes.def"
01434 
01435   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
01436   // context supports C++.
01437 
01438   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
01439   // context supports ObjC.
01440 
01441   case BuiltinType::Char_U:
01442     // The context we're importing from has an unsigned 'char'. If we're 
01443     // importing into a context with a signed 'char', translate to 
01444     // 'unsigned char' instead.
01445     if (Importer.getToContext().getLangOpts().CharIsSigned)
01446       return Importer.getToContext().UnsignedCharTy;
01447     
01448     return Importer.getToContext().CharTy;
01449 
01450   case BuiltinType::Char_S:
01451     // The context we're importing from has an unsigned 'char'. If we're 
01452     // importing into a context with a signed 'char', translate to 
01453     // 'unsigned char' instead.
01454     if (!Importer.getToContext().getLangOpts().CharIsSigned)
01455       return Importer.getToContext().SignedCharTy;
01456     
01457     return Importer.getToContext().CharTy;
01458 
01459   case BuiltinType::WChar_S:
01460   case BuiltinType::WChar_U:
01461     // FIXME: If not in C++, shall we translate to the C equivalent of
01462     // wchar_t?
01463     return Importer.getToContext().WCharTy;
01464   }
01465 
01466   llvm_unreachable("Invalid BuiltinType Kind!");
01467 }
01468 
01469 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
01470   QualType ToElementType = Importer.Import(T->getElementType());
01471   if (ToElementType.isNull())
01472     return QualType();
01473   
01474   return Importer.getToContext().getComplexType(ToElementType);
01475 }
01476 
01477 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
01478   QualType ToPointeeType = Importer.Import(T->getPointeeType());
01479   if (ToPointeeType.isNull())
01480     return QualType();
01481   
01482   return Importer.getToContext().getPointerType(ToPointeeType);
01483 }
01484 
01485 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
01486   // FIXME: Check for blocks support in "to" context.
01487   QualType ToPointeeType = Importer.Import(T->getPointeeType());
01488   if (ToPointeeType.isNull())
01489     return QualType();
01490   
01491   return Importer.getToContext().getBlockPointerType(ToPointeeType);
01492 }
01493 
01494 QualType
01495 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
01496   // FIXME: Check for C++ support in "to" context.
01497   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
01498   if (ToPointeeType.isNull())
01499     return QualType();
01500   
01501   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
01502 }
01503 
01504 QualType
01505 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
01506   // FIXME: Check for C++0x support in "to" context.
01507   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
01508   if (ToPointeeType.isNull())
01509     return QualType();
01510   
01511   return Importer.getToContext().getRValueReferenceType(ToPointeeType);  
01512 }
01513 
01514 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
01515   // FIXME: Check for C++ support in "to" context.
01516   QualType ToPointeeType = Importer.Import(T->getPointeeType());
01517   if (ToPointeeType.isNull())
01518     return QualType();
01519   
01520   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
01521   return Importer.getToContext().getMemberPointerType(ToPointeeType, 
01522                                                       ClassType.getTypePtr());
01523 }
01524 
01525 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
01526   QualType ToElementType = Importer.Import(T->getElementType());
01527   if (ToElementType.isNull())
01528     return QualType();
01529   
01530   return Importer.getToContext().getConstantArrayType(ToElementType, 
01531                                                       T->getSize(),
01532                                                       T->getSizeModifier(),
01533                                                T->getIndexTypeCVRQualifiers());
01534 }
01535 
01536 QualType
01537 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
01538   QualType ToElementType = Importer.Import(T->getElementType());
01539   if (ToElementType.isNull())
01540     return QualType();
01541   
01542   return Importer.getToContext().getIncompleteArrayType(ToElementType, 
01543                                                         T->getSizeModifier(),
01544                                                 T->getIndexTypeCVRQualifiers());
01545 }
01546 
01547 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
01548   QualType ToElementType = Importer.Import(T->getElementType());
01549   if (ToElementType.isNull())
01550     return QualType();
01551 
01552   Expr *Size = Importer.Import(T->getSizeExpr());
01553   if (!Size)
01554     return QualType();
01555   
01556   SourceRange Brackets = Importer.Import(T->getBracketsRange());
01557   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
01558                                                       T->getSizeModifier(),
01559                                                 T->getIndexTypeCVRQualifiers(),
01560                                                       Brackets);
01561 }
01562 
01563 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
01564   QualType ToElementType = Importer.Import(T->getElementType());
01565   if (ToElementType.isNull())
01566     return QualType();
01567   
01568   return Importer.getToContext().getVectorType(ToElementType, 
01569                                                T->getNumElements(),
01570                                                T->getVectorKind());
01571 }
01572 
01573 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
01574   QualType ToElementType = Importer.Import(T->getElementType());
01575   if (ToElementType.isNull())
01576     return QualType();
01577   
01578   return Importer.getToContext().getExtVectorType(ToElementType, 
01579                                                   T->getNumElements());
01580 }
01581 
01582 QualType
01583 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
01584   // FIXME: What happens if we're importing a function without a prototype 
01585   // into C++? Should we make it variadic?
01586   QualType ToResultType = Importer.Import(T->getReturnType());
01587   if (ToResultType.isNull())
01588     return QualType();
01589 
01590   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
01591                                                         T->getExtInfo());
01592 }
01593 
01594 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
01595   QualType ToResultType = Importer.Import(T->getReturnType());
01596   if (ToResultType.isNull())
01597     return QualType();
01598   
01599   // Import argument types
01600   SmallVector<QualType, 4> ArgTypes;
01601   for (const auto &A : T->param_types()) {
01602     QualType ArgType = Importer.Import(A);
01603     if (ArgType.isNull())
01604       return QualType();
01605     ArgTypes.push_back(ArgType);
01606   }
01607   
01608   // Import exception types
01609   SmallVector<QualType, 4> ExceptionTypes;
01610   for (const auto &E : T->exceptions()) {
01611     QualType ExceptionType = Importer.Import(E);
01612     if (ExceptionType.isNull())
01613       return QualType();
01614     ExceptionTypes.push_back(ExceptionType);
01615   }
01616 
01617   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
01618   FunctionProtoType::ExtProtoInfo ToEPI;
01619 
01620   ToEPI.ExtInfo = FromEPI.ExtInfo;
01621   ToEPI.Variadic = FromEPI.Variadic;
01622   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
01623   ToEPI.TypeQuals = FromEPI.TypeQuals;
01624   ToEPI.RefQualifier = FromEPI.RefQualifier;
01625   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
01626   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
01627   ToEPI.ExceptionSpec.NoexceptExpr =
01628       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
01629   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
01630       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
01631   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
01632       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
01633 
01634   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
01635 }
01636 
01637 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
01638   QualType ToInnerType = Importer.Import(T->getInnerType());
01639   if (ToInnerType.isNull())
01640     return QualType();
01641     
01642   return Importer.getToContext().getParenType(ToInnerType);
01643 }
01644 
01645 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
01646   TypedefNameDecl *ToDecl
01647              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
01648   if (!ToDecl)
01649     return QualType();
01650   
01651   return Importer.getToContext().getTypeDeclType(ToDecl);
01652 }
01653 
01654 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
01655   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
01656   if (!ToExpr)
01657     return QualType();
01658   
01659   return Importer.getToContext().getTypeOfExprType(ToExpr);
01660 }
01661 
01662 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
01663   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
01664   if (ToUnderlyingType.isNull())
01665     return QualType();
01666   
01667   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
01668 }
01669 
01670 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
01671   // FIXME: Make sure that the "to" context supports C++0x!
01672   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
01673   if (!ToExpr)
01674     return QualType();
01675   
01676   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
01677   if (UnderlyingType.isNull())
01678     return QualType();
01679 
01680   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
01681 }
01682 
01683 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
01684   QualType ToBaseType = Importer.Import(T->getBaseType());
01685   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
01686   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
01687     return QualType();
01688 
01689   return Importer.getToContext().getUnaryTransformType(ToBaseType,
01690                                                        ToUnderlyingType,
01691                                                        T->getUTTKind());
01692 }
01693 
01694 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
01695   // FIXME: Make sure that the "to" context supports C++11!
01696   QualType FromDeduced = T->getDeducedType();
01697   QualType ToDeduced;
01698   if (!FromDeduced.isNull()) {
01699     ToDeduced = Importer.Import(FromDeduced);
01700     if (ToDeduced.isNull())
01701       return QualType();
01702   }
01703   
01704   return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(), 
01705                                              /*IsDependent*/false);
01706 }
01707 
01708 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
01709   RecordDecl *ToDecl
01710     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
01711   if (!ToDecl)
01712     return QualType();
01713 
01714   return Importer.getToContext().getTagDeclType(ToDecl);
01715 }
01716 
01717 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
01718   EnumDecl *ToDecl
01719     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
01720   if (!ToDecl)
01721     return QualType();
01722 
01723   return Importer.getToContext().getTagDeclType(ToDecl);
01724 }
01725 
01726 QualType ASTNodeImporter::VisitTemplateSpecializationType(
01727                                        const TemplateSpecializationType *T) {
01728   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
01729   if (ToTemplate.isNull())
01730     return QualType();
01731   
01732   SmallVector<TemplateArgument, 2> ToTemplateArgs;
01733   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
01734     return QualType();
01735   
01736   QualType ToCanonType;
01737   if (!QualType(T, 0).isCanonical()) {
01738     QualType FromCanonType 
01739       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
01740     ToCanonType =Importer.Import(FromCanonType);
01741     if (ToCanonType.isNull())
01742       return QualType();
01743   }
01744   return Importer.getToContext().getTemplateSpecializationType(ToTemplate, 
01745                                                          ToTemplateArgs.data(), 
01746                                                          ToTemplateArgs.size(),
01747                                                                ToCanonType);
01748 }
01749 
01750 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
01751   NestedNameSpecifier *ToQualifier = nullptr;
01752   // Note: the qualifier in an ElaboratedType is optional.
01753   if (T->getQualifier()) {
01754     ToQualifier = Importer.Import(T->getQualifier());
01755     if (!ToQualifier)
01756       return QualType();
01757   }
01758 
01759   QualType ToNamedType = Importer.Import(T->getNamedType());
01760   if (ToNamedType.isNull())
01761     return QualType();
01762 
01763   return Importer.getToContext().getElaboratedType(T->getKeyword(),
01764                                                    ToQualifier, ToNamedType);
01765 }
01766 
01767 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
01768   ObjCInterfaceDecl *Class
01769     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
01770   if (!Class)
01771     return QualType();
01772 
01773   return Importer.getToContext().getObjCInterfaceType(Class);
01774 }
01775 
01776 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
01777   QualType ToBaseType = Importer.Import(T->getBaseType());
01778   if (ToBaseType.isNull())
01779     return QualType();
01780 
01781   SmallVector<ObjCProtocolDecl *, 4> Protocols;
01782   for (auto *P : T->quals()) {
01783     ObjCProtocolDecl *Protocol
01784       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
01785     if (!Protocol)
01786       return QualType();
01787     Protocols.push_back(Protocol);
01788   }
01789 
01790   return Importer.getToContext().getObjCObjectType(ToBaseType,
01791                                                    Protocols.data(),
01792                                                    Protocols.size());
01793 }
01794 
01795 QualType
01796 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
01797   QualType ToPointeeType = Importer.Import(T->getPointeeType());
01798   if (ToPointeeType.isNull())
01799     return QualType();
01800 
01801   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
01802 }
01803 
01804 //----------------------------------------------------------------------------
01805 // Import Declarations
01806 //----------------------------------------------------------------------------
01807 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC, 
01808                                       DeclContext *&LexicalDC, 
01809                                       DeclarationName &Name, 
01810                                       SourceLocation &Loc) {
01811   // Import the context of this declaration.
01812   DC = Importer.ImportContext(D->getDeclContext());
01813   if (!DC)
01814     return true;
01815   
01816   LexicalDC = DC;
01817   if (D->getDeclContext() != D->getLexicalDeclContext()) {
01818     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
01819     if (!LexicalDC)
01820       return true;
01821   }
01822   
01823   // Import the name of this declaration.
01824   Name = Importer.Import(D->getDeclName());
01825   if (D->getDeclName() && !Name)
01826     return true;
01827   
01828   // Import the location of this declaration.
01829   Loc = Importer.Import(D->getLocation());
01830   return false;
01831 }
01832 
01833 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
01834   if (!FromD)
01835     return;
01836   
01837   if (!ToD) {
01838     ToD = Importer.Import(FromD);
01839     if (!ToD)
01840       return;
01841   }
01842   
01843   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
01844     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
01845       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
01846         ImportDefinition(FromRecord, ToRecord);
01847       }
01848     }
01849     return;
01850   }
01851 
01852   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
01853     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
01854       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
01855         ImportDefinition(FromEnum, ToEnum);
01856       }
01857     }
01858     return;
01859   }
01860 }
01861 
01862 void
01863 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
01864                                           DeclarationNameInfo& To) {
01865   // NOTE: To.Name and To.Loc are already imported.
01866   // We only have to import To.LocInfo.
01867   switch (To.getName().getNameKind()) {
01868   case DeclarationName::Identifier:
01869   case DeclarationName::ObjCZeroArgSelector:
01870   case DeclarationName::ObjCOneArgSelector:
01871   case DeclarationName::ObjCMultiArgSelector:
01872   case DeclarationName::CXXUsingDirective:
01873     return;
01874 
01875   case DeclarationName::CXXOperatorName: {
01876     SourceRange Range = From.getCXXOperatorNameRange();
01877     To.setCXXOperatorNameRange(Importer.Import(Range));
01878     return;
01879   }
01880   case DeclarationName::CXXLiteralOperatorName: {
01881     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
01882     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
01883     return;
01884   }
01885   case DeclarationName::CXXConstructorName:
01886   case DeclarationName::CXXDestructorName:
01887   case DeclarationName::CXXConversionFunctionName: {
01888     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
01889     To.setNamedTypeInfo(Importer.Import(FromTInfo));
01890     return;
01891   }
01892   }
01893   llvm_unreachable("Unknown name kind.");
01894 }
01895 
01896 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {  
01897   if (Importer.isMinimalImport() && !ForceImport) {
01898     Importer.ImportContext(FromDC);
01899     return;
01900   }
01901   
01902   for (auto *From : FromDC->decls())
01903     Importer.Import(From);
01904 }
01905 
01906 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To, 
01907                                        ImportDefinitionKind Kind) {
01908   if (To->getDefinition() || To->isBeingDefined()) {
01909     if (Kind == IDK_Everything)
01910       ImportDeclContext(From, /*ForceImport=*/true);
01911     
01912     return false;
01913   }
01914   
01915   To->startDefinition();
01916   
01917   // Add base classes.
01918   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
01919     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
01920 
01921     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
01922     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
01923     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
01924     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
01925     ToData.Aggregate = FromData.Aggregate;
01926     ToData.PlainOldData = FromData.PlainOldData;
01927     ToData.Empty = FromData.Empty;
01928     ToData.Polymorphic = FromData.Polymorphic;
01929     ToData.Abstract = FromData.Abstract;
01930     ToData.IsStandardLayout = FromData.IsStandardLayout;
01931     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
01932     ToData.HasPrivateFields = FromData.HasPrivateFields;
01933     ToData.HasProtectedFields = FromData.HasProtectedFields;
01934     ToData.HasPublicFields = FromData.HasPublicFields;
01935     ToData.HasMutableFields = FromData.HasMutableFields;
01936     ToData.HasVariantMembers = FromData.HasVariantMembers;
01937     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
01938     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
01939     ToData.HasUninitializedReferenceMember
01940       = FromData.HasUninitializedReferenceMember;
01941     ToData.NeedOverloadResolutionForMoveConstructor
01942       = FromData.NeedOverloadResolutionForMoveConstructor;
01943     ToData.NeedOverloadResolutionForMoveAssignment
01944       = FromData.NeedOverloadResolutionForMoveAssignment;
01945     ToData.NeedOverloadResolutionForDestructor
01946       = FromData.NeedOverloadResolutionForDestructor;
01947     ToData.DefaultedMoveConstructorIsDeleted
01948       = FromData.DefaultedMoveConstructorIsDeleted;
01949     ToData.DefaultedMoveAssignmentIsDeleted
01950       = FromData.DefaultedMoveAssignmentIsDeleted;
01951     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
01952     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
01953     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
01954     ToData.HasConstexprNonCopyMoveConstructor
01955       = FromData.HasConstexprNonCopyMoveConstructor;
01956     ToData.DefaultedDefaultConstructorIsConstexpr
01957       = FromData.DefaultedDefaultConstructorIsConstexpr;
01958     ToData.HasConstexprDefaultConstructor
01959       = FromData.HasConstexprDefaultConstructor;
01960     ToData.HasNonLiteralTypeFieldsOrBases
01961       = FromData.HasNonLiteralTypeFieldsOrBases;
01962     // ComputedVisibleConversions not imported.
01963     ToData.UserProvidedDefaultConstructor
01964       = FromData.UserProvidedDefaultConstructor;
01965     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
01966     ToData.ImplicitCopyConstructorHasConstParam
01967       = FromData.ImplicitCopyConstructorHasConstParam;
01968     ToData.ImplicitCopyAssignmentHasConstParam
01969       = FromData.ImplicitCopyAssignmentHasConstParam;
01970     ToData.HasDeclaredCopyConstructorWithConstParam
01971       = FromData.HasDeclaredCopyConstructorWithConstParam;
01972     ToData.HasDeclaredCopyAssignmentWithConstParam
01973       = FromData.HasDeclaredCopyAssignmentWithConstParam;
01974     ToData.IsLambda = FromData.IsLambda;
01975 
01976     SmallVector<CXXBaseSpecifier *, 4> Bases;
01977     for (const auto &Base1 : FromCXX->bases()) {
01978       QualType T = Importer.Import(Base1.getType());
01979       if (T.isNull())
01980         return true;
01981 
01982       SourceLocation EllipsisLoc;
01983       if (Base1.isPackExpansion())
01984         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
01985 
01986       // Ensure that we have a definition for the base.
01987       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
01988         
01989       Bases.push_back(
01990                     new (Importer.getToContext()) 
01991                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
01992                                        Base1.isVirtual(),
01993                                        Base1.isBaseOfClass(),
01994                                        Base1.getAccessSpecifierAsWritten(),
01995                                    Importer.Import(Base1.getTypeSourceInfo()),
01996                                        EllipsisLoc));
01997     }
01998     if (!Bases.empty())
01999       ToCXX->setBases(Bases.data(), Bases.size());
02000   }
02001   
02002   if (shouldForceImportDeclContext(Kind))
02003     ImportDeclContext(From, /*ForceImport=*/true);
02004   
02005   To->completeDefinition();
02006   return false;
02007 }
02008 
02009 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
02010                                        ImportDefinitionKind Kind) {
02011   if (To->getDefinition())
02012     return false;
02013 
02014   // FIXME: Can we really import any initializer? Alternatively, we could force
02015   // ourselves to import every declaration of a variable and then only use
02016   // getInit() here.
02017   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
02018 
02019   // FIXME: Other bits to merge?
02020 
02021   return false;
02022 }
02023 
02024 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To, 
02025                                        ImportDefinitionKind Kind) {
02026   if (To->getDefinition() || To->isBeingDefined()) {
02027     if (Kind == IDK_Everything)
02028       ImportDeclContext(From, /*ForceImport=*/true);
02029     return false;
02030   }
02031   
02032   To->startDefinition();
02033 
02034   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
02035   if (T.isNull())
02036     return true;
02037   
02038   QualType ToPromotionType = Importer.Import(From->getPromotionType());
02039   if (ToPromotionType.isNull())
02040     return true;
02041 
02042   if (shouldForceImportDeclContext(Kind))
02043     ImportDeclContext(From, /*ForceImport=*/true);
02044   
02045   // FIXME: we might need to merge the number of positive or negative bits
02046   // if the enumerator lists don't match.
02047   To->completeDefinition(T, ToPromotionType,
02048                          From->getNumPositiveBits(),
02049                          From->getNumNegativeBits());
02050   return false;
02051 }
02052 
02053 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
02054                                                 TemplateParameterList *Params) {
02055   SmallVector<NamedDecl *, 4> ToParams;
02056   ToParams.reserve(Params->size());
02057   for (TemplateParameterList::iterator P = Params->begin(), 
02058                                     PEnd = Params->end();
02059        P != PEnd; ++P) {
02060     Decl *To = Importer.Import(*P);
02061     if (!To)
02062       return nullptr;
02063 
02064     ToParams.push_back(cast<NamedDecl>(To));
02065   }
02066   
02067   return TemplateParameterList::Create(Importer.getToContext(),
02068                                        Importer.Import(Params->getTemplateLoc()),
02069                                        Importer.Import(Params->getLAngleLoc()),
02070                                        ToParams.data(), ToParams.size(),
02071                                        Importer.Import(Params->getRAngleLoc()));
02072 }
02073 
02074 TemplateArgument 
02075 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
02076   switch (From.getKind()) {
02077   case TemplateArgument::Null:
02078     return TemplateArgument();
02079      
02080   case TemplateArgument::Type: {
02081     QualType ToType = Importer.Import(From.getAsType());
02082     if (ToType.isNull())
02083       return TemplateArgument();
02084     return TemplateArgument(ToType);
02085   }
02086       
02087   case TemplateArgument::Integral: {
02088     QualType ToType = Importer.Import(From.getIntegralType());
02089     if (ToType.isNull())
02090       return TemplateArgument();
02091     return TemplateArgument(From, ToType);
02092   }
02093 
02094   case TemplateArgument::Declaration: {
02095     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
02096     QualType ToType = Importer.Import(From.getParamTypeForDecl());
02097     if (!To || ToType.isNull())
02098       return TemplateArgument();
02099     return TemplateArgument(To, ToType);
02100   }
02101 
02102   case TemplateArgument::NullPtr: {
02103     QualType ToType = Importer.Import(From.getNullPtrType());
02104     if (ToType.isNull())
02105       return TemplateArgument();
02106     return TemplateArgument(ToType, /*isNullPtr*/true);
02107   }
02108 
02109   case TemplateArgument::Template: {
02110     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
02111     if (ToTemplate.isNull())
02112       return TemplateArgument();
02113     
02114     return TemplateArgument(ToTemplate);
02115   }
02116 
02117   case TemplateArgument::TemplateExpansion: {
02118     TemplateName ToTemplate 
02119       = Importer.Import(From.getAsTemplateOrTemplatePattern());
02120     if (ToTemplate.isNull())
02121       return TemplateArgument();
02122     
02123     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
02124   }
02125 
02126   case TemplateArgument::Expression:
02127     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
02128       return TemplateArgument(ToExpr);
02129     return TemplateArgument();
02130       
02131   case TemplateArgument::Pack: {
02132     SmallVector<TemplateArgument, 2> ToPack;
02133     ToPack.reserve(From.pack_size());
02134     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
02135       return TemplateArgument();
02136     
02137     TemplateArgument *ToArgs 
02138       = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
02139     std::copy(ToPack.begin(), ToPack.end(), ToArgs);
02140     return TemplateArgument(ToArgs, ToPack.size());
02141   }
02142   }
02143   
02144   llvm_unreachable("Invalid template argument kind");
02145 }
02146 
02147 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
02148                                               unsigned NumFromArgs,
02149                               SmallVectorImpl<TemplateArgument> &ToArgs) {
02150   for (unsigned I = 0; I != NumFromArgs; ++I) {
02151     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
02152     if (To.isNull() && !FromArgs[I].isNull())
02153       return true;
02154     
02155     ToArgs.push_back(To);
02156   }
02157   
02158   return false;
02159 }
02160 
02161 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, 
02162                                         RecordDecl *ToRecord, bool Complain) {
02163   // Eliminate a potential failure point where we attempt to re-import
02164   // something we're trying to import while completing ToRecord.
02165   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
02166   if (ToOrigin) {
02167     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
02168     if (ToOriginRecord)
02169       ToRecord = ToOriginRecord;
02170   }
02171 
02172   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
02173                                    ToRecord->getASTContext(),
02174                                    Importer.getNonEquivalentDecls(),
02175                                    false, Complain);
02176   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
02177 }
02178 
02179 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
02180                                         bool Complain) {
02181   StructuralEquivalenceContext Ctx(
02182       Importer.getFromContext(), Importer.getToContext(),
02183       Importer.getNonEquivalentDecls(), false, Complain);
02184   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
02185 }
02186 
02187 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
02188   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
02189                                    Importer.getToContext(),
02190                                    Importer.getNonEquivalentDecls());
02191   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
02192 }
02193 
02194 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
02195                                         EnumConstantDecl *ToEC)
02196 {
02197   const llvm::APSInt &FromVal = FromEC->getInitVal();
02198   const llvm::APSInt &ToVal = ToEC->getInitVal();
02199 
02200   return FromVal.isSigned() == ToVal.isSigned() &&
02201          FromVal.getBitWidth() == ToVal.getBitWidth() &&
02202          FromVal == ToVal;
02203 }
02204 
02205 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
02206                                         ClassTemplateDecl *To) {
02207   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
02208                                    Importer.getToContext(),
02209                                    Importer.getNonEquivalentDecls());
02210   return Ctx.IsStructurallyEquivalent(From, To);  
02211 }
02212 
02213 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
02214                                         VarTemplateDecl *To) {
02215   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
02216                                    Importer.getToContext(),
02217                                    Importer.getNonEquivalentDecls());
02218   return Ctx.IsStructurallyEquivalent(From, To);
02219 }
02220 
02221 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
02222   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
02223     << D->getDeclKindName();
02224   return nullptr;
02225 }
02226 
02227 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
02228   TranslationUnitDecl *ToD = 
02229     Importer.getToContext().getTranslationUnitDecl();
02230     
02231   Importer.Imported(D, ToD);
02232     
02233   return ToD;
02234 }
02235 
02236 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
02237   // Import the major distinguishing characteristics of this namespace.
02238   DeclContext *DC, *LexicalDC;
02239   DeclarationName Name;
02240   SourceLocation Loc;
02241   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02242     return nullptr;
02243 
02244   NamespaceDecl *MergeWithNamespace = nullptr;
02245   if (!Name) {
02246     // This is an anonymous namespace. Adopt an existing anonymous
02247     // namespace if we can.
02248     // FIXME: Not testable.
02249     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
02250       MergeWithNamespace = TU->getAnonymousNamespace();
02251     else
02252       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
02253   } else {
02254     SmallVector<NamedDecl *, 4> ConflictingDecls;
02255     SmallVector<NamedDecl *, 2> FoundDecls;
02256     DC->localUncachedLookup(Name, FoundDecls);
02257     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02258       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
02259         continue;
02260       
02261       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
02262         MergeWithNamespace = FoundNS;
02263         ConflictingDecls.clear();
02264         break;
02265       }
02266       
02267       ConflictingDecls.push_back(FoundDecls[I]);
02268     }
02269     
02270     if (!ConflictingDecls.empty()) {
02271       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
02272                                          ConflictingDecls.data(), 
02273                                          ConflictingDecls.size());
02274     }
02275   }
02276   
02277   // Create the "to" namespace, if needed.
02278   NamespaceDecl *ToNamespace = MergeWithNamespace;
02279   if (!ToNamespace) {
02280     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
02281                                         D->isInline(),
02282                                         Importer.Import(D->getLocStart()),
02283                                         Loc, Name.getAsIdentifierInfo(),
02284                                         /*PrevDecl=*/nullptr);
02285     ToNamespace->setLexicalDeclContext(LexicalDC);
02286     LexicalDC->addDeclInternal(ToNamespace);
02287     
02288     // If this is an anonymous namespace, register it as the anonymous
02289     // namespace within its context.
02290     if (!Name) {
02291       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
02292         TU->setAnonymousNamespace(ToNamespace);
02293       else
02294         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
02295     }
02296   }
02297   Importer.Imported(D, ToNamespace);
02298   
02299   ImportDeclContext(D);
02300   
02301   return ToNamespace;
02302 }
02303 
02304 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
02305   // Import the major distinguishing characteristics of this typedef.
02306   DeclContext *DC, *LexicalDC;
02307   DeclarationName Name;
02308   SourceLocation Loc;
02309   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02310     return nullptr;
02311 
02312   // If this typedef is not in block scope, determine whether we've
02313   // seen a typedef with the same name (that we can merge with) or any
02314   // other entity by that name (which name lookup could conflict with).
02315   if (!DC->isFunctionOrMethod()) {
02316     SmallVector<NamedDecl *, 4> ConflictingDecls;
02317     unsigned IDNS = Decl::IDNS_Ordinary;
02318     SmallVector<NamedDecl *, 2> FoundDecls;
02319     DC->localUncachedLookup(Name, FoundDecls);
02320     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02321       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
02322         continue;
02323       if (TypedefNameDecl *FoundTypedef =
02324             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
02325         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
02326                                             FoundTypedef->getUnderlyingType()))
02327           return Importer.Imported(D, FoundTypedef);
02328       }
02329       
02330       ConflictingDecls.push_back(FoundDecls[I]);
02331     }
02332     
02333     if (!ConflictingDecls.empty()) {
02334       Name = Importer.HandleNameConflict(Name, DC, IDNS,
02335                                          ConflictingDecls.data(), 
02336                                          ConflictingDecls.size());
02337       if (!Name)
02338         return nullptr;
02339     }
02340   }
02341   
02342   // Import the underlying type of this typedef;
02343   QualType T = Importer.Import(D->getUnderlyingType());
02344   if (T.isNull())
02345     return nullptr;
02346 
02347   // Create the new typedef node.
02348   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
02349   SourceLocation StartL = Importer.Import(D->getLocStart());
02350   TypedefNameDecl *ToTypedef;
02351   if (IsAlias)
02352     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
02353                                       StartL, Loc,
02354                                       Name.getAsIdentifierInfo(),
02355                                       TInfo);
02356   else
02357     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
02358                                     StartL, Loc,
02359                                     Name.getAsIdentifierInfo(),
02360                                     TInfo);
02361   
02362   ToTypedef->setAccess(D->getAccess());
02363   ToTypedef->setLexicalDeclContext(LexicalDC);
02364   Importer.Imported(D, ToTypedef);
02365   LexicalDC->addDeclInternal(ToTypedef);
02366   
02367   return ToTypedef;
02368 }
02369 
02370 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
02371   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
02372 }
02373 
02374 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
02375   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
02376 }
02377 
02378 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
02379   // Import the major distinguishing characteristics of this enum.
02380   DeclContext *DC, *LexicalDC;
02381   DeclarationName Name;
02382   SourceLocation Loc;
02383   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02384     return nullptr;
02385 
02386   // Figure out what enum name we're looking for.
02387   unsigned IDNS = Decl::IDNS_Tag;
02388   DeclarationName SearchName = Name;
02389   if (!SearchName && D->getTypedefNameForAnonDecl()) {
02390     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
02391     IDNS = Decl::IDNS_Ordinary;
02392   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
02393     IDNS |= Decl::IDNS_Ordinary;
02394   
02395   // We may already have an enum of the same name; try to find and match it.
02396   if (!DC->isFunctionOrMethod() && SearchName) {
02397     SmallVector<NamedDecl *, 4> ConflictingDecls;
02398     SmallVector<NamedDecl *, 2> FoundDecls;
02399     DC->localUncachedLookup(SearchName, FoundDecls);
02400     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02401       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
02402         continue;
02403       
02404       Decl *Found = FoundDecls[I];
02405       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
02406         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
02407           Found = Tag->getDecl();
02408       }
02409       
02410       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
02411         if (IsStructuralMatch(D, FoundEnum))
02412           return Importer.Imported(D, FoundEnum);
02413       }
02414       
02415       ConflictingDecls.push_back(FoundDecls[I]);
02416     }
02417     
02418     if (!ConflictingDecls.empty()) {
02419       Name = Importer.HandleNameConflict(Name, DC, IDNS,
02420                                          ConflictingDecls.data(), 
02421                                          ConflictingDecls.size());
02422     }
02423   }
02424   
02425   // Create the enum declaration.
02426   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
02427                                   Importer.Import(D->getLocStart()),
02428                                   Loc, Name.getAsIdentifierInfo(), nullptr,
02429                                   D->isScoped(), D->isScopedUsingClassTag(),
02430                                   D->isFixed());
02431   // Import the qualifier, if any.
02432   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
02433   D2->setAccess(D->getAccess());
02434   D2->setLexicalDeclContext(LexicalDC);
02435   Importer.Imported(D, D2);
02436   LexicalDC->addDeclInternal(D2);
02437 
02438   // Import the integer type.
02439   QualType ToIntegerType = Importer.Import(D->getIntegerType());
02440   if (ToIntegerType.isNull())
02441     return nullptr;
02442   D2->setIntegerType(ToIntegerType);
02443   
02444   // Import the definition
02445   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
02446     return nullptr;
02447 
02448   return D2;
02449 }
02450 
02451 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
02452   // If this record has a definition in the translation unit we're coming from,
02453   // but this particular declaration is not that definition, import the
02454   // definition and map to that.
02455   TagDecl *Definition = D->getDefinition();
02456   if (Definition && Definition != D) {
02457     Decl *ImportedDef = Importer.Import(Definition);
02458     if (!ImportedDef)
02459       return nullptr;
02460 
02461     return Importer.Imported(D, ImportedDef);
02462   }
02463   
02464   // Import the major distinguishing characteristics of this record.
02465   DeclContext *DC, *LexicalDC;
02466   DeclarationName Name;
02467   SourceLocation Loc;
02468   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02469     return nullptr;
02470 
02471   // Figure out what structure name we're looking for.
02472   unsigned IDNS = Decl::IDNS_Tag;
02473   DeclarationName SearchName = Name;
02474   if (!SearchName && D->getTypedefNameForAnonDecl()) {
02475     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
02476     IDNS = Decl::IDNS_Ordinary;
02477   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
02478     IDNS |= Decl::IDNS_Ordinary;
02479 
02480   // We may already have a record of the same name; try to find and match it.
02481   RecordDecl *AdoptDecl = nullptr;
02482   if (!DC->isFunctionOrMethod()) {
02483     SmallVector<NamedDecl *, 4> ConflictingDecls;
02484     SmallVector<NamedDecl *, 2> FoundDecls;
02485     DC->localUncachedLookup(SearchName, FoundDecls);
02486     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02487       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
02488         continue;
02489       
02490       Decl *Found = FoundDecls[I];
02491       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
02492         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
02493           Found = Tag->getDecl();
02494       }
02495       
02496       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
02497         if (D->isAnonymousStructOrUnion() && 
02498             FoundRecord->isAnonymousStructOrUnion()) {
02499           // If both anonymous structs/unions are in a record context, make sure
02500           // they occur in the same location in the context records.
02501           if (Optional<unsigned> Index1
02502               = findAnonymousStructOrUnionIndex(D)) {
02503             if (Optional<unsigned> Index2 =
02504                     findAnonymousStructOrUnionIndex(FoundRecord)) {
02505               if (*Index1 != *Index2)
02506                 continue;
02507             }
02508           }
02509         }
02510 
02511         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
02512           if ((SearchName && !D->isCompleteDefinition())
02513               || (D->isCompleteDefinition() &&
02514                   D->isAnonymousStructOrUnion()
02515                     == FoundDef->isAnonymousStructOrUnion() &&
02516                   IsStructuralMatch(D, FoundDef))) {
02517             // The record types structurally match, or the "from" translation
02518             // unit only had a forward declaration anyway; call it the same
02519             // function.
02520             // FIXME: For C++, we should also merge methods here.
02521             return Importer.Imported(D, FoundDef);
02522           }
02523         } else if (!D->isCompleteDefinition()) {
02524           // We have a forward declaration of this type, so adopt that forward
02525           // declaration rather than building a new one.
02526             
02527           // If one or both can be completed from external storage then try one
02528           // last time to complete and compare them before doing this.
02529             
02530           if (FoundRecord->hasExternalLexicalStorage() &&
02531               !FoundRecord->isCompleteDefinition())
02532             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
02533           if (D->hasExternalLexicalStorage())
02534             D->getASTContext().getExternalSource()->CompleteType(D);
02535             
02536           if (FoundRecord->isCompleteDefinition() &&
02537               D->isCompleteDefinition() &&
02538               !IsStructuralMatch(D, FoundRecord))
02539             continue;
02540               
02541           AdoptDecl = FoundRecord;
02542           continue;
02543         } else if (!SearchName) {
02544           continue;
02545         }
02546       }
02547       
02548       ConflictingDecls.push_back(FoundDecls[I]);
02549     }
02550     
02551     if (!ConflictingDecls.empty() && SearchName) {
02552       Name = Importer.HandleNameConflict(Name, DC, IDNS,
02553                                          ConflictingDecls.data(), 
02554                                          ConflictingDecls.size());
02555     }
02556   }
02557   
02558   // Create the record declaration.
02559   RecordDecl *D2 = AdoptDecl;
02560   SourceLocation StartLoc = Importer.Import(D->getLocStart());
02561   if (!D2) {
02562     if (isa<CXXRecordDecl>(D)) {
02563       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(), 
02564                                                    D->getTagKind(),
02565                                                    DC, StartLoc, Loc,
02566                                                    Name.getAsIdentifierInfo());
02567       D2 = D2CXX;
02568       D2->setAccess(D->getAccess());
02569     } else {
02570       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
02571                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
02572     }
02573     
02574     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
02575     D2->setLexicalDeclContext(LexicalDC);
02576     LexicalDC->addDeclInternal(D2);
02577     if (D->isAnonymousStructOrUnion())
02578       D2->setAnonymousStructOrUnion(true);
02579   }
02580   
02581   Importer.Imported(D, D2);
02582 
02583   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
02584     return nullptr;
02585 
02586   return D2;
02587 }
02588 
02589 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
02590   // Import the major distinguishing characteristics of this enumerator.
02591   DeclContext *DC, *LexicalDC;
02592   DeclarationName Name;
02593   SourceLocation Loc;
02594   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02595     return nullptr;
02596 
02597   QualType T = Importer.Import(D->getType());
02598   if (T.isNull())
02599     return nullptr;
02600 
02601   // Determine whether there are any other declarations with the same name and 
02602   // in the same context.
02603   if (!LexicalDC->isFunctionOrMethod()) {
02604     SmallVector<NamedDecl *, 4> ConflictingDecls;
02605     unsigned IDNS = Decl::IDNS_Ordinary;
02606     SmallVector<NamedDecl *, 2> FoundDecls;
02607     DC->localUncachedLookup(Name, FoundDecls);
02608     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02609       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
02610         continue;
02611 
02612       if (EnumConstantDecl *FoundEnumConstant
02613             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
02614         if (IsStructuralMatch(D, FoundEnumConstant))
02615           return Importer.Imported(D, FoundEnumConstant);
02616       }
02617 
02618       ConflictingDecls.push_back(FoundDecls[I]);
02619     }
02620     
02621     if (!ConflictingDecls.empty()) {
02622       Name = Importer.HandleNameConflict(Name, DC, IDNS,
02623                                          ConflictingDecls.data(), 
02624                                          ConflictingDecls.size());
02625       if (!Name)
02626         return nullptr;
02627     }
02628   }
02629   
02630   Expr *Init = Importer.Import(D->getInitExpr());
02631   if (D->getInitExpr() && !Init)
02632     return nullptr;
02633 
02634   EnumConstantDecl *ToEnumerator
02635     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc, 
02636                                Name.getAsIdentifierInfo(), T, 
02637                                Init, D->getInitVal());
02638   ToEnumerator->setAccess(D->getAccess());
02639   ToEnumerator->setLexicalDeclContext(LexicalDC);
02640   Importer.Imported(D, ToEnumerator);
02641   LexicalDC->addDeclInternal(ToEnumerator);
02642   return ToEnumerator;
02643 }
02644 
02645 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
02646   // Import the major distinguishing characteristics of this function.
02647   DeclContext *DC, *LexicalDC;
02648   DeclarationName Name;
02649   SourceLocation Loc;
02650   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02651     return nullptr;
02652 
02653   // Try to find a function in our own ("to") context with the same name, same
02654   // type, and in the same context as the function we're importing.
02655   if (!LexicalDC->isFunctionOrMethod()) {
02656     SmallVector<NamedDecl *, 4> ConflictingDecls;
02657     unsigned IDNS = Decl::IDNS_Ordinary;
02658     SmallVector<NamedDecl *, 2> FoundDecls;
02659     DC->localUncachedLookup(Name, FoundDecls);
02660     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02661       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
02662         continue;
02663     
02664       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
02665         if (FoundFunction->hasExternalFormalLinkage() &&
02666             D->hasExternalFormalLinkage()) {
02667           if (Importer.IsStructurallyEquivalent(D->getType(), 
02668                                                 FoundFunction->getType())) {
02669             // FIXME: Actually try to merge the body and other attributes.
02670             return Importer.Imported(D, FoundFunction);
02671           }
02672         
02673           // FIXME: Check for overloading more carefully, e.g., by boosting
02674           // Sema::IsOverload out to the AST library.
02675           
02676           // Function overloading is okay in C++.
02677           if (Importer.getToContext().getLangOpts().CPlusPlus)
02678             continue;
02679           
02680           // Complain about inconsistent function types.
02681           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
02682             << Name << D->getType() << FoundFunction->getType();
02683           Importer.ToDiag(FoundFunction->getLocation(), 
02684                           diag::note_odr_value_here)
02685             << FoundFunction->getType();
02686         }
02687       }
02688       
02689       ConflictingDecls.push_back(FoundDecls[I]);
02690     }
02691     
02692     if (!ConflictingDecls.empty()) {
02693       Name = Importer.HandleNameConflict(Name, DC, IDNS,
02694                                          ConflictingDecls.data(), 
02695                                          ConflictingDecls.size());
02696       if (!Name)
02697         return nullptr;
02698     }    
02699   }
02700 
02701   DeclarationNameInfo NameInfo(Name, Loc);
02702   // Import additional name location/type info.
02703   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
02704 
02705   QualType FromTy = D->getType();
02706   bool usedDifferentExceptionSpec = false;
02707 
02708   if (const FunctionProtoType *
02709         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
02710     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
02711     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
02712     // FunctionDecl that we are importing the FunctionProtoType for.
02713     // To avoid an infinite recursion when importing, create the FunctionDecl
02714     // with a simplified function type and update it afterwards.
02715     if (FromEPI.ExceptionSpec.SourceDecl ||
02716         FromEPI.ExceptionSpec.SourceTemplate ||
02717         FromEPI.ExceptionSpec.NoexceptExpr) {
02718       FunctionProtoType::ExtProtoInfo DefaultEPI;
02719       FromTy = Importer.getFromContext().getFunctionType(
02720           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
02721       usedDifferentExceptionSpec = true;
02722     }
02723   }
02724 
02725   // Import the type.
02726   QualType T = Importer.Import(FromTy);
02727   if (T.isNull())
02728     return nullptr;
02729 
02730   // Import the function parameters.
02731   SmallVector<ParmVarDecl *, 8> Parameters;
02732   for (auto P : D->params()) {
02733     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
02734     if (!ToP)
02735       return nullptr;
02736 
02737     Parameters.push_back(ToP);
02738   }
02739   
02740   // Create the imported function.
02741   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
02742   FunctionDecl *ToFunction = nullptr;
02743   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
02744     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
02745                                             cast<CXXRecordDecl>(DC),
02746                                             D->getInnerLocStart(),
02747                                             NameInfo, T, TInfo, 
02748                                             FromConstructor->isExplicit(),
02749                                             D->isInlineSpecified(), 
02750                                             D->isImplicit(),
02751                                             D->isConstexpr());
02752   } else if (isa<CXXDestructorDecl>(D)) {
02753     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
02754                                            cast<CXXRecordDecl>(DC),
02755                                            D->getInnerLocStart(),
02756                                            NameInfo, T, TInfo,
02757                                            D->isInlineSpecified(),
02758                                            D->isImplicit());
02759   } else if (CXXConversionDecl *FromConversion
02760                                            = dyn_cast<CXXConversionDecl>(D)) {
02761     ToFunction = CXXConversionDecl::Create(Importer.getToContext(), 
02762                                            cast<CXXRecordDecl>(DC),
02763                                            D->getInnerLocStart(),
02764                                            NameInfo, T, TInfo,
02765                                            D->isInlineSpecified(),
02766                                            FromConversion->isExplicit(),
02767                                            D->isConstexpr(),
02768                                            Importer.Import(D->getLocEnd()));
02769   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
02770     ToFunction = CXXMethodDecl::Create(Importer.getToContext(), 
02771                                        cast<CXXRecordDecl>(DC),
02772                                        D->getInnerLocStart(),
02773                                        NameInfo, T, TInfo,
02774                                        Method->getStorageClass(),
02775                                        Method->isInlineSpecified(),
02776                                        D->isConstexpr(),
02777                                        Importer.Import(D->getLocEnd()));
02778   } else {
02779     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
02780                                       D->getInnerLocStart(),
02781                                       NameInfo, T, TInfo, D->getStorageClass(),
02782                                       D->isInlineSpecified(),
02783                                       D->hasWrittenPrototype(),
02784                                       D->isConstexpr());
02785   }
02786 
02787   // Import the qualifier, if any.
02788   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
02789   ToFunction->setAccess(D->getAccess());
02790   ToFunction->setLexicalDeclContext(LexicalDC);
02791   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
02792   ToFunction->setTrivial(D->isTrivial());
02793   ToFunction->setPure(D->isPure());
02794   Importer.Imported(D, ToFunction);
02795 
02796   // Set the parameters.
02797   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
02798     Parameters[I]->setOwningFunction(ToFunction);
02799     ToFunction->addDeclInternal(Parameters[I]);
02800   }
02801   ToFunction->setParams(Parameters);
02802 
02803   if (usedDifferentExceptionSpec) {
02804     // Update FunctionProtoType::ExtProtoInfo.
02805     QualType T = Importer.Import(D->getType());
02806     if (T.isNull())
02807       return nullptr;
02808     ToFunction->setType(T);
02809   }
02810 
02811   // FIXME: Other bits to merge?
02812 
02813   // Add this function to the lexical context.
02814   LexicalDC->addDeclInternal(ToFunction);
02815 
02816   return ToFunction;
02817 }
02818 
02819 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
02820   return VisitFunctionDecl(D);
02821 }
02822 
02823 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
02824   return VisitCXXMethodDecl(D);
02825 }
02826 
02827 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
02828   return VisitCXXMethodDecl(D);
02829 }
02830 
02831 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
02832   return VisitCXXMethodDecl(D);
02833 }
02834 
02835 static unsigned getFieldIndex(Decl *F) {
02836   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
02837   if (!Owner)
02838     return 0;
02839 
02840   unsigned Index = 1;
02841   for (const auto *D : Owner->noload_decls()) {
02842     if (D == F)
02843       return Index;
02844 
02845     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
02846       ++Index;
02847   }
02848 
02849   return Index;
02850 }
02851 
02852 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
02853   // Import the major distinguishing characteristics of a variable.
02854   DeclContext *DC, *LexicalDC;
02855   DeclarationName Name;
02856   SourceLocation Loc;
02857   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02858     return nullptr;
02859 
02860   // Determine whether we've already imported this field. 
02861   SmallVector<NamedDecl *, 2> FoundDecls;
02862   DC->localUncachedLookup(Name, FoundDecls);
02863   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02864     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
02865       // For anonymous fields, match up by index.
02866       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
02867         continue;
02868 
02869       if (Importer.IsStructurallyEquivalent(D->getType(), 
02870                                             FoundField->getType())) {
02871         Importer.Imported(D, FoundField);
02872         return FoundField;
02873       }
02874       
02875       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
02876         << Name << D->getType() << FoundField->getType();
02877       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
02878         << FoundField->getType();
02879       return nullptr;
02880     }
02881   }
02882 
02883   // Import the type.
02884   QualType T = Importer.Import(D->getType());
02885   if (T.isNull())
02886     return nullptr;
02887 
02888   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
02889   Expr *BitWidth = Importer.Import(D->getBitWidth());
02890   if (!BitWidth && D->getBitWidth())
02891     return nullptr;
02892 
02893   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
02894                                          Importer.Import(D->getInnerLocStart()),
02895                                          Loc, Name.getAsIdentifierInfo(),
02896                                          T, TInfo, BitWidth, D->isMutable(),
02897                                          D->getInClassInitStyle());
02898   ToField->setAccess(D->getAccess());
02899   ToField->setLexicalDeclContext(LexicalDC);
02900   if (ToField->hasInClassInitializer())
02901     ToField->setInClassInitializer(D->getInClassInitializer());
02902   ToField->setImplicit(D->isImplicit());
02903   Importer.Imported(D, ToField);
02904   LexicalDC->addDeclInternal(ToField);
02905   return ToField;
02906 }
02907 
02908 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
02909   // Import the major distinguishing characteristics of a variable.
02910   DeclContext *DC, *LexicalDC;
02911   DeclarationName Name;
02912   SourceLocation Loc;
02913   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02914     return nullptr;
02915 
02916   // Determine whether we've already imported this field. 
02917   SmallVector<NamedDecl *, 2> FoundDecls;
02918   DC->localUncachedLookup(Name, FoundDecls);
02919   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02920     if (IndirectFieldDecl *FoundField 
02921                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
02922       // For anonymous indirect fields, match up by index.
02923       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
02924         continue;
02925 
02926       if (Importer.IsStructurallyEquivalent(D->getType(), 
02927                                             FoundField->getType(),
02928                                             !Name.isEmpty())) {
02929         Importer.Imported(D, FoundField);
02930         return FoundField;
02931       }
02932 
02933       // If there are more anonymous fields to check, continue.
02934       if (!Name && I < N-1)
02935         continue;
02936 
02937       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
02938         << Name << D->getType() << FoundField->getType();
02939       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
02940         << FoundField->getType();
02941       return nullptr;
02942     }
02943   }
02944 
02945   // Import the type.
02946   QualType T = Importer.Import(D->getType());
02947   if (T.isNull())
02948     return nullptr;
02949 
02950   NamedDecl **NamedChain =
02951     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
02952 
02953   unsigned i = 0;
02954   for (auto *PI : D->chain()) {
02955     Decl *D = Importer.Import(PI);
02956     if (!D)
02957       return nullptr;
02958     NamedChain[i++] = cast<NamedDecl>(D);
02959   }
02960 
02961   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
02962       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
02963       NamedChain, D->getChainingSize());
02964 
02965   for (const auto *Attr : D->attrs())
02966     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
02967 
02968   ToIndirectField->setAccess(D->getAccess());
02969   ToIndirectField->setLexicalDeclContext(LexicalDC);
02970   Importer.Imported(D, ToIndirectField);
02971   LexicalDC->addDeclInternal(ToIndirectField);
02972   return ToIndirectField;
02973 }
02974 
02975 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
02976   // Import the major distinguishing characteristics of an ivar.
02977   DeclContext *DC, *LexicalDC;
02978   DeclarationName Name;
02979   SourceLocation Loc;
02980   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
02981     return nullptr;
02982 
02983   // Determine whether we've already imported this ivar 
02984   SmallVector<NamedDecl *, 2> FoundDecls;
02985   DC->localUncachedLookup(Name, FoundDecls);
02986   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
02987     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
02988       if (Importer.IsStructurallyEquivalent(D->getType(), 
02989                                             FoundIvar->getType())) {
02990         Importer.Imported(D, FoundIvar);
02991         return FoundIvar;
02992       }
02993 
02994       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
02995         << Name << D->getType() << FoundIvar->getType();
02996       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
02997         << FoundIvar->getType();
02998       return nullptr;
02999     }
03000   }
03001 
03002   // Import the type.
03003   QualType T = Importer.Import(D->getType());
03004   if (T.isNull())
03005     return nullptr;
03006 
03007   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
03008   Expr *BitWidth = Importer.Import(D->getBitWidth());
03009   if (!BitWidth && D->getBitWidth())
03010     return nullptr;
03011 
03012   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
03013                                               cast<ObjCContainerDecl>(DC),
03014                                        Importer.Import(D->getInnerLocStart()),
03015                                               Loc, Name.getAsIdentifierInfo(),
03016                                               T, TInfo, D->getAccessControl(),
03017                                               BitWidth, D->getSynthesize());
03018   ToIvar->setLexicalDeclContext(LexicalDC);
03019   Importer.Imported(D, ToIvar);
03020   LexicalDC->addDeclInternal(ToIvar);
03021   return ToIvar;
03022   
03023 }
03024 
03025 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
03026   // Import the major distinguishing characteristics of a variable.
03027   DeclContext *DC, *LexicalDC;
03028   DeclarationName Name;
03029   SourceLocation Loc;
03030   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03031     return nullptr;
03032 
03033   // Try to find a variable in our own ("to") context with the same name and
03034   // in the same context as the variable we're importing.
03035   if (D->isFileVarDecl()) {
03036     VarDecl *MergeWithVar = nullptr;
03037     SmallVector<NamedDecl *, 4> ConflictingDecls;
03038     unsigned IDNS = Decl::IDNS_Ordinary;
03039     SmallVector<NamedDecl *, 2> FoundDecls;
03040     DC->localUncachedLookup(Name, FoundDecls);
03041     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03042       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
03043         continue;
03044       
03045       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
03046         // We have found a variable that we may need to merge with. Check it.
03047         if (FoundVar->hasExternalFormalLinkage() &&
03048             D->hasExternalFormalLinkage()) {
03049           if (Importer.IsStructurallyEquivalent(D->getType(), 
03050                                                 FoundVar->getType())) {
03051             MergeWithVar = FoundVar;
03052             break;
03053           }
03054 
03055           const ArrayType *FoundArray
03056             = Importer.getToContext().getAsArrayType(FoundVar->getType());
03057           const ArrayType *TArray
03058             = Importer.getToContext().getAsArrayType(D->getType());
03059           if (FoundArray && TArray) {
03060             if (isa<IncompleteArrayType>(FoundArray) &&
03061                 isa<ConstantArrayType>(TArray)) {
03062               // Import the type.
03063               QualType T = Importer.Import(D->getType());
03064               if (T.isNull())
03065                 return nullptr;
03066 
03067               FoundVar->setType(T);
03068               MergeWithVar = FoundVar;
03069               break;
03070             } else if (isa<IncompleteArrayType>(TArray) &&
03071                        isa<ConstantArrayType>(FoundArray)) {
03072               MergeWithVar = FoundVar;
03073               break;
03074             }
03075           }
03076 
03077           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
03078             << Name << D->getType() << FoundVar->getType();
03079           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
03080             << FoundVar->getType();
03081         }
03082       }
03083       
03084       ConflictingDecls.push_back(FoundDecls[I]);
03085     }
03086 
03087     if (MergeWithVar) {
03088       // An equivalent variable with external linkage has been found. Link 
03089       // the two declarations, then merge them.
03090       Importer.Imported(D, MergeWithVar);
03091       
03092       if (VarDecl *DDef = D->getDefinition()) {
03093         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
03094           Importer.ToDiag(ExistingDef->getLocation(), 
03095                           diag::err_odr_variable_multiple_def)
03096             << Name;
03097           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
03098         } else {
03099           Expr *Init = Importer.Import(DDef->getInit());
03100           MergeWithVar->setInit(Init);
03101           if (DDef->isInitKnownICE()) {
03102             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
03103             Eval->CheckedICE = true;
03104             Eval->IsICE = DDef->isInitICE();
03105           }
03106         }
03107       }
03108       
03109       return MergeWithVar;
03110     }
03111     
03112     if (!ConflictingDecls.empty()) {
03113       Name = Importer.HandleNameConflict(Name, DC, IDNS,
03114                                          ConflictingDecls.data(), 
03115                                          ConflictingDecls.size());
03116       if (!Name)
03117         return nullptr;
03118     }
03119   }
03120     
03121   // Import the type.
03122   QualType T = Importer.Import(D->getType());
03123   if (T.isNull())
03124     return nullptr;
03125 
03126   // Create the imported variable.
03127   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
03128   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
03129                                    Importer.Import(D->getInnerLocStart()),
03130                                    Loc, Name.getAsIdentifierInfo(),
03131                                    T, TInfo,
03132                                    D->getStorageClass());
03133   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
03134   ToVar->setAccess(D->getAccess());
03135   ToVar->setLexicalDeclContext(LexicalDC);
03136   Importer.Imported(D, ToVar);
03137   LexicalDC->addDeclInternal(ToVar);
03138 
03139   // Merge the initializer.
03140   if (ImportDefinition(D, ToVar))
03141     return nullptr;
03142 
03143   return ToVar;
03144 }
03145 
03146 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
03147   // Parameters are created in the translation unit's context, then moved
03148   // into the function declaration's context afterward.
03149   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
03150   
03151   // Import the name of this declaration.
03152   DeclarationName Name = Importer.Import(D->getDeclName());
03153   if (D->getDeclName() && !Name)
03154     return nullptr;
03155 
03156   // Import the location of this declaration.
03157   SourceLocation Loc = Importer.Import(D->getLocation());
03158   
03159   // Import the parameter's type.
03160   QualType T = Importer.Import(D->getType());
03161   if (T.isNull())
03162     return nullptr;
03163 
03164   // Create the imported parameter.
03165   ImplicitParamDecl *ToParm
03166     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
03167                                 Loc, Name.getAsIdentifierInfo(),
03168                                 T);
03169   return Importer.Imported(D, ToParm);
03170 }
03171 
03172 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
03173   // Parameters are created in the translation unit's context, then moved
03174   // into the function declaration's context afterward.
03175   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
03176   
03177   // Import the name of this declaration.
03178   DeclarationName Name = Importer.Import(D->getDeclName());
03179   if (D->getDeclName() && !Name)
03180     return nullptr;
03181 
03182   // Import the location of this declaration.
03183   SourceLocation Loc = Importer.Import(D->getLocation());
03184   
03185   // Import the parameter's type.
03186   QualType T = Importer.Import(D->getType());
03187   if (T.isNull())
03188     return nullptr;
03189 
03190   // Create the imported parameter.
03191   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
03192   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
03193                                      Importer.Import(D->getInnerLocStart()),
03194                                             Loc, Name.getAsIdentifierInfo(),
03195                                             T, TInfo, D->getStorageClass(),
03196                                             /*FIXME: Default argument*/nullptr);
03197   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
03198   return Importer.Imported(D, ToParm);
03199 }
03200 
03201 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
03202   // Import the major distinguishing characteristics of a method.
03203   DeclContext *DC, *LexicalDC;
03204   DeclarationName Name;
03205   SourceLocation Loc;
03206   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03207     return nullptr;
03208 
03209   SmallVector<NamedDecl *, 2> FoundDecls;
03210   DC->localUncachedLookup(Name, FoundDecls);
03211   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03212     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
03213       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
03214         continue;
03215 
03216       // Check return types.
03217       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
03218                                              FoundMethod->getReturnType())) {
03219         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
03220             << D->isInstanceMethod() << Name << D->getReturnType()
03221             << FoundMethod->getReturnType();
03222         Importer.ToDiag(FoundMethod->getLocation(), 
03223                         diag::note_odr_objc_method_here)
03224           << D->isInstanceMethod() << Name;
03225         return nullptr;
03226       }
03227 
03228       // Check the number of parameters.
03229       if (D->param_size() != FoundMethod->param_size()) {
03230         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
03231           << D->isInstanceMethod() << Name
03232           << D->param_size() << FoundMethod->param_size();
03233         Importer.ToDiag(FoundMethod->getLocation(), 
03234                         diag::note_odr_objc_method_here)
03235           << D->isInstanceMethod() << Name;
03236         return nullptr;
03237       }
03238 
03239       // Check parameter types.
03240       for (ObjCMethodDecl::param_iterator P = D->param_begin(), 
03241              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
03242            P != PEnd; ++P, ++FoundP) {
03243         if (!Importer.IsStructurallyEquivalent((*P)->getType(), 
03244                                                (*FoundP)->getType())) {
03245           Importer.FromDiag((*P)->getLocation(), 
03246                             diag::err_odr_objc_method_param_type_inconsistent)
03247             << D->isInstanceMethod() << Name
03248             << (*P)->getType() << (*FoundP)->getType();
03249           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
03250             << (*FoundP)->getType();
03251           return nullptr;
03252         }
03253       }
03254 
03255       // Check variadic/non-variadic.
03256       // Check the number of parameters.
03257       if (D->isVariadic() != FoundMethod->isVariadic()) {
03258         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
03259           << D->isInstanceMethod() << Name;
03260         Importer.ToDiag(FoundMethod->getLocation(), 
03261                         diag::note_odr_objc_method_here)
03262           << D->isInstanceMethod() << Name;
03263         return nullptr;
03264       }
03265 
03266       // FIXME: Any other bits we need to merge?
03267       return Importer.Imported(D, FoundMethod);
03268     }
03269   }
03270 
03271   // Import the result type.
03272   QualType ResultTy = Importer.Import(D->getReturnType());
03273   if (ResultTy.isNull())
03274     return nullptr;
03275 
03276   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
03277 
03278   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
03279       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
03280       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
03281       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
03282       D->getImplementationControl(), D->hasRelatedResultType());
03283 
03284   // FIXME: When we decide to merge method definitions, we'll need to
03285   // deal with implicit parameters.
03286 
03287   // Import the parameters
03288   SmallVector<ParmVarDecl *, 5> ToParams;
03289   for (auto *FromP : D->params()) {
03290     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
03291     if (!ToP)
03292       return nullptr;
03293 
03294     ToParams.push_back(ToP);
03295   }
03296   
03297   // Set the parameters.
03298   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
03299     ToParams[I]->setOwningFunction(ToMethod);
03300     ToMethod->addDeclInternal(ToParams[I]);
03301   }
03302   SmallVector<SourceLocation, 12> SelLocs;
03303   D->getSelectorLocs(SelLocs);
03304   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs); 
03305 
03306   ToMethod->setLexicalDeclContext(LexicalDC);
03307   Importer.Imported(D, ToMethod);
03308   LexicalDC->addDeclInternal(ToMethod);
03309   return ToMethod;
03310 }
03311 
03312 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
03313   // Import the major distinguishing characteristics of a category.
03314   DeclContext *DC, *LexicalDC;
03315   DeclarationName Name;
03316   SourceLocation Loc;
03317   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03318     return nullptr;
03319 
03320   ObjCInterfaceDecl *ToInterface
03321     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
03322   if (!ToInterface)
03323     return nullptr;
03324 
03325   // Determine if we've already encountered this category.
03326   ObjCCategoryDecl *MergeWithCategory
03327     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
03328   ObjCCategoryDecl *ToCategory = MergeWithCategory;
03329   if (!ToCategory) {
03330     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
03331                                           Importer.Import(D->getAtStartLoc()),
03332                                           Loc, 
03333                                        Importer.Import(D->getCategoryNameLoc()), 
03334                                           Name.getAsIdentifierInfo(),
03335                                           ToInterface,
03336                                        Importer.Import(D->getIvarLBraceLoc()),
03337                                        Importer.Import(D->getIvarRBraceLoc()));
03338     ToCategory->setLexicalDeclContext(LexicalDC);
03339     LexicalDC->addDeclInternal(ToCategory);
03340     Importer.Imported(D, ToCategory);
03341     
03342     // Import protocols
03343     SmallVector<ObjCProtocolDecl *, 4> Protocols;
03344     SmallVector<SourceLocation, 4> ProtocolLocs;
03345     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
03346       = D->protocol_loc_begin();
03347     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
03348                                           FromProtoEnd = D->protocol_end();
03349          FromProto != FromProtoEnd;
03350          ++FromProto, ++FromProtoLoc) {
03351       ObjCProtocolDecl *ToProto
03352         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
03353       if (!ToProto)
03354         return nullptr;
03355       Protocols.push_back(ToProto);
03356       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
03357     }
03358     
03359     // FIXME: If we're merging, make sure that the protocol list is the same.
03360     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
03361                                 ProtocolLocs.data(), Importer.getToContext());
03362     
03363   } else {
03364     Importer.Imported(D, ToCategory);
03365   }
03366   
03367   // Import all of the members of this category.
03368   ImportDeclContext(D);
03369  
03370   // If we have an implementation, import it as well.
03371   if (D->getImplementation()) {
03372     ObjCCategoryImplDecl *Impl
03373       = cast_or_null<ObjCCategoryImplDecl>(
03374                                        Importer.Import(D->getImplementation()));
03375     if (!Impl)
03376       return nullptr;
03377 
03378     ToCategory->setImplementation(Impl);
03379   }
03380   
03381   return ToCategory;
03382 }
03383 
03384 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From, 
03385                                        ObjCProtocolDecl *To,
03386                                        ImportDefinitionKind Kind) {
03387   if (To->getDefinition()) {
03388     if (shouldForceImportDeclContext(Kind))
03389       ImportDeclContext(From);
03390     return false;
03391   }
03392 
03393   // Start the protocol definition
03394   To->startDefinition();
03395   
03396   // Import protocols
03397   SmallVector<ObjCProtocolDecl *, 4> Protocols;
03398   SmallVector<SourceLocation, 4> ProtocolLocs;
03399   ObjCProtocolDecl::protocol_loc_iterator 
03400   FromProtoLoc = From->protocol_loc_begin();
03401   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
03402                                         FromProtoEnd = From->protocol_end();
03403        FromProto != FromProtoEnd;
03404        ++FromProto, ++FromProtoLoc) {
03405     ObjCProtocolDecl *ToProto
03406       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
03407     if (!ToProto)
03408       return true;
03409     Protocols.push_back(ToProto);
03410     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
03411   }
03412   
03413   // FIXME: If we're merging, make sure that the protocol list is the same.
03414   To->setProtocolList(Protocols.data(), Protocols.size(),
03415                       ProtocolLocs.data(), Importer.getToContext());
03416 
03417   if (shouldForceImportDeclContext(Kind)) {
03418     // Import all of the members of this protocol.
03419     ImportDeclContext(From, /*ForceImport=*/true);
03420   }
03421   return false;
03422 }
03423 
03424 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
03425   // If this protocol has a definition in the translation unit we're coming 
03426   // from, but this particular declaration is not that definition, import the
03427   // definition and map to that.
03428   ObjCProtocolDecl *Definition = D->getDefinition();
03429   if (Definition && Definition != D) {
03430     Decl *ImportedDef = Importer.Import(Definition);
03431     if (!ImportedDef)
03432       return nullptr;
03433 
03434     return Importer.Imported(D, ImportedDef);
03435   }
03436 
03437   // Import the major distinguishing characteristics of a protocol.
03438   DeclContext *DC, *LexicalDC;
03439   DeclarationName Name;
03440   SourceLocation Loc;
03441   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03442     return nullptr;
03443 
03444   ObjCProtocolDecl *MergeWithProtocol = nullptr;
03445   SmallVector<NamedDecl *, 2> FoundDecls;
03446   DC->localUncachedLookup(Name, FoundDecls);
03447   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03448     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
03449       continue;
03450     
03451     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
03452       break;
03453   }
03454   
03455   ObjCProtocolDecl *ToProto = MergeWithProtocol;
03456   if (!ToProto) {
03457     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
03458                                        Name.getAsIdentifierInfo(), Loc,
03459                                        Importer.Import(D->getAtStartLoc()),
03460                                        /*PrevDecl=*/nullptr);
03461     ToProto->setLexicalDeclContext(LexicalDC);
03462     LexicalDC->addDeclInternal(ToProto);
03463   }
03464     
03465   Importer.Imported(D, ToProto);
03466 
03467   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
03468     return nullptr;
03469 
03470   return ToProto;
03471 }
03472 
03473 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From, 
03474                                        ObjCInterfaceDecl *To,
03475                                        ImportDefinitionKind Kind) {
03476   if (To->getDefinition()) {
03477     // Check consistency of superclass.
03478     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
03479     if (FromSuper) {
03480       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
03481       if (!FromSuper)
03482         return true;
03483     }
03484     
03485     ObjCInterfaceDecl *ToSuper = To->getSuperClass();    
03486     if ((bool)FromSuper != (bool)ToSuper ||
03487         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
03488       Importer.ToDiag(To->getLocation(), 
03489                       diag::err_odr_objc_superclass_inconsistent)
03490         << To->getDeclName();
03491       if (ToSuper)
03492         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
03493           << To->getSuperClass()->getDeclName();
03494       else
03495         Importer.ToDiag(To->getLocation(), 
03496                         diag::note_odr_objc_missing_superclass);
03497       if (From->getSuperClass())
03498         Importer.FromDiag(From->getSuperClassLoc(), 
03499                           diag::note_odr_objc_superclass)
03500         << From->getSuperClass()->getDeclName();
03501       else
03502         Importer.FromDiag(From->getLocation(), 
03503                           diag::note_odr_objc_missing_superclass);        
03504     }
03505     
03506     if (shouldForceImportDeclContext(Kind))
03507       ImportDeclContext(From);
03508     return false;
03509   }
03510   
03511   // Start the definition.
03512   To->startDefinition();
03513   
03514   // If this class has a superclass, import it.
03515   if (From->getSuperClass()) {
03516     ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
03517                                  Importer.Import(From->getSuperClass()));
03518     if (!Super)
03519       return true;
03520     
03521     To->setSuperClass(Super);
03522     To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
03523   }
03524   
03525   // Import protocols
03526   SmallVector<ObjCProtocolDecl *, 4> Protocols;
03527   SmallVector<SourceLocation, 4> ProtocolLocs;
03528   ObjCInterfaceDecl::protocol_loc_iterator 
03529   FromProtoLoc = From->protocol_loc_begin();
03530   
03531   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
03532                                          FromProtoEnd = From->protocol_end();
03533        FromProto != FromProtoEnd;
03534        ++FromProto, ++FromProtoLoc) {
03535     ObjCProtocolDecl *ToProto
03536       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
03537     if (!ToProto)
03538       return true;
03539     Protocols.push_back(ToProto);
03540     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
03541   }
03542   
03543   // FIXME: If we're merging, make sure that the protocol list is the same.
03544   To->setProtocolList(Protocols.data(), Protocols.size(),
03545                       ProtocolLocs.data(), Importer.getToContext());
03546   
03547   // Import categories. When the categories themselves are imported, they'll
03548   // hook themselves into this interface.
03549   for (auto *Cat : From->known_categories())
03550     Importer.Import(Cat);
03551   
03552   // If we have an @implementation, import it as well.
03553   if (From->getImplementation()) {
03554     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
03555                                      Importer.Import(From->getImplementation()));
03556     if (!Impl)
03557       return true;
03558     
03559     To->setImplementation(Impl);
03560   }
03561 
03562   if (shouldForceImportDeclContext(Kind)) {
03563     // Import all of the members of this class.
03564     ImportDeclContext(From, /*ForceImport=*/true);
03565   }
03566   return false;
03567 }
03568 
03569 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
03570   // If this class has a definition in the translation unit we're coming from,
03571   // but this particular declaration is not that definition, import the
03572   // definition and map to that.
03573   ObjCInterfaceDecl *Definition = D->getDefinition();
03574   if (Definition && Definition != D) {
03575     Decl *ImportedDef = Importer.Import(Definition);
03576     if (!ImportedDef)
03577       return nullptr;
03578 
03579     return Importer.Imported(D, ImportedDef);
03580   }
03581 
03582   // Import the major distinguishing characteristics of an @interface.
03583   DeclContext *DC, *LexicalDC;
03584   DeclarationName Name;
03585   SourceLocation Loc;
03586   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03587     return nullptr;
03588 
03589   // Look for an existing interface with the same name.
03590   ObjCInterfaceDecl *MergeWithIface = nullptr;
03591   SmallVector<NamedDecl *, 2> FoundDecls;
03592   DC->localUncachedLookup(Name, FoundDecls);
03593   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03594     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
03595       continue;
03596     
03597     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
03598       break;
03599   }
03600   
03601   // Create an interface declaration, if one does not already exist.
03602   ObjCInterfaceDecl *ToIface = MergeWithIface;
03603   if (!ToIface) {
03604     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
03605                                         Importer.Import(D->getAtStartLoc()),
03606                                         Name.getAsIdentifierInfo(), 
03607                                         /*PrevDecl=*/nullptr, Loc,
03608                                         D->isImplicitInterfaceDecl());
03609     ToIface->setLexicalDeclContext(LexicalDC);
03610     LexicalDC->addDeclInternal(ToIface);
03611   }
03612   Importer.Imported(D, ToIface);
03613   
03614   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
03615     return nullptr;
03616 
03617   return ToIface;
03618 }
03619 
03620 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
03621   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
03622                                         Importer.Import(D->getCategoryDecl()));
03623   if (!Category)
03624     return nullptr;
03625 
03626   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
03627   if (!ToImpl) {
03628     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
03629     if (!DC)
03630       return nullptr;
03631 
03632     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
03633     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
03634                                           Importer.Import(D->getIdentifier()),
03635                                           Category->getClassInterface(),
03636                                           Importer.Import(D->getLocation()),
03637                                           Importer.Import(D->getAtStartLoc()),
03638                                           CategoryNameLoc);
03639     
03640     DeclContext *LexicalDC = DC;
03641     if (D->getDeclContext() != D->getLexicalDeclContext()) {
03642       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
03643       if (!LexicalDC)
03644         return nullptr;
03645 
03646       ToImpl->setLexicalDeclContext(LexicalDC);
03647     }
03648     
03649     LexicalDC->addDeclInternal(ToImpl);
03650     Category->setImplementation(ToImpl);
03651   }
03652   
03653   Importer.Imported(D, ToImpl);
03654   ImportDeclContext(D);
03655   return ToImpl;
03656 }
03657 
03658 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
03659   // Find the corresponding interface.
03660   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
03661                                        Importer.Import(D->getClassInterface()));
03662   if (!Iface)
03663     return nullptr;
03664 
03665   // Import the superclass, if any.
03666   ObjCInterfaceDecl *Super = nullptr;
03667   if (D->getSuperClass()) {
03668     Super = cast_or_null<ObjCInterfaceDecl>(
03669                                           Importer.Import(D->getSuperClass()));
03670     if (!Super)
03671       return nullptr;
03672   }
03673 
03674   ObjCImplementationDecl *Impl = Iface->getImplementation();
03675   if (!Impl) {
03676     // We haven't imported an implementation yet. Create a new @implementation
03677     // now.
03678     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
03679                                   Importer.ImportContext(D->getDeclContext()),
03680                                           Iface, Super,
03681                                           Importer.Import(D->getLocation()),
03682                                           Importer.Import(D->getAtStartLoc()),
03683                                           Importer.Import(D->getSuperClassLoc()),
03684                                           Importer.Import(D->getIvarLBraceLoc()),
03685                                           Importer.Import(D->getIvarRBraceLoc()));
03686     
03687     if (D->getDeclContext() != D->getLexicalDeclContext()) {
03688       DeclContext *LexicalDC
03689         = Importer.ImportContext(D->getLexicalDeclContext());
03690       if (!LexicalDC)
03691         return nullptr;
03692       Impl->setLexicalDeclContext(LexicalDC);
03693     }
03694     
03695     // Associate the implementation with the class it implements.
03696     Iface->setImplementation(Impl);
03697     Importer.Imported(D, Iface->getImplementation());
03698   } else {
03699     Importer.Imported(D, Iface->getImplementation());
03700 
03701     // Verify that the existing @implementation has the same superclass.
03702     if ((Super && !Impl->getSuperClass()) ||
03703         (!Super && Impl->getSuperClass()) ||
03704         (Super && Impl->getSuperClass() &&
03705          !declaresSameEntity(Super->getCanonicalDecl(),
03706                              Impl->getSuperClass()))) {
03707       Importer.ToDiag(Impl->getLocation(),
03708                       diag::err_odr_objc_superclass_inconsistent)
03709         << Iface->getDeclName();
03710       // FIXME: It would be nice to have the location of the superclass
03711       // below.
03712       if (Impl->getSuperClass())
03713         Importer.ToDiag(Impl->getLocation(),
03714                         diag::note_odr_objc_superclass)
03715         << Impl->getSuperClass()->getDeclName();
03716       else
03717         Importer.ToDiag(Impl->getLocation(),
03718                         diag::note_odr_objc_missing_superclass);
03719       if (D->getSuperClass())
03720         Importer.FromDiag(D->getLocation(),
03721                           diag::note_odr_objc_superclass)
03722         << D->getSuperClass()->getDeclName();
03723       else
03724         Importer.FromDiag(D->getLocation(),
03725                           diag::note_odr_objc_missing_superclass);
03726       return nullptr;
03727     }
03728   }
03729     
03730   // Import all of the members of this @implementation.
03731   ImportDeclContext(D);
03732 
03733   return Impl;
03734 }
03735 
03736 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
03737   // Import the major distinguishing characteristics of an @property.
03738   DeclContext *DC, *LexicalDC;
03739   DeclarationName Name;
03740   SourceLocation Loc;
03741   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03742     return nullptr;
03743 
03744   // Check whether we have already imported this property.
03745   SmallVector<NamedDecl *, 2> FoundDecls;
03746   DC->localUncachedLookup(Name, FoundDecls);
03747   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03748     if (ObjCPropertyDecl *FoundProp
03749                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
03750       // Check property types.
03751       if (!Importer.IsStructurallyEquivalent(D->getType(), 
03752                                              FoundProp->getType())) {
03753         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
03754           << Name << D->getType() << FoundProp->getType();
03755         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
03756           << FoundProp->getType();
03757         return nullptr;
03758       }
03759 
03760       // FIXME: Check property attributes, getters, setters, etc.?
03761 
03762       // Consider these properties to be equivalent.
03763       Importer.Imported(D, FoundProp);
03764       return FoundProp;
03765     }
03766   }
03767 
03768   // Import the type.
03769   TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
03770   if (!T)
03771     return nullptr;
03772 
03773   // Create the new property.
03774   ObjCPropertyDecl *ToProperty
03775     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
03776                                Name.getAsIdentifierInfo(), 
03777                                Importer.Import(D->getAtLoc()),
03778                                Importer.Import(D->getLParenLoc()),
03779                                T,
03780                                D->getPropertyImplementation());
03781   Importer.Imported(D, ToProperty);
03782   ToProperty->setLexicalDeclContext(LexicalDC);
03783   LexicalDC->addDeclInternal(ToProperty);
03784 
03785   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
03786   ToProperty->setPropertyAttributesAsWritten(
03787                                       D->getPropertyAttributesAsWritten());
03788   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
03789   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
03790   ToProperty->setGetterMethodDecl(
03791      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
03792   ToProperty->setSetterMethodDecl(
03793      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
03794   ToProperty->setPropertyIvarDecl(
03795        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
03796   return ToProperty;
03797 }
03798 
03799 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
03800   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
03801                                         Importer.Import(D->getPropertyDecl()));
03802   if (!Property)
03803     return nullptr;
03804 
03805   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
03806   if (!DC)
03807     return nullptr;
03808 
03809   // Import the lexical declaration context.
03810   DeclContext *LexicalDC = DC;
03811   if (D->getDeclContext() != D->getLexicalDeclContext()) {
03812     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
03813     if (!LexicalDC)
03814       return nullptr;
03815   }
03816 
03817   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
03818   if (!InImpl)
03819     return nullptr;
03820 
03821   // Import the ivar (for an @synthesize).
03822   ObjCIvarDecl *Ivar = nullptr;
03823   if (D->getPropertyIvarDecl()) {
03824     Ivar = cast_or_null<ObjCIvarDecl>(
03825                                     Importer.Import(D->getPropertyIvarDecl()));
03826     if (!Ivar)
03827       return nullptr;
03828   }
03829 
03830   ObjCPropertyImplDecl *ToImpl
03831     = InImpl->FindPropertyImplDecl(Property->getIdentifier());
03832   if (!ToImpl) {    
03833     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
03834                                           Importer.Import(D->getLocStart()),
03835                                           Importer.Import(D->getLocation()),
03836                                           Property,
03837                                           D->getPropertyImplementation(),
03838                                           Ivar, 
03839                                   Importer.Import(D->getPropertyIvarDeclLoc()));
03840     ToImpl->setLexicalDeclContext(LexicalDC);
03841     Importer.Imported(D, ToImpl);
03842     LexicalDC->addDeclInternal(ToImpl);
03843   } else {
03844     // Check that we have the same kind of property implementation (@synthesize
03845     // vs. @dynamic).
03846     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
03847       Importer.ToDiag(ToImpl->getLocation(), 
03848                       diag::err_odr_objc_property_impl_kind_inconsistent)
03849         << Property->getDeclName() 
03850         << (ToImpl->getPropertyImplementation() 
03851                                               == ObjCPropertyImplDecl::Dynamic);
03852       Importer.FromDiag(D->getLocation(),
03853                         diag::note_odr_objc_property_impl_kind)
03854         << D->getPropertyDecl()->getDeclName()
03855         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
03856       return nullptr;
03857     }
03858     
03859     // For @synthesize, check that we have the same 
03860     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
03861         Ivar != ToImpl->getPropertyIvarDecl()) {
03862       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 
03863                       diag::err_odr_objc_synthesize_ivar_inconsistent)
03864         << Property->getDeclName()
03865         << ToImpl->getPropertyIvarDecl()->getDeclName()
03866         << Ivar->getDeclName();
03867       Importer.FromDiag(D->getPropertyIvarDeclLoc(), 
03868                         diag::note_odr_objc_synthesize_ivar_here)
03869         << D->getPropertyIvarDecl()->getDeclName();
03870       return nullptr;
03871     }
03872     
03873     // Merge the existing implementation with the new implementation.
03874     Importer.Imported(D, ToImpl);
03875   }
03876   
03877   return ToImpl;
03878 }
03879 
03880 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
03881   // For template arguments, we adopt the translation unit as our declaration
03882   // context. This context will be fixed when the actual template declaration
03883   // is created.
03884   
03885   // FIXME: Import default argument.
03886   return TemplateTypeParmDecl::Create(Importer.getToContext(),
03887                               Importer.getToContext().getTranslationUnitDecl(),
03888                                       Importer.Import(D->getLocStart()),
03889                                       Importer.Import(D->getLocation()),
03890                                       D->getDepth(),
03891                                       D->getIndex(), 
03892                                       Importer.Import(D->getIdentifier()),
03893                                       D->wasDeclaredWithTypename(),
03894                                       D->isParameterPack());
03895 }
03896 
03897 Decl *
03898 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
03899   // Import the name of this declaration.
03900   DeclarationName Name = Importer.Import(D->getDeclName());
03901   if (D->getDeclName() && !Name)
03902     return nullptr;
03903 
03904   // Import the location of this declaration.
03905   SourceLocation Loc = Importer.Import(D->getLocation());
03906 
03907   // Import the type of this declaration.
03908   QualType T = Importer.Import(D->getType());
03909   if (T.isNull())
03910     return nullptr;
03911 
03912   // Import type-source information.
03913   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
03914   if (D->getTypeSourceInfo() && !TInfo)
03915     return nullptr;
03916 
03917   // FIXME: Import default argument.
03918   
03919   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
03920                                Importer.getToContext().getTranslationUnitDecl(),
03921                                          Importer.Import(D->getInnerLocStart()),
03922                                          Loc, D->getDepth(), D->getPosition(),
03923                                          Name.getAsIdentifierInfo(),
03924                                          T, D->isParameterPack(), TInfo);
03925 }
03926 
03927 Decl *
03928 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
03929   // Import the name of this declaration.
03930   DeclarationName Name = Importer.Import(D->getDeclName());
03931   if (D->getDeclName() && !Name)
03932     return nullptr;
03933 
03934   // Import the location of this declaration.
03935   SourceLocation Loc = Importer.Import(D->getLocation());
03936   
03937   // Import template parameters.
03938   TemplateParameterList *TemplateParams
03939     = ImportTemplateParameterList(D->getTemplateParameters());
03940   if (!TemplateParams)
03941     return nullptr;
03942 
03943   // FIXME: Import default argument.
03944   
03945   return TemplateTemplateParmDecl::Create(Importer.getToContext(), 
03946                               Importer.getToContext().getTranslationUnitDecl(), 
03947                                           Loc, D->getDepth(), D->getPosition(),
03948                                           D->isParameterPack(),
03949                                           Name.getAsIdentifierInfo(), 
03950                                           TemplateParams);
03951 }
03952 
03953 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
03954   // If this record has a definition in the translation unit we're coming from,
03955   // but this particular declaration is not that definition, import the
03956   // definition and map to that.
03957   CXXRecordDecl *Definition 
03958     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
03959   if (Definition && Definition != D->getTemplatedDecl()) {
03960     Decl *ImportedDef
03961       = Importer.Import(Definition->getDescribedClassTemplate());
03962     if (!ImportedDef)
03963       return nullptr;
03964 
03965     return Importer.Imported(D, ImportedDef);
03966   }
03967   
03968   // Import the major distinguishing characteristics of this class template.
03969   DeclContext *DC, *LexicalDC;
03970   DeclarationName Name;
03971   SourceLocation Loc;
03972   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
03973     return nullptr;
03974 
03975   // We may already have a template of the same name; try to find and match it.
03976   if (!DC->isFunctionOrMethod()) {
03977     SmallVector<NamedDecl *, 4> ConflictingDecls;
03978     SmallVector<NamedDecl *, 2> FoundDecls;
03979     DC->localUncachedLookup(Name, FoundDecls);
03980     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
03981       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
03982         continue;
03983       
03984       Decl *Found = FoundDecls[I];
03985       if (ClassTemplateDecl *FoundTemplate 
03986                                         = dyn_cast<ClassTemplateDecl>(Found)) {
03987         if (IsStructuralMatch(D, FoundTemplate)) {
03988           // The class templates structurally match; call it the same template.
03989           // FIXME: We may be filling in a forward declaration here. Handle
03990           // this case!
03991           Importer.Imported(D->getTemplatedDecl(), 
03992                             FoundTemplate->getTemplatedDecl());
03993           return Importer.Imported(D, FoundTemplate);
03994         }         
03995       }
03996       
03997       ConflictingDecls.push_back(FoundDecls[I]);
03998     }
03999     
04000     if (!ConflictingDecls.empty()) {
04001       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
04002                                          ConflictingDecls.data(), 
04003                                          ConflictingDecls.size());
04004     }
04005     
04006     if (!Name)
04007       return nullptr;
04008   }
04009 
04010   CXXRecordDecl *DTemplated = D->getTemplatedDecl();
04011   
04012   // Create the declaration that is being templated.
04013   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
04014   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
04015   CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
04016                                                      DTemplated->getTagKind(),
04017                                                      DC, StartLoc, IdLoc,
04018                                                    Name.getAsIdentifierInfo());
04019   D2Templated->setAccess(DTemplated->getAccess());
04020   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
04021   D2Templated->setLexicalDeclContext(LexicalDC);
04022   
04023   // Create the class template declaration itself.
04024   TemplateParameterList *TemplateParams
04025     = ImportTemplateParameterList(D->getTemplateParameters());
04026   if (!TemplateParams)
04027     return nullptr;
04028 
04029   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC, 
04030                                                     Loc, Name, TemplateParams, 
04031                                                     D2Templated, 
04032                                                     /*PrevDecl=*/nullptr);
04033   D2Templated->setDescribedClassTemplate(D2);    
04034   
04035   D2->setAccess(D->getAccess());
04036   D2->setLexicalDeclContext(LexicalDC);
04037   LexicalDC->addDeclInternal(D2);
04038   
04039   // Note the relationship between the class templates.
04040   Importer.Imported(D, D2);
04041   Importer.Imported(DTemplated, D2Templated);
04042 
04043   if (DTemplated->isCompleteDefinition() &&
04044       !D2Templated->isCompleteDefinition()) {
04045     // FIXME: Import definition!
04046   }
04047   
04048   return D2;
04049 }
04050 
04051 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
04052                                           ClassTemplateSpecializationDecl *D) {
04053   // If this record has a definition in the translation unit we're coming from,
04054   // but this particular declaration is not that definition, import the
04055   // definition and map to that.
04056   TagDecl *Definition = D->getDefinition();
04057   if (Definition && Definition != D) {
04058     Decl *ImportedDef = Importer.Import(Definition);
04059     if (!ImportedDef)
04060       return nullptr;
04061 
04062     return Importer.Imported(D, ImportedDef);
04063   }
04064 
04065   ClassTemplateDecl *ClassTemplate
04066     = cast_or_null<ClassTemplateDecl>(Importer.Import(
04067                                                  D->getSpecializedTemplate()));
04068   if (!ClassTemplate)
04069     return nullptr;
04070 
04071   // Import the context of this declaration.
04072   DeclContext *DC = ClassTemplate->getDeclContext();
04073   if (!DC)
04074     return nullptr;
04075 
04076   DeclContext *LexicalDC = DC;
04077   if (D->getDeclContext() != D->getLexicalDeclContext()) {
04078     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
04079     if (!LexicalDC)
04080       return nullptr;
04081   }
04082   
04083   // Import the location of this declaration.
04084   SourceLocation StartLoc = Importer.Import(D->getLocStart());
04085   SourceLocation IdLoc = Importer.Import(D->getLocation());
04086 
04087   // Import template arguments.
04088   SmallVector<TemplateArgument, 2> TemplateArgs;
04089   if (ImportTemplateArguments(D->getTemplateArgs().data(), 
04090                               D->getTemplateArgs().size(),
04091                               TemplateArgs))
04092     return nullptr;
04093 
04094   // Try to find an existing specialization with these template arguments.
04095   void *InsertPos = nullptr;
04096   ClassTemplateSpecializationDecl *D2
04097     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
04098   if (D2) {
04099     // We already have a class template specialization with these template
04100     // arguments.
04101     
04102     // FIXME: Check for specialization vs. instantiation errors.
04103     
04104     if (RecordDecl *FoundDef = D2->getDefinition()) {
04105       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
04106         // The record types structurally match, or the "from" translation
04107         // unit only had a forward declaration anyway; call it the same
04108         // function.
04109         return Importer.Imported(D, FoundDef);
04110       }
04111     }
04112   } else {
04113     // Create a new specialization.
04114     D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(), 
04115                                                  D->getTagKind(), DC, 
04116                                                  StartLoc, IdLoc,
04117                                                  ClassTemplate,
04118                                                  TemplateArgs.data(), 
04119                                                  TemplateArgs.size(), 
04120                                                  /*PrevDecl=*/nullptr);
04121     D2->setSpecializationKind(D->getSpecializationKind());
04122 
04123     // Add this specialization to the class template.
04124     ClassTemplate->AddSpecialization(D2, InsertPos);
04125     
04126     // Import the qualifier, if any.
04127     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
04128     
04129     // Add the specialization to this context.
04130     D2->setLexicalDeclContext(LexicalDC);
04131     LexicalDC->addDeclInternal(D2);
04132   }
04133   Importer.Imported(D, D2);
04134   
04135   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
04136     return nullptr;
04137 
04138   return D2;
04139 }
04140 
04141 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
04142   // If this variable has a definition in the translation unit we're coming
04143   // from,
04144   // but this particular declaration is not that definition, import the
04145   // definition and map to that.
04146   VarDecl *Definition =
04147       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
04148   if (Definition && Definition != D->getTemplatedDecl()) {
04149     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
04150     if (!ImportedDef)
04151       return nullptr;
04152 
04153     return Importer.Imported(D, ImportedDef);
04154   }
04155 
04156   // Import the major distinguishing characteristics of this variable template.
04157   DeclContext *DC, *LexicalDC;
04158   DeclarationName Name;
04159   SourceLocation Loc;
04160   if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
04161     return nullptr;
04162 
04163   // We may already have a template of the same name; try to find and match it.
04164   assert(!DC->isFunctionOrMethod() &&
04165          "Variable templates cannot be declared at function scope");
04166   SmallVector<NamedDecl *, 4> ConflictingDecls;
04167   SmallVector<NamedDecl *, 2> FoundDecls;
04168   DC->localUncachedLookup(Name, FoundDecls);
04169   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
04170     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
04171       continue;
04172 
04173     Decl *Found = FoundDecls[I];
04174     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
04175       if (IsStructuralMatch(D, FoundTemplate)) {
04176         // The variable templates structurally match; call it the same template.
04177         Importer.Imported(D->getTemplatedDecl(),
04178                           FoundTemplate->getTemplatedDecl());
04179         return Importer.Imported(D, FoundTemplate);
04180       }
04181     }
04182 
04183     ConflictingDecls.push_back(FoundDecls[I]);
04184   }
04185 
04186   if (!ConflictingDecls.empty()) {
04187     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
04188                                        ConflictingDecls.data(),
04189                                        ConflictingDecls.size());
04190   }
04191 
04192   if (!Name)
04193     return nullptr;
04194 
04195   VarDecl *DTemplated = D->getTemplatedDecl();
04196 
04197   // Import the type.
04198   QualType T = Importer.Import(DTemplated->getType());
04199   if (T.isNull())
04200     return nullptr;
04201 
04202   // Create the declaration that is being templated.
04203   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
04204   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
04205   TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
04206   VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
04207                                          IdLoc, Name.getAsIdentifierInfo(), T,
04208                                          TInfo, DTemplated->getStorageClass());
04209   D2Templated->setAccess(DTemplated->getAccess());
04210   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
04211   D2Templated->setLexicalDeclContext(LexicalDC);
04212 
04213   // Importer.Imported(DTemplated, D2Templated);
04214   // LexicalDC->addDeclInternal(D2Templated);
04215 
04216   // Merge the initializer.
04217   if (ImportDefinition(DTemplated, D2Templated))
04218     return nullptr;
04219 
04220   // Create the variable template declaration itself.
04221   TemplateParameterList *TemplateParams =
04222       ImportTemplateParameterList(D->getTemplateParameters());
04223   if (!TemplateParams)
04224     return nullptr;
04225 
04226   VarTemplateDecl *D2 = VarTemplateDecl::Create(
04227       Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
04228   D2Templated->setDescribedVarTemplate(D2);
04229 
04230   D2->setAccess(D->getAccess());
04231   D2->setLexicalDeclContext(LexicalDC);
04232   LexicalDC->addDeclInternal(D2);
04233 
04234   // Note the relationship between the variable templates.
04235   Importer.Imported(D, D2);
04236   Importer.Imported(DTemplated, D2Templated);
04237 
04238   if (DTemplated->isThisDeclarationADefinition() &&
04239       !D2Templated->isThisDeclarationADefinition()) {
04240     // FIXME: Import definition!
04241   }
04242 
04243   return D2;
04244 }
04245 
04246 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
04247     VarTemplateSpecializationDecl *D) {
04248   // If this record has a definition in the translation unit we're coming from,
04249   // but this particular declaration is not that definition, import the
04250   // definition and map to that.
04251   VarDecl *Definition = D->getDefinition();
04252   if (Definition && Definition != D) {
04253     Decl *ImportedDef = Importer.Import(Definition);
04254     if (!ImportedDef)
04255       return nullptr;
04256 
04257     return Importer.Imported(D, ImportedDef);
04258   }
04259 
04260   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
04261       Importer.Import(D->getSpecializedTemplate()));
04262   if (!VarTemplate)
04263     return nullptr;
04264 
04265   // Import the context of this declaration.
04266   DeclContext *DC = VarTemplate->getDeclContext();
04267   if (!DC)
04268     return nullptr;
04269 
04270   DeclContext *LexicalDC = DC;
04271   if (D->getDeclContext() != D->getLexicalDeclContext()) {
04272     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
04273     if (!LexicalDC)
04274       return nullptr;
04275   }
04276 
04277   // Import the location of this declaration.
04278   SourceLocation StartLoc = Importer.Import(D->getLocStart());
04279   SourceLocation IdLoc = Importer.Import(D->getLocation());
04280 
04281   // Import template arguments.
04282   SmallVector<TemplateArgument, 2> TemplateArgs;
04283   if (ImportTemplateArguments(D->getTemplateArgs().data(),
04284                               D->getTemplateArgs().size(), TemplateArgs))
04285     return nullptr;
04286 
04287   // Try to find an existing specialization with these template arguments.
04288   void *InsertPos = nullptr;
04289   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
04290       TemplateArgs, InsertPos);
04291   if (D2) {
04292     // We already have a variable template specialization with these template
04293     // arguments.
04294 
04295     // FIXME: Check for specialization vs. instantiation errors.
04296 
04297     if (VarDecl *FoundDef = D2->getDefinition()) {
04298       if (!D->isThisDeclarationADefinition() ||
04299           IsStructuralMatch(D, FoundDef)) {
04300         // The record types structurally match, or the "from" translation
04301         // unit only had a forward declaration anyway; call it the same
04302         // variable.
04303         return Importer.Imported(D, FoundDef);
04304       }
04305     }
04306   } else {
04307 
04308     // Import the type.
04309     QualType T = Importer.Import(D->getType());
04310     if (T.isNull())
04311       return nullptr;
04312     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
04313 
04314     // Create a new specialization.
04315     D2 = VarTemplateSpecializationDecl::Create(
04316         Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
04317         D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
04318     D2->setSpecializationKind(D->getSpecializationKind());
04319     D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
04320 
04321     // Add this specialization to the class template.
04322     VarTemplate->AddSpecialization(D2, InsertPos);
04323 
04324     // Import the qualifier, if any.
04325     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
04326 
04327     // Add the specialization to this context.
04328     D2->setLexicalDeclContext(LexicalDC);
04329     LexicalDC->addDeclInternal(D2);
04330   }
04331   Importer.Imported(D, D2);
04332 
04333   if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
04334     return nullptr;
04335 
04336   return D2;
04337 }
04338 
04339 //----------------------------------------------------------------------------
04340 // Import Statements
04341 //----------------------------------------------------------------------------
04342 
04343 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
04344   Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
04345     << S->getStmtClassName();
04346   return nullptr;
04347 }
04348 
04349 //----------------------------------------------------------------------------
04350 // Import Expressions
04351 //----------------------------------------------------------------------------
04352 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
04353   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
04354     << E->getStmtClassName();
04355   return nullptr;
04356 }
04357 
04358 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
04359   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
04360   if (!ToD)
04361     return nullptr;
04362 
04363   NamedDecl *FoundD = nullptr;
04364   if (E->getDecl() != E->getFoundDecl()) {
04365     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
04366     if (!FoundD)
04367       return nullptr;
04368   }
04369   
04370   QualType T = Importer.Import(E->getType());
04371   if (T.isNull())
04372     return nullptr;
04373 
04374   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(), 
04375                                          Importer.Import(E->getQualifierLoc()),
04376                                    Importer.Import(E->getTemplateKeywordLoc()),
04377                                          ToD,
04378                                          E->refersToEnclosingLocal(),
04379                                          Importer.Import(E->getLocation()),
04380                                          T, E->getValueKind(),
04381                                          FoundD,
04382                                          /*FIXME:TemplateArgs=*/nullptr);
04383   if (E->hadMultipleCandidates())
04384     DRE->setHadMultipleCandidates(true);
04385   return DRE;
04386 }
04387 
04388 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
04389   QualType T = Importer.Import(E->getType());
04390   if (T.isNull())
04391     return nullptr;
04392 
04393   return IntegerLiteral::Create(Importer.getToContext(), 
04394                                 E->getValue(), T,
04395                                 Importer.Import(E->getLocation()));
04396 }
04397 
04398 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
04399   QualType T = Importer.Import(E->getType());
04400   if (T.isNull())
04401     return nullptr;
04402 
04403   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
04404                                                         E->getKind(), T,
04405                                           Importer.Import(E->getLocation()));
04406 }
04407 
04408 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
04409   Expr *SubExpr = Importer.Import(E->getSubExpr());
04410   if (!SubExpr)
04411     return nullptr;
04412 
04413   return new (Importer.getToContext()) 
04414                                   ParenExpr(Importer.Import(E->getLParen()),
04415                                             Importer.Import(E->getRParen()),
04416                                             SubExpr);
04417 }
04418 
04419 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
04420   QualType T = Importer.Import(E->getType());
04421   if (T.isNull())
04422     return nullptr;
04423 
04424   Expr *SubExpr = Importer.Import(E->getSubExpr());
04425   if (!SubExpr)
04426     return nullptr;
04427 
04428   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
04429                                                      T, E->getValueKind(),
04430                                                      E->getObjectKind(),
04431                                          Importer.Import(E->getOperatorLoc()));                                        
04432 }
04433 
04434 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
04435                                             UnaryExprOrTypeTraitExpr *E) {
04436   QualType ResultType = Importer.Import(E->getType());
04437   
04438   if (E->isArgumentType()) {
04439     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
04440     if (!TInfo)
04441       return nullptr;
04442 
04443     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
04444                                            TInfo, ResultType,
04445                                            Importer.Import(E->getOperatorLoc()),
04446                                            Importer.Import(E->getRParenLoc()));
04447   }
04448   
04449   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
04450   if (!SubExpr)
04451     return nullptr;
04452 
04453   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
04454                                           SubExpr, ResultType,
04455                                           Importer.Import(E->getOperatorLoc()),
04456                                           Importer.Import(E->getRParenLoc()));
04457 }
04458 
04459 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
04460   QualType T = Importer.Import(E->getType());
04461   if (T.isNull())
04462     return nullptr;
04463 
04464   Expr *LHS = Importer.Import(E->getLHS());
04465   if (!LHS)
04466     return nullptr;
04467 
04468   Expr *RHS = Importer.Import(E->getRHS());
04469   if (!RHS)
04470     return nullptr;
04471 
04472   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
04473                                                       T, E->getValueKind(),
04474                                                       E->getObjectKind(),
04475                                            Importer.Import(E->getOperatorLoc()),
04476                                                       E->isFPContractable());
04477 }
04478 
04479 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
04480   QualType T = Importer.Import(E->getType());
04481   if (T.isNull())
04482     return nullptr;
04483 
04484   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
04485   if (CompLHSType.isNull())
04486     return nullptr;
04487 
04488   QualType CompResultType = Importer.Import(E->getComputationResultType());
04489   if (CompResultType.isNull())
04490     return nullptr;
04491 
04492   Expr *LHS = Importer.Import(E->getLHS());
04493   if (!LHS)
04494     return nullptr;
04495 
04496   Expr *RHS = Importer.Import(E->getRHS());
04497   if (!RHS)
04498     return nullptr;
04499 
04500   return new (Importer.getToContext()) 
04501                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
04502                                                T, E->getValueKind(),
04503                                                E->getObjectKind(),
04504                                                CompLHSType, CompResultType,
04505                                            Importer.Import(E->getOperatorLoc()),
04506                                                E->isFPContractable());
04507 }
04508 
04509 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
04510   if (E->path_empty()) return false;
04511 
04512   // TODO: import cast paths
04513   return true;
04514 }
04515 
04516 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
04517   QualType T = Importer.Import(E->getType());
04518   if (T.isNull())
04519     return nullptr;
04520 
04521   Expr *SubExpr = Importer.Import(E->getSubExpr());
04522   if (!SubExpr)
04523     return nullptr;
04524 
04525   CXXCastPath BasePath;
04526   if (ImportCastPath(E, BasePath))
04527     return nullptr;
04528 
04529   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
04530                                   SubExpr, &BasePath, E->getValueKind());
04531 }
04532 
04533 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
04534   QualType T = Importer.Import(E->getType());
04535   if (T.isNull())
04536     return nullptr;
04537 
04538   Expr *SubExpr = Importer.Import(E->getSubExpr());
04539   if (!SubExpr)
04540     return nullptr;
04541 
04542   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
04543   if (!TInfo && E->getTypeInfoAsWritten())
04544     return nullptr;
04545 
04546   CXXCastPath BasePath;
04547   if (ImportCastPath(E, BasePath))
04548     return nullptr;
04549 
04550   return CStyleCastExpr::Create(Importer.getToContext(), T,
04551                                 E->getValueKind(), E->getCastKind(),
04552                                 SubExpr, &BasePath, TInfo,
04553                                 Importer.Import(E->getLParenLoc()),
04554                                 Importer.Import(E->getRParenLoc()));
04555 }
04556 
04557 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
04558                          ASTContext &FromContext, FileManager &FromFileManager,
04559                          bool MinimalImport)
04560   : ToContext(ToContext), FromContext(FromContext),
04561     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
04562     Minimal(MinimalImport), LastDiagFromFrom(false)
04563 {
04564   ImportedDecls[FromContext.getTranslationUnitDecl()]
04565     = ToContext.getTranslationUnitDecl();
04566 }
04567 
04568 ASTImporter::~ASTImporter() { }
04569 
04570 QualType ASTImporter::Import(QualType FromT) {
04571   if (FromT.isNull())
04572     return QualType();
04573 
04574   const Type *fromTy = FromT.getTypePtr();
04575   
04576   // Check whether we've already imported this type.  
04577   llvm::DenseMap<const Type *, const Type *>::iterator Pos
04578     = ImportedTypes.find(fromTy);
04579   if (Pos != ImportedTypes.end())
04580     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
04581   
04582   // Import the type
04583   ASTNodeImporter Importer(*this);
04584   QualType ToT = Importer.Visit(fromTy);
04585   if (ToT.isNull())
04586     return ToT;
04587   
04588   // Record the imported type.
04589   ImportedTypes[fromTy] = ToT.getTypePtr();
04590   
04591   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
04592 }
04593 
04594 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
04595   if (!FromTSI)
04596     return FromTSI;
04597 
04598   // FIXME: For now we just create a "trivial" type source info based
04599   // on the type and a single location. Implement a real version of this.
04600   QualType T = Import(FromTSI->getType());
04601   if (T.isNull())
04602     return nullptr;
04603 
04604   return ToContext.getTrivialTypeSourceInfo(T, 
04605                         FromTSI->getTypeLoc().getLocStart());
04606 }
04607 
04608 Decl *ASTImporter::Import(Decl *FromD) {
04609   if (!FromD)
04610     return nullptr;
04611 
04612   ASTNodeImporter Importer(*this);
04613 
04614   // Check whether we've already imported this declaration.  
04615   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
04616   if (Pos != ImportedDecls.end()) {
04617     Decl *ToD = Pos->second;
04618     Importer.ImportDefinitionIfNeeded(FromD, ToD);
04619     return ToD;
04620   }
04621   
04622   // Import the type
04623   Decl *ToD = Importer.Visit(FromD);
04624   if (!ToD)
04625     return nullptr;
04626 
04627   // Record the imported declaration.
04628   ImportedDecls[FromD] = ToD;
04629   
04630   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
04631     // Keep track of anonymous tags that have an associated typedef.
04632     if (FromTag->getTypedefNameForAnonDecl())
04633       AnonTagsWithPendingTypedefs.push_back(FromTag);
04634   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
04635     // When we've finished transforming a typedef, see whether it was the
04636     // typedef for an anonymous tag.
04637     for (SmallVectorImpl<TagDecl *>::iterator
04638                FromTag = AnonTagsWithPendingTypedefs.begin(), 
04639             FromTagEnd = AnonTagsWithPendingTypedefs.end();
04640          FromTag != FromTagEnd; ++FromTag) {
04641       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
04642         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
04643           // We found the typedef for an anonymous tag; link them.
04644           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
04645           AnonTagsWithPendingTypedefs.erase(FromTag);
04646           break;
04647         }
04648       }
04649     }
04650   }
04651   
04652   return ToD;
04653 }
04654 
04655 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
04656   if (!FromDC)
04657     return FromDC;
04658 
04659   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
04660   if (!ToDC)
04661     return nullptr;
04662 
04663   // When we're using a record/enum/Objective-C class/protocol as a context, we 
04664   // need it to have a definition.
04665   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
04666     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
04667     if (ToRecord->isCompleteDefinition()) {
04668       // Do nothing.
04669     } else if (FromRecord->isCompleteDefinition()) {
04670       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
04671                                               ASTNodeImporter::IDK_Basic);
04672     } else {
04673       CompleteDecl(ToRecord);
04674     }
04675   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
04676     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
04677     if (ToEnum->isCompleteDefinition()) {
04678       // Do nothing.
04679     } else if (FromEnum->isCompleteDefinition()) {
04680       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
04681                                               ASTNodeImporter::IDK_Basic);
04682     } else {
04683       CompleteDecl(ToEnum);
04684     }    
04685   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
04686     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
04687     if (ToClass->getDefinition()) {
04688       // Do nothing.
04689     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
04690       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
04691                                               ASTNodeImporter::IDK_Basic);
04692     } else {
04693       CompleteDecl(ToClass);
04694     }
04695   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
04696     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
04697     if (ToProto->getDefinition()) {
04698       // Do nothing.
04699     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
04700       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
04701                                               ASTNodeImporter::IDK_Basic);
04702     } else {
04703       CompleteDecl(ToProto);
04704     }    
04705   }
04706   
04707   return ToDC;
04708 }
04709 
04710 Expr *ASTImporter::Import(Expr *FromE) {
04711   if (!FromE)
04712     return nullptr;
04713 
04714   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
04715 }
04716 
04717 Stmt *ASTImporter::Import(Stmt *FromS) {
04718   if (!FromS)
04719     return nullptr;
04720 
04721   // Check whether we've already imported this declaration.  
04722   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
04723   if (Pos != ImportedStmts.end())
04724     return Pos->second;
04725   
04726   // Import the type
04727   ASTNodeImporter Importer(*this);
04728   Stmt *ToS = Importer.Visit(FromS);
04729   if (!ToS)
04730     return nullptr;
04731 
04732   // Record the imported declaration.
04733   ImportedStmts[FromS] = ToS;
04734   return ToS;
04735 }
04736 
04737 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
04738   if (!FromNNS)
04739     return nullptr;
04740 
04741   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
04742 
04743   switch (FromNNS->getKind()) {
04744   case NestedNameSpecifier::Identifier:
04745     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
04746       return NestedNameSpecifier::Create(ToContext, prefix, II);
04747     }
04748     return nullptr;
04749 
04750   case NestedNameSpecifier::Namespace:
04751     if (NamespaceDecl *NS = 
04752           cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
04753       return NestedNameSpecifier::Create(ToContext, prefix, NS);
04754     }
04755     return nullptr;
04756 
04757   case NestedNameSpecifier::NamespaceAlias:
04758     if (NamespaceAliasDecl *NSAD = 
04759           cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
04760       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
04761     }
04762     return nullptr;
04763 
04764   case NestedNameSpecifier::Global:
04765     return NestedNameSpecifier::GlobalSpecifier(ToContext);
04766 
04767   case NestedNameSpecifier::Super:
04768     if (CXXRecordDecl *RD =
04769             cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
04770       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
04771     }
04772     return nullptr;
04773 
04774   case NestedNameSpecifier::TypeSpec:
04775   case NestedNameSpecifier::TypeSpecWithTemplate: {
04776       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
04777       if (!T.isNull()) {
04778         bool bTemplate = FromNNS->getKind() == 
04779                          NestedNameSpecifier::TypeSpecWithTemplate;
04780         return NestedNameSpecifier::Create(ToContext, prefix, 
04781                                            bTemplate, T.getTypePtr());
04782       }
04783     }
04784       return nullptr;
04785   }
04786 
04787   llvm_unreachable("Invalid nested name specifier kind");
04788 }
04789 
04790 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
04791   // FIXME: Implement!
04792   return NestedNameSpecifierLoc();
04793 }
04794 
04795 TemplateName ASTImporter::Import(TemplateName From) {
04796   switch (From.getKind()) {
04797   case TemplateName::Template:
04798     if (TemplateDecl *ToTemplate
04799                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
04800       return TemplateName(ToTemplate);
04801       
04802     return TemplateName();
04803       
04804   case TemplateName::OverloadedTemplate: {
04805     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
04806     UnresolvedSet<2> ToTemplates;
04807     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
04808                                              E = FromStorage->end();
04809          I != E; ++I) {
04810       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I))) 
04811         ToTemplates.addDecl(To);
04812       else
04813         return TemplateName();
04814     }
04815     return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 
04816                                                ToTemplates.end());
04817   }
04818       
04819   case TemplateName::QualifiedTemplate: {
04820     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
04821     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
04822     if (!Qualifier)
04823       return TemplateName();
04824     
04825     if (TemplateDecl *ToTemplate
04826         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
04827       return ToContext.getQualifiedTemplateName(Qualifier, 
04828                                                 QTN->hasTemplateKeyword(), 
04829                                                 ToTemplate);
04830     
04831     return TemplateName();
04832   }
04833   
04834   case TemplateName::DependentTemplate: {
04835     DependentTemplateName *DTN = From.getAsDependentTemplateName();
04836     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
04837     if (!Qualifier)
04838       return TemplateName();
04839     
04840     if (DTN->isIdentifier()) {
04841       return ToContext.getDependentTemplateName(Qualifier, 
04842                                                 Import(DTN->getIdentifier()));
04843     }
04844     
04845     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
04846   }
04847 
04848   case TemplateName::SubstTemplateTemplateParm: {
04849     SubstTemplateTemplateParmStorage *subst
04850       = From.getAsSubstTemplateTemplateParm();
04851     TemplateTemplateParmDecl *param
04852       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
04853     if (!param)
04854       return TemplateName();
04855 
04856     TemplateName replacement = Import(subst->getReplacement());
04857     if (replacement.isNull()) return TemplateName();
04858     
04859     return ToContext.getSubstTemplateTemplateParm(param, replacement);
04860   }
04861       
04862   case TemplateName::SubstTemplateTemplateParmPack: {
04863     SubstTemplateTemplateParmPackStorage *SubstPack
04864       = From.getAsSubstTemplateTemplateParmPack();
04865     TemplateTemplateParmDecl *Param
04866       = cast_or_null<TemplateTemplateParmDecl>(
04867                                         Import(SubstPack->getParameterPack()));
04868     if (!Param)
04869       return TemplateName();
04870     
04871     ASTNodeImporter Importer(*this);
04872     TemplateArgument ArgPack 
04873       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
04874     if (ArgPack.isNull())
04875       return TemplateName();
04876     
04877     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
04878   }
04879   }
04880   
04881   llvm_unreachable("Invalid template name kind");
04882 }
04883 
04884 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
04885   if (FromLoc.isInvalid())
04886     return SourceLocation();
04887 
04888   SourceManager &FromSM = FromContext.getSourceManager();
04889   
04890   // For now, map everything down to its spelling location, so that we
04891   // don't have to import macro expansions.
04892   // FIXME: Import macro expansions!
04893   FromLoc = FromSM.getSpellingLoc(FromLoc);
04894   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
04895   SourceManager &ToSM = ToContext.getSourceManager();
04896   return ToSM.getLocForStartOfFile(Import(Decomposed.first))
04897              .getLocWithOffset(Decomposed.second);
04898 }
04899 
04900 SourceRange ASTImporter::Import(SourceRange FromRange) {
04901   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
04902 }
04903 
04904 FileID ASTImporter::Import(FileID FromID) {
04905   llvm::DenseMap<FileID, FileID>::iterator Pos
04906     = ImportedFileIDs.find(FromID);
04907   if (Pos != ImportedFileIDs.end())
04908     return Pos->second;
04909   
04910   SourceManager &FromSM = FromContext.getSourceManager();
04911   SourceManager &ToSM = ToContext.getSourceManager();
04912   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
04913   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
04914   
04915   // Include location of this file.
04916   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
04917   
04918   // Map the FileID for to the "to" source manager.
04919   FileID ToID;
04920   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
04921   if (Cache->OrigEntry) {
04922     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
04923     // disk again
04924     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
04925     // than mmap the files several times.
04926     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
04927     ToID = ToSM.createFileID(Entry, ToIncludeLoc, 
04928                              FromSLoc.getFile().getFileCharacteristic());
04929   } else {
04930     // FIXME: We want to re-use the existing MemoryBuffer!
04931     const llvm::MemoryBuffer *
04932         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
04933     std::unique_ptr<llvm::MemoryBuffer> ToBuf
04934       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
04935                                              FromBuf->getBufferIdentifier());
04936     ToID = ToSM.createFileID(std::move(ToBuf),
04937                              FromSLoc.getFile().getFileCharacteristic());
04938   }
04939   
04940   
04941   ImportedFileIDs[FromID] = ToID;
04942   return ToID;
04943 }
04944 
04945 void ASTImporter::ImportDefinition(Decl *From) {
04946   Decl *To = Import(From);
04947   if (!To)
04948     return;
04949   
04950   if (DeclContext *FromDC = cast<DeclContext>(From)) {
04951     ASTNodeImporter Importer(*this);
04952       
04953     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
04954       if (!ToRecord->getDefinition()) {
04955         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord, 
04956                                   ASTNodeImporter::IDK_Everything);
04957         return;
04958       }      
04959     }
04960 
04961     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
04962       if (!ToEnum->getDefinition()) {
04963         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum, 
04964                                   ASTNodeImporter::IDK_Everything);
04965         return;
04966       }      
04967     }
04968     
04969     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
04970       if (!ToIFace->getDefinition()) {
04971         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
04972                                   ASTNodeImporter::IDK_Everything);
04973         return;
04974       }
04975     }
04976 
04977     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
04978       if (!ToProto->getDefinition()) {
04979         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
04980                                   ASTNodeImporter::IDK_Everything);
04981         return;
04982       }
04983     }
04984     
04985     Importer.ImportDeclContext(FromDC, true);
04986   }
04987 }
04988 
04989 DeclarationName ASTImporter::Import(DeclarationName FromName) {
04990   if (!FromName)
04991     return DeclarationName();
04992 
04993   switch (FromName.getNameKind()) {
04994   case DeclarationName::Identifier:
04995     return Import(FromName.getAsIdentifierInfo());
04996 
04997   case DeclarationName::ObjCZeroArgSelector:
04998   case DeclarationName::ObjCOneArgSelector:
04999   case DeclarationName::ObjCMultiArgSelector:
05000     return Import(FromName.getObjCSelector());
05001 
05002   case DeclarationName::CXXConstructorName: {
05003     QualType T = Import(FromName.getCXXNameType());
05004     if (T.isNull())
05005       return DeclarationName();
05006 
05007     return ToContext.DeclarationNames.getCXXConstructorName(
05008                                                ToContext.getCanonicalType(T));
05009   }
05010 
05011   case DeclarationName::CXXDestructorName: {
05012     QualType T = Import(FromName.getCXXNameType());
05013     if (T.isNull())
05014       return DeclarationName();
05015 
05016     return ToContext.DeclarationNames.getCXXDestructorName(
05017                                                ToContext.getCanonicalType(T));
05018   }
05019 
05020   case DeclarationName::CXXConversionFunctionName: {
05021     QualType T = Import(FromName.getCXXNameType());
05022     if (T.isNull())
05023       return DeclarationName();
05024 
05025     return ToContext.DeclarationNames.getCXXConversionFunctionName(
05026                                                ToContext.getCanonicalType(T));
05027   }
05028 
05029   case DeclarationName::CXXOperatorName:
05030     return ToContext.DeclarationNames.getCXXOperatorName(
05031                                           FromName.getCXXOverloadedOperator());
05032 
05033   case DeclarationName::CXXLiteralOperatorName:
05034     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
05035                                    Import(FromName.getCXXLiteralIdentifier()));
05036 
05037   case DeclarationName::CXXUsingDirective:
05038     // FIXME: STATICS!
05039     return DeclarationName::getUsingDirectiveName();
05040   }
05041 
05042   llvm_unreachable("Invalid DeclarationName Kind!");
05043 }
05044 
05045 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
05046   if (!FromId)
05047     return nullptr;
05048 
05049   return &ToContext.Idents.get(FromId->getName());
05050 }
05051 
05052 Selector ASTImporter::Import(Selector FromSel) {
05053   if (FromSel.isNull())
05054     return Selector();
05055 
05056   SmallVector<IdentifierInfo *, 4> Idents;
05057   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
05058   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
05059     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
05060   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
05061 }
05062 
05063 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
05064                                                 DeclContext *DC,
05065                                                 unsigned IDNS,
05066                                                 NamedDecl **Decls,
05067                                                 unsigned NumDecls) {
05068   return Name;
05069 }
05070 
05071 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
05072   if (LastDiagFromFrom)
05073     ToContext.getDiagnostics().notePriorDiagnosticFrom(
05074       FromContext.getDiagnostics());
05075   LastDiagFromFrom = false;
05076   return ToContext.getDiagnostics().Report(Loc, DiagID);
05077 }
05078 
05079 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
05080   if (!LastDiagFromFrom)
05081     FromContext.getDiagnostics().notePriorDiagnosticFrom(
05082       ToContext.getDiagnostics());
05083   LastDiagFromFrom = true;
05084   return FromContext.getDiagnostics().Report(Loc, DiagID);
05085 }
05086 
05087 void ASTImporter::CompleteDecl (Decl *D) {
05088   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
05089     if (!ID->getDefinition())
05090       ID->startDefinition();
05091   }
05092   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
05093     if (!PD->getDefinition())
05094       PD->startDefinition();
05095   }
05096   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
05097     if (!TD->getDefinition() && !TD->isBeingDefined()) {
05098       TD->startDefinition();
05099       TD->setCompleteDefinition(true);
05100     }
05101   }
05102   else {
05103     assert (0 && "CompleteDecl called on a Decl that can't be completed");
05104   }
05105 }
05106 
05107 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
05108   ImportedDecls[From] = To;
05109   return To;
05110 }
05111 
05112 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
05113                                            bool Complain) {
05114   llvm::DenseMap<const Type *, const Type *>::iterator Pos
05115    = ImportedTypes.find(From.getTypePtr());
05116   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
05117     return true;
05118       
05119   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
05120                                    false, Complain);
05121   return Ctx.IsStructurallyEquivalent(From, To);
05122 }