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