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"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/Support/MemoryBuffer.h"
28 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29 public DeclVisitor<ASTNodeImporter, Decl *>,
30 public StmtVisitor<ASTNodeImporter, Stmt *> {
31 ASTImporter &Importer;
34 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
36 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
41 QualType VisitType(const Type *T);
42 QualType VisitBuiltinType(const BuiltinType *T);
43 QualType VisitComplexType(const ComplexType *T);
44 QualType VisitPointerType(const PointerType *T);
45 QualType VisitBlockPointerType(const BlockPointerType *T);
46 QualType VisitLValueReferenceType(const LValueReferenceType *T);
47 QualType VisitRValueReferenceType(const RValueReferenceType *T);
48 QualType VisitMemberPointerType(const MemberPointerType *T);
49 QualType VisitConstantArrayType(const ConstantArrayType *T);
50 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
51 QualType VisitVariableArrayType(const VariableArrayType *T);
52 // FIXME: DependentSizedArrayType
53 // FIXME: DependentSizedExtVectorType
54 QualType VisitVectorType(const VectorType *T);
55 QualType VisitExtVectorType(const ExtVectorType *T);
56 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
57 QualType VisitFunctionProtoType(const FunctionProtoType *T);
58 // FIXME: UnresolvedUsingType
59 QualType VisitParenType(const ParenType *T);
60 QualType VisitTypedefType(const TypedefType *T);
61 QualType VisitTypeOfExprType(const TypeOfExprType *T);
62 // FIXME: DependentTypeOfExprType
63 QualType VisitTypeOfType(const TypeOfType *T);
64 QualType VisitDecltypeType(const DecltypeType *T);
65 QualType VisitUnaryTransformType(const UnaryTransformType *T);
66 QualType VisitAutoType(const AutoType *T);
67 // FIXME: DependentDecltypeType
68 QualType VisitRecordType(const RecordType *T);
69 QualType VisitEnumType(const EnumType *T);
70 // FIXME: TemplateTypeParmType
71 // FIXME: SubstTemplateTypeParmType
72 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
73 QualType VisitElaboratedType(const ElaboratedType *T);
74 // FIXME: DependentNameType
75 // FIXME: DependentTemplateSpecializationType
76 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
77 QualType VisitObjCObjectType(const ObjCObjectType *T);
78 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80 // Importing declarations
81 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
82 DeclContext *&LexicalDC, DeclarationName &Name,
84 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = 0);
85 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
86 DeclarationNameInfo& To);
87 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89 /// \brief What we should import from the definition.
90 enum ImportDefinitionKind {
91 /// \brief Import the default subset of the definition, which might be
92 /// nothing (if minimal import is set) or might be everything (if minimal
93 /// import is not set).
95 /// \brief Import everything.
97 /// \brief Import only the bare bones needed to establish a valid
102 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
103 return IDK == IDK_Everything ||
104 (IDK == IDK_Default && !Importer.isMinimalImport());
107 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
108 ImportDefinitionKind Kind = IDK_Default);
109 bool ImportDefinition(VarDecl *From, VarDecl *To,
110 ImportDefinitionKind Kind = IDK_Default);
111 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
112 ImportDefinitionKind Kind = IDK_Default);
113 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
114 ImportDefinitionKind Kind = IDK_Default);
115 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
116 ImportDefinitionKind Kind = IDK_Default);
117 TemplateParameterList *ImportTemplateParameterList(
118 TemplateParameterList *Params);
119 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
120 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
121 unsigned NumFromArgs,
122 SmallVectorImpl<TemplateArgument> &ToArgs);
123 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
124 bool Complain = true);
125 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
126 bool Complain = true);
127 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
128 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
129 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
130 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
131 Decl *VisitDecl(Decl *D);
132 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
133 Decl *VisitNamespaceDecl(NamespaceDecl *D);
134 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
135 Decl *VisitTypedefDecl(TypedefDecl *D);
136 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
137 Decl *VisitEnumDecl(EnumDecl *D);
138 Decl *VisitRecordDecl(RecordDecl *D);
139 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
140 Decl *VisitFunctionDecl(FunctionDecl *D);
141 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
142 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
143 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
144 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
145 Decl *VisitFieldDecl(FieldDecl *D);
146 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
147 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
148 Decl *VisitVarDecl(VarDecl *D);
149 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
150 Decl *VisitParmVarDecl(ParmVarDecl *D);
151 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
152 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
153 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
154 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
155 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
156 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
157 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
158 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
159 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
160 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
161 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
162 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
163 Decl *VisitClassTemplateSpecializationDecl(
164 ClassTemplateSpecializationDecl *D);
165 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
166 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
168 // Importing statements
169 Stmt *VisitStmt(Stmt *S);
171 // Importing expressions
172 Expr *VisitExpr(Expr *E);
173 Expr *VisitDeclRefExpr(DeclRefExpr *E);
174 Expr *VisitIntegerLiteral(IntegerLiteral *E);
175 Expr *VisitCharacterLiteral(CharacterLiteral *E);
176 Expr *VisitParenExpr(ParenExpr *E);
177 Expr *VisitUnaryOperator(UnaryOperator *E);
178 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
179 Expr *VisitBinaryOperator(BinaryOperator *E);
180 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
181 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
182 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
185 using namespace clang;
187 //----------------------------------------------------------------------------
188 // Structural Equivalence
189 //----------------------------------------------------------------------------
192 struct StructuralEquivalenceContext {
193 /// \brief AST contexts for which we are checking structural equivalence.
196 /// \brief The set of "tentative" equivalences between two canonical
197 /// declarations, mapping from a declaration in the first context to the
198 /// declaration in the second context that we believe to be equivalent.
199 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
201 /// \brief Queue of declarations in the first context whose equivalence
202 /// with a declaration in the second context still needs to be verified.
203 std::deque<Decl *> DeclsToCheck;
205 /// \brief Declaration (from, to) pairs that are known not to be equivalent
206 /// (which we have already complained about).
207 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
209 /// \brief Whether we're being strict about the spelling of types when
210 /// unifying two types.
211 bool StrictTypeSpelling;
213 /// \brief Whether to complain about failures.
216 /// \brief \c true if the last diagnostic came from C2.
219 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
220 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
221 bool StrictTypeSpelling = false,
222 bool Complain = true)
223 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
224 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
225 LastDiagFromC2(false) {}
227 /// \brief Determine whether the two declarations are structurally
229 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
231 /// \brief Determine whether the two types are structurally equivalent.
232 bool IsStructurallyEquivalent(QualType T1, QualType T2);
235 /// \brief Finish checking all of the structural equivalences.
237 /// \returns true if an error occurred, false otherwise.
241 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
242 assert(Complain && "Not allowed to complain");
244 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
245 LastDiagFromC2 = false;
246 return C1.getDiagnostics().Report(Loc, DiagID);
249 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
250 assert(Complain && "Not allowed to complain");
252 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
253 LastDiagFromC2 = true;
254 return C2.getDiagnostics().Report(Loc, DiagID);
259 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
260 QualType T1, QualType T2);
261 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
264 /// \brief Determine structural equivalence of two expressions.
265 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
266 Expr *E1, Expr *E2) {
270 // FIXME: Actually perform a structural comparison!
274 /// \brief Determine whether two identifiers are equivalent.
275 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
276 const IdentifierInfo *Name2) {
277 if (!Name1 || !Name2)
278 return Name1 == Name2;
280 return Name1->getName() == Name2->getName();
283 /// \brief Determine whether two nested-name-specifiers are equivalent.
284 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
285 NestedNameSpecifier *NNS1,
286 NestedNameSpecifier *NNS2) {
291 /// \brief Determine whether two template arguments are equivalent.
292 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
293 const TemplateArgument &Arg1,
294 const TemplateArgument &Arg2) {
295 if (Arg1.getKind() != Arg2.getKind())
298 switch (Arg1.getKind()) {
299 case TemplateArgument::Null:
302 case TemplateArgument::Type:
303 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
305 case TemplateArgument::Integral:
306 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
307 Arg2.getIntegralType()))
310 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
312 case TemplateArgument::Declaration:
313 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
315 case TemplateArgument::NullPtr:
316 return true; // FIXME: Is this correct?
318 case TemplateArgument::Template:
319 return IsStructurallyEquivalent(Context,
320 Arg1.getAsTemplate(),
321 Arg2.getAsTemplate());
323 case TemplateArgument::TemplateExpansion:
324 return IsStructurallyEquivalent(Context,
325 Arg1.getAsTemplateOrTemplatePattern(),
326 Arg2.getAsTemplateOrTemplatePattern());
328 case TemplateArgument::Expression:
329 return IsStructurallyEquivalent(Context,
330 Arg1.getAsExpr(), Arg2.getAsExpr());
332 case TemplateArgument::Pack:
333 if (Arg1.pack_size() != Arg2.pack_size())
336 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
337 if (!IsStructurallyEquivalent(Context,
338 Arg1.pack_begin()[I],
339 Arg2.pack_begin()[I]))
345 llvm_unreachable("Invalid template argument kind");
348 /// \brief Determine structural equivalence for the common part of array
350 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
351 const ArrayType *Array1,
352 const ArrayType *Array2) {
353 if (!IsStructurallyEquivalent(Context,
354 Array1->getElementType(),
355 Array2->getElementType()))
357 if (Array1->getSizeModifier() != Array2->getSizeModifier())
359 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
365 /// \brief Determine structural equivalence of two types.
366 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
367 QualType T1, QualType T2) {
368 if (T1.isNull() || T2.isNull())
369 return T1.isNull() && T2.isNull();
371 if (!Context.StrictTypeSpelling) {
372 // We aren't being strict about token-to-token equivalence of types,
373 // so map down to the canonical type.
374 T1 = Context.C1.getCanonicalType(T1);
375 T2 = Context.C2.getCanonicalType(T2);
378 if (T1.getQualifiers() != T2.getQualifiers())
381 Type::TypeClass TC = T1->getTypeClass();
383 if (T1->getTypeClass() != T2->getTypeClass()) {
384 // Compare function types with prototypes vs. without prototypes as if
385 // both did not have prototypes.
386 if (T1->getTypeClass() == Type::FunctionProto &&
387 T2->getTypeClass() == Type::FunctionNoProto)
388 TC = Type::FunctionNoProto;
389 else if (T1->getTypeClass() == Type::FunctionNoProto &&
390 T2->getTypeClass() == Type::FunctionProto)
391 TC = Type::FunctionNoProto;
398 // FIXME: Deal with Char_S/Char_U.
399 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
404 if (!IsStructurallyEquivalent(Context,
405 cast<ComplexType>(T1)->getElementType(),
406 cast<ComplexType>(T2)->getElementType()))
412 if (!IsStructurallyEquivalent(Context,
413 cast<AdjustedType>(T1)->getOriginalType(),
414 cast<AdjustedType>(T2)->getOriginalType()))
419 if (!IsStructurallyEquivalent(Context,
420 cast<PointerType>(T1)->getPointeeType(),
421 cast<PointerType>(T2)->getPointeeType()))
425 case Type::BlockPointer:
426 if (!IsStructurallyEquivalent(Context,
427 cast<BlockPointerType>(T1)->getPointeeType(),
428 cast<BlockPointerType>(T2)->getPointeeType()))
432 case Type::LValueReference:
433 case Type::RValueReference: {
434 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
435 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
436 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
438 if (Ref1->isInnerRef() != Ref2->isInnerRef())
440 if (!IsStructurallyEquivalent(Context,
441 Ref1->getPointeeTypeAsWritten(),
442 Ref2->getPointeeTypeAsWritten()))
447 case Type::MemberPointer: {
448 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
449 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
450 if (!IsStructurallyEquivalent(Context,
451 MemPtr1->getPointeeType(),
452 MemPtr2->getPointeeType()))
454 if (!IsStructurallyEquivalent(Context,
455 QualType(MemPtr1->getClass(), 0),
456 QualType(MemPtr2->getClass(), 0)))
461 case Type::ConstantArray: {
462 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
463 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
464 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
467 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
472 case Type::IncompleteArray:
473 if (!IsArrayStructurallyEquivalent(Context,
475 cast<ArrayType>(T2)))
479 case Type::VariableArray: {
480 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
481 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
482 if (!IsStructurallyEquivalent(Context,
483 Array1->getSizeExpr(), Array2->getSizeExpr()))
486 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
492 case Type::DependentSizedArray: {
493 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
494 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
495 if (!IsStructurallyEquivalent(Context,
496 Array1->getSizeExpr(), Array2->getSizeExpr()))
499 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
505 case Type::DependentSizedExtVector: {
506 const DependentSizedExtVectorType *Vec1
507 = cast<DependentSizedExtVectorType>(T1);
508 const DependentSizedExtVectorType *Vec2
509 = cast<DependentSizedExtVectorType>(T2);
510 if (!IsStructurallyEquivalent(Context,
511 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
513 if (!IsStructurallyEquivalent(Context,
514 Vec1->getElementType(),
515 Vec2->getElementType()))
521 case Type::ExtVector: {
522 const VectorType *Vec1 = cast<VectorType>(T1);
523 const VectorType *Vec2 = cast<VectorType>(T2);
524 if (!IsStructurallyEquivalent(Context,
525 Vec1->getElementType(),
526 Vec2->getElementType()))
528 if (Vec1->getNumElements() != Vec2->getNumElements())
530 if (Vec1->getVectorKind() != Vec2->getVectorKind())
535 case Type::FunctionProto: {
536 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
537 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
538 if (Proto1->getNumParams() != Proto2->getNumParams())
540 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
541 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
542 Proto2->getParamType(I)))
545 if (Proto1->isVariadic() != Proto2->isVariadic())
547 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
549 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
550 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
552 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
553 if (!IsStructurallyEquivalent(Context,
554 Proto1->getExceptionType(I),
555 Proto2->getExceptionType(I)))
558 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
559 if (!IsStructurallyEquivalent(Context,
560 Proto1->getNoexceptExpr(),
561 Proto2->getNoexceptExpr()))
564 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
567 // Fall through to check the bits common with FunctionNoProtoType.
570 case Type::FunctionNoProto: {
571 const FunctionType *Function1 = cast<FunctionType>(T1);
572 const FunctionType *Function2 = cast<FunctionType>(T2);
573 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
574 Function2->getReturnType()))
576 if (Function1->getExtInfo() != Function2->getExtInfo())
581 case Type::UnresolvedUsing:
582 if (!IsStructurallyEquivalent(Context,
583 cast<UnresolvedUsingType>(T1)->getDecl(),
584 cast<UnresolvedUsingType>(T2)->getDecl()))
589 case Type::Attributed:
590 if (!IsStructurallyEquivalent(Context,
591 cast<AttributedType>(T1)->getModifiedType(),
592 cast<AttributedType>(T2)->getModifiedType()))
594 if (!IsStructurallyEquivalent(Context,
595 cast<AttributedType>(T1)->getEquivalentType(),
596 cast<AttributedType>(T2)->getEquivalentType()))
601 if (!IsStructurallyEquivalent(Context,
602 cast<ParenType>(T1)->getInnerType(),
603 cast<ParenType>(T2)->getInnerType()))
608 if (!IsStructurallyEquivalent(Context,
609 cast<TypedefType>(T1)->getDecl(),
610 cast<TypedefType>(T2)->getDecl()))
614 case Type::TypeOfExpr:
615 if (!IsStructurallyEquivalent(Context,
616 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
617 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
622 if (!IsStructurallyEquivalent(Context,
623 cast<TypeOfType>(T1)->getUnderlyingType(),
624 cast<TypeOfType>(T2)->getUnderlyingType()))
628 case Type::UnaryTransform:
629 if (!IsStructurallyEquivalent(Context,
630 cast<UnaryTransformType>(T1)->getUnderlyingType(),
631 cast<UnaryTransformType>(T1)->getUnderlyingType()))
636 if (!IsStructurallyEquivalent(Context,
637 cast<DecltypeType>(T1)->getUnderlyingExpr(),
638 cast<DecltypeType>(T2)->getUnderlyingExpr()))
643 if (!IsStructurallyEquivalent(Context,
644 cast<AutoType>(T1)->getDeducedType(),
645 cast<AutoType>(T2)->getDeducedType()))
651 if (!IsStructurallyEquivalent(Context,
652 cast<TagType>(T1)->getDecl(),
653 cast<TagType>(T2)->getDecl()))
657 case Type::TemplateTypeParm: {
658 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
659 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
660 if (Parm1->getDepth() != Parm2->getDepth())
662 if (Parm1->getIndex() != Parm2->getIndex())
664 if (Parm1->isParameterPack() != Parm2->isParameterPack())
667 // Names of template type parameters are never significant.
671 case Type::SubstTemplateTypeParm: {
672 const SubstTemplateTypeParmType *Subst1
673 = cast<SubstTemplateTypeParmType>(T1);
674 const SubstTemplateTypeParmType *Subst2
675 = cast<SubstTemplateTypeParmType>(T2);
676 if (!IsStructurallyEquivalent(Context,
677 QualType(Subst1->getReplacedParameter(), 0),
678 QualType(Subst2->getReplacedParameter(), 0)))
680 if (!IsStructurallyEquivalent(Context,
681 Subst1->getReplacementType(),
682 Subst2->getReplacementType()))
687 case Type::SubstTemplateTypeParmPack: {
688 const SubstTemplateTypeParmPackType *Subst1
689 = cast<SubstTemplateTypeParmPackType>(T1);
690 const SubstTemplateTypeParmPackType *Subst2
691 = cast<SubstTemplateTypeParmPackType>(T2);
692 if (!IsStructurallyEquivalent(Context,
693 QualType(Subst1->getReplacedParameter(), 0),
694 QualType(Subst2->getReplacedParameter(), 0)))
696 if (!IsStructurallyEquivalent(Context,
697 Subst1->getArgumentPack(),
698 Subst2->getArgumentPack()))
702 case Type::TemplateSpecialization: {
703 const TemplateSpecializationType *Spec1
704 = cast<TemplateSpecializationType>(T1);
705 const TemplateSpecializationType *Spec2
706 = cast<TemplateSpecializationType>(T2);
707 if (!IsStructurallyEquivalent(Context,
708 Spec1->getTemplateName(),
709 Spec2->getTemplateName()))
711 if (Spec1->getNumArgs() != Spec2->getNumArgs())
713 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
714 if (!IsStructurallyEquivalent(Context,
715 Spec1->getArg(I), Spec2->getArg(I)))
721 case Type::Elaborated: {
722 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
723 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
724 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
725 if (Elab1->getKeyword() != Elab2->getKeyword())
727 if (!IsStructurallyEquivalent(Context,
728 Elab1->getQualifier(),
729 Elab2->getQualifier()))
731 if (!IsStructurallyEquivalent(Context,
732 Elab1->getNamedType(),
733 Elab2->getNamedType()))
738 case Type::InjectedClassName: {
739 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
740 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
741 if (!IsStructurallyEquivalent(Context,
742 Inj1->getInjectedSpecializationType(),
743 Inj2->getInjectedSpecializationType()))
748 case Type::DependentName: {
749 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
750 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
751 if (!IsStructurallyEquivalent(Context,
752 Typename1->getQualifier(),
753 Typename2->getQualifier()))
755 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
756 Typename2->getIdentifier()))
762 case Type::DependentTemplateSpecialization: {
763 const DependentTemplateSpecializationType *Spec1 =
764 cast<DependentTemplateSpecializationType>(T1);
765 const DependentTemplateSpecializationType *Spec2 =
766 cast<DependentTemplateSpecializationType>(T2);
767 if (!IsStructurallyEquivalent(Context,
768 Spec1->getQualifier(),
769 Spec2->getQualifier()))
771 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
772 Spec2->getIdentifier()))
774 if (Spec1->getNumArgs() != Spec2->getNumArgs())
776 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
777 if (!IsStructurallyEquivalent(Context,
778 Spec1->getArg(I), Spec2->getArg(I)))
784 case Type::PackExpansion:
785 if (!IsStructurallyEquivalent(Context,
786 cast<PackExpansionType>(T1)->getPattern(),
787 cast<PackExpansionType>(T2)->getPattern()))
791 case Type::ObjCInterface: {
792 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
793 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
794 if (!IsStructurallyEquivalent(Context,
795 Iface1->getDecl(), Iface2->getDecl()))
800 case Type::ObjCObject: {
801 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
802 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
803 if (!IsStructurallyEquivalent(Context,
805 Obj2->getBaseType()))
807 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
809 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
810 if (!IsStructurallyEquivalent(Context,
811 Obj1->getProtocol(I),
812 Obj2->getProtocol(I)))
818 case Type::ObjCObjectPointer: {
819 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
820 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
821 if (!IsStructurallyEquivalent(Context,
822 Ptr1->getPointeeType(),
823 Ptr2->getPointeeType()))
829 if (!IsStructurallyEquivalent(Context,
830 cast<AtomicType>(T1)->getValueType(),
831 cast<AtomicType>(T2)->getValueType()))
841 /// \brief Determine structural equivalence of two fields.
842 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
843 FieldDecl *Field1, FieldDecl *Field2) {
844 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
846 // For anonymous structs/unions, match up the anonymous struct/union type
847 // declarations directly, so that we don't go off searching for anonymous
849 if (Field1->isAnonymousStructOrUnion() &&
850 Field2->isAnonymousStructOrUnion()) {
851 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
852 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
853 return IsStructurallyEquivalent(Context, D1, D2);
856 // Check for equivalent field names.
857 IdentifierInfo *Name1 = Field1->getIdentifier();
858 IdentifierInfo *Name2 = Field2->getIdentifier();
859 if (!::IsStructurallyEquivalent(Name1, Name2))
862 if (!IsStructurallyEquivalent(Context,
863 Field1->getType(), Field2->getType())) {
864 if (Context.Complain) {
865 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
866 << Context.C2.getTypeDeclType(Owner2);
867 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
868 << Field2->getDeclName() << Field2->getType();
869 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
870 << Field1->getDeclName() << Field1->getType();
875 if (Field1->isBitField() != Field2->isBitField()) {
876 if (Context.Complain) {
877 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
878 << Context.C2.getTypeDeclType(Owner2);
879 if (Field1->isBitField()) {
880 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
881 << Field1->getDeclName() << Field1->getType()
882 << Field1->getBitWidthValue(Context.C1);
883 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
884 << Field2->getDeclName();
886 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
887 << Field2->getDeclName() << Field2->getType()
888 << Field2->getBitWidthValue(Context.C2);
889 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
890 << Field1->getDeclName();
896 if (Field1->isBitField()) {
897 // Make sure that the bit-fields are the same length.
898 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
899 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
901 if (Bits1 != Bits2) {
902 if (Context.Complain) {
903 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
904 << Context.C2.getTypeDeclType(Owner2);
905 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
906 << Field2->getDeclName() << Field2->getType() << Bits2;
907 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
908 << Field1->getDeclName() << Field1->getType() << Bits1;
917 /// \brief Find the index of the given anonymous struct/union within its
920 /// \returns Returns the index of this anonymous struct/union in its context,
921 /// including the next assigned index (if none of them match). Returns an
922 /// empty option if the context is not a record, i.e.. if the anonymous
923 /// struct/union is at namespace or block scope.
924 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
925 ASTContext &Context = Anon->getASTContext();
926 QualType AnonTy = Context.getRecordType(Anon);
928 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
933 for (const auto *D : Owner->noload_decls()) {
934 const auto *F = dyn_cast<FieldDecl>(D);
935 if (!F || !F->isAnonymousStructOrUnion())
938 if (Context.hasSameType(F->getType(), AnonTy))
947 /// \brief Determine structural equivalence of two records.
948 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
949 RecordDecl *D1, RecordDecl *D2) {
950 if (D1->isUnion() != D2->isUnion()) {
951 if (Context.Complain) {
952 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
953 << Context.C2.getTypeDeclType(D2);
954 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
955 << D1->getDeclName() << (unsigned)D1->getTagKind();
960 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
961 // If both anonymous structs/unions are in a record context, make sure
962 // they occur in the same location in the context records.
963 if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
964 if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
965 if (*Index1 != *Index2)
971 // If both declarations are class template specializations, we know
972 // the ODR applies, so check the template and template arguments.
973 ClassTemplateSpecializationDecl *Spec1
974 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
975 ClassTemplateSpecializationDecl *Spec2
976 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
977 if (Spec1 && Spec2) {
978 // Check that the specialized templates are the same.
979 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
980 Spec2->getSpecializedTemplate()))
983 // Check that the template arguments are the same.
984 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
987 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
988 if (!IsStructurallyEquivalent(Context,
989 Spec1->getTemplateArgs().get(I),
990 Spec2->getTemplateArgs().get(I)))
993 // If one is a class template specialization and the other is not, these
994 // structures are different.
995 else if (Spec1 || Spec2)
998 // Compare the definitions of these two records. If either or both are
999 // incomplete, we assume that they are equivalent.
1000 D1 = D1->getDefinition();
1001 D2 = D2->getDefinition();
1005 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1006 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1007 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1008 if (Context.Complain) {
1009 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1010 << Context.C2.getTypeDeclType(D2);
1011 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1012 << D2CXX->getNumBases();
1013 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1014 << D1CXX->getNumBases();
1019 // Check the base classes.
1020 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1021 BaseEnd1 = D1CXX->bases_end(),
1022 Base2 = D2CXX->bases_begin();
1025 if (!IsStructurallyEquivalent(Context,
1026 Base1->getType(), Base2->getType())) {
1027 if (Context.Complain) {
1028 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1029 << Context.C2.getTypeDeclType(D2);
1030 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1032 << Base2->getSourceRange();
1033 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1035 << Base1->getSourceRange();
1040 // Check virtual vs. non-virtual inheritance mismatch.
1041 if (Base1->isVirtual() != Base2->isVirtual()) {
1042 if (Context.Complain) {
1043 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1044 << Context.C2.getTypeDeclType(D2);
1045 Context.Diag2(Base2->getLocStart(),
1046 diag::note_odr_virtual_base)
1047 << Base2->isVirtual() << Base2->getSourceRange();
1048 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1049 << Base1->isVirtual()
1050 << Base1->getSourceRange();
1055 } else if (D1CXX->getNumBases() > 0) {
1056 if (Context.Complain) {
1057 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1058 << Context.C2.getTypeDeclType(D2);
1059 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1060 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1062 << Base1->getSourceRange();
1063 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1069 // Check the fields for consistency.
1070 RecordDecl::field_iterator Field2 = D2->field_begin(),
1071 Field2End = D2->field_end();
1072 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1073 Field1End = D1->field_end();
1074 Field1 != Field1End;
1075 ++Field1, ++Field2) {
1076 if (Field2 == Field2End) {
1077 if (Context.Complain) {
1078 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1079 << Context.C2.getTypeDeclType(D2);
1080 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1081 << Field1->getDeclName() << Field1->getType();
1082 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1087 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1091 if (Field2 != Field2End) {
1092 if (Context.Complain) {
1093 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1094 << Context.C2.getTypeDeclType(D2);
1095 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1096 << Field2->getDeclName() << Field2->getType();
1097 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1105 /// \brief Determine structural equivalence of two enums.
1106 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1107 EnumDecl *D1, EnumDecl *D2) {
1108 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1109 EC2End = D2->enumerator_end();
1110 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1111 EC1End = D1->enumerator_end();
1112 EC1 != EC1End; ++EC1, ++EC2) {
1113 if (EC2 == EC2End) {
1114 if (Context.Complain) {
1115 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1116 << Context.C2.getTypeDeclType(D2);
1117 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1118 << EC1->getDeclName()
1119 << EC1->getInitVal().toString(10);
1120 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1125 llvm::APSInt Val1 = EC1->getInitVal();
1126 llvm::APSInt Val2 = EC2->getInitVal();
1127 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1128 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1129 if (Context.Complain) {
1130 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1131 << Context.C2.getTypeDeclType(D2);
1132 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1133 << EC2->getDeclName()
1134 << EC2->getInitVal().toString(10);
1135 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1136 << EC1->getDeclName()
1137 << EC1->getInitVal().toString(10);
1143 if (EC2 != EC2End) {
1144 if (Context.Complain) {
1145 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1146 << Context.C2.getTypeDeclType(D2);
1147 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1148 << EC2->getDeclName()
1149 << EC2->getInitVal().toString(10);
1150 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1158 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1159 TemplateParameterList *Params1,
1160 TemplateParameterList *Params2) {
1161 if (Params1->size() != Params2->size()) {
1162 if (Context.Complain) {
1163 Context.Diag2(Params2->getTemplateLoc(),
1164 diag::err_odr_different_num_template_parameters)
1165 << Params1->size() << Params2->size();
1166 Context.Diag1(Params1->getTemplateLoc(),
1167 diag::note_odr_template_parameter_list);
1172 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1173 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1174 if (Context.Complain) {
1175 Context.Diag2(Params2->getParam(I)->getLocation(),
1176 diag::err_odr_different_template_parameter_kind);
1177 Context.Diag1(Params1->getParam(I)->getLocation(),
1178 diag::note_odr_template_parameter_here);
1183 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1184 Params2->getParam(I))) {
1193 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1194 TemplateTypeParmDecl *D1,
1195 TemplateTypeParmDecl *D2) {
1196 if (D1->isParameterPack() != D2->isParameterPack()) {
1197 if (Context.Complain) {
1198 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1199 << D2->isParameterPack();
1200 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1201 << D1->isParameterPack();
1209 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1210 NonTypeTemplateParmDecl *D1,
1211 NonTypeTemplateParmDecl *D2) {
1212 if (D1->isParameterPack() != D2->isParameterPack()) {
1213 if (Context.Complain) {
1214 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1215 << D2->isParameterPack();
1216 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1217 << D1->isParameterPack();
1223 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1224 if (Context.Complain) {
1225 Context.Diag2(D2->getLocation(),
1226 diag::err_odr_non_type_parameter_type_inconsistent)
1227 << D2->getType() << D1->getType();
1228 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1237 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1238 TemplateTemplateParmDecl *D1,
1239 TemplateTemplateParmDecl *D2) {
1240 if (D1->isParameterPack() != D2->isParameterPack()) {
1241 if (Context.Complain) {
1242 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1243 << D2->isParameterPack();
1244 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1245 << D1->isParameterPack();
1250 // Check template parameter lists.
1251 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1252 D2->getTemplateParameters());
1255 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1256 ClassTemplateDecl *D1,
1257 ClassTemplateDecl *D2) {
1258 // Check template parameters.
1259 if (!IsStructurallyEquivalent(Context,
1260 D1->getTemplateParameters(),
1261 D2->getTemplateParameters()))
1264 // Check the templated declaration.
1265 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1266 D2->getTemplatedDecl());
1269 /// \brief Determine structural equivalence of two declarations.
1270 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1271 Decl *D1, Decl *D2) {
1272 // FIXME: Check for known structural equivalences via a callback of some sort.
1274 // Check whether we already know that these two declarations are not
1275 // structurally equivalent.
1276 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1277 D2->getCanonicalDecl())))
1280 // Determine whether we've already produced a tentative equivalence for D1.
1281 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1283 return EquivToD1 == D2->getCanonicalDecl();
1285 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1286 EquivToD1 = D2->getCanonicalDecl();
1287 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1291 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1293 if (!::IsStructurallyEquivalent(*this, D1, D2))
1299 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1301 if (!::IsStructurallyEquivalent(*this, T1, T2))
1307 bool StructuralEquivalenceContext::Finish() {
1308 while (!DeclsToCheck.empty()) {
1309 // Check the next declaration.
1310 Decl *D1 = DeclsToCheck.front();
1311 DeclsToCheck.pop_front();
1313 Decl *D2 = TentativeEquivalences[D1];
1314 assert(D2 && "Unrecorded tentative equivalence?");
1316 bool Equivalent = true;
1318 // FIXME: Switch on all declaration kinds. For now, we're just going to
1319 // check the obvious ones.
1320 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1321 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1322 // Check for equivalent structure names.
1323 IdentifierInfo *Name1 = Record1->getIdentifier();
1324 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1325 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1326 IdentifierInfo *Name2 = Record2->getIdentifier();
1327 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1328 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1329 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1330 !::IsStructurallyEquivalent(*this, Record1, Record2))
1333 // Record/non-record mismatch.
1336 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1337 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1338 // Check for equivalent enum names.
1339 IdentifierInfo *Name1 = Enum1->getIdentifier();
1340 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1341 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1342 IdentifierInfo *Name2 = Enum2->getIdentifier();
1343 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1344 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1345 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1346 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1349 // Enum/non-enum mismatch
1352 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1353 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1354 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1355 Typedef2->getIdentifier()) ||
1356 !::IsStructurallyEquivalent(*this,
1357 Typedef1->getUnderlyingType(),
1358 Typedef2->getUnderlyingType()))
1361 // Typedef/non-typedef mismatch.
1364 } else if (ClassTemplateDecl *ClassTemplate1
1365 = dyn_cast<ClassTemplateDecl>(D1)) {
1366 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1367 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1368 ClassTemplate2->getIdentifier()) ||
1369 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1372 // Class template/non-class-template mismatch.
1375 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1376 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1377 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1383 } else if (NonTypeTemplateParmDecl *NTTP1
1384 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1385 if (NonTypeTemplateParmDecl *NTTP2
1386 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1387 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1393 } else if (TemplateTemplateParmDecl *TTP1
1394 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1395 if (TemplateTemplateParmDecl *TTP2
1396 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1397 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1406 // Note that these two declarations are not equivalent (and we already
1408 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1409 D2->getCanonicalDecl()));
1412 // FIXME: Check other declaration kinds!
1418 //----------------------------------------------------------------------------
1420 //----------------------------------------------------------------------------
1422 QualType ASTNodeImporter::VisitType(const Type *T) {
1423 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1424 << T->getTypeClassName();
1428 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1429 switch (T->getKind()) {
1430 #define SHARED_SINGLETON_TYPE(Expansion)
1431 #define BUILTIN_TYPE(Id, SingletonId) \
1432 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1433 #include "clang/AST/BuiltinTypes.def"
1435 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1436 // context supports C++.
1438 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1439 // context supports ObjC.
1441 case BuiltinType::Char_U:
1442 // The context we're importing from has an unsigned 'char'. If we're
1443 // importing into a context with a signed 'char', translate to
1444 // 'unsigned char' instead.
1445 if (Importer.getToContext().getLangOpts().CharIsSigned)
1446 return Importer.getToContext().UnsignedCharTy;
1448 return Importer.getToContext().CharTy;
1450 case BuiltinType::Char_S:
1451 // The context we're importing from has an unsigned 'char'. If we're
1452 // importing into a context with a signed 'char', translate to
1453 // 'unsigned char' instead.
1454 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1455 return Importer.getToContext().SignedCharTy;
1457 return Importer.getToContext().CharTy;
1459 case BuiltinType::WChar_S:
1460 case BuiltinType::WChar_U:
1461 // FIXME: If not in C++, shall we translate to the C equivalent of
1463 return Importer.getToContext().WCharTy;
1466 llvm_unreachable("Invalid BuiltinType Kind!");
1469 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1470 QualType ToElementType = Importer.Import(T->getElementType());
1471 if (ToElementType.isNull())
1474 return Importer.getToContext().getComplexType(ToElementType);
1477 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1478 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1479 if (ToPointeeType.isNull())
1482 return Importer.getToContext().getPointerType(ToPointeeType);
1485 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1486 // FIXME: Check for blocks support in "to" context.
1487 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1488 if (ToPointeeType.isNull())
1491 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1495 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1496 // FIXME: Check for C++ support in "to" context.
1497 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1498 if (ToPointeeType.isNull())
1501 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1505 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1506 // FIXME: Check for C++0x support in "to" context.
1507 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1508 if (ToPointeeType.isNull())
1511 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1514 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1515 // FIXME: Check for C++ support in "to" context.
1516 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1517 if (ToPointeeType.isNull())
1520 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1521 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1522 ClassType.getTypePtr());
1525 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1526 QualType ToElementType = Importer.Import(T->getElementType());
1527 if (ToElementType.isNull())
1530 return Importer.getToContext().getConstantArrayType(ToElementType,
1532 T->getSizeModifier(),
1533 T->getIndexTypeCVRQualifiers());
1537 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1538 QualType ToElementType = Importer.Import(T->getElementType());
1539 if (ToElementType.isNull())
1542 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1543 T->getSizeModifier(),
1544 T->getIndexTypeCVRQualifiers());
1547 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1548 QualType ToElementType = Importer.Import(T->getElementType());
1549 if (ToElementType.isNull())
1552 Expr *Size = Importer.Import(T->getSizeExpr());
1556 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1557 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1558 T->getSizeModifier(),
1559 T->getIndexTypeCVRQualifiers(),
1563 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1564 QualType ToElementType = Importer.Import(T->getElementType());
1565 if (ToElementType.isNull())
1568 return Importer.getToContext().getVectorType(ToElementType,
1569 T->getNumElements(),
1570 T->getVectorKind());
1573 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1574 QualType ToElementType = Importer.Import(T->getElementType());
1575 if (ToElementType.isNull())
1578 return Importer.getToContext().getExtVectorType(ToElementType,
1579 T->getNumElements());
1583 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1584 // FIXME: What happens if we're importing a function without a prototype
1585 // into C++? Should we make it variadic?
1586 QualType ToResultType = Importer.Import(T->getReturnType());
1587 if (ToResultType.isNull())
1590 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1594 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1595 QualType ToResultType = Importer.Import(T->getReturnType());
1596 if (ToResultType.isNull())
1599 // Import argument types
1600 SmallVector<QualType, 4> ArgTypes;
1601 for (const auto &A : T->param_types()) {
1602 QualType ArgType = Importer.Import(A);
1603 if (ArgType.isNull())
1605 ArgTypes.push_back(ArgType);
1608 // Import exception types
1609 SmallVector<QualType, 4> ExceptionTypes;
1610 for (FunctionProtoType::exception_iterator E = T->exception_begin(),
1611 EEnd = T->exception_end();
1613 QualType ExceptionType = Importer.Import(*E);
1614 if (ExceptionType.isNull())
1616 ExceptionTypes.push_back(ExceptionType);
1619 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1620 FunctionProtoType::ExtProtoInfo ToEPI;
1622 ToEPI.ExtInfo = FromEPI.ExtInfo;
1623 ToEPI.Variadic = FromEPI.Variadic;
1624 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1625 ToEPI.TypeQuals = FromEPI.TypeQuals;
1626 ToEPI.RefQualifier = FromEPI.RefQualifier;
1627 ToEPI.NumExceptions = ExceptionTypes.size();
1628 ToEPI.Exceptions = ExceptionTypes.data();
1629 ToEPI.ConsumedParameters = FromEPI.ConsumedParameters;
1630 ToEPI.ExceptionSpecType = FromEPI.ExceptionSpecType;
1631 ToEPI.NoexceptExpr = Importer.Import(FromEPI.NoexceptExpr);
1632 ToEPI.ExceptionSpecDecl = cast_or_null<FunctionDecl>(
1633 Importer.Import(FromEPI.ExceptionSpecDecl));
1634 ToEPI.ExceptionSpecTemplate = cast_or_null<FunctionDecl>(
1635 Importer.Import(FromEPI.ExceptionSpecTemplate));
1637 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1640 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1641 QualType ToInnerType = Importer.Import(T->getInnerType());
1642 if (ToInnerType.isNull())
1645 return Importer.getToContext().getParenType(ToInnerType);
1648 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1649 TypedefNameDecl *ToDecl
1650 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1654 return Importer.getToContext().getTypeDeclType(ToDecl);
1657 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1658 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1662 return Importer.getToContext().getTypeOfExprType(ToExpr);
1665 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1666 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1667 if (ToUnderlyingType.isNull())
1670 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1673 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1674 // FIXME: Make sure that the "to" context supports C++0x!
1675 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1679 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1680 if (UnderlyingType.isNull())
1683 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1686 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1687 QualType ToBaseType = Importer.Import(T->getBaseType());
1688 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1689 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1692 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1697 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1698 // FIXME: Make sure that the "to" context supports C++11!
1699 QualType FromDeduced = T->getDeducedType();
1701 if (!FromDeduced.isNull()) {
1702 ToDeduced = Importer.Import(FromDeduced);
1703 if (ToDeduced.isNull())
1707 return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto(),
1708 /*IsDependent*/false);
1711 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1713 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1717 return Importer.getToContext().getTagDeclType(ToDecl);
1720 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1722 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1726 return Importer.getToContext().getTagDeclType(ToDecl);
1729 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1730 const TemplateSpecializationType *T) {
1731 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1732 if (ToTemplate.isNull())
1735 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1736 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1739 QualType ToCanonType;
1740 if (!QualType(T, 0).isCanonical()) {
1741 QualType FromCanonType
1742 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1743 ToCanonType =Importer.Import(FromCanonType);
1744 if (ToCanonType.isNull())
1747 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1748 ToTemplateArgs.data(),
1749 ToTemplateArgs.size(),
1753 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1754 NestedNameSpecifier *ToQualifier = 0;
1755 // Note: the qualifier in an ElaboratedType is optional.
1756 if (T->getQualifier()) {
1757 ToQualifier = Importer.Import(T->getQualifier());
1762 QualType ToNamedType = Importer.Import(T->getNamedType());
1763 if (ToNamedType.isNull())
1766 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1767 ToQualifier, ToNamedType);
1770 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1771 ObjCInterfaceDecl *Class
1772 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1776 return Importer.getToContext().getObjCInterfaceType(Class);
1779 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1780 QualType ToBaseType = Importer.Import(T->getBaseType());
1781 if (ToBaseType.isNull())
1784 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1785 for (ObjCObjectType::qual_iterator P = T->qual_begin(),
1786 PEnd = T->qual_end();
1788 ObjCProtocolDecl *Protocol
1789 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(*P));
1792 Protocols.push_back(Protocol);
1795 return Importer.getToContext().getObjCObjectType(ToBaseType,
1801 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1802 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1803 if (ToPointeeType.isNull())
1806 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1809 //----------------------------------------------------------------------------
1810 // Import Declarations
1811 //----------------------------------------------------------------------------
1812 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1813 DeclContext *&LexicalDC,
1814 DeclarationName &Name,
1815 SourceLocation &Loc) {
1816 // Import the context of this declaration.
1817 DC = Importer.ImportContext(D->getDeclContext());
1822 if (D->getDeclContext() != D->getLexicalDeclContext()) {
1823 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1828 // Import the name of this declaration.
1829 Name = Importer.Import(D->getDeclName());
1830 if (D->getDeclName() && !Name)
1833 // Import the location of this declaration.
1834 Loc = Importer.Import(D->getLocation());
1838 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1843 ToD = Importer.Import(FromD);
1848 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1849 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1850 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1851 ImportDefinition(FromRecord, ToRecord);
1857 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1858 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1859 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1860 ImportDefinition(FromEnum, ToEnum);
1868 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1869 DeclarationNameInfo& To) {
1870 // NOTE: To.Name and To.Loc are already imported.
1871 // We only have to import To.LocInfo.
1872 switch (To.getName().getNameKind()) {
1873 case DeclarationName::Identifier:
1874 case DeclarationName::ObjCZeroArgSelector:
1875 case DeclarationName::ObjCOneArgSelector:
1876 case DeclarationName::ObjCMultiArgSelector:
1877 case DeclarationName::CXXUsingDirective:
1880 case DeclarationName::CXXOperatorName: {
1881 SourceRange Range = From.getCXXOperatorNameRange();
1882 To.setCXXOperatorNameRange(Importer.Import(Range));
1885 case DeclarationName::CXXLiteralOperatorName: {
1886 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1887 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1890 case DeclarationName::CXXConstructorName:
1891 case DeclarationName::CXXDestructorName:
1892 case DeclarationName::CXXConversionFunctionName: {
1893 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1894 To.setNamedTypeInfo(Importer.Import(FromTInfo));
1898 llvm_unreachable("Unknown name kind.");
1901 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1902 if (Importer.isMinimalImport() && !ForceImport) {
1903 Importer.ImportContext(FromDC);
1907 for (auto *From : FromDC->decls())
1908 Importer.Import(From);
1911 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1912 ImportDefinitionKind Kind) {
1913 if (To->getDefinition() || To->isBeingDefined()) {
1914 if (Kind == IDK_Everything)
1915 ImportDeclContext(From, /*ForceImport=*/true);
1920 To->startDefinition();
1922 // Add base classes.
1923 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1924 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1926 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1927 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1928 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1929 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1930 ToData.Aggregate = FromData.Aggregate;
1931 ToData.PlainOldData = FromData.PlainOldData;
1932 ToData.Empty = FromData.Empty;
1933 ToData.Polymorphic = FromData.Polymorphic;
1934 ToData.Abstract = FromData.Abstract;
1935 ToData.IsStandardLayout = FromData.IsStandardLayout;
1936 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
1937 ToData.HasPrivateFields = FromData.HasPrivateFields;
1938 ToData.HasProtectedFields = FromData.HasProtectedFields;
1939 ToData.HasPublicFields = FromData.HasPublicFields;
1940 ToData.HasMutableFields = FromData.HasMutableFields;
1941 ToData.HasVariantMembers = FromData.HasVariantMembers;
1942 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1943 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1944 ToData.HasUninitializedReferenceMember
1945 = FromData.HasUninitializedReferenceMember;
1946 ToData.NeedOverloadResolutionForMoveConstructor
1947 = FromData.NeedOverloadResolutionForMoveConstructor;
1948 ToData.NeedOverloadResolutionForMoveAssignment
1949 = FromData.NeedOverloadResolutionForMoveAssignment;
1950 ToData.NeedOverloadResolutionForDestructor
1951 = FromData.NeedOverloadResolutionForDestructor;
1952 ToData.DefaultedMoveConstructorIsDeleted
1953 = FromData.DefaultedMoveConstructorIsDeleted;
1954 ToData.DefaultedMoveAssignmentIsDeleted
1955 = FromData.DefaultedMoveAssignmentIsDeleted;
1956 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1957 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1958 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1959 ToData.HasConstexprNonCopyMoveConstructor
1960 = FromData.HasConstexprNonCopyMoveConstructor;
1961 ToData.DefaultedDefaultConstructorIsConstexpr
1962 = FromData.DefaultedDefaultConstructorIsConstexpr;
1963 ToData.HasConstexprDefaultConstructor
1964 = FromData.HasConstexprDefaultConstructor;
1965 ToData.HasNonLiteralTypeFieldsOrBases
1966 = FromData.HasNonLiteralTypeFieldsOrBases;
1967 // ComputedVisibleConversions not imported.
1968 ToData.UserProvidedDefaultConstructor
1969 = FromData.UserProvidedDefaultConstructor;
1970 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1971 ToData.ImplicitCopyConstructorHasConstParam
1972 = FromData.ImplicitCopyConstructorHasConstParam;
1973 ToData.ImplicitCopyAssignmentHasConstParam
1974 = FromData.ImplicitCopyAssignmentHasConstParam;
1975 ToData.HasDeclaredCopyConstructorWithConstParam
1976 = FromData.HasDeclaredCopyConstructorWithConstParam;
1977 ToData.HasDeclaredCopyAssignmentWithConstParam
1978 = FromData.HasDeclaredCopyAssignmentWithConstParam;
1979 ToData.IsLambda = FromData.IsLambda;
1981 SmallVector<CXXBaseSpecifier *, 4> Bases;
1982 for (const auto &Base1 : FromCXX->bases()) {
1983 QualType T = Importer.Import(Base1.getType());
1987 SourceLocation EllipsisLoc;
1988 if (Base1.isPackExpansion())
1989 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
1991 // Ensure that we have a definition for the base.
1992 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
1995 new (Importer.getToContext())
1996 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
1998 Base1.isBaseOfClass(),
1999 Base1.getAccessSpecifierAsWritten(),
2000 Importer.Import(Base1.getTypeSourceInfo()),
2004 ToCXX->setBases(Bases.data(), Bases.size());
2007 if (shouldForceImportDeclContext(Kind))
2008 ImportDeclContext(From, /*ForceImport=*/true);
2010 To->completeDefinition();
2014 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2015 ImportDefinitionKind Kind) {
2016 if (To->getDefinition())
2019 // FIXME: Can we really import any initializer? Alternatively, we could force
2020 // ourselves to import every declaration of a variable and then only use
2022 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2024 // FIXME: Other bits to merge?
2029 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2030 ImportDefinitionKind Kind) {
2031 if (To->getDefinition() || To->isBeingDefined()) {
2032 if (Kind == IDK_Everything)
2033 ImportDeclContext(From, /*ForceImport=*/true);
2037 To->startDefinition();
2039 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2043 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2044 if (ToPromotionType.isNull())
2047 if (shouldForceImportDeclContext(Kind))
2048 ImportDeclContext(From, /*ForceImport=*/true);
2050 // FIXME: we might need to merge the number of positive or negative bits
2051 // if the enumerator lists don't match.
2052 To->completeDefinition(T, ToPromotionType,
2053 From->getNumPositiveBits(),
2054 From->getNumNegativeBits());
2058 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2059 TemplateParameterList *Params) {
2060 SmallVector<NamedDecl *, 4> ToParams;
2061 ToParams.reserve(Params->size());
2062 for (TemplateParameterList::iterator P = Params->begin(),
2063 PEnd = Params->end();
2065 Decl *To = Importer.Import(*P);
2069 ToParams.push_back(cast<NamedDecl>(To));
2072 return TemplateParameterList::Create(Importer.getToContext(),
2073 Importer.Import(Params->getTemplateLoc()),
2074 Importer.Import(Params->getLAngleLoc()),
2075 ToParams.data(), ToParams.size(),
2076 Importer.Import(Params->getRAngleLoc()));
2080 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2081 switch (From.getKind()) {
2082 case TemplateArgument::Null:
2083 return TemplateArgument();
2085 case TemplateArgument::Type: {
2086 QualType ToType = Importer.Import(From.getAsType());
2087 if (ToType.isNull())
2088 return TemplateArgument();
2089 return TemplateArgument(ToType);
2092 case TemplateArgument::Integral: {
2093 QualType ToType = Importer.Import(From.getIntegralType());
2094 if (ToType.isNull())
2095 return TemplateArgument();
2096 return TemplateArgument(From, ToType);
2099 case TemplateArgument::Declaration: {
2100 ValueDecl *FromD = From.getAsDecl();
2101 if (ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(FromD)))
2102 return TemplateArgument(To, From.isDeclForReferenceParam());
2103 return TemplateArgument();
2106 case TemplateArgument::NullPtr: {
2107 QualType ToType = Importer.Import(From.getNullPtrType());
2108 if (ToType.isNull())
2109 return TemplateArgument();
2110 return TemplateArgument(ToType, /*isNullPtr*/true);
2113 case TemplateArgument::Template: {
2114 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2115 if (ToTemplate.isNull())
2116 return TemplateArgument();
2118 return TemplateArgument(ToTemplate);
2121 case TemplateArgument::TemplateExpansion: {
2122 TemplateName ToTemplate
2123 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2124 if (ToTemplate.isNull())
2125 return TemplateArgument();
2127 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2130 case TemplateArgument::Expression:
2131 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2132 return TemplateArgument(ToExpr);
2133 return TemplateArgument();
2135 case TemplateArgument::Pack: {
2136 SmallVector<TemplateArgument, 2> ToPack;
2137 ToPack.reserve(From.pack_size());
2138 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2139 return TemplateArgument();
2141 TemplateArgument *ToArgs
2142 = new (Importer.getToContext()) TemplateArgument[ToPack.size()];
2143 std::copy(ToPack.begin(), ToPack.end(), ToArgs);
2144 return TemplateArgument(ToArgs, ToPack.size());
2148 llvm_unreachable("Invalid template argument kind");
2151 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2152 unsigned NumFromArgs,
2153 SmallVectorImpl<TemplateArgument> &ToArgs) {
2154 for (unsigned I = 0; I != NumFromArgs; ++I) {
2155 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2156 if (To.isNull() && !FromArgs[I].isNull())
2159 ToArgs.push_back(To);
2165 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2166 RecordDecl *ToRecord, bool Complain) {
2167 // Eliminate a potential failure point where we attempt to re-import
2168 // something we're trying to import while completing ToRecord.
2169 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2171 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2173 ToRecord = ToOriginRecord;
2176 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2177 ToRecord->getASTContext(),
2178 Importer.getNonEquivalentDecls(),
2180 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2183 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2185 StructuralEquivalenceContext Ctx(
2186 Importer.getFromContext(), Importer.getToContext(),
2187 Importer.getNonEquivalentDecls(), false, Complain);
2188 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2191 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2192 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2193 Importer.getToContext(),
2194 Importer.getNonEquivalentDecls());
2195 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2198 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2199 EnumConstantDecl *ToEC)
2201 const llvm::APSInt &FromVal = FromEC->getInitVal();
2202 const llvm::APSInt &ToVal = ToEC->getInitVal();
2204 return FromVal.isSigned() == ToVal.isSigned() &&
2205 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2209 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2210 ClassTemplateDecl *To) {
2211 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2212 Importer.getToContext(),
2213 Importer.getNonEquivalentDecls());
2214 return Ctx.IsStructurallyEquivalent(From, To);
2217 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2218 VarTemplateDecl *To) {
2219 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2220 Importer.getToContext(),
2221 Importer.getNonEquivalentDecls());
2222 return Ctx.IsStructurallyEquivalent(From, To);
2225 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2226 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2227 << D->getDeclKindName();
2231 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2232 TranslationUnitDecl *ToD =
2233 Importer.getToContext().getTranslationUnitDecl();
2235 Importer.Imported(D, ToD);
2240 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2241 // Import the major distinguishing characteristics of this namespace.
2242 DeclContext *DC, *LexicalDC;
2243 DeclarationName Name;
2245 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2248 NamespaceDecl *MergeWithNamespace = 0;
2250 // This is an anonymous namespace. Adopt an existing anonymous
2251 // namespace if we can.
2252 // FIXME: Not testable.
2253 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2254 MergeWithNamespace = TU->getAnonymousNamespace();
2256 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2258 SmallVector<NamedDecl *, 4> ConflictingDecls;
2259 SmallVector<NamedDecl *, 2> FoundDecls;
2260 DC->localUncachedLookup(Name, FoundDecls);
2261 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2262 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2265 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2266 MergeWithNamespace = FoundNS;
2267 ConflictingDecls.clear();
2271 ConflictingDecls.push_back(FoundDecls[I]);
2274 if (!ConflictingDecls.empty()) {
2275 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2276 ConflictingDecls.data(),
2277 ConflictingDecls.size());
2281 // Create the "to" namespace, if needed.
2282 NamespaceDecl *ToNamespace = MergeWithNamespace;
2284 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2286 Importer.Import(D->getLocStart()),
2287 Loc, Name.getAsIdentifierInfo(),
2289 ToNamespace->setLexicalDeclContext(LexicalDC);
2290 LexicalDC->addDeclInternal(ToNamespace);
2292 // If this is an anonymous namespace, register it as the anonymous
2293 // namespace within its context.
2295 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2296 TU->setAnonymousNamespace(ToNamespace);
2298 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2301 Importer.Imported(D, ToNamespace);
2303 ImportDeclContext(D);
2308 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2309 // Import the major distinguishing characteristics of this typedef.
2310 DeclContext *DC, *LexicalDC;
2311 DeclarationName Name;
2313 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2316 // If this typedef is not in block scope, determine whether we've
2317 // seen a typedef with the same name (that we can merge with) or any
2318 // other entity by that name (which name lookup could conflict with).
2319 if (!DC->isFunctionOrMethod()) {
2320 SmallVector<NamedDecl *, 4> ConflictingDecls;
2321 unsigned IDNS = Decl::IDNS_Ordinary;
2322 SmallVector<NamedDecl *, 2> FoundDecls;
2323 DC->localUncachedLookup(Name, FoundDecls);
2324 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2325 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2327 if (TypedefNameDecl *FoundTypedef =
2328 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2329 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2330 FoundTypedef->getUnderlyingType()))
2331 return Importer.Imported(D, FoundTypedef);
2334 ConflictingDecls.push_back(FoundDecls[I]);
2337 if (!ConflictingDecls.empty()) {
2338 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2339 ConflictingDecls.data(),
2340 ConflictingDecls.size());
2346 // Import the underlying type of this typedef;
2347 QualType T = Importer.Import(D->getUnderlyingType());
2351 // Create the new typedef node.
2352 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2353 SourceLocation StartL = Importer.Import(D->getLocStart());
2354 TypedefNameDecl *ToTypedef;
2356 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2358 Name.getAsIdentifierInfo(),
2361 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2363 Name.getAsIdentifierInfo(),
2366 ToTypedef->setAccess(D->getAccess());
2367 ToTypedef->setLexicalDeclContext(LexicalDC);
2368 Importer.Imported(D, ToTypedef);
2369 LexicalDC->addDeclInternal(ToTypedef);
2374 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2375 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2378 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2379 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2382 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2383 // Import the major distinguishing characteristics of this enum.
2384 DeclContext *DC, *LexicalDC;
2385 DeclarationName Name;
2387 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2390 // Figure out what enum name we're looking for.
2391 unsigned IDNS = Decl::IDNS_Tag;
2392 DeclarationName SearchName = Name;
2393 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2394 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2395 IDNS = Decl::IDNS_Ordinary;
2396 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2397 IDNS |= Decl::IDNS_Ordinary;
2399 // We may already have an enum of the same name; try to find and match it.
2400 if (!DC->isFunctionOrMethod() && SearchName) {
2401 SmallVector<NamedDecl *, 4> ConflictingDecls;
2402 SmallVector<NamedDecl *, 2> FoundDecls;
2403 DC->localUncachedLookup(SearchName, FoundDecls);
2404 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2405 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2408 Decl *Found = FoundDecls[I];
2409 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2410 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2411 Found = Tag->getDecl();
2414 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2415 if (IsStructuralMatch(D, FoundEnum))
2416 return Importer.Imported(D, FoundEnum);
2419 ConflictingDecls.push_back(FoundDecls[I]);
2422 if (!ConflictingDecls.empty()) {
2423 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2424 ConflictingDecls.data(),
2425 ConflictingDecls.size());
2429 // Create the enum declaration.
2430 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2431 Importer.Import(D->getLocStart()),
2432 Loc, Name.getAsIdentifierInfo(), 0,
2433 D->isScoped(), D->isScopedUsingClassTag(),
2435 // Import the qualifier, if any.
2436 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2437 D2->setAccess(D->getAccess());
2438 D2->setLexicalDeclContext(LexicalDC);
2439 Importer.Imported(D, D2);
2440 LexicalDC->addDeclInternal(D2);
2442 // Import the integer type.
2443 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2444 if (ToIntegerType.isNull())
2446 D2->setIntegerType(ToIntegerType);
2448 // Import the definition
2449 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2455 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2456 // If this record has a definition in the translation unit we're coming from,
2457 // but this particular declaration is not that definition, import the
2458 // definition and map to that.
2459 TagDecl *Definition = D->getDefinition();
2460 if (Definition && Definition != D) {
2461 Decl *ImportedDef = Importer.Import(Definition);
2465 return Importer.Imported(D, ImportedDef);
2468 // Import the major distinguishing characteristics of this record.
2469 DeclContext *DC, *LexicalDC;
2470 DeclarationName Name;
2472 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2475 // Figure out what structure name we're looking for.
2476 unsigned IDNS = Decl::IDNS_Tag;
2477 DeclarationName SearchName = Name;
2478 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2479 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2480 IDNS = Decl::IDNS_Ordinary;
2481 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2482 IDNS |= Decl::IDNS_Ordinary;
2484 // We may already have a record of the same name; try to find and match it.
2485 RecordDecl *AdoptDecl = 0;
2486 if (!DC->isFunctionOrMethod()) {
2487 SmallVector<NamedDecl *, 4> ConflictingDecls;
2488 SmallVector<NamedDecl *, 2> FoundDecls;
2489 DC->localUncachedLookup(SearchName, FoundDecls);
2490 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2491 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2494 Decl *Found = FoundDecls[I];
2495 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2496 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2497 Found = Tag->getDecl();
2500 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2501 if (D->isAnonymousStructOrUnion() &&
2502 FoundRecord->isAnonymousStructOrUnion()) {
2503 // If both anonymous structs/unions are in a record context, make sure
2504 // they occur in the same location in the context records.
2505 if (Optional<unsigned> Index1
2506 = findAnonymousStructOrUnionIndex(D)) {
2507 if (Optional<unsigned> Index2 =
2508 findAnonymousStructOrUnionIndex(FoundRecord)) {
2509 if (*Index1 != *Index2)
2515 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2516 if ((SearchName && !D->isCompleteDefinition())
2517 || (D->isCompleteDefinition() &&
2518 D->isAnonymousStructOrUnion()
2519 == FoundDef->isAnonymousStructOrUnion() &&
2520 IsStructuralMatch(D, FoundDef))) {
2521 // The record types structurally match, or the "from" translation
2522 // unit only had a forward declaration anyway; call it the same
2524 // FIXME: For C++, we should also merge methods here.
2525 return Importer.Imported(D, FoundDef);
2527 } else if (!D->isCompleteDefinition()) {
2528 // We have a forward declaration of this type, so adopt that forward
2529 // declaration rather than building a new one.
2531 // If one or both can be completed from external storage then try one
2532 // last time to complete and compare them before doing this.
2534 if (FoundRecord->hasExternalLexicalStorage() &&
2535 !FoundRecord->isCompleteDefinition())
2536 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2537 if (D->hasExternalLexicalStorage())
2538 D->getASTContext().getExternalSource()->CompleteType(D);
2540 if (FoundRecord->isCompleteDefinition() &&
2541 D->isCompleteDefinition() &&
2542 !IsStructuralMatch(D, FoundRecord))
2545 AdoptDecl = FoundRecord;
2547 } else if (!SearchName) {
2552 ConflictingDecls.push_back(FoundDecls[I]);
2555 if (!ConflictingDecls.empty() && SearchName) {
2556 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2557 ConflictingDecls.data(),
2558 ConflictingDecls.size());
2562 // Create the record declaration.
2563 RecordDecl *D2 = AdoptDecl;
2564 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2566 if (isa<CXXRecordDecl>(D)) {
2567 CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2570 Name.getAsIdentifierInfo());
2572 D2->setAccess(D->getAccess());
2574 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2575 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2578 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2579 D2->setLexicalDeclContext(LexicalDC);
2580 LexicalDC->addDeclInternal(D2);
2581 if (D->isAnonymousStructOrUnion())
2582 D2->setAnonymousStructOrUnion(true);
2585 Importer.Imported(D, D2);
2587 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2593 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2594 // Import the major distinguishing characteristics of this enumerator.
2595 DeclContext *DC, *LexicalDC;
2596 DeclarationName Name;
2598 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2601 QualType T = Importer.Import(D->getType());
2605 // Determine whether there are any other declarations with the same name and
2606 // in the same context.
2607 if (!LexicalDC->isFunctionOrMethod()) {
2608 SmallVector<NamedDecl *, 4> ConflictingDecls;
2609 unsigned IDNS = Decl::IDNS_Ordinary;
2610 SmallVector<NamedDecl *, 2> FoundDecls;
2611 DC->localUncachedLookup(Name, FoundDecls);
2612 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2613 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2616 if (EnumConstantDecl *FoundEnumConstant
2617 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2618 if (IsStructuralMatch(D, FoundEnumConstant))
2619 return Importer.Imported(D, FoundEnumConstant);
2622 ConflictingDecls.push_back(FoundDecls[I]);
2625 if (!ConflictingDecls.empty()) {
2626 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2627 ConflictingDecls.data(),
2628 ConflictingDecls.size());
2634 Expr *Init = Importer.Import(D->getInitExpr());
2635 if (D->getInitExpr() && !Init)
2638 EnumConstantDecl *ToEnumerator
2639 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2640 Name.getAsIdentifierInfo(), T,
2641 Init, D->getInitVal());
2642 ToEnumerator->setAccess(D->getAccess());
2643 ToEnumerator->setLexicalDeclContext(LexicalDC);
2644 Importer.Imported(D, ToEnumerator);
2645 LexicalDC->addDeclInternal(ToEnumerator);
2646 return ToEnumerator;
2649 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2650 // Import the major distinguishing characteristics of this function.
2651 DeclContext *DC, *LexicalDC;
2652 DeclarationName Name;
2654 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2657 // Try to find a function in our own ("to") context with the same name, same
2658 // type, and in the same context as the function we're importing.
2659 if (!LexicalDC->isFunctionOrMethod()) {
2660 SmallVector<NamedDecl *, 4> ConflictingDecls;
2661 unsigned IDNS = Decl::IDNS_Ordinary;
2662 SmallVector<NamedDecl *, 2> FoundDecls;
2663 DC->localUncachedLookup(Name, FoundDecls);
2664 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2665 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2668 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2669 if (FoundFunction->hasExternalFormalLinkage() &&
2670 D->hasExternalFormalLinkage()) {
2671 if (Importer.IsStructurallyEquivalent(D->getType(),
2672 FoundFunction->getType())) {
2673 // FIXME: Actually try to merge the body and other attributes.
2674 return Importer.Imported(D, FoundFunction);
2677 // FIXME: Check for overloading more carefully, e.g., by boosting
2678 // Sema::IsOverload out to the AST library.
2680 // Function overloading is okay in C++.
2681 if (Importer.getToContext().getLangOpts().CPlusPlus)
2684 // Complain about inconsistent function types.
2685 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2686 << Name << D->getType() << FoundFunction->getType();
2687 Importer.ToDiag(FoundFunction->getLocation(),
2688 diag::note_odr_value_here)
2689 << FoundFunction->getType();
2693 ConflictingDecls.push_back(FoundDecls[I]);
2696 if (!ConflictingDecls.empty()) {
2697 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2698 ConflictingDecls.data(),
2699 ConflictingDecls.size());
2705 DeclarationNameInfo NameInfo(Name, Loc);
2706 // Import additional name location/type info.
2707 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2709 QualType FromTy = D->getType();
2710 bool usedDifferentExceptionSpec = false;
2712 if (const FunctionProtoType *
2713 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2714 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2715 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2716 // FunctionDecl that we are importing the FunctionProtoType for.
2717 // To avoid an infinite recursion when importing, create the FunctionDecl
2718 // with a simplified function type and update it afterwards.
2719 if (FromEPI.ExceptionSpecDecl || FromEPI.ExceptionSpecTemplate ||
2720 FromEPI.NoexceptExpr) {
2721 FunctionProtoType::ExtProtoInfo DefaultEPI;
2722 FromTy = Importer.getFromContext().getFunctionType(
2723 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2724 usedDifferentExceptionSpec = true;
2729 QualType T = Importer.Import(FromTy);
2733 // Import the function parameters.
2734 SmallVector<ParmVarDecl *, 8> Parameters;
2735 for (auto P : D->params()) {
2736 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2740 Parameters.push_back(ToP);
2743 // Create the imported function.
2744 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2745 FunctionDecl *ToFunction = 0;
2746 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2747 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2748 cast<CXXRecordDecl>(DC),
2749 D->getInnerLocStart(),
2751 FromConstructor->isExplicit(),
2752 D->isInlineSpecified(),
2755 } else if (isa<CXXDestructorDecl>(D)) {
2756 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2757 cast<CXXRecordDecl>(DC),
2758 D->getInnerLocStart(),
2760 D->isInlineSpecified(),
2762 } else if (CXXConversionDecl *FromConversion
2763 = dyn_cast<CXXConversionDecl>(D)) {
2764 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2765 cast<CXXRecordDecl>(DC),
2766 D->getInnerLocStart(),
2768 D->isInlineSpecified(),
2769 FromConversion->isExplicit(),
2771 Importer.Import(D->getLocEnd()));
2772 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2773 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2774 cast<CXXRecordDecl>(DC),
2775 D->getInnerLocStart(),
2777 Method->getStorageClass(),
2778 Method->isInlineSpecified(),
2780 Importer.Import(D->getLocEnd()));
2782 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2783 D->getInnerLocStart(),
2784 NameInfo, T, TInfo, D->getStorageClass(),
2785 D->isInlineSpecified(),
2786 D->hasWrittenPrototype(),
2790 // Import the qualifier, if any.
2791 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2792 ToFunction->setAccess(D->getAccess());
2793 ToFunction->setLexicalDeclContext(LexicalDC);
2794 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2795 ToFunction->setTrivial(D->isTrivial());
2796 ToFunction->setPure(D->isPure());
2797 Importer.Imported(D, ToFunction);
2799 // Set the parameters.
2800 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2801 Parameters[I]->setOwningFunction(ToFunction);
2802 ToFunction->addDeclInternal(Parameters[I]);
2804 ToFunction->setParams(Parameters);
2806 if (usedDifferentExceptionSpec) {
2807 // Update FunctionProtoType::ExtProtoInfo.
2808 QualType T = Importer.Import(D->getType());
2811 ToFunction->setType(T);
2814 // FIXME: Other bits to merge?
2816 // Add this function to the lexical context.
2817 LexicalDC->addDeclInternal(ToFunction);
2822 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2823 return VisitFunctionDecl(D);
2826 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2827 return VisitCXXMethodDecl(D);
2830 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2831 return VisitCXXMethodDecl(D);
2834 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2835 return VisitCXXMethodDecl(D);
2838 static unsigned getFieldIndex(Decl *F) {
2839 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2844 for (const auto *D : Owner->noload_decls()) {
2848 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2855 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2856 // Import the major distinguishing characteristics of a variable.
2857 DeclContext *DC, *LexicalDC;
2858 DeclarationName Name;
2860 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2863 // Determine whether we've already imported this field.
2864 SmallVector<NamedDecl *, 2> FoundDecls;
2865 DC->localUncachedLookup(Name, FoundDecls);
2866 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2867 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2868 // For anonymous fields, match up by index.
2869 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2872 if (Importer.IsStructurallyEquivalent(D->getType(),
2873 FoundField->getType())) {
2874 Importer.Imported(D, FoundField);
2878 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2879 << Name << D->getType() << FoundField->getType();
2880 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2881 << FoundField->getType();
2887 QualType T = Importer.Import(D->getType());
2891 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2892 Expr *BitWidth = Importer.Import(D->getBitWidth());
2893 if (!BitWidth && D->getBitWidth())
2896 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2897 Importer.Import(D->getInnerLocStart()),
2898 Loc, Name.getAsIdentifierInfo(),
2899 T, TInfo, BitWidth, D->isMutable(),
2900 D->getInClassInitStyle());
2901 ToField->setAccess(D->getAccess());
2902 ToField->setLexicalDeclContext(LexicalDC);
2903 if (ToField->hasInClassInitializer())
2904 ToField->setInClassInitializer(D->getInClassInitializer());
2905 ToField->setImplicit(D->isImplicit());
2906 Importer.Imported(D, ToField);
2907 LexicalDC->addDeclInternal(ToField);
2911 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2912 // Import the major distinguishing characteristics of a variable.
2913 DeclContext *DC, *LexicalDC;
2914 DeclarationName Name;
2916 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2919 // Determine whether we've already imported this field.
2920 SmallVector<NamedDecl *, 2> FoundDecls;
2921 DC->localUncachedLookup(Name, FoundDecls);
2922 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2923 if (IndirectFieldDecl *FoundField
2924 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2925 // For anonymous indirect fields, match up by index.
2926 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2929 if (Importer.IsStructurallyEquivalent(D->getType(),
2930 FoundField->getType(),
2932 Importer.Imported(D, FoundField);
2936 // If there are more anonymous fields to check, continue.
2937 if (!Name && I < N-1)
2940 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2941 << Name << D->getType() << FoundField->getType();
2942 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2943 << FoundField->getType();
2949 QualType T = Importer.Import(D->getType());
2953 NamedDecl **NamedChain =
2954 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2957 for (auto *PI : D->chain()) {
2958 Decl *D = Importer.Import(PI);
2961 NamedChain[i++] = cast<NamedDecl>(D);
2964 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2965 Importer.getToContext(), DC,
2966 Loc, Name.getAsIdentifierInfo(), T,
2967 NamedChain, D->getChainingSize());
2968 ToIndirectField->setAccess(D->getAccess());
2969 ToIndirectField->setLexicalDeclContext(LexicalDC);
2970 Importer.Imported(D, ToIndirectField);
2971 LexicalDC->addDeclInternal(ToIndirectField);
2972 return ToIndirectField;
2975 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2976 // Import the major distinguishing characteristics of an ivar.
2977 DeclContext *DC, *LexicalDC;
2978 DeclarationName Name;
2980 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
2983 // Determine whether we've already imported this ivar
2984 SmallVector<NamedDecl *, 2> FoundDecls;
2985 DC->localUncachedLookup(Name, FoundDecls);
2986 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2987 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
2988 if (Importer.IsStructurallyEquivalent(D->getType(),
2989 FoundIvar->getType())) {
2990 Importer.Imported(D, FoundIvar);
2994 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2995 << Name << D->getType() << FoundIvar->getType();
2996 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2997 << FoundIvar->getType();
3003 QualType T = Importer.Import(D->getType());
3007 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3008 Expr *BitWidth = Importer.Import(D->getBitWidth());
3009 if (!BitWidth && D->getBitWidth())
3012 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3013 cast<ObjCContainerDecl>(DC),
3014 Importer.Import(D->getInnerLocStart()),
3015 Loc, Name.getAsIdentifierInfo(),
3016 T, TInfo, D->getAccessControl(),
3017 BitWidth, D->getSynthesize());
3018 ToIvar->setLexicalDeclContext(LexicalDC);
3019 Importer.Imported(D, ToIvar);
3020 LexicalDC->addDeclInternal(ToIvar);
3025 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3026 // Import the major distinguishing characteristics of a variable.
3027 DeclContext *DC, *LexicalDC;
3028 DeclarationName Name;
3030 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3033 // Try to find a variable in our own ("to") context with the same name and
3034 // in the same context as the variable we're importing.
3035 if (D->isFileVarDecl()) {
3036 VarDecl *MergeWithVar = 0;
3037 SmallVector<NamedDecl *, 4> ConflictingDecls;
3038 unsigned IDNS = Decl::IDNS_Ordinary;
3039 SmallVector<NamedDecl *, 2> FoundDecls;
3040 DC->localUncachedLookup(Name, FoundDecls);
3041 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3042 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3045 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3046 // We have found a variable that we may need to merge with. Check it.
3047 if (FoundVar->hasExternalFormalLinkage() &&
3048 D->hasExternalFormalLinkage()) {
3049 if (Importer.IsStructurallyEquivalent(D->getType(),
3050 FoundVar->getType())) {
3051 MergeWithVar = FoundVar;
3055 const ArrayType *FoundArray
3056 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3057 const ArrayType *TArray
3058 = Importer.getToContext().getAsArrayType(D->getType());
3059 if (FoundArray && TArray) {
3060 if (isa<IncompleteArrayType>(FoundArray) &&
3061 isa<ConstantArrayType>(TArray)) {
3063 QualType T = Importer.Import(D->getType());
3067 FoundVar->setType(T);
3068 MergeWithVar = FoundVar;
3070 } else if (isa<IncompleteArrayType>(TArray) &&
3071 isa<ConstantArrayType>(FoundArray)) {
3072 MergeWithVar = FoundVar;
3077 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3078 << Name << D->getType() << FoundVar->getType();
3079 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3080 << FoundVar->getType();
3084 ConflictingDecls.push_back(FoundDecls[I]);
3088 // An equivalent variable with external linkage has been found. Link
3089 // the two declarations, then merge them.
3090 Importer.Imported(D, MergeWithVar);
3092 if (VarDecl *DDef = D->getDefinition()) {
3093 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3094 Importer.ToDiag(ExistingDef->getLocation(),
3095 diag::err_odr_variable_multiple_def)
3097 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3099 Expr *Init = Importer.Import(DDef->getInit());
3100 MergeWithVar->setInit(Init);
3101 if (DDef->isInitKnownICE()) {
3102 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3103 Eval->CheckedICE = true;
3104 Eval->IsICE = DDef->isInitICE();
3109 return MergeWithVar;
3112 if (!ConflictingDecls.empty()) {
3113 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3114 ConflictingDecls.data(),
3115 ConflictingDecls.size());
3122 QualType T = Importer.Import(D->getType());
3126 // Create the imported variable.
3127 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3128 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3129 Importer.Import(D->getInnerLocStart()),
3130 Loc, Name.getAsIdentifierInfo(),
3132 D->getStorageClass());
3133 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3134 ToVar->setAccess(D->getAccess());
3135 ToVar->setLexicalDeclContext(LexicalDC);
3136 Importer.Imported(D, ToVar);
3137 LexicalDC->addDeclInternal(ToVar);
3139 // Merge the initializer.
3140 if (ImportDefinition(D, ToVar))
3146 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3147 // Parameters are created in the translation unit's context, then moved
3148 // into the function declaration's context afterward.
3149 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3151 // Import the name of this declaration.
3152 DeclarationName Name = Importer.Import(D->getDeclName());
3153 if (D->getDeclName() && !Name)
3156 // Import the location of this declaration.
3157 SourceLocation Loc = Importer.Import(D->getLocation());
3159 // Import the parameter's type.
3160 QualType T = Importer.Import(D->getType());
3164 // Create the imported parameter.
3165 ImplicitParamDecl *ToParm
3166 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3167 Loc, Name.getAsIdentifierInfo(),
3169 return Importer.Imported(D, ToParm);
3172 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3173 // Parameters are created in the translation unit's context, then moved
3174 // into the function declaration's context afterward.
3175 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3177 // Import the name of this declaration.
3178 DeclarationName Name = Importer.Import(D->getDeclName());
3179 if (D->getDeclName() && !Name)
3182 // Import the location of this declaration.
3183 SourceLocation Loc = Importer.Import(D->getLocation());
3185 // Import the parameter's type.
3186 QualType T = Importer.Import(D->getType());
3190 // Create the imported parameter.
3191 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3192 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3193 Importer.Import(D->getInnerLocStart()),
3194 Loc, Name.getAsIdentifierInfo(),
3195 T, TInfo, D->getStorageClass(),
3196 /*FIXME: Default argument*/ 0);
3197 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3198 return Importer.Imported(D, ToParm);
3201 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3202 // Import the major distinguishing characteristics of a method.
3203 DeclContext *DC, *LexicalDC;
3204 DeclarationName Name;
3206 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3209 SmallVector<NamedDecl *, 2> FoundDecls;
3210 DC->localUncachedLookup(Name, FoundDecls);
3211 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3212 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3213 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3216 // Check return types.
3217 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3218 FoundMethod->getReturnType())) {
3219 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3220 << D->isInstanceMethod() << Name << D->getReturnType()
3221 << FoundMethod->getReturnType();
3222 Importer.ToDiag(FoundMethod->getLocation(),
3223 diag::note_odr_objc_method_here)
3224 << D->isInstanceMethod() << Name;
3228 // Check the number of parameters.
3229 if (D->param_size() != FoundMethod->param_size()) {
3230 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3231 << D->isInstanceMethod() << Name
3232 << D->param_size() << FoundMethod->param_size();
3233 Importer.ToDiag(FoundMethod->getLocation(),
3234 diag::note_odr_objc_method_here)
3235 << D->isInstanceMethod() << Name;
3239 // Check parameter types.
3240 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3241 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3242 P != PEnd; ++P, ++FoundP) {
3243 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3244 (*FoundP)->getType())) {
3245 Importer.FromDiag((*P)->getLocation(),
3246 diag::err_odr_objc_method_param_type_inconsistent)
3247 << D->isInstanceMethod() << Name
3248 << (*P)->getType() << (*FoundP)->getType();
3249 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3250 << (*FoundP)->getType();
3255 // Check variadic/non-variadic.
3256 // Check the number of parameters.
3257 if (D->isVariadic() != FoundMethod->isVariadic()) {
3258 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3259 << D->isInstanceMethod() << Name;
3260 Importer.ToDiag(FoundMethod->getLocation(),
3261 diag::note_odr_objc_method_here)
3262 << D->isInstanceMethod() << Name;
3266 // FIXME: Any other bits we need to merge?
3267 return Importer.Imported(D, FoundMethod);
3271 // Import the result type.
3272 QualType ResultTy = Importer.Import(D->getReturnType());
3273 if (ResultTy.isNull())
3276 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3278 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3279 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3280 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3281 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3282 D->getImplementationControl(), D->hasRelatedResultType());
3284 // FIXME: When we decide to merge method definitions, we'll need to
3285 // deal with implicit parameters.
3287 // Import the parameters
3288 SmallVector<ParmVarDecl *, 5> ToParams;
3289 for (auto *FromP : D->params()) {
3290 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3294 ToParams.push_back(ToP);
3297 // Set the parameters.
3298 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3299 ToParams[I]->setOwningFunction(ToMethod);
3300 ToMethod->addDeclInternal(ToParams[I]);
3302 SmallVector<SourceLocation, 12> SelLocs;
3303 D->getSelectorLocs(SelLocs);
3304 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3306 ToMethod->setLexicalDeclContext(LexicalDC);
3307 Importer.Imported(D, ToMethod);
3308 LexicalDC->addDeclInternal(ToMethod);
3312 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3313 // Import the major distinguishing characteristics of a category.
3314 DeclContext *DC, *LexicalDC;
3315 DeclarationName Name;
3317 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3320 ObjCInterfaceDecl *ToInterface
3321 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3325 // Determine if we've already encountered this category.
3326 ObjCCategoryDecl *MergeWithCategory
3327 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3328 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3330 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3331 Importer.Import(D->getAtStartLoc()),
3333 Importer.Import(D->getCategoryNameLoc()),
3334 Name.getAsIdentifierInfo(),
3336 Importer.Import(D->getIvarLBraceLoc()),
3337 Importer.Import(D->getIvarRBraceLoc()));
3338 ToCategory->setLexicalDeclContext(LexicalDC);
3339 LexicalDC->addDeclInternal(ToCategory);
3340 Importer.Imported(D, ToCategory);
3343 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3344 SmallVector<SourceLocation, 4> ProtocolLocs;
3345 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3346 = D->protocol_loc_begin();
3347 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3348 FromProtoEnd = D->protocol_end();
3349 FromProto != FromProtoEnd;
3350 ++FromProto, ++FromProtoLoc) {
3351 ObjCProtocolDecl *ToProto
3352 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3355 Protocols.push_back(ToProto);
3356 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3359 // FIXME: If we're merging, make sure that the protocol list is the same.
3360 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3361 ProtocolLocs.data(), Importer.getToContext());
3364 Importer.Imported(D, ToCategory);
3367 // Import all of the members of this category.
3368 ImportDeclContext(D);
3370 // If we have an implementation, import it as well.
3371 if (D->getImplementation()) {
3372 ObjCCategoryImplDecl *Impl
3373 = cast_or_null<ObjCCategoryImplDecl>(
3374 Importer.Import(D->getImplementation()));
3378 ToCategory->setImplementation(Impl);
3384 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3385 ObjCProtocolDecl *To,
3386 ImportDefinitionKind Kind) {
3387 if (To->getDefinition()) {
3388 if (shouldForceImportDeclContext(Kind))
3389 ImportDeclContext(From);
3393 // Start the protocol definition
3394 To->startDefinition();
3397 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3398 SmallVector<SourceLocation, 4> ProtocolLocs;
3399 ObjCProtocolDecl::protocol_loc_iterator
3400 FromProtoLoc = From->protocol_loc_begin();
3401 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3402 FromProtoEnd = From->protocol_end();
3403 FromProto != FromProtoEnd;
3404 ++FromProto, ++FromProtoLoc) {
3405 ObjCProtocolDecl *ToProto
3406 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3409 Protocols.push_back(ToProto);
3410 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3413 // FIXME: If we're merging, make sure that the protocol list is the same.
3414 To->setProtocolList(Protocols.data(), Protocols.size(),
3415 ProtocolLocs.data(), Importer.getToContext());
3417 if (shouldForceImportDeclContext(Kind)) {
3418 // Import all of the members of this protocol.
3419 ImportDeclContext(From, /*ForceImport=*/true);
3424 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3425 // If this protocol has a definition in the translation unit we're coming
3426 // from, but this particular declaration is not that definition, import the
3427 // definition and map to that.
3428 ObjCProtocolDecl *Definition = D->getDefinition();
3429 if (Definition && Definition != D) {
3430 Decl *ImportedDef = Importer.Import(Definition);
3434 return Importer.Imported(D, ImportedDef);
3437 // Import the major distinguishing characteristics of a protocol.
3438 DeclContext *DC, *LexicalDC;
3439 DeclarationName Name;
3441 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3444 ObjCProtocolDecl *MergeWithProtocol = 0;
3445 SmallVector<NamedDecl *, 2> FoundDecls;
3446 DC->localUncachedLookup(Name, FoundDecls);
3447 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3448 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3451 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3455 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3457 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3458 Name.getAsIdentifierInfo(), Loc,
3459 Importer.Import(D->getAtStartLoc()),
3461 ToProto->setLexicalDeclContext(LexicalDC);
3462 LexicalDC->addDeclInternal(ToProto);
3465 Importer.Imported(D, ToProto);
3467 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3473 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3474 ObjCInterfaceDecl *To,
3475 ImportDefinitionKind Kind) {
3476 if (To->getDefinition()) {
3477 // Check consistency of superclass.
3478 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3480 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3485 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3486 if ((bool)FromSuper != (bool)ToSuper ||
3487 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3488 Importer.ToDiag(To->getLocation(),
3489 diag::err_odr_objc_superclass_inconsistent)
3490 << To->getDeclName();
3492 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3493 << To->getSuperClass()->getDeclName();
3495 Importer.ToDiag(To->getLocation(),
3496 diag::note_odr_objc_missing_superclass);
3497 if (From->getSuperClass())
3498 Importer.FromDiag(From->getSuperClassLoc(),
3499 diag::note_odr_objc_superclass)
3500 << From->getSuperClass()->getDeclName();
3502 Importer.FromDiag(From->getLocation(),
3503 diag::note_odr_objc_missing_superclass);
3506 if (shouldForceImportDeclContext(Kind))
3507 ImportDeclContext(From);
3511 // Start the definition.
3512 To->startDefinition();
3514 // If this class has a superclass, import it.
3515 if (From->getSuperClass()) {
3516 ObjCInterfaceDecl *Super = cast_or_null<ObjCInterfaceDecl>(
3517 Importer.Import(From->getSuperClass()));
3521 To->setSuperClass(Super);
3522 To->setSuperClassLoc(Importer.Import(From->getSuperClassLoc()));
3526 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3527 SmallVector<SourceLocation, 4> ProtocolLocs;
3528 ObjCInterfaceDecl::protocol_loc_iterator
3529 FromProtoLoc = From->protocol_loc_begin();
3531 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3532 FromProtoEnd = From->protocol_end();
3533 FromProto != FromProtoEnd;
3534 ++FromProto, ++FromProtoLoc) {
3535 ObjCProtocolDecl *ToProto
3536 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3539 Protocols.push_back(ToProto);
3540 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3543 // FIXME: If we're merging, make sure that the protocol list is the same.
3544 To->setProtocolList(Protocols.data(), Protocols.size(),
3545 ProtocolLocs.data(), Importer.getToContext());
3547 // Import categories. When the categories themselves are imported, they'll
3548 // hook themselves into this interface.
3549 for (auto *Cat : From->known_categories())
3550 Importer.Import(Cat);
3552 // If we have an @implementation, import it as well.
3553 if (From->getImplementation()) {
3554 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3555 Importer.Import(From->getImplementation()));
3559 To->setImplementation(Impl);
3562 if (shouldForceImportDeclContext(Kind)) {
3563 // Import all of the members of this class.
3564 ImportDeclContext(From, /*ForceImport=*/true);
3569 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3570 // If this class has a definition in the translation unit we're coming from,
3571 // but this particular declaration is not that definition, import the
3572 // definition and map to that.
3573 ObjCInterfaceDecl *Definition = D->getDefinition();
3574 if (Definition && Definition != D) {
3575 Decl *ImportedDef = Importer.Import(Definition);
3579 return Importer.Imported(D, ImportedDef);
3582 // Import the major distinguishing characteristics of an @interface.
3583 DeclContext *DC, *LexicalDC;
3584 DeclarationName Name;
3586 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3589 // Look for an existing interface with the same name.
3590 ObjCInterfaceDecl *MergeWithIface = 0;
3591 SmallVector<NamedDecl *, 2> FoundDecls;
3592 DC->localUncachedLookup(Name, FoundDecls);
3593 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3594 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3597 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3601 // Create an interface declaration, if one does not already exist.
3602 ObjCInterfaceDecl *ToIface = MergeWithIface;
3604 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3605 Importer.Import(D->getAtStartLoc()),
3606 Name.getAsIdentifierInfo(),
3608 D->isImplicitInterfaceDecl());
3609 ToIface->setLexicalDeclContext(LexicalDC);
3610 LexicalDC->addDeclInternal(ToIface);
3612 Importer.Imported(D, ToIface);
3614 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3620 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3621 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3622 Importer.Import(D->getCategoryDecl()));
3626 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3628 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3632 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3633 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3634 Importer.Import(D->getIdentifier()),
3635 Category->getClassInterface(),
3636 Importer.Import(D->getLocation()),
3637 Importer.Import(D->getAtStartLoc()),
3640 DeclContext *LexicalDC = DC;
3641 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3642 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3646 ToImpl->setLexicalDeclContext(LexicalDC);
3649 LexicalDC->addDeclInternal(ToImpl);
3650 Category->setImplementation(ToImpl);
3653 Importer.Imported(D, ToImpl);
3654 ImportDeclContext(D);
3658 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3659 // Find the corresponding interface.
3660 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3661 Importer.Import(D->getClassInterface()));
3665 // Import the superclass, if any.
3666 ObjCInterfaceDecl *Super = 0;
3667 if (D->getSuperClass()) {
3668 Super = cast_or_null<ObjCInterfaceDecl>(
3669 Importer.Import(D->getSuperClass()));
3674 ObjCImplementationDecl *Impl = Iface->getImplementation();
3676 // We haven't imported an implementation yet. Create a new @implementation
3678 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3679 Importer.ImportContext(D->getDeclContext()),
3681 Importer.Import(D->getLocation()),
3682 Importer.Import(D->getAtStartLoc()),
3683 Importer.Import(D->getSuperClassLoc()),
3684 Importer.Import(D->getIvarLBraceLoc()),
3685 Importer.Import(D->getIvarRBraceLoc()));
3687 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3688 DeclContext *LexicalDC
3689 = Importer.ImportContext(D->getLexicalDeclContext());
3692 Impl->setLexicalDeclContext(LexicalDC);
3695 // Associate the implementation with the class it implements.
3696 Iface->setImplementation(Impl);
3697 Importer.Imported(D, Iface->getImplementation());
3699 Importer.Imported(D, Iface->getImplementation());
3701 // Verify that the existing @implementation has the same superclass.
3702 if ((Super && !Impl->getSuperClass()) ||
3703 (!Super && Impl->getSuperClass()) ||
3704 (Super && Impl->getSuperClass() &&
3705 !declaresSameEntity(Super->getCanonicalDecl(), Impl->getSuperClass()))) {
3706 Importer.ToDiag(Impl->getLocation(),
3707 diag::err_odr_objc_superclass_inconsistent)
3708 << Iface->getDeclName();
3709 // FIXME: It would be nice to have the location of the superclass
3711 if (Impl->getSuperClass())
3712 Importer.ToDiag(Impl->getLocation(),
3713 diag::note_odr_objc_superclass)
3714 << Impl->getSuperClass()->getDeclName();
3716 Importer.ToDiag(Impl->getLocation(),
3717 diag::note_odr_objc_missing_superclass);
3718 if (D->getSuperClass())
3719 Importer.FromDiag(D->getLocation(),
3720 diag::note_odr_objc_superclass)
3721 << D->getSuperClass()->getDeclName();
3723 Importer.FromDiag(D->getLocation(),
3724 diag::note_odr_objc_missing_superclass);
3729 // Import all of the members of this @implementation.
3730 ImportDeclContext(D);
3735 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3736 // Import the major distinguishing characteristics of an @property.
3737 DeclContext *DC, *LexicalDC;
3738 DeclarationName Name;
3740 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3743 // Check whether we have already imported this property.
3744 SmallVector<NamedDecl *, 2> FoundDecls;
3745 DC->localUncachedLookup(Name, FoundDecls);
3746 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3747 if (ObjCPropertyDecl *FoundProp
3748 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3749 // Check property types.
3750 if (!Importer.IsStructurallyEquivalent(D->getType(),
3751 FoundProp->getType())) {
3752 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3753 << Name << D->getType() << FoundProp->getType();
3754 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3755 << FoundProp->getType();
3759 // FIXME: Check property attributes, getters, setters, etc.?
3761 // Consider these properties to be equivalent.
3762 Importer.Imported(D, FoundProp);
3768 TypeSourceInfo *T = Importer.Import(D->getTypeSourceInfo());
3772 // Create the new property.
3773 ObjCPropertyDecl *ToProperty
3774 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3775 Name.getAsIdentifierInfo(),
3776 Importer.Import(D->getAtLoc()),
3777 Importer.Import(D->getLParenLoc()),
3779 D->getPropertyImplementation());
3780 Importer.Imported(D, ToProperty);
3781 ToProperty->setLexicalDeclContext(LexicalDC);
3782 LexicalDC->addDeclInternal(ToProperty);
3784 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3785 ToProperty->setPropertyAttributesAsWritten(
3786 D->getPropertyAttributesAsWritten());
3787 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
3788 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
3789 ToProperty->setGetterMethodDecl(
3790 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3791 ToProperty->setSetterMethodDecl(
3792 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3793 ToProperty->setPropertyIvarDecl(
3794 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3798 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3799 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3800 Importer.Import(D->getPropertyDecl()));
3804 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3808 // Import the lexical declaration context.
3809 DeclContext *LexicalDC = DC;
3810 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3811 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3816 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3820 // Import the ivar (for an @synthesize).
3821 ObjCIvarDecl *Ivar = 0;
3822 if (D->getPropertyIvarDecl()) {
3823 Ivar = cast_or_null<ObjCIvarDecl>(
3824 Importer.Import(D->getPropertyIvarDecl()));
3829 ObjCPropertyImplDecl *ToImpl
3830 = InImpl->FindPropertyImplDecl(Property->getIdentifier());
3832 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3833 Importer.Import(D->getLocStart()),
3834 Importer.Import(D->getLocation()),
3836 D->getPropertyImplementation(),
3838 Importer.Import(D->getPropertyIvarDeclLoc()));
3839 ToImpl->setLexicalDeclContext(LexicalDC);
3840 Importer.Imported(D, ToImpl);
3841 LexicalDC->addDeclInternal(ToImpl);
3843 // Check that we have the same kind of property implementation (@synthesize
3845 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3846 Importer.ToDiag(ToImpl->getLocation(),
3847 diag::err_odr_objc_property_impl_kind_inconsistent)
3848 << Property->getDeclName()
3849 << (ToImpl->getPropertyImplementation()
3850 == ObjCPropertyImplDecl::Dynamic);
3851 Importer.FromDiag(D->getLocation(),
3852 diag::note_odr_objc_property_impl_kind)
3853 << D->getPropertyDecl()->getDeclName()
3854 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3858 // For @synthesize, check that we have the same
3859 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3860 Ivar != ToImpl->getPropertyIvarDecl()) {
3861 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3862 diag::err_odr_objc_synthesize_ivar_inconsistent)
3863 << Property->getDeclName()
3864 << ToImpl->getPropertyIvarDecl()->getDeclName()
3865 << Ivar->getDeclName();
3866 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3867 diag::note_odr_objc_synthesize_ivar_here)
3868 << D->getPropertyIvarDecl()->getDeclName();
3872 // Merge the existing implementation with the new implementation.
3873 Importer.Imported(D, ToImpl);
3879 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3880 // For template arguments, we adopt the translation unit as our declaration
3881 // context. This context will be fixed when the actual template declaration
3884 // FIXME: Import default argument.
3885 return TemplateTypeParmDecl::Create(Importer.getToContext(),
3886 Importer.getToContext().getTranslationUnitDecl(),
3887 Importer.Import(D->getLocStart()),
3888 Importer.Import(D->getLocation()),
3891 Importer.Import(D->getIdentifier()),
3892 D->wasDeclaredWithTypename(),
3893 D->isParameterPack());
3897 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3898 // Import the name of this declaration.
3899 DeclarationName Name = Importer.Import(D->getDeclName());
3900 if (D->getDeclName() && !Name)
3903 // Import the location of this declaration.
3904 SourceLocation Loc = Importer.Import(D->getLocation());
3906 // Import the type of this declaration.
3907 QualType T = Importer.Import(D->getType());
3911 // Import type-source information.
3912 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3913 if (D->getTypeSourceInfo() && !TInfo)
3916 // FIXME: Import default argument.
3918 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3919 Importer.getToContext().getTranslationUnitDecl(),
3920 Importer.Import(D->getInnerLocStart()),
3921 Loc, D->getDepth(), D->getPosition(),
3922 Name.getAsIdentifierInfo(),
3923 T, D->isParameterPack(), TInfo);
3927 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3928 // Import the name of this declaration.
3929 DeclarationName Name = Importer.Import(D->getDeclName());
3930 if (D->getDeclName() && !Name)
3933 // Import the location of this declaration.
3934 SourceLocation Loc = Importer.Import(D->getLocation());
3936 // Import template parameters.
3937 TemplateParameterList *TemplateParams
3938 = ImportTemplateParameterList(D->getTemplateParameters());
3939 if (!TemplateParams)
3942 // FIXME: Import default argument.
3944 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3945 Importer.getToContext().getTranslationUnitDecl(),
3946 Loc, D->getDepth(), D->getPosition(),
3947 D->isParameterPack(),
3948 Name.getAsIdentifierInfo(),
3952 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3953 // If this record has a definition in the translation unit we're coming from,
3954 // but this particular declaration is not that definition, import the
3955 // definition and map to that.
3956 CXXRecordDecl *Definition
3957 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
3958 if (Definition && Definition != D->getTemplatedDecl()) {
3960 = Importer.Import(Definition->getDescribedClassTemplate());
3964 return Importer.Imported(D, ImportedDef);
3967 // Import the major distinguishing characteristics of this class template.
3968 DeclContext *DC, *LexicalDC;
3969 DeclarationName Name;
3971 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
3974 // We may already have a template of the same name; try to find and match it.
3975 if (!DC->isFunctionOrMethod()) {
3976 SmallVector<NamedDecl *, 4> ConflictingDecls;
3977 SmallVector<NamedDecl *, 2> FoundDecls;
3978 DC->localUncachedLookup(Name, FoundDecls);
3979 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3980 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3983 Decl *Found = FoundDecls[I];
3984 if (ClassTemplateDecl *FoundTemplate
3985 = dyn_cast<ClassTemplateDecl>(Found)) {
3986 if (IsStructuralMatch(D, FoundTemplate)) {
3987 // The class templates structurally match; call it the same template.
3988 // FIXME: We may be filling in a forward declaration here. Handle
3990 Importer.Imported(D->getTemplatedDecl(),
3991 FoundTemplate->getTemplatedDecl());
3992 return Importer.Imported(D, FoundTemplate);
3996 ConflictingDecls.push_back(FoundDecls[I]);
3999 if (!ConflictingDecls.empty()) {
4000 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4001 ConflictingDecls.data(),
4002 ConflictingDecls.size());
4009 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4011 // Create the declaration that is being templated.
4012 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4013 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4014 CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4015 DTemplated->getTagKind(),
4016 DC, StartLoc, IdLoc,
4017 Name.getAsIdentifierInfo());
4018 D2Templated->setAccess(DTemplated->getAccess());
4019 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4020 D2Templated->setLexicalDeclContext(LexicalDC);
4022 // Create the class template declaration itself.
4023 TemplateParameterList *TemplateParams
4024 = ImportTemplateParameterList(D->getTemplateParameters());
4025 if (!TemplateParams)
4028 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4029 Loc, Name, TemplateParams,
4032 D2Templated->setDescribedClassTemplate(D2);
4034 D2->setAccess(D->getAccess());
4035 D2->setLexicalDeclContext(LexicalDC);
4036 LexicalDC->addDeclInternal(D2);
4038 // Note the relationship between the class templates.
4039 Importer.Imported(D, D2);
4040 Importer.Imported(DTemplated, D2Templated);
4042 if (DTemplated->isCompleteDefinition() &&
4043 !D2Templated->isCompleteDefinition()) {
4044 // FIXME: Import definition!
4050 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4051 ClassTemplateSpecializationDecl *D) {
4052 // If this record has a definition in the translation unit we're coming from,
4053 // but this particular declaration is not that definition, import the
4054 // definition and map to that.
4055 TagDecl *Definition = D->getDefinition();
4056 if (Definition && Definition != D) {
4057 Decl *ImportedDef = Importer.Import(Definition);
4061 return Importer.Imported(D, ImportedDef);
4064 ClassTemplateDecl *ClassTemplate
4065 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4066 D->getSpecializedTemplate()));
4070 // Import the context of this declaration.
4071 DeclContext *DC = ClassTemplate->getDeclContext();
4075 DeclContext *LexicalDC = DC;
4076 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4077 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4082 // Import the location of this declaration.
4083 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4084 SourceLocation IdLoc = Importer.Import(D->getLocation());
4086 // Import template arguments.
4087 SmallVector<TemplateArgument, 2> TemplateArgs;
4088 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4089 D->getTemplateArgs().size(),
4093 // Try to find an existing specialization with these template arguments.
4094 void *InsertPos = 0;
4095 ClassTemplateSpecializationDecl *D2
4096 = ClassTemplate->findSpecialization(TemplateArgs.data(),
4097 TemplateArgs.size(), InsertPos);
4099 // We already have a class template specialization with these template
4102 // FIXME: Check for specialization vs. instantiation errors.
4104 if (RecordDecl *FoundDef = D2->getDefinition()) {
4105 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4106 // The record types structurally match, or the "from" translation
4107 // unit only had a forward declaration anyway; call it the same
4109 return Importer.Imported(D, FoundDef);
4113 // Create a new specialization.
4114 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4115 D->getTagKind(), DC,
4118 TemplateArgs.data(),
4119 TemplateArgs.size(),
4121 D2->setSpecializationKind(D->getSpecializationKind());
4123 // Add this specialization to the class template.
4124 ClassTemplate->AddSpecialization(D2, InsertPos);
4126 // Import the qualifier, if any.
4127 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4129 // Add the specialization to this context.
4130 D2->setLexicalDeclContext(LexicalDC);
4131 LexicalDC->addDeclInternal(D2);
4133 Importer.Imported(D, D2);
4135 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4141 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4142 // If this variable has a definition in the translation unit we're coming
4144 // but this particular declaration is not that definition, import the
4145 // definition and map to that.
4146 VarDecl *Definition =
4147 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4148 if (Definition && Definition != D->getTemplatedDecl()) {
4149 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4153 return Importer.Imported(D, ImportedDef);
4156 // Import the major distinguishing characteristics of this variable template.
4157 DeclContext *DC, *LexicalDC;
4158 DeclarationName Name;
4160 if (ImportDeclParts(D, DC, LexicalDC, Name, Loc))
4163 // We may already have a template of the same name; try to find and match it.
4164 assert(!DC->isFunctionOrMethod() &&
4165 "Variable templates cannot be declared at function scope");
4166 SmallVector<NamedDecl *, 4> ConflictingDecls;
4167 SmallVector<NamedDecl *, 2> FoundDecls;
4168 DC->localUncachedLookup(Name, FoundDecls);
4169 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4170 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4173 Decl *Found = FoundDecls[I];
4174 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4175 if (IsStructuralMatch(D, FoundTemplate)) {
4176 // The variable templates structurally match; call it the same template.
4177 Importer.Imported(D->getTemplatedDecl(),
4178 FoundTemplate->getTemplatedDecl());
4179 return Importer.Imported(D, FoundTemplate);
4183 ConflictingDecls.push_back(FoundDecls[I]);
4186 if (!ConflictingDecls.empty()) {
4187 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4188 ConflictingDecls.data(),
4189 ConflictingDecls.size());
4195 VarDecl *DTemplated = D->getTemplatedDecl();
4198 QualType T = Importer.Import(DTemplated->getType());
4202 // Create the declaration that is being templated.
4203 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4204 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4205 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4206 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4207 IdLoc, Name.getAsIdentifierInfo(), T,
4208 TInfo, DTemplated->getStorageClass());
4209 D2Templated->setAccess(DTemplated->getAccess());
4210 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4211 D2Templated->setLexicalDeclContext(LexicalDC);
4213 // Importer.Imported(DTemplated, D2Templated);
4214 // LexicalDC->addDeclInternal(D2Templated);
4216 // Merge the initializer.
4217 if (ImportDefinition(DTemplated, D2Templated))
4220 // Create the variable template declaration itself.
4221 TemplateParameterList *TemplateParams =
4222 ImportTemplateParameterList(D->getTemplateParameters());
4223 if (!TemplateParams)
4226 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4227 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4228 D2Templated->setDescribedVarTemplate(D2);
4230 D2->setAccess(D->getAccess());
4231 D2->setLexicalDeclContext(LexicalDC);
4232 LexicalDC->addDeclInternal(D2);
4234 // Note the relationship between the variable templates.
4235 Importer.Imported(D, D2);
4236 Importer.Imported(DTemplated, D2Templated);
4238 if (DTemplated->isThisDeclarationADefinition() &&
4239 !D2Templated->isThisDeclarationADefinition()) {
4240 // FIXME: Import definition!
4246 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4247 VarTemplateSpecializationDecl *D) {
4248 // If this record has a definition in the translation unit we're coming from,
4249 // but this particular declaration is not that definition, import the
4250 // definition and map to that.
4251 VarDecl *Definition = D->getDefinition();
4252 if (Definition && Definition != D) {
4253 Decl *ImportedDef = Importer.Import(Definition);
4257 return Importer.Imported(D, ImportedDef);
4260 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4261 Importer.Import(D->getSpecializedTemplate()));
4265 // Import the context of this declaration.
4266 DeclContext *DC = VarTemplate->getDeclContext();
4270 DeclContext *LexicalDC = DC;
4271 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4272 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4277 // Import the location of this declaration.
4278 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4279 SourceLocation IdLoc = Importer.Import(D->getLocation());
4281 // Import template arguments.
4282 SmallVector<TemplateArgument, 2> TemplateArgs;
4283 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4284 D->getTemplateArgs().size(), TemplateArgs))
4287 // Try to find an existing specialization with these template arguments.
4288 void *InsertPos = 0;
4289 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4290 TemplateArgs.data(), TemplateArgs.size(), InsertPos);
4292 // We already have a variable template specialization with these template
4295 // FIXME: Check for specialization vs. instantiation errors.
4297 if (VarDecl *FoundDef = D2->getDefinition()) {
4298 if (!D->isThisDeclarationADefinition() ||
4299 IsStructuralMatch(D, FoundDef)) {
4300 // The record types structurally match, or the "from" translation
4301 // unit only had a forward declaration anyway; call it the same
4303 return Importer.Imported(D, FoundDef);
4309 QualType T = Importer.Import(D->getType());
4312 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4314 // Create a new specialization.
4315 D2 = VarTemplateSpecializationDecl::Create(
4316 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4317 D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4318 D2->setSpecializationKind(D->getSpecializationKind());
4319 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4321 // Add this specialization to the class template.
4322 VarTemplate->AddSpecialization(D2, InsertPos);
4324 // Import the qualifier, if any.
4325 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4327 // Add the specialization to this context.
4328 D2->setLexicalDeclContext(LexicalDC);
4329 LexicalDC->addDeclInternal(D2);
4331 Importer.Imported(D, D2);
4333 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4339 //----------------------------------------------------------------------------
4340 // Import Statements
4341 //----------------------------------------------------------------------------
4343 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4344 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4345 << S->getStmtClassName();
4349 //----------------------------------------------------------------------------
4350 // Import Expressions
4351 //----------------------------------------------------------------------------
4352 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
4353 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
4354 << E->getStmtClassName();
4358 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
4359 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
4363 NamedDecl *FoundD = 0;
4364 if (E->getDecl() != E->getFoundDecl()) {
4365 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
4370 QualType T = Importer.Import(E->getType());
4374 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
4375 Importer.Import(E->getQualifierLoc()),
4376 Importer.Import(E->getTemplateKeywordLoc()),
4378 E->refersToEnclosingLocal(),
4379 Importer.Import(E->getLocation()),
4380 T, E->getValueKind(),
4382 /*FIXME:TemplateArgs=*/0);
4383 if (E->hadMultipleCandidates())
4384 DRE->setHadMultipleCandidates(true);
4388 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
4389 QualType T = Importer.Import(E->getType());
4393 return IntegerLiteral::Create(Importer.getToContext(),
4395 Importer.Import(E->getLocation()));
4398 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
4399 QualType T = Importer.Import(E->getType());
4403 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
4405 Importer.Import(E->getLocation()));
4408 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
4409 Expr *SubExpr = Importer.Import(E->getSubExpr());
4413 return new (Importer.getToContext())
4414 ParenExpr(Importer.Import(E->getLParen()),
4415 Importer.Import(E->getRParen()),
4419 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
4420 QualType T = Importer.Import(E->getType());
4424 Expr *SubExpr = Importer.Import(E->getSubExpr());
4428 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
4429 T, E->getValueKind(),
4431 Importer.Import(E->getOperatorLoc()));
4434 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
4435 UnaryExprOrTypeTraitExpr *E) {
4436 QualType ResultType = Importer.Import(E->getType());
4438 if (E->isArgumentType()) {
4439 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
4443 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4445 Importer.Import(E->getOperatorLoc()),
4446 Importer.Import(E->getRParenLoc()));
4449 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
4453 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4454 SubExpr, ResultType,
4455 Importer.Import(E->getOperatorLoc()),
4456 Importer.Import(E->getRParenLoc()));
4459 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
4460 QualType T = Importer.Import(E->getType());
4464 Expr *LHS = Importer.Import(E->getLHS());
4468 Expr *RHS = Importer.Import(E->getRHS());
4472 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
4473 T, E->getValueKind(),
4475 Importer.Import(E->getOperatorLoc()),
4476 E->isFPContractable());
4479 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
4480 QualType T = Importer.Import(E->getType());
4484 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
4485 if (CompLHSType.isNull())
4488 QualType CompResultType = Importer.Import(E->getComputationResultType());
4489 if (CompResultType.isNull())
4492 Expr *LHS = Importer.Import(E->getLHS());
4496 Expr *RHS = Importer.Import(E->getRHS());
4500 return new (Importer.getToContext())
4501 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
4502 T, E->getValueKind(),
4504 CompLHSType, CompResultType,
4505 Importer.Import(E->getOperatorLoc()),
4506 E->isFPContractable());
4509 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
4510 if (E->path_empty()) return false;
4512 // TODO: import cast paths
4516 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
4517 QualType T = Importer.Import(E->getType());
4521 Expr *SubExpr = Importer.Import(E->getSubExpr());
4525 CXXCastPath BasePath;
4526 if (ImportCastPath(E, BasePath))
4529 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
4530 SubExpr, &BasePath, E->getValueKind());
4533 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
4534 QualType T = Importer.Import(E->getType());
4538 Expr *SubExpr = Importer.Import(E->getSubExpr());
4542 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
4543 if (!TInfo && E->getTypeInfoAsWritten())
4546 CXXCastPath BasePath;
4547 if (ImportCastPath(E, BasePath))
4550 return CStyleCastExpr::Create(Importer.getToContext(), T,
4551 E->getValueKind(), E->getCastKind(),
4552 SubExpr, &BasePath, TInfo,
4553 Importer.Import(E->getLParenLoc()),
4554 Importer.Import(E->getRParenLoc()));
4557 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
4558 ASTContext &FromContext, FileManager &FromFileManager,
4560 : ToContext(ToContext), FromContext(FromContext),
4561 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
4562 Minimal(MinimalImport), LastDiagFromFrom(false)
4564 ImportedDecls[FromContext.getTranslationUnitDecl()]
4565 = ToContext.getTranslationUnitDecl();
4568 ASTImporter::~ASTImporter() { }
4570 QualType ASTImporter::Import(QualType FromT) {
4574 const Type *fromTy = FromT.getTypePtr();
4576 // Check whether we've already imported this type.
4577 llvm::DenseMap<const Type *, const Type *>::iterator Pos
4578 = ImportedTypes.find(fromTy);
4579 if (Pos != ImportedTypes.end())
4580 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
4583 ASTNodeImporter Importer(*this);
4584 QualType ToT = Importer.Visit(fromTy);
4588 // Record the imported type.
4589 ImportedTypes[fromTy] = ToT.getTypePtr();
4591 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
4594 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
4598 // FIXME: For now we just create a "trivial" type source info based
4599 // on the type and a single location. Implement a real version of this.
4600 QualType T = Import(FromTSI->getType());
4604 return ToContext.getTrivialTypeSourceInfo(T,
4605 FromTSI->getTypeLoc().getLocStart());
4608 Decl *ASTImporter::Import(Decl *FromD) {
4612 ASTNodeImporter Importer(*this);
4614 // Check whether we've already imported this declaration.
4615 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
4616 if (Pos != ImportedDecls.end()) {
4617 Decl *ToD = Pos->second;
4618 Importer.ImportDefinitionIfNeeded(FromD, ToD);
4623 Decl *ToD = Importer.Visit(FromD);
4627 // Record the imported declaration.
4628 ImportedDecls[FromD] = ToD;
4630 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
4631 // Keep track of anonymous tags that have an associated typedef.
4632 if (FromTag->getTypedefNameForAnonDecl())
4633 AnonTagsWithPendingTypedefs.push_back(FromTag);
4634 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
4635 // When we've finished transforming a typedef, see whether it was the
4636 // typedef for an anonymous tag.
4637 for (SmallVectorImpl<TagDecl *>::iterator
4638 FromTag = AnonTagsWithPendingTypedefs.begin(),
4639 FromTagEnd = AnonTagsWithPendingTypedefs.end();
4640 FromTag != FromTagEnd; ++FromTag) {
4641 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
4642 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
4643 // We found the typedef for an anonymous tag; link them.
4644 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
4645 AnonTagsWithPendingTypedefs.erase(FromTag);
4655 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
4659 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
4663 // When we're using a record/enum/Objective-C class/protocol as a context, we
4664 // need it to have a definition.
4665 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
4666 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
4667 if (ToRecord->isCompleteDefinition()) {
4669 } else if (FromRecord->isCompleteDefinition()) {
4670 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
4671 ASTNodeImporter::IDK_Basic);
4673 CompleteDecl(ToRecord);
4675 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
4676 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
4677 if (ToEnum->isCompleteDefinition()) {
4679 } else if (FromEnum->isCompleteDefinition()) {
4680 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
4681 ASTNodeImporter::IDK_Basic);
4683 CompleteDecl(ToEnum);
4685 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
4686 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
4687 if (ToClass->getDefinition()) {
4689 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
4690 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
4691 ASTNodeImporter::IDK_Basic);
4693 CompleteDecl(ToClass);
4695 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
4696 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
4697 if (ToProto->getDefinition()) {
4699 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
4700 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
4701 ASTNodeImporter::IDK_Basic);
4703 CompleteDecl(ToProto);
4710 Expr *ASTImporter::Import(Expr *FromE) {
4714 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
4717 Stmt *ASTImporter::Import(Stmt *FromS) {
4721 // Check whether we've already imported this declaration.
4722 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
4723 if (Pos != ImportedStmts.end())
4727 ASTNodeImporter Importer(*this);
4728 Stmt *ToS = Importer.Visit(FromS);
4732 // Record the imported declaration.
4733 ImportedStmts[FromS] = ToS;
4737 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
4741 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
4743 switch (FromNNS->getKind()) {
4744 case NestedNameSpecifier::Identifier:
4745 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
4746 return NestedNameSpecifier::Create(ToContext, prefix, II);
4750 case NestedNameSpecifier::Namespace:
4751 if (NamespaceDecl *NS =
4752 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
4753 return NestedNameSpecifier::Create(ToContext, prefix, NS);
4757 case NestedNameSpecifier::NamespaceAlias:
4758 if (NamespaceAliasDecl *NSAD =
4759 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
4760 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
4764 case NestedNameSpecifier::Global:
4765 return NestedNameSpecifier::GlobalSpecifier(ToContext);
4767 case NestedNameSpecifier::TypeSpec:
4768 case NestedNameSpecifier::TypeSpecWithTemplate: {
4769 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
4771 bool bTemplate = FromNNS->getKind() ==
4772 NestedNameSpecifier::TypeSpecWithTemplate;
4773 return NestedNameSpecifier::Create(ToContext, prefix,
4774 bTemplate, T.getTypePtr());
4780 llvm_unreachable("Invalid nested name specifier kind");
4783 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
4784 // FIXME: Implement!
4785 return NestedNameSpecifierLoc();
4788 TemplateName ASTImporter::Import(TemplateName From) {
4789 switch (From.getKind()) {
4790 case TemplateName::Template:
4791 if (TemplateDecl *ToTemplate
4792 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4793 return TemplateName(ToTemplate);
4795 return TemplateName();
4797 case TemplateName::OverloadedTemplate: {
4798 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
4799 UnresolvedSet<2> ToTemplates;
4800 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
4801 E = FromStorage->end();
4803 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
4804 ToTemplates.addDecl(To);
4806 return TemplateName();
4808 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
4812 case TemplateName::QualifiedTemplate: {
4813 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
4814 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
4816 return TemplateName();
4818 if (TemplateDecl *ToTemplate
4819 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
4820 return ToContext.getQualifiedTemplateName(Qualifier,
4821 QTN->hasTemplateKeyword(),
4824 return TemplateName();
4827 case TemplateName::DependentTemplate: {
4828 DependentTemplateName *DTN = From.getAsDependentTemplateName();
4829 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
4831 return TemplateName();
4833 if (DTN->isIdentifier()) {
4834 return ToContext.getDependentTemplateName(Qualifier,
4835 Import(DTN->getIdentifier()));
4838 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
4841 case TemplateName::SubstTemplateTemplateParm: {
4842 SubstTemplateTemplateParmStorage *subst
4843 = From.getAsSubstTemplateTemplateParm();
4844 TemplateTemplateParmDecl *param
4845 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
4847 return TemplateName();
4849 TemplateName replacement = Import(subst->getReplacement());
4850 if (replacement.isNull()) return TemplateName();
4852 return ToContext.getSubstTemplateTemplateParm(param, replacement);
4855 case TemplateName::SubstTemplateTemplateParmPack: {
4856 SubstTemplateTemplateParmPackStorage *SubstPack
4857 = From.getAsSubstTemplateTemplateParmPack();
4858 TemplateTemplateParmDecl *Param
4859 = cast_or_null<TemplateTemplateParmDecl>(
4860 Import(SubstPack->getParameterPack()));
4862 return TemplateName();
4864 ASTNodeImporter Importer(*this);
4865 TemplateArgument ArgPack
4866 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
4867 if (ArgPack.isNull())
4868 return TemplateName();
4870 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
4874 llvm_unreachable("Invalid template name kind");
4877 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
4878 if (FromLoc.isInvalid())
4879 return SourceLocation();
4881 SourceManager &FromSM = FromContext.getSourceManager();
4883 // For now, map everything down to its spelling location, so that we
4884 // don't have to import macro expansions.
4885 // FIXME: Import macro expansions!
4886 FromLoc = FromSM.getSpellingLoc(FromLoc);
4887 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
4888 SourceManager &ToSM = ToContext.getSourceManager();
4889 return ToSM.getLocForStartOfFile(Import(Decomposed.first))
4890 .getLocWithOffset(Decomposed.second);
4893 SourceRange ASTImporter::Import(SourceRange FromRange) {
4894 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
4897 FileID ASTImporter::Import(FileID FromID) {
4898 llvm::DenseMap<FileID, FileID>::iterator Pos
4899 = ImportedFileIDs.find(FromID);
4900 if (Pos != ImportedFileIDs.end())
4903 SourceManager &FromSM = FromContext.getSourceManager();
4904 SourceManager &ToSM = ToContext.getSourceManager();
4905 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
4906 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
4908 // Include location of this file.
4909 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
4911 // Map the FileID for to the "to" source manager.
4913 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
4914 if (Cache->OrigEntry) {
4915 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
4917 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
4918 // than mmap the files several times.
4919 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
4920 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
4921 FromSLoc.getFile().getFileCharacteristic());
4923 // FIXME: We want to re-use the existing MemoryBuffer!
4924 const llvm::MemoryBuffer *
4925 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
4926 llvm::MemoryBuffer *ToBuf
4927 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
4928 FromBuf->getBufferIdentifier());
4929 ToID = ToSM.createFileIDForMemBuffer(ToBuf,
4930 FromSLoc.getFile().getFileCharacteristic());
4934 ImportedFileIDs[FromID] = ToID;
4938 void ASTImporter::ImportDefinition(Decl *From) {
4939 Decl *To = Import(From);
4943 if (DeclContext *FromDC = cast<DeclContext>(From)) {
4944 ASTNodeImporter Importer(*this);
4946 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
4947 if (!ToRecord->getDefinition()) {
4948 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
4949 ASTNodeImporter::IDK_Everything);
4954 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
4955 if (!ToEnum->getDefinition()) {
4956 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
4957 ASTNodeImporter::IDK_Everything);
4962 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
4963 if (!ToIFace->getDefinition()) {
4964 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
4965 ASTNodeImporter::IDK_Everything);
4970 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
4971 if (!ToProto->getDefinition()) {
4972 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
4973 ASTNodeImporter::IDK_Everything);
4978 Importer.ImportDeclContext(FromDC, true);
4982 DeclarationName ASTImporter::Import(DeclarationName FromName) {
4984 return DeclarationName();
4986 switch (FromName.getNameKind()) {
4987 case DeclarationName::Identifier:
4988 return Import(FromName.getAsIdentifierInfo());
4990 case DeclarationName::ObjCZeroArgSelector:
4991 case DeclarationName::ObjCOneArgSelector:
4992 case DeclarationName::ObjCMultiArgSelector:
4993 return Import(FromName.getObjCSelector());
4995 case DeclarationName::CXXConstructorName: {
4996 QualType T = Import(FromName.getCXXNameType());
4998 return DeclarationName();
5000 return ToContext.DeclarationNames.getCXXConstructorName(
5001 ToContext.getCanonicalType(T));
5004 case DeclarationName::CXXDestructorName: {
5005 QualType T = Import(FromName.getCXXNameType());
5007 return DeclarationName();
5009 return ToContext.DeclarationNames.getCXXDestructorName(
5010 ToContext.getCanonicalType(T));
5013 case DeclarationName::CXXConversionFunctionName: {
5014 QualType T = Import(FromName.getCXXNameType());
5016 return DeclarationName();
5018 return ToContext.DeclarationNames.getCXXConversionFunctionName(
5019 ToContext.getCanonicalType(T));
5022 case DeclarationName::CXXOperatorName:
5023 return ToContext.DeclarationNames.getCXXOperatorName(
5024 FromName.getCXXOverloadedOperator());
5026 case DeclarationName::CXXLiteralOperatorName:
5027 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5028 Import(FromName.getCXXLiteralIdentifier()));
5030 case DeclarationName::CXXUsingDirective:
5032 return DeclarationName::getUsingDirectiveName();
5035 llvm_unreachable("Invalid DeclarationName Kind!");
5038 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5042 return &ToContext.Idents.get(FromId->getName());
5045 Selector ASTImporter::Import(Selector FromSel) {
5046 if (FromSel.isNull())
5049 SmallVector<IdentifierInfo *, 4> Idents;
5050 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5051 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5052 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5053 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5056 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5060 unsigned NumDecls) {
5064 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5065 if (LastDiagFromFrom)
5066 ToContext.getDiagnostics().notePriorDiagnosticFrom(
5067 FromContext.getDiagnostics());
5068 LastDiagFromFrom = false;
5069 return ToContext.getDiagnostics().Report(Loc, DiagID);
5072 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5073 if (!LastDiagFromFrom)
5074 FromContext.getDiagnostics().notePriorDiagnosticFrom(
5075 ToContext.getDiagnostics());
5076 LastDiagFromFrom = true;
5077 return FromContext.getDiagnostics().Report(Loc, DiagID);
5080 void ASTImporter::CompleteDecl (Decl *D) {
5081 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5082 if (!ID->getDefinition())
5083 ID->startDefinition();
5085 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5086 if (!PD->getDefinition())
5087 PD->startDefinition();
5089 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5090 if (!TD->getDefinition() && !TD->isBeingDefined()) {
5091 TD->startDefinition();
5092 TD->setCompleteDefinition(true);
5096 assert (0 && "CompleteDecl called on a Decl that can't be completed");
5100 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5101 ImportedDecls[From] = To;
5105 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5107 llvm::DenseMap<const Type *, const Type *>::iterator Pos
5108 = ImportedTypes.find(From.getTypePtr());
5109 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5112 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5114 return Ctx.IsStructurallyEquivalent(From, To);