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