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/ASTStructuralEquivalence.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclVisitor.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/AST/TypeVisitor.h"
23 #include "clang/Basic/FileManager.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "llvm/Support/MemoryBuffer.h"
29 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
30 public DeclVisitor<ASTNodeImporter, Decl *>,
31 public StmtVisitor<ASTNodeImporter, Stmt *> {
32 ASTImporter &Importer;
35 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
37 using TypeVisitor<ASTNodeImporter, QualType>::Visit;
38 using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
39 using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
42 QualType VisitType(const Type *T);
43 QualType VisitAtomicType(const AtomicType *T);
44 QualType VisitBuiltinType(const BuiltinType *T);
45 QualType VisitDecayedType(const DecayedType *T);
46 QualType VisitComplexType(const ComplexType *T);
47 QualType VisitPointerType(const PointerType *T);
48 QualType VisitBlockPointerType(const BlockPointerType *T);
49 QualType VisitLValueReferenceType(const LValueReferenceType *T);
50 QualType VisitRValueReferenceType(const RValueReferenceType *T);
51 QualType VisitMemberPointerType(const MemberPointerType *T);
52 QualType VisitConstantArrayType(const ConstantArrayType *T);
53 QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
54 QualType VisitVariableArrayType(const VariableArrayType *T);
55 // FIXME: DependentSizedArrayType
56 // FIXME: DependentSizedExtVectorType
57 QualType VisitVectorType(const VectorType *T);
58 QualType VisitExtVectorType(const ExtVectorType *T);
59 QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
60 QualType VisitFunctionProtoType(const FunctionProtoType *T);
61 // FIXME: UnresolvedUsingType
62 QualType VisitParenType(const ParenType *T);
63 QualType VisitTypedefType(const TypedefType *T);
64 QualType VisitTypeOfExprType(const TypeOfExprType *T);
65 // FIXME: DependentTypeOfExprType
66 QualType VisitTypeOfType(const TypeOfType *T);
67 QualType VisitDecltypeType(const DecltypeType *T);
68 QualType VisitUnaryTransformType(const UnaryTransformType *T);
69 QualType VisitAutoType(const AutoType *T);
70 QualType VisitInjectedClassNameType(const InjectedClassNameType *T);
71 // FIXME: DependentDecltypeType
72 QualType VisitRecordType(const RecordType *T);
73 QualType VisitEnumType(const EnumType *T);
74 QualType VisitAttributedType(const AttributedType *T);
75 QualType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
76 QualType VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T);
77 QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
78 QualType VisitElaboratedType(const ElaboratedType *T);
79 // FIXME: DependentNameType
80 // FIXME: DependentTemplateSpecializationType
81 QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
82 QualType VisitObjCObjectType(const ObjCObjectType *T);
83 QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
85 // Importing declarations
86 bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
87 DeclContext *&LexicalDC, DeclarationName &Name,
88 NamedDecl *&ToD, SourceLocation &Loc);
89 void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
90 void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
91 DeclarationNameInfo& To);
92 void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
94 bool ImportCastPath(CastExpr *E, CXXCastPath &Path);
96 typedef DesignatedInitExpr::Designator Designator;
97 Designator ImportDesignator(const Designator &D);
100 /// \brief What we should import from the definition.
101 enum ImportDefinitionKind {
102 /// \brief Import the default subset of the definition, which might be
103 /// nothing (if minimal import is set) or might be everything (if minimal
104 /// import is not set).
106 /// \brief Import everything.
108 /// \brief Import only the bare bones needed to establish a valid
113 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
114 return IDK == IDK_Everything ||
115 (IDK == IDK_Default && !Importer.isMinimalImport());
118 bool ImportDefinition(RecordDecl *From, RecordDecl *To,
119 ImportDefinitionKind Kind = IDK_Default);
120 bool ImportDefinition(VarDecl *From, VarDecl *To,
121 ImportDefinitionKind Kind = IDK_Default);
122 bool ImportDefinition(EnumDecl *From, EnumDecl *To,
123 ImportDefinitionKind Kind = IDK_Default);
124 bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
125 ImportDefinitionKind Kind = IDK_Default);
126 bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
127 ImportDefinitionKind Kind = IDK_Default);
128 TemplateParameterList *ImportTemplateParameterList(
129 TemplateParameterList *Params);
130 TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
131 TemplateArgumentLoc ImportTemplateArgumentLoc(
132 const TemplateArgumentLoc &TALoc, bool &Error);
133 bool ImportTemplateArguments(const TemplateArgument *FromArgs,
134 unsigned NumFromArgs,
135 SmallVectorImpl<TemplateArgument> &ToArgs);
136 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
137 bool Complain = true);
138 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
139 bool Complain = true);
140 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
141 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
142 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
143 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
144 Decl *VisitDecl(Decl *D);
145 Decl *VisitAccessSpecDecl(AccessSpecDecl *D);
146 Decl *VisitStaticAssertDecl(StaticAssertDecl *D);
147 Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
148 Decl *VisitNamespaceDecl(NamespaceDecl *D);
149 Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
150 Decl *VisitTypedefDecl(TypedefDecl *D);
151 Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
152 Decl *VisitLabelDecl(LabelDecl *D);
153 Decl *VisitEnumDecl(EnumDecl *D);
154 Decl *VisitRecordDecl(RecordDecl *D);
155 Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
156 Decl *VisitFunctionDecl(FunctionDecl *D);
157 Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
158 Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
159 Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
160 Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
161 Decl *VisitFieldDecl(FieldDecl *D);
162 Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
163 Decl *VisitFriendDecl(FriendDecl *D);
164 Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
165 Decl *VisitVarDecl(VarDecl *D);
166 Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
167 Decl *VisitParmVarDecl(ParmVarDecl *D);
168 Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
169 Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
170 Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
171 Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
172 Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
174 ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
175 Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
176 Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
177 Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
178 Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
179 Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
180 Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
181 Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
182 Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
183 Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
184 Decl *VisitClassTemplateSpecializationDecl(
185 ClassTemplateSpecializationDecl *D);
186 Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
187 Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
189 // Importing statements
190 DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
192 Stmt *VisitStmt(Stmt *S);
193 Stmt *VisitGCCAsmStmt(GCCAsmStmt *S);
194 Stmt *VisitDeclStmt(DeclStmt *S);
195 Stmt *VisitNullStmt(NullStmt *S);
196 Stmt *VisitCompoundStmt(CompoundStmt *S);
197 Stmt *VisitCaseStmt(CaseStmt *S);
198 Stmt *VisitDefaultStmt(DefaultStmt *S);
199 Stmt *VisitLabelStmt(LabelStmt *S);
200 Stmt *VisitAttributedStmt(AttributedStmt *S);
201 Stmt *VisitIfStmt(IfStmt *S);
202 Stmt *VisitSwitchStmt(SwitchStmt *S);
203 Stmt *VisitWhileStmt(WhileStmt *S);
204 Stmt *VisitDoStmt(DoStmt *S);
205 Stmt *VisitForStmt(ForStmt *S);
206 Stmt *VisitGotoStmt(GotoStmt *S);
207 Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
208 Stmt *VisitContinueStmt(ContinueStmt *S);
209 Stmt *VisitBreakStmt(BreakStmt *S);
210 Stmt *VisitReturnStmt(ReturnStmt *S);
212 // FIXME: SEHExceptStmt
213 // FIXME: SEHFinallyStmt
215 // FIXME: SEHLeaveStmt
216 // FIXME: CapturedStmt
217 Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
218 Stmt *VisitCXXTryStmt(CXXTryStmt *S);
219 Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
220 // FIXME: MSDependentExistsStmt
221 Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
222 Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
223 Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
224 Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
225 Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
226 Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
227 Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
229 // Importing expressions
230 Expr *VisitExpr(Expr *E);
231 Expr *VisitVAArgExpr(VAArgExpr *E);
232 Expr *VisitGNUNullExpr(GNUNullExpr *E);
233 Expr *VisitPredefinedExpr(PredefinedExpr *E);
234 Expr *VisitDeclRefExpr(DeclRefExpr *E);
235 Expr *VisitImplicitValueInitExpr(ImplicitValueInitExpr *ILE);
236 Expr *VisitDesignatedInitExpr(DesignatedInitExpr *E);
237 Expr *VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
238 Expr *VisitIntegerLiteral(IntegerLiteral *E);
239 Expr *VisitFloatingLiteral(FloatingLiteral *E);
240 Expr *VisitCharacterLiteral(CharacterLiteral *E);
241 Expr *VisitStringLiteral(StringLiteral *E);
242 Expr *VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
243 Expr *VisitAtomicExpr(AtomicExpr *E);
244 Expr *VisitAddrLabelExpr(AddrLabelExpr *E);
245 Expr *VisitParenExpr(ParenExpr *E);
246 Expr *VisitParenListExpr(ParenListExpr *E);
247 Expr *VisitStmtExpr(StmtExpr *E);
248 Expr *VisitUnaryOperator(UnaryOperator *E);
249 Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
250 Expr *VisitBinaryOperator(BinaryOperator *E);
251 Expr *VisitConditionalOperator(ConditionalOperator *E);
252 Expr *VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
253 Expr *VisitOpaqueValueExpr(OpaqueValueExpr *E);
254 Expr *VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
255 Expr *VisitExpressionTraitExpr(ExpressionTraitExpr *E);
256 Expr *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
257 Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
258 Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
259 Expr *VisitExplicitCastExpr(ExplicitCastExpr *E);
260 Expr *VisitOffsetOfExpr(OffsetOfExpr *OE);
261 Expr *VisitCXXThrowExpr(CXXThrowExpr *E);
262 Expr *VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
263 Expr *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
264 Expr *VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
265 Expr *VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
266 Expr *VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE);
267 Expr *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
268 Expr *VisitCXXNewExpr(CXXNewExpr *CE);
269 Expr *VisitCXXDeleteExpr(CXXDeleteExpr *E);
270 Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
271 Expr *VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
272 Expr *VisitExprWithCleanups(ExprWithCleanups *EWC);
273 Expr *VisitCXXThisExpr(CXXThisExpr *E);
274 Expr *VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
275 Expr *VisitMemberExpr(MemberExpr *E);
276 Expr *VisitCallExpr(CallExpr *E);
277 Expr *VisitInitListExpr(InitListExpr *E);
278 Expr *VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
279 Expr *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
280 Expr *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
281 Expr *VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
282 Expr *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
285 template<typename IIter, typename OIter>
286 void ImportArray(IIter Ibegin, IIter Iend, OIter Obegin) {
287 typedef typename std::remove_reference<decltype(*Obegin)>::type ItemT;
288 ASTImporter &ImporterRef = Importer;
289 std::transform(Ibegin, Iend, Obegin,
290 [&ImporterRef](ItemT From) -> ItemT {
291 return ImporterRef.Import(From);
295 template<typename IIter, typename OIter>
296 bool ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
297 typedef typename std::remove_reference<decltype(**Obegin)>::type ItemT;
298 ASTImporter &ImporterRef = Importer;
300 std::transform(Ibegin, Iend, Obegin,
301 [&ImporterRef, &Failed](ItemT *From) -> ItemT * {
302 ItemT *To = cast_or_null<ItemT>(
303 ImporterRef.Import(From));
311 template<typename InContainerTy, typename OutContainerTy>
312 bool ImportContainerChecked(const InContainerTy &InContainer,
313 OutContainerTy &OutContainer) {
314 return ImportArrayChecked(InContainer.begin(), InContainer.end(),
315 OutContainer.begin());
318 template<typename InContainerTy, typename OIter>
319 bool ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
320 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
325 //----------------------------------------------------------------------------
327 //----------------------------------------------------------------------------
329 using namespace clang;
331 QualType ASTNodeImporter::VisitType(const Type *T) {
332 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
333 << T->getTypeClassName();
337 QualType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
338 QualType UnderlyingType = Importer.Import(T->getValueType());
339 if(UnderlyingType.isNull())
342 return Importer.getToContext().getAtomicType(UnderlyingType);
345 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
346 switch (T->getKind()) {
347 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
348 case BuiltinType::Id: \
349 return Importer.getToContext().SingletonId;
350 #include "clang/Basic/OpenCLImageTypes.def"
351 #define SHARED_SINGLETON_TYPE(Expansion)
352 #define BUILTIN_TYPE(Id, SingletonId) \
353 case BuiltinType::Id: return Importer.getToContext().SingletonId;
354 #include "clang/AST/BuiltinTypes.def"
356 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
357 // context supports C++.
359 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
360 // context supports ObjC.
362 case BuiltinType::Char_U:
363 // The context we're importing from has an unsigned 'char'. If we're
364 // importing into a context with a signed 'char', translate to
365 // 'unsigned char' instead.
366 if (Importer.getToContext().getLangOpts().CharIsSigned)
367 return Importer.getToContext().UnsignedCharTy;
369 return Importer.getToContext().CharTy;
371 case BuiltinType::Char_S:
372 // The context we're importing from has an unsigned 'char'. If we're
373 // importing into a context with a signed 'char', translate to
374 // 'unsigned char' instead.
375 if (!Importer.getToContext().getLangOpts().CharIsSigned)
376 return Importer.getToContext().SignedCharTy;
378 return Importer.getToContext().CharTy;
380 case BuiltinType::WChar_S:
381 case BuiltinType::WChar_U:
382 // FIXME: If not in C++, shall we translate to the C equivalent of
384 return Importer.getToContext().WCharTy;
387 llvm_unreachable("Invalid BuiltinType Kind!");
390 QualType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
391 QualType OrigT = Importer.Import(T->getOriginalType());
395 return Importer.getToContext().getDecayedType(OrigT);
398 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
399 QualType ToElementType = Importer.Import(T->getElementType());
400 if (ToElementType.isNull())
403 return Importer.getToContext().getComplexType(ToElementType);
406 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
407 QualType ToPointeeType = Importer.Import(T->getPointeeType());
408 if (ToPointeeType.isNull())
411 return Importer.getToContext().getPointerType(ToPointeeType);
414 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
415 // FIXME: Check for blocks support in "to" context.
416 QualType ToPointeeType = Importer.Import(T->getPointeeType());
417 if (ToPointeeType.isNull())
420 return Importer.getToContext().getBlockPointerType(ToPointeeType);
424 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
425 // FIXME: Check for C++ support in "to" context.
426 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
427 if (ToPointeeType.isNull())
430 return Importer.getToContext().getLValueReferenceType(ToPointeeType);
434 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
435 // FIXME: Check for C++0x support in "to" context.
436 QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
437 if (ToPointeeType.isNull())
440 return Importer.getToContext().getRValueReferenceType(ToPointeeType);
443 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
444 // FIXME: Check for C++ support in "to" context.
445 QualType ToPointeeType = Importer.Import(T->getPointeeType());
446 if (ToPointeeType.isNull())
449 QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
450 return Importer.getToContext().getMemberPointerType(ToPointeeType,
451 ClassType.getTypePtr());
454 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
455 QualType ToElementType = Importer.Import(T->getElementType());
456 if (ToElementType.isNull())
459 return Importer.getToContext().getConstantArrayType(ToElementType,
461 T->getSizeModifier(),
462 T->getIndexTypeCVRQualifiers());
466 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
467 QualType ToElementType = Importer.Import(T->getElementType());
468 if (ToElementType.isNull())
471 return Importer.getToContext().getIncompleteArrayType(ToElementType,
472 T->getSizeModifier(),
473 T->getIndexTypeCVRQualifiers());
476 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
477 QualType ToElementType = Importer.Import(T->getElementType());
478 if (ToElementType.isNull())
481 Expr *Size = Importer.Import(T->getSizeExpr());
485 SourceRange Brackets = Importer.Import(T->getBracketsRange());
486 return Importer.getToContext().getVariableArrayType(ToElementType, Size,
487 T->getSizeModifier(),
488 T->getIndexTypeCVRQualifiers(),
492 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
493 QualType ToElementType = Importer.Import(T->getElementType());
494 if (ToElementType.isNull())
497 return Importer.getToContext().getVectorType(ToElementType,
502 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
503 QualType ToElementType = Importer.Import(T->getElementType());
504 if (ToElementType.isNull())
507 return Importer.getToContext().getExtVectorType(ToElementType,
508 T->getNumElements());
512 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
513 // FIXME: What happens if we're importing a function without a prototype
514 // into C++? Should we make it variadic?
515 QualType ToResultType = Importer.Import(T->getReturnType());
516 if (ToResultType.isNull())
519 return Importer.getToContext().getFunctionNoProtoType(ToResultType,
523 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
524 QualType ToResultType = Importer.Import(T->getReturnType());
525 if (ToResultType.isNull())
528 // Import argument types
529 SmallVector<QualType, 4> ArgTypes;
530 for (const auto &A : T->param_types()) {
531 QualType ArgType = Importer.Import(A);
532 if (ArgType.isNull())
534 ArgTypes.push_back(ArgType);
537 // Import exception types
538 SmallVector<QualType, 4> ExceptionTypes;
539 for (const auto &E : T->exceptions()) {
540 QualType ExceptionType = Importer.Import(E);
541 if (ExceptionType.isNull())
543 ExceptionTypes.push_back(ExceptionType);
546 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
547 FunctionProtoType::ExtProtoInfo ToEPI;
549 ToEPI.ExtInfo = FromEPI.ExtInfo;
550 ToEPI.Variadic = FromEPI.Variadic;
551 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
552 ToEPI.TypeQuals = FromEPI.TypeQuals;
553 ToEPI.RefQualifier = FromEPI.RefQualifier;
554 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
555 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
556 ToEPI.ExceptionSpec.NoexceptExpr =
557 Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
558 ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
559 Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
560 ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
561 Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
563 return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
566 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
567 QualType ToInnerType = Importer.Import(T->getInnerType());
568 if (ToInnerType.isNull())
571 return Importer.getToContext().getParenType(ToInnerType);
574 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
575 TypedefNameDecl *ToDecl
576 = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
580 return Importer.getToContext().getTypeDeclType(ToDecl);
583 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
584 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
588 return Importer.getToContext().getTypeOfExprType(ToExpr);
591 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
592 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
593 if (ToUnderlyingType.isNull())
596 return Importer.getToContext().getTypeOfType(ToUnderlyingType);
599 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
600 // FIXME: Make sure that the "to" context supports C++0x!
601 Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
605 QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
606 if (UnderlyingType.isNull())
609 return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
612 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
613 QualType ToBaseType = Importer.Import(T->getBaseType());
614 QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
615 if (ToBaseType.isNull() || ToUnderlyingType.isNull())
618 return Importer.getToContext().getUnaryTransformType(ToBaseType,
623 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
624 // FIXME: Make sure that the "to" context supports C++11!
625 QualType FromDeduced = T->getDeducedType();
627 if (!FromDeduced.isNull()) {
628 ToDeduced = Importer.Import(FromDeduced);
629 if (ToDeduced.isNull())
633 return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
634 /*IsDependent*/false);
637 QualType ASTNodeImporter::VisitInjectedClassNameType(
638 const InjectedClassNameType *T) {
639 CXXRecordDecl *D = cast_or_null<CXXRecordDecl>(Importer.Import(T->getDecl()));
643 QualType InjType = Importer.Import(T->getInjectedSpecializationType());
644 if (InjType.isNull())
647 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
648 // See comments in InjectedClassNameType definition for details
649 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
651 TypeAlignmentInBits = 4,
652 TypeAlignment = 1 << TypeAlignmentInBits
655 return QualType(new (Importer.getToContext(), TypeAlignment)
656 InjectedClassNameType(D, InjType), 0);
659 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
661 = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
665 return Importer.getToContext().getTagDeclType(ToDecl);
668 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
670 = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
674 return Importer.getToContext().getTagDeclType(ToDecl);
677 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
678 QualType FromModifiedType = T->getModifiedType();
679 QualType FromEquivalentType = T->getEquivalentType();
680 QualType ToModifiedType;
681 QualType ToEquivalentType;
683 if (!FromModifiedType.isNull()) {
684 ToModifiedType = Importer.Import(FromModifiedType);
685 if (ToModifiedType.isNull())
688 if (!FromEquivalentType.isNull()) {
689 ToEquivalentType = Importer.Import(FromEquivalentType);
690 if (ToEquivalentType.isNull())
694 return Importer.getToContext().getAttributedType(T->getAttrKind(),
695 ToModifiedType, ToEquivalentType);
699 QualType ASTNodeImporter::VisitTemplateTypeParmType(
700 const TemplateTypeParmType *T) {
701 TemplateTypeParmDecl *ParmDecl =
702 cast_or_null<TemplateTypeParmDecl>(Importer.Import(T->getDecl()));
703 if (!ParmDecl && T->getDecl())
706 return Importer.getToContext().getTemplateTypeParmType(
707 T->getDepth(), T->getIndex(), T->isParameterPack(), ParmDecl);
710 QualType ASTNodeImporter::VisitSubstTemplateTypeParmType(
711 const SubstTemplateTypeParmType *T) {
712 const TemplateTypeParmType *Replaced =
713 cast_or_null<TemplateTypeParmType>(Importer.Import(
714 QualType(T->getReplacedParameter(), 0)).getTypePtr());
718 QualType Replacement = Importer.Import(T->getReplacementType());
719 if (Replacement.isNull())
721 Replacement = Replacement.getCanonicalType();
723 return Importer.getToContext().getSubstTemplateTypeParmType(
724 Replaced, Replacement);
727 QualType ASTNodeImporter::VisitTemplateSpecializationType(
728 const TemplateSpecializationType *T) {
729 TemplateName ToTemplate = Importer.Import(T->getTemplateName());
730 if (ToTemplate.isNull())
733 SmallVector<TemplateArgument, 2> ToTemplateArgs;
734 if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
737 QualType ToCanonType;
738 if (!QualType(T, 0).isCanonical()) {
739 QualType FromCanonType
740 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
741 ToCanonType =Importer.Import(FromCanonType);
742 if (ToCanonType.isNull())
745 return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
750 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
751 NestedNameSpecifier *ToQualifier = nullptr;
752 // Note: the qualifier in an ElaboratedType is optional.
753 if (T->getQualifier()) {
754 ToQualifier = Importer.Import(T->getQualifier());
759 QualType ToNamedType = Importer.Import(T->getNamedType());
760 if (ToNamedType.isNull())
763 return Importer.getToContext().getElaboratedType(T->getKeyword(),
764 ToQualifier, ToNamedType);
767 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
768 ObjCInterfaceDecl *Class
769 = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
773 return Importer.getToContext().getObjCInterfaceType(Class);
776 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
777 QualType ToBaseType = Importer.Import(T->getBaseType());
778 if (ToBaseType.isNull())
781 SmallVector<QualType, 4> TypeArgs;
782 for (auto TypeArg : T->getTypeArgsAsWritten()) {
783 QualType ImportedTypeArg = Importer.Import(TypeArg);
784 if (ImportedTypeArg.isNull())
787 TypeArgs.push_back(ImportedTypeArg);
790 SmallVector<ObjCProtocolDecl *, 4> Protocols;
791 for (auto *P : T->quals()) {
792 ObjCProtocolDecl *Protocol
793 = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
796 Protocols.push_back(Protocol);
799 return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
801 T->isKindOfTypeAsWritten());
805 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
806 QualType ToPointeeType = Importer.Import(T->getPointeeType());
807 if (ToPointeeType.isNull())
810 return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
813 //----------------------------------------------------------------------------
814 // Import Declarations
815 //----------------------------------------------------------------------------
816 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
817 DeclContext *&LexicalDC,
818 DeclarationName &Name,
820 SourceLocation &Loc) {
821 // Import the context of this declaration.
822 DC = Importer.ImportContext(D->getDeclContext());
827 if (D->getDeclContext() != D->getLexicalDeclContext()) {
828 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
833 // Import the name of this declaration.
834 Name = Importer.Import(D->getDeclName());
835 if (D->getDeclName() && !Name)
838 // Import the location of this declaration.
839 Loc = Importer.Import(D->getLocation());
840 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
844 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
849 ToD = Importer.Import(FromD);
854 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
855 if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
856 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
857 ImportDefinition(FromRecord, ToRecord);
863 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
864 if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
865 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
866 ImportDefinition(FromEnum, ToEnum);
874 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
875 DeclarationNameInfo& To) {
876 // NOTE: To.Name and To.Loc are already imported.
877 // We only have to import To.LocInfo.
878 switch (To.getName().getNameKind()) {
879 case DeclarationName::Identifier:
880 case DeclarationName::ObjCZeroArgSelector:
881 case DeclarationName::ObjCOneArgSelector:
882 case DeclarationName::ObjCMultiArgSelector:
883 case DeclarationName::CXXUsingDirective:
884 case DeclarationName::CXXDeductionGuideName:
887 case DeclarationName::CXXOperatorName: {
888 SourceRange Range = From.getCXXOperatorNameRange();
889 To.setCXXOperatorNameRange(Importer.Import(Range));
892 case DeclarationName::CXXLiteralOperatorName: {
893 SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
894 To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
897 case DeclarationName::CXXConstructorName:
898 case DeclarationName::CXXDestructorName:
899 case DeclarationName::CXXConversionFunctionName: {
900 TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
901 To.setNamedTypeInfo(Importer.Import(FromTInfo));
905 llvm_unreachable("Unknown name kind.");
908 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
909 if (Importer.isMinimalImport() && !ForceImport) {
910 Importer.ImportContext(FromDC);
914 for (auto *From : FromDC->decls())
915 Importer.Import(From);
918 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
919 ImportDefinitionKind Kind) {
920 if (To->getDefinition() || To->isBeingDefined()) {
921 if (Kind == IDK_Everything)
922 ImportDeclContext(From, /*ForceImport=*/true);
927 To->startDefinition();
930 if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
931 CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
933 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
934 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
935 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
936 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
937 ToData.Aggregate = FromData.Aggregate;
938 ToData.PlainOldData = FromData.PlainOldData;
939 ToData.Empty = FromData.Empty;
940 ToData.Polymorphic = FromData.Polymorphic;
941 ToData.Abstract = FromData.Abstract;
942 ToData.IsStandardLayout = FromData.IsStandardLayout;
943 ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
944 ToData.HasPrivateFields = FromData.HasPrivateFields;
945 ToData.HasProtectedFields = FromData.HasProtectedFields;
946 ToData.HasPublicFields = FromData.HasPublicFields;
947 ToData.HasMutableFields = FromData.HasMutableFields;
948 ToData.HasVariantMembers = FromData.HasVariantMembers;
949 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
950 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
951 ToData.HasUninitializedReferenceMember
952 = FromData.HasUninitializedReferenceMember;
953 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
954 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
955 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
956 ToData.NeedOverloadResolutionForMoveConstructor
957 = FromData.NeedOverloadResolutionForMoveConstructor;
958 ToData.NeedOverloadResolutionForMoveAssignment
959 = FromData.NeedOverloadResolutionForMoveAssignment;
960 ToData.NeedOverloadResolutionForDestructor
961 = FromData.NeedOverloadResolutionForDestructor;
962 ToData.DefaultedMoveConstructorIsDeleted
963 = FromData.DefaultedMoveConstructorIsDeleted;
964 ToData.DefaultedMoveAssignmentIsDeleted
965 = FromData.DefaultedMoveAssignmentIsDeleted;
966 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
967 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
968 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
969 ToData.HasConstexprNonCopyMoveConstructor
970 = FromData.HasConstexprNonCopyMoveConstructor;
971 ToData.HasDefaultedDefaultConstructor
972 = FromData.HasDefaultedDefaultConstructor;
973 ToData.DefaultedDefaultConstructorIsConstexpr
974 = FromData.DefaultedDefaultConstructorIsConstexpr;
975 ToData.HasConstexprDefaultConstructor
976 = FromData.HasConstexprDefaultConstructor;
977 ToData.HasNonLiteralTypeFieldsOrBases
978 = FromData.HasNonLiteralTypeFieldsOrBases;
979 // ComputedVisibleConversions not imported.
980 ToData.UserProvidedDefaultConstructor
981 = FromData.UserProvidedDefaultConstructor;
982 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
983 ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
984 = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
985 ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
986 = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
987 ToData.ImplicitCopyAssignmentHasConstParam
988 = FromData.ImplicitCopyAssignmentHasConstParam;
989 ToData.HasDeclaredCopyConstructorWithConstParam
990 = FromData.HasDeclaredCopyConstructorWithConstParam;
991 ToData.HasDeclaredCopyAssignmentWithConstParam
992 = FromData.HasDeclaredCopyAssignmentWithConstParam;
993 ToData.IsLambda = FromData.IsLambda;
995 SmallVector<CXXBaseSpecifier *, 4> Bases;
996 for (const auto &Base1 : FromCXX->bases()) {
997 QualType T = Importer.Import(Base1.getType());
1001 SourceLocation EllipsisLoc;
1002 if (Base1.isPackExpansion())
1003 EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
1005 // Ensure that we have a definition for the base.
1006 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
1009 new (Importer.getToContext())
1010 CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
1012 Base1.isBaseOfClass(),
1013 Base1.getAccessSpecifierAsWritten(),
1014 Importer.Import(Base1.getTypeSourceInfo()),
1018 ToCXX->setBases(Bases.data(), Bases.size());
1021 if (shouldForceImportDeclContext(Kind))
1022 ImportDeclContext(From, /*ForceImport=*/true);
1024 To->completeDefinition();
1028 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
1029 ImportDefinitionKind Kind) {
1030 if (To->getAnyInitializer())
1033 // FIXME: Can we really import any initializer? Alternatively, we could force
1034 // ourselves to import every declaration of a variable and then only use
1036 To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
1038 // FIXME: Other bits to merge?
1043 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
1044 ImportDefinitionKind Kind) {
1045 if (To->getDefinition() || To->isBeingDefined()) {
1046 if (Kind == IDK_Everything)
1047 ImportDeclContext(From, /*ForceImport=*/true);
1051 To->startDefinition();
1053 QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
1057 QualType ToPromotionType = Importer.Import(From->getPromotionType());
1058 if (ToPromotionType.isNull())
1061 if (shouldForceImportDeclContext(Kind))
1062 ImportDeclContext(From, /*ForceImport=*/true);
1064 // FIXME: we might need to merge the number of positive or negative bits
1065 // if the enumerator lists don't match.
1066 To->completeDefinition(T, ToPromotionType,
1067 From->getNumPositiveBits(),
1068 From->getNumNegativeBits());
1072 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
1073 TemplateParameterList *Params) {
1074 SmallVector<NamedDecl *, 4> ToParams(Params->size());
1075 if (ImportContainerChecked(*Params, ToParams))
1078 Expr *ToRequiresClause;
1079 if (Expr *const R = Params->getRequiresClause()) {
1080 ToRequiresClause = Importer.Import(R);
1081 if (!ToRequiresClause)
1084 ToRequiresClause = nullptr;
1087 return TemplateParameterList::Create(Importer.getToContext(),
1088 Importer.Import(Params->getTemplateLoc()),
1089 Importer.Import(Params->getLAngleLoc()),
1091 Importer.Import(Params->getRAngleLoc()),
1096 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1097 switch (From.getKind()) {
1098 case TemplateArgument::Null:
1099 return TemplateArgument();
1101 case TemplateArgument::Type: {
1102 QualType ToType = Importer.Import(From.getAsType());
1103 if (ToType.isNull())
1104 return TemplateArgument();
1105 return TemplateArgument(ToType);
1108 case TemplateArgument::Integral: {
1109 QualType ToType = Importer.Import(From.getIntegralType());
1110 if (ToType.isNull())
1111 return TemplateArgument();
1112 return TemplateArgument(From, ToType);
1115 case TemplateArgument::Declaration: {
1116 ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
1117 QualType ToType = Importer.Import(From.getParamTypeForDecl());
1118 if (!To || ToType.isNull())
1119 return TemplateArgument();
1120 return TemplateArgument(To, ToType);
1123 case TemplateArgument::NullPtr: {
1124 QualType ToType = Importer.Import(From.getNullPtrType());
1125 if (ToType.isNull())
1126 return TemplateArgument();
1127 return TemplateArgument(ToType, /*isNullPtr*/true);
1130 case TemplateArgument::Template: {
1131 TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
1132 if (ToTemplate.isNull())
1133 return TemplateArgument();
1135 return TemplateArgument(ToTemplate);
1138 case TemplateArgument::TemplateExpansion: {
1139 TemplateName ToTemplate
1140 = Importer.Import(From.getAsTemplateOrTemplatePattern());
1141 if (ToTemplate.isNull())
1142 return TemplateArgument();
1144 return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
1147 case TemplateArgument::Expression:
1148 if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
1149 return TemplateArgument(ToExpr);
1150 return TemplateArgument();
1152 case TemplateArgument::Pack: {
1153 SmallVector<TemplateArgument, 2> ToPack;
1154 ToPack.reserve(From.pack_size());
1155 if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
1156 return TemplateArgument();
1158 return TemplateArgument(
1159 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
1163 llvm_unreachable("Invalid template argument kind");
1166 TemplateArgumentLoc ASTNodeImporter::ImportTemplateArgumentLoc(
1167 const TemplateArgumentLoc &TALoc, bool &Error) {
1169 TemplateArgument Arg = ImportTemplateArgument(TALoc.getArgument());
1170 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
1171 TemplateArgumentLocInfo ToInfo;
1172 if (Arg.getKind() == TemplateArgument::Expression) {
1173 Expr *E = Importer.Import(FromInfo.getAsExpr());
1174 ToInfo = TemplateArgumentLocInfo(E);
1177 } else if (Arg.getKind() == TemplateArgument::Type) {
1178 if (TypeSourceInfo *TSI = Importer.Import(FromInfo.getAsTypeSourceInfo()))
1179 ToInfo = TemplateArgumentLocInfo(TSI);
1183 ToInfo = TemplateArgumentLocInfo(
1184 Importer.Import(FromInfo.getTemplateQualifierLoc()),
1185 Importer.Import(FromInfo.getTemplateNameLoc()),
1186 Importer.Import(FromInfo.getTemplateEllipsisLoc()));
1188 return TemplateArgumentLoc(Arg, ToInfo);
1191 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
1192 unsigned NumFromArgs,
1193 SmallVectorImpl<TemplateArgument> &ToArgs) {
1194 for (unsigned I = 0; I != NumFromArgs; ++I) {
1195 TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
1196 if (To.isNull() && !FromArgs[I].isNull())
1199 ToArgs.push_back(To);
1205 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1206 RecordDecl *ToRecord, bool Complain) {
1207 // Eliminate a potential failure point where we attempt to re-import
1208 // something we're trying to import while completing ToRecord.
1209 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1211 RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1213 ToRecord = ToOriginRecord;
1216 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1217 ToRecord->getASTContext(),
1218 Importer.getNonEquivalentDecls(),
1220 return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
1223 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
1225 StructuralEquivalenceContext Ctx(
1226 Importer.getFromContext(), Importer.getToContext(),
1227 Importer.getNonEquivalentDecls(), false, Complain);
1228 return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
1231 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1232 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1233 Importer.getToContext(),
1234 Importer.getNonEquivalentDecls());
1235 return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
1238 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
1239 EnumConstantDecl *ToEC)
1241 const llvm::APSInt &FromVal = FromEC->getInitVal();
1242 const llvm::APSInt &ToVal = ToEC->getInitVal();
1244 return FromVal.isSigned() == ToVal.isSigned() &&
1245 FromVal.getBitWidth() == ToVal.getBitWidth() &&
1249 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
1250 ClassTemplateDecl *To) {
1251 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1252 Importer.getToContext(),
1253 Importer.getNonEquivalentDecls());
1254 return Ctx.IsStructurallyEquivalent(From, To);
1257 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
1258 VarTemplateDecl *To) {
1259 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1260 Importer.getToContext(),
1261 Importer.getNonEquivalentDecls());
1262 return Ctx.IsStructurallyEquivalent(From, To);
1265 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
1266 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1267 << D->getDeclKindName();
1271 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
1272 TranslationUnitDecl *ToD =
1273 Importer.getToContext().getTranslationUnitDecl();
1275 Importer.Imported(D, ToD);
1280 Decl *ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
1282 SourceLocation Loc = Importer.Import(D->getLocation());
1283 SourceLocation ColonLoc = Importer.Import(D->getColonLoc());
1285 // Import the context of this declaration.
1286 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1290 AccessSpecDecl *accessSpecDecl
1291 = AccessSpecDecl::Create(Importer.getToContext(), D->getAccess(),
1294 if (!accessSpecDecl)
1297 // Lexical DeclContext and Semantic DeclContext
1298 // is always the same for the accessSpec.
1299 accessSpecDecl->setLexicalDeclContext(DC);
1300 DC->addDeclInternal(accessSpecDecl);
1302 return accessSpecDecl;
1305 Decl *ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
1306 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
1310 DeclContext *LexicalDC = DC;
1312 // Import the location of this declaration.
1313 SourceLocation Loc = Importer.Import(D->getLocation());
1315 Expr *AssertExpr = Importer.Import(D->getAssertExpr());
1319 StringLiteral *FromMsg = D->getMessage();
1320 StringLiteral *ToMsg = cast_or_null<StringLiteral>(Importer.Import(FromMsg));
1321 if (!ToMsg && FromMsg)
1324 StaticAssertDecl *ToD = StaticAssertDecl::Create(
1325 Importer.getToContext(), DC, Loc, AssertExpr, ToMsg,
1326 Importer.Import(D->getRParenLoc()), D->isFailed());
1328 ToD->setLexicalDeclContext(LexicalDC);
1329 LexicalDC->addDeclInternal(ToD);
1330 Importer.Imported(D, ToD);
1334 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
1335 // Import the major distinguishing characteristics of this namespace.
1336 DeclContext *DC, *LexicalDC;
1337 DeclarationName Name;
1340 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1345 NamespaceDecl *MergeWithNamespace = nullptr;
1347 // This is an anonymous namespace. Adopt an existing anonymous
1348 // namespace if we can.
1349 // FIXME: Not testable.
1350 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1351 MergeWithNamespace = TU->getAnonymousNamespace();
1353 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
1355 SmallVector<NamedDecl *, 4> ConflictingDecls;
1356 SmallVector<NamedDecl *, 2> FoundDecls;
1357 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1358 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1359 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
1362 if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
1363 MergeWithNamespace = FoundNS;
1364 ConflictingDecls.clear();
1368 ConflictingDecls.push_back(FoundDecls[I]);
1371 if (!ConflictingDecls.empty()) {
1372 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
1373 ConflictingDecls.data(),
1374 ConflictingDecls.size());
1378 // Create the "to" namespace, if needed.
1379 NamespaceDecl *ToNamespace = MergeWithNamespace;
1381 ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
1383 Importer.Import(D->getLocStart()),
1384 Loc, Name.getAsIdentifierInfo(),
1385 /*PrevDecl=*/nullptr);
1386 ToNamespace->setLexicalDeclContext(LexicalDC);
1387 LexicalDC->addDeclInternal(ToNamespace);
1389 // If this is an anonymous namespace, register it as the anonymous
1390 // namespace within its context.
1392 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
1393 TU->setAnonymousNamespace(ToNamespace);
1395 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
1398 Importer.Imported(D, ToNamespace);
1400 ImportDeclContext(D);
1405 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
1406 // Import the major distinguishing characteristics of this typedef.
1407 DeclContext *DC, *LexicalDC;
1408 DeclarationName Name;
1411 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1416 // If this typedef is not in block scope, determine whether we've
1417 // seen a typedef with the same name (that we can merge with) or any
1418 // other entity by that name (which name lookup could conflict with).
1419 if (!DC->isFunctionOrMethod()) {
1420 SmallVector<NamedDecl *, 4> ConflictingDecls;
1421 unsigned IDNS = Decl::IDNS_Ordinary;
1422 SmallVector<NamedDecl *, 2> FoundDecls;
1423 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1424 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1425 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1427 if (TypedefNameDecl *FoundTypedef =
1428 dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
1429 if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
1430 FoundTypedef->getUnderlyingType()))
1431 return Importer.Imported(D, FoundTypedef);
1434 ConflictingDecls.push_back(FoundDecls[I]);
1437 if (!ConflictingDecls.empty()) {
1438 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1439 ConflictingDecls.data(),
1440 ConflictingDecls.size());
1446 // Import the underlying type of this typedef;
1447 QualType T = Importer.Import(D->getUnderlyingType());
1451 // Create the new typedef node.
1452 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1453 SourceLocation StartL = Importer.Import(D->getLocStart());
1454 TypedefNameDecl *ToTypedef;
1456 ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
1458 Name.getAsIdentifierInfo(),
1461 ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
1463 Name.getAsIdentifierInfo(),
1466 ToTypedef->setAccess(D->getAccess());
1467 ToTypedef->setLexicalDeclContext(LexicalDC);
1468 Importer.Imported(D, ToTypedef);
1469 LexicalDC->addDeclInternal(ToTypedef);
1474 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
1475 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
1478 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
1479 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
1482 Decl *ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
1483 // Import the major distinguishing characteristics of this label.
1484 DeclContext *DC, *LexicalDC;
1485 DeclarationName Name;
1488 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1493 assert(LexicalDC->isFunctionOrMethod());
1495 LabelDecl *ToLabel = D->isGnuLocal()
1496 ? LabelDecl::Create(Importer.getToContext(),
1497 DC, Importer.Import(D->getLocation()),
1498 Name.getAsIdentifierInfo(),
1499 Importer.Import(D->getLocStart()))
1500 : LabelDecl::Create(Importer.getToContext(),
1501 DC, Importer.Import(D->getLocation()),
1502 Name.getAsIdentifierInfo());
1503 Importer.Imported(D, ToLabel);
1505 LabelStmt *Label = cast_or_null<LabelStmt>(Importer.Import(D->getStmt()));
1509 ToLabel->setStmt(Label);
1510 ToLabel->setLexicalDeclContext(LexicalDC);
1511 LexicalDC->addDeclInternal(ToLabel);
1515 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
1516 // Import the major distinguishing characteristics of this enum.
1517 DeclContext *DC, *LexicalDC;
1518 DeclarationName Name;
1521 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1526 // Figure out what enum name we're looking for.
1527 unsigned IDNS = Decl::IDNS_Tag;
1528 DeclarationName SearchName = Name;
1529 if (!SearchName && D->getTypedefNameForAnonDecl()) {
1530 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
1531 IDNS = Decl::IDNS_Ordinary;
1532 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
1533 IDNS |= Decl::IDNS_Ordinary;
1535 // We may already have an enum of the same name; try to find and match it.
1536 if (!DC->isFunctionOrMethod() && SearchName) {
1537 SmallVector<NamedDecl *, 4> ConflictingDecls;
1538 SmallVector<NamedDecl *, 2> FoundDecls;
1539 DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
1540 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1541 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1544 Decl *Found = FoundDecls[I];
1545 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
1546 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1547 Found = Tag->getDecl();
1550 if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
1551 if (IsStructuralMatch(D, FoundEnum))
1552 return Importer.Imported(D, FoundEnum);
1555 ConflictingDecls.push_back(FoundDecls[I]);
1558 if (!ConflictingDecls.empty()) {
1559 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1560 ConflictingDecls.data(),
1561 ConflictingDecls.size());
1565 // Create the enum declaration.
1566 EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
1567 Importer.Import(D->getLocStart()),
1568 Loc, Name.getAsIdentifierInfo(), nullptr,
1569 D->isScoped(), D->isScopedUsingClassTag(),
1571 // Import the qualifier, if any.
1572 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
1573 D2->setAccess(D->getAccess());
1574 D2->setLexicalDeclContext(LexicalDC);
1575 Importer.Imported(D, D2);
1576 LexicalDC->addDeclInternal(D2);
1578 // Import the integer type.
1579 QualType ToIntegerType = Importer.Import(D->getIntegerType());
1580 if (ToIntegerType.isNull())
1582 D2->setIntegerType(ToIntegerType);
1584 // Import the definition
1585 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
1591 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
1592 // If this record has a definition in the translation unit we're coming from,
1593 // but this particular declaration is not that definition, import the
1594 // definition and map to that.
1595 TagDecl *Definition = D->getDefinition();
1596 if (Definition && Definition != D) {
1597 Decl *ImportedDef = Importer.Import(Definition);
1601 return Importer.Imported(D, ImportedDef);
1604 // Import the major distinguishing characteristics of this record.
1605 DeclContext *DC, *LexicalDC;
1606 DeclarationName Name;
1609 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1614 // Figure out what structure name we're looking for.
1615 unsigned IDNS = Decl::IDNS_Tag;
1616 DeclarationName SearchName = Name;
1617 if (!SearchName && D->getTypedefNameForAnonDecl()) {
1618 SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
1619 IDNS = Decl::IDNS_Ordinary;
1620 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
1621 IDNS |= Decl::IDNS_Ordinary;
1623 // We may already have a record of the same name; try to find and match it.
1624 RecordDecl *AdoptDecl = nullptr;
1625 RecordDecl *PrevDecl = nullptr;
1626 if (!DC->isFunctionOrMethod()) {
1627 SmallVector<NamedDecl *, 4> ConflictingDecls;
1628 SmallVector<NamedDecl *, 2> FoundDecls;
1629 DC->getRedeclContext()->localUncachedLookup(SearchName, FoundDecls);
1631 if (!FoundDecls.empty()) {
1632 // We're going to have to compare D against potentially conflicting Decls, so complete it.
1633 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
1634 D->getASTContext().getExternalSource()->CompleteType(D);
1637 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1638 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1641 Decl *Found = FoundDecls[I];
1642 if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
1643 if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
1644 Found = Tag->getDecl();
1647 if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
1648 if (D->isAnonymousStructOrUnion() &&
1649 FoundRecord->isAnonymousStructOrUnion()) {
1650 // If both anonymous structs/unions are in a record context, make sure
1651 // they occur in the same location in the context records.
1652 if (Optional<unsigned> Index1 =
1653 StructuralEquivalenceContext::findUntaggedStructOrUnionIndex(
1655 if (Optional<unsigned> Index2 = StructuralEquivalenceContext::
1656 findUntaggedStructOrUnionIndex(FoundRecord)) {
1657 if (*Index1 != *Index2)
1663 PrevDecl = FoundRecord;
1665 if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
1666 if ((SearchName && !D->isCompleteDefinition())
1667 || (D->isCompleteDefinition() &&
1668 D->isAnonymousStructOrUnion()
1669 == FoundDef->isAnonymousStructOrUnion() &&
1670 IsStructuralMatch(D, FoundDef))) {
1671 // The record types structurally match, or the "from" translation
1672 // unit only had a forward declaration anyway; call it the same
1674 // FIXME: For C++, we should also merge methods here.
1675 return Importer.Imported(D, FoundDef);
1677 } else if (!D->isCompleteDefinition()) {
1678 // We have a forward declaration of this type, so adopt that forward
1679 // declaration rather than building a new one.
1681 // If one or both can be completed from external storage then try one
1682 // last time to complete and compare them before doing this.
1684 if (FoundRecord->hasExternalLexicalStorage() &&
1685 !FoundRecord->isCompleteDefinition())
1686 FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
1687 if (D->hasExternalLexicalStorage())
1688 D->getASTContext().getExternalSource()->CompleteType(D);
1690 if (FoundRecord->isCompleteDefinition() &&
1691 D->isCompleteDefinition() &&
1692 !IsStructuralMatch(D, FoundRecord))
1695 AdoptDecl = FoundRecord;
1697 } else if (!SearchName) {
1702 ConflictingDecls.push_back(FoundDecls[I]);
1705 if (!ConflictingDecls.empty() && SearchName) {
1706 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1707 ConflictingDecls.data(),
1708 ConflictingDecls.size());
1712 // Create the record declaration.
1713 RecordDecl *D2 = AdoptDecl;
1714 SourceLocation StartLoc = Importer.Import(D->getLocStart());
1716 CXXRecordDecl *D2CXX = nullptr;
1717 if (CXXRecordDecl *DCXX = llvm::dyn_cast<CXXRecordDecl>(D)) {
1718 if (DCXX->isLambda()) {
1719 TypeSourceInfo *TInfo = Importer.Import(DCXX->getLambdaTypeInfo());
1720 D2CXX = CXXRecordDecl::CreateLambda(Importer.getToContext(),
1722 DCXX->isDependentLambda(),
1723 DCXX->isGenericLambda(),
1724 DCXX->getLambdaCaptureDefault());
1725 Decl *CDecl = Importer.Import(DCXX->getLambdaContextDecl());
1726 if (DCXX->getLambdaContextDecl() && !CDecl)
1728 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), CDecl);
1729 } else if (DCXX->isInjectedClassName()) {
1730 // We have to be careful to do a similar dance to the one in
1731 // Sema::ActOnStartCXXMemberDeclarations
1732 CXXRecordDecl *const PrevDecl = nullptr;
1733 const bool DelayTypeCreation = true;
1734 D2CXX = CXXRecordDecl::Create(
1735 Importer.getToContext(), D->getTagKind(), DC, StartLoc, Loc,
1736 Name.getAsIdentifierInfo(), PrevDecl, DelayTypeCreation);
1737 Importer.getToContext().getTypeDeclType(
1738 D2CXX, llvm::dyn_cast<CXXRecordDecl>(DC));
1740 D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
1743 Name.getAsIdentifierInfo());
1746 D2->setAccess(D->getAccess());
1748 D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
1749 DC, StartLoc, Loc, Name.getAsIdentifierInfo());
1752 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
1753 D2->setLexicalDeclContext(LexicalDC);
1754 LexicalDC->addDeclInternal(D2);
1755 if (D->isAnonymousStructOrUnion())
1756 D2->setAnonymousStructOrUnion(true);
1758 // FIXME: do this for all Redeclarables, not just RecordDecls.
1759 D2->setPreviousDecl(PrevDecl);
1763 Importer.Imported(D, D2);
1765 if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
1771 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
1772 // Import the major distinguishing characteristics of this enumerator.
1773 DeclContext *DC, *LexicalDC;
1774 DeclarationName Name;
1777 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1782 QualType T = Importer.Import(D->getType());
1786 // Determine whether there are any other declarations with the same name and
1787 // in the same context.
1788 if (!LexicalDC->isFunctionOrMethod()) {
1789 SmallVector<NamedDecl *, 4> ConflictingDecls;
1790 unsigned IDNS = Decl::IDNS_Ordinary;
1791 SmallVector<NamedDecl *, 2> FoundDecls;
1792 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1793 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1794 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1797 if (EnumConstantDecl *FoundEnumConstant
1798 = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
1799 if (IsStructuralMatch(D, FoundEnumConstant))
1800 return Importer.Imported(D, FoundEnumConstant);
1803 ConflictingDecls.push_back(FoundDecls[I]);
1806 if (!ConflictingDecls.empty()) {
1807 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1808 ConflictingDecls.data(),
1809 ConflictingDecls.size());
1815 Expr *Init = Importer.Import(D->getInitExpr());
1816 if (D->getInitExpr() && !Init)
1819 EnumConstantDecl *ToEnumerator
1820 = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
1821 Name.getAsIdentifierInfo(), T,
1822 Init, D->getInitVal());
1823 ToEnumerator->setAccess(D->getAccess());
1824 ToEnumerator->setLexicalDeclContext(LexicalDC);
1825 Importer.Imported(D, ToEnumerator);
1826 LexicalDC->addDeclInternal(ToEnumerator);
1827 return ToEnumerator;
1830 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
1831 // Import the major distinguishing characteristics of this function.
1832 DeclContext *DC, *LexicalDC;
1833 DeclarationName Name;
1836 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
1841 // Try to find a function in our own ("to") context with the same name, same
1842 // type, and in the same context as the function we're importing.
1843 if (!LexicalDC->isFunctionOrMethod()) {
1844 SmallVector<NamedDecl *, 4> ConflictingDecls;
1845 unsigned IDNS = Decl::IDNS_Ordinary;
1846 SmallVector<NamedDecl *, 2> FoundDecls;
1847 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
1848 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
1849 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
1852 if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
1853 if (FoundFunction->hasExternalFormalLinkage() &&
1854 D->hasExternalFormalLinkage()) {
1855 if (Importer.IsStructurallyEquivalent(D->getType(),
1856 FoundFunction->getType())) {
1857 // FIXME: Actually try to merge the body and other attributes.
1858 return Importer.Imported(D, FoundFunction);
1861 // FIXME: Check for overloading more carefully, e.g., by boosting
1862 // Sema::IsOverload out to the AST library.
1864 // Function overloading is okay in C++.
1865 if (Importer.getToContext().getLangOpts().CPlusPlus)
1868 // Complain about inconsistent function types.
1869 Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
1870 << Name << D->getType() << FoundFunction->getType();
1871 Importer.ToDiag(FoundFunction->getLocation(),
1872 diag::note_odr_value_here)
1873 << FoundFunction->getType();
1877 ConflictingDecls.push_back(FoundDecls[I]);
1880 if (!ConflictingDecls.empty()) {
1881 Name = Importer.HandleNameConflict(Name, DC, IDNS,
1882 ConflictingDecls.data(),
1883 ConflictingDecls.size());
1889 DeclarationNameInfo NameInfo(Name, Loc);
1890 // Import additional name location/type info.
1891 ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
1893 QualType FromTy = D->getType();
1894 bool usedDifferentExceptionSpec = false;
1896 if (const FunctionProtoType *
1897 FromFPT = D->getType()->getAs<FunctionProtoType>()) {
1898 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
1899 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
1900 // FunctionDecl that we are importing the FunctionProtoType for.
1901 // To avoid an infinite recursion when importing, create the FunctionDecl
1902 // with a simplified function type and update it afterwards.
1903 if (FromEPI.ExceptionSpec.SourceDecl ||
1904 FromEPI.ExceptionSpec.SourceTemplate ||
1905 FromEPI.ExceptionSpec.NoexceptExpr) {
1906 FunctionProtoType::ExtProtoInfo DefaultEPI;
1907 FromTy = Importer.getFromContext().getFunctionType(
1908 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
1909 usedDifferentExceptionSpec = true;
1914 QualType T = Importer.Import(FromTy);
1918 // Import the function parameters.
1919 SmallVector<ParmVarDecl *, 8> Parameters;
1920 for (auto P : D->parameters()) {
1921 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
1925 Parameters.push_back(ToP);
1928 // Create the imported function.
1929 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
1930 FunctionDecl *ToFunction = nullptr;
1931 SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
1932 if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
1933 ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
1934 cast<CXXRecordDecl>(DC),
1937 FromConstructor->isExplicit(),
1938 D->isInlineSpecified(),
1941 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
1942 SmallVector<CXXCtorInitializer *, 4> CtorInitializers;
1943 for (CXXCtorInitializer *I : FromConstructor->inits()) {
1944 CXXCtorInitializer *ToI =
1945 cast_or_null<CXXCtorInitializer>(Importer.Import(I));
1948 CtorInitializers.push_back(ToI);
1950 CXXCtorInitializer **Memory =
1951 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
1952 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
1953 CXXConstructorDecl *ToCtor = llvm::cast<CXXConstructorDecl>(ToFunction);
1954 ToCtor->setCtorInitializers(Memory);
1955 ToCtor->setNumCtorInitializers(NumInitializers);
1957 } else if (isa<CXXDestructorDecl>(D)) {
1958 ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
1959 cast<CXXRecordDecl>(DC),
1962 D->isInlineSpecified(),
1964 } else if (CXXConversionDecl *FromConversion
1965 = dyn_cast<CXXConversionDecl>(D)) {
1966 ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
1967 cast<CXXRecordDecl>(DC),
1970 D->isInlineSpecified(),
1971 FromConversion->isExplicit(),
1973 Importer.Import(D->getLocEnd()));
1974 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
1975 ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
1976 cast<CXXRecordDecl>(DC),
1979 Method->getStorageClass(),
1980 Method->isInlineSpecified(),
1982 Importer.Import(D->getLocEnd()));
1984 ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
1986 NameInfo, T, TInfo, D->getStorageClass(),
1987 D->isInlineSpecified(),
1988 D->hasWrittenPrototype(),
1992 // Import the qualifier, if any.
1993 ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
1994 ToFunction->setAccess(D->getAccess());
1995 ToFunction->setLexicalDeclContext(LexicalDC);
1996 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
1997 ToFunction->setTrivial(D->isTrivial());
1998 ToFunction->setPure(D->isPure());
1999 Importer.Imported(D, ToFunction);
2001 // Set the parameters.
2002 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2003 Parameters[I]->setOwningFunction(ToFunction);
2004 ToFunction->addDeclInternal(Parameters[I]);
2006 ToFunction->setParams(Parameters);
2008 if (usedDifferentExceptionSpec) {
2009 // Update FunctionProtoType::ExtProtoInfo.
2010 QualType T = Importer.Import(D->getType());
2013 ToFunction->setType(T);
2016 // Import the body, if any.
2017 if (Stmt *FromBody = D->getBody()) {
2018 if (Stmt *ToBody = Importer.Import(FromBody)) {
2019 ToFunction->setBody(ToBody);
2023 // FIXME: Other bits to merge?
2025 // Add this function to the lexical context.
2026 LexicalDC->addDeclInternal(ToFunction);
2031 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2032 return VisitFunctionDecl(D);
2035 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2036 return VisitCXXMethodDecl(D);
2039 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2040 return VisitCXXMethodDecl(D);
2043 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2044 return VisitCXXMethodDecl(D);
2047 static unsigned getFieldIndex(Decl *F) {
2048 RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2053 for (const auto *D : Owner->noload_decls()) {
2057 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2064 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2065 // Import the major distinguishing characteristics of a variable.
2066 DeclContext *DC, *LexicalDC;
2067 DeclarationName Name;
2070 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2075 // Determine whether we've already imported this field.
2076 SmallVector<NamedDecl *, 2> FoundDecls;
2077 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2078 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2079 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2080 // For anonymous fields, match up by index.
2081 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2084 if (Importer.IsStructurallyEquivalent(D->getType(),
2085 FoundField->getType())) {
2086 Importer.Imported(D, FoundField);
2090 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2091 << Name << D->getType() << FoundField->getType();
2092 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2093 << FoundField->getType();
2099 QualType T = Importer.Import(D->getType());
2103 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2104 Expr *BitWidth = Importer.Import(D->getBitWidth());
2105 if (!BitWidth && D->getBitWidth())
2108 FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2109 Importer.Import(D->getInnerLocStart()),
2110 Loc, Name.getAsIdentifierInfo(),
2111 T, TInfo, BitWidth, D->isMutable(),
2112 D->getInClassInitStyle());
2113 ToField->setAccess(D->getAccess());
2114 ToField->setLexicalDeclContext(LexicalDC);
2115 if (Expr *FromInitializer = D->getInClassInitializer()) {
2116 Expr *ToInitializer = Importer.Import(FromInitializer);
2118 ToField->setInClassInitializer(ToInitializer);
2122 ToField->setImplicit(D->isImplicit());
2123 Importer.Imported(D, ToField);
2124 LexicalDC->addDeclInternal(ToField);
2128 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
2129 // Import the major distinguishing characteristics of a variable.
2130 DeclContext *DC, *LexicalDC;
2131 DeclarationName Name;
2134 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2139 // Determine whether we've already imported this field.
2140 SmallVector<NamedDecl *, 2> FoundDecls;
2141 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2142 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2143 if (IndirectFieldDecl *FoundField
2144 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
2145 // For anonymous indirect fields, match up by index.
2146 if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2149 if (Importer.IsStructurallyEquivalent(D->getType(),
2150 FoundField->getType(),
2152 Importer.Imported(D, FoundField);
2156 // If there are more anonymous fields to check, continue.
2157 if (!Name && I < N-1)
2160 Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2161 << Name << D->getType() << FoundField->getType();
2162 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2163 << FoundField->getType();
2169 QualType T = Importer.Import(D->getType());
2173 NamedDecl **NamedChain =
2174 new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
2177 for (auto *PI : D->chain()) {
2178 Decl *D = Importer.Import(PI);
2181 NamedChain[i++] = cast<NamedDecl>(D);
2184 IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
2185 Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
2186 {NamedChain, D->getChainingSize()});
2188 for (const auto *Attr : D->attrs())
2189 ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
2191 ToIndirectField->setAccess(D->getAccess());
2192 ToIndirectField->setLexicalDeclContext(LexicalDC);
2193 Importer.Imported(D, ToIndirectField);
2194 LexicalDC->addDeclInternal(ToIndirectField);
2195 return ToIndirectField;
2198 Decl *ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
2199 // Import the major distinguishing characteristics of a declaration.
2200 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2201 DeclContext *LexicalDC = D->getDeclContext() == D->getLexicalDeclContext()
2202 ? DC : Importer.ImportContext(D->getLexicalDeclContext());
2203 if (!DC || !LexicalDC)
2206 // Determine whether we've already imported this decl.
2207 // FriendDecl is not a NamedDecl so we cannot use localUncachedLookup.
2208 auto *RD = cast<CXXRecordDecl>(DC);
2209 FriendDecl *ImportedFriend = RD->getFirstFriend();
2210 StructuralEquivalenceContext Context(
2211 Importer.getFromContext(), Importer.getToContext(),
2212 Importer.getNonEquivalentDecls(), false, false);
2214 while (ImportedFriend) {
2215 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
2216 if (Context.IsStructurallyEquivalent(D->getFriendDecl(),
2217 ImportedFriend->getFriendDecl()))
2218 return Importer.Imported(D, ImportedFriend);
2220 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
2221 if (Importer.IsStructurallyEquivalent(
2222 D->getFriendType()->getType(),
2223 ImportedFriend->getFriendType()->getType(), true))
2224 return Importer.Imported(D, ImportedFriend);
2226 ImportedFriend = ImportedFriend->getNextFriend();
2229 // Not found. Create it.
2230 FriendDecl::FriendUnion ToFU;
2231 if (NamedDecl *FriendD = D->getFriendDecl())
2232 ToFU = cast_or_null<NamedDecl>(Importer.Import(FriendD));
2234 ToFU = Importer.Import(D->getFriendType());
2238 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
2239 TemplateParameterList **FromTPLists =
2240 D->getTrailingObjects<TemplateParameterList *>();
2241 for (unsigned I = 0; I < D->NumTPLists; I++) {
2242 TemplateParameterList *List = ImportTemplateParameterList(FromTPLists[I]);
2245 ToTPLists[I] = List;
2248 FriendDecl *FrD = FriendDecl::Create(Importer.getToContext(), DC,
2249 Importer.Import(D->getLocation()),
2250 ToFU, Importer.Import(D->getFriendLoc()),
2253 Importer.Imported(D, FrD);
2254 RD->pushFriendDecl(FrD);
2256 FrD->setAccess(D->getAccess());
2257 FrD->setLexicalDeclContext(LexicalDC);
2258 LexicalDC->addDeclInternal(FrD);
2262 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
2263 // Import the major distinguishing characteristics of an ivar.
2264 DeclContext *DC, *LexicalDC;
2265 DeclarationName Name;
2268 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2273 // Determine whether we've already imported this ivar
2274 SmallVector<NamedDecl *, 2> FoundDecls;
2275 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2276 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2277 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
2278 if (Importer.IsStructurallyEquivalent(D->getType(),
2279 FoundIvar->getType())) {
2280 Importer.Imported(D, FoundIvar);
2284 Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
2285 << Name << D->getType() << FoundIvar->getType();
2286 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
2287 << FoundIvar->getType();
2293 QualType T = Importer.Import(D->getType());
2297 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2298 Expr *BitWidth = Importer.Import(D->getBitWidth());
2299 if (!BitWidth && D->getBitWidth())
2302 ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
2303 cast<ObjCContainerDecl>(DC),
2304 Importer.Import(D->getInnerLocStart()),
2305 Loc, Name.getAsIdentifierInfo(),
2306 T, TInfo, D->getAccessControl(),
2307 BitWidth, D->getSynthesize());
2308 ToIvar->setLexicalDeclContext(LexicalDC);
2309 Importer.Imported(D, ToIvar);
2310 LexicalDC->addDeclInternal(ToIvar);
2315 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
2316 // Import the major distinguishing characteristics of a variable.
2317 DeclContext *DC, *LexicalDC;
2318 DeclarationName Name;
2321 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2326 // Try to find a variable in our own ("to") context with the same name and
2327 // in the same context as the variable we're importing.
2328 if (D->isFileVarDecl()) {
2329 VarDecl *MergeWithVar = nullptr;
2330 SmallVector<NamedDecl *, 4> ConflictingDecls;
2331 unsigned IDNS = Decl::IDNS_Ordinary;
2332 SmallVector<NamedDecl *, 2> FoundDecls;
2333 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2334 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2335 if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2338 if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
2339 // We have found a variable that we may need to merge with. Check it.
2340 if (FoundVar->hasExternalFormalLinkage() &&
2341 D->hasExternalFormalLinkage()) {
2342 if (Importer.IsStructurallyEquivalent(D->getType(),
2343 FoundVar->getType())) {
2344 MergeWithVar = FoundVar;
2348 const ArrayType *FoundArray
2349 = Importer.getToContext().getAsArrayType(FoundVar->getType());
2350 const ArrayType *TArray
2351 = Importer.getToContext().getAsArrayType(D->getType());
2352 if (FoundArray && TArray) {
2353 if (isa<IncompleteArrayType>(FoundArray) &&
2354 isa<ConstantArrayType>(TArray)) {
2356 QualType T = Importer.Import(D->getType());
2360 FoundVar->setType(T);
2361 MergeWithVar = FoundVar;
2363 } else if (isa<IncompleteArrayType>(TArray) &&
2364 isa<ConstantArrayType>(FoundArray)) {
2365 MergeWithVar = FoundVar;
2370 Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
2371 << Name << D->getType() << FoundVar->getType();
2372 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
2373 << FoundVar->getType();
2377 ConflictingDecls.push_back(FoundDecls[I]);
2381 // An equivalent variable with external linkage has been found. Link
2382 // the two declarations, then merge them.
2383 Importer.Imported(D, MergeWithVar);
2385 if (VarDecl *DDef = D->getDefinition()) {
2386 if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
2387 Importer.ToDiag(ExistingDef->getLocation(),
2388 diag::err_odr_variable_multiple_def)
2390 Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
2392 Expr *Init = Importer.Import(DDef->getInit());
2393 MergeWithVar->setInit(Init);
2394 if (DDef->isInitKnownICE()) {
2395 EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
2396 Eval->CheckedICE = true;
2397 Eval->IsICE = DDef->isInitICE();
2402 return MergeWithVar;
2405 if (!ConflictingDecls.empty()) {
2406 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2407 ConflictingDecls.data(),
2408 ConflictingDecls.size());
2415 QualType T = Importer.Import(D->getType());
2419 // Create the imported variable.
2420 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2421 VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
2422 Importer.Import(D->getInnerLocStart()),
2423 Loc, Name.getAsIdentifierInfo(),
2425 D->getStorageClass());
2426 ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2427 ToVar->setAccess(D->getAccess());
2428 ToVar->setLexicalDeclContext(LexicalDC);
2429 Importer.Imported(D, ToVar);
2430 LexicalDC->addDeclInternal(ToVar);
2432 if (!D->isFileVarDecl() &&
2436 // Merge the initializer.
2437 if (ImportDefinition(D, ToVar))
2440 if (D->isConstexpr())
2441 ToVar->setConstexpr(true);
2446 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
2447 // Parameters are created in the translation unit's context, then moved
2448 // into the function declaration's context afterward.
2449 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2451 // Import the name of this declaration.
2452 DeclarationName Name = Importer.Import(D->getDeclName());
2453 if (D->getDeclName() && !Name)
2456 // Import the location of this declaration.
2457 SourceLocation Loc = Importer.Import(D->getLocation());
2459 // Import the parameter's type.
2460 QualType T = Importer.Import(D->getType());
2464 // Create the imported parameter.
2465 auto *ToParm = ImplicitParamDecl::Create(Importer.getToContext(), DC, Loc,
2466 Name.getAsIdentifierInfo(), T,
2467 D->getParameterKind());
2468 return Importer.Imported(D, ToParm);
2471 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
2472 // Parameters are created in the translation unit's context, then moved
2473 // into the function declaration's context afterward.
2474 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
2476 // Import the name of this declaration.
2477 DeclarationName Name = Importer.Import(D->getDeclName());
2478 if (D->getDeclName() && !Name)
2481 // Import the location of this declaration.
2482 SourceLocation Loc = Importer.Import(D->getLocation());
2484 // Import the parameter's type.
2485 QualType T = Importer.Import(D->getType());
2489 // Create the imported parameter.
2490 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2491 ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
2492 Importer.Import(D->getInnerLocStart()),
2493 Loc, Name.getAsIdentifierInfo(),
2494 T, TInfo, D->getStorageClass(),
2495 /*DefaultArg*/ nullptr);
2497 // Set the default argument.
2498 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
2499 ToParm->setKNRPromoted(D->isKNRPromoted());
2501 Expr *ToDefArg = nullptr;
2502 Expr *FromDefArg = nullptr;
2503 if (D->hasUninstantiatedDefaultArg()) {
2504 FromDefArg = D->getUninstantiatedDefaultArg();
2505 ToDefArg = Importer.Import(FromDefArg);
2506 ToParm->setUninstantiatedDefaultArg(ToDefArg);
2507 } else if (D->hasUnparsedDefaultArg()) {
2508 ToParm->setUnparsedDefaultArg();
2509 } else if (D->hasDefaultArg()) {
2510 FromDefArg = D->getDefaultArg();
2511 ToDefArg = Importer.Import(FromDefArg);
2512 ToParm->setDefaultArg(ToDefArg);
2514 if (FromDefArg && !ToDefArg)
2518 ToParm->setIsUsed();
2520 return Importer.Imported(D, ToParm);
2523 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
2524 // Import the major distinguishing characteristics of a method.
2525 DeclContext *DC, *LexicalDC;
2526 DeclarationName Name;
2529 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2534 SmallVector<NamedDecl *, 2> FoundDecls;
2535 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2536 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2537 if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
2538 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
2541 // Check return types.
2542 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
2543 FoundMethod->getReturnType())) {
2544 Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
2545 << D->isInstanceMethod() << Name << D->getReturnType()
2546 << FoundMethod->getReturnType();
2547 Importer.ToDiag(FoundMethod->getLocation(),
2548 diag::note_odr_objc_method_here)
2549 << D->isInstanceMethod() << Name;
2553 // Check the number of parameters.
2554 if (D->param_size() != FoundMethod->param_size()) {
2555 Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
2556 << D->isInstanceMethod() << Name
2557 << D->param_size() << FoundMethod->param_size();
2558 Importer.ToDiag(FoundMethod->getLocation(),
2559 diag::note_odr_objc_method_here)
2560 << D->isInstanceMethod() << Name;
2564 // Check parameter types.
2565 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
2566 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
2567 P != PEnd; ++P, ++FoundP) {
2568 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
2569 (*FoundP)->getType())) {
2570 Importer.FromDiag((*P)->getLocation(),
2571 diag::err_odr_objc_method_param_type_inconsistent)
2572 << D->isInstanceMethod() << Name
2573 << (*P)->getType() << (*FoundP)->getType();
2574 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
2575 << (*FoundP)->getType();
2580 // Check variadic/non-variadic.
2581 // Check the number of parameters.
2582 if (D->isVariadic() != FoundMethod->isVariadic()) {
2583 Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
2584 << D->isInstanceMethod() << Name;
2585 Importer.ToDiag(FoundMethod->getLocation(),
2586 diag::note_odr_objc_method_here)
2587 << D->isInstanceMethod() << Name;
2591 // FIXME: Any other bits we need to merge?
2592 return Importer.Imported(D, FoundMethod);
2596 // Import the result type.
2597 QualType ResultTy = Importer.Import(D->getReturnType());
2598 if (ResultTy.isNull())
2601 TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
2603 ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
2604 Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
2605 Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
2606 D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
2607 D->getImplementationControl(), D->hasRelatedResultType());
2609 // FIXME: When we decide to merge method definitions, we'll need to
2610 // deal with implicit parameters.
2612 // Import the parameters
2613 SmallVector<ParmVarDecl *, 5> ToParams;
2614 for (auto *FromP : D->parameters()) {
2615 ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
2619 ToParams.push_back(ToP);
2622 // Set the parameters.
2623 for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
2624 ToParams[I]->setOwningFunction(ToMethod);
2625 ToMethod->addDeclInternal(ToParams[I]);
2627 SmallVector<SourceLocation, 12> SelLocs;
2628 D->getSelectorLocs(SelLocs);
2629 ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
2631 ToMethod->setLexicalDeclContext(LexicalDC);
2632 Importer.Imported(D, ToMethod);
2633 LexicalDC->addDeclInternal(ToMethod);
2637 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
2638 // Import the major distinguishing characteristics of a category.
2639 DeclContext *DC, *LexicalDC;
2640 DeclarationName Name;
2643 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2648 TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
2652 ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
2653 Importer.getToContext(), DC,
2655 Importer.Import(D->getVarianceLoc()),
2657 Importer.Import(D->getLocation()),
2658 Name.getAsIdentifierInfo(),
2659 Importer.Import(D->getColonLoc()),
2661 Importer.Imported(D, Result);
2662 Result->setLexicalDeclContext(LexicalDC);
2666 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
2667 // Import the major distinguishing characteristics of a category.
2668 DeclContext *DC, *LexicalDC;
2669 DeclarationName Name;
2672 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2677 ObjCInterfaceDecl *ToInterface
2678 = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
2682 // Determine if we've already encountered this category.
2683 ObjCCategoryDecl *MergeWithCategory
2684 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
2685 ObjCCategoryDecl *ToCategory = MergeWithCategory;
2687 ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
2688 Importer.Import(D->getAtStartLoc()),
2690 Importer.Import(D->getCategoryNameLoc()),
2691 Name.getAsIdentifierInfo(),
2693 /*TypeParamList=*/nullptr,
2694 Importer.Import(D->getIvarLBraceLoc()),
2695 Importer.Import(D->getIvarRBraceLoc()));
2696 ToCategory->setLexicalDeclContext(LexicalDC);
2697 LexicalDC->addDeclInternal(ToCategory);
2698 Importer.Imported(D, ToCategory);
2699 // Import the type parameter list after calling Imported, to avoid
2700 // loops when bringing in their DeclContext.
2701 ToCategory->setTypeParamList(ImportObjCTypeParamList(
2702 D->getTypeParamList()));
2705 SmallVector<ObjCProtocolDecl *, 4> Protocols;
2706 SmallVector<SourceLocation, 4> ProtocolLocs;
2707 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
2708 = D->protocol_loc_begin();
2709 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
2710 FromProtoEnd = D->protocol_end();
2711 FromProto != FromProtoEnd;
2712 ++FromProto, ++FromProtoLoc) {
2713 ObjCProtocolDecl *ToProto
2714 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2717 Protocols.push_back(ToProto);
2718 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2721 // FIXME: If we're merging, make sure that the protocol list is the same.
2722 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
2723 ProtocolLocs.data(), Importer.getToContext());
2726 Importer.Imported(D, ToCategory);
2729 // Import all of the members of this category.
2730 ImportDeclContext(D);
2732 // If we have an implementation, import it as well.
2733 if (D->getImplementation()) {
2734 ObjCCategoryImplDecl *Impl
2735 = cast_or_null<ObjCCategoryImplDecl>(
2736 Importer.Import(D->getImplementation()));
2740 ToCategory->setImplementation(Impl);
2746 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
2747 ObjCProtocolDecl *To,
2748 ImportDefinitionKind Kind) {
2749 if (To->getDefinition()) {
2750 if (shouldForceImportDeclContext(Kind))
2751 ImportDeclContext(From);
2755 // Start the protocol definition
2756 To->startDefinition();
2759 SmallVector<ObjCProtocolDecl *, 4> Protocols;
2760 SmallVector<SourceLocation, 4> ProtocolLocs;
2761 ObjCProtocolDecl::protocol_loc_iterator
2762 FromProtoLoc = From->protocol_loc_begin();
2763 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
2764 FromProtoEnd = From->protocol_end();
2765 FromProto != FromProtoEnd;
2766 ++FromProto, ++FromProtoLoc) {
2767 ObjCProtocolDecl *ToProto
2768 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2771 Protocols.push_back(ToProto);
2772 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2775 // FIXME: If we're merging, make sure that the protocol list is the same.
2776 To->setProtocolList(Protocols.data(), Protocols.size(),
2777 ProtocolLocs.data(), Importer.getToContext());
2779 if (shouldForceImportDeclContext(Kind)) {
2780 // Import all of the members of this protocol.
2781 ImportDeclContext(From, /*ForceImport=*/true);
2786 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
2787 // If this protocol has a definition in the translation unit we're coming
2788 // from, but this particular declaration is not that definition, import the
2789 // definition and map to that.
2790 ObjCProtocolDecl *Definition = D->getDefinition();
2791 if (Definition && Definition != D) {
2792 Decl *ImportedDef = Importer.Import(Definition);
2796 return Importer.Imported(D, ImportedDef);
2799 // Import the major distinguishing characteristics of a protocol.
2800 DeclContext *DC, *LexicalDC;
2801 DeclarationName Name;
2804 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2809 ObjCProtocolDecl *MergeWithProtocol = nullptr;
2810 SmallVector<NamedDecl *, 2> FoundDecls;
2811 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2812 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2813 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
2816 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
2820 ObjCProtocolDecl *ToProto = MergeWithProtocol;
2822 ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
2823 Name.getAsIdentifierInfo(), Loc,
2824 Importer.Import(D->getAtStartLoc()),
2825 /*PrevDecl=*/nullptr);
2826 ToProto->setLexicalDeclContext(LexicalDC);
2827 LexicalDC->addDeclInternal(ToProto);
2830 Importer.Imported(D, ToProto);
2832 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
2838 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
2839 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
2840 DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
2842 SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
2843 SourceLocation LangLoc = Importer.Import(D->getLocation());
2845 bool HasBraces = D->hasBraces();
2847 LinkageSpecDecl *ToLinkageSpec =
2848 LinkageSpecDecl::Create(Importer.getToContext(),
2856 SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
2857 ToLinkageSpec->setRBraceLoc(RBraceLoc);
2860 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
2861 LexicalDC->addDeclInternal(ToLinkageSpec);
2863 Importer.Imported(D, ToLinkageSpec);
2865 return ToLinkageSpec;
2868 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
2869 ObjCInterfaceDecl *To,
2870 ImportDefinitionKind Kind) {
2871 if (To->getDefinition()) {
2872 // Check consistency of superclass.
2873 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
2875 FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
2880 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
2881 if ((bool)FromSuper != (bool)ToSuper ||
2882 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
2883 Importer.ToDiag(To->getLocation(),
2884 diag::err_odr_objc_superclass_inconsistent)
2885 << To->getDeclName();
2887 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
2888 << To->getSuperClass()->getDeclName();
2890 Importer.ToDiag(To->getLocation(),
2891 diag::note_odr_objc_missing_superclass);
2892 if (From->getSuperClass())
2893 Importer.FromDiag(From->getSuperClassLoc(),
2894 diag::note_odr_objc_superclass)
2895 << From->getSuperClass()->getDeclName();
2897 Importer.FromDiag(From->getLocation(),
2898 diag::note_odr_objc_missing_superclass);
2901 if (shouldForceImportDeclContext(Kind))
2902 ImportDeclContext(From);
2906 // Start the definition.
2907 To->startDefinition();
2909 // If this class has a superclass, import it.
2910 if (From->getSuperClass()) {
2911 TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
2915 To->setSuperClass(SuperTInfo);
2919 SmallVector<ObjCProtocolDecl *, 4> Protocols;
2920 SmallVector<SourceLocation, 4> ProtocolLocs;
2921 ObjCInterfaceDecl::protocol_loc_iterator
2922 FromProtoLoc = From->protocol_loc_begin();
2924 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
2925 FromProtoEnd = From->protocol_end();
2926 FromProto != FromProtoEnd;
2927 ++FromProto, ++FromProtoLoc) {
2928 ObjCProtocolDecl *ToProto
2929 = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
2932 Protocols.push_back(ToProto);
2933 ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
2936 // FIXME: If we're merging, make sure that the protocol list is the same.
2937 To->setProtocolList(Protocols.data(), Protocols.size(),
2938 ProtocolLocs.data(), Importer.getToContext());
2940 // Import categories. When the categories themselves are imported, they'll
2941 // hook themselves into this interface.
2942 for (auto *Cat : From->known_categories())
2943 Importer.Import(Cat);
2945 // If we have an @implementation, import it as well.
2946 if (From->getImplementation()) {
2947 ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
2948 Importer.Import(From->getImplementation()));
2952 To->setImplementation(Impl);
2955 if (shouldForceImportDeclContext(Kind)) {
2956 // Import all of the members of this class.
2957 ImportDeclContext(From, /*ForceImport=*/true);
2963 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
2967 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
2968 for (auto fromTypeParam : *list) {
2969 auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
2970 Importer.Import(fromTypeParam));
2974 toTypeParams.push_back(toTypeParam);
2977 return ObjCTypeParamList::create(Importer.getToContext(),
2978 Importer.Import(list->getLAngleLoc()),
2980 Importer.Import(list->getRAngleLoc()));
2983 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
2984 // If this class has a definition in the translation unit we're coming from,
2985 // but this particular declaration is not that definition, import the
2986 // definition and map to that.
2987 ObjCInterfaceDecl *Definition = D->getDefinition();
2988 if (Definition && Definition != D) {
2989 Decl *ImportedDef = Importer.Import(Definition);
2993 return Importer.Imported(D, ImportedDef);
2996 // Import the major distinguishing characteristics of an @interface.
2997 DeclContext *DC, *LexicalDC;
2998 DeclarationName Name;
3001 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3006 // Look for an existing interface with the same name.
3007 ObjCInterfaceDecl *MergeWithIface = nullptr;
3008 SmallVector<NamedDecl *, 2> FoundDecls;
3009 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3010 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3011 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3014 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3018 // Create an interface declaration, if one does not already exist.
3019 ObjCInterfaceDecl *ToIface = MergeWithIface;
3021 ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3022 Importer.Import(D->getAtStartLoc()),
3023 Name.getAsIdentifierInfo(),
3024 /*TypeParamList=*/nullptr,
3025 /*PrevDecl=*/nullptr, Loc,
3026 D->isImplicitInterfaceDecl());
3027 ToIface->setLexicalDeclContext(LexicalDC);
3028 LexicalDC->addDeclInternal(ToIface);
3030 Importer.Imported(D, ToIface);
3031 // Import the type parameter list after calling Imported, to avoid
3032 // loops when bringing in their DeclContext.
3033 ToIface->setTypeParamList(ImportObjCTypeParamList(
3034 D->getTypeParamListAsWritten()));
3036 if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3042 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3043 ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3044 Importer.Import(D->getCategoryDecl()));
3048 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3050 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3054 SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3055 ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3056 Importer.Import(D->getIdentifier()),
3057 Category->getClassInterface(),
3058 Importer.Import(D->getLocation()),
3059 Importer.Import(D->getAtStartLoc()),
3062 DeclContext *LexicalDC = DC;
3063 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3064 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3068 ToImpl->setLexicalDeclContext(LexicalDC);
3071 LexicalDC->addDeclInternal(ToImpl);
3072 Category->setImplementation(ToImpl);
3075 Importer.Imported(D, ToImpl);
3076 ImportDeclContext(D);
3080 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3081 // Find the corresponding interface.
3082 ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3083 Importer.Import(D->getClassInterface()));
3087 // Import the superclass, if any.
3088 ObjCInterfaceDecl *Super = nullptr;
3089 if (D->getSuperClass()) {
3090 Super = cast_or_null<ObjCInterfaceDecl>(
3091 Importer.Import(D->getSuperClass()));
3096 ObjCImplementationDecl *Impl = Iface->getImplementation();
3098 // We haven't imported an implementation yet. Create a new @implementation
3100 Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3101 Importer.ImportContext(D->getDeclContext()),
3103 Importer.Import(D->getLocation()),
3104 Importer.Import(D->getAtStartLoc()),
3105 Importer.Import(D->getSuperClassLoc()),
3106 Importer.Import(D->getIvarLBraceLoc()),
3107 Importer.Import(D->getIvarRBraceLoc()));
3109 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3110 DeclContext *LexicalDC
3111 = Importer.ImportContext(D->getLexicalDeclContext());
3114 Impl->setLexicalDeclContext(LexicalDC);
3117 // Associate the implementation with the class it implements.
3118 Iface->setImplementation(Impl);
3119 Importer.Imported(D, Iface->getImplementation());
3121 Importer.Imported(D, Iface->getImplementation());
3123 // Verify that the existing @implementation has the same superclass.
3124 if ((Super && !Impl->getSuperClass()) ||
3125 (!Super && Impl->getSuperClass()) ||
3126 (Super && Impl->getSuperClass() &&
3127 !declaresSameEntity(Super->getCanonicalDecl(),
3128 Impl->getSuperClass()))) {
3129 Importer.ToDiag(Impl->getLocation(),
3130 diag::err_odr_objc_superclass_inconsistent)
3131 << Iface->getDeclName();
3132 // FIXME: It would be nice to have the location of the superclass
3134 if (Impl->getSuperClass())
3135 Importer.ToDiag(Impl->getLocation(),
3136 diag::note_odr_objc_superclass)
3137 << Impl->getSuperClass()->getDeclName();
3139 Importer.ToDiag(Impl->getLocation(),
3140 diag::note_odr_objc_missing_superclass);
3141 if (D->getSuperClass())
3142 Importer.FromDiag(D->getLocation(),
3143 diag::note_odr_objc_superclass)
3144 << D->getSuperClass()->getDeclName();
3146 Importer.FromDiag(D->getLocation(),
3147 diag::note_odr_objc_missing_superclass);
3152 // Import all of the members of this @implementation.
3153 ImportDeclContext(D);
3158 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3159 // Import the major distinguishing characteristics of an @property.
3160 DeclContext *DC, *LexicalDC;
3161 DeclarationName Name;
3164 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3169 // Check whether we have already imported this property.
3170 SmallVector<NamedDecl *, 2> FoundDecls;
3171 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3172 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3173 if (ObjCPropertyDecl *FoundProp
3174 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3175 // Check property types.
3176 if (!Importer.IsStructurallyEquivalent(D->getType(),
3177 FoundProp->getType())) {
3178 Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3179 << Name << D->getType() << FoundProp->getType();
3180 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3181 << FoundProp->getType();
3185 // FIXME: Check property attributes, getters, setters, etc.?
3187 // Consider these properties to be equivalent.
3188 Importer.Imported(D, FoundProp);
3194 TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
3198 // Create the new property.
3199 ObjCPropertyDecl *ToProperty
3200 = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
3201 Name.getAsIdentifierInfo(),
3202 Importer.Import(D->getAtLoc()),
3203 Importer.Import(D->getLParenLoc()),
3204 Importer.Import(D->getType()),
3206 D->getPropertyImplementation());
3207 Importer.Imported(D, ToProperty);
3208 ToProperty->setLexicalDeclContext(LexicalDC);
3209 LexicalDC->addDeclInternal(ToProperty);
3211 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
3212 ToProperty->setPropertyAttributesAsWritten(
3213 D->getPropertyAttributesAsWritten());
3214 ToProperty->setGetterName(Importer.Import(D->getGetterName()),
3215 Importer.Import(D->getGetterNameLoc()));
3216 ToProperty->setSetterName(Importer.Import(D->getSetterName()),
3217 Importer.Import(D->getSetterNameLoc()));
3218 ToProperty->setGetterMethodDecl(
3219 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
3220 ToProperty->setSetterMethodDecl(
3221 cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
3222 ToProperty->setPropertyIvarDecl(
3223 cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
3227 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
3228 ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
3229 Importer.Import(D->getPropertyDecl()));
3233 DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3237 // Import the lexical declaration context.
3238 DeclContext *LexicalDC = DC;
3239 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3240 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3245 ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
3249 // Import the ivar (for an @synthesize).
3250 ObjCIvarDecl *Ivar = nullptr;
3251 if (D->getPropertyIvarDecl()) {
3252 Ivar = cast_or_null<ObjCIvarDecl>(
3253 Importer.Import(D->getPropertyIvarDecl()));
3258 ObjCPropertyImplDecl *ToImpl
3259 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
3260 Property->getQueryKind());
3262 ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
3263 Importer.Import(D->getLocStart()),
3264 Importer.Import(D->getLocation()),
3266 D->getPropertyImplementation(),
3268 Importer.Import(D->getPropertyIvarDeclLoc()));
3269 ToImpl->setLexicalDeclContext(LexicalDC);
3270 Importer.Imported(D, ToImpl);
3271 LexicalDC->addDeclInternal(ToImpl);
3273 // Check that we have the same kind of property implementation (@synthesize
3275 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
3276 Importer.ToDiag(ToImpl->getLocation(),
3277 diag::err_odr_objc_property_impl_kind_inconsistent)
3278 << Property->getDeclName()
3279 << (ToImpl->getPropertyImplementation()
3280 == ObjCPropertyImplDecl::Dynamic);
3281 Importer.FromDiag(D->getLocation(),
3282 diag::note_odr_objc_property_impl_kind)
3283 << D->getPropertyDecl()->getDeclName()
3284 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
3288 // For @synthesize, check that we have the same
3289 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
3290 Ivar != ToImpl->getPropertyIvarDecl()) {
3291 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
3292 diag::err_odr_objc_synthesize_ivar_inconsistent)
3293 << Property->getDeclName()
3294 << ToImpl->getPropertyIvarDecl()->getDeclName()
3295 << Ivar->getDeclName();
3296 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
3297 diag::note_odr_objc_synthesize_ivar_here)
3298 << D->getPropertyIvarDecl()->getDeclName();
3302 // Merge the existing implementation with the new implementation.
3303 Importer.Imported(D, ToImpl);
3309 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
3310 // For template arguments, we adopt the translation unit as our declaration
3311 // context. This context will be fixed when the actual template declaration
3314 // FIXME: Import default argument.
3315 return TemplateTypeParmDecl::Create(Importer.getToContext(),
3316 Importer.getToContext().getTranslationUnitDecl(),
3317 Importer.Import(D->getLocStart()),
3318 Importer.Import(D->getLocation()),
3321 Importer.Import(D->getIdentifier()),
3322 D->wasDeclaredWithTypename(),
3323 D->isParameterPack());
3327 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
3328 // Import the name of this declaration.
3329 DeclarationName Name = Importer.Import(D->getDeclName());
3330 if (D->getDeclName() && !Name)
3333 // Import the location of this declaration.
3334 SourceLocation Loc = Importer.Import(D->getLocation());
3336 // Import the type of this declaration.
3337 QualType T = Importer.Import(D->getType());
3341 // Import type-source information.
3342 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3343 if (D->getTypeSourceInfo() && !TInfo)
3346 // FIXME: Import default argument.
3348 return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
3349 Importer.getToContext().getTranslationUnitDecl(),
3350 Importer.Import(D->getInnerLocStart()),
3351 Loc, D->getDepth(), D->getPosition(),
3352 Name.getAsIdentifierInfo(),
3353 T, D->isParameterPack(), TInfo);
3357 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
3358 // Import the name of this declaration.
3359 DeclarationName Name = Importer.Import(D->getDeclName());
3360 if (D->getDeclName() && !Name)
3363 // Import the location of this declaration.
3364 SourceLocation Loc = Importer.Import(D->getLocation());
3366 // Import template parameters.
3367 TemplateParameterList *TemplateParams
3368 = ImportTemplateParameterList(D->getTemplateParameters());
3369 if (!TemplateParams)
3372 // FIXME: Import default argument.
3374 return TemplateTemplateParmDecl::Create(Importer.getToContext(),
3375 Importer.getToContext().getTranslationUnitDecl(),
3376 Loc, D->getDepth(), D->getPosition(),
3377 D->isParameterPack(),
3378 Name.getAsIdentifierInfo(),
3382 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
3383 // If this record has a definition in the translation unit we're coming from,
3384 // but this particular declaration is not that definition, import the
3385 // definition and map to that.
3386 CXXRecordDecl *Definition
3387 = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
3388 if (Definition && Definition != D->getTemplatedDecl()) {
3390 = Importer.Import(Definition->getDescribedClassTemplate());
3394 return Importer.Imported(D, ImportedDef);
3397 // Import the major distinguishing characteristics of this class template.
3398 DeclContext *DC, *LexicalDC;
3399 DeclarationName Name;
3402 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3407 // We may already have a template of the same name; try to find and match it.
3408 if (!DC->isFunctionOrMethod()) {
3409 SmallVector<NamedDecl *, 4> ConflictingDecls;
3410 SmallVector<NamedDecl *, 2> FoundDecls;
3411 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3412 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3413 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3416 Decl *Found = FoundDecls[I];
3417 if (ClassTemplateDecl *FoundTemplate
3418 = dyn_cast<ClassTemplateDecl>(Found)) {
3419 if (IsStructuralMatch(D, FoundTemplate)) {
3420 // The class templates structurally match; call it the same template.
3421 // FIXME: We may be filling in a forward declaration here. Handle
3423 Importer.Imported(D->getTemplatedDecl(),
3424 FoundTemplate->getTemplatedDecl());
3425 return Importer.Imported(D, FoundTemplate);
3429 ConflictingDecls.push_back(FoundDecls[I]);
3432 if (!ConflictingDecls.empty()) {
3433 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
3434 ConflictingDecls.data(),
3435 ConflictingDecls.size());
3442 CXXRecordDecl *DTemplated = D->getTemplatedDecl();
3444 // Create the declaration that is being templated.
3445 // Create the declaration that is being templated.
3446 CXXRecordDecl *D2Templated = cast_or_null<CXXRecordDecl>(
3447 Importer.Import(DTemplated));
3451 // Resolve possible cyclic import.
3452 if (Decl *AlreadyImported = Importer.GetAlreadyImportedOrNull(D))
3453 return AlreadyImported;
3455 // Create the class template declaration itself.
3456 TemplateParameterList *TemplateParams
3457 = ImportTemplateParameterList(D->getTemplateParameters());
3458 if (!TemplateParams)
3461 ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
3462 Loc, Name, TemplateParams,
3464 D2Templated->setDescribedClassTemplate(D2);
3466 D2->setAccess(D->getAccess());
3467 D2->setLexicalDeclContext(LexicalDC);
3468 LexicalDC->addDeclInternal(D2);
3470 // Note the relationship between the class templates.
3471 Importer.Imported(D, D2);
3472 Importer.Imported(DTemplated, D2Templated);
3474 if (DTemplated->isCompleteDefinition() &&
3475 !D2Templated->isCompleteDefinition()) {
3476 // FIXME: Import definition!
3482 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
3483 ClassTemplateSpecializationDecl *D) {
3484 // If this record has a definition in the translation unit we're coming from,
3485 // but this particular declaration is not that definition, import the
3486 // definition and map to that.
3487 TagDecl *Definition = D->getDefinition();
3488 if (Definition && Definition != D) {
3489 Decl *ImportedDef = Importer.Import(Definition);
3493 return Importer.Imported(D, ImportedDef);
3496 ClassTemplateDecl *ClassTemplate
3497 = cast_or_null<ClassTemplateDecl>(Importer.Import(
3498 D->getSpecializedTemplate()));
3502 // Import the context of this declaration.
3503 DeclContext *DC = ClassTemplate->getDeclContext();
3507 DeclContext *LexicalDC = DC;
3508 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3509 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3514 // Import the location of this declaration.
3515 SourceLocation StartLoc = Importer.Import(D->getLocStart());
3516 SourceLocation IdLoc = Importer.Import(D->getLocation());
3518 // Import template arguments.
3519 SmallVector<TemplateArgument, 2> TemplateArgs;
3520 if (ImportTemplateArguments(D->getTemplateArgs().data(),
3521 D->getTemplateArgs().size(),
3525 // Try to find an existing specialization with these template arguments.
3526 void *InsertPos = nullptr;
3527 ClassTemplateSpecializationDecl *D2
3528 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
3530 // We already have a class template specialization with these template
3533 // FIXME: Check for specialization vs. instantiation errors.
3535 if (RecordDecl *FoundDef = D2->getDefinition()) {
3536 if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
3537 // The record types structurally match, or the "from" translation
3538 // unit only had a forward declaration anyway; call it the same
3540 return Importer.Imported(D, FoundDef);
3544 // Create a new specialization.
3545 if (ClassTemplatePartialSpecializationDecl *PartialSpec =
3546 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
3548 // Import TemplateArgumentListInfo
3549 TemplateArgumentListInfo ToTAInfo;
3550 auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
3551 for (unsigned I = 0, E = ASTTemplateArgs.NumTemplateArgs; I < E; ++I) {
3553 auto ToLoc = ImportTemplateArgumentLoc(ASTTemplateArgs[I], Error);
3556 ToTAInfo.addArgument(ToLoc);
3559 QualType CanonInjType = Importer.Import(
3560 PartialSpec->getInjectedSpecializationType());
3561 if (CanonInjType.isNull())
3563 CanonInjType = CanonInjType.getCanonicalType();
3565 TemplateParameterList *ToTPList = ImportTemplateParameterList(
3566 PartialSpec->getTemplateParameters());
3567 if (!ToTPList && PartialSpec->getTemplateParameters())
3570 D2 = ClassTemplatePartialSpecializationDecl::Create(
3571 Importer.getToContext(), D->getTagKind(), DC, StartLoc, IdLoc,
3572 ToTPList, ClassTemplate,
3573 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
3574 ToTAInfo, CanonInjType, nullptr);
3577 D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
3578 D->getTagKind(), DC,
3582 /*PrevDecl=*/nullptr);
3585 D2->setSpecializationKind(D->getSpecializationKind());
3587 // Add this specialization to the class template.
3588 ClassTemplate->AddSpecialization(D2, InsertPos);
3590 // Import the qualifier, if any.
3591 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3593 Importer.Imported(D, D2);
3595 if (auto *TSI = D->getTypeAsWritten()) {
3596 TypeSourceInfo *TInfo = Importer.Import(TSI);
3599 D2->setTypeAsWritten(TInfo);
3600 D2->setTemplateKeywordLoc(Importer.Import(D->getTemplateKeywordLoc()));
3601 D2->setExternLoc(Importer.Import(D->getExternLoc()));
3604 SourceLocation POI = Importer.Import(D->getPointOfInstantiation());
3606 D2->setPointOfInstantiation(POI);
3607 else if (D->getPointOfInstantiation().isValid())
3610 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
3612 // Add the specialization to this context.
3613 D2->setLexicalDeclContext(LexicalDC);
3614 LexicalDC->addDeclInternal(D2);
3616 Importer.Imported(D, D2);
3617 if (D->isCompleteDefinition() && ImportDefinition(D, D2))
3623 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
3624 // If this variable has a definition in the translation unit we're coming
3626 // but this particular declaration is not that definition, import the
3627 // definition and map to that.
3628 VarDecl *Definition =
3629 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
3630 if (Definition && Definition != D->getTemplatedDecl()) {
3631 Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
3635 return Importer.Imported(D, ImportedDef);
3638 // Import the major distinguishing characteristics of this variable template.
3639 DeclContext *DC, *LexicalDC;
3640 DeclarationName Name;
3643 if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3648 // We may already have a template of the same name; try to find and match it.
3649 assert(!DC->isFunctionOrMethod() &&
3650 "Variable templates cannot be declared at function scope");
3651 SmallVector<NamedDecl *, 4> ConflictingDecls;
3652 SmallVector<NamedDecl *, 2> FoundDecls;
3653 DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3654 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3655 if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3658 Decl *Found = FoundDecls[I];
3659 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
3660 if (IsStructuralMatch(D, FoundTemplate)) {
3661 // The variable templates structurally match; call it the same template.
3662 Importer.Imported(D->getTemplatedDecl(),
3663 FoundTemplate->getTemplatedDecl());
3664 return Importer.Imported(D, FoundTemplate);
3668 ConflictingDecls.push_back(FoundDecls[I]);
3671 if (!ConflictingDecls.empty()) {
3672 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
3673 ConflictingDecls.data(),
3674 ConflictingDecls.size());
3680 VarDecl *DTemplated = D->getTemplatedDecl();
3683 QualType T = Importer.Import(DTemplated->getType());
3687 // Create the declaration that is being templated.
3688 SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
3689 SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
3690 TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
3691 VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
3692 IdLoc, Name.getAsIdentifierInfo(), T,
3693 TInfo, DTemplated->getStorageClass());
3694 D2Templated->setAccess(DTemplated->getAccess());
3695 D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
3696 D2Templated->setLexicalDeclContext(LexicalDC);
3698 // Importer.Imported(DTemplated, D2Templated);
3699 // LexicalDC->addDeclInternal(D2Templated);
3701 // Merge the initializer.
3702 if (ImportDefinition(DTemplated, D2Templated))
3705 // Create the variable template declaration itself.
3706 TemplateParameterList *TemplateParams =
3707 ImportTemplateParameterList(D->getTemplateParameters());
3708 if (!TemplateParams)
3711 VarTemplateDecl *D2 = VarTemplateDecl::Create(
3712 Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
3713 D2Templated->setDescribedVarTemplate(D2);
3715 D2->setAccess(D->getAccess());
3716 D2->setLexicalDeclContext(LexicalDC);
3717 LexicalDC->addDeclInternal(D2);
3719 // Note the relationship between the variable templates.
3720 Importer.Imported(D, D2);
3721 Importer.Imported(DTemplated, D2Templated);
3723 if (DTemplated->isThisDeclarationADefinition() &&
3724 !D2Templated->isThisDeclarationADefinition()) {
3725 // FIXME: Import definition!
3731 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
3732 VarTemplateSpecializationDecl *D) {
3733 // If this record has a definition in the translation unit we're coming from,
3734 // but this particular declaration is not that definition, import the
3735 // definition and map to that.
3736 VarDecl *Definition = D->getDefinition();
3737 if (Definition && Definition != D) {
3738 Decl *ImportedDef = Importer.Import(Definition);
3742 return Importer.Imported(D, ImportedDef);
3745 VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
3746 Importer.Import(D->getSpecializedTemplate()));
3750 // Import the context of this declaration.
3751 DeclContext *DC = VarTemplate->getDeclContext();
3755 DeclContext *LexicalDC = DC;
3756 if (D->getDeclContext() != D->getLexicalDeclContext()) {
3757 LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3762 // Import the location of this declaration.
3763 SourceLocation StartLoc = Importer.Import(D->getLocStart());
3764 SourceLocation IdLoc = Importer.Import(D->getLocation());
3766 // Import template arguments.
3767 SmallVector<TemplateArgument, 2> TemplateArgs;
3768 if (ImportTemplateArguments(D->getTemplateArgs().data(),
3769 D->getTemplateArgs().size(), TemplateArgs))
3772 // Try to find an existing specialization with these template arguments.
3773 void *InsertPos = nullptr;
3774 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
3775 TemplateArgs, InsertPos);
3777 // We already have a variable template specialization with these template
3780 // FIXME: Check for specialization vs. instantiation errors.
3782 if (VarDecl *FoundDef = D2->getDefinition()) {
3783 if (!D->isThisDeclarationADefinition() ||
3784 IsStructuralMatch(D, FoundDef)) {
3785 // The record types structurally match, or the "from" translation
3786 // unit only had a forward declaration anyway; call it the same
3788 return Importer.Imported(D, FoundDef);
3794 QualType T = Importer.Import(D->getType());
3797 TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3799 // Create a new specialization.
3800 D2 = VarTemplateSpecializationDecl::Create(
3801 Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
3802 D->getStorageClass(), TemplateArgs);
3803 D2->setSpecializationKind(D->getSpecializationKind());
3804 D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
3806 // Add this specialization to the class template.
3807 VarTemplate->AddSpecialization(D2, InsertPos);
3809 // Import the qualifier, if any.
3810 D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3812 // Add the specialization to this context.
3813 D2->setLexicalDeclContext(LexicalDC);
3814 LexicalDC->addDeclInternal(D2);
3816 Importer.Imported(D, D2);
3818 if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
3824 //----------------------------------------------------------------------------
3825 // Import Statements
3826 //----------------------------------------------------------------------------
3828 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
3830 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
3831 size_t NumDecls = DG.end() - DG.begin();
3832 SmallVector<Decl *, 1> ToDecls(NumDecls);
3833 auto &_Importer = this->Importer;
3834 std::transform(DG.begin(), DG.end(), ToDecls.begin(),
3835 [&_Importer](Decl *D) -> Decl * {
3836 return _Importer.Import(D);
3838 return DeclGroupRef::Create(Importer.getToContext(),
3843 Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
3844 Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
3845 << S->getStmtClassName();
3850 Stmt *ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
3851 SmallVector<IdentifierInfo *, 4> Names;
3852 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
3853 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
3854 // ToII is nullptr when no symbolic name is given for output operand
3855 // see ParseStmtAsm::ParseAsmOperandsOpt
3856 if (!ToII && S->getOutputIdentifier(I))
3858 Names.push_back(ToII);
3860 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
3861 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
3862 // ToII is nullptr when no symbolic name is given for input operand
3863 // see ParseStmtAsm::ParseAsmOperandsOpt
3864 if (!ToII && S->getInputIdentifier(I))
3866 Names.push_back(ToII);
3869 SmallVector<StringLiteral *, 4> Clobbers;
3870 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
3871 StringLiteral *Clobber = cast_or_null<StringLiteral>(
3872 Importer.Import(S->getClobberStringLiteral(I)));
3875 Clobbers.push_back(Clobber);
3878 SmallVector<StringLiteral *, 4> Constraints;
3879 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
3880 StringLiteral *Output = cast_or_null<StringLiteral>(
3881 Importer.Import(S->getOutputConstraintLiteral(I)));
3884 Constraints.push_back(Output);
3887 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
3888 StringLiteral *Input = cast_or_null<StringLiteral>(
3889 Importer.Import(S->getInputConstraintLiteral(I)));
3892 Constraints.push_back(Input);
3895 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs());
3896 if (ImportContainerChecked(S->outputs(), Exprs))
3899 if (ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
3902 StringLiteral *AsmStr = cast_or_null<StringLiteral>(
3903 Importer.Import(S->getAsmString()));
3907 return new (Importer.getToContext()) GCCAsmStmt(
3908 Importer.getToContext(),
3909 Importer.Import(S->getAsmLoc()),
3918 S->getNumClobbers(),
3920 Importer.Import(S->getRParenLoc()));
3923 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
3924 DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
3925 for (Decl *ToD : ToDG) {
3929 SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
3930 SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
3931 return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
3934 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
3935 SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
3936 return new (Importer.getToContext()) NullStmt(ToSemiLoc,
3937 S->hasLeadingEmptyMacro());
3940 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
3941 llvm::SmallVector<Stmt *, 8> ToStmts(S->size());
3943 if (ImportContainerChecked(S->body(), ToStmts))
3946 SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
3947 SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
3948 return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
3950 ToLBraceLoc, ToRBraceLoc);
3953 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
3954 Expr *ToLHS = Importer.Import(S->getLHS());
3957 Expr *ToRHS = Importer.Import(S->getRHS());
3958 if (!ToRHS && S->getRHS())
3960 SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
3961 SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
3962 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
3963 return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
3964 ToCaseLoc, ToEllipsisLoc,
3968 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
3969 SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
3970 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
3971 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
3972 if (!ToSubStmt && S->getSubStmt())
3974 return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
3978 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
3979 SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
3980 LabelDecl *ToLabelDecl =
3981 cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
3982 if (!ToLabelDecl && S->getDecl())
3984 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
3985 if (!ToSubStmt && S->getSubStmt())
3987 return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
3991 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
3992 SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
3993 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
3994 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
3995 ASTContext &_ToContext = Importer.getToContext();
3996 std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
3997 [&_ToContext](const Attr *A) -> const Attr * {
3998 return A->clone(_ToContext);
4000 for (const Attr *ToA : ToAttrs) {
4004 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4005 if (!ToSubStmt && S->getSubStmt())
4007 return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4008 ToAttrs, ToSubStmt);
4011 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4012 SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4013 Stmt *ToInit = Importer.Import(S->getInit());
4014 if (!ToInit && S->getInit())
4016 VarDecl *ToConditionVariable = nullptr;
4017 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4018 ToConditionVariable =
4019 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4020 if (!ToConditionVariable)
4023 Expr *ToCondition = Importer.Import(S->getCond());
4024 if (!ToCondition && S->getCond())
4026 Stmt *ToThenStmt = Importer.Import(S->getThen());
4027 if (!ToThenStmt && S->getThen())
4029 SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4030 Stmt *ToElseStmt = Importer.Import(S->getElse());
4031 if (!ToElseStmt && S->getElse())
4033 return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4034 ToIfLoc, S->isConstexpr(),
4036 ToConditionVariable,
4037 ToCondition, ToThenStmt,
4038 ToElseLoc, ToElseStmt);
4041 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4042 Stmt *ToInit = Importer.Import(S->getInit());
4043 if (!ToInit && S->getInit())
4045 VarDecl *ToConditionVariable = nullptr;
4046 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4047 ToConditionVariable =
4048 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4049 if (!ToConditionVariable)
4052 Expr *ToCondition = Importer.Import(S->getCond());
4053 if (!ToCondition && S->getCond())
4055 SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4056 Importer.getToContext(), ToInit,
4057 ToConditionVariable, ToCondition);
4058 Stmt *ToBody = Importer.Import(S->getBody());
4059 if (!ToBody && S->getBody())
4061 ToStmt->setBody(ToBody);
4062 ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4063 // Now we have to re-chain the cases.
4064 SwitchCase *LastChainedSwitchCase = nullptr;
4065 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4066 SC = SC->getNextSwitchCase()) {
4067 SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4070 if (LastChainedSwitchCase)
4071 LastChainedSwitchCase->setNextSwitchCase(ToSC);
4073 ToStmt->setSwitchCaseList(ToSC);
4074 LastChainedSwitchCase = ToSC;
4079 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4080 VarDecl *ToConditionVariable = nullptr;
4081 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4082 ToConditionVariable =
4083 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4084 if (!ToConditionVariable)
4087 Expr *ToCondition = Importer.Import(S->getCond());
4088 if (!ToCondition && S->getCond())
4090 Stmt *ToBody = Importer.Import(S->getBody());
4091 if (!ToBody && S->getBody())
4093 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4094 return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4095 ToConditionVariable,
4096 ToCondition, ToBody,
4100 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4101 Stmt *ToBody = Importer.Import(S->getBody());
4102 if (!ToBody && S->getBody())
4104 Expr *ToCondition = Importer.Import(S->getCond());
4105 if (!ToCondition && S->getCond())
4107 SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4108 SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4109 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4110 return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4111 ToDoLoc, ToWhileLoc,
4115 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4116 Stmt *ToInit = Importer.Import(S->getInit());
4117 if (!ToInit && S->getInit())
4119 Expr *ToCondition = Importer.Import(S->getCond());
4120 if (!ToCondition && S->getCond())
4122 VarDecl *ToConditionVariable = nullptr;
4123 if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4124 ToConditionVariable =
4125 dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4126 if (!ToConditionVariable)
4129 Expr *ToInc = Importer.Import(S->getInc());
4130 if (!ToInc && S->getInc())
4132 Stmt *ToBody = Importer.Import(S->getBody());
4133 if (!ToBody && S->getBody())
4135 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4136 SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4137 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4138 return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4139 ToInit, ToCondition,
4140 ToConditionVariable,
4142 ToForLoc, ToLParenLoc,
4146 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4147 LabelDecl *ToLabel = nullptr;
4148 if (LabelDecl *FromLabel = S->getLabel()) {
4149 ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4153 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4154 SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4155 return new (Importer.getToContext()) GotoStmt(ToLabel,
4156 ToGotoLoc, ToLabelLoc);
4159 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4160 SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4161 SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4162 Expr *ToTarget = Importer.Import(S->getTarget());
4163 if (!ToTarget && S->getTarget())
4165 return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4169 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4170 SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4171 return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4174 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4175 SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4176 return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4179 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4180 SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4181 Expr *ToRetExpr = Importer.Import(S->getRetValue());
4182 if (!ToRetExpr && S->getRetValue())
4184 VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4185 VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4186 if (!ToNRVOCandidate && NRVOCandidate)
4188 return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4192 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4193 SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4194 VarDecl *ToExceptionDecl = nullptr;
4195 if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4197 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4198 if (!ToExceptionDecl)
4201 Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4202 if (!ToHandlerBlock && S->getHandlerBlock())
4204 return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4209 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4210 SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4211 Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4212 if (!ToTryBlock && S->getTryBlock())
4214 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4215 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4216 CXXCatchStmt *FromHandler = S->getHandler(HI);
4217 if (Stmt *ToHandler = Importer.Import(FromHandler))
4218 ToHandlers[HI] = ToHandler;
4222 return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4226 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4228 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4229 if (!ToRange && S->getRangeStmt())
4232 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginStmt()));
4233 if (!ToBegin && S->getBeginStmt())
4236 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getEndStmt()));
4237 if (!ToEnd && S->getEndStmt())
4239 Expr *ToCond = Importer.Import(S->getCond());
4240 if (!ToCond && S->getCond())
4242 Expr *ToInc = Importer.Import(S->getInc());
4243 if (!ToInc && S->getInc())
4245 DeclStmt *ToLoopVar =
4246 dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4247 if (!ToLoopVar && S->getLoopVarStmt())
4249 Stmt *ToBody = Importer.Import(S->getBody());
4250 if (!ToBody && S->getBody())
4252 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4253 SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
4254 SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4255 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4256 return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBegin, ToEnd,
4259 ToForLoc, ToCoawaitLoc,
4260 ToColonLoc, ToRParenLoc);
4263 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4264 Stmt *ToElem = Importer.Import(S->getElement());
4265 if (!ToElem && S->getElement())
4267 Expr *ToCollect = Importer.Import(S->getCollection());
4268 if (!ToCollect && S->getCollection())
4270 Stmt *ToBody = Importer.Import(S->getBody());
4271 if (!ToBody && S->getBody())
4273 SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4274 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4275 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4281 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4282 SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4283 SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4284 VarDecl *ToExceptionDecl = nullptr;
4285 if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4287 dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4288 if (!ToExceptionDecl)
4291 Stmt *ToBody = Importer.Import(S->getCatchBody());
4292 if (!ToBody && S->getCatchBody())
4294 return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
4300 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4301 SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
4302 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
4303 if (!ToAtFinallyStmt && S->getFinallyBody())
4305 return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
4309 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
4310 SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
4311 Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
4312 if (!ToAtTryStmt && S->getTryBody())
4314 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
4315 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
4316 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
4317 if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
4318 ToCatchStmts[CI] = ToCatchStmt;
4322 Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
4323 if (!ToAtFinallyStmt && S->getFinallyStmt())
4325 return ObjCAtTryStmt::Create(Importer.getToContext(),
4326 ToAtTryLoc, ToAtTryStmt,
4327 ToCatchStmts.begin(), ToCatchStmts.size(),
4331 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
4332 (ObjCAtSynchronizedStmt *S) {
4333 SourceLocation ToAtSynchronizedLoc =
4334 Importer.Import(S->getAtSynchronizedLoc());
4335 Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
4336 if (!ToSynchExpr && S->getSynchExpr())
4338 Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
4339 if (!ToSynchBody && S->getSynchBody())
4341 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
4342 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
4345 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
4346 SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
4347 Expr *ToThrow = Importer.Import(S->getThrowExpr());
4348 if (!ToThrow && S->getThrowExpr())
4350 return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
4353 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
4354 (ObjCAutoreleasePoolStmt *S) {
4355 SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
4356 Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4357 if (!ToSubStmt && S->getSubStmt())
4359 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
4363 //----------------------------------------------------------------------------
4364 // Import Expressions
4365 //----------------------------------------------------------------------------
4366 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
4367 Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
4368 << E->getStmtClassName();
4372 Expr *ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
4373 QualType T = Importer.Import(E->getType());
4377 Expr *SubExpr = Importer.Import(E->getSubExpr());
4378 if (!SubExpr && E->getSubExpr())
4381 TypeSourceInfo *TInfo = Importer.Import(E->getWrittenTypeInfo());
4385 return new (Importer.getToContext()) VAArgExpr(
4386 Importer.Import(E->getBuiltinLoc()), SubExpr, TInfo,
4387 Importer.Import(E->getRParenLoc()), T, E->isMicrosoftABI());
4391 Expr *ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
4392 QualType T = Importer.Import(E->getType());
4396 return new (Importer.getToContext()) GNUNullExpr(
4397 T, Importer.Import(E->getLocStart()));
4400 Expr *ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
4401 QualType T = Importer.Import(E->getType());
4405 StringLiteral *SL = cast_or_null<StringLiteral>(
4406 Importer.Import(E->getFunctionName()));
4407 if (!SL && E->getFunctionName())
4410 return new (Importer.getToContext()) PredefinedExpr(
4411 Importer.Import(E->getLocStart()), T, E->getIdentType(), SL);
4414 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
4415 ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
4419 NamedDecl *FoundD = nullptr;
4420 if (E->getDecl() != E->getFoundDecl()) {
4421 FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
4426 QualType T = Importer.Import(E->getType());
4431 TemplateArgumentListInfo ToTAInfo;
4432 TemplateArgumentListInfo *ResInfo = nullptr;
4433 if (E->hasExplicitTemplateArgs()) {
4434 for (const auto &FromLoc : E->template_arguments()) {
4436 TemplateArgumentLoc ToTALoc = ImportTemplateArgumentLoc(FromLoc, Error);
4439 ToTAInfo.addArgument(ToTALoc);
4441 ResInfo = &ToTAInfo;
4444 DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
4445 Importer.Import(E->getQualifierLoc()),
4446 Importer.Import(E->getTemplateKeywordLoc()),
4448 E->refersToEnclosingVariableOrCapture(),
4449 Importer.Import(E->getLocation()),
4450 T, E->getValueKind(),
4452 if (E->hadMultipleCandidates())
4453 DRE->setHadMultipleCandidates(true);
4457 Expr *ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
4458 QualType T = Importer.Import(E->getType());
4462 return new (Importer.getToContext()) ImplicitValueInitExpr(T);
4465 ASTNodeImporter::Designator
4466 ASTNodeImporter::ImportDesignator(const Designator &D) {
4467 if (D.isFieldDesignator()) {
4468 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
4469 // Caller checks for import error
4470 return Designator(ToFieldName, Importer.Import(D.getDotLoc()),
4471 Importer.Import(D.getFieldLoc()));
4473 if (D.isArrayDesignator())
4474 return Designator(D.getFirstExprIndex(),
4475 Importer.Import(D.getLBracketLoc()),
4476 Importer.Import(D.getRBracketLoc()));
4478 assert(D.isArrayRangeDesignator());
4479 return Designator(D.getFirstExprIndex(),
4480 Importer.Import(D.getLBracketLoc()),
4481 Importer.Import(D.getEllipsisLoc()),
4482 Importer.Import(D.getRBracketLoc()));
4486 Expr *ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *DIE) {
4487 Expr *Init = cast_or_null<Expr>(Importer.Import(DIE->getInit()));
4491 SmallVector<Expr *, 4> IndexExprs(DIE->getNumSubExprs() - 1);
4492 // List elements from the second, the first is Init itself
4493 for (unsigned I = 1, E = DIE->getNumSubExprs(); I < E; I++) {
4494 if (Expr *Arg = cast_or_null<Expr>(Importer.Import(DIE->getSubExpr(I))))
4495 IndexExprs[I - 1] = Arg;
4500 SmallVector<Designator, 4> Designators(DIE->size());
4501 llvm::transform(DIE->designators(), Designators.begin(),
4502 [this](const Designator &D) -> Designator {
4503 return ImportDesignator(D);
4506 for (const Designator &D : DIE->designators())
4507 if (D.isFieldDesignator() && !D.getFieldName())
4510 return DesignatedInitExpr::Create(
4511 Importer.getToContext(), Designators,
4512 IndexExprs, Importer.Import(DIE->getEqualOrColonLoc()),
4513 DIE->usesGNUSyntax(), Init);
4516 Expr *ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
4517 QualType T = Importer.Import(E->getType());
4521 return new (Importer.getToContext())
4522 CXXNullPtrLiteralExpr(T, Importer.Import(E->getLocation()));
4525 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
4526 QualType T = Importer.Import(E->getType());
4530 return IntegerLiteral::Create(Importer.getToContext(),
4532 Importer.Import(E->getLocation()));
4535 Expr *ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
4536 QualType T = Importer.Import(E->getType());
4540 return FloatingLiteral::Create(Importer.getToContext(),
4541 E->getValue(), E->isExact(), T,
4542 Importer.Import(E->getLocation()));
4545 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
4546 QualType T = Importer.Import(E->getType());
4550 return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
4552 Importer.Import(E->getLocation()));
4555 Expr *ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
4556 QualType T = Importer.Import(E->getType());
4560 SmallVector<SourceLocation, 4> Locations(E->getNumConcatenated());
4561 ImportArray(E->tokloc_begin(), E->tokloc_end(), Locations.begin());
4563 return StringLiteral::Create(Importer.getToContext(), E->getBytes(),
4564 E->getKind(), E->isPascal(), T,
4565 Locations.data(), Locations.size());
4568 Expr *ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
4569 QualType T = Importer.Import(E->getType());
4573 TypeSourceInfo *TInfo = Importer.Import(E->getTypeSourceInfo());
4577 Expr *Init = Importer.Import(E->getInitializer());
4581 return new (Importer.getToContext()) CompoundLiteralExpr(
4582 Importer.Import(E->getLParenLoc()), TInfo, T, E->getValueKind(),
4583 Init, E->isFileScope());
4586 Expr *ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
4587 QualType T = Importer.Import(E->getType());
4591 SmallVector<Expr *, 6> Exprs(E->getNumSubExprs());
4592 if (ImportArrayChecked(
4593 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
4597 return new (Importer.getToContext()) AtomicExpr(
4598 Importer.Import(E->getBuiltinLoc()), Exprs, T, E->getOp(),
4599 Importer.Import(E->getRParenLoc()));
4602 Expr *ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
4603 QualType T = Importer.Import(E->getType());
4607 LabelDecl *ToLabel = cast_or_null<LabelDecl>(Importer.Import(E->getLabel()));
4611 return new (Importer.getToContext()) AddrLabelExpr(
4612 Importer.Import(E->getAmpAmpLoc()), Importer.Import(E->getLabelLoc()),
4616 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
4617 Expr *SubExpr = Importer.Import(E->getSubExpr());
4621 return new (Importer.getToContext())
4622 ParenExpr(Importer.Import(E->getLParen()),
4623 Importer.Import(E->getRParen()),
4627 Expr *ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
4628 SmallVector<Expr *, 4> Exprs(E->getNumExprs());
4629 if (ImportContainerChecked(E->exprs(), Exprs))
4632 return new (Importer.getToContext()) ParenListExpr(
4633 Importer.getToContext(), Importer.Import(E->getLParenLoc()),
4634 Exprs, Importer.Import(E->getLParenLoc()));
4637 Expr *ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
4638 QualType T = Importer.Import(E->getType());
4642 CompoundStmt *ToSubStmt = cast_or_null<CompoundStmt>(
4643 Importer.Import(E->getSubStmt()));
4644 if (!ToSubStmt && E->getSubStmt())
4647 return new (Importer.getToContext()) StmtExpr(ToSubStmt, T,
4648 Importer.Import(E->getLParenLoc()), Importer.Import(E->getRParenLoc()));
4651 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
4652 QualType T = Importer.Import(E->getType());
4656 Expr *SubExpr = Importer.Import(E->getSubExpr());
4660 return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
4661 T, E->getValueKind(),
4663 Importer.Import(E->getOperatorLoc()));
4666 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
4667 UnaryExprOrTypeTraitExpr *E) {
4668 QualType ResultType = Importer.Import(E->getType());
4670 if (E->isArgumentType()) {
4671 TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
4675 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4677 Importer.Import(E->getOperatorLoc()),
4678 Importer.Import(E->getRParenLoc()));
4681 Expr *SubExpr = Importer.Import(E->getArgumentExpr());
4685 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
4686 SubExpr, ResultType,
4687 Importer.Import(E->getOperatorLoc()),
4688 Importer.Import(E->getRParenLoc()));
4691 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
4692 QualType T = Importer.Import(E->getType());
4696 Expr *LHS = Importer.Import(E->getLHS());
4700 Expr *RHS = Importer.Import(E->getRHS());
4704 return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
4705 T, E->getValueKind(),
4707 Importer.Import(E->getOperatorLoc()),
4708 E->getFPFeatures());
4711 Expr *ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) {
4712 QualType T = Importer.Import(E->getType());
4716 Expr *ToLHS = Importer.Import(E->getLHS());
4720 Expr *ToRHS = Importer.Import(E->getRHS());
4724 Expr *ToCond = Importer.Import(E->getCond());
4728 return new (Importer.getToContext()) ConditionalOperator(
4729 ToCond, Importer.Import(E->getQuestionLoc()),
4730 ToLHS, Importer.Import(E->getColonLoc()),
4731 ToRHS, T, E->getValueKind(), E->getObjectKind());
4734 Expr *ASTNodeImporter::VisitBinaryConditionalOperator(
4735 BinaryConditionalOperator *E) {
4736 QualType T = Importer.Import(E->getType());
4740 Expr *Common = Importer.Import(E->getCommon());
4744 Expr *Cond = Importer.Import(E->getCond());
4748 OpaqueValueExpr *OpaqueValue = cast_or_null<OpaqueValueExpr>(
4749 Importer.Import(E->getOpaqueValue()));
4753 Expr *TrueExpr = Importer.Import(E->getTrueExpr());
4757 Expr *FalseExpr = Importer.Import(E->getFalseExpr());
4761 return new (Importer.getToContext()) BinaryConditionalOperator(
4762 Common, OpaqueValue, Cond, TrueExpr, FalseExpr,
4763 Importer.Import(E->getQuestionLoc()), Importer.Import(E->getColonLoc()),
4764 T, E->getValueKind(), E->getObjectKind());
4767 Expr *ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
4768 QualType T = Importer.Import(E->getType());
4772 TypeSourceInfo *ToQueried = Importer.Import(E->getQueriedTypeSourceInfo());
4776 Expr *Dim = Importer.Import(E->getDimensionExpression());
4777 if (!Dim && E->getDimensionExpression())
4780 return new (Importer.getToContext()) ArrayTypeTraitExpr(
4781 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
4782 E->getValue(), Dim, Importer.Import(E->getLocEnd()), T);
4785 Expr *ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) {
4786 QualType T = Importer.Import(E->getType());
4790 Expr *ToQueried = Importer.Import(E->getQueriedExpression());
4794 return new (Importer.getToContext()) ExpressionTraitExpr(
4795 Importer.Import(E->getLocStart()), E->getTrait(), ToQueried,
4796 E->getValue(), Importer.Import(E->getLocEnd()), T);
4799 Expr *ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) {
4800 QualType T = Importer.Import(E->getType());
4804 Expr *SourceExpr = Importer.Import(E->getSourceExpr());
4805 if (!SourceExpr && E->getSourceExpr())
4808 return new (Importer.getToContext()) OpaqueValueExpr(
4809 Importer.Import(E->getLocation()), T, E->getValueKind(),
4810 E->getObjectKind(), SourceExpr);
4813 Expr *ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
4814 QualType T = Importer.Import(E->getType());
4818 Expr *ToLHS = Importer.Import(E->getLHS());
4822 Expr *ToRHS = Importer.Import(E->getRHS());
4826 return new (Importer.getToContext()) ArraySubscriptExpr(
4827 ToLHS, ToRHS, T, E->getValueKind(), E->getObjectKind(),
4828 Importer.Import(E->getRBracketLoc()));
4831 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
4832 QualType T = Importer.Import(E->getType());
4836 QualType CompLHSType = Importer.Import(E->getComputationLHSType());
4837 if (CompLHSType.isNull())
4840 QualType CompResultType = Importer.Import(E->getComputationResultType());
4841 if (CompResultType.isNull())
4844 Expr *LHS = Importer.Import(E->getLHS());
4848 Expr *RHS = Importer.Import(E->getRHS());
4852 return new (Importer.getToContext())
4853 CompoundAssignOperator(LHS, RHS, E->getOpcode(),
4854 T, E->getValueKind(),
4856 CompLHSType, CompResultType,
4857 Importer.Import(E->getOperatorLoc()),
4858 E->getFPFeatures());
4861 bool ASTNodeImporter::ImportCastPath(CastExpr *CE, CXXCastPath &Path) {
4862 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
4863 if (CXXBaseSpecifier *Spec = Importer.Import(*I))
4864 Path.push_back(Spec);
4871 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
4872 QualType T = Importer.Import(E->getType());
4876 Expr *SubExpr = Importer.Import(E->getSubExpr());
4880 CXXCastPath BasePath;
4881 if (ImportCastPath(E, BasePath))
4884 return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
4885 SubExpr, &BasePath, E->getValueKind());
4888 Expr *ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) {
4889 QualType T = Importer.Import(E->getType());
4893 Expr *SubExpr = Importer.Import(E->getSubExpr());
4897 TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
4898 if (!TInfo && E->getTypeInfoAsWritten())
4901 CXXCastPath BasePath;
4902 if (ImportCastPath(E, BasePath))
4905 switch (E->getStmtClass()) {
4906 case Stmt::CStyleCastExprClass: {
4907 CStyleCastExpr *CCE = cast<CStyleCastExpr>(E);
4908 return CStyleCastExpr::Create(Importer.getToContext(), T,
4909 E->getValueKind(), E->getCastKind(),
4910 SubExpr, &BasePath, TInfo,
4911 Importer.Import(CCE->getLParenLoc()),
4912 Importer.Import(CCE->getRParenLoc()));
4915 case Stmt::CXXFunctionalCastExprClass: {
4916 CXXFunctionalCastExpr *FCE = cast<CXXFunctionalCastExpr>(E);
4917 return CXXFunctionalCastExpr::Create(Importer.getToContext(), T,
4918 E->getValueKind(), TInfo,
4919 E->getCastKind(), SubExpr, &BasePath,
4920 Importer.Import(FCE->getLParenLoc()),
4921 Importer.Import(FCE->getRParenLoc()));
4924 case Stmt::ObjCBridgedCastExprClass: {
4925 ObjCBridgedCastExpr *OCE = cast<ObjCBridgedCastExpr>(E);
4926 return new (Importer.getToContext()) ObjCBridgedCastExpr(
4927 Importer.Import(OCE->getLParenLoc()), OCE->getBridgeKind(),
4928 E->getCastKind(), Importer.Import(OCE->getBridgeKeywordLoc()),
4932 break; // just fall through
4935 CXXNamedCastExpr *Named = cast<CXXNamedCastExpr>(E);
4936 SourceLocation ExprLoc = Importer.Import(Named->getOperatorLoc()),
4937 RParenLoc = Importer.Import(Named->getRParenLoc());
4938 SourceRange Brackets = Importer.Import(Named->getAngleBrackets());
4940 switch (E->getStmtClass()) {
4941 case Stmt::CXXStaticCastExprClass:
4942 return CXXStaticCastExpr::Create(Importer.getToContext(), T,
4943 E->getValueKind(), E->getCastKind(),
4944 SubExpr, &BasePath, TInfo,
4945 ExprLoc, RParenLoc, Brackets);
4947 case Stmt::CXXDynamicCastExprClass:
4948 return CXXDynamicCastExpr::Create(Importer.getToContext(), T,
4949 E->getValueKind(), E->getCastKind(),
4950 SubExpr, &BasePath, TInfo,
4951 ExprLoc, RParenLoc, Brackets);
4953 case Stmt::CXXReinterpretCastExprClass:
4954 return CXXReinterpretCastExpr::Create(Importer.getToContext(), T,
4955 E->getValueKind(), E->getCastKind(),
4956 SubExpr, &BasePath, TInfo,
4957 ExprLoc, RParenLoc, Brackets);
4959 case Stmt::CXXConstCastExprClass:
4960 return CXXConstCastExpr::Create(Importer.getToContext(), T,
4961 E->getValueKind(), SubExpr, TInfo, ExprLoc,
4962 RParenLoc, Brackets);
4964 llvm_unreachable("Cast expression of unsupported type!");
4969 Expr *ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *OE) {
4970 QualType T = Importer.Import(OE->getType());
4974 SmallVector<OffsetOfNode, 4> Nodes;
4975 for (int I = 0, E = OE->getNumComponents(); I < E; ++I) {
4976 const OffsetOfNode &Node = OE->getComponent(I);
4978 switch (Node.getKind()) {
4979 case OffsetOfNode::Array:
4980 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()),
4981 Node.getArrayExprIndex(),
4982 Importer.Import(Node.getLocEnd())));
4985 case OffsetOfNode::Base: {
4986 CXXBaseSpecifier *BS = Importer.Import(Node.getBase());
4987 if (!BS && Node.getBase())
4989 Nodes.push_back(OffsetOfNode(BS));
4992 case OffsetOfNode::Field: {
4993 FieldDecl *FD = cast_or_null<FieldDecl>(Importer.Import(Node.getField()));
4996 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), FD,
4997 Importer.Import(Node.getLocEnd())));
5000 case OffsetOfNode::Identifier: {
5001 IdentifierInfo *ToII = Importer.Import(Node.getFieldName());
5004 Nodes.push_back(OffsetOfNode(Importer.Import(Node.getLocStart()), ToII,
5005 Importer.Import(Node.getLocEnd())));
5011 SmallVector<Expr *, 4> Exprs(OE->getNumExpressions());
5012 for (int I = 0, E = OE->getNumExpressions(); I < E; ++I) {
5013 Expr *ToIndexExpr = Importer.Import(OE->getIndexExpr(I));
5016 Exprs[I] = ToIndexExpr;
5019 TypeSourceInfo *TInfo = Importer.Import(OE->getTypeSourceInfo());
5020 if (!TInfo && OE->getTypeSourceInfo())
5023 return OffsetOfExpr::Create(Importer.getToContext(), T,
5024 Importer.Import(OE->getOperatorLoc()),
5025 TInfo, Nodes, Exprs,
5026 Importer.Import(OE->getRParenLoc()));
5029 Expr *ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) {
5030 QualType T = Importer.Import(E->getType());
5034 Expr *Operand = Importer.Import(E->getOperand());
5038 CanThrowResult CanThrow;
5039 if (E->isValueDependent())
5040 CanThrow = CT_Dependent;
5042 CanThrow = E->getValue() ? CT_Can : CT_Cannot;
5044 return new (Importer.getToContext()) CXXNoexceptExpr(
5045 T, Operand, CanThrow,
5046 Importer.Import(E->getLocStart()), Importer.Import(E->getLocEnd()));
5049 Expr *ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) {
5050 QualType T = Importer.Import(E->getType());
5054 Expr *SubExpr = Importer.Import(E->getSubExpr());
5055 if (!SubExpr && E->getSubExpr())
5058 return new (Importer.getToContext()) CXXThrowExpr(
5059 SubExpr, T, Importer.Import(E->getThrowLoc()),
5060 E->isThrownVariableInScope());
5063 Expr *ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
5064 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
5065 Importer.Import(E->getParam()));
5069 return CXXDefaultArgExpr::Create(
5070 Importer.getToContext(), Importer.Import(E->getUsedLocation()), Param);
5073 Expr *ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
5074 QualType T = Importer.Import(E->getType());
5078 TypeSourceInfo *TypeInfo = Importer.Import(E->getTypeSourceInfo());
5082 return new (Importer.getToContext()) CXXScalarValueInitExpr(
5083 T, TypeInfo, Importer.Import(E->getRParenLoc()));
5086 Expr *ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
5087 Expr *SubExpr = Importer.Import(E->getSubExpr());
5091 auto *Dtor = cast_or_null<CXXDestructorDecl>(
5092 Importer.Import(const_cast<CXXDestructorDecl *>(
5093 E->getTemporary()->getDestructor())));
5097 ASTContext &ToCtx = Importer.getToContext();
5098 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, Dtor);
5099 return CXXBindTemporaryExpr::Create(ToCtx, Temp, SubExpr);
5102 Expr *ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *CE) {
5103 QualType T = Importer.Import(CE->getType());
5107 SmallVector<Expr *, 8> Args(CE->getNumArgs());
5108 if (ImportContainerChecked(CE->arguments(), Args))
5111 auto *Ctor = cast_or_null<CXXConstructorDecl>(
5112 Importer.Import(CE->getConstructor()));
5116 return CXXTemporaryObjectExpr::Create(
5117 Importer.getToContext(), T,
5118 Importer.Import(CE->getLocStart()),
5122 CE->hadMultipleCandidates(),
5123 CE->isListInitialization(),
5124 CE->isStdInitListInitialization(),
5125 CE->requiresZeroInitialization(),
5126 CE->getConstructionKind(),
5127 Importer.Import(CE->getParenOrBraceRange()));
5131 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
5132 QualType T = Importer.Import(E->getType());
5136 Expr *TempE = Importer.Import(E->GetTemporaryExpr());
5140 ValueDecl *ExtendedBy = cast_or_null<ValueDecl>(
5141 Importer.Import(const_cast<ValueDecl *>(E->getExtendingDecl())));
5142 if (!ExtendedBy && E->getExtendingDecl())
5145 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
5146 T, TempE, E->isBoundToLvalueReference());
5148 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
5149 ToMTE->setExtendingDecl(ExtendedBy, E->getManglingNumber());
5153 Expr *ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *CE) {
5154 QualType T = Importer.Import(CE->getType());
5158 SmallVector<Expr *, 4> PlacementArgs(CE->getNumPlacementArgs());
5159 if (ImportContainerChecked(CE->placement_arguments(), PlacementArgs))
5162 FunctionDecl *OperatorNewDecl = cast_or_null<FunctionDecl>(
5163 Importer.Import(CE->getOperatorNew()));
5164 if (!OperatorNewDecl && CE->getOperatorNew())
5167 FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
5168 Importer.Import(CE->getOperatorDelete()));
5169 if (!OperatorDeleteDecl && CE->getOperatorDelete())
5172 Expr *ToInit = Importer.Import(CE->getInitializer());
5173 if (!ToInit && CE->getInitializer())
5176 TypeSourceInfo *TInfo = Importer.Import(CE->getAllocatedTypeSourceInfo());
5180 Expr *ToArrSize = Importer.Import(CE->getArraySize());
5181 if (!ToArrSize && CE->getArraySize())
5184 return new (Importer.getToContext()) CXXNewExpr(
5185 Importer.getToContext(),
5187 OperatorNewDecl, OperatorDeleteDecl,
5188 CE->passAlignment(),
5189 CE->doesUsualArrayDeleteWantSize(),
5191 Importer.Import(CE->getTypeIdParens()),
5192 ToArrSize, CE->getInitializationStyle(), ToInit, T, TInfo,
5193 Importer.Import(CE->getSourceRange()),
5194 Importer.Import(CE->getDirectInitRange()));
5197 Expr *ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) {
5198 QualType T = Importer.Import(E->getType());
5202 FunctionDecl *OperatorDeleteDecl = cast_or_null<FunctionDecl>(
5203 Importer.Import(E->getOperatorDelete()));
5204 if (!OperatorDeleteDecl && E->getOperatorDelete())
5207 Expr *ToArg = Importer.Import(E->getArgument());
5208 if (!ToArg && E->getArgument())
5211 return new (Importer.getToContext()) CXXDeleteExpr(
5212 T, E->isGlobalDelete(),
5214 E->isArrayFormAsWritten(),
5215 E->doesUsualArrayDeleteWantSize(),
5218 Importer.Import(E->getLocStart()));
5221 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5222 QualType T = Importer.Import(E->getType());
5226 CXXConstructorDecl *ToCCD =
5227 dyn_cast_or_null<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5231 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
5232 if (ImportContainerChecked(E->arguments(), ToArgs))
5235 return CXXConstructExpr::Create(Importer.getToContext(), T,
5236 Importer.Import(E->getLocation()),
5237 ToCCD, E->isElidable(),
5238 ToArgs, E->hadMultipleCandidates(),
5239 E->isListInitialization(),
5240 E->isStdInitListInitialization(),
5241 E->requiresZeroInitialization(),
5242 E->getConstructionKind(),
5243 Importer.Import(E->getParenOrBraceRange()));
5246 Expr *ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *EWC) {
5247 Expr *SubExpr = Importer.Import(EWC->getSubExpr());
5248 if (!SubExpr && EWC->getSubExpr())
5251 SmallVector<ExprWithCleanups::CleanupObject, 8> Objs(EWC->getNumObjects());
5252 for (unsigned I = 0, E = EWC->getNumObjects(); I < E; I++)
5253 if (ExprWithCleanups::CleanupObject Obj =
5254 cast_or_null<BlockDecl>(Importer.Import(EWC->getObject(I))))
5259 return ExprWithCleanups::Create(Importer.getToContext(),
5260 SubExpr, EWC->cleanupsHaveSideEffects(),
5264 Expr *ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
5265 QualType T = Importer.Import(E->getType());
5269 Expr *ToFn = Importer.Import(E->getCallee());
5273 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
5274 if (ImportContainerChecked(E->arguments(), ToArgs))
5277 return new (Importer.getToContext()) CXXMemberCallExpr(
5278 Importer.getToContext(), ToFn, ToArgs, T, E->getValueKind(),
5279 Importer.Import(E->getRParenLoc()));
5282 Expr *ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) {
5283 QualType T = Importer.Import(E->getType());
5287 return new (Importer.getToContext())
5288 CXXThisExpr(Importer.Import(E->getLocation()), T, E->isImplicit());
5291 Expr *ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
5292 QualType T = Importer.Import(E->getType());
5296 return new (Importer.getToContext())
5297 CXXBoolLiteralExpr(E->getValue(), T, Importer.Import(E->getLocation()));
5301 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5302 QualType T = Importer.Import(E->getType());
5306 Expr *ToBase = Importer.Import(E->getBase());
5307 if (!ToBase && E->getBase())
5310 ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5311 if (!ToMember && E->getMemberDecl())
5314 DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5315 dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5316 E->getFoundDecl().getAccess());
5318 DeclarationNameInfo ToMemberNameInfo(
5319 Importer.Import(E->getMemberNameInfo().getName()),
5320 Importer.Import(E->getMemberNameInfo().getLoc()));
5322 if (E->hasExplicitTemplateArgs()) {
5323 return nullptr; // FIXME: handle template arguments
5326 return MemberExpr::Create(Importer.getToContext(), ToBase,
5328 Importer.Import(E->getOperatorLoc()),
5329 Importer.Import(E->getQualifierLoc()),
5330 Importer.Import(E->getTemplateKeywordLoc()),
5331 ToMember, ToFoundDecl, ToMemberNameInfo,
5332 nullptr, T, E->getValueKind(),
5333 E->getObjectKind());
5336 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5337 QualType T = Importer.Import(E->getType());
5341 Expr *ToCallee = Importer.Import(E->getCallee());
5342 if (!ToCallee && E->getCallee())
5345 unsigned NumArgs = E->getNumArgs();
5347 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5349 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5350 Expr *FromArg = E->getArg(ai);
5351 Expr *ToArg = Importer.Import(FromArg);
5357 Expr **ToArgs_Copied = new (Importer.getToContext())
5360 for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5361 ToArgs_Copied[ai] = ToArgs[ai];
5363 return new (Importer.getToContext())
5364 CallExpr(Importer.getToContext(), ToCallee,
5365 llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5366 Importer.Import(E->getRParenLoc()));
5369 Expr *ASTNodeImporter::VisitInitListExpr(InitListExpr *ILE) {
5370 QualType T = Importer.Import(ILE->getType());
5374 llvm::SmallVector<Expr *, 4> Exprs(ILE->getNumInits());
5375 if (ImportContainerChecked(ILE->inits(), Exprs))
5378 ASTContext &ToCtx = Importer.getToContext();
5379 InitListExpr *To = new (ToCtx) InitListExpr(
5380 ToCtx, Importer.Import(ILE->getLBraceLoc()),
5381 Exprs, Importer.Import(ILE->getLBraceLoc()));
5384 if (ILE->hasArrayFiller()) {
5385 Expr *Filler = Importer.Import(ILE->getArrayFiller());
5388 To->setArrayFiller(Filler);
5391 if (FieldDecl *FromFD = ILE->getInitializedFieldInUnion()) {
5392 FieldDecl *ToFD = cast_or_null<FieldDecl>(Importer.Import(FromFD));
5395 To->setInitializedFieldInUnion(ToFD);
5398 if (InitListExpr *SyntForm = ILE->getSyntacticForm()) {
5399 InitListExpr *ToSyntForm = cast_or_null<InitListExpr>(
5400 Importer.Import(SyntForm));
5403 To->setSyntacticForm(ToSyntForm);
5406 To->sawArrayRangeDesignator(ILE->hadArrayRangeDesignator());
5407 To->setValueDependent(ILE->isValueDependent());
5408 To->setInstantiationDependent(ILE->isInstantiationDependent());
5413 Expr *ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) {
5414 QualType ToType = Importer.Import(E->getType());
5415 if (ToType.isNull())
5418 Expr *ToCommon = Importer.Import(E->getCommonExpr());
5419 if (!ToCommon && E->getCommonExpr())
5422 Expr *ToSubExpr = Importer.Import(E->getSubExpr());
5423 if (!ToSubExpr && E->getSubExpr())
5426 return new (Importer.getToContext())
5427 ArrayInitLoopExpr(ToType, ToCommon, ToSubExpr);
5430 Expr *ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
5431 QualType ToType = Importer.Import(E->getType());
5432 if (ToType.isNull())
5434 return new (Importer.getToContext()) ArrayInitIndexExpr(ToType);
5437 Expr *ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
5438 FieldDecl *ToField = llvm::dyn_cast_or_null<FieldDecl>(
5439 Importer.Import(DIE->getField()));
5440 if (!ToField && DIE->getField())
5443 return CXXDefaultInitExpr::Create(
5444 Importer.getToContext(), Importer.Import(DIE->getLocStart()), ToField);
5447 Expr *ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
5448 QualType ToType = Importer.Import(E->getType());
5449 if (ToType.isNull() && !E->getType().isNull())
5451 ExprValueKind VK = E->getValueKind();
5452 CastKind CK = E->getCastKind();
5453 Expr *ToOp = Importer.Import(E->getSubExpr());
5454 if (!ToOp && E->getSubExpr())
5456 CXXCastPath BasePath;
5457 if (ImportCastPath(E, BasePath))
5459 TypeSourceInfo *ToWritten = Importer.Import(E->getTypeInfoAsWritten());
5460 SourceLocation ToOperatorLoc = Importer.Import(E->getOperatorLoc());
5461 SourceLocation ToRParenLoc = Importer.Import(E->getRParenLoc());
5462 SourceRange ToAngleBrackets = Importer.Import(E->getAngleBrackets());
5464 if (isa<CXXStaticCastExpr>(E)) {
5465 return CXXStaticCastExpr::Create(
5466 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
5467 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
5468 } else if (isa<CXXDynamicCastExpr>(E)) {
5469 return CXXDynamicCastExpr::Create(
5470 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
5471 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
5472 } else if (isa<CXXReinterpretCastExpr>(E)) {
5473 return CXXReinterpretCastExpr::Create(
5474 Importer.getToContext(), ToType, VK, CK, ToOp, &BasePath,
5475 ToWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
5482 Expr *ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr(
5483 SubstNonTypeTemplateParmExpr *E) {
5484 QualType T = Importer.Import(E->getType());
5488 NonTypeTemplateParmDecl *Param = cast_or_null<NonTypeTemplateParmDecl>(
5489 Importer.Import(E->getParameter()));
5493 Expr *Replacement = Importer.Import(E->getReplacement());
5497 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
5498 T, E->getValueKind(), Importer.Import(E->getExprLoc()), Param,
5502 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
5503 ASTContext &FromContext, FileManager &FromFileManager,
5505 : ToContext(ToContext), FromContext(FromContext),
5506 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
5507 Minimal(MinimalImport), LastDiagFromFrom(false)
5509 ImportedDecls[FromContext.getTranslationUnitDecl()]
5510 = ToContext.getTranslationUnitDecl();
5513 ASTImporter::~ASTImporter() { }
5515 QualType ASTImporter::Import(QualType FromT) {
5519 const Type *fromTy = FromT.getTypePtr();
5521 // Check whether we've already imported this type.
5522 llvm::DenseMap<const Type *, const Type *>::iterator Pos
5523 = ImportedTypes.find(fromTy);
5524 if (Pos != ImportedTypes.end())
5525 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
5528 ASTNodeImporter Importer(*this);
5529 QualType ToT = Importer.Visit(fromTy);
5533 // Record the imported type.
5534 ImportedTypes[fromTy] = ToT.getTypePtr();
5536 return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
5539 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
5543 // FIXME: For now we just create a "trivial" type source info based
5544 // on the type and a single location. Implement a real version of this.
5545 QualType T = Import(FromTSI->getType());
5549 return ToContext.getTrivialTypeSourceInfo(T,
5550 Import(FromTSI->getTypeLoc().getLocStart()));
5553 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
5554 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5555 if (Pos != ImportedDecls.end()) {
5556 Decl *ToD = Pos->second;
5557 ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
5564 Decl *ASTImporter::Import(Decl *FromD) {
5568 ASTNodeImporter Importer(*this);
5570 // Check whether we've already imported this declaration.
5571 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5572 if (Pos != ImportedDecls.end()) {
5573 Decl *ToD = Pos->second;
5574 Importer.ImportDefinitionIfNeeded(FromD, ToD);
5579 Decl *ToD = Importer.Visit(FromD);
5583 // Record the imported declaration.
5584 ImportedDecls[FromD] = ToD;
5586 if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
5587 // Keep track of anonymous tags that have an associated typedef.
5588 if (FromTag->getTypedefNameForAnonDecl())
5589 AnonTagsWithPendingTypedefs.push_back(FromTag);
5590 } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
5591 // When we've finished transforming a typedef, see whether it was the
5592 // typedef for an anonymous tag.
5593 for (SmallVectorImpl<TagDecl *>::iterator
5594 FromTag = AnonTagsWithPendingTypedefs.begin(),
5595 FromTagEnd = AnonTagsWithPendingTypedefs.end();
5596 FromTag != FromTagEnd; ++FromTag) {
5597 if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
5598 if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
5599 // We found the typedef for an anonymous tag; link them.
5600 ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
5601 AnonTagsWithPendingTypedefs.erase(FromTag);
5611 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
5615 DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
5619 // When we're using a record/enum/Objective-C class/protocol as a context, we
5620 // need it to have a definition.
5621 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
5622 RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
5623 if (ToRecord->isCompleteDefinition()) {
5625 } else if (FromRecord->isCompleteDefinition()) {
5626 ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
5627 ASTNodeImporter::IDK_Basic);
5629 CompleteDecl(ToRecord);
5631 } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
5632 EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
5633 if (ToEnum->isCompleteDefinition()) {
5635 } else if (FromEnum->isCompleteDefinition()) {
5636 ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
5637 ASTNodeImporter::IDK_Basic);
5639 CompleteDecl(ToEnum);
5641 } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
5642 ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
5643 if (ToClass->getDefinition()) {
5645 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
5646 ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
5647 ASTNodeImporter::IDK_Basic);
5649 CompleteDecl(ToClass);
5651 } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
5652 ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
5653 if (ToProto->getDefinition()) {
5655 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
5656 ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
5657 ASTNodeImporter::IDK_Basic);
5659 CompleteDecl(ToProto);
5666 Expr *ASTImporter::Import(Expr *FromE) {
5670 return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
5673 Stmt *ASTImporter::Import(Stmt *FromS) {
5677 // Check whether we've already imported this declaration.
5678 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
5679 if (Pos != ImportedStmts.end())
5683 ASTNodeImporter Importer(*this);
5684 Stmt *ToS = Importer.Visit(FromS);
5688 // Record the imported declaration.
5689 ImportedStmts[FromS] = ToS;
5693 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
5697 NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
5699 switch (FromNNS->getKind()) {
5700 case NestedNameSpecifier::Identifier:
5701 if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
5702 return NestedNameSpecifier::Create(ToContext, prefix, II);
5706 case NestedNameSpecifier::Namespace:
5707 if (NamespaceDecl *NS =
5708 cast_or_null<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
5709 return NestedNameSpecifier::Create(ToContext, prefix, NS);
5713 case NestedNameSpecifier::NamespaceAlias:
5714 if (NamespaceAliasDecl *NSAD =
5715 cast_or_null<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
5716 return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
5720 case NestedNameSpecifier::Global:
5721 return NestedNameSpecifier::GlobalSpecifier(ToContext);
5723 case NestedNameSpecifier::Super:
5724 if (CXXRecordDecl *RD =
5725 cast_or_null<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
5726 return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
5730 case NestedNameSpecifier::TypeSpec:
5731 case NestedNameSpecifier::TypeSpecWithTemplate: {
5732 QualType T = Import(QualType(FromNNS->getAsType(), 0u));
5734 bool bTemplate = FromNNS->getKind() ==
5735 NestedNameSpecifier::TypeSpecWithTemplate;
5736 return NestedNameSpecifier::Create(ToContext, prefix,
5737 bTemplate, T.getTypePtr());
5743 llvm_unreachable("Invalid nested name specifier kind");
5746 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
5747 // Copied from NestedNameSpecifier mostly.
5748 SmallVector<NestedNameSpecifierLoc , 8> NestedNames;
5749 NestedNameSpecifierLoc NNS = FromNNS;
5751 // Push each of the nested-name-specifiers's onto a stack for
5752 // serialization in reverse order.
5754 NestedNames.push_back(NNS);
5755 NNS = NNS.getPrefix();
5758 NestedNameSpecifierLocBuilder Builder;
5760 while (!NestedNames.empty()) {
5761 NNS = NestedNames.pop_back_val();
5762 NestedNameSpecifier *Spec = Import(NNS.getNestedNameSpecifier());
5764 return NestedNameSpecifierLoc();
5766 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind();
5768 case NestedNameSpecifier::Identifier:
5769 Builder.Extend(getToContext(),
5770 Spec->getAsIdentifier(),
5771 Import(NNS.getLocalBeginLoc()),
5772 Import(NNS.getLocalEndLoc()));
5775 case NestedNameSpecifier::Namespace:
5776 Builder.Extend(getToContext(),
5777 Spec->getAsNamespace(),
5778 Import(NNS.getLocalBeginLoc()),
5779 Import(NNS.getLocalEndLoc()));
5782 case NestedNameSpecifier::NamespaceAlias:
5783 Builder.Extend(getToContext(),
5784 Spec->getAsNamespaceAlias(),
5785 Import(NNS.getLocalBeginLoc()),
5786 Import(NNS.getLocalEndLoc()));
5789 case NestedNameSpecifier::TypeSpec:
5790 case NestedNameSpecifier::TypeSpecWithTemplate: {
5791 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo(
5792 QualType(Spec->getAsType(), 0));
5793 Builder.Extend(getToContext(),
5794 Import(NNS.getLocalBeginLoc()),
5796 Import(NNS.getLocalEndLoc()));
5800 case NestedNameSpecifier::Global:
5801 Builder.MakeGlobal(getToContext(), Import(NNS.getLocalBeginLoc()));
5804 case NestedNameSpecifier::Super: {
5805 SourceRange ToRange = Import(NNS.getSourceRange());
5806 Builder.MakeSuper(getToContext(),
5807 Spec->getAsRecordDecl(),
5814 return Builder.getWithLocInContext(getToContext());
5817 TemplateName ASTImporter::Import(TemplateName From) {
5818 switch (From.getKind()) {
5819 case TemplateName::Template:
5820 if (TemplateDecl *ToTemplate
5821 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5822 return TemplateName(ToTemplate);
5824 return TemplateName();
5826 case TemplateName::OverloadedTemplate: {
5827 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
5828 UnresolvedSet<2> ToTemplates;
5829 for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
5830 E = FromStorage->end();
5832 if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
5833 ToTemplates.addDecl(To);
5835 return TemplateName();
5837 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
5841 case TemplateName::QualifiedTemplate: {
5842 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
5843 NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
5845 return TemplateName();
5847 if (TemplateDecl *ToTemplate
5848 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5849 return ToContext.getQualifiedTemplateName(Qualifier,
5850 QTN->hasTemplateKeyword(),
5853 return TemplateName();
5856 case TemplateName::DependentTemplate: {
5857 DependentTemplateName *DTN = From.getAsDependentTemplateName();
5858 NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
5860 return TemplateName();
5862 if (DTN->isIdentifier()) {
5863 return ToContext.getDependentTemplateName(Qualifier,
5864 Import(DTN->getIdentifier()));
5867 return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
5870 case TemplateName::SubstTemplateTemplateParm: {
5871 SubstTemplateTemplateParmStorage *subst
5872 = From.getAsSubstTemplateTemplateParm();
5873 TemplateTemplateParmDecl *param
5874 = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
5876 return TemplateName();
5878 TemplateName replacement = Import(subst->getReplacement());
5879 if (replacement.isNull()) return TemplateName();
5881 return ToContext.getSubstTemplateTemplateParm(param, replacement);
5884 case TemplateName::SubstTemplateTemplateParmPack: {
5885 SubstTemplateTemplateParmPackStorage *SubstPack
5886 = From.getAsSubstTemplateTemplateParmPack();
5887 TemplateTemplateParmDecl *Param
5888 = cast_or_null<TemplateTemplateParmDecl>(
5889 Import(SubstPack->getParameterPack()));
5891 return TemplateName();
5893 ASTNodeImporter Importer(*this);
5894 TemplateArgument ArgPack
5895 = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
5896 if (ArgPack.isNull())
5897 return TemplateName();
5899 return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
5903 llvm_unreachable("Invalid template name kind");
5906 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
5907 if (FromLoc.isInvalid())
5908 return SourceLocation();
5910 SourceManager &FromSM = FromContext.getSourceManager();
5912 // For now, map everything down to its file location, so that we
5913 // don't have to import macro expansions.
5914 // FIXME: Import macro expansions!
5915 FromLoc = FromSM.getFileLoc(FromLoc);
5916 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
5917 SourceManager &ToSM = ToContext.getSourceManager();
5918 FileID ToFileID = Import(Decomposed.first);
5919 if (ToFileID.isInvalid())
5920 return SourceLocation();
5921 SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
5922 .getLocWithOffset(Decomposed.second);
5926 SourceRange ASTImporter::Import(SourceRange FromRange) {
5927 return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
5930 FileID ASTImporter::Import(FileID FromID) {
5931 llvm::DenseMap<FileID, FileID>::iterator Pos
5932 = ImportedFileIDs.find(FromID);
5933 if (Pos != ImportedFileIDs.end())
5936 SourceManager &FromSM = FromContext.getSourceManager();
5937 SourceManager &ToSM = ToContext.getSourceManager();
5938 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
5939 assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
5941 // Include location of this file.
5942 SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
5944 // Map the FileID for to the "to" source manager.
5946 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
5947 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
5948 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
5950 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
5951 // than mmap the files several times.
5952 const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
5955 ToID = ToSM.createFileID(Entry, ToIncludeLoc,
5956 FromSLoc.getFile().getFileCharacteristic());
5958 // FIXME: We want to re-use the existing MemoryBuffer!
5959 const llvm::MemoryBuffer *
5960 FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
5961 std::unique_ptr<llvm::MemoryBuffer> ToBuf
5962 = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
5963 FromBuf->getBufferIdentifier());
5964 ToID = ToSM.createFileID(std::move(ToBuf),
5965 FromSLoc.getFile().getFileCharacteristic());
5969 ImportedFileIDs[FromID] = ToID;
5973 CXXCtorInitializer *ASTImporter::Import(CXXCtorInitializer *From) {
5974 Expr *ToExpr = Import(From->getInit());
5975 if (!ToExpr && From->getInit())
5978 if (From->isBaseInitializer()) {
5979 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
5980 if (!ToTInfo && From->getTypeSourceInfo())
5983 return new (ToContext) CXXCtorInitializer(
5984 ToContext, ToTInfo, From->isBaseVirtual(), Import(From->getLParenLoc()),
5985 ToExpr, Import(From->getRParenLoc()),
5986 From->isPackExpansion() ? Import(From->getEllipsisLoc())
5987 : SourceLocation());
5988 } else if (From->isMemberInitializer()) {
5989 FieldDecl *ToField =
5990 llvm::cast_or_null<FieldDecl>(Import(From->getMember()));
5991 if (!ToField && From->getMember())
5994 return new (ToContext) CXXCtorInitializer(
5995 ToContext, ToField, Import(From->getMemberLocation()),
5996 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
5997 } else if (From->isIndirectMemberInitializer()) {
5998 IndirectFieldDecl *ToIField = llvm::cast_or_null<IndirectFieldDecl>(
5999 Import(From->getIndirectMember()));
6000 if (!ToIField && From->getIndirectMember())
6003 return new (ToContext) CXXCtorInitializer(
6004 ToContext, ToIField, Import(From->getMemberLocation()),
6005 Import(From->getLParenLoc()), ToExpr, Import(From->getRParenLoc()));
6006 } else if (From->isDelegatingInitializer()) {
6007 TypeSourceInfo *ToTInfo = Import(From->getTypeSourceInfo());
6008 if (!ToTInfo && From->getTypeSourceInfo())
6011 return new (ToContext)
6012 CXXCtorInitializer(ToContext, ToTInfo, Import(From->getLParenLoc()),
6013 ToExpr, Import(From->getRParenLoc()));
6020 CXXBaseSpecifier *ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) {
6021 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
6022 if (Pos != ImportedCXXBaseSpecifiers.end())
6025 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
6026 Import(BaseSpec->getSourceRange()),
6027 BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
6028 BaseSpec->getAccessSpecifierAsWritten(),
6029 Import(BaseSpec->getTypeSourceInfo()),
6030 Import(BaseSpec->getEllipsisLoc()));
6031 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
6035 void ASTImporter::ImportDefinition(Decl *From) {
6036 Decl *To = Import(From);
6040 if (DeclContext *FromDC = cast<DeclContext>(From)) {
6041 ASTNodeImporter Importer(*this);
6043 if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
6044 if (!ToRecord->getDefinition()) {
6045 Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
6046 ASTNodeImporter::IDK_Everything);
6051 if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
6052 if (!ToEnum->getDefinition()) {
6053 Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
6054 ASTNodeImporter::IDK_Everything);
6059 if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
6060 if (!ToIFace->getDefinition()) {
6061 Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
6062 ASTNodeImporter::IDK_Everything);
6067 if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
6068 if (!ToProto->getDefinition()) {
6069 Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
6070 ASTNodeImporter::IDK_Everything);
6075 Importer.ImportDeclContext(FromDC, true);
6079 DeclarationName ASTImporter::Import(DeclarationName FromName) {
6081 return DeclarationName();
6083 switch (FromName.getNameKind()) {
6084 case DeclarationName::Identifier:
6085 return Import(FromName.getAsIdentifierInfo());
6087 case DeclarationName::ObjCZeroArgSelector:
6088 case DeclarationName::ObjCOneArgSelector:
6089 case DeclarationName::ObjCMultiArgSelector:
6090 return Import(FromName.getObjCSelector());
6092 case DeclarationName::CXXConstructorName: {
6093 QualType T = Import(FromName.getCXXNameType());
6095 return DeclarationName();
6097 return ToContext.DeclarationNames.getCXXConstructorName(
6098 ToContext.getCanonicalType(T));
6101 case DeclarationName::CXXDestructorName: {
6102 QualType T = Import(FromName.getCXXNameType());
6104 return DeclarationName();
6106 return ToContext.DeclarationNames.getCXXDestructorName(
6107 ToContext.getCanonicalType(T));
6110 case DeclarationName::CXXDeductionGuideName: {
6111 TemplateDecl *Template = cast_or_null<TemplateDecl>(
6112 Import(FromName.getCXXDeductionGuideTemplate()));
6114 return DeclarationName();
6115 return ToContext.DeclarationNames.getCXXDeductionGuideName(Template);
6118 case DeclarationName::CXXConversionFunctionName: {
6119 QualType T = Import(FromName.getCXXNameType());
6121 return DeclarationName();
6123 return ToContext.DeclarationNames.getCXXConversionFunctionName(
6124 ToContext.getCanonicalType(T));
6127 case DeclarationName::CXXOperatorName:
6128 return ToContext.DeclarationNames.getCXXOperatorName(
6129 FromName.getCXXOverloadedOperator());
6131 case DeclarationName::CXXLiteralOperatorName:
6132 return ToContext.DeclarationNames.getCXXLiteralOperatorName(
6133 Import(FromName.getCXXLiteralIdentifier()));
6135 case DeclarationName::CXXUsingDirective:
6137 return DeclarationName::getUsingDirectiveName();
6140 llvm_unreachable("Invalid DeclarationName Kind!");
6143 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
6147 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
6149 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
6150 ToId->setBuiltinID(FromId->getBuiltinID());
6155 Selector ASTImporter::Import(Selector FromSel) {
6156 if (FromSel.isNull())
6159 SmallVector<IdentifierInfo *, 4> Idents;
6160 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
6161 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
6162 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
6163 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
6166 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
6170 unsigned NumDecls) {
6174 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
6175 if (LastDiagFromFrom)
6176 ToContext.getDiagnostics().notePriorDiagnosticFrom(
6177 FromContext.getDiagnostics());
6178 LastDiagFromFrom = false;
6179 return ToContext.getDiagnostics().Report(Loc, DiagID);
6182 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
6183 if (!LastDiagFromFrom)
6184 FromContext.getDiagnostics().notePriorDiagnosticFrom(
6185 ToContext.getDiagnostics());
6186 LastDiagFromFrom = true;
6187 return FromContext.getDiagnostics().Report(Loc, DiagID);
6190 void ASTImporter::CompleteDecl (Decl *D) {
6191 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
6192 if (!ID->getDefinition())
6193 ID->startDefinition();
6195 else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
6196 if (!PD->getDefinition())
6197 PD->startDefinition();
6199 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
6200 if (!TD->getDefinition() && !TD->isBeingDefined()) {
6201 TD->startDefinition();
6202 TD->setCompleteDefinition(true);
6206 assert (0 && "CompleteDecl called on a Decl that can't be completed");
6210 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
6211 if (From->hasAttrs()) {
6212 for (Attr *FromAttr : From->getAttrs())
6213 To->addAttr(FromAttr->clone(To->getASTContext()));
6215 if (From->isUsed()) {
6218 if (From->isImplicit()) {
6221 ImportedDecls[From] = To;
6225 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
6227 llvm::DenseMap<const Type *, const Type *>::iterator Pos
6228 = ImportedTypes.find(From.getTypePtr());
6229 if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
6232 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
6234 return Ctx.IsStructurallyEquivalent(From, To);