1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the ASTImporter class which imports AST nodes from one
11 // context into another context.
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
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/TypeLoc.h"
23 #include "clang/AST/TypeVisitor.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/SourceManager.h"
26 #include "llvm/Support/MemoryBuffer.h"
29 using namespace clang;
32 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
33 public DeclVisitor<ASTNodeImporter, Decl *>,
34 public StmtVisitor<ASTNodeImporter, Stmt *> {
35 ASTImporter &Importer;
38 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
40 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
41 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
42 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
45 QualType VisitType(Type *T);
46 QualType VisitBuiltinType(BuiltinType *T);
47 QualType VisitComplexType(ComplexType *T);
48 QualType VisitPointerType(PointerType *T);
49 QualType VisitBlockPointerType(BlockPointerType *T);
50 QualType VisitLValueReferenceType(LValueReferenceType *T);
51 QualType VisitRValueReferenceType(RValueReferenceType *T);
52 QualType VisitMemberPointerType(MemberPointerType *T);
53 QualType VisitConstantArrayType(ConstantArrayType *T);
54 QualType VisitIncompleteArrayType(IncompleteArrayType *T);
55 QualType VisitVariableArrayType(VariableArrayType *T);
56 // FIXME: DependentSizedArrayType
57 // FIXME: DependentSizedExtVectorType
58 QualType VisitVectorType(VectorType *T);
59 QualType VisitExtVectorType(ExtVectorType *T);
60 QualType VisitFunctionNoProtoType(FunctionNoProtoType *T);
61 QualType VisitFunctionProtoType(FunctionProtoType *T);
62 // FIXME: UnresolvedUsingType
63 QualType VisitTypedefType(TypedefType *T);
64 QualType VisitTypeOfExprType(TypeOfExprType *T);
65 // FIXME: DependentTypeOfExprType
66 QualType VisitTypeOfType(TypeOfType *T);
67 QualType VisitDecltypeType(DecltypeType *T);
68 // FIXME: DependentDecltypeType
69 QualType VisitRecordType(RecordType *T);
70 QualType VisitEnumType(EnumType *T);
71 QualType VisitElaboratedType(ElaboratedType *T);
72 // FIXME: TemplateTypeParmType
73 // FIXME: SubstTemplateTypeParmType
74 // FIXME: TemplateSpecializationType
75 QualType VisitQualifiedNameType(QualifiedNameType *T);
76 // FIXME: TypenameType
77 QualType VisitObjCInterfaceType(ObjCInterfaceType *T);
78 QualType VisitObjCObjectPointerType(ObjCObjectPointerType *T);
80 // Importing declarations
81 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
82 DeclContext *&LexicalDC, DeclarationName &Name,
84 void ImportDeclContext(DeclContext *FromDC);
85 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord);
86 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
87 Decl *VisitDecl(Decl *D);
88 Decl *VisitNamespaceDecl(NamespaceDecl *D);
89 Decl *VisitTypedefDecl(TypedefDecl *D);
90 Decl *VisitEnumDecl(EnumDecl *D);
91 Decl *VisitRecordDecl(RecordDecl *D);
92 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
93 Decl *VisitFunctionDecl(FunctionDecl *D);
94 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
95 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
96 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
97 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
98 Decl *VisitFieldDecl(FieldDecl *D);
99 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
100 Decl *VisitVarDecl(VarDecl *D);
101 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
102 Decl *VisitParmVarDecl(ParmVarDecl *D);
103 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
104 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
105 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
106 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
107 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
108 Decl *VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
109 Decl *VisitObjCClassDecl(ObjCClassDecl *D);
111 // Importing statements
112 Stmt *VisitStmt(Stmt *S);
114 // Importing expressions
115 Expr *VisitExpr(Expr *E);
116 Expr *VisitDeclRefExpr(DeclRefExpr *E);
117 Expr *VisitIntegerLiteral(IntegerLiteral *E);
118 Expr *VisitCharacterLiteral(CharacterLiteral *E);
119 Expr *VisitParenExpr(ParenExpr *E);
120 Expr *VisitUnaryOperator(UnaryOperator *E);
121 Expr *VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E);
122 Expr *VisitBinaryOperator(BinaryOperator *E);
123 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
124 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
125 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
129 //----------------------------------------------------------------------------
130 // Structural Equivalence
131 //----------------------------------------------------------------------------
134 struct StructuralEquivalenceContext {
135 /// \brief AST contexts for which we are checking structural equivalence.
138 /// \brief Diagnostic object used to emit diagnostics.
141 /// \brief The set of "tentative" equivalences between two canonical
142 /// declarations, mapping from a declaration in the first context to the
143 /// declaration in the second context that we believe to be equivalent.
144 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
146 /// \brief Queue of declarations in the first context whose equivalence
147 /// with a declaration in the second context still needs to be verified.
148 std::deque<Decl *> DeclsToCheck;
150 /// \brief Declaration (from, to) pairs that are known not to be equivalent
151 /// (which we have already complained about).
152 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
154 /// \brief Whether we're being strict about the spelling of types when
155 /// unifying two types.
156 bool StrictTypeSpelling;
158 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
160 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
161 bool StrictTypeSpelling = false)
162 : C1(C1), C2(C2), Diags(Diags), NonEquivalentDecls(NonEquivalentDecls),
163 StrictTypeSpelling(StrictTypeSpelling) { }
165 /// \brief Determine whether the two declarations are structurally
167 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
169 /// \brief Determine whether the two types are structurally equivalent.
170 bool IsStructurallyEquivalent(QualType T1, QualType T2);
173 /// \brief Finish checking all of the structural equivalences.
175 /// \returns true if an error occurred, false otherwise.
179 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
180 return Diags.Report(FullSourceLoc(Loc, C1.getSourceManager()), DiagID);
183 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
184 return Diags.Report(FullSourceLoc(Loc, C2.getSourceManager()), DiagID);
189 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
190 QualType T1, QualType T2);
191 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
194 /// \brief Determine if two APInts have the same value, after zero-extending
195 /// one of them (if needed!) to ensure that the bit-widths match.
196 static bool IsSameValue(const llvm::APInt &I1, const llvm::APInt &I2) {
197 if (I1.getBitWidth() == I2.getBitWidth())
200 if (I1.getBitWidth() > I2.getBitWidth())
201 return I1 == llvm::APInt(I2).zext(I1.getBitWidth());
203 return llvm::APInt(I1).zext(I2.getBitWidth()) == I2;
206 /// \brief Determine if two APSInts have the same value, zero- or sign-extending
208 static bool IsSameValue(const llvm::APSInt &I1, const llvm::APSInt &I2) {
209 if (I1.getBitWidth() == I2.getBitWidth() && I1.isSigned() == I2.isSigned())
212 // Check for a bit-width mismatch.
213 if (I1.getBitWidth() > I2.getBitWidth())
214 return IsSameValue(I1, llvm::APSInt(I2).extend(I1.getBitWidth()));
215 else if (I2.getBitWidth() > I1.getBitWidth())
216 return IsSameValue(llvm::APSInt(I1).extend(I2.getBitWidth()), I2);
218 // We have a signedness mismatch. Turn the signed value into an unsigned
224 return llvm::APSInt(I1, true) == I2;
230 return I1 == llvm::APSInt(I2, true);
233 /// \brief Determine structural equivalence of two expressions.
234 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
235 Expr *E1, Expr *E2) {
239 // FIXME: Actually perform a structural comparison!
243 /// \brief Determine whether two identifiers are equivalent.
244 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
245 const IdentifierInfo *Name2) {
246 if (!Name1 || !Name2)
247 return Name1 == Name2;
249 return Name1->getName() == Name2->getName();
252 /// \brief Determine whether two nested-name-specifiers are equivalent.
253 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
254 NestedNameSpecifier *NNS1,
255 NestedNameSpecifier *NNS2) {
260 /// \brief Determine whether two template arguments are equivalent.
261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
262 const TemplateArgument &Arg1,
263 const TemplateArgument &Arg2) {
268 /// \brief Determine structural equivalence for the common part of array
270 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
271 const ArrayType *Array1,
272 const ArrayType *Array2) {
273 if (!IsStructurallyEquivalent(Context,
274 Array1->getElementType(),
275 Array2->getElementType()))
277 if (Array1->getSizeModifier() != Array2->getSizeModifier())
279 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
285 /// \brief Determine structural equivalence of two types.
286 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
287 QualType T1, QualType T2) {
288 if (T1.isNull() || T2.isNull())
289 return T1.isNull() && T2.isNull();
291 if (!Context.StrictTypeSpelling) {
292 // We aren't being strict about token-to-token equivalence of types,
293 // so map down to the canonical type.
294 T1 = Context.C1.getCanonicalType(T1);
295 T2 = Context.C2.getCanonicalType(T2);
298 if (T1.getQualifiers() != T2.getQualifiers())
301 Type::TypeClass TC = T1->getTypeClass();
303 if (T1->getTypeClass() != T2->getTypeClass()) {
304 // Compare function types with prototypes vs. without prototypes as if
305 // both did not have prototypes.
306 if (T1->getTypeClass() == Type::FunctionProto &&
307 T2->getTypeClass() == Type::FunctionNoProto)
308 TC = Type::FunctionNoProto;
309 else if (T1->getTypeClass() == Type::FunctionNoProto &&
310 T2->getTypeClass() == Type::FunctionProto)
311 TC = Type::FunctionNoProto;
318 // FIXME: Deal with Char_S/Char_U.
319 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
324 if (!IsStructurallyEquivalent(Context,
325 cast<ComplexType>(T1)->getElementType(),
326 cast<ComplexType>(T2)->getElementType()))
331 if (!IsStructurallyEquivalent(Context,
332 cast<PointerType>(T1)->getPointeeType(),
333 cast<PointerType>(T2)->getPointeeType()))
337 case Type::BlockPointer:
338 if (!IsStructurallyEquivalent(Context,
339 cast<BlockPointerType>(T1)->getPointeeType(),
340 cast<BlockPointerType>(T2)->getPointeeType()))
344 case Type::LValueReference:
345 case Type::RValueReference: {
346 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
347 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
348 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
350 if (Ref1->isInnerRef() != Ref2->isInnerRef())
352 if (!IsStructurallyEquivalent(Context,
353 Ref1->getPointeeTypeAsWritten(),
354 Ref2->getPointeeTypeAsWritten()))
359 case Type::MemberPointer: {
360 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
361 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
362 if (!IsStructurallyEquivalent(Context,
363 MemPtr1->getPointeeType(),
364 MemPtr2->getPointeeType()))
366 if (!IsStructurallyEquivalent(Context,
367 QualType(MemPtr1->getClass(), 0),
368 QualType(MemPtr2->getClass(), 0)))
373 case Type::ConstantArray: {
374 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
375 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
376 if (!IsSameValue(Array1->getSize(), Array2->getSize()))
379 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
384 case Type::IncompleteArray:
385 if (!IsArrayStructurallyEquivalent(Context,
387 cast<ArrayType>(T2)))
391 case Type::VariableArray: {
392 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
393 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
394 if (!IsStructurallyEquivalent(Context,
395 Array1->getSizeExpr(), Array2->getSizeExpr()))
398 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
404 case Type::DependentSizedArray: {
405 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
406 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
407 if (!IsStructurallyEquivalent(Context,
408 Array1->getSizeExpr(), Array2->getSizeExpr()))
411 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
417 case Type::DependentSizedExtVector: {
418 const DependentSizedExtVectorType *Vec1
419 = cast<DependentSizedExtVectorType>(T1);
420 const DependentSizedExtVectorType *Vec2
421 = cast<DependentSizedExtVectorType>(T2);
422 if (!IsStructurallyEquivalent(Context,
423 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
425 if (!IsStructurallyEquivalent(Context,
426 Vec1->getElementType(),
427 Vec2->getElementType()))
433 case Type::ExtVector: {
434 const VectorType *Vec1 = cast<VectorType>(T1);
435 const VectorType *Vec2 = cast<VectorType>(T2);
436 if (!IsStructurallyEquivalent(Context,
437 Vec1->getElementType(),
438 Vec2->getElementType()))
440 if (Vec1->getNumElements() != Vec2->getNumElements())
442 if (Vec1->isAltiVec() != Vec2->isAltiVec())
444 if (Vec1->isPixel() != Vec2->isPixel())
449 case Type::FunctionProto: {
450 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
451 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
452 if (Proto1->getNumArgs() != Proto2->getNumArgs())
454 for (unsigned I = 0, N = Proto1->getNumArgs(); I != N; ++I) {
455 if (!IsStructurallyEquivalent(Context,
456 Proto1->getArgType(I),
457 Proto2->getArgType(I)))
460 if (Proto1->isVariadic() != Proto2->isVariadic())
462 if (Proto1->hasExceptionSpec() != Proto2->hasExceptionSpec())
464 if (Proto1->hasAnyExceptionSpec() != Proto2->hasAnyExceptionSpec())
466 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
468 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
469 if (!IsStructurallyEquivalent(Context,
470 Proto1->getExceptionType(I),
471 Proto2->getExceptionType(I)))
474 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
477 // Fall through to check the bits common with FunctionNoProtoType.
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()))
487 if (Function1->getNoReturnAttr() != Function2->getNoReturnAttr())
489 if (Function1->getCallConv() != Function2->getCallConv())
494 case Type::UnresolvedUsing:
495 if (!IsStructurallyEquivalent(Context,
496 cast<UnresolvedUsingType>(T1)->getDecl(),
497 cast<UnresolvedUsingType>(T2)->getDecl()))
503 if (!IsStructurallyEquivalent(Context,
504 cast<TypedefType>(T1)->getDecl(),
505 cast<TypedefType>(T2)->getDecl()))
509 case Type::TypeOfExpr:
510 if (!IsStructurallyEquivalent(Context,
511 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
512 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
517 if (!IsStructurallyEquivalent(Context,
518 cast<TypeOfType>(T1)->getUnderlyingType(),
519 cast<TypeOfType>(T2)->getUnderlyingType()))
524 if (!IsStructurallyEquivalent(Context,
525 cast<DecltypeType>(T1)->getUnderlyingExpr(),
526 cast<DecltypeType>(T2)->getUnderlyingExpr()))
532 if (!IsStructurallyEquivalent(Context,
533 cast<TagType>(T1)->getDecl(),
534 cast<TagType>(T2)->getDecl()))
538 case Type::Elaborated: {
539 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
540 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
541 if (Elab1->getTagKind() != Elab2->getTagKind())
543 if (!IsStructurallyEquivalent(Context,
544 Elab1->getUnderlyingType(),
545 Elab2->getUnderlyingType()))
550 case Type::TemplateTypeParm: {
551 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
552 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
553 if (Parm1->getDepth() != Parm2->getDepth())
555 if (Parm1->getIndex() != Parm2->getIndex())
557 if (Parm1->isParameterPack() != Parm2->isParameterPack())
560 // Names of template type parameters are never significant.
564 case Type::SubstTemplateTypeParm: {
565 const SubstTemplateTypeParmType *Subst1
566 = cast<SubstTemplateTypeParmType>(T1);
567 const SubstTemplateTypeParmType *Subst2
568 = cast<SubstTemplateTypeParmType>(T2);
569 if (!IsStructurallyEquivalent(Context,
570 QualType(Subst1->getReplacedParameter(), 0),
571 QualType(Subst2->getReplacedParameter(), 0)))
573 if (!IsStructurallyEquivalent(Context,
574 Subst1->getReplacementType(),
575 Subst2->getReplacementType()))
580 case Type::TemplateSpecialization: {
581 const TemplateSpecializationType *Spec1
582 = cast<TemplateSpecializationType>(T1);
583 const TemplateSpecializationType *Spec2
584 = cast<TemplateSpecializationType>(T2);
585 if (!IsStructurallyEquivalent(Context,
586 Spec1->getTemplateName(),
587 Spec2->getTemplateName()))
589 if (Spec1->getNumArgs() != Spec2->getNumArgs())
591 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
592 if (!IsStructurallyEquivalent(Context,
593 Spec1->getArg(I), Spec2->getArg(I)))
599 case Type::QualifiedName: {
600 const QualifiedNameType *Qual1 = cast<QualifiedNameType>(T1);
601 const QualifiedNameType *Qual2 = cast<QualifiedNameType>(T2);
602 if (!IsStructurallyEquivalent(Context,
603 Qual1->getQualifier(),
604 Qual2->getQualifier()))
606 if (!IsStructurallyEquivalent(Context,
607 Qual1->getNamedType(),
608 Qual2->getNamedType()))
613 case Type::Typename: {
614 const TypenameType *Typename1 = cast<TypenameType>(T1);
615 const TypenameType *Typename2 = cast<TypenameType>(T2);
616 if (!IsStructurallyEquivalent(Context,
617 Typename1->getQualifier(),
618 Typename2->getQualifier()))
620 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
621 Typename2->getIdentifier()))
623 if (!IsStructurallyEquivalent(Context,
624 QualType(Typename1->getTemplateId(), 0),
625 QualType(Typename2->getTemplateId(), 0)))
631 case Type::ObjCInterface: {
632 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
633 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
634 if (!IsStructurallyEquivalent(Context,
635 Iface1->getDecl(), Iface2->getDecl()))
637 if (Iface1->getNumProtocols() != Iface2->getNumProtocols())
639 for (unsigned I = 0, N = Iface1->getNumProtocols(); I != N; ++I) {
640 if (!IsStructurallyEquivalent(Context,
641 Iface1->getProtocol(I),
642 Iface2->getProtocol(I)))
648 case Type::ObjCObjectPointer: {
649 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
650 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
651 if (!IsStructurallyEquivalent(Context,
652 Ptr1->getPointeeType(),
653 Ptr2->getPointeeType()))
655 if (Ptr1->getNumProtocols() != Ptr2->getNumProtocols())
657 for (unsigned I = 0, N = Ptr1->getNumProtocols(); I != N; ++I) {
658 if (!IsStructurallyEquivalent(Context,
659 Ptr1->getProtocol(I),
660 Ptr2->getProtocol(I)))
671 /// \brief Determine structural equivalence of two records.
672 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
673 RecordDecl *D1, RecordDecl *D2) {
674 if (D1->isUnion() != D2->isUnion()) {
675 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
676 << Context.C2.getTypeDeclType(D2);
677 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
678 << D1->getDeclName() << (unsigned)D1->getTagKind();
682 // Compare the definitions of these two records. If either or both are
683 // incomplete, we assume that they are equivalent.
684 D1 = D1->getDefinition();
685 D2 = D2->getDefinition();
689 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
690 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
691 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
692 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
693 << Context.C2.getTypeDeclType(D2);
694 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
695 << D2CXX->getNumBases();
696 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
697 << D1CXX->getNumBases();
701 // Check the base classes.
702 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
703 BaseEnd1 = D1CXX->bases_end(),
704 Base2 = D2CXX->bases_begin();
707 if (!IsStructurallyEquivalent(Context,
708 Base1->getType(), Base2->getType())) {
709 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
710 << Context.C2.getTypeDeclType(D2);
711 Context.Diag2(Base2->getSourceRange().getBegin(), diag::note_odr_base)
713 << Base2->getSourceRange();
714 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
716 << Base1->getSourceRange();
720 // Check virtual vs. non-virtual inheritance mismatch.
721 if (Base1->isVirtual() != Base2->isVirtual()) {
722 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
723 << Context.C2.getTypeDeclType(D2);
724 Context.Diag2(Base2->getSourceRange().getBegin(),
725 diag::note_odr_virtual_base)
726 << Base2->isVirtual() << Base2->getSourceRange();
727 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
728 << Base1->isVirtual()
729 << Base1->getSourceRange();
733 } else if (D1CXX->getNumBases() > 0) {
734 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
735 << Context.C2.getTypeDeclType(D2);
736 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
737 Context.Diag1(Base1->getSourceRange().getBegin(), diag::note_odr_base)
739 << Base1->getSourceRange();
740 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
745 // Check the fields for consistency.
746 CXXRecordDecl::field_iterator Field2 = D2->field_begin(),
747 Field2End = D2->field_end();
748 for (CXXRecordDecl::field_iterator Field1 = D1->field_begin(),
749 Field1End = D1->field_end();
751 ++Field1, ++Field2) {
752 if (Field2 == Field2End) {
753 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
754 << Context.C2.getTypeDeclType(D2);
755 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
756 << Field1->getDeclName() << Field1->getType();
757 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
761 if (!IsStructurallyEquivalent(Context,
762 Field1->getType(), Field2->getType())) {
763 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
764 << Context.C2.getTypeDeclType(D2);
765 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
766 << Field2->getDeclName() << Field2->getType();
767 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
768 << Field1->getDeclName() << Field1->getType();
772 if (Field1->isBitField() != Field2->isBitField()) {
773 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
774 << Context.C2.getTypeDeclType(D2);
775 if (Field1->isBitField()) {
777 Field1->getBitWidth()->isIntegerConstantExpr(Bits, Context.C1);
778 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
779 << Field1->getDeclName() << Field1->getType()
780 << Bits.toString(10, false);
781 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
782 << Field2->getDeclName();
785 Field2->getBitWidth()->isIntegerConstantExpr(Bits, Context.C2);
786 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
787 << Field2->getDeclName() << Field2->getType()
788 << Bits.toString(10, false);
789 Context.Diag1(Field1->getLocation(),
790 diag::note_odr_not_bit_field)
791 << Field1->getDeclName();
796 if (Field1->isBitField()) {
797 // Make sure that the bit-fields are the same length.
798 llvm::APSInt Bits1, Bits2;
799 if (!Field1->getBitWidth()->isIntegerConstantExpr(Bits1, Context.C1))
801 if (!Field2->getBitWidth()->isIntegerConstantExpr(Bits2, Context.C2))
804 if (!IsSameValue(Bits1, Bits2)) {
805 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
806 << Context.C2.getTypeDeclType(D2);
807 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
808 << Field2->getDeclName() << Field2->getType()
809 << Bits2.toString(10, false);
810 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
811 << Field1->getDeclName() << Field1->getType()
812 << Bits1.toString(10, false);
818 if (Field2 != Field2End) {
819 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
820 << Context.C2.getTypeDeclType(D2);
821 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
822 << Field2->getDeclName() << Field2->getType();
823 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
830 /// \brief Determine structural equivalence of two enums.
831 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
832 EnumDecl *D1, EnumDecl *D2) {
833 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
834 EC2End = D2->enumerator_end();
835 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
836 EC1End = D1->enumerator_end();
837 EC1 != EC1End; ++EC1, ++EC2) {
839 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
840 << Context.C2.getTypeDeclType(D2);
841 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
842 << EC1->getDeclName()
843 << EC1->getInitVal().toString(10);
844 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
848 llvm::APSInt Val1 = EC1->getInitVal();
849 llvm::APSInt Val2 = EC2->getInitVal();
850 if (!IsSameValue(Val1, Val2) ||
851 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
852 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
853 << Context.C2.getTypeDeclType(D2);
854 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
855 << EC2->getDeclName()
856 << EC2->getInitVal().toString(10);
857 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
858 << EC1->getDeclName()
859 << EC1->getInitVal().toString(10);
865 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
866 << Context.C2.getTypeDeclType(D2);
867 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
868 << EC2->getDeclName()
869 << EC2->getInitVal().toString(10);
870 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
877 /// \brief Determine structural equivalence of two declarations.
878 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
879 Decl *D1, Decl *D2) {
880 // FIXME: Check for known structural equivalences via a callback of some sort.
882 // Check whether we already know that these two declarations are not
883 // structurally equivalent.
884 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
885 D2->getCanonicalDecl())))
888 // Determine whether we've already produced a tentative equivalence for D1.
889 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
891 return EquivToD1 == D2->getCanonicalDecl();
893 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
894 EquivToD1 = D2->getCanonicalDecl();
895 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
899 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
901 if (!::IsStructurallyEquivalent(*this, D1, D2))
907 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
909 if (!::IsStructurallyEquivalent(*this, T1, T2))
915 bool StructuralEquivalenceContext::Finish() {
916 while (!DeclsToCheck.empty()) {
917 // Check the next declaration.
918 Decl *D1 = DeclsToCheck.front();
919 DeclsToCheck.pop_front();
921 Decl *D2 = TentativeEquivalences[D1];
922 assert(D2 && "Unrecorded tentative equivalence?");
924 bool Equivalent = true;
926 // FIXME: Switch on all declaration kinds. For now, we're just going to
927 // check the obvious ones.
928 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
929 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
930 // Check for equivalent structure names.
931 IdentifierInfo *Name1 = Record1->getIdentifier();
932 if (!Name1 && Record1->getTypedefForAnonDecl())
933 Name1 = Record1->getTypedefForAnonDecl()->getIdentifier();
934 IdentifierInfo *Name2 = Record2->getIdentifier();
935 if (!Name2 && Record2->getTypedefForAnonDecl())
936 Name2 = Record2->getTypedefForAnonDecl()->getIdentifier();
937 if (!::IsStructurallyEquivalent(Name1, Name2) ||
938 !::IsStructurallyEquivalent(*this, Record1, Record2))
941 // Record/non-record mismatch.
944 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
945 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
946 // Check for equivalent enum names.
947 IdentifierInfo *Name1 = Enum1->getIdentifier();
948 if (!Name1 && Enum1->getTypedefForAnonDecl())
949 Name1 = Enum1->getTypedefForAnonDecl()->getIdentifier();
950 IdentifierInfo *Name2 = Enum2->getIdentifier();
951 if (!Name2 && Enum2->getTypedefForAnonDecl())
952 Name2 = Enum2->getTypedefForAnonDecl()->getIdentifier();
953 if (!::IsStructurallyEquivalent(Name1, Name2) ||
954 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
957 // Enum/non-enum mismatch
960 } else if (TypedefDecl *Typedef1 = dyn_cast<TypedefDecl>(D1)) {
961 if (TypedefDecl *Typedef2 = dyn_cast<TypedefDecl>(D2)) {
962 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
963 Typedef2->getIdentifier()) ||
964 !::IsStructurallyEquivalent(*this,
965 Typedef1->getUnderlyingType(),
966 Typedef2->getUnderlyingType()))
969 // Typedef/non-typedef mismatch.
975 // Note that these two declarations are not equivalent (and we already
977 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
978 D2->getCanonicalDecl()));
981 // FIXME: Check other declaration kinds!
987 //----------------------------------------------------------------------------
989 //----------------------------------------------------------------------------
991 QualType ASTNodeImporter::VisitType(Type *T) {
992 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
993 << T->getTypeClassName();
997 QualType ASTNodeImporter::VisitBuiltinType(BuiltinType *T) {
998 switch (T->getKind()) {
999 case BuiltinType::Void: return Importer.getToContext().VoidTy;
1000 case BuiltinType::Bool: return Importer.getToContext().BoolTy;
1002 case BuiltinType::Char_U:
1003 // The context we're importing from has an unsigned 'char'. If we're
1004 // importing into a context with a signed 'char', translate to
1005 // 'unsigned char' instead.
1006 if (Importer.getToContext().getLangOptions().CharIsSigned)
1007 return Importer.getToContext().UnsignedCharTy;
1009 return Importer.getToContext().CharTy;
1011 case BuiltinType::UChar: return Importer.getToContext().UnsignedCharTy;
1013 case BuiltinType::Char16:
1014 // FIXME: Make sure that the "to" context supports C++!
1015 return Importer.getToContext().Char16Ty;
1017 case BuiltinType::Char32:
1018 // FIXME: Make sure that the "to" context supports C++!
1019 return Importer.getToContext().Char32Ty;
1021 case BuiltinType::UShort: return Importer.getToContext().UnsignedShortTy;
1022 case BuiltinType::UInt: return Importer.getToContext().UnsignedIntTy;
1023 case BuiltinType::ULong: return Importer.getToContext().UnsignedLongTy;
1024 case BuiltinType::ULongLong:
1025 return Importer.getToContext().UnsignedLongLongTy;
1026 case BuiltinType::UInt128: return Importer.getToContext().UnsignedInt128Ty;
1028 case BuiltinType::Char_S:
1029 // The context we're importing from has an unsigned 'char'. If we're
1030 // importing into a context with a signed 'char', translate to
1031 // 'unsigned char' instead.
1032 if (!Importer.getToContext().getLangOptions().CharIsSigned)
1033 return Importer.getToContext().SignedCharTy;
1035 return Importer.getToContext().CharTy;
1037 case BuiltinType::SChar: return Importer.getToContext().SignedCharTy;
1038 case BuiltinType::WChar:
1039 // FIXME: If not in C++, shall we translate to the C equivalent of
1041 return Importer.getToContext().WCharTy;
1043 case BuiltinType::Short : return Importer.getToContext().ShortTy;
1044 case BuiltinType::Int : return Importer.getToContext().IntTy;
1045 case BuiltinType::Long : return Importer.getToContext().LongTy;
1046 case BuiltinType::LongLong : return Importer.getToContext().LongLongTy;
1047 case BuiltinType::Int128 : return Importer.getToContext().Int128Ty;
1048 case BuiltinType::Float: return Importer.getToContext().FloatTy;
1049 case BuiltinType::Double: return Importer.getToContext().DoubleTy;
1050 case BuiltinType::LongDouble: return Importer.getToContext().LongDoubleTy;
1052 case BuiltinType::NullPtr:
1053 // FIXME: Make sure that the "to" context supports C++0x!
1054 return Importer.getToContext().NullPtrTy;
1056 case BuiltinType::Overload: return Importer.getToContext().OverloadTy;
1057 case BuiltinType::Dependent: return Importer.getToContext().DependentTy;
1058 case BuiltinType::UndeducedAuto:
1059 // FIXME: Make sure that the "to" context supports C++0x!
1060 return Importer.getToContext().UndeducedAutoTy;
1062 case BuiltinType::ObjCId:
1063 // FIXME: Make sure that the "to" context supports Objective-C!
1064 return Importer.getToContext().ObjCBuiltinIdTy;
1066 case BuiltinType::ObjCClass:
1067 return Importer.getToContext().ObjCBuiltinClassTy;
1069 case BuiltinType::ObjCSel:
1070 return Importer.getToContext().ObjCBuiltinSelTy;
1076 QualType ASTNodeImporter::VisitComplexType(ComplexType *T) {
1077 QualType ToElementType = Importer.Import(T->getElementType());
1078 if (ToElementType.isNull())
1081 return Importer.getToContext().getComplexType(ToElementType);
1084 QualType ASTNodeImporter::VisitPointerType(PointerType *T) {
1085 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1086 if (ToPointeeType.isNull())
1089 return Importer.getToContext().getPointerType(ToPointeeType);
1092 QualType ASTNodeImporter::VisitBlockPointerType(BlockPointerType *T) {
1093 // FIXME: Check for blocks support in "to" context.
1094 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1095 if (ToPointeeType.isNull())
1098 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1101 QualType ASTNodeImporter::VisitLValueReferenceType(LValueReferenceType *T) {
1102 // FIXME: Check for C++ support in "to" context.
1103 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1104 if (ToPointeeType.isNull())
1107 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1110 QualType ASTNodeImporter::VisitRValueReferenceType(RValueReferenceType *T) {
1111 // FIXME: Check for C++0x support in "to" context.
1112 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1113 if (ToPointeeType.isNull())
1116 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1119 QualType ASTNodeImporter::VisitMemberPointerType(MemberPointerType *T) {
1120 // FIXME: Check for C++ support in "to" context.
1121 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1122 if (ToPointeeType.isNull())
1125 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1126 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1127 ClassType.getTypePtr());
1130 QualType ASTNodeImporter::VisitConstantArrayType(ConstantArrayType *T) {
1131 QualType ToElementType = Importer.Import(T->getElementType());
1132 if (ToElementType.isNull())
1135 return Importer.getToContext().getConstantArrayType(ToElementType,
1137 T->getSizeModifier(),
1138 T->getIndexTypeCVRQualifiers());
1141 QualType ASTNodeImporter::VisitIncompleteArrayType(IncompleteArrayType *T) {
1142 QualType ToElementType = Importer.Import(T->getElementType());
1143 if (ToElementType.isNull())
1146 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1147 T->getSizeModifier(),
1148 T->getIndexTypeCVRQualifiers());
1151 QualType ASTNodeImporter::VisitVariableArrayType(VariableArrayType *T) {
1152 QualType ToElementType = Importer.Import(T->getElementType());
1153 if (ToElementType.isNull())
1156 Expr *Size = Importer.Import(T->getSizeExpr());
1160 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1161 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1162 T->getSizeModifier(),
1163 T->getIndexTypeCVRQualifiers(),
1167 QualType ASTNodeImporter::VisitVectorType(VectorType *T) {
1168 QualType ToElementType = Importer.Import(T->getElementType());
1169 if (ToElementType.isNull())
1172 return Importer.getToContext().getVectorType(ToElementType,
1173 T->getNumElements(),
1178 QualType ASTNodeImporter::VisitExtVectorType(ExtVectorType *T) {
1179 QualType ToElementType = Importer.Import(T->getElementType());
1180 if (ToElementType.isNull())
1183 return Importer.getToContext().getExtVectorType(ToElementType,
1184 T->getNumElements());
1187 QualType ASTNodeImporter::VisitFunctionNoProtoType(FunctionNoProtoType *T) {
1188 // FIXME: What happens if we're importing a function without a prototype
1189 // into C++? Should we make it variadic?
1190 QualType ToResultType = Importer.Import(T->getResultType());
1191 if (ToResultType.isNull())
1194 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1195 T->getNoReturnAttr(),
1199 QualType ASTNodeImporter::VisitFunctionProtoType(FunctionProtoType *T) {
1200 QualType ToResultType = Importer.Import(T->getResultType());
1201 if (ToResultType.isNull())
1204 // Import argument types
1205 llvm::SmallVector<QualType, 4> ArgTypes;
1206 for (FunctionProtoType::arg_type_iterator A = T->arg_type_begin(),
1207 AEnd = T->arg_type_end();
1209 QualType ArgType = Importer.Import(*A);
1210 if (ArgType.isNull())
1212 ArgTypes.push_back(ArgType);
1215 // Import exception types
1216 llvm::SmallVector<QualType, 4> ExceptionTypes;
1217 for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1218 EEnd = T->exception_end();
1220 QualType ExceptionType = Importer.Import(*E);
1221 if (ExceptionType.isNull())
1223 ExceptionTypes.push_back(ExceptionType);
1226 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes.data(),
1230 T->hasExceptionSpec(),
1231 T->hasAnyExceptionSpec(),
1232 ExceptionTypes.size(),
1233 ExceptionTypes.data(),
1234 T->getNoReturnAttr(),
1238 QualType ASTNodeImporter::VisitTypedefType(TypedefType *T) {
1240 = dyn_cast_or_null<TypedefDecl>(Importer.Import(T->getDecl()));
1244 return Importer.getToContext().getTypeDeclType(ToDecl);
1247 QualType ASTNodeImporter::VisitTypeOfExprType(TypeOfExprType *T) {
1248 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1252 return Importer.getToContext().getTypeOfExprType(ToExpr);
1255 QualType ASTNodeImporter::VisitTypeOfType(TypeOfType *T) {
1256 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1257 if (ToUnderlyingType.isNull())
1260 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1263 QualType ASTNodeImporter::VisitDecltypeType(DecltypeType *T) {
1264 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1268 return Importer.getToContext().getDecltypeType(ToExpr);
1271 QualType ASTNodeImporter::VisitRecordType(RecordType *T) {
1273 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1277 return Importer.getToContext().getTagDeclType(ToDecl);
1280 QualType ASTNodeImporter::VisitEnumType(EnumType *T) {
1282 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1286 return Importer.getToContext().getTagDeclType(ToDecl);
1289 QualType ASTNodeImporter::VisitElaboratedType(ElaboratedType *T) {
1290 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1291 if (ToUnderlyingType.isNull())
1294 return Importer.getToContext().getElaboratedType(ToUnderlyingType,
1298 QualType ASTNodeImporter::VisitQualifiedNameType(QualifiedNameType *T) {
1299 NestedNameSpecifier *ToQualifier = Importer.Import(T->getQualifier());
1303 QualType ToNamedType = Importer.Import(T->getNamedType());
1304 if (ToNamedType.isNull())
1307 return Importer.getToContext().getQualifiedNameType(ToQualifier, ToNamedType);
1310 QualType ASTNodeImporter::VisitObjCInterfaceType(ObjCInterfaceType *T) {
1311 ObjCInterfaceDecl *Class
1312 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1316 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
1317 for (ObjCInterfaceType::qual_iterator P = T->qual_begin(),
1318 PEnd = T->qual_end();
1320 ObjCProtocolDecl *Protocol
1321 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1324 Protocols.push_back(Protocol);
1327 return Importer.getToContext().getObjCInterfaceType(Class,
1332 QualType ASTNodeImporter::VisitObjCObjectPointerType(ObjCObjectPointerType *T) {
1333 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1334 if (ToPointeeType.isNull())
1337 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
1338 for (ObjCObjectPointerType::qual_iterator P = T->qual_begin(),
1339 PEnd = T->qual_end();
1341 ObjCProtocolDecl *Protocol
1342 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1345 Protocols.push_back(Protocol);
1348 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType,
1353 //----------------------------------------------------------------------------
1354 // Import Declarations
1355 //----------------------------------------------------------------------------
1356 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1357 DeclContext *&LexicalDC,
1358 DeclarationName &Name,
1359 SourceLocation &Loc) {
1360 // Import the context of this declaration.
1361 DC = Importer.ImportContext(D->getDeclContext());
1366 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1367 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1372 // Import the name of this declaration.
1373 Name = Importer.Import(D->getDeclName());
1374 if (D->getDeclName() && !Name)
1377 // Import the location of this declaration.
1378 Loc = Importer.Import(D->getLocation());
1382 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC) {
1383 for (DeclContext::decl_iterator From = FromDC->decls_begin(),
1384 FromEnd = FromDC->decls_end();
1387 Importer.Import(*From);
1390 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1391 RecordDecl *ToRecord) {
1392 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1393 Importer.getToContext(),
1394 Importer.getDiags(),
1395 Importer.getNonEquivalentDecls());
1396 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
1399 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1400 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1401 Importer.getToContext(),
1402 Importer.getDiags(),
1403 Importer.getNonEquivalentDecls());
1404 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
1407 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1408 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1409 << D->getDeclKindName();
1413 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1414 // Import the major distinguishing characteristics of this namespace.
1415 DeclContext *DC, *LexicalDC;
1416 DeclarationName Name;
1418 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1421 NamespaceDecl *MergeWithNamespace = 0;
1423 // This is an anonymous namespace. Adopt an existing anonymous
1424 // namespace if we can.
1425 // FIXME: Not testable.
1426 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1427 MergeWithNamespace = TU->getAnonymousNamespace();
1429 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1431 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1432 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1433 Lookup.first != Lookup.second;
1435 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
1438 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(*Lookup.first)) {
1439 MergeWithNamespace = FoundNS;
1440 ConflictingDecls.clear();
1444 ConflictingDecls.push_back(*Lookup.first);
1447 if (!ConflictingDecls.empty()) {
1448 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
1449 ConflictingDecls.data(),
1450 ConflictingDecls.size());
1454 // Create the "to" namespace, if needed.
1455 NamespaceDecl *ToNamespace = MergeWithNamespace;
1457 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC, Loc,
1458 Name.getAsIdentifierInfo());
1459 ToNamespace->setLexicalDeclContext(LexicalDC);
1460 LexicalDC->addDecl(ToNamespace);
1462 // If this is an anonymous namespace, register it as the anonymous
1463 // namespace within its context.
1465 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1466 TU->setAnonymousNamespace(ToNamespace);
1468 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1471 Importer.Imported(D, ToNamespace);
1473 ImportDeclContext(D);
1478 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
1479 // Import the major distinguishing characteristics of this typedef.
1480 DeclContext *DC, *LexicalDC;
1481 DeclarationName Name;
1483 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1486 // If this typedef is not in block scope, determine whether we've
1487 // seen a typedef with the same name (that we can merge with) or any
1488 // other entity by that name (which name lookup could conflict with).
1489 if (!DC->isFunctionOrMethod()) {
1490 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1491 unsigned IDNS = Decl::IDNS_Ordinary;
1492 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1493 Lookup.first != Lookup.second;
1495 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1497 if (TypedefDecl *FoundTypedef = dyn_cast<TypedefDecl>(*Lookup.first)) {
1498 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1499 FoundTypedef->getUnderlyingType()))
1500 return Importer.Imported(D, FoundTypedef);
1503 ConflictingDecls.push_back(*Lookup.first);
1506 if (!ConflictingDecls.empty()) {
1507 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1508 ConflictingDecls.data(),
1509 ConflictingDecls.size());
1515 // Import the underlying type of this typedef;
1516 QualType T = Importer.Import(D->getUnderlyingType());
1520 // Create the new typedef node.
1521 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1522 TypedefDecl *ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
1523 Loc, Name.getAsIdentifierInfo(),
1525 ToTypedef->setAccess(D->getAccess());
1526 ToTypedef->setLexicalDeclContext(LexicalDC);
1527 Importer.Imported(D, ToTypedef);
1528 LexicalDC->addDecl(ToTypedef);
1533 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
1534 // Import the major distinguishing characteristics of this enum.
1535 DeclContext *DC, *LexicalDC;
1536 DeclarationName Name;
1538 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1541 // Figure out what enum name we're looking for.
1542 unsigned IDNS = Decl::IDNS_Tag;
1543 DeclarationName SearchName = Name;
1544 if (!SearchName && D->getTypedefForAnonDecl()) {
1545 SearchName = Importer.Import(D->getTypedefForAnonDecl()->getDeclName());
1546 IDNS = Decl::IDNS_Ordinary;
1547 } else if (Importer.getToContext().getLangOptions().CPlusPlus)
1548 IDNS |= Decl::IDNS_Ordinary;
1550 // We may already have an enum of the same name; try to find and match it.
1551 if (!DC->isFunctionOrMethod() && SearchName) {
1552 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1553 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1554 Lookup.first != Lookup.second;
1556 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1559 Decl *Found = *Lookup.first;
1560 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Found)) {
1561 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1562 Found = Tag->getDecl();
1565 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
1566 if (IsStructuralMatch(D, FoundEnum))
1567 return Importer.Imported(D, FoundEnum);
1570 ConflictingDecls.push_back(*Lookup.first);
1573 if (!ConflictingDecls.empty()) {
1574 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1575 ConflictingDecls.data(),
1576 ConflictingDecls.size());
1580 // Create the enum declaration.
1581 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC, Loc,
1582 Name.getAsIdentifierInfo(),
1583 Importer.Import(D->getTagKeywordLoc()),
1585 D2->setAccess(D->getAccess());
1586 D2->setLexicalDeclContext(LexicalDC);
1587 Importer.Imported(D, D2);
1588 LexicalDC->addDecl(D2);
1590 // Import the integer type.
1591 QualType ToIntegerType = Importer.Import(D->getIntegerType());
1592 if (ToIntegerType.isNull())
1594 D2->setIntegerType(ToIntegerType);
1596 // Import the definition
1597 if (D->isDefinition()) {
1598 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(D));
1602 QualType ToPromotionType = Importer.Import(D->getPromotionType());
1603 if (ToPromotionType.isNull())
1606 D2->startDefinition();
1607 ImportDeclContext(D);
1608 D2->completeDefinition(T, ToPromotionType);
1614 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
1615 // If this record has a definition in the translation unit we're coming from,
1616 // but this particular declaration is not that definition, import the
1617 // definition and map to that.
1618 TagDecl *Definition = D->getDefinition();
1619 if (Definition && Definition != D) {
1620 Decl *ImportedDef = Importer.Import(Definition);
1624 return Importer.Imported(D, ImportedDef);
1627 // Import the major distinguishing characteristics of this record.
1628 DeclContext *DC, *LexicalDC;
1629 DeclarationName Name;
1631 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1634 // Figure out what structure name we're looking for.
1635 unsigned IDNS = Decl::IDNS_Tag;
1636 DeclarationName SearchName = Name;
1637 if (!SearchName && D->getTypedefForAnonDecl()) {
1638 SearchName = Importer.Import(D->getTypedefForAnonDecl()->getDeclName());
1639 IDNS = Decl::IDNS_Ordinary;
1640 } else if (Importer.getToContext().getLangOptions().CPlusPlus)
1641 IDNS |= Decl::IDNS_Ordinary;
1643 // We may already have a record of the same name; try to find and match it.
1644 RecordDecl *AdoptDecl = 0;
1645 if (!DC->isFunctionOrMethod() && SearchName) {
1646 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1647 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1648 Lookup.first != Lookup.second;
1650 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1653 Decl *Found = *Lookup.first;
1654 if (TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Found)) {
1655 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1656 Found = Tag->getDecl();
1659 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
1660 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
1661 if (!D->isDefinition() || IsStructuralMatch(D, FoundDef)) {
1662 // The record types structurally match, or the "from" translation
1663 // unit only had a forward declaration anyway; call it the same
1665 // FIXME: For C++, we should also merge methods here.
1666 return Importer.Imported(D, FoundDef);
1669 // We have a forward declaration of this type, so adopt that forward
1670 // declaration rather than building a new one.
1671 AdoptDecl = FoundRecord;
1676 ConflictingDecls.push_back(*Lookup.first);
1679 if (!ConflictingDecls.empty()) {
1680 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1681 ConflictingDecls.data(),
1682 ConflictingDecls.size());
1686 // Create the record declaration.
1687 RecordDecl *D2 = AdoptDecl;
1689 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D)) {
1690 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
1693 Name.getAsIdentifierInfo(),
1694 Importer.Import(D->getTagKeywordLoc()));
1696 D2->setAccess(D->getAccess());
1698 if (D->isDefinition()) {
1699 // Add base classes.
1700 llvm::SmallVector<CXXBaseSpecifier *, 4> Bases;
1701 for (CXXRecordDecl::base_class_iterator
1702 Base1 = D1CXX->bases_begin(),
1703 FromBaseEnd = D1CXX->bases_end();
1704 Base1 != FromBaseEnd;
1706 QualType T = Importer.Import(Base1->getType());
1711 new (Importer.getToContext())
1712 CXXBaseSpecifier(Importer.Import(Base1->getSourceRange()),
1714 Base1->isBaseOfClass(),
1715 Base1->getAccessSpecifierAsWritten(),
1719 D2CXX->setBases(Bases.data(), Bases.size());
1722 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
1724 Name.getAsIdentifierInfo(),
1725 Importer.Import(D->getTagKeywordLoc()));
1727 D2->setLexicalDeclContext(LexicalDC);
1728 LexicalDC->addDecl(D2);
1731 Importer.Imported(D, D2);
1733 if (D->isDefinition()) {
1734 D2->startDefinition();
1735 ImportDeclContext(D);
1736 D2->completeDefinition();
1742 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
1743 // Import the major distinguishing characteristics of this enumerator.
1744 DeclContext *DC, *LexicalDC;
1745 DeclarationName Name;
1747 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1750 QualType T = Importer.Import(D->getType());
1754 // Determine whether there are any other declarations with the same name and
1755 // in the same context.
1756 if (!LexicalDC->isFunctionOrMethod()) {
1757 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1758 unsigned IDNS = Decl::IDNS_Ordinary;
1759 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1760 Lookup.first != Lookup.second;
1762 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1765 ConflictingDecls.push_back(*Lookup.first);
1768 if (!ConflictingDecls.empty()) {
1769 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1770 ConflictingDecls.data(),
1771 ConflictingDecls.size());
1777 Expr *Init = Importer.Import(D->getInitExpr());
1778 if (D->getInitExpr() && !Init)
1781 EnumConstantDecl *ToEnumerator
1782 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
1783 Name.getAsIdentifierInfo(), T,
1784 Init, D->getInitVal());
1785 ToEnumerator->setAccess(D->getAccess());
1786 ToEnumerator->setLexicalDeclContext(LexicalDC);
1787 Importer.Imported(D, ToEnumerator);
1788 LexicalDC->addDecl(ToEnumerator);
1789 return ToEnumerator;
1792 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
1793 // Import the major distinguishing characteristics of this function.
1794 DeclContext *DC, *LexicalDC;
1795 DeclarationName Name;
1797 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1800 // Try to find a function in our own ("to") context with the same name, same
1801 // type, and in the same context as the function we're importing.
1802 if (!LexicalDC->isFunctionOrMethod()) {
1803 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
1804 unsigned IDNS = Decl::IDNS_Ordinary;
1805 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1806 Lookup.first != Lookup.second;
1808 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
1811 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(*Lookup.first)) {
1812 if (isExternalLinkage(FoundFunction->getLinkage()) &&
1813 isExternalLinkage(D->getLinkage())) {
1814 if (Importer.IsStructurallyEquivalent(D->getType(),
1815 FoundFunction->getType())) {
1816 // FIXME: Actually try to merge the body and other attributes.
1817 return Importer.Imported(D, FoundFunction);
1820 // FIXME: Check for overloading more carefully, e.g., by boosting
1821 // Sema::IsOverload out to the AST library.
1823 // Function overloading is okay in C++.
1824 if (Importer.getToContext().getLangOptions().CPlusPlus)
1827 // Complain about inconsistent function types.
1828 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
1829 << Name << D->getType() << FoundFunction->getType();
1830 Importer.ToDiag(FoundFunction->getLocation(),
1831 diag::note_odr_value_here)
1832 << FoundFunction->getType();
1836 ConflictingDecls.push_back(*Lookup.first);
1839 if (!ConflictingDecls.empty()) {
1840 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1841 ConflictingDecls.data(),
1842 ConflictingDecls.size());
1849 QualType T = Importer.Import(D->getType());
1853 // Import the function parameters.
1854 llvm::SmallVector<ParmVarDecl *, 8> Parameters;
1855 for (FunctionDecl::param_iterator P = D->param_begin(), PEnd = D->param_end();
1857 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*P));
1861 Parameters.push_back(ToP);
1864 // Create the imported function.
1865 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1866 FunctionDecl *ToFunction = 0;
1867 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
1868 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
1869 cast<CXXRecordDecl>(DC),
1870 Loc, Name, T, TInfo,
1871 FromConstructor->isExplicit(),
1872 D->isInlineSpecified(),
1874 } else if (isa<CXXDestructorDecl>(D)) {
1875 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
1876 cast<CXXRecordDecl>(DC),
1878 D->isInlineSpecified(),
1880 } else if (CXXConversionDecl *FromConversion
1881 = dyn_cast<CXXConversionDecl>(D)) {
1882 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
1883 cast<CXXRecordDecl>(DC),
1884 Loc, Name, T, TInfo,
1885 D->isInlineSpecified(),
1886 FromConversion->isExplicit());
1888 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC, Loc,
1889 Name, T, TInfo, D->getStorageClass(),
1890 D->isInlineSpecified(),
1891 D->hasWrittenPrototype());
1893 ToFunction->setAccess(D->getAccess());
1894 ToFunction->setLexicalDeclContext(LexicalDC);
1895 Importer.Imported(D, ToFunction);
1896 LexicalDC->addDecl(ToFunction);
1898 // Set the parameters.
1899 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
1900 Parameters[I]->setOwningFunction(ToFunction);
1901 ToFunction->addDecl(Parameters[I]);
1903 ToFunction->setParams(Parameters.data(), Parameters.size());
1905 // FIXME: Other bits to merge?
1910 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
1911 return VisitFunctionDecl(D);
1914 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1915 return VisitCXXMethodDecl(D);
1918 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1919 return VisitCXXMethodDecl(D);
1922 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
1923 return VisitCXXMethodDecl(D);
1926 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
1927 // Import the major distinguishing characteristics of a variable.
1928 DeclContext *DC, *LexicalDC;
1929 DeclarationName Name;
1931 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1935 QualType T = Importer.Import(D->getType());
1939 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1940 Expr *BitWidth = Importer.Import(D->getBitWidth());
1941 if (!BitWidth && D->getBitWidth())
1944 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
1945 Loc, Name.getAsIdentifierInfo(),
1946 T, TInfo, BitWidth, D->isMutable());
1947 ToField->setAccess(D->getAccess());
1948 ToField->setLexicalDeclContext(LexicalDC);
1949 Importer.Imported(D, ToField);
1950 LexicalDC->addDecl(ToField);
1954 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
1955 // Import the major distinguishing characteristics of an ivar.
1956 DeclContext *DC, *LexicalDC;
1957 DeclarationName Name;
1959 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
1962 // Determine whether we've already imported this ivar
1963 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
1964 Lookup.first != Lookup.second;
1966 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(*Lookup.first)) {
1967 if (Importer.IsStructurallyEquivalent(D->getType(),
1968 FoundIvar->getType())) {
1969 Importer.Imported(D, FoundIvar);
1973 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
1974 << Name << D->getType() << FoundIvar->getType();
1975 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
1976 << FoundIvar->getType();
1982 QualType T = Importer.Import(D->getType());
1986 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1987 Expr *BitWidth = Importer.Import(D->getBitWidth());
1988 if (!BitWidth && D->getBitWidth())
1991 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(), DC,
1992 Loc, Name.getAsIdentifierInfo(),
1993 T, TInfo, D->getAccessControl(),
1995 ToIvar->setLexicalDeclContext(LexicalDC);
1996 Importer.Imported(D, ToIvar);
1997 LexicalDC->addDecl(ToIvar);
2002 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2003 // Import the major distinguishing characteristics of a variable.
2004 DeclContext *DC, *LexicalDC;
2005 DeclarationName Name;
2007 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2010 // Try to find a variable in our own ("to") context with the same name and
2011 // in the same context as the variable we're importing.
2012 if (D->isFileVarDecl()) {
2013 VarDecl *MergeWithVar = 0;
2014 llvm::SmallVector<NamedDecl *, 4> ConflictingDecls;
2015 unsigned IDNS = Decl::IDNS_Ordinary;
2016 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2017 Lookup.first != Lookup.second;
2019 if (!(*Lookup.first)->isInIdentifierNamespace(IDNS))
2022 if (VarDecl *FoundVar = dyn_cast<VarDecl>(*Lookup.first)) {
2023 // We have found a variable that we may need to merge with. Check it.
2024 if (isExternalLinkage(FoundVar->getLinkage()) &&
2025 isExternalLinkage(D->getLinkage())) {
2026 if (Importer.IsStructurallyEquivalent(D->getType(),
2027 FoundVar->getType())) {
2028 MergeWithVar = FoundVar;
2032 const ArrayType *FoundArray
2033 = Importer.getToContext().getAsArrayType(FoundVar->getType());
2034 const ArrayType *TArray
2035 = Importer.getToContext().getAsArrayType(D->getType());
2036 if (FoundArray && TArray) {
2037 if (isa<IncompleteArrayType>(FoundArray) &&
2038 isa<ConstantArrayType>(TArray)) {
2040 QualType T = Importer.Import(D->getType());
2044 FoundVar->setType(T);
2045 MergeWithVar = FoundVar;
2047 } else if (isa<IncompleteArrayType>(TArray) &&
2048 isa<ConstantArrayType>(FoundArray)) {
2049 MergeWithVar = FoundVar;
2054 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2055 << Name << D->getType() << FoundVar->getType();
2056 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2057 << FoundVar->getType();
2061 ConflictingDecls.push_back(*Lookup.first);
2065 // An equivalent variable with external linkage has been found. Link
2066 // the two declarations, then merge them.
2067 Importer.Imported(D, MergeWithVar);
2069 if (VarDecl *DDef = D->getDefinition()) {
2070 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2071 Importer.ToDiag(ExistingDef->getLocation(),
2072 diag::err_odr_variable_multiple_def)
2074 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2076 Expr *Init = Importer.Import(DDef->getInit());
2077 MergeWithVar->setInit(Init);
2081 return MergeWithVar;
2084 if (!ConflictingDecls.empty()) {
2085 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2086 ConflictingDecls.data(),
2087 ConflictingDecls.size());
2094 QualType T = Importer.Import(D->getType());
2098 // Create the imported variable.
2099 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2100 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC, Loc,
2101 Name.getAsIdentifierInfo(), T, TInfo,
2102 D->getStorageClass());
2103 ToVar->setAccess(D->getAccess());
2104 ToVar->setLexicalDeclContext(LexicalDC);
2105 Importer.Imported(D, ToVar);
2106 LexicalDC->addDecl(ToVar);
2108 // Merge the initializer.
2109 // FIXME: Can we really import any initializer? Alternatively, we could force
2110 // ourselves to import every declaration of a variable and then only use
2112 ToVar->setInit(Importer.Import(const_cast<Expr *>(D->getAnyInitializer())));
2114 // FIXME: Other bits to merge?
2119 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2120 // Parameters are created in the translation unit's context, then moved
2121 // into the function declaration's context afterward.
2122 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2124 // Import the name of this declaration.
2125 DeclarationName Name = Importer.Import(D->getDeclName());
2126 if (D->getDeclName() && !Name)
2129 // Import the location of this declaration.
2130 SourceLocation Loc = Importer.Import(D->getLocation());
2132 // Import the parameter's type.
2133 QualType T = Importer.Import(D->getType());
2137 // Create the imported parameter.
2138 ImplicitParamDecl *ToParm
2139 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
2140 Loc, Name.getAsIdentifierInfo(),
2142 return Importer.Imported(D, ToParm);
2145 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2146 // Parameters are created in the translation unit's context, then moved
2147 // into the function declaration's context afterward.
2148 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2150 // Import the name of this declaration.
2151 DeclarationName Name = Importer.Import(D->getDeclName());
2152 if (D->getDeclName() && !Name)
2155 // Import the location of this declaration.
2156 SourceLocation Loc = Importer.Import(D->getLocation());
2158 // Import the parameter's type.
2159 QualType T = Importer.Import(D->getType());
2163 // Create the imported parameter.
2164 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2165 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2166 Loc, Name.getAsIdentifierInfo(),
2167 T, TInfo, D->getStorageClass(),
2168 /*FIXME: Default argument*/ 0);
2169 return Importer.Imported(D, ToParm);
2172 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2173 // Import the major distinguishing characteristics of a method.
2174 DeclContext *DC, *LexicalDC;
2175 DeclarationName Name;
2177 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2180 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2181 Lookup.first != Lookup.second;
2183 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(*Lookup.first)) {
2184 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2187 // Check return types.
2188 if (!Importer.IsStructurallyEquivalent(D->getResultType(),
2189 FoundMethod->getResultType())) {
2190 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2191 << D->isInstanceMethod() << Name
2192 << D->getResultType() << FoundMethod->getResultType();
2193 Importer.ToDiag(FoundMethod->getLocation(),
2194 diag::note_odr_objc_method_here)
2195 << D->isInstanceMethod() << Name;
2199 // Check the number of parameters.
2200 if (D->param_size() != FoundMethod->param_size()) {
2201 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2202 << D->isInstanceMethod() << Name
2203 << D->param_size() << FoundMethod->param_size();
2204 Importer.ToDiag(FoundMethod->getLocation(),
2205 diag::note_odr_objc_method_here)
2206 << D->isInstanceMethod() << Name;
2210 // Check parameter types.
2211 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
2212 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
2213 P != PEnd; ++P, ++FoundP) {
2214 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
2215 (*FoundP)->getType())) {
2216 Importer.FromDiag((*P)->getLocation(),
2217 diag::err_odr_objc_method_param_type_inconsistent)
2218 << D->isInstanceMethod() << Name
2219 << (*P)->getType() << (*FoundP)->getType();
2220 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
2221 << (*FoundP)->getType();
2226 // Check variadic/non-variadic.
2227 // Check the number of parameters.
2228 if (D->isVariadic() != FoundMethod->isVariadic()) {
2229 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
2230 << D->isInstanceMethod() << Name;
2231 Importer.ToDiag(FoundMethod->getLocation(),
2232 diag::note_odr_objc_method_here)
2233 << D->isInstanceMethod() << Name;
2237 // FIXME: Any other bits we need to merge?
2238 return Importer.Imported(D, FoundMethod);
2242 // Import the result type.
2243 QualType ResultTy = Importer.Import(D->getResultType());
2244 if (ResultTy.isNull())
2247 ObjCMethodDecl *ToMethod
2248 = ObjCMethodDecl::Create(Importer.getToContext(),
2250 Importer.Import(D->getLocEnd()),
2251 Name.getObjCSelector(),
2253 D->isInstanceMethod(),
2256 D->getImplementationControl());
2258 // FIXME: When we decide to merge method definitions, we'll need to
2259 // deal with implicit parameters.
2261 // Import the parameters
2262 llvm::SmallVector<ParmVarDecl *, 5> ToParams;
2263 for (ObjCMethodDecl::param_iterator FromP = D->param_begin(),
2264 FromPEnd = D->param_end();
2267 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(*FromP));
2271 ToParams.push_back(ToP);
2274 // Set the parameters.
2275 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
2276 ToParams[I]->setOwningFunction(ToMethod);
2277 ToMethod->addDecl(ToParams[I]);
2279 ToMethod->setMethodParams(Importer.getToContext(),
2280 ToParams.data(), ToParams.size());
2282 ToMethod->setLexicalDeclContext(LexicalDC);
2283 Importer.Imported(D, ToMethod);
2284 LexicalDC->addDecl(ToMethod);
2288 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
2289 // Import the major distinguishing characteristics of a category.
2290 DeclContext *DC, *LexicalDC;
2291 DeclarationName Name;
2293 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2296 ObjCInterfaceDecl *ToInterface
2297 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
2301 // Determine if we've already encountered this category.
2302 ObjCCategoryDecl *MergeWithCategory
2303 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
2304 ObjCCategoryDecl *ToCategory = MergeWithCategory;
2306 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
2307 Importer.Import(D->getAtLoc()),
2309 Importer.Import(D->getCategoryNameLoc()),
2310 Name.getAsIdentifierInfo());
2311 ToCategory->setLexicalDeclContext(LexicalDC);
2312 LexicalDC->addDecl(ToCategory);
2313 Importer.Imported(D, ToCategory);
2315 // Link this category into its class's category list.
2316 ToCategory->setClassInterface(ToInterface);
2317 ToCategory->insertNextClassCategory();
2320 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2321 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2322 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
2323 = D->protocol_loc_begin();
2324 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
2325 FromProtoEnd = D->protocol_end();
2326 FromProto != FromProtoEnd;
2327 ++FromProto, ++FromProtoLoc) {
2328 ObjCProtocolDecl *ToProto
2329 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2332 Protocols.push_back(ToProto);
2333 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2336 // FIXME: If we're merging, make sure that the protocol list is the same.
2337 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
2338 ProtocolLocs.data(), Importer.getToContext());
2341 Importer.Imported(D, ToCategory);
2344 // Import all of the members of this category.
2345 ImportDeclContext(D);
2347 // If we have an implementation, import it as well.
2348 if (D->getImplementation()) {
2349 ObjCCategoryImplDecl *Impl
2350 = cast<ObjCCategoryImplDecl>(Importer.Import(D->getImplementation()));
2354 ToCategory->setImplementation(Impl);
2360 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
2361 // Import the major distinguishing characteristics of a protocol.
2362 DeclContext *DC, *LexicalDC;
2363 DeclarationName Name;
2365 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2368 ObjCProtocolDecl *MergeWithProtocol = 0;
2369 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2370 Lookup.first != Lookup.second;
2372 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
2375 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(*Lookup.first)))
2379 ObjCProtocolDecl *ToProto = MergeWithProtocol;
2380 if (!ToProto || ToProto->isForwardDecl()) {
2382 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC, Loc,
2383 Name.getAsIdentifierInfo());
2384 ToProto->setForwardDecl(D->isForwardDecl());
2385 ToProto->setLexicalDeclContext(LexicalDC);
2386 LexicalDC->addDecl(ToProto);
2388 Importer.Imported(D, ToProto);
2391 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2392 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2393 ObjCProtocolDecl::protocol_loc_iterator
2394 FromProtoLoc = D->protocol_loc_begin();
2395 for (ObjCProtocolDecl::protocol_iterator FromProto = D->protocol_begin(),
2396 FromProtoEnd = D->protocol_end();
2397 FromProto != FromProtoEnd;
2398 ++FromProto, ++FromProtoLoc) {
2399 ObjCProtocolDecl *ToProto
2400 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2403 Protocols.push_back(ToProto);
2404 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2407 // FIXME: If we're merging, make sure that the protocol list is the same.
2408 ToProto->setProtocolList(Protocols.data(), Protocols.size(),
2409 ProtocolLocs.data(), Importer.getToContext());
2411 Importer.Imported(D, ToProto);
2414 // Import all of the members of this protocol.
2415 ImportDeclContext(D);
2420 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
2421 // Import the major distinguishing characteristics of an @interface.
2422 DeclContext *DC, *LexicalDC;
2423 DeclarationName Name;
2425 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2428 ObjCInterfaceDecl *MergeWithIface = 0;
2429 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2430 Lookup.first != Lookup.second;
2432 if (!(*Lookup.first)->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2435 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(*Lookup.first)))
2439 ObjCInterfaceDecl *ToIface = MergeWithIface;
2440 if (!ToIface || ToIface->isForwardDecl()) {
2442 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(),
2444 Name.getAsIdentifierInfo(),
2445 Importer.Import(D->getClassLoc()),
2447 D->isImplicitInterfaceDecl());
2448 ToIface->setForwardDecl(D->isForwardDecl());
2449 ToIface->setLexicalDeclContext(LexicalDC);
2450 LexicalDC->addDecl(ToIface);
2452 Importer.Imported(D, ToIface);
2454 if (D->getSuperClass()) {
2455 ObjCInterfaceDecl *Super
2456 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getSuperClass()));
2460 ToIface->setSuperClass(Super);
2461 ToIface->setSuperClassLoc(Importer.Import(D->getSuperClassLoc()));
2465 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2466 llvm::SmallVector<SourceLocation, 4> ProtocolLocs;
2467 ObjCInterfaceDecl::protocol_loc_iterator
2468 FromProtoLoc = D->protocol_loc_begin();
2469 for (ObjCInterfaceDecl::protocol_iterator FromProto = D->protocol_begin(),
2470 FromProtoEnd = D->protocol_end();
2471 FromProto != FromProtoEnd;
2472 ++FromProto, ++FromProtoLoc) {
2473 ObjCProtocolDecl *ToProto
2474 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2477 Protocols.push_back(ToProto);
2478 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2481 // FIXME: If we're merging, make sure that the protocol list is the same.
2482 ToIface->setProtocolList(Protocols.data(), Protocols.size(),
2483 ProtocolLocs.data(), Importer.getToContext());
2485 // Import @end range
2486 ToIface->setAtEndRange(Importer.Import(D->getAtEndRange()));
2488 Importer.Imported(D, ToIface);
2490 // Check for consistency of superclasses.
2491 DeclarationName FromSuperName, ToSuperName;
2492 if (D->getSuperClass())
2493 FromSuperName = Importer.Import(D->getSuperClass()->getDeclName());
2494 if (ToIface->getSuperClass())
2495 ToSuperName = ToIface->getSuperClass()->getDeclName();
2496 if (FromSuperName != ToSuperName) {
2497 Importer.ToDiag(ToIface->getLocation(),
2498 diag::err_odr_objc_superclass_inconsistent)
2499 << ToIface->getDeclName();
2500 if (ToIface->getSuperClass())
2501 Importer.ToDiag(ToIface->getSuperClassLoc(),
2502 diag::note_odr_objc_superclass)
2503 << ToIface->getSuperClass()->getDeclName();
2505 Importer.ToDiag(ToIface->getLocation(),
2506 diag::note_odr_objc_missing_superclass);
2507 if (D->getSuperClass())
2508 Importer.FromDiag(D->getSuperClassLoc(),
2509 diag::note_odr_objc_superclass)
2510 << D->getSuperClass()->getDeclName();
2512 Importer.FromDiag(D->getLocation(),
2513 diag::note_odr_objc_missing_superclass);
2518 // Import categories. When the categories themselves are imported, they'll
2519 // hook themselves into this interface.
2520 for (ObjCCategoryDecl *FromCat = D->getCategoryList(); FromCat;
2521 FromCat = FromCat->getNextClassCategory())
2522 Importer.Import(FromCat);
2524 // Import all of the members of this class.
2525 ImportDeclContext(D);
2527 // If we have an @implementation, import it as well.
2528 if (D->getImplementation()) {
2529 ObjCImplementationDecl *Impl
2530 = cast<ObjCImplementationDecl>(Importer.Import(D->getImplementation()));
2534 ToIface->setImplementation(Impl);
2540 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
2541 // Import the major distinguishing characteristics of an @property.
2542 DeclContext *DC, *LexicalDC;
2543 DeclarationName Name;
2545 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2548 // Check whether we have already imported this property.
2549 for (DeclContext::lookup_result Lookup = DC->lookup(Name);
2550 Lookup.first != Lookup.second;
2552 if (ObjCPropertyDecl *FoundProp
2553 = dyn_cast<ObjCPropertyDecl>(*Lookup.first)) {
2554 // Check property types.
2555 if (!Importer.IsStructurallyEquivalent(D->getType(),
2556 FoundProp->getType())) {
2557 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
2558 << Name << D->getType() << FoundProp->getType();
2559 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
2560 << FoundProp->getType();
2564 // FIXME: Check property attributes, getters, setters, etc.?
2566 // Consider these properties to be equivalent.
2567 Importer.Imported(D, FoundProp);
2573 QualType T = Importer.Import(D->getType());
2577 // Create the new property.
2578 ObjCPropertyDecl *ToProperty
2579 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
2580 Name.getAsIdentifierInfo(),
2581 Importer.Import(D->getAtLoc()),
2583 D->getPropertyImplementation());
2584 Importer.Imported(D, ToProperty);
2585 ToProperty->setLexicalDeclContext(LexicalDC);
2586 LexicalDC->addDecl(ToProperty);
2588 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
2589 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
2590 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
2591 ToProperty->setGetterMethodDecl(
2592 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
2593 ToProperty->setSetterMethodDecl(
2594 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
2595 ToProperty->setPropertyIvarDecl(
2596 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
2601 ASTNodeImporter::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D) {
2602 // Import the context of this declaration.
2603 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2607 DeclContext *LexicalDC = DC;
2608 if (D->getDeclContext() != D->getLexicalDeclContext()) {
2609 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2614 // Import the location of this declaration.
2615 SourceLocation Loc = Importer.Import(D->getLocation());
2617 llvm::SmallVector<ObjCProtocolDecl *, 4> Protocols;
2618 llvm::SmallVector<SourceLocation, 4> Locations;
2619 ObjCForwardProtocolDecl::protocol_loc_iterator FromProtoLoc
2620 = D->protocol_loc_begin();
2621 for (ObjCForwardProtocolDecl::protocol_iterator FromProto
2622 = D->protocol_begin(), FromProtoEnd = D->protocol_end();
2623 FromProto != FromProtoEnd;
2624 ++FromProto, ++FromProtoLoc) {
2625 ObjCProtocolDecl *ToProto
2626 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2630 Protocols.push_back(ToProto);
2631 Locations.push_back(Importer.Import(*FromProtoLoc));
2634 ObjCForwardProtocolDecl *ToForward
2635 = ObjCForwardProtocolDecl::Create(Importer.getToContext(), DC, Loc,
2636 Protocols.data(), Protocols.size(),
2638 ToForward->setLexicalDeclContext(LexicalDC);
2639 LexicalDC->addDecl(ToForward);
2640 Importer.Imported(D, ToForward);
2644 Decl *ASTNodeImporter::VisitObjCClassDecl(ObjCClassDecl *D) {
2645 // Import the context of this declaration.
2646 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2650 DeclContext *LexicalDC = DC;
2651 if (D->getDeclContext() != D->getLexicalDeclContext()) {
2652 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2657 // Import the location of this declaration.
2658 SourceLocation Loc = Importer.Import(D->getLocation());
2660 llvm::SmallVector<ObjCInterfaceDecl *, 4> Interfaces;
2661 llvm::SmallVector<SourceLocation, 4> Locations;
2662 for (ObjCClassDecl::iterator From = D->begin(), FromEnd = D->end();
2663 From != FromEnd; ++From) {
2664 ObjCInterfaceDecl *ToIface
2665 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(From->getInterface()));
2669 Interfaces.push_back(ToIface);
2670 Locations.push_back(Importer.Import(From->getLocation()));
2673 ObjCClassDecl *ToClass = ObjCClassDecl::Create(Importer.getToContext(), DC,
2678 ToClass->setLexicalDeclContext(LexicalDC);
2679 LexicalDC->addDecl(ToClass);
2680 Importer.Imported(D, ToClass);
2684 //----------------------------------------------------------------------------
2685 // Import Statements
2686 //----------------------------------------------------------------------------
2688 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
2689 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
2690 << S->getStmtClassName();
2694 //----------------------------------------------------------------------------
2695 // Import Expressions
2696 //----------------------------------------------------------------------------
2697 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
2698 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
2699 << E->getStmtClassName();
2703 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
2704 NestedNameSpecifier *Qualifier = 0;
2705 if (E->getQualifier()) {
2706 Qualifier = Importer.Import(E->getQualifier());
2707 if (!E->getQualifier())
2711 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
2715 QualType T = Importer.Import(E->getType());
2719 return DeclRefExpr::Create(Importer.getToContext(), Qualifier,
2720 Importer.Import(E->getQualifierRange()),
2722 Importer.Import(E->getLocation()),
2724 /*FIXME:TemplateArgs=*/0);
2727 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
2728 QualType T = Importer.Import(E->getType());
2732 return new (Importer.getToContext())
2733 IntegerLiteral(E->getValue(), T, Importer.Import(E->getLocation()));
2736 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
2737 QualType T = Importer.Import(E->getType());
2741 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
2743 Importer.Import(E->getLocation()));
2746 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
2747 Expr *SubExpr = Importer.Import(E->getSubExpr());
2751 return new (Importer.getToContext())
2752 ParenExpr(Importer.Import(E->getLParen()),
2753 Importer.Import(E->getRParen()),
2757 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
2758 QualType T = Importer.Import(E->getType());
2762 Expr *SubExpr = Importer.Import(E->getSubExpr());
2766 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
2768 Importer.Import(E->getOperatorLoc()));
2771 Expr *ASTNodeImporter::VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) {
2772 QualType ResultType = Importer.Import(E->getType());
2774 if (E->isArgumentType()) {
2775 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
2779 return new (Importer.getToContext()) SizeOfAlignOfExpr(E->isSizeOf(),
2781 Importer.Import(E->getOperatorLoc()),
2782 Importer.Import(E->getRParenLoc()));
2785 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
2789 return new (Importer.getToContext()) SizeOfAlignOfExpr(E->isSizeOf(),
2790 SubExpr, ResultType,
2791 Importer.Import(E->getOperatorLoc()),
2792 Importer.Import(E->getRParenLoc()));
2795 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
2796 QualType T = Importer.Import(E->getType());
2800 Expr *LHS = Importer.Import(E->getLHS());
2804 Expr *RHS = Importer.Import(E->getRHS());
2808 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
2810 Importer.Import(E->getOperatorLoc()));
2813 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
2814 QualType T = Importer.Import(E->getType());
2818 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
2819 if (CompLHSType.isNull())
2822 QualType CompResultType = Importer.Import(E->getComputationResultType());
2823 if (CompResultType.isNull())
2826 Expr *LHS = Importer.Import(E->getLHS());
2830 Expr *RHS = Importer.Import(E->getRHS());
2834 return new (Importer.getToContext())
2835 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
2836 T, CompLHSType, CompResultType,
2837 Importer.Import(E->getOperatorLoc()));
2840 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
2841 QualType T = Importer.Import(E->getType());
2845 Expr *SubExpr = Importer.Import(E->getSubExpr());
2849 return new (Importer.getToContext()) ImplicitCastExpr(T, E->getCastKind(),
2854 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
2855 QualType T = Importer.Import(E->getType());
2859 Expr *SubExpr = Importer.Import(E->getSubExpr());
2863 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
2864 if (!TInfo && E->getTypeInfoAsWritten())
2867 return new (Importer.getToContext()) CStyleCastExpr(T, E->getCastKind(),
2869 Importer.Import(E->getLParenLoc()),
2870 Importer.Import(E->getRParenLoc()));
2873 ASTImporter::ASTImporter(Diagnostic &Diags,
2874 ASTContext &ToContext, FileManager &ToFileManager,
2875 ASTContext &FromContext, FileManager &FromFileManager)
2876 : ToContext(ToContext), FromContext(FromContext),
2877 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
2879 ImportedDecls[FromContext.getTranslationUnitDecl()]
2880 = ToContext.getTranslationUnitDecl();
2883 ASTImporter::~ASTImporter() { }
2885 QualType ASTImporter::Import(QualType FromT) {
2889 // Check whether we've already imported this type.
2890 llvm::DenseMap<Type *, Type *>::iterator Pos
2891 = ImportedTypes.find(FromT.getTypePtr());
2892 if (Pos != ImportedTypes.end())
2893 return ToContext.getQualifiedType(Pos->second, FromT.getQualifiers());
2896 ASTNodeImporter Importer(*this);
2897 QualType ToT = Importer.Visit(FromT.getTypePtr());
2901 // Record the imported type.
2902 ImportedTypes[FromT.getTypePtr()] = ToT.getTypePtr();
2904 return ToContext.getQualifiedType(ToT, FromT.getQualifiers());
2907 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
2911 // FIXME: For now we just create a "trivial" type source info based
2912 // on the type and a seingle location. Implement a real version of
2914 QualType T = Import(FromTSI->getType());
2918 return ToContext.getTrivialTypeSourceInfo(T,
2919 FromTSI->getTypeLoc().getFullSourceRange().getBegin());
2922 Decl *ASTImporter::Import(Decl *FromD) {
2926 // Check whether we've already imported this declaration.
2927 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
2928 if (Pos != ImportedDecls.end())
2932 ASTNodeImporter Importer(*this);
2933 Decl *ToD = Importer.Visit(FromD);
2937 // Record the imported declaration.
2938 ImportedDecls[FromD] = ToD;
2940 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
2941 // Keep track of anonymous tags that have an associated typedef.
2942 if (FromTag->getTypedefForAnonDecl())
2943 AnonTagsWithPendingTypedefs.push_back(FromTag);
2944 } else if (TypedefDecl *FromTypedef = dyn_cast<TypedefDecl>(FromD)) {
2945 // When we've finished transforming a typedef, see whether it was the
2946 // typedef for an anonymous tag.
2947 for (llvm::SmallVector<TagDecl *, 4>::iterator
2948 FromTag = AnonTagsWithPendingTypedefs.begin(),
2949 FromTagEnd = AnonTagsWithPendingTypedefs.end();
2950 FromTag != FromTagEnd; ++FromTag) {
2951 if ((*FromTag)->getTypedefForAnonDecl() == FromTypedef) {
2952 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
2953 // We found the typedef for an anonymous tag; link them.
2954 ToTag->setTypedefForAnonDecl(cast<TypedefDecl>(ToD));
2955 AnonTagsWithPendingTypedefs.erase(FromTag);
2965 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
2969 return cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
2972 Expr *ASTImporter::Import(Expr *FromE) {
2976 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
2979 Stmt *ASTImporter::Import(Stmt *FromS) {
2983 // Check whether we've already imported this declaration.
2984 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
2985 if (Pos != ImportedStmts.end())
2989 ASTNodeImporter Importer(*this);
2990 Stmt *ToS = Importer.Visit(FromS);
2994 // Record the imported declaration.
2995 ImportedStmts[FromS] = ToS;
2999 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
3003 // FIXME: Implement!
3007 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
3008 if (FromLoc.isInvalid())
3009 return SourceLocation();
3011 SourceManager &FromSM = FromContext.getSourceManager();
3013 // For now, map everything down to its spelling location, so that we
3014 // don't have to import macro instantiations.
3015 // FIXME: Import macro instantiations!
3016 FromLoc = FromSM.getSpellingLoc(FromLoc);
3017 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
3018 SourceManager &ToSM = ToContext.getSourceManager();
3019 return ToSM.getLocForStartOfFile(Import(Decomposed.first))
3020 .getFileLocWithOffset(Decomposed.second);
3023 SourceRange ASTImporter::Import(SourceRange FromRange) {
3024 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
3027 FileID ASTImporter::Import(FileID FromID) {
3028 llvm::DenseMap<unsigned, FileID>::iterator Pos
3029 = ImportedFileIDs.find(FromID.getHashValue());
3030 if (Pos != ImportedFileIDs.end())
3033 SourceManager &FromSM = FromContext.getSourceManager();
3034 SourceManager &ToSM = ToContext.getSourceManager();
3035 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
3036 assert(FromSLoc.isFile() && "Cannot handle macro instantiations yet");
3038 // Include location of this file.
3039 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
3041 // Map the FileID for to the "to" source manager.
3043 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
3045 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
3047 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
3048 // than mmap the files several times.
3049 const FileEntry *Entry = ToFileManager.getFile(Cache->Entry->getName());
3050 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
3051 FromSLoc.getFile().getFileCharacteristic());
3053 // FIXME: We want to re-use the existing MemoryBuffer!
3054 const llvm::MemoryBuffer *FromBuf = Cache->getBuffer();
3055 llvm::MemoryBuffer *ToBuf
3056 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBufferStart(),
3057 FromBuf->getBufferEnd(),
3058 FromBuf->getBufferIdentifier());
3059 ToID = ToSM.createFileIDForMemBuffer(ToBuf);
3063 ImportedFileIDs[FromID.getHashValue()] = ToID;
3067 DeclarationName ASTImporter::Import(DeclarationName FromName) {
3069 return DeclarationName();
3071 switch (FromName.getNameKind()) {
3072 case DeclarationName::Identifier:
3073 return Import(FromName.getAsIdentifierInfo());
3075 case DeclarationName::ObjCZeroArgSelector:
3076 case DeclarationName::ObjCOneArgSelector:
3077 case DeclarationName::ObjCMultiArgSelector:
3078 return Import(FromName.getObjCSelector());
3080 case DeclarationName::CXXConstructorName: {
3081 QualType T = Import(FromName.getCXXNameType());
3083 return DeclarationName();
3085 return ToContext.DeclarationNames.getCXXConstructorName(
3086 ToContext.getCanonicalType(T));
3089 case DeclarationName::CXXDestructorName: {
3090 QualType T = Import(FromName.getCXXNameType());
3092 return DeclarationName();
3094 return ToContext.DeclarationNames.getCXXDestructorName(
3095 ToContext.getCanonicalType(T));
3098 case DeclarationName::CXXConversionFunctionName: {
3099 QualType T = Import(FromName.getCXXNameType());
3101 return DeclarationName();
3103 return ToContext.DeclarationNames.getCXXConversionFunctionName(
3104 ToContext.getCanonicalType(T));
3107 case DeclarationName::CXXOperatorName:
3108 return ToContext.DeclarationNames.getCXXOperatorName(
3109 FromName.getCXXOverloadedOperator());
3111 case DeclarationName::CXXLiteralOperatorName:
3112 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
3113 Import(FromName.getCXXLiteralIdentifier()));
3115 case DeclarationName::CXXUsingDirective:
3117 return DeclarationName::getUsingDirectiveName();
3120 // Silence bogus GCC warning
3121 return DeclarationName();
3124 IdentifierInfo *ASTImporter::Import(IdentifierInfo *FromId) {
3128 return &ToContext.Idents.get(FromId->getName());
3131 Selector ASTImporter::Import(Selector FromSel) {
3132 if (FromSel.isNull())
3135 llvm::SmallVector<IdentifierInfo *, 4> Idents;
3136 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
3137 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
3138 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
3139 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
3142 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
3146 unsigned NumDecls) {
3150 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
3151 return Diags.Report(FullSourceLoc(Loc, ToContext.getSourceManager()),
3155 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
3156 return Diags.Report(FullSourceLoc(Loc, FromContext.getSourceManager()),
3160 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
3161 ImportedDecls[From] = To;
3165 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To) {
3166 llvm::DenseMap<Type *, Type *>::iterator Pos
3167 = ImportedTypes.find(From.getTypePtr());
3168 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
3171 StructuralEquivalenceContext Ctx(FromContext, ToContext, Diags,
3172 NonEquivalentDecls);
3173 return Ctx.IsStructurallyEquivalent(From, To);