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