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 QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
68 // FIXME: DependentDecltypeType
69 QualType VisitRecordType(const RecordType *T);
70 QualType VisitEnumType(const EnumType *T);
71 QualType VisitAttributedType(const AttributedType *T);
72 QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
73 // FIXME: SubstTemplateTypeParmType
74 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
75 QualType VisitElaboratedType(const ElaboratedType *T);
76 // FIXME: DependentNameType
77 // FIXME: DependentTemplateSpecializationType
78 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
79 QualType VisitObjCObjectType(const ObjCObjectType *T);
80 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
82 // Importing declarations
83 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
84 DeclContext *&LexicalDC, DeclarationName &Name,
85 NamedDecl *&ToD, SourceLocation &Loc);
86 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
87 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
88 DeclarationNameInfo& To);
89 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
91 typedef DesignatedInitExpr::Designator Designator;
92 Designator ImportDesignator(const Designator &D);
95 /// \brief What we should import from the definition.
96 enum ImportDefinitionKind {
97 /// \brief Import the default subset of the definition, which might be
98 /// nothing (if minimal import is set) or might be everything (if minimal
99 /// import is not set).
101 /// \brief Import everything.
103 /// \brief Import only the bare bones needed to establish a valid
108 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
109 return IDK == IDK_Everything ||
110 (IDK == IDK_Default && !Importer.isMinimalImport());
113 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
114 ImportDefinitionKind Kind = IDK_Default);
115 bool ImportDefinition(VarDecl *From, VarDecl *To,
116 ImportDefinitionKind Kind = IDK_Default);
117 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
118 ImportDefinitionKind Kind = IDK_Default);
119 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
120 ImportDefinitionKind Kind = IDK_Default);
121 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
122 ImportDefinitionKind Kind = IDK_Default);
123 TemplateParameterList *ImportTemplateParameterList(
124 TemplateParameterList *Params);
125 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
126 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
127 unsigned NumFromArgs,
128 SmallVectorImpl<TemplateArgument> &ToArgs);
129 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
130 bool Complain = true);
131 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
132 bool Complain = true);
133 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
134 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
135 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
136 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
137 Decl *VisitDecl(Decl *D);
138 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
139 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
140 Decl *VisitNamespaceDecl(NamespaceDecl *D);
141 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
142 Decl *VisitTypedefDecl(TypedefDecl *D);
143 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
144 Decl *VisitLabelDecl(LabelDecl *D);
145 Decl *VisitEnumDecl(EnumDecl *D);
146 Decl *VisitRecordDecl(RecordDecl *D);
147 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
148 Decl *VisitFunctionDecl(FunctionDecl *D);
149 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
150 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
151 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
152 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
153 Decl *VisitFieldDecl(FieldDecl *D);
154 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
155 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
156 Decl *VisitVarDecl(VarDecl *D);
157 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
158 Decl *VisitParmVarDecl(ParmVarDecl *D);
159 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
160 Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
161 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
162 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
163 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
165 ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
166 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
167 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
168 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
169 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
170 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
171 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
172 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
173 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
174 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
175 Decl *VisitClassTemplateSpecializationDecl(
176 ClassTemplateSpecializationDecl *D);
177 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
178 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
180 // Importing statements
181 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
183 Stmt *VisitStmt(Stmt *S);
184 Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
185 Stmt *VisitDeclStmt(DeclStmt *S);
186 Stmt *VisitNullStmt(NullStmt *S);
187 Stmt *VisitCompoundStmt(CompoundStmt *S);
188 Stmt *VisitCaseStmt(CaseStmt *S);
189 Stmt *VisitDefaultStmt(DefaultStmt *S);
190 Stmt *VisitLabelStmt(LabelStmt *S);
191 Stmt *VisitAttributedStmt(AttributedStmt *S);
192 Stmt *VisitIfStmt(IfStmt *S);
193 Stmt *VisitSwitchStmt(SwitchStmt *S);
194 Stmt *VisitWhileStmt(WhileStmt *S);
195 Stmt *VisitDoStmt(DoStmt *S);
196 Stmt *VisitForStmt(ForStmt *S);
197 Stmt *VisitGotoStmt(GotoStmt *S);
198 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
199 Stmt *VisitContinueStmt(ContinueStmt *S);
200 Stmt *VisitBreakStmt(BreakStmt *S);
201 Stmt *VisitReturnStmt(ReturnStmt *S);
203 // FIXME: SEHExceptStmt
204 // FIXME: SEHFinallyStmt
206 // FIXME: SEHLeaveStmt
207 // FIXME: CapturedStmt
208 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
209 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
210 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
211 // FIXME: MSDependentExistsStmt
212 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
213 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
214 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
215 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
216 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
217 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
218 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
220 // Importing expressions
221 Expr *VisitExpr(Expr *E);
222 Expr *VisitVAArgExpr(VAArgExpr *E);
223 Expr *VisitGNUNullExpr(GNUNullExpr *E);
224 Expr *VisitPredefinedExpr(PredefinedExpr *E);
225 Expr *VisitDeclRefExpr(DeclRefExpr *E);
226 Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
227 Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
228 Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
229 Expr *VisitIntegerLiteral(IntegerLiteral *E);
230 Expr *VisitFloatingLiteral(FloatingLiteral *E);
231 Expr *VisitCharacterLiteral(CharacterLiteral *E);
232 Expr *VisitStringLiteral(StringLiteral *E);
233 Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
234 Expr *VisitAtomicExpr(AtomicExpr *E);
235 Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
236 Expr *VisitParenExpr(ParenExpr *E);
237 Expr *VisitParenListExpr(ParenListExpr *E);
238 Expr *VisitStmtExpr(StmtExpr *E);
239 Expr *VisitUnaryOperator(UnaryOperator *E);
240 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
241 Expr *VisitBinaryOperator(BinaryOperator *E);
242 Expr *VisitConditionalOperator(ConditionalOperator *E);
243 Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
244 Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
245 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
246 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
247 Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
248 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
249 Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
250 Expr *VisitCXXThisExpr(CXXThisExpr *E);
251 Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
252 Expr *VisitMemberExpr(MemberExpr *E);
253 Expr *VisitCallExpr(CallExpr *E);
254 Expr *VisitInitListExpr(InitListExpr *E);
255 Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
256 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
258 template<typename IIter, typename OIter>
259 void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
260 typedef typename std::remove_reference<decltype(*Obegin)>::type ItemT;
261 ASTImporter &ImporterRef = Importer;
262 std::transform(Ibegin, Iend, Obegin,
263 [&ImporterRef](ItemT From) -> ItemT {
264 return ImporterRef.Import(From);
268 template<typename IIter, typename OIter>
269 bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
270 typedef typename std::remove_reference<decltype(**Obegin)>::type ItemT;
271 ASTImporter &ImporterRef = Importer;
273 std::transform(Ibegin, Iend, Obegin,
274 [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
275 ItemT *To = ImporterRef.Import(From);
285 using namespace clang;
287 //----------------------------------------------------------------------------
288 // Structural Equivalence
289 //----------------------------------------------------------------------------
292 struct StructuralEquivalenceContext {
293 /// \brief AST contexts for which we are checking structural equivalence.
296 /// \brief The set of "tentative" equivalences between two canonical
297 /// declarations, mapping from a declaration in the first context to the
298 /// declaration in the second context that we believe to be equivalent.
299 llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
301 /// \brief Queue of declarations in the first context whose equivalence
302 /// with a declaration in the second context still needs to be verified.
303 std::deque<Decl *> DeclsToCheck;
305 /// \brief Declaration (from, to) pairs that are known not to be equivalent
306 /// (which we have already complained about).
307 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
309 /// \brief Whether we're being strict about the spelling of types when
310 /// unifying two types.
311 bool StrictTypeSpelling;
313 /// \brief Whether to complain about failures.
316 /// \brief \c true if the last diagnostic came from C2.
319 StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
320 llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
321 bool StrictTypeSpelling = false,
322 bool Complain = true)
323 : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
324 StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
325 LastDiagFromC2(false) {}
327 /// \brief Determine whether the two declarations are structurally
329 bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
331 /// \brief Determine whether the two types are structurally equivalent.
332 bool IsStructurallyEquivalent(QualType T1, QualType T2);
335 /// \brief Finish checking all of the structural equivalences.
337 /// \returns true if an error occurred, false otherwise.
341 DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
342 assert(Complain && "Not allowed to complain");
344 C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
345 LastDiagFromC2 = false;
346 return C1.getDiagnostics().Report(Loc, DiagID);
349 DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
350 assert(Complain && "Not allowed to complain");
352 C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
353 LastDiagFromC2 = true;
354 return C2.getDiagnostics().Report(Loc, DiagID);
359 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
360 QualType T1, QualType T2);
361 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
364 /// \brief Determine structural equivalence of two expressions.
365 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
366 Expr *E1, Expr *E2) {
370 // FIXME: Actually perform a structural comparison!
374 /// \brief Determine whether two identifiers are equivalent.
375 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
376 const IdentifierInfo *Name2) {
377 if (!Name1 || !Name2)
378 return Name1 == Name2;
380 return Name1->getName() == Name2->getName();
383 /// \brief Determine whether two nested-name-specifiers are equivalent.
384 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
385 NestedNameSpecifier *NNS1,
386 NestedNameSpecifier *NNS2) {
391 /// \brief Determine whether two template arguments are equivalent.
392 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
393 const TemplateArgument &Arg1,
394 const TemplateArgument &Arg2) {
395 if (Arg1.getKind() != Arg2.getKind())
398 switch (Arg1.getKind()) {
399 case TemplateArgument::Null:
402 case TemplateArgument::Type:
403 return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
405 case TemplateArgument::Integral:
406 if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
407 Arg2.getIntegralType()))
410 return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
412 case TemplateArgument::Declaration:
413 return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
415 case TemplateArgument::NullPtr:
416 return true; // FIXME: Is this correct?
418 case TemplateArgument::Template:
419 return IsStructurallyEquivalent(Context,
420 Arg1.getAsTemplate(),
421 Arg2.getAsTemplate());
423 case TemplateArgument::TemplateExpansion:
424 return IsStructurallyEquivalent(Context,
425 Arg1.getAsTemplateOrTemplatePattern(),
426 Arg2.getAsTemplateOrTemplatePattern());
428 case TemplateArgument::Expression:
429 return IsStructurallyEquivalent(Context,
430 Arg1.getAsExpr(), Arg2.getAsExpr());
432 case TemplateArgument::Pack:
433 if (Arg1.pack_size() != Arg2.pack_size())
436 for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
437 if (!IsStructurallyEquivalent(Context,
438 Arg1.pack_begin()[I],
439 Arg2.pack_begin()[I]))
445 llvm_unreachable("Invalid template argument kind");
448 /// \brief Determine structural equivalence for the common part of array
450 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
451 const ArrayType *Array1,
452 const ArrayType *Array2) {
453 if (!IsStructurallyEquivalent(Context,
454 Array1->getElementType(),
455 Array2->getElementType()))
457 if (Array1->getSizeModifier() != Array2->getSizeModifier())
459 if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
465 /// \brief Determine structural equivalence of two types.
466 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
467 QualType T1, QualType T2) {
468 if (T1.isNull() || T2.isNull())
469 return T1.isNull() && T2.isNull();
471 if (!Context.StrictTypeSpelling) {
472 // We aren't being strict about token-to-token equivalence of types,
473 // so map down to the canonical type.
474 T1 = Context.C1.getCanonicalType(T1);
475 T2 = Context.C2.getCanonicalType(T2);
478 if (T1.getQualifiers() != T2.getQualifiers())
481 Type::TypeClass TC = T1->getTypeClass();
483 if (T1->getTypeClass() != T2->getTypeClass()) {
484 // Compare function types with prototypes vs. without prototypes as if
485 // both did not have prototypes.
486 if (T1->getTypeClass() == Type::FunctionProto &&
487 T2->getTypeClass() == Type::FunctionNoProto)
488 TC = Type::FunctionNoProto;
489 else if (T1->getTypeClass() == Type::FunctionNoProto &&
490 T2->getTypeClass() == Type::FunctionProto)
491 TC = Type::FunctionNoProto;
498 // FIXME: Deal with Char_S/Char_U.
499 if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
504 if (!IsStructurallyEquivalent(Context,
505 cast<ComplexType>(T1)->getElementType(),
506 cast<ComplexType>(T2)->getElementType()))
512 if (!IsStructurallyEquivalent(Context,
513 cast<AdjustedType>(T1)->getOriginalType(),
514 cast<AdjustedType>(T2)->getOriginalType()))
519 if (!IsStructurallyEquivalent(Context,
520 cast<PointerType>(T1)->getPointeeType(),
521 cast<PointerType>(T2)->getPointeeType()))
525 case Type::BlockPointer:
526 if (!IsStructurallyEquivalent(Context,
527 cast<BlockPointerType>(T1)->getPointeeType(),
528 cast<BlockPointerType>(T2)->getPointeeType()))
532 case Type::LValueReference:
533 case Type::RValueReference: {
534 const ReferenceType *Ref1 = cast<ReferenceType>(T1);
535 const ReferenceType *Ref2 = cast<ReferenceType>(T2);
536 if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
538 if (Ref1->isInnerRef() != Ref2->isInnerRef())
540 if (!IsStructurallyEquivalent(Context,
541 Ref1->getPointeeTypeAsWritten(),
542 Ref2->getPointeeTypeAsWritten()))
547 case Type::MemberPointer: {
548 const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
549 const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
550 if (!IsStructurallyEquivalent(Context,
551 MemPtr1->getPointeeType(),
552 MemPtr2->getPointeeType()))
554 if (!IsStructurallyEquivalent(Context,
555 QualType(MemPtr1->getClass(), 0),
556 QualType(MemPtr2->getClass(), 0)))
561 case Type::ConstantArray: {
562 const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
563 const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
564 if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
567 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
572 case Type::IncompleteArray:
573 if (!IsArrayStructurallyEquivalent(Context,
575 cast<ArrayType>(T2)))
579 case Type::VariableArray: {
580 const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
581 const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
582 if (!IsStructurallyEquivalent(Context,
583 Array1->getSizeExpr(), Array2->getSizeExpr()))
586 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
592 case Type::DependentSizedArray: {
593 const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
594 const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
595 if (!IsStructurallyEquivalent(Context,
596 Array1->getSizeExpr(), Array2->getSizeExpr()))
599 if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
605 case Type::DependentSizedExtVector: {
606 const DependentSizedExtVectorType *Vec1
607 = cast<DependentSizedExtVectorType>(T1);
608 const DependentSizedExtVectorType *Vec2
609 = cast<DependentSizedExtVectorType>(T2);
610 if (!IsStructurallyEquivalent(Context,
611 Vec1->getSizeExpr(), Vec2->getSizeExpr()))
613 if (!IsStructurallyEquivalent(Context,
614 Vec1->getElementType(),
615 Vec2->getElementType()))
621 case Type::ExtVector: {
622 const VectorType *Vec1 = cast<VectorType>(T1);
623 const VectorType *Vec2 = cast<VectorType>(T2);
624 if (!IsStructurallyEquivalent(Context,
625 Vec1->getElementType(),
626 Vec2->getElementType()))
628 if (Vec1->getNumElements() != Vec2->getNumElements())
630 if (Vec1->getVectorKind() != Vec2->getVectorKind())
635 case Type::FunctionProto: {
636 const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
637 const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
638 if (Proto1->getNumParams() != Proto2->getNumParams())
640 for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
641 if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
642 Proto2->getParamType(I)))
645 if (Proto1->isVariadic() != Proto2->isVariadic())
647 if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
649 if (Proto1->getExceptionSpecType() == EST_Dynamic) {
650 if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
652 for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
653 if (!IsStructurallyEquivalent(Context,
654 Proto1->getExceptionType(I),
655 Proto2->getExceptionType(I)))
658 } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
659 if (!IsStructurallyEquivalent(Context,
660 Proto1->getNoexceptExpr(),
661 Proto2->getNoexceptExpr()))
664 if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
667 // Fall through to check the bits common with FunctionNoProtoType.
670 case Type::FunctionNoProto: {
671 const FunctionType *Function1 = cast<FunctionType>(T1);
672 const FunctionType *Function2 = cast<FunctionType>(T2);
673 if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
674 Function2->getReturnType()))
676 if (Function1->getExtInfo() != Function2->getExtInfo())
681 case Type::UnresolvedUsing:
682 if (!IsStructurallyEquivalent(Context,
683 cast<UnresolvedUsingType>(T1)->getDecl(),
684 cast<UnresolvedUsingType>(T2)->getDecl()))
689 case Type::Attributed:
690 if (!IsStructurallyEquivalent(Context,
691 cast<AttributedType>(T1)->getModifiedType(),
692 cast<AttributedType>(T2)->getModifiedType()))
694 if (!IsStructurallyEquivalent(Context,
695 cast<AttributedType>(T1)->getEquivalentType(),
696 cast<AttributedType>(T2)->getEquivalentType()))
701 if (!IsStructurallyEquivalent(Context,
702 cast<ParenType>(T1)->getInnerType(),
703 cast<ParenType>(T2)->getInnerType()))
708 if (!IsStructurallyEquivalent(Context,
709 cast<TypedefType>(T1)->getDecl(),
710 cast<TypedefType>(T2)->getDecl()))
714 case Type::TypeOfExpr:
715 if (!IsStructurallyEquivalent(Context,
716 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
717 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
722 if (!IsStructurallyEquivalent(Context,
723 cast<TypeOfType>(T1)->getUnderlyingType(),
724 cast<TypeOfType>(T2)->getUnderlyingType()))
728 case Type::UnaryTransform:
729 if (!IsStructurallyEquivalent(Context,
730 cast<UnaryTransformType>(T1)->getUnderlyingType(),
731 cast<UnaryTransformType>(T1)->getUnderlyingType()))
736 if (!IsStructurallyEquivalent(Context,
737 cast<DecltypeType>(T1)->getUnderlyingExpr(),
738 cast<DecltypeType>(T2)->getUnderlyingExpr()))
743 if (!IsStructurallyEquivalent(Context,
744 cast<AutoType>(T1)->getDeducedType(),
745 cast<AutoType>(T2)->getDeducedType()))
751 if (!IsStructurallyEquivalent(Context,
752 cast<TagType>(T1)->getDecl(),
753 cast<TagType>(T2)->getDecl()))
757 case Type::TemplateTypeParm: {
758 const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
759 const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
760 if (Parm1->getDepth() != Parm2->getDepth())
762 if (Parm1->getIndex() != Parm2->getIndex())
764 if (Parm1->isParameterPack() != Parm2->isParameterPack())
767 // Names of template type parameters are never significant.
771 case Type::SubstTemplateTypeParm: {
772 const SubstTemplateTypeParmType *Subst1
773 = cast<SubstTemplateTypeParmType>(T1);
774 const SubstTemplateTypeParmType *Subst2
775 = cast<SubstTemplateTypeParmType>(T2);
776 if (!IsStructurallyEquivalent(Context,
777 QualType(Subst1->getReplacedParameter(), 0),
778 QualType(Subst2->getReplacedParameter(), 0)))
780 if (!IsStructurallyEquivalent(Context,
781 Subst1->getReplacementType(),
782 Subst2->getReplacementType()))
787 case Type::SubstTemplateTypeParmPack: {
788 const SubstTemplateTypeParmPackType *Subst1
789 = cast<SubstTemplateTypeParmPackType>(T1);
790 const SubstTemplateTypeParmPackType *Subst2
791 = cast<SubstTemplateTypeParmPackType>(T2);
792 if (!IsStructurallyEquivalent(Context,
793 QualType(Subst1->getReplacedParameter(), 0),
794 QualType(Subst2->getReplacedParameter(), 0)))
796 if (!IsStructurallyEquivalent(Context,
797 Subst1->getArgumentPack(),
798 Subst2->getArgumentPack()))
802 case Type::TemplateSpecialization: {
803 const TemplateSpecializationType *Spec1
804 = cast<TemplateSpecializationType>(T1);
805 const TemplateSpecializationType *Spec2
806 = cast<TemplateSpecializationType>(T2);
807 if (!IsStructurallyEquivalent(Context,
808 Spec1->getTemplateName(),
809 Spec2->getTemplateName()))
811 if (Spec1->getNumArgs() != Spec2->getNumArgs())
813 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
814 if (!IsStructurallyEquivalent(Context,
815 Spec1->getArg(I), Spec2->getArg(I)))
821 case Type::Elaborated: {
822 const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
823 const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
824 // CHECKME: what if a keyword is ETK_None or ETK_typename ?
825 if (Elab1->getKeyword() != Elab2->getKeyword())
827 if (!IsStructurallyEquivalent(Context,
828 Elab1->getQualifier(),
829 Elab2->getQualifier()))
831 if (!IsStructurallyEquivalent(Context,
832 Elab1->getNamedType(),
833 Elab2->getNamedType()))
838 case Type::InjectedClassName: {
839 const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
840 const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
841 if (!IsStructurallyEquivalent(Context,
842 Inj1->getInjectedSpecializationType(),
843 Inj2->getInjectedSpecializationType()))
848 case Type::DependentName: {
849 const DependentNameType *Typename1 = cast<DependentNameType>(T1);
850 const DependentNameType *Typename2 = cast<DependentNameType>(T2);
851 if (!IsStructurallyEquivalent(Context,
852 Typename1->getQualifier(),
853 Typename2->getQualifier()))
855 if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
856 Typename2->getIdentifier()))
862 case Type::DependentTemplateSpecialization: {
863 const DependentTemplateSpecializationType *Spec1 =
864 cast<DependentTemplateSpecializationType>(T1);
865 const DependentTemplateSpecializationType *Spec2 =
866 cast<DependentTemplateSpecializationType>(T2);
867 if (!IsStructurallyEquivalent(Context,
868 Spec1->getQualifier(),
869 Spec2->getQualifier()))
871 if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
872 Spec2->getIdentifier()))
874 if (Spec1->getNumArgs() != Spec2->getNumArgs())
876 for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
877 if (!IsStructurallyEquivalent(Context,
878 Spec1->getArg(I), Spec2->getArg(I)))
884 case Type::PackExpansion:
885 if (!IsStructurallyEquivalent(Context,
886 cast<PackExpansionType>(T1)->getPattern(),
887 cast<PackExpansionType>(T2)->getPattern()))
891 case Type::ObjCInterface: {
892 const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
893 const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
894 if (!IsStructurallyEquivalent(Context,
895 Iface1->getDecl(), Iface2->getDecl()))
900 case Type::ObjCObject: {
901 const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
902 const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
903 if (!IsStructurallyEquivalent(Context,
905 Obj2->getBaseType()))
907 if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
909 for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
910 if (!IsStructurallyEquivalent(Context,
911 Obj1->getProtocol(I),
912 Obj2->getProtocol(I)))
918 case Type::ObjCObjectPointer: {
919 const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
920 const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
921 if (!IsStructurallyEquivalent(Context,
922 Ptr1->getPointeeType(),
923 Ptr2->getPointeeType()))
929 if (!IsStructurallyEquivalent(Context,
930 cast<AtomicType>(T1)->getValueType(),
931 cast<AtomicType>(T2)->getValueType()))
937 if (!IsStructurallyEquivalent(Context,
938 cast<PipeType>(T1)->getElementType(),
939 cast<PipeType>(T2)->getElementType()))
949 /// \brief Determine structural equivalence of two fields.
950 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
951 FieldDecl *Field1, FieldDecl *Field2) {
952 RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
954 // For anonymous structs/unions, match up the anonymous struct/union type
955 // declarations directly, so that we don't go off searching for anonymous
957 if (Field1->isAnonymousStructOrUnion() &&
958 Field2->isAnonymousStructOrUnion()) {
959 RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
960 RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
961 return IsStructurallyEquivalent(Context, D1, D2);
964 // Check for equivalent field names.
965 IdentifierInfo *Name1 = Field1->getIdentifier();
966 IdentifierInfo *Name2 = Field2->getIdentifier();
967 if (!::IsStructurallyEquivalent(Name1, Name2))
970 if (!IsStructurallyEquivalent(Context,
971 Field1->getType(), Field2->getType())) {
972 if (Context.Complain) {
973 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
974 << Context.C2.getTypeDeclType(Owner2);
975 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
976 << Field2->getDeclName() << Field2->getType();
977 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
978 << Field1->getDeclName() << Field1->getType();
983 if (Field1->isBitField() != Field2->isBitField()) {
984 if (Context.Complain) {
985 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
986 << Context.C2.getTypeDeclType(Owner2);
987 if (Field1->isBitField()) {
988 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
989 << Field1->getDeclName() << Field1->getType()
990 << Field1->getBitWidthValue(Context.C1);
991 Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
992 << Field2->getDeclName();
994 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
995 << Field2->getDeclName() << Field2->getType()
996 << Field2->getBitWidthValue(Context.C2);
997 Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
998 << Field1->getDeclName();
1004 if (Field1->isBitField()) {
1005 // Make sure that the bit-fields are the same length.
1006 unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
1007 unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
1009 if (Bits1 != Bits2) {
1010 if (Context.Complain) {
1011 Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1012 << Context.C2.getTypeDeclType(Owner2);
1013 Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
1014 << Field2->getDeclName() << Field2->getType() << Bits2;
1015 Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
1016 << Field1->getDeclName() << Field1->getType() << Bits1;
1025 /// \brief Find the index of the given anonymous struct/union within its
1028 /// \returns Returns the index of this anonymous struct/union in its context,
1029 /// including the next assigned index (if none of them match). Returns an
1030 /// empty option if the context is not a record, i.e.. if the anonymous
1031 /// struct/union is at namespace or block scope.
1032 static Optional<unsigned> findUntaggedStructOrUnionIndex(RecordDecl *Anon) {
1033 ASTContext &Context = Anon->getASTContext();
1034 QualType AnonTy = Context.getRecordType(Anon);
1036 RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
1041 for (const auto *D : Owner->noload_decls()) {
1042 const auto *F = dyn_cast<FieldDecl>(D);
1046 if (F->isAnonymousStructOrUnion()) {
1047 if (Context.hasSameType(F->getType(), AnonTy))
1053 // If the field looks like this:
1054 // struct { ... } A;
1055 QualType FieldType = F->getType();
1056 if (const auto *RecType = dyn_cast<RecordType>(FieldType)) {
1057 const RecordDecl *RecDecl = RecType->getDecl();
1058 if (RecDecl->getDeclContext() == Owner &&
1059 !RecDecl->getIdentifier()) {
1060 if (Context.hasSameType(FieldType, AnonTy))
1071 /// \brief Determine structural equivalence of two records.
1072 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1073 RecordDecl *D1, RecordDecl *D2) {
1074 if (D1->isUnion() != D2->isUnion()) {
1075 if (Context.Complain) {
1076 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1077 << Context.C2.getTypeDeclType(D2);
1078 Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1079 << D1->getDeclName() << (unsigned)D1->getTagKind();
1084 if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1085 // If both anonymous structs/unions are in a record context, make sure
1086 // they occur in the same location in the context records.
1087 if (Optional<unsigned> Index1 = findUntaggedStructOrUnionIndex(D1)) {
1088 if (Optional<unsigned> Index2 = findUntaggedStructOrUnionIndex(D2)) {
1089 if (*Index1 != *Index2)
1095 // If both declarations are class template specializations, we know
1096 // the ODR applies, so check the template and template arguments.
1097 ClassTemplateSpecializationDecl *Spec1
1098 = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1099 ClassTemplateSpecializationDecl *Spec2
1100 = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1101 if (Spec1 && Spec2) {
1102 // Check that the specialized templates are the same.
1103 if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1104 Spec2->getSpecializedTemplate()))
1107 // Check that the template arguments are the same.
1108 if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1111 for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1112 if (!IsStructurallyEquivalent(Context,
1113 Spec1->getTemplateArgs().get(I),
1114 Spec2->getTemplateArgs().get(I)))
1117 // If one is a class template specialization and the other is not, these
1118 // structures are different.
1119 else if (Spec1 || Spec2)
1122 // Compare the definitions of these two records. If either or both are
1123 // incomplete, we assume that they are equivalent.
1124 D1 = D1->getDefinition();
1125 D2 = D2->getDefinition();
1129 if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1130 if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1131 if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1132 if (Context.Complain) {
1133 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1134 << Context.C2.getTypeDeclType(D2);
1135 Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1136 << D2CXX->getNumBases();
1137 Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1138 << D1CXX->getNumBases();
1143 // Check the base classes.
1144 for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1145 BaseEnd1 = D1CXX->bases_end(),
1146 Base2 = D2CXX->bases_begin();
1149 if (!IsStructurallyEquivalent(Context,
1150 Base1->getType(), Base2->getType())) {
1151 if (Context.Complain) {
1152 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1153 << Context.C2.getTypeDeclType(D2);
1154 Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1156 << Base2->getSourceRange();
1157 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1159 << Base1->getSourceRange();
1164 // Check virtual vs. non-virtual inheritance mismatch.
1165 if (Base1->isVirtual() != Base2->isVirtual()) {
1166 if (Context.Complain) {
1167 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1168 << Context.C2.getTypeDeclType(D2);
1169 Context.Diag2(Base2->getLocStart(),
1170 diag::note_odr_virtual_base)
1171 << Base2->isVirtual() << Base2->getSourceRange();
1172 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1173 << Base1->isVirtual()
1174 << Base1->getSourceRange();
1179 } else if (D1CXX->getNumBases() > 0) {
1180 if (Context.Complain) {
1181 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1182 << Context.C2.getTypeDeclType(D2);
1183 const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1184 Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1186 << Base1->getSourceRange();
1187 Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1193 // Check the fields for consistency.
1194 RecordDecl::field_iterator Field2 = D2->field_begin(),
1195 Field2End = D2->field_end();
1196 for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1197 Field1End = D1->field_end();
1198 Field1 != Field1End;
1199 ++Field1, ++Field2) {
1200 if (Field2 == Field2End) {
1201 if (Context.Complain) {
1202 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1203 << Context.C2.getTypeDeclType(D2);
1204 Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1205 << Field1->getDeclName() << Field1->getType();
1206 Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1211 if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1215 if (Field2 != Field2End) {
1216 if (Context.Complain) {
1217 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1218 << Context.C2.getTypeDeclType(D2);
1219 Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1220 << Field2->getDeclName() << Field2->getType();
1221 Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1229 /// \brief Determine structural equivalence of two enums.
1230 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1231 EnumDecl *D1, EnumDecl *D2) {
1232 EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1233 EC2End = D2->enumerator_end();
1234 for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1235 EC1End = D1->enumerator_end();
1236 EC1 != EC1End; ++EC1, ++EC2) {
1237 if (EC2 == EC2End) {
1238 if (Context.Complain) {
1239 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1240 << Context.C2.getTypeDeclType(D2);
1241 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1242 << EC1->getDeclName()
1243 << EC1->getInitVal().toString(10);
1244 Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1249 llvm::APSInt Val1 = EC1->getInitVal();
1250 llvm::APSInt Val2 = EC2->getInitVal();
1251 if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1252 !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1253 if (Context.Complain) {
1254 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1255 << Context.C2.getTypeDeclType(D2);
1256 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1257 << EC2->getDeclName()
1258 << EC2->getInitVal().toString(10);
1259 Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1260 << EC1->getDeclName()
1261 << EC1->getInitVal().toString(10);
1267 if (EC2 != EC2End) {
1268 if (Context.Complain) {
1269 Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1270 << Context.C2.getTypeDeclType(D2);
1271 Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1272 << EC2->getDeclName()
1273 << EC2->getInitVal().toString(10);
1274 Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1282 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1283 TemplateParameterList *Params1,
1284 TemplateParameterList *Params2) {
1285 if (Params1->size() != Params2->size()) {
1286 if (Context.Complain) {
1287 Context.Diag2(Params2->getTemplateLoc(),
1288 diag::err_odr_different_num_template_parameters)
1289 << Params1->size() << Params2->size();
1290 Context.Diag1(Params1->getTemplateLoc(),
1291 diag::note_odr_template_parameter_list);
1296 for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1297 if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1298 if (Context.Complain) {
1299 Context.Diag2(Params2->getParam(I)->getLocation(),
1300 diag::err_odr_different_template_parameter_kind);
1301 Context.Diag1(Params1->getParam(I)->getLocation(),
1302 diag::note_odr_template_parameter_here);
1307 if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1308 Params2->getParam(I))) {
1317 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1318 TemplateTypeParmDecl *D1,
1319 TemplateTypeParmDecl *D2) {
1320 if (D1->isParameterPack() != D2->isParameterPack()) {
1321 if (Context.Complain) {
1322 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1323 << D2->isParameterPack();
1324 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1325 << D1->isParameterPack();
1333 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1334 NonTypeTemplateParmDecl *D1,
1335 NonTypeTemplateParmDecl *D2) {
1336 if (D1->isParameterPack() != D2->isParameterPack()) {
1337 if (Context.Complain) {
1338 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1339 << D2->isParameterPack();
1340 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1341 << D1->isParameterPack();
1347 if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1348 if (Context.Complain) {
1349 Context.Diag2(D2->getLocation(),
1350 diag::err_odr_non_type_parameter_type_inconsistent)
1351 << D2->getType() << D1->getType();
1352 Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1361 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1362 TemplateTemplateParmDecl *D1,
1363 TemplateTemplateParmDecl *D2) {
1364 if (D1->isParameterPack() != D2->isParameterPack()) {
1365 if (Context.Complain) {
1366 Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1367 << D2->isParameterPack();
1368 Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1369 << D1->isParameterPack();
1374 // Check template parameter lists.
1375 return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1376 D2->getTemplateParameters());
1379 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1380 ClassTemplateDecl *D1,
1381 ClassTemplateDecl *D2) {
1382 // Check template parameters.
1383 if (!IsStructurallyEquivalent(Context,
1384 D1->getTemplateParameters(),
1385 D2->getTemplateParameters()))
1388 // Check the templated declaration.
1389 return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1390 D2->getTemplatedDecl());
1393 /// \brief Determine structural equivalence of two declarations.
1394 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1395 Decl *D1, Decl *D2) {
1396 // FIXME: Check for known structural equivalences via a callback of some sort.
1398 // Check whether we already know that these two declarations are not
1399 // structurally equivalent.
1400 if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1401 D2->getCanonicalDecl())))
1404 // Determine whether we've already produced a tentative equivalence for D1.
1405 Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1407 return EquivToD1 == D2->getCanonicalDecl();
1409 // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1410 EquivToD1 = D2->getCanonicalDecl();
1411 Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1415 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1417 if (!::IsStructurallyEquivalent(*this, D1, D2))
1423 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1425 if (!::IsStructurallyEquivalent(*this, T1, T2))
1431 bool StructuralEquivalenceContext::Finish() {
1432 while (!DeclsToCheck.empty()) {
1433 // Check the next declaration.
1434 Decl *D1 = DeclsToCheck.front();
1435 DeclsToCheck.pop_front();
1437 Decl *D2 = TentativeEquivalences[D1];
1438 assert(D2 && "Unrecorded tentative equivalence?");
1440 bool Equivalent = true;
1442 // FIXME: Switch on all declaration kinds. For now, we're just going to
1443 // check the obvious ones.
1444 if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1445 if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1446 // Check for equivalent structure names.
1447 IdentifierInfo *Name1 = Record1->getIdentifier();
1448 if (!Name1 && Record1->getTypedefNameForAnonDecl())
1449 Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1450 IdentifierInfo *Name2 = Record2->getIdentifier();
1451 if (!Name2 && Record2->getTypedefNameForAnonDecl())
1452 Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1453 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1454 !::IsStructurallyEquivalent(*this, Record1, Record2))
1457 // Record/non-record mismatch.
1460 } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1461 if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1462 // Check for equivalent enum names.
1463 IdentifierInfo *Name1 = Enum1->getIdentifier();
1464 if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1465 Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1466 IdentifierInfo *Name2 = Enum2->getIdentifier();
1467 if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1468 Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1469 if (!::IsStructurallyEquivalent(Name1, Name2) ||
1470 !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1473 // Enum/non-enum mismatch
1476 } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1477 if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1478 if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1479 Typedef2->getIdentifier()) ||
1480 !::IsStructurallyEquivalent(*this,
1481 Typedef1->getUnderlyingType(),
1482 Typedef2->getUnderlyingType()))
1485 // Typedef/non-typedef mismatch.
1488 } else if (ClassTemplateDecl *ClassTemplate1
1489 = dyn_cast<ClassTemplateDecl>(D1)) {
1490 if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1491 if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1492 ClassTemplate2->getIdentifier()) ||
1493 !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1496 // Class template/non-class-template mismatch.
1499 } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1500 if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1501 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1507 } else if (NonTypeTemplateParmDecl *NTTP1
1508 = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1509 if (NonTypeTemplateParmDecl *NTTP2
1510 = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1511 if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1517 } else if (TemplateTemplateParmDecl *TTP1
1518 = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1519 if (TemplateTemplateParmDecl *TTP2
1520 = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1521 if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1530 // Note that these two declarations are not equivalent (and we already
1532 NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1533 D2->getCanonicalDecl()));
1536 // FIXME: Check other declaration kinds!
1542 //----------------------------------------------------------------------------
1544 //----------------------------------------------------------------------------
1546 QualType ASTNodeImporter::VisitType(const Type *T) {
1547 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1548 << T->getTypeClassName();
1552 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1553 switch (T->getKind()) {
1554 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1555 case BuiltinType::Id: \
1556 return Importer.getToContext().SingletonId;
1557 #include "clang/Basic/OpenCLImageTypes.def"
1558 #define SHARED_SINGLETON_TYPE(Expansion)
1559 #define BUILTIN_TYPE(Id, SingletonId) \
1560 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1561 #include "clang/AST/BuiltinTypes.def"
1563 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1564 // context supports C++.
1566 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1567 // context supports ObjC.
1569 case BuiltinType::Char_U:
1570 // The context we're importing from has an unsigned 'char'. If we're
1571 // importing into a context with a signed 'char', translate to
1572 // 'unsigned char' instead.
1573 if (Importer.getToContext().getLangOpts().CharIsSigned)
1574 return Importer.getToContext().UnsignedCharTy;
1576 return Importer.getToContext().CharTy;
1578 case BuiltinType::Char_S:
1579 // The context we're importing from has an unsigned 'char'. If we're
1580 // importing into a context with a signed 'char', translate to
1581 // 'unsigned char' instead.
1582 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1583 return Importer.getToContext().SignedCharTy;
1585 return Importer.getToContext().CharTy;
1587 case BuiltinType::WChar_S:
1588 case BuiltinType::WChar_U:
1589 // FIXME: If not in C++, shall we translate to the C equivalent of
1591 return Importer.getToContext().WCharTy;
1594 llvm_unreachable("Invalid BuiltinType Kind!");
1597 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1598 QualType ToElementType = Importer.Import(T->getElementType());
1599 if (ToElementType.isNull())
1602 return Importer.getToContext().getComplexType(ToElementType);
1605 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1606 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1607 if (ToPointeeType.isNull())
1610 return Importer.getToContext().getPointerType(ToPointeeType);
1613 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1614 // FIXME: Check for blocks support in "to" context.
1615 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1616 if (ToPointeeType.isNull())
1619 return Importer.getToContext().getBlockPointerType(ToPointeeType);
1623 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1624 // FIXME: Check for C++ support in "to" context.
1625 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1626 if (ToPointeeType.isNull())
1629 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1633 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1634 // FIXME: Check for C++0x support in "to" context.
1635 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1636 if (ToPointeeType.isNull())
1639 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1642 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1643 // FIXME: Check for C++ support in "to" context.
1644 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1645 if (ToPointeeType.isNull())
1648 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1649 return Importer.getToContext().getMemberPointerType(ToPointeeType,
1650 ClassType.getTypePtr());
1653 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1654 QualType ToElementType = Importer.Import(T->getElementType());
1655 if (ToElementType.isNull())
1658 return Importer.getToContext().getConstantArrayType(ToElementType,
1660 T->getSizeModifier(),
1661 T->getIndexTypeCVRQualifiers());
1665 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1666 QualType ToElementType = Importer.Import(T->getElementType());
1667 if (ToElementType.isNull())
1670 return Importer.getToContext().getIncompleteArrayType(ToElementType,
1671 T->getSizeModifier(),
1672 T->getIndexTypeCVRQualifiers());
1675 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1676 QualType ToElementType = Importer.Import(T->getElementType());
1677 if (ToElementType.isNull())
1680 Expr *Size = Importer.Import(T->getSizeExpr());
1684 SourceRange Brackets = Importer.Import(T->getBracketsRange());
1685 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1686 T->getSizeModifier(),
1687 T->getIndexTypeCVRQualifiers(),
1691 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1692 QualType ToElementType = Importer.Import(T->getElementType());
1693 if (ToElementType.isNull())
1696 return Importer.getToContext().getVectorType(ToElementType,
1697 T->getNumElements(),
1698 T->getVectorKind());
1701 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1702 QualType ToElementType = Importer.Import(T->getElementType());
1703 if (ToElementType.isNull())
1706 return Importer.getToContext().getExtVectorType(ToElementType,
1707 T->getNumElements());
1711 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1712 // FIXME: What happens if we're importing a function without a prototype
1713 // into C++? Should we make it variadic?
1714 QualType ToResultType = Importer.Import(T->getReturnType());
1715 if (ToResultType.isNull())
1718 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1722 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1723 QualType ToResultType = Importer.Import(T->getReturnType());
1724 if (ToResultType.isNull())
1727 // Import argument types
1728 SmallVector<QualType, 4> ArgTypes;
1729 for (const auto &A : T->param_types()) {
1730 QualType ArgType = Importer.Import(A);
1731 if (ArgType.isNull())
1733 ArgTypes.push_back(ArgType);
1736 // Import exception types
1737 SmallVector<QualType, 4> ExceptionTypes;
1738 for (const auto &E : T->exceptions()) {
1739 QualType ExceptionType = Importer.Import(E);
1740 if (ExceptionType.isNull())
1742 ExceptionTypes.push_back(ExceptionType);
1745 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1746 FunctionProtoType::ExtProtoInfo ToEPI;
1748 ToEPI.ExtInfo = FromEPI.ExtInfo;
1749 ToEPI.Variadic = FromEPI.Variadic;
1750 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1751 ToEPI.TypeQuals = FromEPI.TypeQuals;
1752 ToEPI.RefQualifier = FromEPI.RefQualifier;
1753 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1754 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1755 ToEPI.ExceptionSpec.NoexceptExpr =
1756 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1757 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1758 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1759 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1760 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1762 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1765 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1766 QualType ToInnerType = Importer.Import(T->getInnerType());
1767 if (ToInnerType.isNull())
1770 return Importer.getToContext().getParenType(ToInnerType);
1773 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1774 TypedefNameDecl *ToDecl
1775 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1779 return Importer.getToContext().getTypeDeclType(ToDecl);
1782 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1783 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1787 return Importer.getToContext().getTypeOfExprType(ToExpr);
1790 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1791 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1792 if (ToUnderlyingType.isNull())
1795 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1798 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1799 // FIXME: Make sure that the "to" context supports C++0x!
1800 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1804 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1805 if (UnderlyingType.isNull())
1808 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1811 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1812 QualType ToBaseType = Importer.Import(T->getBaseType());
1813 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1814 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1817 return Importer.getToContext().getUnaryTransformType(ToBaseType,
1822 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1823 // FIXME: Make sure that the "to" context supports C++11!
1824 QualType FromDeduced = T->getDeducedType();
1826 if (!FromDeduced.isNull()) {
1827 ToDeduced = Importer.Import(FromDeduced);
1828 if (ToDeduced.isNull())
1832 return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1833 /*IsDependent*/false);
1836 QualType ASTNodeImporter::VisitInjectedClassNameType(
1837 const InjectedClassNameType *T) {
1838 CXXRecordDecl *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
1842 QualType InjType = Importer.Import(T->getInjectedSpecializationType());
1843 if (InjType.isNull())
1846 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1847 // See comments in InjectedClassNameType definition for details
1848 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1850 TypeAlignmentInBits = 4,
1851 TypeAlignment = 1 << TypeAlignmentInBits
1854 return QualType(new (Importer.getToContext(), TypeAlignment)
1855 InjectedClassNameType(D, InjType), 0);
1858 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1860 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1864 return Importer.getToContext().getTagDeclType(ToDecl);
1867 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1869 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1873 return Importer.getToContext().getTagDeclType(ToDecl);
1876 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1877 QualType FromModifiedType = T->getModifiedType();
1878 QualType FromEquivalentType = T->getEquivalentType();
1879 QualType ToModifiedType;
1880 QualType ToEquivalentType;
1882 if (!FromModifiedType.isNull()) {
1883 ToModifiedType = Importer.Import(FromModifiedType);
1884 if (ToModifiedType.isNull())
1887 if (!FromEquivalentType.isNull()) {
1888 ToEquivalentType = Importer.Import(FromEquivalentType);
1889 if (ToEquivalentType.isNull())
1893 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1894 ToModifiedType, ToEquivalentType);
1898 QualType ASTNodeImporter::VisitTemplateTypeParmType(
1899 const TemplateTypeParmType *T) {
1900 TemplateTypeParmDecl *ParmDecl =
1901 cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
1902 if (!ParmDecl && T->getDecl())
1905 return Importer.getToContext().getTemplateTypeParmType(
1906 T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
1909 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1910 const TemplateSpecializationType *T) {
1911 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1912 if (ToTemplate.isNull())
1915 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1916 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1919 QualType ToCanonType;
1920 if (!QualType(T, 0).isCanonical()) {
1921 QualType FromCanonType
1922 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1923 ToCanonType =Importer.Import(FromCanonType);
1924 if (ToCanonType.isNull())
1927 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1932 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1933 NestedNameSpecifier *ToQualifier = nullptr;
1934 // Note: the qualifier in an ElaboratedType is optional.
1935 if (T->getQualifier()) {
1936 ToQualifier = Importer.Import(T->getQualifier());
1941 QualType ToNamedType = Importer.Import(T->getNamedType());
1942 if (ToNamedType.isNull())
1945 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1946 ToQualifier, ToNamedType);
1949 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1950 ObjCInterfaceDecl *Class
1951 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1955 return Importer.getToContext().getObjCInterfaceType(Class);
1958 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1959 QualType ToBaseType = Importer.Import(T->getBaseType());
1960 if (ToBaseType.isNull())
1963 SmallVector<QualType, 4> TypeArgs;
1964 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1965 QualType ImportedTypeArg = Importer.Import(TypeArg);
1966 if (ImportedTypeArg.isNull())
1969 TypeArgs.push_back(ImportedTypeArg);
1972 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1973 for (auto *P : T->quals()) {
1974 ObjCProtocolDecl *Protocol
1975 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1978 Protocols.push_back(Protocol);
1981 return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1983 T->isKindOfTypeAsWritten());
1987 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1988 QualType ToPointeeType = Importer.Import(T->getPointeeType());
1989 if (ToPointeeType.isNull())
1992 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1995 //----------------------------------------------------------------------------
1996 // Import Declarations
1997 //----------------------------------------------------------------------------
1998 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1999 DeclContext *&LexicalDC,
2000 DeclarationName &Name,
2002 SourceLocation &Loc) {
2003 // Import the context of this declaration.
2004 DC = Importer.ImportContext(D->getDeclContext());
2009 if (D->getDeclContext() != D->getLexicalDeclContext()) {
2010 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2015 // Import the name of this declaration.
2016 Name = Importer.Import(D->getDeclName());
2017 if (D->getDeclName() && !Name)
2020 // Import the location of this declaration.
2021 Loc = Importer.Import(D->getLocation());
2022 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
2026 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
2031 ToD = Importer.Import(FromD);
2036 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
2037 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
2038 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
2039 ImportDefinition(FromRecord, ToRecord);
2045 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
2046 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
2047 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
2048 ImportDefinition(FromEnum, ToEnum);
2056 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
2057 DeclarationNameInfo& To) {
2058 // NOTE: To.Name and To.Loc are already imported.
2059 // We only have to import To.LocInfo.
2060 switch (To.getName().getNameKind()) {
2061 case DeclarationName::Identifier:
2062 case DeclarationName::ObjCZeroArgSelector:
2063 case DeclarationName::ObjCOneArgSelector:
2064 case DeclarationName::ObjCMultiArgSelector:
2065 case DeclarationName::CXXUsingDirective:
2068 case DeclarationName::CXXOperatorName: {
2069 SourceRange Range = From.getCXXOperatorNameRange();
2070 To.setCXXOperatorNameRange(Importer.Import(Range));
2073 case DeclarationName::CXXLiteralOperatorName: {
2074 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
2075 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
2078 case DeclarationName::CXXConstructorName:
2079 case DeclarationName::CXXDestructorName:
2080 case DeclarationName::CXXConversionFunctionName: {
2081 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
2082 To.setNamedTypeInfo(Importer.Import(FromTInfo));
2086 llvm_unreachable("Unknown name kind.");
2089 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
2090 if (Importer.isMinimalImport() && !ForceImport) {
2091 Importer.ImportContext(FromDC);
2095 for (auto *From : FromDC->decls())
2096 Importer.Import(From);
2099 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
2100 ImportDefinitionKind Kind) {
2101 if (To->getDefinition() || To->isBeingDefined()) {
2102 if (Kind == IDK_Everything)
2103 ImportDeclContext(From, /*ForceImport=*/true);
2108 To->startDefinition();
2110 // Add base classes.
2111 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
2112 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
2114 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2115 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2116 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2117 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2118 ToData.Aggregate = FromData.Aggregate;
2119 ToData.PlainOldData = FromData.PlainOldData;
2120 ToData.Empty = FromData.Empty;
2121 ToData.Polymorphic = FromData.Polymorphic;
2122 ToData.Abstract = FromData.Abstract;
2123 ToData.IsStandardLayout = FromData.IsStandardLayout;
2124 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2125 ToData.HasPrivateFields = FromData.HasPrivateFields;
2126 ToData.HasProtectedFields = FromData.HasProtectedFields;
2127 ToData.HasPublicFields = FromData.HasPublicFields;
2128 ToData.HasMutableFields = FromData.HasMutableFields;
2129 ToData.HasVariantMembers = FromData.HasVariantMembers;
2130 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2131 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2132 ToData.HasUninitializedReferenceMember
2133 = FromData.HasUninitializedReferenceMember;
2134 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
2135 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
2136 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
2137 ToData.NeedOverloadResolutionForMoveConstructor
2138 = FromData.NeedOverloadResolutionForMoveConstructor;
2139 ToData.NeedOverloadResolutionForMoveAssignment
2140 = FromData.NeedOverloadResolutionForMoveAssignment;
2141 ToData.NeedOverloadResolutionForDestructor
2142 = FromData.NeedOverloadResolutionForDestructor;
2143 ToData.DefaultedMoveConstructorIsDeleted
2144 = FromData.DefaultedMoveConstructorIsDeleted;
2145 ToData.DefaultedMoveAssignmentIsDeleted
2146 = FromData.DefaultedMoveAssignmentIsDeleted;
2147 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2148 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2149 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2150 ToData.HasConstexprNonCopyMoveConstructor
2151 = FromData.HasConstexprNonCopyMoveConstructor;
2152 ToData.HasDefaultedDefaultConstructor
2153 = FromData.HasDefaultedDefaultConstructor;
2154 ToData.DefaultedDefaultConstructorIsConstexpr
2155 = FromData.DefaultedDefaultConstructorIsConstexpr;
2156 ToData.HasConstexprDefaultConstructor
2157 = FromData.HasConstexprDefaultConstructor;
2158 ToData.HasNonLiteralTypeFieldsOrBases
2159 = FromData.HasNonLiteralTypeFieldsOrBases;
2160 // ComputedVisibleConversions not imported.
2161 ToData.UserProvidedDefaultConstructor
2162 = FromData.UserProvidedDefaultConstructor;
2163 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2164 ToData.ImplicitCopyConstructorHasConstParam
2165 = FromData.ImplicitCopyConstructorHasConstParam;
2166 ToData.ImplicitCopyAssignmentHasConstParam
2167 = FromData.ImplicitCopyAssignmentHasConstParam;
2168 ToData.HasDeclaredCopyConstructorWithConstParam
2169 = FromData.HasDeclaredCopyConstructorWithConstParam;
2170 ToData.HasDeclaredCopyAssignmentWithConstParam
2171 = FromData.HasDeclaredCopyAssignmentWithConstParam;
2172 ToData.IsLambda = FromData.IsLambda;
2174 SmallVector<CXXBaseSpecifier *, 4> Bases;
2175 for (const auto &Base1 : FromCXX->bases()) {
2176 QualType T = Importer.Import(Base1.getType());
2180 SourceLocation EllipsisLoc;
2181 if (Base1.isPackExpansion())
2182 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2184 // Ensure that we have a definition for the base.
2185 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2188 new (Importer.getToContext())
2189 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2191 Base1.isBaseOfClass(),
2192 Base1.getAccessSpecifierAsWritten(),
2193 Importer.Import(Base1.getTypeSourceInfo()),
2197 ToCXX->setBases(Bases.data(), Bases.size());
2200 if (shouldForceImportDeclContext(Kind))
2201 ImportDeclContext(From, /*ForceImport=*/true);
2203 To->completeDefinition();
2207 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2208 ImportDefinitionKind Kind) {
2209 if (To->getAnyInitializer())
2212 // FIXME: Can we really import any initializer? Alternatively, we could force
2213 // ourselves to import every declaration of a variable and then only use
2215 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2217 // FIXME: Other bits to merge?
2222 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2223 ImportDefinitionKind Kind) {
2224 if (To->getDefinition() || To->isBeingDefined()) {
2225 if (Kind == IDK_Everything)
2226 ImportDeclContext(From, /*ForceImport=*/true);
2230 To->startDefinition();
2232 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2236 QualType ToPromotionType = Importer.Import(From->getPromotionType());
2237 if (ToPromotionType.isNull())
2240 if (shouldForceImportDeclContext(Kind))
2241 ImportDeclContext(From, /*ForceImport=*/true);
2243 // FIXME: we might need to merge the number of positive or negative bits
2244 // if the enumerator lists don't match.
2245 To->completeDefinition(T, ToPromotionType,
2246 From->getNumPositiveBits(),
2247 From->getNumNegativeBits());
2251 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2252 TemplateParameterList *Params) {
2253 SmallVector<NamedDecl *, 4> ToParams;
2254 ToParams.reserve(Params->size());
2255 for (TemplateParameterList::iterator P = Params->begin(),
2256 PEnd = Params->end();
2258 Decl *To = Importer.Import(*P);
2262 ToParams.push_back(cast<NamedDecl>(To));
2265 Expr *ToRequiresClause;
2266 if (Expr *const R = Params->getRequiresClause()) {
2267 ToRequiresClause = Importer.Import(R);
2268 if (!ToRequiresClause)
2271 ToRequiresClause = nullptr;
2274 return TemplateParameterList::Create(Importer.getToContext(),
2275 Importer.Import(Params->getTemplateLoc()),
2276 Importer.Import(Params->getLAngleLoc()),
2278 Importer.Import(Params->getRAngleLoc()),
2283 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2284 switch (From.getKind()) {
2285 case TemplateArgument::Null:
2286 return TemplateArgument();
2288 case TemplateArgument::Type: {
2289 QualType ToType = Importer.Import(From.getAsType());
2290 if (ToType.isNull())
2291 return TemplateArgument();
2292 return TemplateArgument(ToType);
2295 case TemplateArgument::Integral: {
2296 QualType ToType = Importer.Import(From.getIntegralType());
2297 if (ToType.isNull())
2298 return TemplateArgument();
2299 return TemplateArgument(From, ToType);
2302 case TemplateArgument::Declaration: {
2303 ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2304 QualType ToType = Importer.Import(From.getParamTypeForDecl());
2305 if (!To || ToType.isNull())
2306 return TemplateArgument();
2307 return TemplateArgument(To, ToType);
2310 case TemplateArgument::NullPtr: {
2311 QualType ToType = Importer.Import(From.getNullPtrType());
2312 if (ToType.isNull())
2313 return TemplateArgument();
2314 return TemplateArgument(ToType, /*isNullPtr*/true);
2317 case TemplateArgument::Template: {
2318 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2319 if (ToTemplate.isNull())
2320 return TemplateArgument();
2322 return TemplateArgument(ToTemplate);
2325 case TemplateArgument::TemplateExpansion: {
2326 TemplateName ToTemplate
2327 = Importer.Import(From.getAsTemplateOrTemplatePattern());
2328 if (ToTemplate.isNull())
2329 return TemplateArgument();
2331 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2334 case TemplateArgument::Expression:
2335 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2336 return TemplateArgument(ToExpr);
2337 return TemplateArgument();
2339 case TemplateArgument::Pack: {
2340 SmallVector<TemplateArgument, 2> ToPack;
2341 ToPack.reserve(From.pack_size());
2342 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2343 return TemplateArgument();
2345 return TemplateArgument(
2346 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2350 llvm_unreachable("Invalid template argument kind");
2353 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2354 unsigned NumFromArgs,
2355 SmallVectorImpl<TemplateArgument> &ToArgs) {
2356 for (unsigned I = 0; I != NumFromArgs; ++I) {
2357 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2358 if (To.isNull() && !FromArgs[I].isNull())
2361 ToArgs.push_back(To);
2367 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2368 RecordDecl *ToRecord, bool Complain) {
2369 // Eliminate a potential failure point where we attempt to re-import
2370 // something we're trying to import while completing ToRecord.
2371 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2373 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2375 ToRecord = ToOriginRecord;
2378 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2379 ToRecord->getASTContext(),
2380 Importer.getNonEquivalentDecls(),
2382 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2385 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2387 StructuralEquivalenceContext Ctx(
2388 Importer.getFromContext(), Importer.getToContext(),
2389 Importer.getNonEquivalentDecls(), false, Complain);
2390 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2393 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2394 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2395 Importer.getToContext(),
2396 Importer.getNonEquivalentDecls());
2397 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2400 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2401 EnumConstantDecl *ToEC)
2403 const llvm::APSInt &FromVal = FromEC->getInitVal();
2404 const llvm::APSInt &ToVal = ToEC->getInitVal();
2406 return FromVal.isSigned() == ToVal.isSigned() &&
2407 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2411 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2412 ClassTemplateDecl *To) {
2413 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2414 Importer.getToContext(),
2415 Importer.getNonEquivalentDecls());
2416 return Ctx.IsStructurallyEquivalent(From, To);
2419 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2420 VarTemplateDecl *To) {
2421 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2422 Importer.getToContext(),
2423 Importer.getNonEquivalentDecls());
2424 return Ctx.IsStructurallyEquivalent(From, To);
2427 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2428 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2429 << D->getDeclKindName();
2433 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2434 TranslationUnitDecl *ToD =
2435 Importer.getToContext().getTranslationUnitDecl();
2437 Importer.Imported(D, ToD);
2442 Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2444 SourceLocation Loc = Importer.Import(D->getLocation());
2445 SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
2447 // Import the context of this declaration.
2448 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2452 AccessSpecDecl *accessSpecDecl
2453 = AccessSpecDecl::Create(Importer.getToContext(), D->getAccess(),
2456 if (!accessSpecDecl)
2459 // Lexical DeclContext and Semantic DeclContext
2460 // is always the same for the accessSpec.
2461 accessSpecDecl->setLexicalDeclContext(DC);
2462 DC->addDeclInternal(accessSpecDecl);
2464 return accessSpecDecl;
2467 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2468 // Import the major distinguishing characteristics of this namespace.
2469 DeclContext *DC, *LexicalDC;
2470 DeclarationName Name;
2473 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2478 NamespaceDecl *MergeWithNamespace = nullptr;
2480 // This is an anonymous namespace. Adopt an existing anonymous
2481 // namespace if we can.
2482 // FIXME: Not testable.
2483 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2484 MergeWithNamespace = TU->getAnonymousNamespace();
2486 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2488 SmallVector<NamedDecl *, 4> ConflictingDecls;
2489 SmallVector<NamedDecl *, 2> FoundDecls;
2490 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2491 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2492 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2495 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2496 MergeWithNamespace = FoundNS;
2497 ConflictingDecls.clear();
2501 ConflictingDecls.push_back(FoundDecls[I]);
2504 if (!ConflictingDecls.empty()) {
2505 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2506 ConflictingDecls.data(),
2507 ConflictingDecls.size());
2511 // Create the "to" namespace, if needed.
2512 NamespaceDecl *ToNamespace = MergeWithNamespace;
2514 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2516 Importer.Import(D->getLocStart()),
2517 Loc, Name.getAsIdentifierInfo(),
2518 /*PrevDecl=*/nullptr);
2519 ToNamespace->setLexicalDeclContext(LexicalDC);
2520 LexicalDC->addDeclInternal(ToNamespace);
2522 // If this is an anonymous namespace, register it as the anonymous
2523 // namespace within its context.
2525 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2526 TU->setAnonymousNamespace(ToNamespace);
2528 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2531 Importer.Imported(D, ToNamespace);
2533 ImportDeclContext(D);
2538 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2539 // Import the major distinguishing characteristics of this typedef.
2540 DeclContext *DC, *LexicalDC;
2541 DeclarationName Name;
2544 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2549 // If this typedef is not in block scope, determine whether we've
2550 // seen a typedef with the same name (that we can merge with) or any
2551 // other entity by that name (which name lookup could conflict with).
2552 if (!DC->isFunctionOrMethod()) {
2553 SmallVector<NamedDecl *, 4> ConflictingDecls;
2554 unsigned IDNS = Decl::IDNS_Ordinary;
2555 SmallVector<NamedDecl *, 2> FoundDecls;
2556 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2557 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2558 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2560 if (TypedefNameDecl *FoundTypedef =
2561 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2562 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2563 FoundTypedef->getUnderlyingType()))
2564 return Importer.Imported(D, FoundTypedef);
2567 ConflictingDecls.push_back(FoundDecls[I]);
2570 if (!ConflictingDecls.empty()) {
2571 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2572 ConflictingDecls.data(),
2573 ConflictingDecls.size());
2579 // Import the underlying type of this typedef;
2580 QualType T = Importer.Import(D->getUnderlyingType());
2584 // Create the new typedef node.
2585 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2586 SourceLocation StartL = Importer.Import(D->getLocStart());
2587 TypedefNameDecl *ToTypedef;
2589 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2591 Name.getAsIdentifierInfo(),
2594 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2596 Name.getAsIdentifierInfo(),
2599 ToTypedef->setAccess(D->getAccess());
2600 ToTypedef->setLexicalDeclContext(LexicalDC);
2601 Importer.Imported(D, ToTypedef);
2602 LexicalDC->addDeclInternal(ToTypedef);
2607 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2608 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2611 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2612 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2615 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2616 // Import the major distinguishing characteristics of this label.
2617 DeclContext *DC, *LexicalDC;
2618 DeclarationName Name;
2621 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2626 assert(LexicalDC->isFunctionOrMethod());
2628 LabelDecl *ToLabel = D->isGnuLocal()
2629 ? LabelDecl::Create(Importer.getToContext(),
2630 DC, Importer.Import(D->getLocation()),
2631 Name.getAsIdentifierInfo(),
2632 Importer.Import(D->getLocStart()))
2633 : LabelDecl::Create(Importer.getToContext(),
2634 DC, Importer.Import(D->getLocation()),
2635 Name.getAsIdentifierInfo());
2636 Importer.Imported(D, ToLabel);
2638 LabelStmt *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
2642 ToLabel->setStmt(Label);
2643 ToLabel->setLexicalDeclContext(LexicalDC);
2644 LexicalDC->addDeclInternal(ToLabel);
2648 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2649 // Import the major distinguishing characteristics of this enum.
2650 DeclContext *DC, *LexicalDC;
2651 DeclarationName Name;
2654 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2659 // Figure out what enum name we're looking for.
2660 unsigned IDNS = Decl::IDNS_Tag;
2661 DeclarationName SearchName = Name;
2662 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2663 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2664 IDNS = Decl::IDNS_Ordinary;
2665 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2666 IDNS |= Decl::IDNS_Ordinary;
2668 // We may already have an enum of the same name; try to find and match it.
2669 if (!DC->isFunctionOrMethod() && SearchName) {
2670 SmallVector<NamedDecl *, 4> ConflictingDecls;
2671 SmallVector<NamedDecl *, 2> FoundDecls;
2672 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2673 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2674 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2677 Decl *Found = FoundDecls[I];
2678 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2679 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2680 Found = Tag->getDecl();
2683 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2684 if (IsStructuralMatch(D, FoundEnum))
2685 return Importer.Imported(D, FoundEnum);
2688 ConflictingDecls.push_back(FoundDecls[I]);
2691 if (!ConflictingDecls.empty()) {
2692 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2693 ConflictingDecls.data(),
2694 ConflictingDecls.size());
2698 // Create the enum declaration.
2699 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2700 Importer.Import(D->getLocStart()),
2701 Loc, Name.getAsIdentifierInfo(), nullptr,
2702 D->isScoped(), D->isScopedUsingClassTag(),
2704 // Import the qualifier, if any.
2705 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2706 D2->setAccess(D->getAccess());
2707 D2->setLexicalDeclContext(LexicalDC);
2708 Importer.Imported(D, D2);
2709 LexicalDC->addDeclInternal(D2);
2711 // Import the integer type.
2712 QualType ToIntegerType = Importer.Import(D->getIntegerType());
2713 if (ToIntegerType.isNull())
2715 D2->setIntegerType(ToIntegerType);
2717 // Import the definition
2718 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2724 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2725 // If this record has a definition in the translation unit we're coming from,
2726 // but this particular declaration is not that definition, import the
2727 // definition and map to that.
2728 TagDecl *Definition = D->getDefinition();
2729 if (Definition && Definition != D) {
2730 Decl *ImportedDef = Importer.Import(Definition);
2734 return Importer.Imported(D, ImportedDef);
2737 // Import the major distinguishing characteristics of this record.
2738 DeclContext *DC, *LexicalDC;
2739 DeclarationName Name;
2742 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2747 // Figure out what structure name we're looking for.
2748 unsigned IDNS = Decl::IDNS_Tag;
2749 DeclarationName SearchName = Name;
2750 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2751 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2752 IDNS = Decl::IDNS_Ordinary;
2753 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2754 IDNS |= Decl::IDNS_Ordinary;
2756 // We may already have a record of the same name; try to find and match it.
2757 RecordDecl *AdoptDecl = nullptr;
2758 if (!DC->isFunctionOrMethod()) {
2759 SmallVector<NamedDecl *, 4> ConflictingDecls;
2760 SmallVector<NamedDecl *, 2> FoundDecls;
2761 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2762 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2763 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2766 Decl *Found = FoundDecls[I];
2767 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2768 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2769 Found = Tag->getDecl();
2772 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2773 if (D->isAnonymousStructOrUnion() &&
2774 FoundRecord->isAnonymousStructOrUnion()) {
2775 // If both anonymous structs/unions are in a record context, make sure
2776 // they occur in the same location in the context records.
2777 if (Optional<unsigned> Index1
2778 = findUntaggedStructOrUnionIndex(D)) {
2779 if (Optional<unsigned> Index2 =
2780 findUntaggedStructOrUnionIndex(FoundRecord)) {
2781 if (*Index1 != *Index2)
2787 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2788 if ((SearchName && !D->isCompleteDefinition())
2789 || (D->isCompleteDefinition() &&
2790 D->isAnonymousStructOrUnion()
2791 == FoundDef->isAnonymousStructOrUnion() &&
2792 IsStructuralMatch(D, FoundDef))) {
2793 // The record types structurally match, or the "from" translation
2794 // unit only had a forward declaration anyway; call it the same
2796 // FIXME: For C++, we should also merge methods here.
2797 return Importer.Imported(D, FoundDef);
2799 } else if (!D->isCompleteDefinition()) {
2800 // We have a forward declaration of this type, so adopt that forward
2801 // declaration rather than building a new one.
2803 // If one or both can be completed from external storage then try one
2804 // last time to complete and compare them before doing this.
2806 if (FoundRecord->hasExternalLexicalStorage() &&
2807 !FoundRecord->isCompleteDefinition())
2808 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2809 if (D->hasExternalLexicalStorage())
2810 D->getASTContext().getExternalSource()->CompleteType(D);
2812 if (FoundRecord->isCompleteDefinition() &&
2813 D->isCompleteDefinition() &&
2814 !IsStructuralMatch(D, FoundRecord))
2817 AdoptDecl = FoundRecord;
2819 } else if (!SearchName) {
2824 ConflictingDecls.push_back(FoundDecls[I]);
2827 if (!ConflictingDecls.empty() && SearchName) {
2828 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2829 ConflictingDecls.data(),
2830 ConflictingDecls.size());
2834 // Create the record declaration.
2835 RecordDecl *D2 = AdoptDecl;
2836 SourceLocation StartLoc = Importer.Import(D->getLocStart());
2838 CXXRecordDecl *D2CXX = nullptr;
2839 if (CXXRecordDecl *DCXX = llvm::dyn_cast<CXXRecordDecl>(D)) {
2840 if (DCXX->isLambda()) {
2841 TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
2842 D2CXX = CXXRecordDecl::CreateLambda(Importer.getToContext(),
2844 DCXX->isDependentLambda(),
2845 DCXX->isGenericLambda(),
2846 DCXX->getLambdaCaptureDefault());
2847 Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
2848 if (DCXX->getLambdaContextDecl() && !CDecl)
2850 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
2851 } else if (DCXX->isInjectedClassName()) {
2852 // We have to be careful to do a similar dance to the one in
2853 // Sema::ActOnStartCXXMemberDeclarations
2854 CXXRecordDecl *const PrevDecl = nullptr;
2855 const bool DelayTypeCreation = true;
2856 D2CXX = CXXRecordDecl::Create(
2857 Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc,
2858 Name.getAsIdentifierInfo(), PrevDecl, DelayTypeCreation);
2859 Importer.getToContext().getTypeDeclType(
2860 D2CXX, llvm::dyn_cast<CXXRecordDecl>(DC));
2862 D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2865 Name.getAsIdentifierInfo());
2868 D2->setAccess(D->getAccess());
2870 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2871 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2874 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2875 D2->setLexicalDeclContext(LexicalDC);
2876 LexicalDC->addDeclInternal(D2);
2877 if (D->isAnonymousStructOrUnion())
2878 D2->setAnonymousStructOrUnion(true);
2881 Importer.Imported(D, D2);
2883 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2889 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2890 // Import the major distinguishing characteristics of this enumerator.
2891 DeclContext *DC, *LexicalDC;
2892 DeclarationName Name;
2895 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2900 QualType T = Importer.Import(D->getType());
2904 // Determine whether there are any other declarations with the same name and
2905 // in the same context.
2906 if (!LexicalDC->isFunctionOrMethod()) {
2907 SmallVector<NamedDecl *, 4> ConflictingDecls;
2908 unsigned IDNS = Decl::IDNS_Ordinary;
2909 SmallVector<NamedDecl *, 2> FoundDecls;
2910 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2911 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2912 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2915 if (EnumConstantDecl *FoundEnumConstant
2916 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2917 if (IsStructuralMatch(D, FoundEnumConstant))
2918 return Importer.Imported(D, FoundEnumConstant);
2921 ConflictingDecls.push_back(FoundDecls[I]);
2924 if (!ConflictingDecls.empty()) {
2925 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2926 ConflictingDecls.data(),
2927 ConflictingDecls.size());
2933 Expr *Init = Importer.Import(D->getInitExpr());
2934 if (D->getInitExpr() && !Init)
2937 EnumConstantDecl *ToEnumerator
2938 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2939 Name.getAsIdentifierInfo(), T,
2940 Init, D->getInitVal());
2941 ToEnumerator->setAccess(D->getAccess());
2942 ToEnumerator->setLexicalDeclContext(LexicalDC);
2943 Importer.Imported(D, ToEnumerator);
2944 LexicalDC->addDeclInternal(ToEnumerator);
2945 return ToEnumerator;
2948 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2949 // Import the major distinguishing characteristics of this function.
2950 DeclContext *DC, *LexicalDC;
2951 DeclarationName Name;
2954 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2959 // Try to find a function in our own ("to") context with the same name, same
2960 // type, and in the same context as the function we're importing.
2961 if (!LexicalDC->isFunctionOrMethod()) {
2962 SmallVector<NamedDecl *, 4> ConflictingDecls;
2963 unsigned IDNS = Decl::IDNS_Ordinary;
2964 SmallVector<NamedDecl *, 2> FoundDecls;
2965 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2966 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2967 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2970 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2971 if (FoundFunction->hasExternalFormalLinkage() &&
2972 D->hasExternalFormalLinkage()) {
2973 if (Importer.IsStructurallyEquivalent(D->getType(),
2974 FoundFunction->getType())) {
2975 // FIXME: Actually try to merge the body and other attributes.
2976 return Importer.Imported(D, FoundFunction);
2979 // FIXME: Check for overloading more carefully, e.g., by boosting
2980 // Sema::IsOverload out to the AST library.
2982 // Function overloading is okay in C++.
2983 if (Importer.getToContext().getLangOpts().CPlusPlus)
2986 // Complain about inconsistent function types.
2987 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2988 << Name << D->getType() << FoundFunction->getType();
2989 Importer.ToDiag(FoundFunction->getLocation(),
2990 diag::note_odr_value_here)
2991 << FoundFunction->getType();
2995 ConflictingDecls.push_back(FoundDecls[I]);
2998 if (!ConflictingDecls.empty()) {
2999 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3000 ConflictingDecls.data(),
3001 ConflictingDecls.size());
3007 DeclarationNameInfo NameInfo(Name, Loc);
3008 // Import additional name location/type info.
3009 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
3011 QualType FromTy = D->getType();
3012 bool usedDifferentExceptionSpec = false;
3014 if (const FunctionProtoType *
3015 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3016 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3017 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3018 // FunctionDecl that we are importing the FunctionProtoType for.
3019 // To avoid an infinite recursion when importing, create the FunctionDecl
3020 // with a simplified function type and update it afterwards.
3021 if (FromEPI.ExceptionSpec.SourceDecl ||
3022 FromEPI.ExceptionSpec.SourceTemplate ||
3023 FromEPI.ExceptionSpec.NoexceptExpr) {
3024 FunctionProtoType::ExtProtoInfo DefaultEPI;
3025 FromTy = Importer.getFromContext().getFunctionType(
3026 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3027 usedDifferentExceptionSpec = true;
3032 QualType T = Importer.Import(FromTy);
3036 // Import the function parameters.
3037 SmallVector<ParmVarDecl *, 8> Parameters;
3038 for (auto P : D->parameters()) {
3039 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
3043 Parameters.push_back(ToP);
3046 // Create the imported function.
3047 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3048 FunctionDecl *ToFunction = nullptr;
3049 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
3050 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3051 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
3052 cast<CXXRecordDecl>(DC),
3055 FromConstructor->isExplicit(),
3056 D->isInlineSpecified(),
3059 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3060 SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
3061 for (CXXCtorInitializer *I : FromConstructor->inits()) {
3062 CXXCtorInitializer *ToI =
3063 cast_or_null<CXXCtorInitializer>(Importer.Import(I));
3066 CtorInitializers.push_back(ToI);
3068 CXXCtorInitializer **Memory =
3069 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3070 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3071 CXXConstructorDecl *ToCtor = llvm::cast<CXXConstructorDecl>(ToFunction);
3072 ToCtor->setCtorInitializers(Memory);
3073 ToCtor->setNumCtorInitializers(NumInitializers);
3075 } else if (isa<CXXDestructorDecl>(D)) {
3076 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
3077 cast<CXXRecordDecl>(DC),
3080 D->isInlineSpecified(),
3082 } else if (CXXConversionDecl *FromConversion
3083 = dyn_cast<CXXConversionDecl>(D)) {
3084 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
3085 cast<CXXRecordDecl>(DC),
3088 D->isInlineSpecified(),
3089 FromConversion->isExplicit(),
3091 Importer.Import(D->getLocEnd()));
3092 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
3093 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
3094 cast<CXXRecordDecl>(DC),
3097 Method->getStorageClass(),
3098 Method->isInlineSpecified(),
3100 Importer.Import(D->getLocEnd()));
3102 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
3104 NameInfo, T, TInfo, D->getStorageClass(),
3105 D->isInlineSpecified(),
3106 D->hasWrittenPrototype(),
3110 // Import the qualifier, if any.
3111 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3112 ToFunction->setAccess(D->getAccess());
3113 ToFunction->setLexicalDeclContext(LexicalDC);
3114 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3115 ToFunction->setTrivial(D->isTrivial());
3116 ToFunction->setPure(D->isPure());
3117 Importer.Imported(D, ToFunction);
3119 // Set the parameters.
3120 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
3121 Parameters[I]->setOwningFunction(ToFunction);
3122 ToFunction->addDeclInternal(Parameters[I]);
3124 ToFunction->setParams(Parameters);
3126 if (usedDifferentExceptionSpec) {
3127 // Update FunctionProtoType::ExtProtoInfo.
3128 QualType T = Importer.Import(D->getType());
3131 ToFunction->setType(T);
3134 // Import the body, if any.
3135 if (Stmt *FromBody = D->getBody()) {
3136 if (Stmt *ToBody = Importer.Import(FromBody)) {
3137 ToFunction->setBody(ToBody);
3141 // FIXME: Other bits to merge?
3143 // Add this function to the lexical context.
3144 LexicalDC->addDeclInternal(ToFunction);
3149 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3150 return VisitFunctionDecl(D);
3153 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3154 return VisitCXXMethodDecl(D);
3157 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3158 return VisitCXXMethodDecl(D);
3161 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3162 return VisitCXXMethodDecl(D);
3165 static unsigned getFieldIndex(Decl *F) {
3166 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
3171 for (const auto *D : Owner->noload_decls()) {
3175 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
3182 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3183 // Import the major distinguishing characteristics of a variable.
3184 DeclContext *DC, *LexicalDC;
3185 DeclarationName Name;
3188 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3193 // Determine whether we've already imported this field.
3194 SmallVector<NamedDecl *, 2> FoundDecls;
3195 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3196 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3197 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
3198 // For anonymous fields, match up by index.
3199 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3202 if (Importer.IsStructurallyEquivalent(D->getType(),
3203 FoundField->getType())) {
3204 Importer.Imported(D, FoundField);
3208 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3209 << Name << D->getType() << FoundField->getType();
3210 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3211 << FoundField->getType();
3217 QualType T = Importer.Import(D->getType());
3221 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3222 Expr *BitWidth = Importer.Import(D->getBitWidth());
3223 if (!BitWidth && D->getBitWidth())
3226 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
3227 Importer.Import(D->getInnerLocStart()),
3228 Loc, Name.getAsIdentifierInfo(),
3229 T, TInfo, BitWidth, D->isMutable(),
3230 D->getInClassInitStyle());
3231 ToField->setAccess(D->getAccess());
3232 ToField->setLexicalDeclContext(LexicalDC);
3233 if (Expr *FromInitializer = D->getInClassInitializer()) {
3234 Expr *ToInitializer = Importer.Import(FromInitializer);
3236 ToField->setInClassInitializer(ToInitializer);
3240 ToField->setImplicit(D->isImplicit());
3241 Importer.Imported(D, ToField);
3242 LexicalDC->addDeclInternal(ToField);
3246 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3247 // Import the major distinguishing characteristics of a variable.
3248 DeclContext *DC, *LexicalDC;
3249 DeclarationName Name;
3252 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3257 // Determine whether we've already imported this field.
3258 SmallVector<NamedDecl *, 2> FoundDecls;
3259 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3260 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3261 if (IndirectFieldDecl *FoundField
3262 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3263 // For anonymous indirect fields, match up by index.
3264 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3267 if (Importer.IsStructurallyEquivalent(D->getType(),
3268 FoundField->getType(),
3270 Importer.Imported(D, FoundField);
3274 // If there are more anonymous fields to check, continue.
3275 if (!Name && I < N-1)
3278 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3279 << Name << D->getType() << FoundField->getType();
3280 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3281 << FoundField->getType();
3287 QualType T = Importer.Import(D->getType());
3291 NamedDecl **NamedChain =
3292 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3295 for (auto *PI : D->chain()) {
3296 Decl *D = Importer.Import(PI);
3299 NamedChain[i++] = cast<NamedDecl>(D);
3302 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3303 Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3304 {NamedChain, D->getChainingSize()});
3306 for (const auto *Attr : D->attrs())
3307 ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3309 ToIndirectField->setAccess(D->getAccess());
3310 ToIndirectField->setLexicalDeclContext(LexicalDC);
3311 Importer.Imported(D, ToIndirectField);
3312 LexicalDC->addDeclInternal(ToIndirectField);
3313 return ToIndirectField;
3316 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3317 // Import the major distinguishing characteristics of an ivar.
3318 DeclContext *DC, *LexicalDC;
3319 DeclarationName Name;
3322 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3327 // Determine whether we've already imported this ivar
3328 SmallVector<NamedDecl *, 2> FoundDecls;
3329 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3330 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3331 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3332 if (Importer.IsStructurallyEquivalent(D->getType(),
3333 FoundIvar->getType())) {
3334 Importer.Imported(D, FoundIvar);
3338 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3339 << Name << D->getType() << FoundIvar->getType();
3340 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3341 << FoundIvar->getType();
3347 QualType T = Importer.Import(D->getType());
3351 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3352 Expr *BitWidth = Importer.Import(D->getBitWidth());
3353 if (!BitWidth && D->getBitWidth())
3356 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3357 cast<ObjCContainerDecl>(DC),
3358 Importer.Import(D->getInnerLocStart()),
3359 Loc, Name.getAsIdentifierInfo(),
3360 T, TInfo, D->getAccessControl(),
3361 BitWidth, D->getSynthesize());
3362 ToIvar->setLexicalDeclContext(LexicalDC);
3363 Importer.Imported(D, ToIvar);
3364 LexicalDC->addDeclInternal(ToIvar);
3369 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3370 // Import the major distinguishing characteristics of a variable.
3371 DeclContext *DC, *LexicalDC;
3372 DeclarationName Name;
3375 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3380 // Try to find a variable in our own ("to") context with the same name and
3381 // in the same context as the variable we're importing.
3382 if (D->isFileVarDecl()) {
3383 VarDecl *MergeWithVar = nullptr;
3384 SmallVector<NamedDecl *, 4> ConflictingDecls;
3385 unsigned IDNS = Decl::IDNS_Ordinary;
3386 SmallVector<NamedDecl *, 2> FoundDecls;
3387 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3388 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3389 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3392 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3393 // We have found a variable that we may need to merge with. Check it.
3394 if (FoundVar->hasExternalFormalLinkage() &&
3395 D->hasExternalFormalLinkage()) {
3396 if (Importer.IsStructurallyEquivalent(D->getType(),
3397 FoundVar->getType())) {
3398 MergeWithVar = FoundVar;
3402 const ArrayType *FoundArray
3403 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3404 const ArrayType *TArray
3405 = Importer.getToContext().getAsArrayType(D->getType());
3406 if (FoundArray && TArray) {
3407 if (isa<IncompleteArrayType>(FoundArray) &&
3408 isa<ConstantArrayType>(TArray)) {
3410 QualType T = Importer.Import(D->getType());
3414 FoundVar->setType(T);
3415 MergeWithVar = FoundVar;
3417 } else if (isa<IncompleteArrayType>(TArray) &&
3418 isa<ConstantArrayType>(FoundArray)) {
3419 MergeWithVar = FoundVar;
3424 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3425 << Name << D->getType() << FoundVar->getType();
3426 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3427 << FoundVar->getType();
3431 ConflictingDecls.push_back(FoundDecls[I]);
3435 // An equivalent variable with external linkage has been found. Link
3436 // the two declarations, then merge them.
3437 Importer.Imported(D, MergeWithVar);
3439 if (VarDecl *DDef = D->getDefinition()) {
3440 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3441 Importer.ToDiag(ExistingDef->getLocation(),
3442 diag::err_odr_variable_multiple_def)
3444 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3446 Expr *Init = Importer.Import(DDef->getInit());
3447 MergeWithVar->setInit(Init);
3448 if (DDef->isInitKnownICE()) {
3449 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3450 Eval->CheckedICE = true;
3451 Eval->IsICE = DDef->isInitICE();
3456 return MergeWithVar;
3459 if (!ConflictingDecls.empty()) {
3460 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3461 ConflictingDecls.data(),
3462 ConflictingDecls.size());
3469 QualType T = Importer.Import(D->getType());
3473 // Create the imported variable.
3474 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3475 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3476 Importer.Import(D->getInnerLocStart()),
3477 Loc, Name.getAsIdentifierInfo(),
3479 D->getStorageClass());
3480 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3481 ToVar->setAccess(D->getAccess());
3482 ToVar->setLexicalDeclContext(LexicalDC);
3483 Importer.Imported(D, ToVar);
3484 LexicalDC->addDeclInternal(ToVar);
3486 if (!D->isFileVarDecl() &&
3490 // Merge the initializer.
3491 if (ImportDefinition(D, ToVar))
3497 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3498 // Parameters are created in the translation unit's context, then moved
3499 // into the function declaration's context afterward.
3500 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3502 // Import the name of this declaration.
3503 DeclarationName Name = Importer.Import(D->getDeclName());
3504 if (D->getDeclName() && !Name)
3507 // Import the location of this declaration.
3508 SourceLocation Loc = Importer.Import(D->getLocation());
3510 // Import the parameter's type.
3511 QualType T = Importer.Import(D->getType());
3515 // Create the imported parameter.
3516 ImplicitParamDecl *ToParm
3517 = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3518 Loc, Name.getAsIdentifierInfo(),
3520 return Importer.Imported(D, ToParm);
3523 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3524 // Parameters are created in the translation unit's context, then moved
3525 // into the function declaration's context afterward.
3526 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3528 // Import the name of this declaration.
3529 DeclarationName Name = Importer.Import(D->getDeclName());
3530 if (D->getDeclName() && !Name)
3533 // Import the location of this declaration.
3534 SourceLocation Loc = Importer.Import(D->getLocation());
3536 // Import the parameter's type.
3537 QualType T = Importer.Import(D->getType());
3541 // Create the imported parameter.
3542 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3543 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3544 Importer.Import(D->getInnerLocStart()),
3545 Loc, Name.getAsIdentifierInfo(),
3546 T, TInfo, D->getStorageClass(),
3547 /*FIXME: Default argument*/nullptr);
3548 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3551 ToParm->setIsUsed();
3553 return Importer.Imported(D, ToParm);
3556 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3557 // Import the major distinguishing characteristics of a method.
3558 DeclContext *DC, *LexicalDC;
3559 DeclarationName Name;
3562 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3567 SmallVector<NamedDecl *, 2> FoundDecls;
3568 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3569 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3570 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3571 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3574 // Check return types.
3575 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3576 FoundMethod->getReturnType())) {
3577 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3578 << D->isInstanceMethod() << Name << D->getReturnType()
3579 << FoundMethod->getReturnType();
3580 Importer.ToDiag(FoundMethod->getLocation(),
3581 diag::note_odr_objc_method_here)
3582 << D->isInstanceMethod() << Name;
3586 // Check the number of parameters.
3587 if (D->param_size() != FoundMethod->param_size()) {
3588 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3589 << D->isInstanceMethod() << Name
3590 << D->param_size() << FoundMethod->param_size();
3591 Importer.ToDiag(FoundMethod->getLocation(),
3592 diag::note_odr_objc_method_here)
3593 << D->isInstanceMethod() << Name;
3597 // Check parameter types.
3598 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3599 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3600 P != PEnd; ++P, ++FoundP) {
3601 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3602 (*FoundP)->getType())) {
3603 Importer.FromDiag((*P)->getLocation(),
3604 diag::err_odr_objc_method_param_type_inconsistent)
3605 << D->isInstanceMethod() << Name
3606 << (*P)->getType() << (*FoundP)->getType();
3607 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3608 << (*FoundP)->getType();
3613 // Check variadic/non-variadic.
3614 // Check the number of parameters.
3615 if (D->isVariadic() != FoundMethod->isVariadic()) {
3616 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3617 << D->isInstanceMethod() << Name;
3618 Importer.ToDiag(FoundMethod->getLocation(),
3619 diag::note_odr_objc_method_here)
3620 << D->isInstanceMethod() << Name;
3624 // FIXME: Any other bits we need to merge?
3625 return Importer.Imported(D, FoundMethod);
3629 // Import the result type.
3630 QualType ResultTy = Importer.Import(D->getReturnType());
3631 if (ResultTy.isNull())
3634 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3636 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3637 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3638 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3639 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3640 D->getImplementationControl(), D->hasRelatedResultType());
3642 // FIXME: When we decide to merge method definitions, we'll need to
3643 // deal with implicit parameters.
3645 // Import the parameters
3646 SmallVector<ParmVarDecl *, 5> ToParams;
3647 for (auto *FromP : D->parameters()) {
3648 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3652 ToParams.push_back(ToP);
3655 // Set the parameters.
3656 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3657 ToParams[I]->setOwningFunction(ToMethod);
3658 ToMethod->addDeclInternal(ToParams[I]);
3660 SmallVector<SourceLocation, 12> SelLocs;
3661 D->getSelectorLocs(SelLocs);
3662 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3664 ToMethod->setLexicalDeclContext(LexicalDC);
3665 Importer.Imported(D, ToMethod);
3666 LexicalDC->addDeclInternal(ToMethod);
3670 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3671 // Import the major distinguishing characteristics of a category.
3672 DeclContext *DC, *LexicalDC;
3673 DeclarationName Name;
3676 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3681 TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3685 ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3686 Importer.getToContext(), DC,
3688 Importer.Import(D->getVarianceLoc()),
3690 Importer.Import(D->getLocation()),
3691 Name.getAsIdentifierInfo(),
3692 Importer.Import(D->getColonLoc()),
3694 Importer.Imported(D, Result);
3695 Result->setLexicalDeclContext(LexicalDC);
3699 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3700 // Import the major distinguishing characteristics of a category.
3701 DeclContext *DC, *LexicalDC;
3702 DeclarationName Name;
3705 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3710 ObjCInterfaceDecl *ToInterface
3711 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3715 // Determine if we've already encountered this category.
3716 ObjCCategoryDecl *MergeWithCategory
3717 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3718 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3720 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3721 Importer.Import(D->getAtStartLoc()),
3723 Importer.Import(D->getCategoryNameLoc()),
3724 Name.getAsIdentifierInfo(),
3726 /*TypeParamList=*/nullptr,
3727 Importer.Import(D->getIvarLBraceLoc()),
3728 Importer.Import(D->getIvarRBraceLoc()));
3729 ToCategory->setLexicalDeclContext(LexicalDC);
3730 LexicalDC->addDeclInternal(ToCategory);
3731 Importer.Imported(D, ToCategory);
3732 // Import the type parameter list after calling Imported, to avoid
3733 // loops when bringing in their DeclContext.
3734 ToCategory->setTypeParamList(ImportObjCTypeParamList(
3735 D->getTypeParamList()));
3738 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3739 SmallVector<SourceLocation, 4> ProtocolLocs;
3740 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3741 = D->protocol_loc_begin();
3742 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3743 FromProtoEnd = D->protocol_end();
3744 FromProto != FromProtoEnd;
3745 ++FromProto, ++FromProtoLoc) {
3746 ObjCProtocolDecl *ToProto
3747 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3750 Protocols.push_back(ToProto);
3751 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3754 // FIXME: If we're merging, make sure that the protocol list is the same.
3755 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3756 ProtocolLocs.data(), Importer.getToContext());
3759 Importer.Imported(D, ToCategory);
3762 // Import all of the members of this category.
3763 ImportDeclContext(D);
3765 // If we have an implementation, import it as well.
3766 if (D->getImplementation()) {
3767 ObjCCategoryImplDecl *Impl
3768 = cast_or_null<ObjCCategoryImplDecl>(
3769 Importer.Import(D->getImplementation()));
3773 ToCategory->setImplementation(Impl);
3779 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3780 ObjCProtocolDecl *To,
3781 ImportDefinitionKind Kind) {
3782 if (To->getDefinition()) {
3783 if (shouldForceImportDeclContext(Kind))
3784 ImportDeclContext(From);
3788 // Start the protocol definition
3789 To->startDefinition();
3792 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3793 SmallVector<SourceLocation, 4> ProtocolLocs;
3794 ObjCProtocolDecl::protocol_loc_iterator
3795 FromProtoLoc = From->protocol_loc_begin();
3796 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3797 FromProtoEnd = From->protocol_end();
3798 FromProto != FromProtoEnd;
3799 ++FromProto, ++FromProtoLoc) {
3800 ObjCProtocolDecl *ToProto
3801 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3804 Protocols.push_back(ToProto);
3805 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3808 // FIXME: If we're merging, make sure that the protocol list is the same.
3809 To->setProtocolList(Protocols.data(), Protocols.size(),
3810 ProtocolLocs.data(), Importer.getToContext());
3812 if (shouldForceImportDeclContext(Kind)) {
3813 // Import all of the members of this protocol.
3814 ImportDeclContext(From, /*ForceImport=*/true);
3819 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3820 // If this protocol has a definition in the translation unit we're coming
3821 // from, but this particular declaration is not that definition, import the
3822 // definition and map to that.
3823 ObjCProtocolDecl *Definition = D->getDefinition();
3824 if (Definition && Definition != D) {
3825 Decl *ImportedDef = Importer.Import(Definition);
3829 return Importer.Imported(D, ImportedDef);
3832 // Import the major distinguishing characteristics of a protocol.
3833 DeclContext *DC, *LexicalDC;
3834 DeclarationName Name;
3837 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3842 ObjCProtocolDecl *MergeWithProtocol = nullptr;
3843 SmallVector<NamedDecl *, 2> FoundDecls;
3844 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3845 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3846 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3849 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3853 ObjCProtocolDecl *ToProto = MergeWithProtocol;
3855 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3856 Name.getAsIdentifierInfo(), Loc,
3857 Importer.Import(D->getAtStartLoc()),
3858 /*PrevDecl=*/nullptr);
3859 ToProto->setLexicalDeclContext(LexicalDC);
3860 LexicalDC->addDeclInternal(ToProto);
3863 Importer.Imported(D, ToProto);
3865 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3871 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3872 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3873 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3875 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3876 SourceLocation LangLoc = Importer.Import(D->getLocation());
3878 bool HasBraces = D->hasBraces();
3880 LinkageSpecDecl *ToLinkageSpec =
3881 LinkageSpecDecl::Create(Importer.getToContext(),
3889 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3890 ToLinkageSpec->setRBraceLoc(RBraceLoc);
3893 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3894 LexicalDC->addDeclInternal(ToLinkageSpec);
3896 Importer.Imported(D, ToLinkageSpec);
3898 return ToLinkageSpec;
3901 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3902 ObjCInterfaceDecl *To,
3903 ImportDefinitionKind Kind) {
3904 if (To->getDefinition()) {
3905 // Check consistency of superclass.
3906 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3908 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3913 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3914 if ((bool)FromSuper != (bool)ToSuper ||
3915 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3916 Importer.ToDiag(To->getLocation(),
3917 diag::err_odr_objc_superclass_inconsistent)
3918 << To->getDeclName();
3920 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3921 << To->getSuperClass()->getDeclName();
3923 Importer.ToDiag(To->getLocation(),
3924 diag::note_odr_objc_missing_superclass);
3925 if (From->getSuperClass())
3926 Importer.FromDiag(From->getSuperClassLoc(),
3927 diag::note_odr_objc_superclass)
3928 << From->getSuperClass()->getDeclName();
3930 Importer.FromDiag(From->getLocation(),
3931 diag::note_odr_objc_missing_superclass);
3934 if (shouldForceImportDeclContext(Kind))
3935 ImportDeclContext(From);
3939 // Start the definition.
3940 To->startDefinition();
3942 // If this class has a superclass, import it.
3943 if (From->getSuperClass()) {
3944 TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3948 To->setSuperClass(SuperTInfo);
3952 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3953 SmallVector<SourceLocation, 4> ProtocolLocs;
3954 ObjCInterfaceDecl::protocol_loc_iterator
3955 FromProtoLoc = From->protocol_loc_begin();
3957 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3958 FromProtoEnd = From->protocol_end();
3959 FromProto != FromProtoEnd;
3960 ++FromProto, ++FromProtoLoc) {
3961 ObjCProtocolDecl *ToProto
3962 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3965 Protocols.push_back(ToProto);
3966 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3969 // FIXME: If we're merging, make sure that the protocol list is the same.
3970 To->setProtocolList(Protocols.data(), Protocols.size(),
3971 ProtocolLocs.data(), Importer.getToContext());
3973 // Import categories. When the categories themselves are imported, they'll
3974 // hook themselves into this interface.
3975 for (auto *Cat : From->known_categories())
3976 Importer.Import(Cat);
3978 // If we have an @implementation, import it as well.
3979 if (From->getImplementation()) {
3980 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3981 Importer.Import(From->getImplementation()));
3985 To->setImplementation(Impl);
3988 if (shouldForceImportDeclContext(Kind)) {
3989 // Import all of the members of this class.
3990 ImportDeclContext(From, /*ForceImport=*/true);
3996 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4000 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4001 for (auto fromTypeParam : *list) {
4002 auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
4003 Importer.Import(fromTypeParam));
4007 toTypeParams.push_back(toTypeParam);
4010 return ObjCTypeParamList::create(Importer.getToContext(),
4011 Importer.Import(list->getLAngleLoc()),
4013 Importer.Import(list->getRAngleLoc()));
4016 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4017 // If this class has a definition in the translation unit we're coming from,
4018 // but this particular declaration is not that definition, import the
4019 // definition and map to that.
4020 ObjCInterfaceDecl *Definition = D->getDefinition();
4021 if (Definition && Definition != D) {
4022 Decl *ImportedDef = Importer.Import(Definition);
4026 return Importer.Imported(D, ImportedDef);
4029 // Import the major distinguishing characteristics of an @interface.
4030 DeclContext *DC, *LexicalDC;
4031 DeclarationName Name;
4034 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4039 // Look for an existing interface with the same name.
4040 ObjCInterfaceDecl *MergeWithIface = nullptr;
4041 SmallVector<NamedDecl *, 2> FoundDecls;
4042 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4043 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4044 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4047 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
4051 // Create an interface declaration, if one does not already exist.
4052 ObjCInterfaceDecl *ToIface = MergeWithIface;
4054 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
4055 Importer.Import(D->getAtStartLoc()),
4056 Name.getAsIdentifierInfo(),
4057 /*TypeParamList=*/nullptr,
4058 /*PrevDecl=*/nullptr, Loc,
4059 D->isImplicitInterfaceDecl());
4060 ToIface->setLexicalDeclContext(LexicalDC);
4061 LexicalDC->addDeclInternal(ToIface);
4063 Importer.Imported(D, ToIface);
4064 // Import the type parameter list after calling Imported, to avoid
4065 // loops when bringing in their DeclContext.
4066 ToIface->setTypeParamList(ImportObjCTypeParamList(
4067 D->getTypeParamListAsWritten()));
4069 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
4075 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4076 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
4077 Importer.Import(D->getCategoryDecl()));
4081 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4083 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4087 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
4088 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
4089 Importer.Import(D->getIdentifier()),
4090 Category->getClassInterface(),
4091 Importer.Import(D->getLocation()),
4092 Importer.Import(D->getAtStartLoc()),
4095 DeclContext *LexicalDC = DC;
4096 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4097 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4101 ToImpl->setLexicalDeclContext(LexicalDC);
4104 LexicalDC->addDeclInternal(ToImpl);
4105 Category->setImplementation(ToImpl);
4108 Importer.Imported(D, ToImpl);
4109 ImportDeclContext(D);
4113 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4114 // Find the corresponding interface.
4115 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
4116 Importer.Import(D->getClassInterface()));
4120 // Import the superclass, if any.
4121 ObjCInterfaceDecl *Super = nullptr;
4122 if (D->getSuperClass()) {
4123 Super = cast_or_null<ObjCInterfaceDecl>(
4124 Importer.Import(D->getSuperClass()));
4129 ObjCImplementationDecl *Impl = Iface->getImplementation();
4131 // We haven't imported an implementation yet. Create a new @implementation
4133 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
4134 Importer.ImportContext(D->getDeclContext()),
4136 Importer.Import(D->getLocation()),
4137 Importer.Import(D->getAtStartLoc()),
4138 Importer.Import(D->getSuperClassLoc()),
4139 Importer.Import(D->getIvarLBraceLoc()),
4140 Importer.Import(D->getIvarRBraceLoc()));
4142 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4143 DeclContext *LexicalDC
4144 = Importer.ImportContext(D->getLexicalDeclContext());
4147 Impl->setLexicalDeclContext(LexicalDC);
4150 // Associate the implementation with the class it implements.
4151 Iface->setImplementation(Impl);
4152 Importer.Imported(D, Iface->getImplementation());
4154 Importer.Imported(D, Iface->getImplementation());
4156 // Verify that the existing @implementation has the same superclass.
4157 if ((Super && !Impl->getSuperClass()) ||
4158 (!Super && Impl->getSuperClass()) ||
4159 (Super && Impl->getSuperClass() &&
4160 !declaresSameEntity(Super->getCanonicalDecl(),
4161 Impl->getSuperClass()))) {
4162 Importer.ToDiag(Impl->getLocation(),
4163 diag::err_odr_objc_superclass_inconsistent)
4164 << Iface->getDeclName();
4165 // FIXME: It would be nice to have the location of the superclass
4167 if (Impl->getSuperClass())
4168 Importer.ToDiag(Impl->getLocation(),
4169 diag::note_odr_objc_superclass)
4170 << Impl->getSuperClass()->getDeclName();
4172 Importer.ToDiag(Impl->getLocation(),
4173 diag::note_odr_objc_missing_superclass);
4174 if (D->getSuperClass())
4175 Importer.FromDiag(D->getLocation(),
4176 diag::note_odr_objc_superclass)
4177 << D->getSuperClass()->getDeclName();
4179 Importer.FromDiag(D->getLocation(),
4180 diag::note_odr_objc_missing_superclass);
4185 // Import all of the members of this @implementation.
4186 ImportDeclContext(D);
4191 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4192 // Import the major distinguishing characteristics of an @property.
4193 DeclContext *DC, *LexicalDC;
4194 DeclarationName Name;
4197 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4202 // Check whether we have already imported this property.
4203 SmallVector<NamedDecl *, 2> FoundDecls;
4204 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4205 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4206 if (ObjCPropertyDecl *FoundProp
4207 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
4208 // Check property types.
4209 if (!Importer.IsStructurallyEquivalent(D->getType(),
4210 FoundProp->getType())) {
4211 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4212 << Name << D->getType() << FoundProp->getType();
4213 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4214 << FoundProp->getType();
4218 // FIXME: Check property attributes, getters, setters, etc.?
4220 // Consider these properties to be equivalent.
4221 Importer.Imported(D, FoundProp);
4227 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
4231 // Create the new property.
4232 ObjCPropertyDecl *ToProperty
4233 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4234 Name.getAsIdentifierInfo(),
4235 Importer.Import(D->getAtLoc()),
4236 Importer.Import(D->getLParenLoc()),
4237 Importer.Import(D->getType()),
4239 D->getPropertyImplementation());
4240 Importer.Imported(D, ToProperty);
4241 ToProperty->setLexicalDeclContext(LexicalDC);
4242 LexicalDC->addDeclInternal(ToProperty);
4244 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4245 ToProperty->setPropertyAttributesAsWritten(
4246 D->getPropertyAttributesAsWritten());
4247 ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4248 ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4249 ToProperty->setGetterMethodDecl(
4250 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4251 ToProperty->setSetterMethodDecl(
4252 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4253 ToProperty->setPropertyIvarDecl(
4254 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4258 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4259 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4260 Importer.Import(D->getPropertyDecl()));
4264 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4268 // Import the lexical declaration context.
4269 DeclContext *LexicalDC = DC;
4270 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4271 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4276 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4280 // Import the ivar (for an @synthesize).
4281 ObjCIvarDecl *Ivar = nullptr;
4282 if (D->getPropertyIvarDecl()) {
4283 Ivar = cast_or_null<ObjCIvarDecl>(
4284 Importer.Import(D->getPropertyIvarDecl()));
4289 ObjCPropertyImplDecl *ToImpl
4290 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4291 Property->getQueryKind());
4293 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4294 Importer.Import(D->getLocStart()),
4295 Importer.Import(D->getLocation()),
4297 D->getPropertyImplementation(),
4299 Importer.Import(D->getPropertyIvarDeclLoc()));
4300 ToImpl->setLexicalDeclContext(LexicalDC);
4301 Importer.Imported(D, ToImpl);
4302 LexicalDC->addDeclInternal(ToImpl);
4304 // Check that we have the same kind of property implementation (@synthesize
4306 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4307 Importer.ToDiag(ToImpl->getLocation(),
4308 diag::err_odr_objc_property_impl_kind_inconsistent)
4309 << Property->getDeclName()
4310 << (ToImpl->getPropertyImplementation()
4311 == ObjCPropertyImplDecl::Dynamic);
4312 Importer.FromDiag(D->getLocation(),
4313 diag::note_odr_objc_property_impl_kind)
4314 << D->getPropertyDecl()->getDeclName()
4315 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4319 // For @synthesize, check that we have the same
4320 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4321 Ivar != ToImpl->getPropertyIvarDecl()) {
4322 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4323 diag::err_odr_objc_synthesize_ivar_inconsistent)
4324 << Property->getDeclName()
4325 << ToImpl->getPropertyIvarDecl()->getDeclName()
4326 << Ivar->getDeclName();
4327 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4328 diag::note_odr_objc_synthesize_ivar_here)
4329 << D->getPropertyIvarDecl()->getDeclName();
4333 // Merge the existing implementation with the new implementation.
4334 Importer.Imported(D, ToImpl);
4340 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4341 // For template arguments, we adopt the translation unit as our declaration
4342 // context. This context will be fixed when the actual template declaration
4345 // FIXME: Import default argument.
4346 return TemplateTypeParmDecl::Create(Importer.getToContext(),
4347 Importer.getToContext().getTranslationUnitDecl(),
4348 Importer.Import(D->getLocStart()),
4349 Importer.Import(D->getLocation()),
4352 Importer.Import(D->getIdentifier()),
4353 D->wasDeclaredWithTypename(),
4354 D->isParameterPack());
4358 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4359 // Import the name of this declaration.
4360 DeclarationName Name = Importer.Import(D->getDeclName());
4361 if (D->getDeclName() && !Name)
4364 // Import the location of this declaration.
4365 SourceLocation Loc = Importer.Import(D->getLocation());
4367 // Import the type of this declaration.
4368 QualType T = Importer.Import(D->getType());
4372 // Import type-source information.
4373 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4374 if (D->getTypeSourceInfo() && !TInfo)
4377 // FIXME: Import default argument.
4379 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4380 Importer.getToContext().getTranslationUnitDecl(),
4381 Importer.Import(D->getInnerLocStart()),
4382 Loc, D->getDepth(), D->getPosition(),
4383 Name.getAsIdentifierInfo(),
4384 T, D->isParameterPack(), TInfo);
4388 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4389 // Import the name of this declaration.
4390 DeclarationName Name = Importer.Import(D->getDeclName());
4391 if (D->getDeclName() && !Name)
4394 // Import the location of this declaration.
4395 SourceLocation Loc = Importer.Import(D->getLocation());
4397 // Import template parameters.
4398 TemplateParameterList *TemplateParams
4399 = ImportTemplateParameterList(D->getTemplateParameters());
4400 if (!TemplateParams)
4403 // FIXME: Import default argument.
4405 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
4406 Importer.getToContext().getTranslationUnitDecl(),
4407 Loc, D->getDepth(), D->getPosition(),
4408 D->isParameterPack(),
4409 Name.getAsIdentifierInfo(),
4413 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4414 // If this record has a definition in the translation unit we're coming from,
4415 // but this particular declaration is not that definition, import the
4416 // definition and map to that.
4417 CXXRecordDecl *Definition
4418 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4419 if (Definition && Definition != D->getTemplatedDecl()) {
4421 = Importer.Import(Definition->getDescribedClassTemplate());
4425 return Importer.Imported(D, ImportedDef);
4428 // Import the major distinguishing characteristics of this class template.
4429 DeclContext *DC, *LexicalDC;
4430 DeclarationName Name;
4433 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4438 // We may already have a template of the same name; try to find and match it.
4439 if (!DC->isFunctionOrMethod()) {
4440 SmallVector<NamedDecl *, 4> ConflictingDecls;
4441 SmallVector<NamedDecl *, 2> FoundDecls;
4442 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4443 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4444 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4447 Decl *Found = FoundDecls[I];
4448 if (ClassTemplateDecl *FoundTemplate
4449 = dyn_cast<ClassTemplateDecl>(Found)) {
4450 if (IsStructuralMatch(D, FoundTemplate)) {
4451 // The class templates structurally match; call it the same template.
4452 // FIXME: We may be filling in a forward declaration here. Handle
4454 Importer.Imported(D->getTemplatedDecl(),
4455 FoundTemplate->getTemplatedDecl());
4456 return Importer.Imported(D, FoundTemplate);
4460 ConflictingDecls.push_back(FoundDecls[I]);
4463 if (!ConflictingDecls.empty()) {
4464 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4465 ConflictingDecls.data(),
4466 ConflictingDecls.size());
4473 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4475 // Create the declaration that is being templated.
4476 // Create the declaration that is being templated.
4477 CXXRecordDecl *D2Templated = cast_or_null<CXXRecordDecl>(
4478 Importer.Import(DTemplated));
4482 // Resolve possible cyclic import.
4483 if (Decl *AlreadyImported = Importer.GetAlreadyImportedOrNull(D))
4484 return AlreadyImported;
4486 // Create the class template declaration itself.
4487 TemplateParameterList *TemplateParams
4488 = ImportTemplateParameterList(D->getTemplateParameters());
4489 if (!TemplateParams)
4492 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4493 Loc, Name, TemplateParams,
4495 /*PrevDecl=*/nullptr);
4496 D2Templated->setDescribedClassTemplate(D2);
4498 D2->setAccess(D->getAccess());
4499 D2->setLexicalDeclContext(LexicalDC);
4500 LexicalDC->addDeclInternal(D2);
4502 // Note the relationship between the class templates.
4503 Importer.Imported(D, D2);
4504 Importer.Imported(DTemplated, D2Templated);
4506 if (DTemplated->isCompleteDefinition() &&
4507 !D2Templated->isCompleteDefinition()) {
4508 // FIXME: Import definition!
4514 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4515 ClassTemplateSpecializationDecl *D) {
4516 // If this record has a definition in the translation unit we're coming from,
4517 // but this particular declaration is not that definition, import the
4518 // definition and map to that.
4519 TagDecl *Definition = D->getDefinition();
4520 if (Definition && Definition != D) {
4521 Decl *ImportedDef = Importer.Import(Definition);
4525 return Importer.Imported(D, ImportedDef);
4528 ClassTemplateDecl *ClassTemplate
4529 = cast_or_null<ClassTemplateDecl>(Importer.Import(
4530 D->getSpecializedTemplate()));
4534 // Import the context of this declaration.
4535 DeclContext *DC = ClassTemplate->getDeclContext();
4539 DeclContext *LexicalDC = DC;
4540 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4541 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4546 // Import the location of this declaration.
4547 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4548 SourceLocation IdLoc = Importer.Import(D->getLocation());
4550 // Import template arguments.
4551 SmallVector<TemplateArgument, 2> TemplateArgs;
4552 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4553 D->getTemplateArgs().size(),
4557 // Try to find an existing specialization with these template arguments.
4558 void *InsertPos = nullptr;
4559 ClassTemplateSpecializationDecl *D2
4560 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4562 // We already have a class template specialization with these template
4565 // FIXME: Check for specialization vs. instantiation errors.
4567 if (RecordDecl *FoundDef = D2->getDefinition()) {
4568 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4569 // The record types structurally match, or the "from" translation
4570 // unit only had a forward declaration anyway; call it the same
4572 return Importer.Imported(D, FoundDef);
4576 // Create a new specialization.
4577 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4578 D->getTagKind(), DC,
4582 /*PrevDecl=*/nullptr);
4583 D2->setSpecializationKind(D->getSpecializationKind());
4585 // Add this specialization to the class template.
4586 ClassTemplate->AddSpecialization(D2, InsertPos);
4588 // Import the qualifier, if any.
4589 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4591 // Add the specialization to this context.
4592 D2->setLexicalDeclContext(LexicalDC);
4593 LexicalDC->addDeclInternal(D2);
4595 Importer.Imported(D, D2);
4597 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4603 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4604 // If this variable has a definition in the translation unit we're coming
4606 // but this particular declaration is not that definition, import the
4607 // definition and map to that.
4608 VarDecl *Definition =
4609 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4610 if (Definition && Definition != D->getTemplatedDecl()) {
4611 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4615 return Importer.Imported(D, ImportedDef);
4618 // Import the major distinguishing characteristics of this variable template.
4619 DeclContext *DC, *LexicalDC;
4620 DeclarationName Name;
4623 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4628 // We may already have a template of the same name; try to find and match it.
4629 assert(!DC->isFunctionOrMethod() &&
4630 "Variable templates cannot be declared at function scope");
4631 SmallVector<NamedDecl *, 4> ConflictingDecls;
4632 SmallVector<NamedDecl *, 2> FoundDecls;
4633 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4634 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4635 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4638 Decl *Found = FoundDecls[I];
4639 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4640 if (IsStructuralMatch(D, FoundTemplate)) {
4641 // The variable templates structurally match; call it the same template.
4642 Importer.Imported(D->getTemplatedDecl(),
4643 FoundTemplate->getTemplatedDecl());
4644 return Importer.Imported(D, FoundTemplate);
4648 ConflictingDecls.push_back(FoundDecls[I]);
4651 if (!ConflictingDecls.empty()) {
4652 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4653 ConflictingDecls.data(),
4654 ConflictingDecls.size());
4660 VarDecl *DTemplated = D->getTemplatedDecl();
4663 QualType T = Importer.Import(DTemplated->getType());
4667 // Create the declaration that is being templated.
4668 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4669 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4670 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4671 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4672 IdLoc, Name.getAsIdentifierInfo(), T,
4673 TInfo, DTemplated->getStorageClass());
4674 D2Templated->setAccess(DTemplated->getAccess());
4675 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4676 D2Templated->setLexicalDeclContext(LexicalDC);
4678 // Importer.Imported(DTemplated, D2Templated);
4679 // LexicalDC->addDeclInternal(D2Templated);
4681 // Merge the initializer.
4682 if (ImportDefinition(DTemplated, D2Templated))
4685 // Create the variable template declaration itself.
4686 TemplateParameterList *TemplateParams =
4687 ImportTemplateParameterList(D->getTemplateParameters());
4688 if (!TemplateParams)
4691 VarTemplateDecl *D2 = VarTemplateDecl::Create(
4692 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4693 D2Templated->setDescribedVarTemplate(D2);
4695 D2->setAccess(D->getAccess());
4696 D2->setLexicalDeclContext(LexicalDC);
4697 LexicalDC->addDeclInternal(D2);
4699 // Note the relationship between the variable templates.
4700 Importer.Imported(D, D2);
4701 Importer.Imported(DTemplated, D2Templated);
4703 if (DTemplated->isThisDeclarationADefinition() &&
4704 !D2Templated->isThisDeclarationADefinition()) {
4705 // FIXME: Import definition!
4711 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4712 VarTemplateSpecializationDecl *D) {
4713 // If this record has a definition in the translation unit we're coming from,
4714 // but this particular declaration is not that definition, import the
4715 // definition and map to that.
4716 VarDecl *Definition = D->getDefinition();
4717 if (Definition && Definition != D) {
4718 Decl *ImportedDef = Importer.Import(Definition);
4722 return Importer.Imported(D, ImportedDef);
4725 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4726 Importer.Import(D->getSpecializedTemplate()));
4730 // Import the context of this declaration.
4731 DeclContext *DC = VarTemplate->getDeclContext();
4735 DeclContext *LexicalDC = DC;
4736 if (D->getDeclContext() != D->getLexicalDeclContext()) {
4737 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4742 // Import the location of this declaration.
4743 SourceLocation StartLoc = Importer.Import(D->getLocStart());
4744 SourceLocation IdLoc = Importer.Import(D->getLocation());
4746 // Import template arguments.
4747 SmallVector<TemplateArgument, 2> TemplateArgs;
4748 if (ImportTemplateArguments(D->getTemplateArgs().data(),
4749 D->getTemplateArgs().size(), TemplateArgs))
4752 // Try to find an existing specialization with these template arguments.
4753 void *InsertPos = nullptr;
4754 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4755 TemplateArgs, InsertPos);
4757 // We already have a variable template specialization with these template
4760 // FIXME: Check for specialization vs. instantiation errors.
4762 if (VarDecl *FoundDef = D2->getDefinition()) {
4763 if (!D->isThisDeclarationADefinition() ||
4764 IsStructuralMatch(D, FoundDef)) {
4765 // The record types structurally match, or the "from" translation
4766 // unit only had a forward declaration anyway; call it the same
4768 return Importer.Imported(D, FoundDef);
4774 QualType T = Importer.Import(D->getType());
4777 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4779 // Create a new specialization.
4780 D2 = VarTemplateSpecializationDecl::Create(
4781 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4782 D->getStorageClass(), TemplateArgs);
4783 D2->setSpecializationKind(D->getSpecializationKind());
4784 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4786 // Add this specialization to the class template.
4787 VarTemplate->AddSpecialization(D2, InsertPos);
4789 // Import the qualifier, if any.
4790 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4792 // Add the specialization to this context.
4793 D2->setLexicalDeclContext(LexicalDC);
4794 LexicalDC->addDeclInternal(D2);
4796 Importer.Imported(D, D2);
4798 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4804 //----------------------------------------------------------------------------
4805 // Import Statements
4806 //----------------------------------------------------------------------------
4808 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4810 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4811 size_t NumDecls = DG.end() - DG.begin();
4812 SmallVector<Decl *, 1> ToDecls(NumDecls);
4813 auto &_Importer = this->Importer;
4814 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4815 [&_Importer](Decl *D) -> Decl * {
4816 return _Importer.Import(D);
4818 return DeclGroupRef::Create(Importer.getToContext(),
4823 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4824 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4825 << S->getStmtClassName();
4830 Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
4831 SmallVector<IdentifierInfo *, 4> Names;
4832 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4833 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
4836 Names.push_back(ToII);
4838 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4839 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
4842 Names.push_back(ToII);
4845 SmallVector<StringLiteral *, 4> Clobbers;
4846 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
4847 StringLiteral *Clobber = cast_or_null<StringLiteral>(
4848 Importer.Import(S->getClobberStringLiteral(I)));
4851 Clobbers.push_back(Clobber);
4854 SmallVector<StringLiteral *, 4> Constraints;
4855 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
4856 StringLiteral *Output = cast_or_null<StringLiteral>(
4857 Importer.Import(S->getOutputConstraintLiteral(I)));
4860 Constraints.push_back(Output);
4863 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
4864 StringLiteral *Input = cast_or_null<StringLiteral>(
4865 Importer.Import(S->getInputConstraintLiteral(I)));
4868 Constraints.push_back(Input);
4871 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
4872 if (ImportArrayChecked(S->begin_outputs(), S->end_outputs(), Exprs.begin()))
4875 if (ImportArrayChecked(S->begin_inputs(), S->end_inputs(),
4876 Exprs.begin() + S->getNumOutputs()))
4879 StringLiteral *AsmStr = cast_or_null<StringLiteral>(
4880 Importer.Import(S->getAsmString()));
4884 return new (Importer.getToContext()) GCCAsmStmt(
4885 Importer.getToContext(),
4886 Importer.Import(S->getAsmLoc()),
4895 S->getNumClobbers(),
4897 Importer.Import(S->getRParenLoc()));
4900 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4901 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4902 for (Decl *ToD : ToDG) {
4906 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4907 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4908 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4911 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4912 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4913 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4914 S->hasLeadingEmptyMacro());
4917 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4918 llvm::SmallVector<Stmt *, 8> ToStmts(S->size());
4920 if (ImportArrayChecked(S->body_begin(), S->body_end(), ToStmts.begin()))
4923 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4924 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4925 return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4927 ToLBraceLoc, ToRBraceLoc);
4930 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4931 Expr *ToLHS = Importer.Import(S->getLHS());
4934 Expr *ToRHS = Importer.Import(S->getRHS());
4935 if (!ToRHS && S->getRHS())
4937 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4938 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4939 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4940 return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4941 ToCaseLoc, ToEllipsisLoc,
4945 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4946 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4947 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4948 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4949 if (!ToSubStmt && S->getSubStmt())
4951 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4955 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4956 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4957 LabelDecl *ToLabelDecl =
4958 cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4959 if (!ToLabelDecl && S->getDecl())
4961 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4962 if (!ToSubStmt && S->getSubStmt())
4964 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4968 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4969 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4970 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4971 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4972 ASTContext &_ToContext = Importer.getToContext();
4973 std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4974 [&_ToContext](const Attr *A) -> const Attr * {
4975 return A->clone(_ToContext);
4977 for (const Attr *ToA : ToAttrs) {
4981 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4982 if (!ToSubStmt && S->getSubStmt())
4984 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4985 ToAttrs, ToSubStmt);
4988 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4989 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4990 Stmt *ToInit = Importer.Import(S->getInit());
4991 if (!ToInit && S->getInit())
4993 VarDecl *ToConditionVariable = nullptr;
4994 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4995 ToConditionVariable =
4996 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4997 if (!ToConditionVariable)
5000 Expr *ToCondition = Importer.Import(S->getCond());
5001 if (!ToCondition && S->getCond())
5003 Stmt *ToThenStmt = Importer.Import(S->getThen());
5004 if (!ToThenStmt && S->getThen())
5006 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
5007 Stmt *ToElseStmt = Importer.Import(S->getElse());
5008 if (!ToElseStmt && S->getElse())
5010 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
5011 ToIfLoc, S->isConstexpr(),
5013 ToConditionVariable,
5014 ToCondition, ToThenStmt,
5015 ToElseLoc, ToElseStmt);
5018 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
5019 Stmt *ToInit = Importer.Import(S->getInit());
5020 if (!ToInit && S->getInit())
5022 VarDecl *ToConditionVariable = nullptr;
5023 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5024 ToConditionVariable =
5025 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5026 if (!ToConditionVariable)
5029 Expr *ToCondition = Importer.Import(S->getCond());
5030 if (!ToCondition && S->getCond())
5032 SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
5033 Importer.getToContext(), ToInit,
5034 ToConditionVariable, ToCondition);
5035 Stmt *ToBody = Importer.Import(S->getBody());
5036 if (!ToBody && S->getBody())
5038 ToStmt->setBody(ToBody);
5039 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
5040 // Now we have to re-chain the cases.
5041 SwitchCase *LastChainedSwitchCase = nullptr;
5042 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5043 SC = SC->getNextSwitchCase()) {
5044 SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
5047 if (LastChainedSwitchCase)
5048 LastChainedSwitchCase->setNextSwitchCase(ToSC);
5050 ToStmt->setSwitchCaseList(ToSC);
5051 LastChainedSwitchCase = ToSC;
5056 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5057 VarDecl *ToConditionVariable = nullptr;
5058 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5059 ToConditionVariable =
5060 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5061 if (!ToConditionVariable)
5064 Expr *ToCondition = Importer.Import(S->getCond());
5065 if (!ToCondition && S->getCond())
5067 Stmt *ToBody = Importer.Import(S->getBody());
5068 if (!ToBody && S->getBody())
5070 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5071 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
5072 ToConditionVariable,
5073 ToCondition, ToBody,
5077 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5078 Stmt *ToBody = Importer.Import(S->getBody());
5079 if (!ToBody && S->getBody())
5081 Expr *ToCondition = Importer.Import(S->getCond());
5082 if (!ToCondition && S->getCond())
5084 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
5085 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
5086 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5087 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
5088 ToDoLoc, ToWhileLoc,
5092 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
5093 Stmt *ToInit = Importer.Import(S->getInit());
5094 if (!ToInit && S->getInit())
5096 Expr *ToCondition = Importer.Import(S->getCond());
5097 if (!ToCondition && S->getCond())
5099 VarDecl *ToConditionVariable = nullptr;
5100 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
5101 ToConditionVariable =
5102 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
5103 if (!ToConditionVariable)
5106 Expr *ToInc = Importer.Import(S->getInc());
5107 if (!ToInc && S->getInc())
5109 Stmt *ToBody = Importer.Import(S->getBody());
5110 if (!ToBody && S->getBody())
5112 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5113 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
5114 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5115 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
5116 ToInit, ToCondition,
5117 ToConditionVariable,
5119 ToForLoc, ToLParenLoc,
5123 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5124 LabelDecl *ToLabel = nullptr;
5125 if (LabelDecl *FromLabel = S->getLabel()) {
5126 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
5130 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5131 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
5132 return new (Importer.getToContext()) GotoStmt(ToLabel,
5133 ToGotoLoc, ToLabelLoc);
5136 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5137 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
5138 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
5139 Expr *ToTarget = Importer.Import(S->getTarget());
5140 if (!ToTarget && S->getTarget())
5142 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
5146 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5147 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
5148 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
5151 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5152 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
5153 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
5156 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5157 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
5158 Expr *ToRetExpr = Importer.Import(S->getRetValue());
5159 if (!ToRetExpr && S->getRetValue())
5161 VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
5162 VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
5163 if (!ToNRVOCandidate && NRVOCandidate)
5165 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
5169 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5170 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
5171 VarDecl *ToExceptionDecl = nullptr;
5172 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
5174 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5175 if (!ToExceptionDecl)
5178 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
5179 if (!ToHandlerBlock && S->getHandlerBlock())
5181 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
5186 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5187 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
5188 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
5189 if (!ToTryBlock && S->getTryBlock())
5191 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5192 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5193 CXXCatchStmt *FromHandler = S->getHandler(HI);
5194 if (Stmt *ToHandler = Importer.Import(FromHandler))
5195 ToHandlers[HI] = ToHandler;
5199 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
5203 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5205 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
5206 if (!ToRange && S->getRangeStmt())
5209 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
5210 if (!ToBegin && S->getBeginStmt())
5213 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
5214 if (!ToEnd && S->getEndStmt())
5216 Expr *ToCond = Importer.Import(S->getCond());
5217 if (!ToCond && S->getCond())
5219 Expr *ToInc = Importer.Import(S->getInc());
5220 if (!ToInc && S->getInc())
5222 DeclStmt *ToLoopVar =
5223 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
5224 if (!ToLoopVar && S->getLoopVarStmt())
5226 Stmt *ToBody = Importer.Import(S->getBody());
5227 if (!ToBody && S->getBody())
5229 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5230 SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
5231 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
5232 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5233 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
5236 ToForLoc, ToCoawaitLoc,
5237 ToColonLoc, ToRParenLoc);
5240 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
5241 Stmt *ToElem = Importer.Import(S->getElement());
5242 if (!ToElem && S->getElement())
5244 Expr *ToCollect = Importer.Import(S->getCollection());
5245 if (!ToCollect && S->getCollection())
5247 Stmt *ToBody = Importer.Import(S->getBody());
5248 if (!ToBody && S->getBody())
5250 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
5251 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5252 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
5258 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5259 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
5260 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
5261 VarDecl *ToExceptionDecl = nullptr;
5262 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
5264 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
5265 if (!ToExceptionDecl)
5268 Stmt *ToBody = Importer.Import(S->getCatchBody());
5269 if (!ToBody && S->getCatchBody())
5271 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
5277 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
5278 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
5279 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
5280 if (!ToAtFinallyStmt && S->getFinallyBody())
5282 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
5286 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
5287 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
5288 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
5289 if (!ToAtTryStmt && S->getTryBody())
5291 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
5292 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
5293 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
5294 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
5295 ToCatchStmts[CI] = ToCatchStmt;
5299 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
5300 if (!ToAtFinallyStmt && S->getFinallyStmt())
5302 return ObjCAtTryStmt::Create(Importer.getToContext(),
5303 ToAtTryLoc, ToAtTryStmt,
5304 ToCatchStmts.begin(), ToCatchStmts.size(),
5308 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
5309 (ObjCAtSynchronizedStmt *S) {
5310 SourceLocation ToAtSynchronizedLoc =
5311 Importer.Import(S->getAtSynchronizedLoc());
5312 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5313 if (!ToSynchExpr && S->getSynchExpr())
5315 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5316 if (!ToSynchBody && S->getSynchBody())
5318 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5319 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5322 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5323 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5324 Expr *ToThrow = Importer.Import(S->getThrowExpr());
5325 if (!ToThrow && S->getThrowExpr())
5327 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5330 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5331 (ObjCAutoreleasePoolStmt *S) {
5332 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5333 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5334 if (!ToSubStmt && S->getSubStmt())
5336 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5340 //----------------------------------------------------------------------------
5341 // Import Expressions
5342 //----------------------------------------------------------------------------
5343 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5344 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5345 << E->getStmtClassName();
5349 Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
5350 QualType T = Importer.Import(E->getType());
5354 Expr *SubExpr = Importer.Import(E->getSubExpr());
5355 if (!SubExpr && E->getSubExpr())
5358 TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
5362 return new (Importer.getToContext()) VAArgExpr(
5363 Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
5364 Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
5368 Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
5369 QualType T = Importer.Import(E->getType());
5373 return new (Importer.getToContext()) GNUNullExpr(
5374 T, Importer.Import(E->getExprLoc()));
5377 Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
5378 QualType T = Importer.Import(E->getType());
5382 StringLiteral *SL = cast_or_null<StringLiteral>(
5383 Importer.Import(E->getFunctionName()));
5384 if (!SL && E->getFunctionName())
5387 return new (Importer.getToContext()) PredefinedExpr(
5388 Importer.Import(E->getExprLoc()), T, E->getIdentType(), SL);
5391 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5392 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5396 NamedDecl *FoundD = nullptr;
5397 if (E->getDecl() != E->getFoundDecl()) {
5398 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5403 QualType T = Importer.Import(E->getType());
5407 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5408 Importer.Import(E->getQualifierLoc()),
5409 Importer.Import(E->getTemplateKeywordLoc()),
5411 E->refersToEnclosingVariableOrCapture(),
5412 Importer.Import(E->getLocation()),
5413 T, E->getValueKind(),
5415 /*FIXME:TemplateArgs=*/nullptr);
5416 if (E->hadMultipleCandidates())
5417 DRE->setHadMultipleCandidates(true);
5421 Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
5422 QualType T = Importer.Import(E->getType());
5426 return new (Importer.getToContext()) ImplicitValueInitExpr(T);
5429 ASTNodeImporter::Designator
5430 ASTNodeImporter::ImportDesignator(const Designator &D) {
5431 if (D.isFieldDesignator()) {
5432 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
5433 // Caller checks for import error
5434 return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
5435 Importer.Import(D.getFieldLoc()));
5437 if (D.isArrayDesignator())
5438 return Designator(D.getFirstExprIndex(),
5439 Importer.Import(D.getLBracketLoc()),
5440 Importer.Import(D.getRBracketLoc()));
5442 assert(D.isArrayRangeDesignator());
5443 return Designator(D.getFirstExprIndex(),
5444 Importer.Import(D.getLBracketLoc()),
5445 Importer.Import(D.getEllipsisLoc()),
5446 Importer.Import(D.getRBracketLoc()));
5450 Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
5451 Expr *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
5455 SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
5456 // List elements from the second, the first is Init itself
5457 for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
5458 if (Expr *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
5459 IndexExprs[I - 1] = Arg;
5464 SmallVector<Designator, 4> Designators(DIE->size());
5465 llvm::transform(DIE->designators(), Designators.begin(),
5466 [this](const Designator &D) -> Designator {
5467 return ImportDesignator(D);
5470 for (const Designator &D : DIE->designators())
5471 if (D.isFieldDesignator() && !D.getFieldName())
5474 return DesignatedInitExpr::Create(
5475 Importer.getToContext(), Designators,
5476 IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
5477 DIE->usesGNUSyntax(), Init);
5480 Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
5481 QualType T = Importer.Import(E->getType());
5485 return new (Importer.getToContext())
5486 CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
5489 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5490 QualType T = Importer.Import(E->getType());
5494 return IntegerLiteral::Create(Importer.getToContext(),
5496 Importer.Import(E->getLocation()));
5499 Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
5500 QualType T = Importer.Import(E->getType());
5504 return FloatingLiteral::Create(Importer.getToContext(),
5505 E->getValue(), E->isExact(), T,
5506 Importer.Import(E->getLocation()));
5509 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5510 QualType T = Importer.Import(E->getType());
5514 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5516 Importer.Import(E->getLocation()));
5519 Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
5520 QualType T = Importer.Import(E->getType());
5524 SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
5525 ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
5527 return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
5528 E->getKind(), E->isPascal(), T,
5529 Locations.data(), Locations.size());
5532 Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
5533 QualType T = Importer.Import(E->getType());
5537 TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
5541 Expr *Init = Importer.Import(E->getInitializer());
5545 return new (Importer.getToContext()) CompoundLiteralExpr(
5546 Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
5547 Init, E->isFileScope());
5550 Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
5551 QualType T = Importer.Import(E->getType());
5555 SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
5556 if (ImportArrayChecked(
5557 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
5561 return new (Importer.getToContext()) AtomicExpr(
5562 Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
5563 Importer.Import(E->getRParenLoc()));
5566 Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
5567 QualType T = Importer.Import(E->getType());
5571 LabelDecl *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
5575 return new (Importer.getToContext()) AddrLabelExpr(
5576 Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
5580 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5581 Expr *SubExpr = Importer.Import(E->getSubExpr());
5585 return new (Importer.getToContext())
5586 ParenExpr(Importer.Import(E->getLParen()),
5587 Importer.Import(E->getRParen()),
5591 Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
5592 SmallVector<Expr *, 4> Exprs(E->getNumExprs());
5593 if (ImportArrayChecked(
5594 E->getExprs(), E->getExprs() + E->getNumExprs(), Exprs.begin()))
5597 return new (Importer.getToContext()) ParenListExpr(
5598 Importer.getToContext(), Importer.Import(E->getLParenLoc()),
5599 Exprs, Importer.Import(E->getLParenLoc()));
5602 Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
5603 QualType T = Importer.Import(E->getType());
5607 CompoundStmt *ToSubStmt = cast_or_null<CompoundStmt>(
5608 Importer.Import(E->getSubStmt()));
5609 if (!ToSubStmt && E->getSubStmt())
5612 return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
5613 Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
5616 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5617 QualType T = Importer.Import(E->getType());
5621 Expr *SubExpr = Importer.Import(E->getSubExpr());
5625 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5626 T, E->getValueKind(),
5628 Importer.Import(E->getOperatorLoc()));
5631 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5632 UnaryExprOrTypeTraitExpr *E) {
5633 QualType ResultType = Importer.Import(E->getType());
5635 if (E->isArgumentType()) {
5636 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5640 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5642 Importer.Import(E->getOperatorLoc()),
5643 Importer.Import(E->getRParenLoc()));
5646 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5650 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5651 SubExpr, ResultType,
5652 Importer.Import(E->getOperatorLoc()),
5653 Importer.Import(E->getRParenLoc()));
5656 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5657 QualType T = Importer.Import(E->getType());
5661 Expr *LHS = Importer.Import(E->getLHS());
5665 Expr *RHS = Importer.Import(E->getRHS());
5669 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5670 T, E->getValueKind(),
5672 Importer.Import(E->getOperatorLoc()),
5673 E->isFPContractable());
5676 Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
5677 QualType T = Importer.Import(E->getType());
5681 Expr *ToLHS = Importer.Import(E->getLHS());
5685 Expr *ToRHS = Importer.Import(E->getRHS());
5689 Expr *ToCond = Importer.Import(E->getCond());
5693 return new (Importer.getToContext()) ConditionalOperator(
5694 ToCond, Importer.Import(E->getQuestionLoc()),
5695 ToLHS, Importer.Import(E->getColonLoc()),
5696 ToRHS, T, E->getValueKind(), E->getObjectKind());
5699 Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
5700 BinaryConditionalOperator *E) {
5701 QualType T = Importer.Import(E->getType());
5705 Expr *Common = Importer.Import(E->getCommon());
5709 Expr *Cond = Importer.Import(E->getCond());
5713 OpaqueValueExpr *OpaqueValue = cast_or_null<OpaqueValueExpr>(
5714 Importer.Import(E->getOpaqueValue()));
5718 Expr *TrueExpr = Importer.Import(E->getTrueExpr());
5722 Expr *FalseExpr = Importer.Import(E->getFalseExpr());
5726 return new (Importer.getToContext()) BinaryConditionalOperator(
5727 Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
5728 Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
5729 T, E->getValueKind(), E->getObjectKind());
5732 Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
5733 QualType T = Importer.Import(E->getType());
5737 Expr *SourceExpr = Importer.Import(E->getSourceExpr());
5738 if (!SourceExpr && E->getSourceExpr())
5741 return new (Importer.getToContext()) OpaqueValueExpr(
5742 Importer.Import(E->getExprLoc()), T, E->getValueKind(),
5743 E->getObjectKind(), SourceExpr);
5746 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5747 QualType T = Importer.Import(E->getType());
5751 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5752 if (CompLHSType.isNull())
5755 QualType CompResultType = Importer.Import(E->getComputationResultType());
5756 if (CompResultType.isNull())
5759 Expr *LHS = Importer.Import(E->getLHS());
5763 Expr *RHS = Importer.Import(E->getRHS());
5767 return new (Importer.getToContext())
5768 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5769 T, E->getValueKind(),
5771 CompLHSType, CompResultType,
5772 Importer.Import(E->getOperatorLoc()),
5773 E->isFPContractable());
5776 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5777 if (E->path_empty()) return false;
5779 // TODO: import cast paths
5783 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5784 QualType T = Importer.Import(E->getType());
5788 Expr *SubExpr = Importer.Import(E->getSubExpr());
5792 CXXCastPath BasePath;
5793 if (ImportCastPath(E, BasePath))
5796 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5797 SubExpr, &BasePath, E->getValueKind());
5800 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5801 QualType T = Importer.Import(E->getType());
5805 Expr *SubExpr = Importer.Import(E->getSubExpr());
5809 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5810 if (!TInfo && E->getTypeInfoAsWritten())
5813 CXXCastPath BasePath;
5814 if (ImportCastPath(E, BasePath))
5817 return CStyleCastExpr::Create(Importer.getToContext(), T,
5818 E->getValueKind(), E->getCastKind(),
5819 SubExpr, &BasePath, TInfo,
5820 Importer.Import(E->getLParenLoc()),
5821 Importer.Import(E->getRParenLoc()));
5824 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5825 QualType T = Importer.Import(E->getType());
5829 CXXConstructorDecl *ToCCD =
5830 dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5834 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
5835 if (ImportArrayChecked(E->getArgs(), E->getArgs() + E->getNumArgs(),
5839 return CXXConstructExpr::Create(Importer.getToContext(), T,
5840 Importer.Import(E->getLocation()),
5841 ToCCD, E->isElidable(),
5842 ToArgs, E->hadMultipleCandidates(),
5843 E->isListInitialization(),
5844 E->isStdInitListInitialization(),
5845 E->requiresZeroInitialization(),
5846 E->getConstructionKind(),
5847 Importer.Import(E->getParenOrBraceRange()));
5850 Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
5851 QualType T = Importer.Import(E->getType());
5855 Expr *ToFn = Importer.Import(E->getCallee());
5859 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
5861 if (ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
5864 return new (Importer.getToContext()) CXXMemberCallExpr(
5865 Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
5866 Importer.Import(E->getRParenLoc()));
5869 Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
5870 QualType T = Importer.Import(E->getType());
5874 return new (Importer.getToContext())
5875 CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
5878 Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
5879 QualType T = Importer.Import(E->getType());
5883 return new (Importer.getToContext())
5884 CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
5888 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5889 QualType T = Importer.Import(E->getType());
5893 Expr *ToBase = Importer.Import(E->getBase());
5894 if (!ToBase && E->getBase())
5897 ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5898 if (!ToMember && E->getMemberDecl())
5901 DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5902 dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5903 E->getFoundDecl().getAccess());
5905 DeclarationNameInfo ToMemberNameInfo(
5906 Importer.Import(E->getMemberNameInfo().getName()),
5907 Importer.Import(E->getMemberNameInfo().getLoc()));
5909 if (E->hasExplicitTemplateArgs()) {
5910 return nullptr; // FIXME: handle template arguments
5913 return MemberExpr::Create(Importer.getToContext(), ToBase,
5915 Importer.Import(E->getOperatorLoc()),
5916 Importer.Import(E->getQualifierLoc()),
5917 Importer.Import(E->getTemplateKeywordLoc()),
5918 ToMember, ToFoundDecl, ToMemberNameInfo,
5919 nullptr, T, E->getValueKind(),
5920 E->getObjectKind());
5923 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5924 QualType T = Importer.Import(E->getType());
5928 Expr *ToCallee = Importer.Import(E->getCallee());
5929 if (!ToCallee && E->getCallee())
5932 unsigned NumArgs = E->getNumArgs();
5934 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5936 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5937 Expr *FromArg = E->getArg(ai);
5938 Expr *ToArg = Importer.Import(FromArg);
5944 Expr **ToArgs_Copied = new (Importer.getToContext())
5947 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5948 ToArgs_Copied[ai] = ToArgs[ai];
5950 return new (Importer.getToContext())
5951 CallExpr(Importer.getToContext(), ToCallee,
5952 llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5953 Importer.Import(E->getRParenLoc()));
5956 Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
5957 QualType T = Importer.Import(ILE->getType());
5961 llvm::SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
5962 if (ImportArrayChecked(
5963 ILE->getInits(), ILE->getInits() + ILE->getNumInits(), Exprs.begin()))
5966 ASTContext &ToCtx = Importer.getToContext();
5967 InitListExpr *To = new (ToCtx) InitListExpr(
5968 ToCtx, Importer.Import(ILE->getLBraceLoc()),
5969 Exprs, Importer.Import(ILE->getLBraceLoc()));
5972 if (ILE->hasArrayFiller()) {
5973 Expr *Filler = Importer.Import(ILE->getArrayFiller());
5976 To->setArrayFiller(Filler);
5979 if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
5980 FieldDecl *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
5983 To->setInitializedFieldInUnion(ToFD);
5986 if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
5987 InitListExpr *ToSyntForm = cast_or_null<InitListExpr>(
5988 Importer.Import(SyntForm));
5991 To->setSyntacticForm(ToSyntForm);
5994 To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
5995 To->setValueDependent(ILE->isValueDependent());
5996 To->setInstantiationDependent(ILE->isInstantiationDependent());
6001 Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
6002 FieldDecl *ToField = llvm::dyn_cast_or_null<FieldDecl>(
6003 Importer.Import(DIE->getField()));
6004 if (!ToField && DIE->getField())
6007 return CXXDefaultInitExpr::Create(
6008 Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
6011 Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
6012 QualType ToType = Importer.Import(E->getType());
6013 if (ToType.isNull() && !E->getType().isNull())
6015 ExprValueKind VK = E->getValueKind();
6016 CastKind CK = E->getCastKind();
6017 Expr *ToOp = Importer.Import(E->getSubExpr());
6018 if (!ToOp && E->getSubExpr())
6020 CXXCastPath BasePath;
6021 if (ImportCastPath(E, BasePath))
6023 TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
6024 SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
6025 SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
6026 SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
6028 if (isa<CXXStaticCastExpr>(E)) {
6029 return CXXStaticCastExpr::Create(
6030 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6031 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6032 } else if (isa<CXXDynamicCastExpr>(E)) {
6033 return CXXDynamicCastExpr::Create(
6034 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6035 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6036 } else if (isa<CXXReinterpretCastExpr>(E)) {
6037 return CXXReinterpretCastExpr::Create(
6038 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
6039 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
6045 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
6046 ASTContext &FromContext, FileManager &FromFileManager,
6048 : ToContext(ToContext), FromContext(FromContext),
6049 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
6050 Minimal(MinimalImport), LastDiagFromFrom(false)
6052 ImportedDecls[FromContext.getTranslationUnitDecl()]
6053 = ToContext.getTranslationUnitDecl();
6056 ASTImporter::~ASTImporter() { }
6058 QualType ASTImporter::Import(QualType FromT) {
6062 const Type *fromTy = FromT.getTypePtr();
6064 // Check whether we've already imported this type.
6065 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6066 = ImportedTypes.find(fromTy);
6067 if (Pos != ImportedTypes.end())
6068 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
6071 ASTNodeImporter Importer(*this);
6072 QualType ToT = Importer.Visit(fromTy);
6076 // Record the imported type.
6077 ImportedTypes[fromTy] = ToT.getTypePtr();
6079 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
6082 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
6086 // FIXME: For now we just create a "trivial" type source info based
6087 // on the type and a single location. Implement a real version of this.
6088 QualType T = Import(FromTSI->getType());
6092 return ToContext.getTrivialTypeSourceInfo(T,
6093 Import(FromTSI->getTypeLoc().getLocStart()));
6096 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
6097 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6098 if (Pos != ImportedDecls.end()) {
6099 Decl *ToD = Pos->second;
6100 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
6107 Decl *ASTImporter::Import(Decl *FromD) {
6111 ASTNodeImporter Importer(*this);
6113 // Check whether we've already imported this declaration.
6114 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
6115 if (Pos != ImportedDecls.end()) {
6116 Decl *ToD = Pos->second;
6117 Importer.ImportDefinitionIfNeeded(FromD, ToD);
6122 Decl *ToD = Importer.Visit(FromD);
6126 // Record the imported declaration.
6127 ImportedDecls[FromD] = ToD;
6129 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
6130 // Keep track of anonymous tags that have an associated typedef.
6131 if (FromTag->getTypedefNameForAnonDecl())
6132 AnonTagsWithPendingTypedefs.push_back(FromTag);
6133 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
6134 // When we've finished transforming a typedef, see whether it was the
6135 // typedef for an anonymous tag.
6136 for (SmallVectorImpl<TagDecl *>::iterator
6137 FromTag = AnonTagsWithPendingTypedefs.begin(),
6138 FromTagEnd = AnonTagsWithPendingTypedefs.end();
6139 FromTag != FromTagEnd; ++FromTag) {
6140 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
6141 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
6142 // We found the typedef for an anonymous tag; link them.
6143 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
6144 AnonTagsWithPendingTypedefs.erase(FromTag);
6154 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
6158 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
6162 // When we're using a record/enum/Objective-C class/protocol as a context, we
6163 // need it to have a definition.
6164 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
6165 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
6166 if (ToRecord->isCompleteDefinition()) {
6168 } else if (FromRecord->isCompleteDefinition()) {
6169 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
6170 ASTNodeImporter::IDK_Basic);
6172 CompleteDecl(ToRecord);
6174 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
6175 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
6176 if (ToEnum->isCompleteDefinition()) {
6178 } else if (FromEnum->isCompleteDefinition()) {
6179 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
6180 ASTNodeImporter::IDK_Basic);
6182 CompleteDecl(ToEnum);
6184 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
6185 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
6186 if (ToClass->getDefinition()) {
6188 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
6189 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
6190 ASTNodeImporter::IDK_Basic);
6192 CompleteDecl(ToClass);
6194 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
6195 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
6196 if (ToProto->getDefinition()) {
6198 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
6199 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
6200 ASTNodeImporter::IDK_Basic);
6202 CompleteDecl(ToProto);
6209 Expr *ASTImporter::Import(Expr *FromE) {
6213 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
6216 Stmt *ASTImporter::Import(Stmt *FromS) {
6220 // Check whether we've already imported this declaration.
6221 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
6222 if (Pos != ImportedStmts.end())
6226 ASTNodeImporter Importer(*this);
6227 Stmt *ToS = Importer.Visit(FromS);
6231 // Record the imported declaration.
6232 ImportedStmts[FromS] = ToS;
6236 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
6240 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
6242 switch (FromNNS->getKind()) {
6243 case NestedNameSpecifier::Identifier:
6244 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
6245 return NestedNameSpecifier::Create(ToContext, prefix, II);
6249 case NestedNameSpecifier::Namespace:
6250 if (NamespaceDecl *NS =
6251 cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
6252 return NestedNameSpecifier::Create(ToContext, prefix, NS);
6256 case NestedNameSpecifier::NamespaceAlias:
6257 if (NamespaceAliasDecl *NSAD =
6258 cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
6259 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
6263 case NestedNameSpecifier::Global:
6264 return NestedNameSpecifier::GlobalSpecifier(ToContext);
6266 case NestedNameSpecifier::Super:
6267 if (CXXRecordDecl *RD =
6268 cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
6269 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
6273 case NestedNameSpecifier::TypeSpec:
6274 case NestedNameSpecifier::TypeSpecWithTemplate: {
6275 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
6277 bool bTemplate = FromNNS->getKind() ==
6278 NestedNameSpecifier::TypeSpecWithTemplate;
6279 return NestedNameSpecifier::Create(ToContext, prefix,
6280 bTemplate, T.getTypePtr());
6286 llvm_unreachable("Invalid nested name specifier kind");
6289 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
6290 // FIXME: Implement!
6291 return NestedNameSpecifierLoc();
6294 TemplateName ASTImporter::Import(TemplateName From) {
6295 switch (From.getKind()) {
6296 case TemplateName::Template:
6297 if (TemplateDecl *ToTemplate
6298 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6299 return TemplateName(ToTemplate);
6301 return TemplateName();
6303 case TemplateName::OverloadedTemplate: {
6304 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
6305 UnresolvedSet<2> ToTemplates;
6306 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
6307 E = FromStorage->end();
6309 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
6310 ToTemplates.addDecl(To);
6312 return TemplateName();
6314 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
6318 case TemplateName::QualifiedTemplate: {
6319 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
6320 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
6322 return TemplateName();
6324 if (TemplateDecl *ToTemplate
6325 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
6326 return ToContext.getQualifiedTemplateName(Qualifier,
6327 QTN->hasTemplateKeyword(),
6330 return TemplateName();
6333 case TemplateName::DependentTemplate: {
6334 DependentTemplateName *DTN = From.getAsDependentTemplateName();
6335 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
6337 return TemplateName();
6339 if (DTN->isIdentifier()) {
6340 return ToContext.getDependentTemplateName(Qualifier,
6341 Import(DTN->getIdentifier()));
6344 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
6347 case TemplateName::SubstTemplateTemplateParm: {
6348 SubstTemplateTemplateParmStorage *subst
6349 = From.getAsSubstTemplateTemplateParm();
6350 TemplateTemplateParmDecl *param
6351 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
6353 return TemplateName();
6355 TemplateName replacement = Import(subst->getReplacement());
6356 if (replacement.isNull()) return TemplateName();
6358 return ToContext.getSubstTemplateTemplateParm(param, replacement);
6361 case TemplateName::SubstTemplateTemplateParmPack: {
6362 SubstTemplateTemplateParmPackStorage *SubstPack
6363 = From.getAsSubstTemplateTemplateParmPack();
6364 TemplateTemplateParmDecl *Param
6365 = cast_or_null<TemplateTemplateParmDecl>(
6366 Import(SubstPack->getParameterPack()));
6368 return TemplateName();
6370 ASTNodeImporter Importer(*this);
6371 TemplateArgument ArgPack
6372 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
6373 if (ArgPack.isNull())
6374 return TemplateName();
6376 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
6380 llvm_unreachable("Invalid template name kind");
6383 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
6384 if (FromLoc.isInvalid())
6385 return SourceLocation();
6387 SourceManager &FromSM = FromContext.getSourceManager();
6389 // For now, map everything down to its spelling location, so that we
6390 // don't have to import macro expansions.
6391 // FIXME: Import macro expansions!
6392 FromLoc = FromSM.getSpellingLoc(FromLoc);
6393 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
6394 SourceManager &ToSM = ToContext.getSourceManager();
6395 FileID ToFileID = Import(Decomposed.first);
6396 if (ToFileID.isInvalid())
6397 return SourceLocation();
6398 SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
6399 .getLocWithOffset(Decomposed.second);
6403 SourceRange ASTImporter::Import(SourceRange FromRange) {
6404 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
6407 FileID ASTImporter::Import(FileID FromID) {
6408 llvm::DenseMap<FileID, FileID>::iterator Pos
6409 = ImportedFileIDs.find(FromID);
6410 if (Pos != ImportedFileIDs.end())
6413 SourceManager &FromSM = FromContext.getSourceManager();
6414 SourceManager &ToSM = ToContext.getSourceManager();
6415 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
6416 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
6418 // Include location of this file.
6419 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
6421 // Map the FileID for to the "to" source manager.
6423 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
6424 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
6425 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
6427 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
6428 // than mmap the files several times.
6429 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
6432 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
6433 FromSLoc.getFile().getFileCharacteristic());
6435 // FIXME: We want to re-use the existing MemoryBuffer!
6436 const llvm::MemoryBuffer *
6437 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
6438 std::unique_ptr<llvm::MemoryBuffer> ToBuf
6439 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
6440 FromBuf->getBufferIdentifier());
6441 ToID = ToSM.createFileID(std::move(ToBuf),
6442 FromSLoc.getFile().getFileCharacteristic());
6446 ImportedFileIDs[FromID] = ToID;
6450 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
6451 Expr *ToExpr = Import(From->getInit());
6452 if (!ToExpr && From->getInit())
6455 if (From->isBaseInitializer()) {
6456 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6457 if (!ToTInfo && From->getTypeSourceInfo())
6460 return new (ToContext) CXXCtorInitializer(
6461 ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
6462 ToExpr, Import(From->getRParenLoc()),
6463 From->isPackExpansion() ? Import(From->getEllipsisLoc())
6464 : SourceLocation());
6465 } else if (From->isMemberInitializer()) {
6466 FieldDecl *ToField =
6467 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
6468 if (!ToField && From->getMember())
6471 return new (ToContext) CXXCtorInitializer(
6472 ToContext, ToField, Import(From->getMemberLocation()),
6473 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6474 } else if (From->isIndirectMemberInitializer()) {
6475 IndirectFieldDecl *ToIField = llvm::cast_or_null<IndirectFieldDecl>(
6476 Import(From->getIndirectMember()));
6477 if (!ToIField && From->getIndirectMember())
6480 return new (ToContext) CXXCtorInitializer(
6481 ToContext, ToIField, Import(From->getMemberLocation()),
6482 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6483 } else if (From->isDelegatingInitializer()) {
6484 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6485 if (!ToTInfo && From->getTypeSourceInfo())
6488 return new (ToContext)
6489 CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
6490 ToExpr, Import(From->getRParenLoc()));
6491 } else if (unsigned NumArrayIndices = From->getNumArrayIndices()) {
6492 FieldDecl *ToField =
6493 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
6494 if (!ToField && From->getMember())
6497 SmallVector<VarDecl *, 4> ToAIs(NumArrayIndices);
6499 for (unsigned AII = 0; AII < NumArrayIndices; ++AII) {
6500 VarDecl *ToArrayIndex =
6501 dyn_cast_or_null<VarDecl>(Import(From->getArrayIndex(AII)));
6502 if (!ToArrayIndex && From->getArrayIndex(AII))
6506 return CXXCtorInitializer::Create(
6507 ToContext, ToField, Import(From->getMemberLocation()),
6508 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()),
6509 ToAIs.data(), NumArrayIndices);
6516 void ASTImporter::ImportDefinition(Decl *From) {
6517 Decl *To = Import(From);
6521 if (DeclContext *FromDC = cast<DeclContext>(From)) {
6522 ASTNodeImporter Importer(*this);
6524 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
6525 if (!ToRecord->getDefinition()) {
6526 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
6527 ASTNodeImporter::IDK_Everything);
6532 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
6533 if (!ToEnum->getDefinition()) {
6534 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
6535 ASTNodeImporter::IDK_Everything);
6540 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
6541 if (!ToIFace->getDefinition()) {
6542 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
6543 ASTNodeImporter::IDK_Everything);
6548 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
6549 if (!ToProto->getDefinition()) {
6550 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
6551 ASTNodeImporter::IDK_Everything);
6556 Importer.ImportDeclContext(FromDC, true);
6560 DeclarationName ASTImporter::Import(DeclarationName FromName) {
6562 return DeclarationName();
6564 switch (FromName.getNameKind()) {
6565 case DeclarationName::Identifier:
6566 return Import(FromName.getAsIdentifierInfo());
6568 case DeclarationName::ObjCZeroArgSelector:
6569 case DeclarationName::ObjCOneArgSelector:
6570 case DeclarationName::ObjCMultiArgSelector:
6571 return Import(FromName.getObjCSelector());
6573 case DeclarationName::CXXConstructorName: {
6574 QualType T = Import(FromName.getCXXNameType());
6576 return DeclarationName();
6578 return ToContext.DeclarationNames.getCXXConstructorName(
6579 ToContext.getCanonicalType(T));
6582 case DeclarationName::CXXDestructorName: {
6583 QualType T = Import(FromName.getCXXNameType());
6585 return DeclarationName();
6587 return ToContext.DeclarationNames.getCXXDestructorName(
6588 ToContext.getCanonicalType(T));
6591 case DeclarationName::CXXConversionFunctionName: {
6592 QualType T = Import(FromName.getCXXNameType());
6594 return DeclarationName();
6596 return ToContext.DeclarationNames.getCXXConversionFunctionName(
6597 ToContext.getCanonicalType(T));
6600 case DeclarationName::CXXOperatorName:
6601 return ToContext.DeclarationNames.getCXXOperatorName(
6602 FromName.getCXXOverloadedOperator());
6604 case DeclarationName::CXXLiteralOperatorName:
6605 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
6606 Import(FromName.getCXXLiteralIdentifier()));
6608 case DeclarationName::CXXUsingDirective:
6610 return DeclarationName::getUsingDirectiveName();
6613 llvm_unreachable("Invalid DeclarationName Kind!");
6616 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
6620 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
6622 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
6623 ToId->setBuiltinID(FromId->getBuiltinID());
6628 Selector ASTImporter::Import(Selector FromSel) {
6629 if (FromSel.isNull())
6632 SmallVector<IdentifierInfo *, 4> Idents;
6633 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
6634 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
6635 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
6636 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
6639 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
6643 unsigned NumDecls) {
6647 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
6648 if (LastDiagFromFrom)
6649 ToContext.getDiagnostics().notePriorDiagnosticFrom(
6650 FromContext.getDiagnostics());
6651 LastDiagFromFrom = false;
6652 return ToContext.getDiagnostics().Report(Loc, DiagID);
6655 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
6656 if (!LastDiagFromFrom)
6657 FromContext.getDiagnostics().notePriorDiagnosticFrom(
6658 ToContext.getDiagnostics());
6659 LastDiagFromFrom = true;
6660 return FromContext.getDiagnostics().Report(Loc, DiagID);
6663 void ASTImporter::CompleteDecl (Decl *D) {
6664 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
6665 if (!ID->getDefinition())
6666 ID->startDefinition();
6668 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
6669 if (!PD->getDefinition())
6670 PD->startDefinition();
6672 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6673 if (!TD->getDefinition() && !TD->isBeingDefined()) {
6674 TD->startDefinition();
6675 TD->setCompleteDefinition(true);
6679 assert (0 && "CompleteDecl called on a Decl that can't be completed");
6683 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
6684 if (From->hasAttrs()) {
6685 for (Attr *FromAttr : From->getAttrs())
6686 To->addAttr(FromAttr->clone(To->getASTContext()));
6688 if (From->isUsed()) {
6691 if (From->isImplicit()) {
6694 ImportedDecls[From] = To;
6698 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
6700 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6701 = ImportedTypes.find(From.getTypePtr());
6702 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
6705 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
6707 return Ctx.IsStructurallyEquivalent(From, To);