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