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