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