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