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