1 //===--- ASTImporter.cpp - Importing ASTs from other Contexts ---*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file defines the ASTImporter class which imports AST nodes from one
11 //  context into another context.
12 //
13 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTImporter.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclVisitor.h"
20 #include "clang/AST/StmtVisitor.h"
21 #include "clang/AST/TypeVisitor.h"
22 #include "clang/Basic/FileManager.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "llvm/Support/MemoryBuffer.h"
25 #include <deque>
26 
27 namespace clang {
28   class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, QualType>,
29                           public DeclVisitor<ASTNodeImporter, Decl *>,
30                           public StmtVisitor<ASTNodeImporter, Stmt *> {
31     ASTImporter &Importer;
32 
33   public:
ASTNodeImporter(ASTImporter & Importer)34     explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) { }
35 
36     using TypeVisitor<ASTNodeImporter, QualType>::Visit;
37     using DeclVisitor<ASTNodeImporter, Decl *>::Visit;
38     using StmtVisitor<ASTNodeImporter, Stmt *>::Visit;
39 
40     // Importing types
41     QualType VisitType(const Type *T);
42     QualType VisitBuiltinType(const BuiltinType *T);
43     QualType VisitComplexType(const ComplexType *T);
44     QualType VisitPointerType(const PointerType *T);
45     QualType VisitBlockPointerType(const BlockPointerType *T);
46     QualType VisitLValueReferenceType(const LValueReferenceType *T);
47     QualType VisitRValueReferenceType(const RValueReferenceType *T);
48     QualType VisitMemberPointerType(const MemberPointerType *T);
49     QualType VisitConstantArrayType(const ConstantArrayType *T);
50     QualType VisitIncompleteArrayType(const IncompleteArrayType *T);
51     QualType VisitVariableArrayType(const VariableArrayType *T);
52     // FIXME: DependentSizedArrayType
53     // FIXME: DependentSizedExtVectorType
54     QualType VisitVectorType(const VectorType *T);
55     QualType VisitExtVectorType(const ExtVectorType *T);
56     QualType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
57     QualType VisitFunctionProtoType(const FunctionProtoType *T);
58     // FIXME: UnresolvedUsingType
59     QualType VisitParenType(const ParenType *T);
60     QualType VisitTypedefType(const TypedefType *T);
61     QualType VisitTypeOfExprType(const TypeOfExprType *T);
62     // FIXME: DependentTypeOfExprType
63     QualType VisitTypeOfType(const TypeOfType *T);
64     QualType VisitDecltypeType(const DecltypeType *T);
65     QualType VisitUnaryTransformType(const UnaryTransformType *T);
66     QualType VisitAutoType(const AutoType *T);
67     // FIXME: DependentDecltypeType
68     QualType VisitRecordType(const RecordType *T);
69     QualType VisitEnumType(const EnumType *T);
70     QualType VisitAttributedType(const AttributedType *T);
71     // FIXME: TemplateTypeParmType
72     // FIXME: SubstTemplateTypeParmType
73     QualType VisitTemplateSpecializationType(const TemplateSpecializationType *T);
74     QualType VisitElaboratedType(const ElaboratedType *T);
75     // FIXME: DependentNameType
76     // FIXME: DependentTemplateSpecializationType
77     QualType VisitObjCInterfaceType(const ObjCInterfaceType *T);
78     QualType VisitObjCObjectType(const ObjCObjectType *T);
79     QualType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
80 
81     // Importing declarations
82     bool ImportDeclParts(NamedDecl *D, DeclContext *&DC,
83                          DeclContext *&LexicalDC, DeclarationName &Name,
84                          NamedDecl *&ToD, SourceLocation &Loc);
85     void ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
86     void ImportDeclarationNameLoc(const DeclarationNameInfo &From,
87                                   DeclarationNameInfo& To);
88     void ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
89 
90     /// \brief What we should import from the definition.
91     enum ImportDefinitionKind {
92       /// \brief Import the default subset of the definition, which might be
93       /// nothing (if minimal import is set) or might be everything (if minimal
94       /// import is not set).
95       IDK_Default,
96       /// \brief Import everything.
97       IDK_Everything,
98       /// \brief Import only the bare bones needed to establish a valid
99       /// DeclContext.
100       IDK_Basic
101     };
102 
shouldForceImportDeclContext(ImportDefinitionKind IDK)103     bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
104       return IDK == IDK_Everything ||
105              (IDK == IDK_Default && !Importer.isMinimalImport());
106     }
107 
108     bool ImportDefinition(RecordDecl *From, RecordDecl *To,
109                           ImportDefinitionKind Kind = IDK_Default);
110     bool ImportDefinition(VarDecl *From, VarDecl *To,
111                           ImportDefinitionKind Kind = IDK_Default);
112     bool ImportDefinition(EnumDecl *From, EnumDecl *To,
113                           ImportDefinitionKind Kind = IDK_Default);
114     bool ImportDefinition(ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
115                           ImportDefinitionKind Kind = IDK_Default);
116     bool ImportDefinition(ObjCProtocolDecl *From, ObjCProtocolDecl *To,
117                           ImportDefinitionKind Kind = IDK_Default);
118     TemplateParameterList *ImportTemplateParameterList(
119                                                  TemplateParameterList *Params);
120     TemplateArgument ImportTemplateArgument(const TemplateArgument &From);
121     bool ImportTemplateArguments(const TemplateArgument *FromArgs,
122                                  unsigned NumFromArgs,
123                                SmallVectorImpl<TemplateArgument> &ToArgs);
124     bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
125                            bool Complain = true);
126     bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
127                            bool Complain = true);
128     bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
129     bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
130     bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
131     bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
132     Decl *VisitDecl(Decl *D);
133     Decl *VisitTranslationUnitDecl(TranslationUnitDecl *D);
134     Decl *VisitNamespaceDecl(NamespaceDecl *D);
135     Decl *VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
136     Decl *VisitTypedefDecl(TypedefDecl *D);
137     Decl *VisitTypeAliasDecl(TypeAliasDecl *D);
138     Decl *VisitEnumDecl(EnumDecl *D);
139     Decl *VisitRecordDecl(RecordDecl *D);
140     Decl *VisitEnumConstantDecl(EnumConstantDecl *D);
141     Decl *VisitFunctionDecl(FunctionDecl *D);
142     Decl *VisitCXXMethodDecl(CXXMethodDecl *D);
143     Decl *VisitCXXConstructorDecl(CXXConstructorDecl *D);
144     Decl *VisitCXXDestructorDecl(CXXDestructorDecl *D);
145     Decl *VisitCXXConversionDecl(CXXConversionDecl *D);
146     Decl *VisitFieldDecl(FieldDecl *D);
147     Decl *VisitIndirectFieldDecl(IndirectFieldDecl *D);
148     Decl *VisitObjCIvarDecl(ObjCIvarDecl *D);
149     Decl *VisitVarDecl(VarDecl *D);
150     Decl *VisitImplicitParamDecl(ImplicitParamDecl *D);
151     Decl *VisitParmVarDecl(ParmVarDecl *D);
152     Decl *VisitObjCMethodDecl(ObjCMethodDecl *D);
153     Decl *VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
154     Decl *VisitObjCCategoryDecl(ObjCCategoryDecl *D);
155     Decl *VisitObjCProtocolDecl(ObjCProtocolDecl *D);
156     Decl *VisitLinkageSpecDecl(LinkageSpecDecl *D);
157 
158     ObjCTypeParamList *ImportObjCTypeParamList(ObjCTypeParamList *list);
159     Decl *VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
160     Decl *VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
161     Decl *VisitObjCImplementationDecl(ObjCImplementationDecl *D);
162     Decl *VisitObjCPropertyDecl(ObjCPropertyDecl *D);
163     Decl *VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
164     Decl *VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
165     Decl *VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
166     Decl *VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
167     Decl *VisitClassTemplateDecl(ClassTemplateDecl *D);
168     Decl *VisitClassTemplateSpecializationDecl(
169                                             ClassTemplateSpecializationDecl *D);
170     Decl *VisitVarTemplateDecl(VarTemplateDecl *D);
171     Decl *VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
172 
173     // Importing statements
174     DeclGroupRef ImportDeclGroup(DeclGroupRef DG);
175 
176     Stmt *VisitStmt(Stmt *S);
177     Stmt *VisitDeclStmt(DeclStmt *S);
178     Stmt *VisitNullStmt(NullStmt *S);
179     Stmt *VisitCompoundStmt(CompoundStmt *S);
180     Stmt *VisitCaseStmt(CaseStmt *S);
181     Stmt *VisitDefaultStmt(DefaultStmt *S);
182     Stmt *VisitLabelStmt(LabelStmt *S);
183     Stmt *VisitAttributedStmt(AttributedStmt *S);
184     Stmt *VisitIfStmt(IfStmt *S);
185     Stmt *VisitSwitchStmt(SwitchStmt *S);
186     Stmt *VisitWhileStmt(WhileStmt *S);
187     Stmt *VisitDoStmt(DoStmt *S);
188     Stmt *VisitForStmt(ForStmt *S);
189     Stmt *VisitGotoStmt(GotoStmt *S);
190     Stmt *VisitIndirectGotoStmt(IndirectGotoStmt *S);
191     Stmt *VisitContinueStmt(ContinueStmt *S);
192     Stmt *VisitBreakStmt(BreakStmt *S);
193     Stmt *VisitReturnStmt(ReturnStmt *S);
194     // FIXME: GCCAsmStmt
195     // FIXME: MSAsmStmt
196     // FIXME: SEHExceptStmt
197     // FIXME: SEHFinallyStmt
198     // FIXME: SEHTryStmt
199     // FIXME: SEHLeaveStmt
200     // FIXME: CapturedStmt
201     Stmt *VisitCXXCatchStmt(CXXCatchStmt *S);
202     Stmt *VisitCXXTryStmt(CXXTryStmt *S);
203     Stmt *VisitCXXForRangeStmt(CXXForRangeStmt *S);
204     // FIXME: MSDependentExistsStmt
205     Stmt *VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
206     Stmt *VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
207     Stmt *VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
208     Stmt *VisitObjCAtTryStmt(ObjCAtTryStmt *S);
209     Stmt *VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
210     Stmt *VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
211     Stmt *VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
212 
213     // Importing expressions
214     Expr *VisitExpr(Expr *E);
215     Expr *VisitDeclRefExpr(DeclRefExpr *E);
216     Expr *VisitIntegerLiteral(IntegerLiteral *E);
217     Expr *VisitCharacterLiteral(CharacterLiteral *E);
218     Expr *VisitParenExpr(ParenExpr *E);
219     Expr *VisitUnaryOperator(UnaryOperator *E);
220     Expr *VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
221     Expr *VisitBinaryOperator(BinaryOperator *E);
222     Expr *VisitCompoundAssignOperator(CompoundAssignOperator *E);
223     Expr *VisitImplicitCastExpr(ImplicitCastExpr *E);
224     Expr *VisitCStyleCastExpr(CStyleCastExpr *E);
225     Expr *VisitCXXConstructExpr(CXXConstructExpr *E);
226     Expr *VisitMemberExpr(MemberExpr *E);
227     Expr *VisitCallExpr(CallExpr *E);
228   };
229 }
230 using namespace clang;
231 
232 //----------------------------------------------------------------------------
233 // Structural Equivalence
234 //----------------------------------------------------------------------------
235 
236 namespace {
237   struct StructuralEquivalenceContext {
238     /// \brief AST contexts for which we are checking structural equivalence.
239     ASTContext &C1, &C2;
240 
241     /// \brief The set of "tentative" equivalences between two canonical
242     /// declarations, mapping from a declaration in the first context to the
243     /// declaration in the second context that we believe to be equivalent.
244     llvm::DenseMap<Decl *, Decl *> TentativeEquivalences;
245 
246     /// \brief Queue of declarations in the first context whose equivalence
247     /// with a declaration in the second context still needs to be verified.
248     std::deque<Decl *> DeclsToCheck;
249 
250     /// \brief Declaration (from, to) pairs that are known not to be equivalent
251     /// (which we have already complained about).
252     llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls;
253 
254     /// \brief Whether we're being strict about the spelling of types when
255     /// unifying two types.
256     bool StrictTypeSpelling;
257 
258     /// \brief Whether to complain about failures.
259     bool Complain;
260 
261     /// \brief \c true if the last diagnostic came from C2.
262     bool LastDiagFromC2;
263 
StructuralEquivalenceContext__anone728b20d0111::StructuralEquivalenceContext264     StructuralEquivalenceContext(ASTContext &C1, ASTContext &C2,
265                llvm::DenseSet<std::pair<Decl *, Decl *> > &NonEquivalentDecls,
266                                  bool StrictTypeSpelling = false,
267                                  bool Complain = true)
268       : C1(C1), C2(C2), NonEquivalentDecls(NonEquivalentDecls),
269         StrictTypeSpelling(StrictTypeSpelling), Complain(Complain),
270         LastDiagFromC2(false) {}
271 
272     /// \brief Determine whether the two declarations are structurally
273     /// equivalent.
274     bool IsStructurallyEquivalent(Decl *D1, Decl *D2);
275 
276     /// \brief Determine whether the two types are structurally equivalent.
277     bool IsStructurallyEquivalent(QualType T1, QualType T2);
278 
279   private:
280     /// \brief Finish checking all of the structural equivalences.
281     ///
282     /// \returns true if an error occurred, false otherwise.
283     bool Finish();
284 
285   public:
Diag1__anone728b20d0111::StructuralEquivalenceContext286     DiagnosticBuilder Diag1(SourceLocation Loc, unsigned DiagID) {
287       assert(Complain && "Not allowed to complain");
288       if (LastDiagFromC2)
289         C1.getDiagnostics().notePriorDiagnosticFrom(C2.getDiagnostics());
290       LastDiagFromC2 = false;
291       return C1.getDiagnostics().Report(Loc, DiagID);
292     }
293 
Diag2__anone728b20d0111::StructuralEquivalenceContext294     DiagnosticBuilder Diag2(SourceLocation Loc, unsigned DiagID) {
295       assert(Complain && "Not allowed to complain");
296       if (!LastDiagFromC2)
297         C2.getDiagnostics().notePriorDiagnosticFrom(C1.getDiagnostics());
298       LastDiagFromC2 = true;
299       return C2.getDiagnostics().Report(Loc, DiagID);
300     }
301   };
302 }
303 
304 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
305                                      QualType T1, QualType T2);
306 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
307                                      Decl *D1, Decl *D2);
308 
309 /// \brief Determine structural equivalence of two expressions.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Expr * E1,Expr * E2)310 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
311                                      Expr *E1, Expr *E2) {
312   if (!E1 || !E2)
313     return E1 == E2;
314 
315   // FIXME: Actually perform a structural comparison!
316   return true;
317 }
318 
319 /// \brief Determine whether two identifiers are equivalent.
IsStructurallyEquivalent(const IdentifierInfo * Name1,const IdentifierInfo * Name2)320 static bool IsStructurallyEquivalent(const IdentifierInfo *Name1,
321                                      const IdentifierInfo *Name2) {
322   if (!Name1 || !Name2)
323     return Name1 == Name2;
324 
325   return Name1->getName() == Name2->getName();
326 }
327 
328 /// \brief Determine whether two nested-name-specifiers are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NestedNameSpecifier * NNS1,NestedNameSpecifier * NNS2)329 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
330                                      NestedNameSpecifier *NNS1,
331                                      NestedNameSpecifier *NNS2) {
332   // FIXME: Implement!
333   return true;
334 }
335 
336 /// \brief Determine whether two template arguments are equivalent.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,const TemplateArgument & Arg1,const TemplateArgument & Arg2)337 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
338                                      const TemplateArgument &Arg1,
339                                      const TemplateArgument &Arg2) {
340   if (Arg1.getKind() != Arg2.getKind())
341     return false;
342 
343   switch (Arg1.getKind()) {
344   case TemplateArgument::Null:
345     return true;
346 
347   case TemplateArgument::Type:
348     return Context.IsStructurallyEquivalent(Arg1.getAsType(), Arg2.getAsType());
349 
350   case TemplateArgument::Integral:
351     if (!Context.IsStructurallyEquivalent(Arg1.getIntegralType(),
352                                           Arg2.getIntegralType()))
353       return false;
354 
355     return llvm::APSInt::isSameValue(Arg1.getAsIntegral(), Arg2.getAsIntegral());
356 
357   case TemplateArgument::Declaration:
358     return Context.IsStructurallyEquivalent(Arg1.getAsDecl(), Arg2.getAsDecl());
359 
360   case TemplateArgument::NullPtr:
361     return true; // FIXME: Is this correct?
362 
363   case TemplateArgument::Template:
364     return IsStructurallyEquivalent(Context,
365                                     Arg1.getAsTemplate(),
366                                     Arg2.getAsTemplate());
367 
368   case TemplateArgument::TemplateExpansion:
369     return IsStructurallyEquivalent(Context,
370                                     Arg1.getAsTemplateOrTemplatePattern(),
371                                     Arg2.getAsTemplateOrTemplatePattern());
372 
373   case TemplateArgument::Expression:
374     return IsStructurallyEquivalent(Context,
375                                     Arg1.getAsExpr(), Arg2.getAsExpr());
376 
377   case TemplateArgument::Pack:
378     if (Arg1.pack_size() != Arg2.pack_size())
379       return false;
380 
381     for (unsigned I = 0, N = Arg1.pack_size(); I != N; ++I)
382       if (!IsStructurallyEquivalent(Context,
383                                     Arg1.pack_begin()[I],
384                                     Arg2.pack_begin()[I]))
385         return false;
386 
387     return true;
388   }
389 
390   llvm_unreachable("Invalid template argument kind");
391 }
392 
393 /// \brief Determine structural equivalence for the common part of array
394 /// types.
IsArrayStructurallyEquivalent(StructuralEquivalenceContext & Context,const ArrayType * Array1,const ArrayType * Array2)395 static bool IsArrayStructurallyEquivalent(StructuralEquivalenceContext &Context,
396                                           const ArrayType *Array1,
397                                           const ArrayType *Array2) {
398   if (!IsStructurallyEquivalent(Context,
399                                 Array1->getElementType(),
400                                 Array2->getElementType()))
401     return false;
402   if (Array1->getSizeModifier() != Array2->getSizeModifier())
403     return false;
404   if (Array1->getIndexTypeQualifiers() != Array2->getIndexTypeQualifiers())
405     return false;
406 
407   return true;
408 }
409 
410 /// \brief Determine structural equivalence of two types.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,QualType T1,QualType T2)411 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
412                                      QualType T1, QualType T2) {
413   if (T1.isNull() || T2.isNull())
414     return T1.isNull() && T2.isNull();
415 
416   if (!Context.StrictTypeSpelling) {
417     // We aren't being strict about token-to-token equivalence of types,
418     // so map down to the canonical type.
419     T1 = Context.C1.getCanonicalType(T1);
420     T2 = Context.C2.getCanonicalType(T2);
421   }
422 
423   if (T1.getQualifiers() != T2.getQualifiers())
424     return false;
425 
426   Type::TypeClass TC = T1->getTypeClass();
427 
428   if (T1->getTypeClass() != T2->getTypeClass()) {
429     // Compare function types with prototypes vs. without prototypes as if
430     // both did not have prototypes.
431     if (T1->getTypeClass() == Type::FunctionProto &&
432         T2->getTypeClass() == Type::FunctionNoProto)
433       TC = Type::FunctionNoProto;
434     else if (T1->getTypeClass() == Type::FunctionNoProto &&
435              T2->getTypeClass() == Type::FunctionProto)
436       TC = Type::FunctionNoProto;
437     else
438       return false;
439   }
440 
441   switch (TC) {
442   case Type::Builtin:
443     // FIXME: Deal with Char_S/Char_U.
444     if (cast<BuiltinType>(T1)->getKind() != cast<BuiltinType>(T2)->getKind())
445       return false;
446     break;
447 
448   case Type::Complex:
449     if (!IsStructurallyEquivalent(Context,
450                                   cast<ComplexType>(T1)->getElementType(),
451                                   cast<ComplexType>(T2)->getElementType()))
452       return false;
453     break;
454 
455   case Type::Adjusted:
456   case Type::Decayed:
457     if (!IsStructurallyEquivalent(Context,
458                                   cast<AdjustedType>(T1)->getOriginalType(),
459                                   cast<AdjustedType>(T2)->getOriginalType()))
460       return false;
461     break;
462 
463   case Type::Pointer:
464     if (!IsStructurallyEquivalent(Context,
465                                   cast<PointerType>(T1)->getPointeeType(),
466                                   cast<PointerType>(T2)->getPointeeType()))
467       return false;
468     break;
469 
470   case Type::BlockPointer:
471     if (!IsStructurallyEquivalent(Context,
472                                   cast<BlockPointerType>(T1)->getPointeeType(),
473                                   cast<BlockPointerType>(T2)->getPointeeType()))
474       return false;
475     break;
476 
477   case Type::LValueReference:
478   case Type::RValueReference: {
479     const ReferenceType *Ref1 = cast<ReferenceType>(T1);
480     const ReferenceType *Ref2 = cast<ReferenceType>(T2);
481     if (Ref1->isSpelledAsLValue() != Ref2->isSpelledAsLValue())
482       return false;
483     if (Ref1->isInnerRef() != Ref2->isInnerRef())
484       return false;
485     if (!IsStructurallyEquivalent(Context,
486                                   Ref1->getPointeeTypeAsWritten(),
487                                   Ref2->getPointeeTypeAsWritten()))
488       return false;
489     break;
490   }
491 
492   case Type::MemberPointer: {
493     const MemberPointerType *MemPtr1 = cast<MemberPointerType>(T1);
494     const MemberPointerType *MemPtr2 = cast<MemberPointerType>(T2);
495     if (!IsStructurallyEquivalent(Context,
496                                   MemPtr1->getPointeeType(),
497                                   MemPtr2->getPointeeType()))
498       return false;
499     if (!IsStructurallyEquivalent(Context,
500                                   QualType(MemPtr1->getClass(), 0),
501                                   QualType(MemPtr2->getClass(), 0)))
502       return false;
503     break;
504   }
505 
506   case Type::ConstantArray: {
507     const ConstantArrayType *Array1 = cast<ConstantArrayType>(T1);
508     const ConstantArrayType *Array2 = cast<ConstantArrayType>(T2);
509     if (!llvm::APInt::isSameValue(Array1->getSize(), Array2->getSize()))
510       return false;
511 
512     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
513       return false;
514     break;
515   }
516 
517   case Type::IncompleteArray:
518     if (!IsArrayStructurallyEquivalent(Context,
519                                        cast<ArrayType>(T1),
520                                        cast<ArrayType>(T2)))
521       return false;
522     break;
523 
524   case Type::VariableArray: {
525     const VariableArrayType *Array1 = cast<VariableArrayType>(T1);
526     const VariableArrayType *Array2 = cast<VariableArrayType>(T2);
527     if (!IsStructurallyEquivalent(Context,
528                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
529       return false;
530 
531     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
532       return false;
533 
534     break;
535   }
536 
537   case Type::DependentSizedArray: {
538     const DependentSizedArrayType *Array1 = cast<DependentSizedArrayType>(T1);
539     const DependentSizedArrayType *Array2 = cast<DependentSizedArrayType>(T2);
540     if (!IsStructurallyEquivalent(Context,
541                                   Array1->getSizeExpr(), Array2->getSizeExpr()))
542       return false;
543 
544     if (!IsArrayStructurallyEquivalent(Context, Array1, Array2))
545       return false;
546 
547     break;
548   }
549 
550   case Type::DependentSizedExtVector: {
551     const DependentSizedExtVectorType *Vec1
552       = cast<DependentSizedExtVectorType>(T1);
553     const DependentSizedExtVectorType *Vec2
554       = cast<DependentSizedExtVectorType>(T2);
555     if (!IsStructurallyEquivalent(Context,
556                                   Vec1->getSizeExpr(), Vec2->getSizeExpr()))
557       return false;
558     if (!IsStructurallyEquivalent(Context,
559                                   Vec1->getElementType(),
560                                   Vec2->getElementType()))
561       return false;
562     break;
563   }
564 
565   case Type::Vector:
566   case Type::ExtVector: {
567     const VectorType *Vec1 = cast<VectorType>(T1);
568     const VectorType *Vec2 = cast<VectorType>(T2);
569     if (!IsStructurallyEquivalent(Context,
570                                   Vec1->getElementType(),
571                                   Vec2->getElementType()))
572       return false;
573     if (Vec1->getNumElements() != Vec2->getNumElements())
574       return false;
575     if (Vec1->getVectorKind() != Vec2->getVectorKind())
576       return false;
577     break;
578   }
579 
580   case Type::FunctionProto: {
581     const FunctionProtoType *Proto1 = cast<FunctionProtoType>(T1);
582     const FunctionProtoType *Proto2 = cast<FunctionProtoType>(T2);
583     if (Proto1->getNumParams() != Proto2->getNumParams())
584       return false;
585     for (unsigned I = 0, N = Proto1->getNumParams(); I != N; ++I) {
586       if (!IsStructurallyEquivalent(Context, Proto1->getParamType(I),
587                                     Proto2->getParamType(I)))
588         return false;
589     }
590     if (Proto1->isVariadic() != Proto2->isVariadic())
591       return false;
592     if (Proto1->getExceptionSpecType() != Proto2->getExceptionSpecType())
593       return false;
594     if (Proto1->getExceptionSpecType() == EST_Dynamic) {
595       if (Proto1->getNumExceptions() != Proto2->getNumExceptions())
596         return false;
597       for (unsigned I = 0, N = Proto1->getNumExceptions(); I != N; ++I) {
598         if (!IsStructurallyEquivalent(Context,
599                                       Proto1->getExceptionType(I),
600                                       Proto2->getExceptionType(I)))
601           return false;
602       }
603     } else if (Proto1->getExceptionSpecType() == EST_ComputedNoexcept) {
604       if (!IsStructurallyEquivalent(Context,
605                                     Proto1->getNoexceptExpr(),
606                                     Proto2->getNoexceptExpr()))
607         return false;
608     }
609     if (Proto1->getTypeQuals() != Proto2->getTypeQuals())
610       return false;
611 
612     // Fall through to check the bits common with FunctionNoProtoType.
613   }
614 
615   case Type::FunctionNoProto: {
616     const FunctionType *Function1 = cast<FunctionType>(T1);
617     const FunctionType *Function2 = cast<FunctionType>(T2);
618     if (!IsStructurallyEquivalent(Context, Function1->getReturnType(),
619                                   Function2->getReturnType()))
620       return false;
621       if (Function1->getExtInfo() != Function2->getExtInfo())
622         return false;
623     break;
624   }
625 
626   case Type::UnresolvedUsing:
627     if (!IsStructurallyEquivalent(Context,
628                                   cast<UnresolvedUsingType>(T1)->getDecl(),
629                                   cast<UnresolvedUsingType>(T2)->getDecl()))
630       return false;
631 
632     break;
633 
634   case Type::Attributed:
635     if (!IsStructurallyEquivalent(Context,
636                                   cast<AttributedType>(T1)->getModifiedType(),
637                                   cast<AttributedType>(T2)->getModifiedType()))
638       return false;
639     if (!IsStructurallyEquivalent(Context,
640                                 cast<AttributedType>(T1)->getEquivalentType(),
641                                 cast<AttributedType>(T2)->getEquivalentType()))
642       return false;
643     break;
644 
645   case Type::Paren:
646     if (!IsStructurallyEquivalent(Context,
647                                   cast<ParenType>(T1)->getInnerType(),
648                                   cast<ParenType>(T2)->getInnerType()))
649       return false;
650     break;
651 
652   case Type::Typedef:
653     if (!IsStructurallyEquivalent(Context,
654                                   cast<TypedefType>(T1)->getDecl(),
655                                   cast<TypedefType>(T2)->getDecl()))
656       return false;
657     break;
658 
659   case Type::TypeOfExpr:
660     if (!IsStructurallyEquivalent(Context,
661                                 cast<TypeOfExprType>(T1)->getUnderlyingExpr(),
662                                 cast<TypeOfExprType>(T2)->getUnderlyingExpr()))
663       return false;
664     break;
665 
666   case Type::TypeOf:
667     if (!IsStructurallyEquivalent(Context,
668                                   cast<TypeOfType>(T1)->getUnderlyingType(),
669                                   cast<TypeOfType>(T2)->getUnderlyingType()))
670       return false;
671     break;
672 
673   case Type::UnaryTransform:
674     if (!IsStructurallyEquivalent(Context,
675                              cast<UnaryTransformType>(T1)->getUnderlyingType(),
676                              cast<UnaryTransformType>(T1)->getUnderlyingType()))
677       return false;
678     break;
679 
680   case Type::Decltype:
681     if (!IsStructurallyEquivalent(Context,
682                                   cast<DecltypeType>(T1)->getUnderlyingExpr(),
683                                   cast<DecltypeType>(T2)->getUnderlyingExpr()))
684       return false;
685     break;
686 
687   case Type::Auto:
688     if (!IsStructurallyEquivalent(Context,
689                                   cast<AutoType>(T1)->getDeducedType(),
690                                   cast<AutoType>(T2)->getDeducedType()))
691       return false;
692     break;
693 
694   case Type::Record:
695   case Type::Enum:
696     if (!IsStructurallyEquivalent(Context,
697                                   cast<TagType>(T1)->getDecl(),
698                                   cast<TagType>(T2)->getDecl()))
699       return false;
700     break;
701 
702   case Type::TemplateTypeParm: {
703     const TemplateTypeParmType *Parm1 = cast<TemplateTypeParmType>(T1);
704     const TemplateTypeParmType *Parm2 = cast<TemplateTypeParmType>(T2);
705     if (Parm1->getDepth() != Parm2->getDepth())
706       return false;
707     if (Parm1->getIndex() != Parm2->getIndex())
708       return false;
709     if (Parm1->isParameterPack() != Parm2->isParameterPack())
710       return false;
711 
712     // Names of template type parameters are never significant.
713     break;
714   }
715 
716   case Type::SubstTemplateTypeParm: {
717     const SubstTemplateTypeParmType *Subst1
718       = cast<SubstTemplateTypeParmType>(T1);
719     const SubstTemplateTypeParmType *Subst2
720       = cast<SubstTemplateTypeParmType>(T2);
721     if (!IsStructurallyEquivalent(Context,
722                                   QualType(Subst1->getReplacedParameter(), 0),
723                                   QualType(Subst2->getReplacedParameter(), 0)))
724       return false;
725     if (!IsStructurallyEquivalent(Context,
726                                   Subst1->getReplacementType(),
727                                   Subst2->getReplacementType()))
728       return false;
729     break;
730   }
731 
732   case Type::SubstTemplateTypeParmPack: {
733     const SubstTemplateTypeParmPackType *Subst1
734       = cast<SubstTemplateTypeParmPackType>(T1);
735     const SubstTemplateTypeParmPackType *Subst2
736       = cast<SubstTemplateTypeParmPackType>(T2);
737     if (!IsStructurallyEquivalent(Context,
738                                   QualType(Subst1->getReplacedParameter(), 0),
739                                   QualType(Subst2->getReplacedParameter(), 0)))
740       return false;
741     if (!IsStructurallyEquivalent(Context,
742                                   Subst1->getArgumentPack(),
743                                   Subst2->getArgumentPack()))
744       return false;
745     break;
746   }
747   case Type::TemplateSpecialization: {
748     const TemplateSpecializationType *Spec1
749       = cast<TemplateSpecializationType>(T1);
750     const TemplateSpecializationType *Spec2
751       = cast<TemplateSpecializationType>(T2);
752     if (!IsStructurallyEquivalent(Context,
753                                   Spec1->getTemplateName(),
754                                   Spec2->getTemplateName()))
755       return false;
756     if (Spec1->getNumArgs() != Spec2->getNumArgs())
757       return false;
758     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
759       if (!IsStructurallyEquivalent(Context,
760                                     Spec1->getArg(I), Spec2->getArg(I)))
761         return false;
762     }
763     break;
764   }
765 
766   case Type::Elaborated: {
767     const ElaboratedType *Elab1 = cast<ElaboratedType>(T1);
768     const ElaboratedType *Elab2 = cast<ElaboratedType>(T2);
769     // CHECKME: what if a keyword is ETK_None or ETK_typename ?
770     if (Elab1->getKeyword() != Elab2->getKeyword())
771       return false;
772     if (!IsStructurallyEquivalent(Context,
773                                   Elab1->getQualifier(),
774                                   Elab2->getQualifier()))
775       return false;
776     if (!IsStructurallyEquivalent(Context,
777                                   Elab1->getNamedType(),
778                                   Elab2->getNamedType()))
779       return false;
780     break;
781   }
782 
783   case Type::InjectedClassName: {
784     const InjectedClassNameType *Inj1 = cast<InjectedClassNameType>(T1);
785     const InjectedClassNameType *Inj2 = cast<InjectedClassNameType>(T2);
786     if (!IsStructurallyEquivalent(Context,
787                                   Inj1->getInjectedSpecializationType(),
788                                   Inj2->getInjectedSpecializationType()))
789       return false;
790     break;
791   }
792 
793   case Type::DependentName: {
794     const DependentNameType *Typename1 = cast<DependentNameType>(T1);
795     const DependentNameType *Typename2 = cast<DependentNameType>(T2);
796     if (!IsStructurallyEquivalent(Context,
797                                   Typename1->getQualifier(),
798                                   Typename2->getQualifier()))
799       return false;
800     if (!IsStructurallyEquivalent(Typename1->getIdentifier(),
801                                   Typename2->getIdentifier()))
802       return false;
803 
804     break;
805   }
806 
807   case Type::DependentTemplateSpecialization: {
808     const DependentTemplateSpecializationType *Spec1 =
809       cast<DependentTemplateSpecializationType>(T1);
810     const DependentTemplateSpecializationType *Spec2 =
811       cast<DependentTemplateSpecializationType>(T2);
812     if (!IsStructurallyEquivalent(Context,
813                                   Spec1->getQualifier(),
814                                   Spec2->getQualifier()))
815       return false;
816     if (!IsStructurallyEquivalent(Spec1->getIdentifier(),
817                                   Spec2->getIdentifier()))
818       return false;
819     if (Spec1->getNumArgs() != Spec2->getNumArgs())
820       return false;
821     for (unsigned I = 0, N = Spec1->getNumArgs(); I != N; ++I) {
822       if (!IsStructurallyEquivalent(Context,
823                                     Spec1->getArg(I), Spec2->getArg(I)))
824         return false;
825     }
826     break;
827   }
828 
829   case Type::PackExpansion:
830     if (!IsStructurallyEquivalent(Context,
831                                   cast<PackExpansionType>(T1)->getPattern(),
832                                   cast<PackExpansionType>(T2)->getPattern()))
833       return false;
834     break;
835 
836   case Type::ObjCInterface: {
837     const ObjCInterfaceType *Iface1 = cast<ObjCInterfaceType>(T1);
838     const ObjCInterfaceType *Iface2 = cast<ObjCInterfaceType>(T2);
839     if (!IsStructurallyEquivalent(Context,
840                                   Iface1->getDecl(), Iface2->getDecl()))
841       return false;
842     break;
843   }
844 
845   case Type::ObjCObject: {
846     const ObjCObjectType *Obj1 = cast<ObjCObjectType>(T1);
847     const ObjCObjectType *Obj2 = cast<ObjCObjectType>(T2);
848     if (!IsStructurallyEquivalent(Context,
849                                   Obj1->getBaseType(),
850                                   Obj2->getBaseType()))
851       return false;
852     if (Obj1->getNumProtocols() != Obj2->getNumProtocols())
853       return false;
854     for (unsigned I = 0, N = Obj1->getNumProtocols(); I != N; ++I) {
855       if (!IsStructurallyEquivalent(Context,
856                                     Obj1->getProtocol(I),
857                                     Obj2->getProtocol(I)))
858         return false;
859     }
860     break;
861   }
862 
863   case Type::ObjCObjectPointer: {
864     const ObjCObjectPointerType *Ptr1 = cast<ObjCObjectPointerType>(T1);
865     const ObjCObjectPointerType *Ptr2 = cast<ObjCObjectPointerType>(T2);
866     if (!IsStructurallyEquivalent(Context,
867                                   Ptr1->getPointeeType(),
868                                   Ptr2->getPointeeType()))
869       return false;
870     break;
871   }
872 
873   case Type::Atomic: {
874     if (!IsStructurallyEquivalent(Context,
875                                   cast<AtomicType>(T1)->getValueType(),
876                                   cast<AtomicType>(T2)->getValueType()))
877       return false;
878     break;
879   }
880 
881   } // end switch
882 
883   return true;
884 }
885 
886 /// \brief Determine structural equivalence of two fields.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,FieldDecl * Field1,FieldDecl * Field2)887 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
888                                      FieldDecl *Field1, FieldDecl *Field2) {
889   RecordDecl *Owner2 = cast<RecordDecl>(Field2->getDeclContext());
890 
891   // For anonymous structs/unions, match up the anonymous struct/union type
892   // declarations directly, so that we don't go off searching for anonymous
893   // types
894   if (Field1->isAnonymousStructOrUnion() &&
895       Field2->isAnonymousStructOrUnion()) {
896     RecordDecl *D1 = Field1->getType()->castAs<RecordType>()->getDecl();
897     RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
898     return IsStructurallyEquivalent(Context, D1, D2);
899   }
900 
901   // Check for equivalent field names.
902   IdentifierInfo *Name1 = Field1->getIdentifier();
903   IdentifierInfo *Name2 = Field2->getIdentifier();
904   if (!::IsStructurallyEquivalent(Name1, Name2))
905     return false;
906 
907   if (!IsStructurallyEquivalent(Context,
908                                 Field1->getType(), Field2->getType())) {
909     if (Context.Complain) {
910       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
911         << Context.C2.getTypeDeclType(Owner2);
912       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
913         << Field2->getDeclName() << Field2->getType();
914       Context.Diag1(Field1->getLocation(), diag::note_odr_field)
915         << Field1->getDeclName() << Field1->getType();
916     }
917     return false;
918   }
919 
920   if (Field1->isBitField() != Field2->isBitField()) {
921     if (Context.Complain) {
922       Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
923         << Context.C2.getTypeDeclType(Owner2);
924       if (Field1->isBitField()) {
925         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
926         << Field1->getDeclName() << Field1->getType()
927         << Field1->getBitWidthValue(Context.C1);
928         Context.Diag2(Field2->getLocation(), diag::note_odr_not_bit_field)
929         << Field2->getDeclName();
930       } else {
931         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
932         << Field2->getDeclName() << Field2->getType()
933         << Field2->getBitWidthValue(Context.C2);
934         Context.Diag1(Field1->getLocation(), diag::note_odr_not_bit_field)
935         << Field1->getDeclName();
936       }
937     }
938     return false;
939   }
940 
941   if (Field1->isBitField()) {
942     // Make sure that the bit-fields are the same length.
943     unsigned Bits1 = Field1->getBitWidthValue(Context.C1);
944     unsigned Bits2 = Field2->getBitWidthValue(Context.C2);
945 
946     if (Bits1 != Bits2) {
947       if (Context.Complain) {
948         Context.Diag2(Owner2->getLocation(), diag::warn_odr_tag_type_inconsistent)
949           << Context.C2.getTypeDeclType(Owner2);
950         Context.Diag2(Field2->getLocation(), diag::note_odr_bit_field)
951           << Field2->getDeclName() << Field2->getType() << Bits2;
952         Context.Diag1(Field1->getLocation(), diag::note_odr_bit_field)
953           << Field1->getDeclName() << Field1->getType() << Bits1;
954       }
955       return false;
956     }
957   }
958 
959   return true;
960 }
961 
962 /// \brief Find the index of the given anonymous struct/union within its
963 /// context.
964 ///
965 /// \returns Returns the index of this anonymous struct/union in its context,
966 /// including the next assigned index (if none of them match). Returns an
967 /// empty option if the context is not a record, i.e.. if the anonymous
968 /// struct/union is at namespace or block scope.
findAnonymousStructOrUnionIndex(RecordDecl * Anon)969 static Optional<unsigned> findAnonymousStructOrUnionIndex(RecordDecl *Anon) {
970   ASTContext &Context = Anon->getASTContext();
971   QualType AnonTy = Context.getRecordType(Anon);
972 
973   RecordDecl *Owner = dyn_cast<RecordDecl>(Anon->getDeclContext());
974   if (!Owner)
975     return None;
976 
977   unsigned Index = 0;
978   for (const auto *D : Owner->noload_decls()) {
979     const auto *F = dyn_cast<FieldDecl>(D);
980     if (!F || !F->isAnonymousStructOrUnion())
981       continue;
982 
983     if (Context.hasSameType(F->getType(), AnonTy))
984       break;
985 
986     ++Index;
987   }
988 
989   return Index;
990 }
991 
992 /// \brief Determine structural equivalence of two records.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,RecordDecl * D1,RecordDecl * D2)993 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
994                                      RecordDecl *D1, RecordDecl *D2) {
995   if (D1->isUnion() != D2->isUnion()) {
996     if (Context.Complain) {
997       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
998         << Context.C2.getTypeDeclType(D2);
999       Context.Diag1(D1->getLocation(), diag::note_odr_tag_kind_here)
1000         << D1->getDeclName() << (unsigned)D1->getTagKind();
1001     }
1002     return false;
1003   }
1004 
1005   if (D1->isAnonymousStructOrUnion() && D2->isAnonymousStructOrUnion()) {
1006     // If both anonymous structs/unions are in a record context, make sure
1007     // they occur in the same location in the context records.
1008     if (Optional<unsigned> Index1 = findAnonymousStructOrUnionIndex(D1)) {
1009       if (Optional<unsigned> Index2 = findAnonymousStructOrUnionIndex(D2)) {
1010         if (*Index1 != *Index2)
1011           return false;
1012       }
1013     }
1014   }
1015 
1016   // If both declarations are class template specializations, we know
1017   // the ODR applies, so check the template and template arguments.
1018   ClassTemplateSpecializationDecl *Spec1
1019     = dyn_cast<ClassTemplateSpecializationDecl>(D1);
1020   ClassTemplateSpecializationDecl *Spec2
1021     = dyn_cast<ClassTemplateSpecializationDecl>(D2);
1022   if (Spec1 && Spec2) {
1023     // Check that the specialized templates are the same.
1024     if (!IsStructurallyEquivalent(Context, Spec1->getSpecializedTemplate(),
1025                                   Spec2->getSpecializedTemplate()))
1026       return false;
1027 
1028     // Check that the template arguments are the same.
1029     if (Spec1->getTemplateArgs().size() != Spec2->getTemplateArgs().size())
1030       return false;
1031 
1032     for (unsigned I = 0, N = Spec1->getTemplateArgs().size(); I != N; ++I)
1033       if (!IsStructurallyEquivalent(Context,
1034                                     Spec1->getTemplateArgs().get(I),
1035                                     Spec2->getTemplateArgs().get(I)))
1036         return false;
1037   }
1038   // If one is a class template specialization and the other is not, these
1039   // structures are different.
1040   else if (Spec1 || Spec2)
1041     return false;
1042 
1043   // Compare the definitions of these two records. If either or both are
1044   // incomplete, we assume that they are equivalent.
1045   D1 = D1->getDefinition();
1046   D2 = D2->getDefinition();
1047   if (!D1 || !D2)
1048     return true;
1049 
1050   if (CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(D1)) {
1051     if (CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(D2)) {
1052       if (D1CXX->getNumBases() != D2CXX->getNumBases()) {
1053         if (Context.Complain) {
1054           Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1055             << Context.C2.getTypeDeclType(D2);
1056           Context.Diag2(D2->getLocation(), diag::note_odr_number_of_bases)
1057             << D2CXX->getNumBases();
1058           Context.Diag1(D1->getLocation(), diag::note_odr_number_of_bases)
1059             << D1CXX->getNumBases();
1060         }
1061         return false;
1062       }
1063 
1064       // Check the base classes.
1065       for (CXXRecordDecl::base_class_iterator Base1 = D1CXX->bases_begin(),
1066                                            BaseEnd1 = D1CXX->bases_end(),
1067                                                 Base2 = D2CXX->bases_begin();
1068            Base1 != BaseEnd1;
1069            ++Base1, ++Base2) {
1070         if (!IsStructurallyEquivalent(Context,
1071                                       Base1->getType(), Base2->getType())) {
1072           if (Context.Complain) {
1073             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1074               << Context.C2.getTypeDeclType(D2);
1075             Context.Diag2(Base2->getLocStart(), diag::note_odr_base)
1076               << Base2->getType()
1077               << Base2->getSourceRange();
1078             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1079               << Base1->getType()
1080               << Base1->getSourceRange();
1081           }
1082           return false;
1083         }
1084 
1085         // Check virtual vs. non-virtual inheritance mismatch.
1086         if (Base1->isVirtual() != Base2->isVirtual()) {
1087           if (Context.Complain) {
1088             Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1089               << Context.C2.getTypeDeclType(D2);
1090             Context.Diag2(Base2->getLocStart(),
1091                           diag::note_odr_virtual_base)
1092               << Base2->isVirtual() << Base2->getSourceRange();
1093             Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1094               << Base1->isVirtual()
1095               << Base1->getSourceRange();
1096           }
1097           return false;
1098         }
1099       }
1100     } else if (D1CXX->getNumBases() > 0) {
1101       if (Context.Complain) {
1102         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1103           << Context.C2.getTypeDeclType(D2);
1104         const CXXBaseSpecifier *Base1 = D1CXX->bases_begin();
1105         Context.Diag1(Base1->getLocStart(), diag::note_odr_base)
1106           << Base1->getType()
1107           << Base1->getSourceRange();
1108         Context.Diag2(D2->getLocation(), diag::note_odr_missing_base);
1109       }
1110       return false;
1111     }
1112   }
1113 
1114   // Check the fields for consistency.
1115   RecordDecl::field_iterator Field2 = D2->field_begin(),
1116                              Field2End = D2->field_end();
1117   for (RecordDecl::field_iterator Field1 = D1->field_begin(),
1118                                   Field1End = D1->field_end();
1119        Field1 != Field1End;
1120        ++Field1, ++Field2) {
1121     if (Field2 == Field2End) {
1122       if (Context.Complain) {
1123         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1124           << Context.C2.getTypeDeclType(D2);
1125         Context.Diag1(Field1->getLocation(), diag::note_odr_field)
1126           << Field1->getDeclName() << Field1->getType();
1127         Context.Diag2(D2->getLocation(), diag::note_odr_missing_field);
1128       }
1129       return false;
1130     }
1131 
1132     if (!IsStructurallyEquivalent(Context, *Field1, *Field2))
1133       return false;
1134   }
1135 
1136   if (Field2 != Field2End) {
1137     if (Context.Complain) {
1138       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1139         << Context.C2.getTypeDeclType(D2);
1140       Context.Diag2(Field2->getLocation(), diag::note_odr_field)
1141         << Field2->getDeclName() << Field2->getType();
1142       Context.Diag1(D1->getLocation(), diag::note_odr_missing_field);
1143     }
1144     return false;
1145   }
1146 
1147   return true;
1148 }
1149 
1150 /// \brief Determine structural equivalence of two enums.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,EnumDecl * D1,EnumDecl * D2)1151 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1152                                      EnumDecl *D1, EnumDecl *D2) {
1153   EnumDecl::enumerator_iterator EC2 = D2->enumerator_begin(),
1154                              EC2End = D2->enumerator_end();
1155   for (EnumDecl::enumerator_iterator EC1 = D1->enumerator_begin(),
1156                                   EC1End = D1->enumerator_end();
1157        EC1 != EC1End; ++EC1, ++EC2) {
1158     if (EC2 == EC2End) {
1159       if (Context.Complain) {
1160         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1161           << Context.C2.getTypeDeclType(D2);
1162         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1163           << EC1->getDeclName()
1164           << EC1->getInitVal().toString(10);
1165         Context.Diag2(D2->getLocation(), diag::note_odr_missing_enumerator);
1166       }
1167       return false;
1168     }
1169 
1170     llvm::APSInt Val1 = EC1->getInitVal();
1171     llvm::APSInt Val2 = EC2->getInitVal();
1172     if (!llvm::APSInt::isSameValue(Val1, Val2) ||
1173         !IsStructurallyEquivalent(EC1->getIdentifier(), EC2->getIdentifier())) {
1174       if (Context.Complain) {
1175         Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1176           << Context.C2.getTypeDeclType(D2);
1177         Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1178           << EC2->getDeclName()
1179           << EC2->getInitVal().toString(10);
1180         Context.Diag1(EC1->getLocation(), diag::note_odr_enumerator)
1181           << EC1->getDeclName()
1182           << EC1->getInitVal().toString(10);
1183       }
1184       return false;
1185     }
1186   }
1187 
1188   if (EC2 != EC2End) {
1189     if (Context.Complain) {
1190       Context.Diag2(D2->getLocation(), diag::warn_odr_tag_type_inconsistent)
1191         << Context.C2.getTypeDeclType(D2);
1192       Context.Diag2(EC2->getLocation(), diag::note_odr_enumerator)
1193         << EC2->getDeclName()
1194         << EC2->getInitVal().toString(10);
1195       Context.Diag1(D1->getLocation(), diag::note_odr_missing_enumerator);
1196     }
1197     return false;
1198   }
1199 
1200   return true;
1201 }
1202 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateParameterList * Params1,TemplateParameterList * Params2)1203 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1204                                      TemplateParameterList *Params1,
1205                                      TemplateParameterList *Params2) {
1206   if (Params1->size() != Params2->size()) {
1207     if (Context.Complain) {
1208       Context.Diag2(Params2->getTemplateLoc(),
1209                     diag::err_odr_different_num_template_parameters)
1210         << Params1->size() << Params2->size();
1211       Context.Diag1(Params1->getTemplateLoc(),
1212                     diag::note_odr_template_parameter_list);
1213     }
1214     return false;
1215   }
1216 
1217   for (unsigned I = 0, N = Params1->size(); I != N; ++I) {
1218     if (Params1->getParam(I)->getKind() != Params2->getParam(I)->getKind()) {
1219       if (Context.Complain) {
1220         Context.Diag2(Params2->getParam(I)->getLocation(),
1221                       diag::err_odr_different_template_parameter_kind);
1222         Context.Diag1(Params1->getParam(I)->getLocation(),
1223                       diag::note_odr_template_parameter_here);
1224       }
1225       return false;
1226     }
1227 
1228     if (!Context.IsStructurallyEquivalent(Params1->getParam(I),
1229                                           Params2->getParam(I))) {
1230 
1231       return false;
1232     }
1233   }
1234 
1235   return true;
1236 }
1237 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTypeParmDecl * D1,TemplateTypeParmDecl * D2)1238 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1239                                      TemplateTypeParmDecl *D1,
1240                                      TemplateTypeParmDecl *D2) {
1241   if (D1->isParameterPack() != D2->isParameterPack()) {
1242     if (Context.Complain) {
1243       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1244         << D2->isParameterPack();
1245       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1246         << D1->isParameterPack();
1247     }
1248     return false;
1249   }
1250 
1251   return true;
1252 }
1253 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,NonTypeTemplateParmDecl * D1,NonTypeTemplateParmDecl * D2)1254 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1255                                      NonTypeTemplateParmDecl *D1,
1256                                      NonTypeTemplateParmDecl *D2) {
1257   if (D1->isParameterPack() != D2->isParameterPack()) {
1258     if (Context.Complain) {
1259       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1260         << D2->isParameterPack();
1261       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1262         << D1->isParameterPack();
1263     }
1264     return false;
1265   }
1266 
1267   // Check types.
1268   if (!Context.IsStructurallyEquivalent(D1->getType(), D2->getType())) {
1269     if (Context.Complain) {
1270       Context.Diag2(D2->getLocation(),
1271                     diag::err_odr_non_type_parameter_type_inconsistent)
1272         << D2->getType() << D1->getType();
1273       Context.Diag1(D1->getLocation(), diag::note_odr_value_here)
1274         << D1->getType();
1275     }
1276     return false;
1277   }
1278 
1279   return true;
1280 }
1281 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,TemplateTemplateParmDecl * D1,TemplateTemplateParmDecl * D2)1282 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1283                                      TemplateTemplateParmDecl *D1,
1284                                      TemplateTemplateParmDecl *D2) {
1285   if (D1->isParameterPack() != D2->isParameterPack()) {
1286     if (Context.Complain) {
1287       Context.Diag2(D2->getLocation(), diag::err_odr_parameter_pack_non_pack)
1288         << D2->isParameterPack();
1289       Context.Diag1(D1->getLocation(), diag::note_odr_parameter_pack_non_pack)
1290         << D1->isParameterPack();
1291     }
1292     return false;
1293   }
1294 
1295   // Check template parameter lists.
1296   return IsStructurallyEquivalent(Context, D1->getTemplateParameters(),
1297                                   D2->getTemplateParameters());
1298 }
1299 
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,ClassTemplateDecl * D1,ClassTemplateDecl * D2)1300 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1301                                      ClassTemplateDecl *D1,
1302                                      ClassTemplateDecl *D2) {
1303   // Check template parameters.
1304   if (!IsStructurallyEquivalent(Context,
1305                                 D1->getTemplateParameters(),
1306                                 D2->getTemplateParameters()))
1307     return false;
1308 
1309   // Check the templated declaration.
1310   return Context.IsStructurallyEquivalent(D1->getTemplatedDecl(),
1311                                           D2->getTemplatedDecl());
1312 }
1313 
1314 /// \brief Determine structural equivalence of two declarations.
IsStructurallyEquivalent(StructuralEquivalenceContext & Context,Decl * D1,Decl * D2)1315 static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
1316                                      Decl *D1, Decl *D2) {
1317   // FIXME: Check for known structural equivalences via a callback of some sort.
1318 
1319   // Check whether we already know that these two declarations are not
1320   // structurally equivalent.
1321   if (Context.NonEquivalentDecls.count(std::make_pair(D1->getCanonicalDecl(),
1322                                                       D2->getCanonicalDecl())))
1323     return false;
1324 
1325   // Determine whether we've already produced a tentative equivalence for D1.
1326   Decl *&EquivToD1 = Context.TentativeEquivalences[D1->getCanonicalDecl()];
1327   if (EquivToD1)
1328     return EquivToD1 == D2->getCanonicalDecl();
1329 
1330   // Produce a tentative equivalence D1 <-> D2, which will be checked later.
1331   EquivToD1 = D2->getCanonicalDecl();
1332   Context.DeclsToCheck.push_back(D1->getCanonicalDecl());
1333   return true;
1334 }
1335 
IsStructurallyEquivalent(Decl * D1,Decl * D2)1336 bool StructuralEquivalenceContext::IsStructurallyEquivalent(Decl *D1,
1337                                                             Decl *D2) {
1338   if (!::IsStructurallyEquivalent(*this, D1, D2))
1339     return false;
1340 
1341   return !Finish();
1342 }
1343 
IsStructurallyEquivalent(QualType T1,QualType T2)1344 bool StructuralEquivalenceContext::IsStructurallyEquivalent(QualType T1,
1345                                                             QualType T2) {
1346   if (!::IsStructurallyEquivalent(*this, T1, T2))
1347     return false;
1348 
1349   return !Finish();
1350 }
1351 
Finish()1352 bool StructuralEquivalenceContext::Finish() {
1353   while (!DeclsToCheck.empty()) {
1354     // Check the next declaration.
1355     Decl *D1 = DeclsToCheck.front();
1356     DeclsToCheck.pop_front();
1357 
1358     Decl *D2 = TentativeEquivalences[D1];
1359     assert(D2 && "Unrecorded tentative equivalence?");
1360 
1361     bool Equivalent = true;
1362 
1363     // FIXME: Switch on all declaration kinds. For now, we're just going to
1364     // check the obvious ones.
1365     if (RecordDecl *Record1 = dyn_cast<RecordDecl>(D1)) {
1366       if (RecordDecl *Record2 = dyn_cast<RecordDecl>(D2)) {
1367         // Check for equivalent structure names.
1368         IdentifierInfo *Name1 = Record1->getIdentifier();
1369         if (!Name1 && Record1->getTypedefNameForAnonDecl())
1370           Name1 = Record1->getTypedefNameForAnonDecl()->getIdentifier();
1371         IdentifierInfo *Name2 = Record2->getIdentifier();
1372         if (!Name2 && Record2->getTypedefNameForAnonDecl())
1373           Name2 = Record2->getTypedefNameForAnonDecl()->getIdentifier();
1374         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1375             !::IsStructurallyEquivalent(*this, Record1, Record2))
1376           Equivalent = false;
1377       } else {
1378         // Record/non-record mismatch.
1379         Equivalent = false;
1380       }
1381     } else if (EnumDecl *Enum1 = dyn_cast<EnumDecl>(D1)) {
1382       if (EnumDecl *Enum2 = dyn_cast<EnumDecl>(D2)) {
1383         // Check for equivalent enum names.
1384         IdentifierInfo *Name1 = Enum1->getIdentifier();
1385         if (!Name1 && Enum1->getTypedefNameForAnonDecl())
1386           Name1 = Enum1->getTypedefNameForAnonDecl()->getIdentifier();
1387         IdentifierInfo *Name2 = Enum2->getIdentifier();
1388         if (!Name2 && Enum2->getTypedefNameForAnonDecl())
1389           Name2 = Enum2->getTypedefNameForAnonDecl()->getIdentifier();
1390         if (!::IsStructurallyEquivalent(Name1, Name2) ||
1391             !::IsStructurallyEquivalent(*this, Enum1, Enum2))
1392           Equivalent = false;
1393       } else {
1394         // Enum/non-enum mismatch
1395         Equivalent = false;
1396       }
1397     } else if (TypedefNameDecl *Typedef1 = dyn_cast<TypedefNameDecl>(D1)) {
1398       if (TypedefNameDecl *Typedef2 = dyn_cast<TypedefNameDecl>(D2)) {
1399         if (!::IsStructurallyEquivalent(Typedef1->getIdentifier(),
1400                                         Typedef2->getIdentifier()) ||
1401             !::IsStructurallyEquivalent(*this,
1402                                         Typedef1->getUnderlyingType(),
1403                                         Typedef2->getUnderlyingType()))
1404           Equivalent = false;
1405       } else {
1406         // Typedef/non-typedef mismatch.
1407         Equivalent = false;
1408       }
1409     } else if (ClassTemplateDecl *ClassTemplate1
1410                                            = dyn_cast<ClassTemplateDecl>(D1)) {
1411       if (ClassTemplateDecl *ClassTemplate2 = dyn_cast<ClassTemplateDecl>(D2)) {
1412         if (!::IsStructurallyEquivalent(ClassTemplate1->getIdentifier(),
1413                                         ClassTemplate2->getIdentifier()) ||
1414             !::IsStructurallyEquivalent(*this, ClassTemplate1, ClassTemplate2))
1415           Equivalent = false;
1416       } else {
1417         // Class template/non-class-template mismatch.
1418         Equivalent = false;
1419       }
1420     } else if (TemplateTypeParmDecl *TTP1= dyn_cast<TemplateTypeParmDecl>(D1)) {
1421       if (TemplateTypeParmDecl *TTP2 = dyn_cast<TemplateTypeParmDecl>(D2)) {
1422         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1423           Equivalent = false;
1424       } else {
1425         // Kind mismatch.
1426         Equivalent = false;
1427       }
1428     } else if (NonTypeTemplateParmDecl *NTTP1
1429                                      = dyn_cast<NonTypeTemplateParmDecl>(D1)) {
1430       if (NonTypeTemplateParmDecl *NTTP2
1431                                       = dyn_cast<NonTypeTemplateParmDecl>(D2)) {
1432         if (!::IsStructurallyEquivalent(*this, NTTP1, NTTP2))
1433           Equivalent = false;
1434       } else {
1435         // Kind mismatch.
1436         Equivalent = false;
1437       }
1438     } else if (TemplateTemplateParmDecl *TTP1
1439                                   = dyn_cast<TemplateTemplateParmDecl>(D1)) {
1440       if (TemplateTemplateParmDecl *TTP2
1441                                     = dyn_cast<TemplateTemplateParmDecl>(D2)) {
1442         if (!::IsStructurallyEquivalent(*this, TTP1, TTP2))
1443           Equivalent = false;
1444       } else {
1445         // Kind mismatch.
1446         Equivalent = false;
1447       }
1448     }
1449 
1450     if (!Equivalent) {
1451       // Note that these two declarations are not equivalent (and we already
1452       // know about it).
1453       NonEquivalentDecls.insert(std::make_pair(D1->getCanonicalDecl(),
1454                                                D2->getCanonicalDecl()));
1455       return true;
1456     }
1457     // FIXME: Check other declaration kinds!
1458   }
1459 
1460   return false;
1461 }
1462 
1463 //----------------------------------------------------------------------------
1464 // Import Types
1465 //----------------------------------------------------------------------------
1466 
VisitType(const Type * T)1467 QualType ASTNodeImporter::VisitType(const Type *T) {
1468   Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1469     << T->getTypeClassName();
1470   return QualType();
1471 }
1472 
VisitBuiltinType(const BuiltinType * T)1473 QualType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1474   switch (T->getKind()) {
1475 #define SHARED_SINGLETON_TYPE(Expansion)
1476 #define BUILTIN_TYPE(Id, SingletonId) \
1477   case BuiltinType::Id: return Importer.getToContext().SingletonId;
1478 #include "clang/AST/BuiltinTypes.def"
1479 
1480   // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1481   // context supports C++.
1482 
1483   // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1484   // context supports ObjC.
1485 
1486   case BuiltinType::Char_U:
1487     // The context we're importing from has an unsigned 'char'. If we're
1488     // importing into a context with a signed 'char', translate to
1489     // 'unsigned char' instead.
1490     if (Importer.getToContext().getLangOpts().CharIsSigned)
1491       return Importer.getToContext().UnsignedCharTy;
1492 
1493     return Importer.getToContext().CharTy;
1494 
1495   case BuiltinType::Char_S:
1496     // The context we're importing from has an unsigned 'char'. If we're
1497     // importing into a context with a signed 'char', translate to
1498     // 'unsigned char' instead.
1499     if (!Importer.getToContext().getLangOpts().CharIsSigned)
1500       return Importer.getToContext().SignedCharTy;
1501 
1502     return Importer.getToContext().CharTy;
1503 
1504   case BuiltinType::WChar_S:
1505   case BuiltinType::WChar_U:
1506     // FIXME: If not in C++, shall we translate to the C equivalent of
1507     // wchar_t?
1508     return Importer.getToContext().WCharTy;
1509   }
1510 
1511   llvm_unreachable("Invalid BuiltinType Kind!");
1512 }
1513 
VisitComplexType(const ComplexType * T)1514 QualType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1515   QualType ToElementType = Importer.Import(T->getElementType());
1516   if (ToElementType.isNull())
1517     return QualType();
1518 
1519   return Importer.getToContext().getComplexType(ToElementType);
1520 }
1521 
VisitPointerType(const PointerType * T)1522 QualType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1523   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1524   if (ToPointeeType.isNull())
1525     return QualType();
1526 
1527   return Importer.getToContext().getPointerType(ToPointeeType);
1528 }
1529 
VisitBlockPointerType(const BlockPointerType * T)1530 QualType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1531   // FIXME: Check for blocks support in "to" context.
1532   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1533   if (ToPointeeType.isNull())
1534     return QualType();
1535 
1536   return Importer.getToContext().getBlockPointerType(ToPointeeType);
1537 }
1538 
1539 QualType
VisitLValueReferenceType(const LValueReferenceType * T)1540 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1541   // FIXME: Check for C++ support in "to" context.
1542   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1543   if (ToPointeeType.isNull())
1544     return QualType();
1545 
1546   return Importer.getToContext().getLValueReferenceType(ToPointeeType);
1547 }
1548 
1549 QualType
VisitRValueReferenceType(const RValueReferenceType * T)1550 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1551   // FIXME: Check for C++0x support in "to" context.
1552   QualType ToPointeeType = Importer.Import(T->getPointeeTypeAsWritten());
1553   if (ToPointeeType.isNull())
1554     return QualType();
1555 
1556   return Importer.getToContext().getRValueReferenceType(ToPointeeType);
1557 }
1558 
VisitMemberPointerType(const MemberPointerType * T)1559 QualType ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1560   // FIXME: Check for C++ support in "to" context.
1561   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1562   if (ToPointeeType.isNull())
1563     return QualType();
1564 
1565   QualType ClassType = Importer.Import(QualType(T->getClass(), 0));
1566   return Importer.getToContext().getMemberPointerType(ToPointeeType,
1567                                                       ClassType.getTypePtr());
1568 }
1569 
VisitConstantArrayType(const ConstantArrayType * T)1570 QualType ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1571   QualType ToElementType = Importer.Import(T->getElementType());
1572   if (ToElementType.isNull())
1573     return QualType();
1574 
1575   return Importer.getToContext().getConstantArrayType(ToElementType,
1576                                                       T->getSize(),
1577                                                       T->getSizeModifier(),
1578                                                T->getIndexTypeCVRQualifiers());
1579 }
1580 
1581 QualType
VisitIncompleteArrayType(const IncompleteArrayType * T)1582 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1583   QualType ToElementType = Importer.Import(T->getElementType());
1584   if (ToElementType.isNull())
1585     return QualType();
1586 
1587   return Importer.getToContext().getIncompleteArrayType(ToElementType,
1588                                                         T->getSizeModifier(),
1589                                                 T->getIndexTypeCVRQualifiers());
1590 }
1591 
VisitVariableArrayType(const VariableArrayType * T)1592 QualType ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1593   QualType ToElementType = Importer.Import(T->getElementType());
1594   if (ToElementType.isNull())
1595     return QualType();
1596 
1597   Expr *Size = Importer.Import(T->getSizeExpr());
1598   if (!Size)
1599     return QualType();
1600 
1601   SourceRange Brackets = Importer.Import(T->getBracketsRange());
1602   return Importer.getToContext().getVariableArrayType(ToElementType, Size,
1603                                                       T->getSizeModifier(),
1604                                                 T->getIndexTypeCVRQualifiers(),
1605                                                       Brackets);
1606 }
1607 
VisitVectorType(const VectorType * T)1608 QualType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1609   QualType ToElementType = Importer.Import(T->getElementType());
1610   if (ToElementType.isNull())
1611     return QualType();
1612 
1613   return Importer.getToContext().getVectorType(ToElementType,
1614                                                T->getNumElements(),
1615                                                T->getVectorKind());
1616 }
1617 
VisitExtVectorType(const ExtVectorType * T)1618 QualType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1619   QualType ToElementType = Importer.Import(T->getElementType());
1620   if (ToElementType.isNull())
1621     return QualType();
1622 
1623   return Importer.getToContext().getExtVectorType(ToElementType,
1624                                                   T->getNumElements());
1625 }
1626 
1627 QualType
VisitFunctionNoProtoType(const FunctionNoProtoType * T)1628 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1629   // FIXME: What happens if we're importing a function without a prototype
1630   // into C++? Should we make it variadic?
1631   QualType ToResultType = Importer.Import(T->getReturnType());
1632   if (ToResultType.isNull())
1633     return QualType();
1634 
1635   return Importer.getToContext().getFunctionNoProtoType(ToResultType,
1636                                                         T->getExtInfo());
1637 }
1638 
VisitFunctionProtoType(const FunctionProtoType * T)1639 QualType ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1640   QualType ToResultType = Importer.Import(T->getReturnType());
1641   if (ToResultType.isNull())
1642     return QualType();
1643 
1644   // Import argument types
1645   SmallVector<QualType, 4> ArgTypes;
1646   for (const auto &A : T->param_types()) {
1647     QualType ArgType = Importer.Import(A);
1648     if (ArgType.isNull())
1649       return QualType();
1650     ArgTypes.push_back(ArgType);
1651   }
1652 
1653   // Import exception types
1654   SmallVector<QualType, 4> ExceptionTypes;
1655   for (const auto &E : T->exceptions()) {
1656     QualType ExceptionType = Importer.Import(E);
1657     if (ExceptionType.isNull())
1658       return QualType();
1659     ExceptionTypes.push_back(ExceptionType);
1660   }
1661 
1662   FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1663   FunctionProtoType::ExtProtoInfo ToEPI;
1664 
1665   ToEPI.ExtInfo = FromEPI.ExtInfo;
1666   ToEPI.Variadic = FromEPI.Variadic;
1667   ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1668   ToEPI.TypeQuals = FromEPI.TypeQuals;
1669   ToEPI.RefQualifier = FromEPI.RefQualifier;
1670   ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1671   ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1672   ToEPI.ExceptionSpec.NoexceptExpr =
1673       Importer.Import(FromEPI.ExceptionSpec.NoexceptExpr);
1674   ToEPI.ExceptionSpec.SourceDecl = cast_or_null<FunctionDecl>(
1675       Importer.Import(FromEPI.ExceptionSpec.SourceDecl));
1676   ToEPI.ExceptionSpec.SourceTemplate = cast_or_null<FunctionDecl>(
1677       Importer.Import(FromEPI.ExceptionSpec.SourceTemplate));
1678 
1679   return Importer.getToContext().getFunctionType(ToResultType, ArgTypes, ToEPI);
1680 }
1681 
VisitParenType(const ParenType * T)1682 QualType ASTNodeImporter::VisitParenType(const ParenType *T) {
1683   QualType ToInnerType = Importer.Import(T->getInnerType());
1684   if (ToInnerType.isNull())
1685     return QualType();
1686 
1687   return Importer.getToContext().getParenType(ToInnerType);
1688 }
1689 
VisitTypedefType(const TypedefType * T)1690 QualType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1691   TypedefNameDecl *ToDecl
1692              = dyn_cast_or_null<TypedefNameDecl>(Importer.Import(T->getDecl()));
1693   if (!ToDecl)
1694     return QualType();
1695 
1696   return Importer.getToContext().getTypeDeclType(ToDecl);
1697 }
1698 
VisitTypeOfExprType(const TypeOfExprType * T)1699 QualType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1700   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1701   if (!ToExpr)
1702     return QualType();
1703 
1704   return Importer.getToContext().getTypeOfExprType(ToExpr);
1705 }
1706 
VisitTypeOfType(const TypeOfType * T)1707 QualType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1708   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1709   if (ToUnderlyingType.isNull())
1710     return QualType();
1711 
1712   return Importer.getToContext().getTypeOfType(ToUnderlyingType);
1713 }
1714 
VisitDecltypeType(const DecltypeType * T)1715 QualType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1716   // FIXME: Make sure that the "to" context supports C++0x!
1717   Expr *ToExpr = Importer.Import(T->getUnderlyingExpr());
1718   if (!ToExpr)
1719     return QualType();
1720 
1721   QualType UnderlyingType = Importer.Import(T->getUnderlyingType());
1722   if (UnderlyingType.isNull())
1723     return QualType();
1724 
1725   return Importer.getToContext().getDecltypeType(ToExpr, UnderlyingType);
1726 }
1727 
VisitUnaryTransformType(const UnaryTransformType * T)1728 QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1729   QualType ToBaseType = Importer.Import(T->getBaseType());
1730   QualType ToUnderlyingType = Importer.Import(T->getUnderlyingType());
1731   if (ToBaseType.isNull() || ToUnderlyingType.isNull())
1732     return QualType();
1733 
1734   return Importer.getToContext().getUnaryTransformType(ToBaseType,
1735                                                        ToUnderlyingType,
1736                                                        T->getUTTKind());
1737 }
1738 
VisitAutoType(const AutoType * T)1739 QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1740   // FIXME: Make sure that the "to" context supports C++11!
1741   QualType FromDeduced = T->getDeducedType();
1742   QualType ToDeduced;
1743   if (!FromDeduced.isNull()) {
1744     ToDeduced = Importer.Import(FromDeduced);
1745     if (ToDeduced.isNull())
1746       return QualType();
1747   }
1748 
1749   return Importer.getToContext().getAutoType(ToDeduced, T->getKeyword(),
1750                                              /*IsDependent*/false);
1751 }
1752 
VisitRecordType(const RecordType * T)1753 QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1754   RecordDecl *ToDecl
1755     = dyn_cast_or_null<RecordDecl>(Importer.Import(T->getDecl()));
1756   if (!ToDecl)
1757     return QualType();
1758 
1759   return Importer.getToContext().getTagDeclType(ToDecl);
1760 }
1761 
VisitEnumType(const EnumType * T)1762 QualType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1763   EnumDecl *ToDecl
1764     = dyn_cast_or_null<EnumDecl>(Importer.Import(T->getDecl()));
1765   if (!ToDecl)
1766     return QualType();
1767 
1768   return Importer.getToContext().getTagDeclType(ToDecl);
1769 }
1770 
VisitAttributedType(const AttributedType * T)1771 QualType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1772   QualType FromModifiedType = T->getModifiedType();
1773   QualType FromEquivalentType = T->getEquivalentType();
1774   QualType ToModifiedType;
1775   QualType ToEquivalentType;
1776 
1777   if (!FromModifiedType.isNull()) {
1778     ToModifiedType = Importer.Import(FromModifiedType);
1779     if (ToModifiedType.isNull())
1780       return QualType();
1781   }
1782   if (!FromEquivalentType.isNull()) {
1783     ToEquivalentType = Importer.Import(FromEquivalentType);
1784     if (ToEquivalentType.isNull())
1785       return QualType();
1786   }
1787 
1788   return Importer.getToContext().getAttributedType(T->getAttrKind(),
1789     ToModifiedType, ToEquivalentType);
1790 }
1791 
VisitTemplateSpecializationType(const TemplateSpecializationType * T)1792 QualType ASTNodeImporter::VisitTemplateSpecializationType(
1793                                        const TemplateSpecializationType *T) {
1794   TemplateName ToTemplate = Importer.Import(T->getTemplateName());
1795   if (ToTemplate.isNull())
1796     return QualType();
1797 
1798   SmallVector<TemplateArgument, 2> ToTemplateArgs;
1799   if (ImportTemplateArguments(T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1800     return QualType();
1801 
1802   QualType ToCanonType;
1803   if (!QualType(T, 0).isCanonical()) {
1804     QualType FromCanonType
1805       = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1806     ToCanonType =Importer.Import(FromCanonType);
1807     if (ToCanonType.isNull())
1808       return QualType();
1809   }
1810   return Importer.getToContext().getTemplateSpecializationType(ToTemplate,
1811                                                          ToTemplateArgs.data(),
1812                                                          ToTemplateArgs.size(),
1813                                                                ToCanonType);
1814 }
1815 
VisitElaboratedType(const ElaboratedType * T)1816 QualType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1817   NestedNameSpecifier *ToQualifier = nullptr;
1818   // Note: the qualifier in an ElaboratedType is optional.
1819   if (T->getQualifier()) {
1820     ToQualifier = Importer.Import(T->getQualifier());
1821     if (!ToQualifier)
1822       return QualType();
1823   }
1824 
1825   QualType ToNamedType = Importer.Import(T->getNamedType());
1826   if (ToNamedType.isNull())
1827     return QualType();
1828 
1829   return Importer.getToContext().getElaboratedType(T->getKeyword(),
1830                                                    ToQualifier, ToNamedType);
1831 }
1832 
VisitObjCInterfaceType(const ObjCInterfaceType * T)1833 QualType ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1834   ObjCInterfaceDecl *Class
1835     = dyn_cast_or_null<ObjCInterfaceDecl>(Importer.Import(T->getDecl()));
1836   if (!Class)
1837     return QualType();
1838 
1839   return Importer.getToContext().getObjCInterfaceType(Class);
1840 }
1841 
VisitObjCObjectType(const ObjCObjectType * T)1842 QualType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1843   QualType ToBaseType = Importer.Import(T->getBaseType());
1844   if (ToBaseType.isNull())
1845     return QualType();
1846 
1847   SmallVector<QualType, 4> TypeArgs;
1848   for (auto TypeArg : T->getTypeArgsAsWritten()) {
1849     QualType ImportedTypeArg = Importer.Import(TypeArg);
1850     if (ImportedTypeArg.isNull())
1851       return QualType();
1852 
1853     TypeArgs.push_back(ImportedTypeArg);
1854   }
1855 
1856   SmallVector<ObjCProtocolDecl *, 4> Protocols;
1857   for (auto *P : T->quals()) {
1858     ObjCProtocolDecl *Protocol
1859       = dyn_cast_or_null<ObjCProtocolDecl>(Importer.Import(P));
1860     if (!Protocol)
1861       return QualType();
1862     Protocols.push_back(Protocol);
1863   }
1864 
1865   return Importer.getToContext().getObjCObjectType(ToBaseType, TypeArgs,
1866                                                    Protocols,
1867                                                    T->isKindOfTypeAsWritten());
1868 }
1869 
1870 QualType
VisitObjCObjectPointerType(const ObjCObjectPointerType * T)1871 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1872   QualType ToPointeeType = Importer.Import(T->getPointeeType());
1873   if (ToPointeeType.isNull())
1874     return QualType();
1875 
1876   return Importer.getToContext().getObjCObjectPointerType(ToPointeeType);
1877 }
1878 
1879 //----------------------------------------------------------------------------
1880 // Import Declarations
1881 //----------------------------------------------------------------------------
ImportDeclParts(NamedDecl * D,DeclContext * & DC,DeclContext * & LexicalDC,DeclarationName & Name,NamedDecl * & ToD,SourceLocation & Loc)1882 bool ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclContext *&DC,
1883                                       DeclContext *&LexicalDC,
1884                                       DeclarationName &Name,
1885                                       NamedDecl *&ToD,
1886                                       SourceLocation &Loc) {
1887   // Import the context of this declaration.
1888   DC = Importer.ImportContext(D->getDeclContext());
1889   if (!DC)
1890     return true;
1891 
1892   LexicalDC = DC;
1893   if (D->getDeclContext() != D->getLexicalDeclContext()) {
1894     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
1895     if (!LexicalDC)
1896       return true;
1897   }
1898 
1899   // Import the name of this declaration.
1900   Name = Importer.Import(D->getDeclName());
1901   if (D->getDeclName() && !Name)
1902     return true;
1903 
1904   // Import the location of this declaration.
1905   Loc = Importer.Import(D->getLocation());
1906   ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1907   return false;
1908 }
1909 
ImportDefinitionIfNeeded(Decl * FromD,Decl * ToD)1910 void ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1911   if (!FromD)
1912     return;
1913 
1914   if (!ToD) {
1915     ToD = Importer.Import(FromD);
1916     if (!ToD)
1917       return;
1918   }
1919 
1920   if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1921     if (RecordDecl *ToRecord = cast_or_null<RecordDecl>(ToD)) {
1922       if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && !ToRecord->getDefinition()) {
1923         ImportDefinition(FromRecord, ToRecord);
1924       }
1925     }
1926     return;
1927   }
1928 
1929   if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1930     if (EnumDecl *ToEnum = cast_or_null<EnumDecl>(ToD)) {
1931       if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1932         ImportDefinition(FromEnum, ToEnum);
1933       }
1934     }
1935     return;
1936   }
1937 }
1938 
1939 void
ImportDeclarationNameLoc(const DeclarationNameInfo & From,DeclarationNameInfo & To)1940 ASTNodeImporter::ImportDeclarationNameLoc(const DeclarationNameInfo &From,
1941                                           DeclarationNameInfo& To) {
1942   // NOTE: To.Name and To.Loc are already imported.
1943   // We only have to import To.LocInfo.
1944   switch (To.getName().getNameKind()) {
1945   case DeclarationName::Identifier:
1946   case DeclarationName::ObjCZeroArgSelector:
1947   case DeclarationName::ObjCOneArgSelector:
1948   case DeclarationName::ObjCMultiArgSelector:
1949   case DeclarationName::CXXUsingDirective:
1950     return;
1951 
1952   case DeclarationName::CXXOperatorName: {
1953     SourceRange Range = From.getCXXOperatorNameRange();
1954     To.setCXXOperatorNameRange(Importer.Import(Range));
1955     return;
1956   }
1957   case DeclarationName::CXXLiteralOperatorName: {
1958     SourceLocation Loc = From.getCXXLiteralOperatorNameLoc();
1959     To.setCXXLiteralOperatorNameLoc(Importer.Import(Loc));
1960     return;
1961   }
1962   case DeclarationName::CXXConstructorName:
1963   case DeclarationName::CXXDestructorName:
1964   case DeclarationName::CXXConversionFunctionName: {
1965     TypeSourceInfo *FromTInfo = From.getNamedTypeInfo();
1966     To.setNamedTypeInfo(Importer.Import(FromTInfo));
1967     return;
1968   }
1969   }
1970   llvm_unreachable("Unknown name kind.");
1971 }
1972 
ImportDeclContext(DeclContext * FromDC,bool ForceImport)1973 void ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1974   if (Importer.isMinimalImport() && !ForceImport) {
1975     Importer.ImportContext(FromDC);
1976     return;
1977   }
1978 
1979   for (auto *From : FromDC->decls())
1980     Importer.Import(From);
1981 }
1982 
ImportDefinition(RecordDecl * From,RecordDecl * To,ImportDefinitionKind Kind)1983 bool ASTNodeImporter::ImportDefinition(RecordDecl *From, RecordDecl *To,
1984                                        ImportDefinitionKind Kind) {
1985   if (To->getDefinition() || To->isBeingDefined()) {
1986     if (Kind == IDK_Everything)
1987       ImportDeclContext(From, /*ForceImport=*/true);
1988 
1989     return false;
1990   }
1991 
1992   To->startDefinition();
1993 
1994   // Add base classes.
1995   if (CXXRecordDecl *ToCXX = dyn_cast<CXXRecordDecl>(To)) {
1996     CXXRecordDecl *FromCXX = cast<CXXRecordDecl>(From);
1997 
1998     struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1999     struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2000     ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
2001     ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
2002     ToData.Aggregate = FromData.Aggregate;
2003     ToData.PlainOldData = FromData.PlainOldData;
2004     ToData.Empty = FromData.Empty;
2005     ToData.Polymorphic = FromData.Polymorphic;
2006     ToData.Abstract = FromData.Abstract;
2007     ToData.IsStandardLayout = FromData.IsStandardLayout;
2008     ToData.HasNoNonEmptyBases = FromData.HasNoNonEmptyBases;
2009     ToData.HasPrivateFields = FromData.HasPrivateFields;
2010     ToData.HasProtectedFields = FromData.HasProtectedFields;
2011     ToData.HasPublicFields = FromData.HasPublicFields;
2012     ToData.HasMutableFields = FromData.HasMutableFields;
2013     ToData.HasVariantMembers = FromData.HasVariantMembers;
2014     ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
2015     ToData.HasInClassInitializer = FromData.HasInClassInitializer;
2016     ToData.HasUninitializedReferenceMember
2017       = FromData.HasUninitializedReferenceMember;
2018     ToData.NeedOverloadResolutionForMoveConstructor
2019       = FromData.NeedOverloadResolutionForMoveConstructor;
2020     ToData.NeedOverloadResolutionForMoveAssignment
2021       = FromData.NeedOverloadResolutionForMoveAssignment;
2022     ToData.NeedOverloadResolutionForDestructor
2023       = FromData.NeedOverloadResolutionForDestructor;
2024     ToData.DefaultedMoveConstructorIsDeleted
2025       = FromData.DefaultedMoveConstructorIsDeleted;
2026     ToData.DefaultedMoveAssignmentIsDeleted
2027       = FromData.DefaultedMoveAssignmentIsDeleted;
2028     ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
2029     ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
2030     ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
2031     ToData.HasConstexprNonCopyMoveConstructor
2032       = FromData.HasConstexprNonCopyMoveConstructor;
2033     ToData.DefaultedDefaultConstructorIsConstexpr
2034       = FromData.DefaultedDefaultConstructorIsConstexpr;
2035     ToData.HasConstexprDefaultConstructor
2036       = FromData.HasConstexprDefaultConstructor;
2037     ToData.HasNonLiteralTypeFieldsOrBases
2038       = FromData.HasNonLiteralTypeFieldsOrBases;
2039     // ComputedVisibleConversions not imported.
2040     ToData.UserProvidedDefaultConstructor
2041       = FromData.UserProvidedDefaultConstructor;
2042     ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
2043     ToData.ImplicitCopyConstructorHasConstParam
2044       = FromData.ImplicitCopyConstructorHasConstParam;
2045     ToData.ImplicitCopyAssignmentHasConstParam
2046       = FromData.ImplicitCopyAssignmentHasConstParam;
2047     ToData.HasDeclaredCopyConstructorWithConstParam
2048       = FromData.HasDeclaredCopyConstructorWithConstParam;
2049     ToData.HasDeclaredCopyAssignmentWithConstParam
2050       = FromData.HasDeclaredCopyAssignmentWithConstParam;
2051     ToData.IsLambda = FromData.IsLambda;
2052 
2053     SmallVector<CXXBaseSpecifier *, 4> Bases;
2054     for (const auto &Base1 : FromCXX->bases()) {
2055       QualType T = Importer.Import(Base1.getType());
2056       if (T.isNull())
2057         return true;
2058 
2059       SourceLocation EllipsisLoc;
2060       if (Base1.isPackExpansion())
2061         EllipsisLoc = Importer.Import(Base1.getEllipsisLoc());
2062 
2063       // Ensure that we have a definition for the base.
2064       ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl());
2065 
2066       Bases.push_back(
2067                     new (Importer.getToContext())
2068                       CXXBaseSpecifier(Importer.Import(Base1.getSourceRange()),
2069                                        Base1.isVirtual(),
2070                                        Base1.isBaseOfClass(),
2071                                        Base1.getAccessSpecifierAsWritten(),
2072                                    Importer.Import(Base1.getTypeSourceInfo()),
2073                                        EllipsisLoc));
2074     }
2075     if (!Bases.empty())
2076       ToCXX->setBases(Bases.data(), Bases.size());
2077   }
2078 
2079   if (shouldForceImportDeclContext(Kind))
2080     ImportDeclContext(From, /*ForceImport=*/true);
2081 
2082   To->completeDefinition();
2083   return false;
2084 }
2085 
ImportDefinition(VarDecl * From,VarDecl * To,ImportDefinitionKind Kind)2086 bool ASTNodeImporter::ImportDefinition(VarDecl *From, VarDecl *To,
2087                                        ImportDefinitionKind Kind) {
2088   if (To->getAnyInitializer())
2089     return false;
2090 
2091   // FIXME: Can we really import any initializer? Alternatively, we could force
2092   // ourselves to import every declaration of a variable and then only use
2093   // getInit() here.
2094   To->setInit(Importer.Import(const_cast<Expr *>(From->getAnyInitializer())));
2095 
2096   // FIXME: Other bits to merge?
2097 
2098   return false;
2099 }
2100 
ImportDefinition(EnumDecl * From,EnumDecl * To,ImportDefinitionKind Kind)2101 bool ASTNodeImporter::ImportDefinition(EnumDecl *From, EnumDecl *To,
2102                                        ImportDefinitionKind Kind) {
2103   if (To->getDefinition() || To->isBeingDefined()) {
2104     if (Kind == IDK_Everything)
2105       ImportDeclContext(From, /*ForceImport=*/true);
2106     return false;
2107   }
2108 
2109   To->startDefinition();
2110 
2111   QualType T = Importer.Import(Importer.getFromContext().getTypeDeclType(From));
2112   if (T.isNull())
2113     return true;
2114 
2115   QualType ToPromotionType = Importer.Import(From->getPromotionType());
2116   if (ToPromotionType.isNull())
2117     return true;
2118 
2119   if (shouldForceImportDeclContext(Kind))
2120     ImportDeclContext(From, /*ForceImport=*/true);
2121 
2122   // FIXME: we might need to merge the number of positive or negative bits
2123   // if the enumerator lists don't match.
2124   To->completeDefinition(T, ToPromotionType,
2125                          From->getNumPositiveBits(),
2126                          From->getNumNegativeBits());
2127   return false;
2128 }
2129 
ImportTemplateParameterList(TemplateParameterList * Params)2130 TemplateParameterList *ASTNodeImporter::ImportTemplateParameterList(
2131                                                 TemplateParameterList *Params) {
2132   SmallVector<NamedDecl *, 4> ToParams;
2133   ToParams.reserve(Params->size());
2134   for (TemplateParameterList::iterator P = Params->begin(),
2135                                     PEnd = Params->end();
2136        P != PEnd; ++P) {
2137     Decl *To = Importer.Import(*P);
2138     if (!To)
2139       return nullptr;
2140 
2141     ToParams.push_back(cast<NamedDecl>(To));
2142   }
2143 
2144   return TemplateParameterList::Create(Importer.getToContext(),
2145                                        Importer.Import(Params->getTemplateLoc()),
2146                                        Importer.Import(Params->getLAngleLoc()),
2147                                        ToParams.data(), ToParams.size(),
2148                                        Importer.Import(Params->getRAngleLoc()));
2149 }
2150 
2151 TemplateArgument
ImportTemplateArgument(const TemplateArgument & From)2152 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2153   switch (From.getKind()) {
2154   case TemplateArgument::Null:
2155     return TemplateArgument();
2156 
2157   case TemplateArgument::Type: {
2158     QualType ToType = Importer.Import(From.getAsType());
2159     if (ToType.isNull())
2160       return TemplateArgument();
2161     return TemplateArgument(ToType);
2162   }
2163 
2164   case TemplateArgument::Integral: {
2165     QualType ToType = Importer.Import(From.getIntegralType());
2166     if (ToType.isNull())
2167       return TemplateArgument();
2168     return TemplateArgument(From, ToType);
2169   }
2170 
2171   case TemplateArgument::Declaration: {
2172     ValueDecl *To = cast_or_null<ValueDecl>(Importer.Import(From.getAsDecl()));
2173     QualType ToType = Importer.Import(From.getParamTypeForDecl());
2174     if (!To || ToType.isNull())
2175       return TemplateArgument();
2176     return TemplateArgument(To, ToType);
2177   }
2178 
2179   case TemplateArgument::NullPtr: {
2180     QualType ToType = Importer.Import(From.getNullPtrType());
2181     if (ToType.isNull())
2182       return TemplateArgument();
2183     return TemplateArgument(ToType, /*isNullPtr*/true);
2184   }
2185 
2186   case TemplateArgument::Template: {
2187     TemplateName ToTemplate = Importer.Import(From.getAsTemplate());
2188     if (ToTemplate.isNull())
2189       return TemplateArgument();
2190 
2191     return TemplateArgument(ToTemplate);
2192   }
2193 
2194   case TemplateArgument::TemplateExpansion: {
2195     TemplateName ToTemplate
2196       = Importer.Import(From.getAsTemplateOrTemplatePattern());
2197     if (ToTemplate.isNull())
2198       return TemplateArgument();
2199 
2200     return TemplateArgument(ToTemplate, From.getNumTemplateExpansions());
2201   }
2202 
2203   case TemplateArgument::Expression:
2204     if (Expr *ToExpr = Importer.Import(From.getAsExpr()))
2205       return TemplateArgument(ToExpr);
2206     return TemplateArgument();
2207 
2208   case TemplateArgument::Pack: {
2209     SmallVector<TemplateArgument, 2> ToPack;
2210     ToPack.reserve(From.pack_size());
2211     if (ImportTemplateArguments(From.pack_begin(), From.pack_size(), ToPack))
2212       return TemplateArgument();
2213 
2214     return TemplateArgument(
2215         llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
2216   }
2217   }
2218 
2219   llvm_unreachable("Invalid template argument kind");
2220 }
2221 
ImportTemplateArguments(const TemplateArgument * FromArgs,unsigned NumFromArgs,SmallVectorImpl<TemplateArgument> & ToArgs)2222 bool ASTNodeImporter::ImportTemplateArguments(const TemplateArgument *FromArgs,
2223                                               unsigned NumFromArgs,
2224                               SmallVectorImpl<TemplateArgument> &ToArgs) {
2225   for (unsigned I = 0; I != NumFromArgs; ++I) {
2226     TemplateArgument To = ImportTemplateArgument(FromArgs[I]);
2227     if (To.isNull() && !FromArgs[I].isNull())
2228       return true;
2229 
2230     ToArgs.push_back(To);
2231   }
2232 
2233   return false;
2234 }
2235 
IsStructuralMatch(RecordDecl * FromRecord,RecordDecl * ToRecord,bool Complain)2236 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2237                                         RecordDecl *ToRecord, bool Complain) {
2238   // Eliminate a potential failure point where we attempt to re-import
2239   // something we're trying to import while completing ToRecord.
2240   Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2241   if (ToOrigin) {
2242     RecordDecl *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2243     if (ToOriginRecord)
2244       ToRecord = ToOriginRecord;
2245   }
2246 
2247   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2248                                    ToRecord->getASTContext(),
2249                                    Importer.getNonEquivalentDecls(),
2250                                    false, Complain);
2251   return Ctx.IsStructurallyEquivalent(FromRecord, ToRecord);
2252 }
2253 
IsStructuralMatch(VarDecl * FromVar,VarDecl * ToVar,bool Complain)2254 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2255                                         bool Complain) {
2256   StructuralEquivalenceContext Ctx(
2257       Importer.getFromContext(), Importer.getToContext(),
2258       Importer.getNonEquivalentDecls(), false, Complain);
2259   return Ctx.IsStructurallyEquivalent(FromVar, ToVar);
2260 }
2261 
IsStructuralMatch(EnumDecl * FromEnum,EnumDecl * ToEnum)2262 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2263   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2264                                    Importer.getToContext(),
2265                                    Importer.getNonEquivalentDecls());
2266   return Ctx.IsStructurallyEquivalent(FromEnum, ToEnum);
2267 }
2268 
IsStructuralMatch(EnumConstantDecl * FromEC,EnumConstantDecl * ToEC)2269 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2270                                         EnumConstantDecl *ToEC)
2271 {
2272   const llvm::APSInt &FromVal = FromEC->getInitVal();
2273   const llvm::APSInt &ToVal = ToEC->getInitVal();
2274 
2275   return FromVal.isSigned() == ToVal.isSigned() &&
2276          FromVal.getBitWidth() == ToVal.getBitWidth() &&
2277          FromVal == ToVal;
2278 }
2279 
IsStructuralMatch(ClassTemplateDecl * From,ClassTemplateDecl * To)2280 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2281                                         ClassTemplateDecl *To) {
2282   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2283                                    Importer.getToContext(),
2284                                    Importer.getNonEquivalentDecls());
2285   return Ctx.IsStructurallyEquivalent(From, To);
2286 }
2287 
IsStructuralMatch(VarTemplateDecl * From,VarTemplateDecl * To)2288 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2289                                         VarTemplateDecl *To) {
2290   StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2291                                    Importer.getToContext(),
2292                                    Importer.getNonEquivalentDecls());
2293   return Ctx.IsStructurallyEquivalent(From, To);
2294 }
2295 
VisitDecl(Decl * D)2296 Decl *ASTNodeImporter::VisitDecl(Decl *D) {
2297   Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2298     << D->getDeclKindName();
2299   return nullptr;
2300 }
2301 
VisitTranslationUnitDecl(TranslationUnitDecl * D)2302 Decl *ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2303   TranslationUnitDecl *ToD =
2304     Importer.getToContext().getTranslationUnitDecl();
2305 
2306   Importer.Imported(D, ToD);
2307 
2308   return ToD;
2309 }
2310 
VisitNamespaceDecl(NamespaceDecl * D)2311 Decl *ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2312   // Import the major distinguishing characteristics of this namespace.
2313   DeclContext *DC, *LexicalDC;
2314   DeclarationName Name;
2315   SourceLocation Loc;
2316   NamedDecl *ToD;
2317   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2318     return nullptr;
2319   if (ToD)
2320     return ToD;
2321 
2322   NamespaceDecl *MergeWithNamespace = nullptr;
2323   if (!Name) {
2324     // This is an anonymous namespace. Adopt an existing anonymous
2325     // namespace if we can.
2326     // FIXME: Not testable.
2327     if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2328       MergeWithNamespace = TU->getAnonymousNamespace();
2329     else
2330       MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2331   } else {
2332     SmallVector<NamedDecl *, 4> ConflictingDecls;
2333     SmallVector<NamedDecl *, 2> FoundDecls;
2334     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2335     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2336       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Namespace))
2337         continue;
2338 
2339       if (NamespaceDecl *FoundNS = dyn_cast<NamespaceDecl>(FoundDecls[I])) {
2340         MergeWithNamespace = FoundNS;
2341         ConflictingDecls.clear();
2342         break;
2343       }
2344 
2345       ConflictingDecls.push_back(FoundDecls[I]);
2346     }
2347 
2348     if (!ConflictingDecls.empty()) {
2349       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2350                                          ConflictingDecls.data(),
2351                                          ConflictingDecls.size());
2352     }
2353   }
2354 
2355   // Create the "to" namespace, if needed.
2356   NamespaceDecl *ToNamespace = MergeWithNamespace;
2357   if (!ToNamespace) {
2358     ToNamespace = NamespaceDecl::Create(Importer.getToContext(), DC,
2359                                         D->isInline(),
2360                                         Importer.Import(D->getLocStart()),
2361                                         Loc, Name.getAsIdentifierInfo(),
2362                                         /*PrevDecl=*/nullptr);
2363     ToNamespace->setLexicalDeclContext(LexicalDC);
2364     LexicalDC->addDeclInternal(ToNamespace);
2365 
2366     // If this is an anonymous namespace, register it as the anonymous
2367     // namespace within its context.
2368     if (!Name) {
2369       if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(DC))
2370         TU->setAnonymousNamespace(ToNamespace);
2371       else
2372         cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2373     }
2374   }
2375   Importer.Imported(D, ToNamespace);
2376 
2377   ImportDeclContext(D);
2378 
2379   return ToNamespace;
2380 }
2381 
VisitTypedefNameDecl(TypedefNameDecl * D,bool IsAlias)2382 Decl *ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2383   // Import the major distinguishing characteristics of this typedef.
2384   DeclContext *DC, *LexicalDC;
2385   DeclarationName Name;
2386   SourceLocation Loc;
2387   NamedDecl *ToD;
2388   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2389     return nullptr;
2390   if (ToD)
2391     return ToD;
2392 
2393   // If this typedef is not in block scope, determine whether we've
2394   // seen a typedef with the same name (that we can merge with) or any
2395   // other entity by that name (which name lookup could conflict with).
2396   if (!DC->isFunctionOrMethod()) {
2397     SmallVector<NamedDecl *, 4> ConflictingDecls;
2398     unsigned IDNS = Decl::IDNS_Ordinary;
2399     SmallVector<NamedDecl *, 2> FoundDecls;
2400     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2401     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2402       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2403         continue;
2404       if (TypedefNameDecl *FoundTypedef =
2405             dyn_cast<TypedefNameDecl>(FoundDecls[I])) {
2406         if (Importer.IsStructurallyEquivalent(D->getUnderlyingType(),
2407                                             FoundTypedef->getUnderlyingType()))
2408           return Importer.Imported(D, FoundTypedef);
2409       }
2410 
2411       ConflictingDecls.push_back(FoundDecls[I]);
2412     }
2413 
2414     if (!ConflictingDecls.empty()) {
2415       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2416                                          ConflictingDecls.data(),
2417                                          ConflictingDecls.size());
2418       if (!Name)
2419         return nullptr;
2420     }
2421   }
2422 
2423   // Import the underlying type of this typedef;
2424   QualType T = Importer.Import(D->getUnderlyingType());
2425   if (T.isNull())
2426     return nullptr;
2427 
2428   // Create the new typedef node.
2429   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2430   SourceLocation StartL = Importer.Import(D->getLocStart());
2431   TypedefNameDecl *ToTypedef;
2432   if (IsAlias)
2433     ToTypedef = TypeAliasDecl::Create(Importer.getToContext(), DC,
2434                                       StartL, Loc,
2435                                       Name.getAsIdentifierInfo(),
2436                                       TInfo);
2437   else
2438     ToTypedef = TypedefDecl::Create(Importer.getToContext(), DC,
2439                                     StartL, Loc,
2440                                     Name.getAsIdentifierInfo(),
2441                                     TInfo);
2442 
2443   ToTypedef->setAccess(D->getAccess());
2444   ToTypedef->setLexicalDeclContext(LexicalDC);
2445   Importer.Imported(D, ToTypedef);
2446   LexicalDC->addDeclInternal(ToTypedef);
2447 
2448   return ToTypedef;
2449 }
2450 
VisitTypedefDecl(TypedefDecl * D)2451 Decl *ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2452   return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2453 }
2454 
VisitTypeAliasDecl(TypeAliasDecl * D)2455 Decl *ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2456   return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2457 }
2458 
VisitEnumDecl(EnumDecl * D)2459 Decl *ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2460   // Import the major distinguishing characteristics of this enum.
2461   DeclContext *DC, *LexicalDC;
2462   DeclarationName Name;
2463   SourceLocation Loc;
2464   NamedDecl *ToD;
2465   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2466     return nullptr;
2467   if (ToD)
2468     return ToD;
2469 
2470   // Figure out what enum name we're looking for.
2471   unsigned IDNS = Decl::IDNS_Tag;
2472   DeclarationName SearchName = Name;
2473   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2474     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2475     IDNS = Decl::IDNS_Ordinary;
2476   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2477     IDNS |= Decl::IDNS_Ordinary;
2478 
2479   // We may already have an enum of the same name; try to find and match it.
2480   if (!DC->isFunctionOrMethod() && SearchName) {
2481     SmallVector<NamedDecl *, 4> ConflictingDecls;
2482     SmallVector<NamedDecl *, 2> FoundDecls;
2483     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2484     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2485       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2486         continue;
2487 
2488       Decl *Found = FoundDecls[I];
2489       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2490         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2491           Found = Tag->getDecl();
2492       }
2493 
2494       if (EnumDecl *FoundEnum = dyn_cast<EnumDecl>(Found)) {
2495         if (IsStructuralMatch(D, FoundEnum))
2496           return Importer.Imported(D, FoundEnum);
2497       }
2498 
2499       ConflictingDecls.push_back(FoundDecls[I]);
2500     }
2501 
2502     if (!ConflictingDecls.empty()) {
2503       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2504                                          ConflictingDecls.data(),
2505                                          ConflictingDecls.size());
2506     }
2507   }
2508 
2509   // Create the enum declaration.
2510   EnumDecl *D2 = EnumDecl::Create(Importer.getToContext(), DC,
2511                                   Importer.Import(D->getLocStart()),
2512                                   Loc, Name.getAsIdentifierInfo(), nullptr,
2513                                   D->isScoped(), D->isScopedUsingClassTag(),
2514                                   D->isFixed());
2515   // Import the qualifier, if any.
2516   D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2517   D2->setAccess(D->getAccess());
2518   D2->setLexicalDeclContext(LexicalDC);
2519   Importer.Imported(D, D2);
2520   LexicalDC->addDeclInternal(D2);
2521 
2522   // Import the integer type.
2523   QualType ToIntegerType = Importer.Import(D->getIntegerType());
2524   if (ToIntegerType.isNull())
2525     return nullptr;
2526   D2->setIntegerType(ToIntegerType);
2527 
2528   // Import the definition
2529   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
2530     return nullptr;
2531 
2532   return D2;
2533 }
2534 
VisitRecordDecl(RecordDecl * D)2535 Decl *ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2536   // If this record has a definition in the translation unit we're coming from,
2537   // but this particular declaration is not that definition, import the
2538   // definition and map to that.
2539   TagDecl *Definition = D->getDefinition();
2540   if (Definition && Definition != D) {
2541     Decl *ImportedDef = Importer.Import(Definition);
2542     if (!ImportedDef)
2543       return nullptr;
2544 
2545     return Importer.Imported(D, ImportedDef);
2546   }
2547 
2548   // Import the major distinguishing characteristics of this record.
2549   DeclContext *DC, *LexicalDC;
2550   DeclarationName Name;
2551   SourceLocation Loc;
2552   NamedDecl *ToD;
2553   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2554     return nullptr;
2555   if (ToD)
2556     return ToD;
2557 
2558   // Figure out what structure name we're looking for.
2559   unsigned IDNS = Decl::IDNS_Tag;
2560   DeclarationName SearchName = Name;
2561   if (!SearchName && D->getTypedefNameForAnonDecl()) {
2562     SearchName = Importer.Import(D->getTypedefNameForAnonDecl()->getDeclName());
2563     IDNS = Decl::IDNS_Ordinary;
2564   } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2565     IDNS |= Decl::IDNS_Ordinary;
2566 
2567   // We may already have a record of the same name; try to find and match it.
2568   RecordDecl *AdoptDecl = nullptr;
2569   if (!DC->isFunctionOrMethod()) {
2570     SmallVector<NamedDecl *, 4> ConflictingDecls;
2571     SmallVector<NamedDecl *, 2> FoundDecls;
2572     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2573     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2574       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2575         continue;
2576 
2577       Decl *Found = FoundDecls[I];
2578       if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2579         if (const TagType *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2580           Found = Tag->getDecl();
2581       }
2582 
2583       if (RecordDecl *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2584         if (D->isAnonymousStructOrUnion() &&
2585             FoundRecord->isAnonymousStructOrUnion()) {
2586           // If both anonymous structs/unions are in a record context, make sure
2587           // they occur in the same location in the context records.
2588           if (Optional<unsigned> Index1
2589               = findAnonymousStructOrUnionIndex(D)) {
2590             if (Optional<unsigned> Index2 =
2591                     findAnonymousStructOrUnionIndex(FoundRecord)) {
2592               if (*Index1 != *Index2)
2593                 continue;
2594             }
2595           }
2596         }
2597 
2598         if (RecordDecl *FoundDef = FoundRecord->getDefinition()) {
2599           if ((SearchName && !D->isCompleteDefinition())
2600               || (D->isCompleteDefinition() &&
2601                   D->isAnonymousStructOrUnion()
2602                     == FoundDef->isAnonymousStructOrUnion() &&
2603                   IsStructuralMatch(D, FoundDef))) {
2604             // The record types structurally match, or the "from" translation
2605             // unit only had a forward declaration anyway; call it the same
2606             // function.
2607             // FIXME: For C++, we should also merge methods here.
2608             return Importer.Imported(D, FoundDef);
2609           }
2610         } else if (!D->isCompleteDefinition()) {
2611           // We have a forward declaration of this type, so adopt that forward
2612           // declaration rather than building a new one.
2613 
2614           // If one or both can be completed from external storage then try one
2615           // last time to complete and compare them before doing this.
2616 
2617           if (FoundRecord->hasExternalLexicalStorage() &&
2618               !FoundRecord->isCompleteDefinition())
2619             FoundRecord->getASTContext().getExternalSource()->CompleteType(FoundRecord);
2620           if (D->hasExternalLexicalStorage())
2621             D->getASTContext().getExternalSource()->CompleteType(D);
2622 
2623           if (FoundRecord->isCompleteDefinition() &&
2624               D->isCompleteDefinition() &&
2625               !IsStructuralMatch(D, FoundRecord))
2626             continue;
2627 
2628           AdoptDecl = FoundRecord;
2629           continue;
2630         } else if (!SearchName) {
2631           continue;
2632         }
2633       }
2634 
2635       ConflictingDecls.push_back(FoundDecls[I]);
2636     }
2637 
2638     if (!ConflictingDecls.empty() && SearchName) {
2639       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2640                                          ConflictingDecls.data(),
2641                                          ConflictingDecls.size());
2642     }
2643   }
2644 
2645   // Create the record declaration.
2646   RecordDecl *D2 = AdoptDecl;
2647   SourceLocation StartLoc = Importer.Import(D->getLocStart());
2648   if (!D2) {
2649     if (isa<CXXRecordDecl>(D)) {
2650       CXXRecordDecl *D2CXX = CXXRecordDecl::Create(Importer.getToContext(),
2651                                                    D->getTagKind(),
2652                                                    DC, StartLoc, Loc,
2653                                                    Name.getAsIdentifierInfo());
2654       D2 = D2CXX;
2655       D2->setAccess(D->getAccess());
2656     } else {
2657       D2 = RecordDecl::Create(Importer.getToContext(), D->getTagKind(),
2658                               DC, StartLoc, Loc, Name.getAsIdentifierInfo());
2659     }
2660 
2661     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2662     D2->setLexicalDeclContext(LexicalDC);
2663     LexicalDC->addDeclInternal(D2);
2664     if (D->isAnonymousStructOrUnion())
2665       D2->setAnonymousStructOrUnion(true);
2666   }
2667 
2668   Importer.Imported(D, D2);
2669 
2670   if (D->isCompleteDefinition() && ImportDefinition(D, D2, IDK_Default))
2671     return nullptr;
2672 
2673   return D2;
2674 }
2675 
VisitEnumConstantDecl(EnumConstantDecl * D)2676 Decl *ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2677   // Import the major distinguishing characteristics of this enumerator.
2678   DeclContext *DC, *LexicalDC;
2679   DeclarationName Name;
2680   SourceLocation Loc;
2681   NamedDecl *ToD;
2682   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2683     return nullptr;
2684   if (ToD)
2685     return ToD;
2686 
2687   QualType T = Importer.Import(D->getType());
2688   if (T.isNull())
2689     return nullptr;
2690 
2691   // Determine whether there are any other declarations with the same name and
2692   // in the same context.
2693   if (!LexicalDC->isFunctionOrMethod()) {
2694     SmallVector<NamedDecl *, 4> ConflictingDecls;
2695     unsigned IDNS = Decl::IDNS_Ordinary;
2696     SmallVector<NamedDecl *, 2> FoundDecls;
2697     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2698     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2699       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2700         continue;
2701 
2702       if (EnumConstantDecl *FoundEnumConstant
2703             = dyn_cast<EnumConstantDecl>(FoundDecls[I])) {
2704         if (IsStructuralMatch(D, FoundEnumConstant))
2705           return Importer.Imported(D, FoundEnumConstant);
2706       }
2707 
2708       ConflictingDecls.push_back(FoundDecls[I]);
2709     }
2710 
2711     if (!ConflictingDecls.empty()) {
2712       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2713                                          ConflictingDecls.data(),
2714                                          ConflictingDecls.size());
2715       if (!Name)
2716         return nullptr;
2717     }
2718   }
2719 
2720   Expr *Init = Importer.Import(D->getInitExpr());
2721   if (D->getInitExpr() && !Init)
2722     return nullptr;
2723 
2724   EnumConstantDecl *ToEnumerator
2725     = EnumConstantDecl::Create(Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2726                                Name.getAsIdentifierInfo(), T,
2727                                Init, D->getInitVal());
2728   ToEnumerator->setAccess(D->getAccess());
2729   ToEnumerator->setLexicalDeclContext(LexicalDC);
2730   Importer.Imported(D, ToEnumerator);
2731   LexicalDC->addDeclInternal(ToEnumerator);
2732   return ToEnumerator;
2733 }
2734 
VisitFunctionDecl(FunctionDecl * D)2735 Decl *ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2736   // Import the major distinguishing characteristics of this function.
2737   DeclContext *DC, *LexicalDC;
2738   DeclarationName Name;
2739   SourceLocation Loc;
2740   NamedDecl *ToD;
2741   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2742     return nullptr;
2743   if (ToD)
2744     return ToD;
2745 
2746   // Try to find a function in our own ("to") context with the same name, same
2747   // type, and in the same context as the function we're importing.
2748   if (!LexicalDC->isFunctionOrMethod()) {
2749     SmallVector<NamedDecl *, 4> ConflictingDecls;
2750     unsigned IDNS = Decl::IDNS_Ordinary;
2751     SmallVector<NamedDecl *, 2> FoundDecls;
2752     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2753     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2754       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
2755         continue;
2756 
2757       if (FunctionDecl *FoundFunction = dyn_cast<FunctionDecl>(FoundDecls[I])) {
2758         if (FoundFunction->hasExternalFormalLinkage() &&
2759             D->hasExternalFormalLinkage()) {
2760           if (Importer.IsStructurallyEquivalent(D->getType(),
2761                                                 FoundFunction->getType())) {
2762             // FIXME: Actually try to merge the body and other attributes.
2763             return Importer.Imported(D, FoundFunction);
2764           }
2765 
2766           // FIXME: Check for overloading more carefully, e.g., by boosting
2767           // Sema::IsOverload out to the AST library.
2768 
2769           // Function overloading is okay in C++.
2770           if (Importer.getToContext().getLangOpts().CPlusPlus)
2771             continue;
2772 
2773           // Complain about inconsistent function types.
2774           Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
2775             << Name << D->getType() << FoundFunction->getType();
2776           Importer.ToDiag(FoundFunction->getLocation(),
2777                           diag::note_odr_value_here)
2778             << FoundFunction->getType();
2779         }
2780       }
2781 
2782       ConflictingDecls.push_back(FoundDecls[I]);
2783     }
2784 
2785     if (!ConflictingDecls.empty()) {
2786       Name = Importer.HandleNameConflict(Name, DC, IDNS,
2787                                          ConflictingDecls.data(),
2788                                          ConflictingDecls.size());
2789       if (!Name)
2790         return nullptr;
2791     }
2792   }
2793 
2794   DeclarationNameInfo NameInfo(Name, Loc);
2795   // Import additional name location/type info.
2796   ImportDeclarationNameLoc(D->getNameInfo(), NameInfo);
2797 
2798   QualType FromTy = D->getType();
2799   bool usedDifferentExceptionSpec = false;
2800 
2801   if (const FunctionProtoType *
2802         FromFPT = D->getType()->getAs<FunctionProtoType>()) {
2803     FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
2804     // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
2805     // FunctionDecl that we are importing the FunctionProtoType for.
2806     // To avoid an infinite recursion when importing, create the FunctionDecl
2807     // with a simplified function type and update it afterwards.
2808     if (FromEPI.ExceptionSpec.SourceDecl ||
2809         FromEPI.ExceptionSpec.SourceTemplate ||
2810         FromEPI.ExceptionSpec.NoexceptExpr) {
2811       FunctionProtoType::ExtProtoInfo DefaultEPI;
2812       FromTy = Importer.getFromContext().getFunctionType(
2813           FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
2814       usedDifferentExceptionSpec = true;
2815     }
2816   }
2817 
2818   // Import the type.
2819   QualType T = Importer.Import(FromTy);
2820   if (T.isNull())
2821     return nullptr;
2822 
2823   // Import the function parameters.
2824   SmallVector<ParmVarDecl *, 8> Parameters;
2825   for (auto P : D->params()) {
2826     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(P));
2827     if (!ToP)
2828       return nullptr;
2829 
2830     Parameters.push_back(ToP);
2831   }
2832 
2833   // Create the imported function.
2834   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2835   FunctionDecl *ToFunction = nullptr;
2836   SourceLocation InnerLocStart = Importer.Import(D->getInnerLocStart());
2837   if (CXXConstructorDecl *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
2838     ToFunction = CXXConstructorDecl::Create(Importer.getToContext(),
2839                                             cast<CXXRecordDecl>(DC),
2840                                             InnerLocStart,
2841                                             NameInfo, T, TInfo,
2842                                             FromConstructor->isExplicit(),
2843                                             D->isInlineSpecified(),
2844                                             D->isImplicit(),
2845                                             D->isConstexpr());
2846   } else if (isa<CXXDestructorDecl>(D)) {
2847     ToFunction = CXXDestructorDecl::Create(Importer.getToContext(),
2848                                            cast<CXXRecordDecl>(DC),
2849                                            InnerLocStart,
2850                                            NameInfo, T, TInfo,
2851                                            D->isInlineSpecified(),
2852                                            D->isImplicit());
2853   } else if (CXXConversionDecl *FromConversion
2854                                            = dyn_cast<CXXConversionDecl>(D)) {
2855     ToFunction = CXXConversionDecl::Create(Importer.getToContext(),
2856                                            cast<CXXRecordDecl>(DC),
2857                                            InnerLocStart,
2858                                            NameInfo, T, TInfo,
2859                                            D->isInlineSpecified(),
2860                                            FromConversion->isExplicit(),
2861                                            D->isConstexpr(),
2862                                            Importer.Import(D->getLocEnd()));
2863   } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
2864     ToFunction = CXXMethodDecl::Create(Importer.getToContext(),
2865                                        cast<CXXRecordDecl>(DC),
2866                                        InnerLocStart,
2867                                        NameInfo, T, TInfo,
2868                                        Method->getStorageClass(),
2869                                        Method->isInlineSpecified(),
2870                                        D->isConstexpr(),
2871                                        Importer.Import(D->getLocEnd()));
2872   } else {
2873     ToFunction = FunctionDecl::Create(Importer.getToContext(), DC,
2874                                       InnerLocStart,
2875                                       NameInfo, T, TInfo, D->getStorageClass(),
2876                                       D->isInlineSpecified(),
2877                                       D->hasWrittenPrototype(),
2878                                       D->isConstexpr());
2879   }
2880 
2881   // Import the qualifier, if any.
2882   ToFunction->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
2883   ToFunction->setAccess(D->getAccess());
2884   ToFunction->setLexicalDeclContext(LexicalDC);
2885   ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
2886   ToFunction->setTrivial(D->isTrivial());
2887   ToFunction->setPure(D->isPure());
2888   Importer.Imported(D, ToFunction);
2889 
2890   // Set the parameters.
2891   for (unsigned I = 0, N = Parameters.size(); I != N; ++I) {
2892     Parameters[I]->setOwningFunction(ToFunction);
2893     ToFunction->addDeclInternal(Parameters[I]);
2894   }
2895   ToFunction->setParams(Parameters);
2896 
2897   if (usedDifferentExceptionSpec) {
2898     // Update FunctionProtoType::ExtProtoInfo.
2899     QualType T = Importer.Import(D->getType());
2900     if (T.isNull())
2901       return nullptr;
2902     ToFunction->setType(T);
2903   }
2904 
2905   // Import the body, if any.
2906   if (Stmt *FromBody = D->getBody()) {
2907     if (Stmt *ToBody = Importer.Import(FromBody)) {
2908       ToFunction->setBody(ToBody);
2909     }
2910   }
2911 
2912   // FIXME: Other bits to merge?
2913 
2914   // Add this function to the lexical context.
2915   LexicalDC->addDeclInternal(ToFunction);
2916 
2917   return ToFunction;
2918 }
2919 
VisitCXXMethodDecl(CXXMethodDecl * D)2920 Decl *ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
2921   return VisitFunctionDecl(D);
2922 }
2923 
VisitCXXConstructorDecl(CXXConstructorDecl * D)2924 Decl *ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2925   return VisitCXXMethodDecl(D);
2926 }
2927 
VisitCXXDestructorDecl(CXXDestructorDecl * D)2928 Decl *ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2929   return VisitCXXMethodDecl(D);
2930 }
2931 
VisitCXXConversionDecl(CXXConversionDecl * D)2932 Decl *ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
2933   return VisitCXXMethodDecl(D);
2934 }
2935 
getFieldIndex(Decl * F)2936 static unsigned getFieldIndex(Decl *F) {
2937   RecordDecl *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
2938   if (!Owner)
2939     return 0;
2940 
2941   unsigned Index = 1;
2942   for (const auto *D : Owner->noload_decls()) {
2943     if (D == F)
2944       return Index;
2945 
2946     if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
2947       ++Index;
2948   }
2949 
2950   return Index;
2951 }
2952 
VisitFieldDecl(FieldDecl * D)2953 Decl *ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
2954   // Import the major distinguishing characteristics of a variable.
2955   DeclContext *DC, *LexicalDC;
2956   DeclarationName Name;
2957   SourceLocation Loc;
2958   NamedDecl *ToD;
2959   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2960     return nullptr;
2961   if (ToD)
2962     return ToD;
2963 
2964   // Determine whether we've already imported this field.
2965   SmallVector<NamedDecl *, 2> FoundDecls;
2966   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
2967   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
2968     if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecls[I])) {
2969       // For anonymous fields, match up by index.
2970       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
2971         continue;
2972 
2973       if (Importer.IsStructurallyEquivalent(D->getType(),
2974                                             FoundField->getType())) {
2975         Importer.Imported(D, FoundField);
2976         return FoundField;
2977       }
2978 
2979       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
2980         << Name << D->getType() << FoundField->getType();
2981       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
2982         << FoundField->getType();
2983       return nullptr;
2984     }
2985   }
2986 
2987   // Import the type.
2988   QualType T = Importer.Import(D->getType());
2989   if (T.isNull())
2990     return nullptr;
2991 
2992   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
2993   Expr *BitWidth = Importer.Import(D->getBitWidth());
2994   if (!BitWidth && D->getBitWidth())
2995     return nullptr;
2996 
2997   FieldDecl *ToField = FieldDecl::Create(Importer.getToContext(), DC,
2998                                          Importer.Import(D->getInnerLocStart()),
2999                                          Loc, Name.getAsIdentifierInfo(),
3000                                          T, TInfo, BitWidth, D->isMutable(),
3001                                          D->getInClassInitStyle());
3002   ToField->setAccess(D->getAccess());
3003   ToField->setLexicalDeclContext(LexicalDC);
3004   if (ToField->hasInClassInitializer())
3005     ToField->setInClassInitializer(D->getInClassInitializer());
3006   ToField->setImplicit(D->isImplicit());
3007   Importer.Imported(D, ToField);
3008   LexicalDC->addDeclInternal(ToField);
3009   return ToField;
3010 }
3011 
VisitIndirectFieldDecl(IndirectFieldDecl * D)3012 Decl *ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3013   // Import the major distinguishing characteristics of a variable.
3014   DeclContext *DC, *LexicalDC;
3015   DeclarationName Name;
3016   SourceLocation Loc;
3017   NamedDecl *ToD;
3018   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3019     return nullptr;
3020   if (ToD)
3021     return ToD;
3022 
3023   // Determine whether we've already imported this field.
3024   SmallVector<NamedDecl *, 2> FoundDecls;
3025   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3026   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3027     if (IndirectFieldDecl *FoundField
3028                                 = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3029       // For anonymous indirect fields, match up by index.
3030       if (!Name && getFieldIndex(D) != getFieldIndex(FoundField))
3031         continue;
3032 
3033       if (Importer.IsStructurallyEquivalent(D->getType(),
3034                                             FoundField->getType(),
3035                                             !Name.isEmpty())) {
3036         Importer.Imported(D, FoundField);
3037         return FoundField;
3038       }
3039 
3040       // If there are more anonymous fields to check, continue.
3041       if (!Name && I < N-1)
3042         continue;
3043 
3044       Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3045         << Name << D->getType() << FoundField->getType();
3046       Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3047         << FoundField->getType();
3048       return nullptr;
3049     }
3050   }
3051 
3052   // Import the type.
3053   QualType T = Importer.Import(D->getType());
3054   if (T.isNull())
3055     return nullptr;
3056 
3057   NamedDecl **NamedChain =
3058     new (Importer.getToContext())NamedDecl*[D->getChainingSize()];
3059 
3060   unsigned i = 0;
3061   for (auto *PI : D->chain()) {
3062     Decl *D = Importer.Import(PI);
3063     if (!D)
3064       return nullptr;
3065     NamedChain[i++] = cast<NamedDecl>(D);
3066   }
3067 
3068   IndirectFieldDecl *ToIndirectField = IndirectFieldDecl::Create(
3069       Importer.getToContext(), DC, Loc, Name.getAsIdentifierInfo(), T,
3070       NamedChain, D->getChainingSize());
3071 
3072   for (const auto *Attr : D->attrs())
3073     ToIndirectField->addAttr(Attr->clone(Importer.getToContext()));
3074 
3075   ToIndirectField->setAccess(D->getAccess());
3076   ToIndirectField->setLexicalDeclContext(LexicalDC);
3077   Importer.Imported(D, ToIndirectField);
3078   LexicalDC->addDeclInternal(ToIndirectField);
3079   return ToIndirectField;
3080 }
3081 
VisitObjCIvarDecl(ObjCIvarDecl * D)3082 Decl *ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3083   // Import the major distinguishing characteristics of an ivar.
3084   DeclContext *DC, *LexicalDC;
3085   DeclarationName Name;
3086   SourceLocation Loc;
3087   NamedDecl *ToD;
3088   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3089     return nullptr;
3090   if (ToD)
3091     return ToD;
3092 
3093   // Determine whether we've already imported this ivar
3094   SmallVector<NamedDecl *, 2> FoundDecls;
3095   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3096   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3097     if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecls[I])) {
3098       if (Importer.IsStructurallyEquivalent(D->getType(),
3099                                             FoundIvar->getType())) {
3100         Importer.Imported(D, FoundIvar);
3101         return FoundIvar;
3102       }
3103 
3104       Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3105         << Name << D->getType() << FoundIvar->getType();
3106       Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3107         << FoundIvar->getType();
3108       return nullptr;
3109     }
3110   }
3111 
3112   // Import the type.
3113   QualType T = Importer.Import(D->getType());
3114   if (T.isNull())
3115     return nullptr;
3116 
3117   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3118   Expr *BitWidth = Importer.Import(D->getBitWidth());
3119   if (!BitWidth && D->getBitWidth())
3120     return nullptr;
3121 
3122   ObjCIvarDecl *ToIvar = ObjCIvarDecl::Create(Importer.getToContext(),
3123                                               cast<ObjCContainerDecl>(DC),
3124                                        Importer.Import(D->getInnerLocStart()),
3125                                               Loc, Name.getAsIdentifierInfo(),
3126                                               T, TInfo, D->getAccessControl(),
3127                                               BitWidth, D->getSynthesize());
3128   ToIvar->setLexicalDeclContext(LexicalDC);
3129   Importer.Imported(D, ToIvar);
3130   LexicalDC->addDeclInternal(ToIvar);
3131   return ToIvar;
3132 
3133 }
3134 
VisitVarDecl(VarDecl * D)3135 Decl *ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3136   // Import the major distinguishing characteristics of a variable.
3137   DeclContext *DC, *LexicalDC;
3138   DeclarationName Name;
3139   SourceLocation Loc;
3140   NamedDecl *ToD;
3141   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3142     return nullptr;
3143   if (ToD)
3144     return ToD;
3145 
3146   // Try to find a variable in our own ("to") context with the same name and
3147   // in the same context as the variable we're importing.
3148   if (D->isFileVarDecl()) {
3149     VarDecl *MergeWithVar = nullptr;
3150     SmallVector<NamedDecl *, 4> ConflictingDecls;
3151     unsigned IDNS = Decl::IDNS_Ordinary;
3152     SmallVector<NamedDecl *, 2> FoundDecls;
3153     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3154     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3155       if (!FoundDecls[I]->isInIdentifierNamespace(IDNS))
3156         continue;
3157 
3158       if (VarDecl *FoundVar = dyn_cast<VarDecl>(FoundDecls[I])) {
3159         // We have found a variable that we may need to merge with. Check it.
3160         if (FoundVar->hasExternalFormalLinkage() &&
3161             D->hasExternalFormalLinkage()) {
3162           if (Importer.IsStructurallyEquivalent(D->getType(),
3163                                                 FoundVar->getType())) {
3164             MergeWithVar = FoundVar;
3165             break;
3166           }
3167 
3168           const ArrayType *FoundArray
3169             = Importer.getToContext().getAsArrayType(FoundVar->getType());
3170           const ArrayType *TArray
3171             = Importer.getToContext().getAsArrayType(D->getType());
3172           if (FoundArray && TArray) {
3173             if (isa<IncompleteArrayType>(FoundArray) &&
3174                 isa<ConstantArrayType>(TArray)) {
3175               // Import the type.
3176               QualType T = Importer.Import(D->getType());
3177               if (T.isNull())
3178                 return nullptr;
3179 
3180               FoundVar->setType(T);
3181               MergeWithVar = FoundVar;
3182               break;
3183             } else if (isa<IncompleteArrayType>(TArray) &&
3184                        isa<ConstantArrayType>(FoundArray)) {
3185               MergeWithVar = FoundVar;
3186               break;
3187             }
3188           }
3189 
3190           Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3191             << Name << D->getType() << FoundVar->getType();
3192           Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3193             << FoundVar->getType();
3194         }
3195       }
3196 
3197       ConflictingDecls.push_back(FoundDecls[I]);
3198     }
3199 
3200     if (MergeWithVar) {
3201       // An equivalent variable with external linkage has been found. Link
3202       // the two declarations, then merge them.
3203       Importer.Imported(D, MergeWithVar);
3204 
3205       if (VarDecl *DDef = D->getDefinition()) {
3206         if (VarDecl *ExistingDef = MergeWithVar->getDefinition()) {
3207           Importer.ToDiag(ExistingDef->getLocation(),
3208                           diag::err_odr_variable_multiple_def)
3209             << Name;
3210           Importer.FromDiag(DDef->getLocation(), diag::note_odr_defined_here);
3211         } else {
3212           Expr *Init = Importer.Import(DDef->getInit());
3213           MergeWithVar->setInit(Init);
3214           if (DDef->isInitKnownICE()) {
3215             EvaluatedStmt *Eval = MergeWithVar->ensureEvaluatedStmt();
3216             Eval->CheckedICE = true;
3217             Eval->IsICE = DDef->isInitICE();
3218           }
3219         }
3220       }
3221 
3222       return MergeWithVar;
3223     }
3224 
3225     if (!ConflictingDecls.empty()) {
3226       Name = Importer.HandleNameConflict(Name, DC, IDNS,
3227                                          ConflictingDecls.data(),
3228                                          ConflictingDecls.size());
3229       if (!Name)
3230         return nullptr;
3231     }
3232   }
3233 
3234   // Import the type.
3235   QualType T = Importer.Import(D->getType());
3236   if (T.isNull())
3237     return nullptr;
3238 
3239   // Create the imported variable.
3240   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3241   VarDecl *ToVar = VarDecl::Create(Importer.getToContext(), DC,
3242                                    Importer.Import(D->getInnerLocStart()),
3243                                    Loc, Name.getAsIdentifierInfo(),
3244                                    T, TInfo,
3245                                    D->getStorageClass());
3246   ToVar->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
3247   ToVar->setAccess(D->getAccess());
3248   ToVar->setLexicalDeclContext(LexicalDC);
3249   Importer.Imported(D, ToVar);
3250   LexicalDC->addDeclInternal(ToVar);
3251 
3252   if (!D->isFileVarDecl() &&
3253       D->isUsed())
3254     ToVar->setIsUsed();
3255 
3256   // Merge the initializer.
3257   if (ImportDefinition(D, ToVar))
3258     return nullptr;
3259 
3260   return ToVar;
3261 }
3262 
VisitImplicitParamDecl(ImplicitParamDecl * D)3263 Decl *ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3264   // Parameters are created in the translation unit's context, then moved
3265   // into the function declaration's context afterward.
3266   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3267 
3268   // Import the name of this declaration.
3269   DeclarationName Name = Importer.Import(D->getDeclName());
3270   if (D->getDeclName() && !Name)
3271     return nullptr;
3272 
3273   // Import the location of this declaration.
3274   SourceLocation Loc = Importer.Import(D->getLocation());
3275 
3276   // Import the parameter's type.
3277   QualType T = Importer.Import(D->getType());
3278   if (T.isNull())
3279     return nullptr;
3280 
3281   // Create the imported parameter.
3282   ImplicitParamDecl *ToParm
3283     = ImplicitParamDecl::Create(Importer.getToContext(), DC,
3284                                 Loc, Name.getAsIdentifierInfo(),
3285                                 T);
3286   return Importer.Imported(D, ToParm);
3287 }
3288 
VisitParmVarDecl(ParmVarDecl * D)3289 Decl *ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3290   // Parameters are created in the translation unit's context, then moved
3291   // into the function declaration's context afterward.
3292   DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3293 
3294   // Import the name of this declaration.
3295   DeclarationName Name = Importer.Import(D->getDeclName());
3296   if (D->getDeclName() && !Name)
3297     return nullptr;
3298 
3299   // Import the location of this declaration.
3300   SourceLocation Loc = Importer.Import(D->getLocation());
3301 
3302   // Import the parameter's type.
3303   QualType T = Importer.Import(D->getType());
3304   if (T.isNull())
3305     return nullptr;
3306 
3307   // Create the imported parameter.
3308   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
3309   ParmVarDecl *ToParm = ParmVarDecl::Create(Importer.getToContext(), DC,
3310                                      Importer.Import(D->getInnerLocStart()),
3311                                             Loc, Name.getAsIdentifierInfo(),
3312                                             T, TInfo, D->getStorageClass(),
3313                                             /*FIXME: Default argument*/nullptr);
3314   ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3315 
3316   if (D->isUsed())
3317     ToParm->setIsUsed();
3318 
3319   return Importer.Imported(D, ToParm);
3320 }
3321 
VisitObjCMethodDecl(ObjCMethodDecl * D)3322 Decl *ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3323   // Import the major distinguishing characteristics of a method.
3324   DeclContext *DC, *LexicalDC;
3325   DeclarationName Name;
3326   SourceLocation Loc;
3327   NamedDecl *ToD;
3328   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3329     return nullptr;
3330   if (ToD)
3331     return ToD;
3332 
3333   SmallVector<NamedDecl *, 2> FoundDecls;
3334   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3335   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3336     if (ObjCMethodDecl *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecls[I])) {
3337       if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3338         continue;
3339 
3340       // Check return types.
3341       if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3342                                              FoundMethod->getReturnType())) {
3343         Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3344             << D->isInstanceMethod() << Name << D->getReturnType()
3345             << FoundMethod->getReturnType();
3346         Importer.ToDiag(FoundMethod->getLocation(),
3347                         diag::note_odr_objc_method_here)
3348           << D->isInstanceMethod() << Name;
3349         return nullptr;
3350       }
3351 
3352       // Check the number of parameters.
3353       if (D->param_size() != FoundMethod->param_size()) {
3354         Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3355           << D->isInstanceMethod() << Name
3356           << D->param_size() << FoundMethod->param_size();
3357         Importer.ToDiag(FoundMethod->getLocation(),
3358                         diag::note_odr_objc_method_here)
3359           << D->isInstanceMethod() << Name;
3360         return nullptr;
3361       }
3362 
3363       // Check parameter types.
3364       for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3365              PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3366            P != PEnd; ++P, ++FoundP) {
3367         if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3368                                                (*FoundP)->getType())) {
3369           Importer.FromDiag((*P)->getLocation(),
3370                             diag::err_odr_objc_method_param_type_inconsistent)
3371             << D->isInstanceMethod() << Name
3372             << (*P)->getType() << (*FoundP)->getType();
3373           Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3374             << (*FoundP)->getType();
3375           return nullptr;
3376         }
3377       }
3378 
3379       // Check variadic/non-variadic.
3380       // Check the number of parameters.
3381       if (D->isVariadic() != FoundMethod->isVariadic()) {
3382         Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3383           << D->isInstanceMethod() << Name;
3384         Importer.ToDiag(FoundMethod->getLocation(),
3385                         diag::note_odr_objc_method_here)
3386           << D->isInstanceMethod() << Name;
3387         return nullptr;
3388       }
3389 
3390       // FIXME: Any other bits we need to merge?
3391       return Importer.Imported(D, FoundMethod);
3392     }
3393   }
3394 
3395   // Import the result type.
3396   QualType ResultTy = Importer.Import(D->getReturnType());
3397   if (ResultTy.isNull())
3398     return nullptr;
3399 
3400   TypeSourceInfo *ReturnTInfo = Importer.Import(D->getReturnTypeSourceInfo());
3401 
3402   ObjCMethodDecl *ToMethod = ObjCMethodDecl::Create(
3403       Importer.getToContext(), Loc, Importer.Import(D->getLocEnd()),
3404       Name.getObjCSelector(), ResultTy, ReturnTInfo, DC, D->isInstanceMethod(),
3405       D->isVariadic(), D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3406       D->getImplementationControl(), D->hasRelatedResultType());
3407 
3408   // FIXME: When we decide to merge method definitions, we'll need to
3409   // deal with implicit parameters.
3410 
3411   // Import the parameters
3412   SmallVector<ParmVarDecl *, 5> ToParams;
3413   for (auto *FromP : D->params()) {
3414     ParmVarDecl *ToP = cast_or_null<ParmVarDecl>(Importer.Import(FromP));
3415     if (!ToP)
3416       return nullptr;
3417 
3418     ToParams.push_back(ToP);
3419   }
3420 
3421   // Set the parameters.
3422   for (unsigned I = 0, N = ToParams.size(); I != N; ++I) {
3423     ToParams[I]->setOwningFunction(ToMethod);
3424     ToMethod->addDeclInternal(ToParams[I]);
3425   }
3426   SmallVector<SourceLocation, 12> SelLocs;
3427   D->getSelectorLocs(SelLocs);
3428   ToMethod->setMethodParams(Importer.getToContext(), ToParams, SelLocs);
3429 
3430   ToMethod->setLexicalDeclContext(LexicalDC);
3431   Importer.Imported(D, ToMethod);
3432   LexicalDC->addDeclInternal(ToMethod);
3433   return ToMethod;
3434 }
3435 
VisitObjCTypeParamDecl(ObjCTypeParamDecl * D)3436 Decl *ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3437   // Import the major distinguishing characteristics of a category.
3438   DeclContext *DC, *LexicalDC;
3439   DeclarationName Name;
3440   SourceLocation Loc;
3441   NamedDecl *ToD;
3442   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3443     return nullptr;
3444   if (ToD)
3445     return ToD;
3446 
3447   TypeSourceInfo *BoundInfo = Importer.Import(D->getTypeSourceInfo());
3448   if (!BoundInfo)
3449     return nullptr;
3450 
3451   ObjCTypeParamDecl *Result = ObjCTypeParamDecl::Create(
3452                                 Importer.getToContext(), DC,
3453                                 D->getVariance(),
3454                                 Importer.Import(D->getVarianceLoc()),
3455                                 D->getIndex(),
3456                                 Importer.Import(D->getLocation()),
3457                                 Name.getAsIdentifierInfo(),
3458                                 Importer.Import(D->getColonLoc()),
3459                                 BoundInfo);
3460   Importer.Imported(D, Result);
3461   Result->setLexicalDeclContext(LexicalDC);
3462   return Result;
3463 }
3464 
VisitObjCCategoryDecl(ObjCCategoryDecl * D)3465 Decl *ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3466   // Import the major distinguishing characteristics of a category.
3467   DeclContext *DC, *LexicalDC;
3468   DeclarationName Name;
3469   SourceLocation Loc;
3470   NamedDecl *ToD;
3471   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3472     return nullptr;
3473   if (ToD)
3474     return ToD;
3475 
3476   ObjCInterfaceDecl *ToInterface
3477     = cast_or_null<ObjCInterfaceDecl>(Importer.Import(D->getClassInterface()));
3478   if (!ToInterface)
3479     return nullptr;
3480 
3481   // Determine if we've already encountered this category.
3482   ObjCCategoryDecl *MergeWithCategory
3483     = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3484   ObjCCategoryDecl *ToCategory = MergeWithCategory;
3485   if (!ToCategory) {
3486     ToCategory = ObjCCategoryDecl::Create(Importer.getToContext(), DC,
3487                                           Importer.Import(D->getAtStartLoc()),
3488                                           Loc,
3489                                        Importer.Import(D->getCategoryNameLoc()),
3490                                           Name.getAsIdentifierInfo(),
3491                                           ToInterface,
3492                                           /*TypeParamList=*/nullptr,
3493                                        Importer.Import(D->getIvarLBraceLoc()),
3494                                        Importer.Import(D->getIvarRBraceLoc()));
3495     ToCategory->setLexicalDeclContext(LexicalDC);
3496     LexicalDC->addDeclInternal(ToCategory);
3497     Importer.Imported(D, ToCategory);
3498     // Import the type parameter list after calling Imported, to avoid
3499     // loops when bringing in their DeclContext.
3500     ToCategory->setTypeParamList(ImportObjCTypeParamList(
3501                                    D->getTypeParamList()));
3502 
3503     // Import protocols
3504     SmallVector<ObjCProtocolDecl *, 4> Protocols;
3505     SmallVector<SourceLocation, 4> ProtocolLocs;
3506     ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3507       = D->protocol_loc_begin();
3508     for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3509                                           FromProtoEnd = D->protocol_end();
3510          FromProto != FromProtoEnd;
3511          ++FromProto, ++FromProtoLoc) {
3512       ObjCProtocolDecl *ToProto
3513         = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3514       if (!ToProto)
3515         return nullptr;
3516       Protocols.push_back(ToProto);
3517       ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3518     }
3519 
3520     // FIXME: If we're merging, make sure that the protocol list is the same.
3521     ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3522                                 ProtocolLocs.data(), Importer.getToContext());
3523 
3524   } else {
3525     Importer.Imported(D, ToCategory);
3526   }
3527 
3528   // Import all of the members of this category.
3529   ImportDeclContext(D);
3530 
3531   // If we have an implementation, import it as well.
3532   if (D->getImplementation()) {
3533     ObjCCategoryImplDecl *Impl
3534       = cast_or_null<ObjCCategoryImplDecl>(
3535                                        Importer.Import(D->getImplementation()));
3536     if (!Impl)
3537       return nullptr;
3538 
3539     ToCategory->setImplementation(Impl);
3540   }
3541 
3542   return ToCategory;
3543 }
3544 
ImportDefinition(ObjCProtocolDecl * From,ObjCProtocolDecl * To,ImportDefinitionKind Kind)3545 bool ASTNodeImporter::ImportDefinition(ObjCProtocolDecl *From,
3546                                        ObjCProtocolDecl *To,
3547                                        ImportDefinitionKind Kind) {
3548   if (To->getDefinition()) {
3549     if (shouldForceImportDeclContext(Kind))
3550       ImportDeclContext(From);
3551     return false;
3552   }
3553 
3554   // Start the protocol definition
3555   To->startDefinition();
3556 
3557   // Import protocols
3558   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3559   SmallVector<SourceLocation, 4> ProtocolLocs;
3560   ObjCProtocolDecl::protocol_loc_iterator
3561   FromProtoLoc = From->protocol_loc_begin();
3562   for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
3563                                         FromProtoEnd = From->protocol_end();
3564        FromProto != FromProtoEnd;
3565        ++FromProto, ++FromProtoLoc) {
3566     ObjCProtocolDecl *ToProto
3567       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3568     if (!ToProto)
3569       return true;
3570     Protocols.push_back(ToProto);
3571     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3572   }
3573 
3574   // FIXME: If we're merging, make sure that the protocol list is the same.
3575   To->setProtocolList(Protocols.data(), Protocols.size(),
3576                       ProtocolLocs.data(), Importer.getToContext());
3577 
3578   if (shouldForceImportDeclContext(Kind)) {
3579     // Import all of the members of this protocol.
3580     ImportDeclContext(From, /*ForceImport=*/true);
3581   }
3582   return false;
3583 }
3584 
VisitObjCProtocolDecl(ObjCProtocolDecl * D)3585 Decl *ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
3586   // If this protocol has a definition in the translation unit we're coming
3587   // from, but this particular declaration is not that definition, import the
3588   // definition and map to that.
3589   ObjCProtocolDecl *Definition = D->getDefinition();
3590   if (Definition && Definition != D) {
3591     Decl *ImportedDef = Importer.Import(Definition);
3592     if (!ImportedDef)
3593       return nullptr;
3594 
3595     return Importer.Imported(D, ImportedDef);
3596   }
3597 
3598   // Import the major distinguishing characteristics of a protocol.
3599   DeclContext *DC, *LexicalDC;
3600   DeclarationName Name;
3601   SourceLocation Loc;
3602   NamedDecl *ToD;
3603   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3604     return nullptr;
3605   if (ToD)
3606     return ToD;
3607 
3608   ObjCProtocolDecl *MergeWithProtocol = nullptr;
3609   SmallVector<NamedDecl *, 2> FoundDecls;
3610   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3611   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3612     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
3613       continue;
3614 
3615     if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecls[I])))
3616       break;
3617   }
3618 
3619   ObjCProtocolDecl *ToProto = MergeWithProtocol;
3620   if (!ToProto) {
3621     ToProto = ObjCProtocolDecl::Create(Importer.getToContext(), DC,
3622                                        Name.getAsIdentifierInfo(), Loc,
3623                                        Importer.Import(D->getAtStartLoc()),
3624                                        /*PrevDecl=*/nullptr);
3625     ToProto->setLexicalDeclContext(LexicalDC);
3626     LexicalDC->addDeclInternal(ToProto);
3627   }
3628 
3629   Importer.Imported(D, ToProto);
3630 
3631   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToProto))
3632     return nullptr;
3633 
3634   return ToProto;
3635 }
3636 
VisitLinkageSpecDecl(LinkageSpecDecl * D)3637 Decl *ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
3638   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3639   DeclContext *LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3640 
3641   SourceLocation ExternLoc = Importer.Import(D->getExternLoc());
3642   SourceLocation LangLoc = Importer.Import(D->getLocation());
3643 
3644   bool HasBraces = D->hasBraces();
3645 
3646   LinkageSpecDecl *ToLinkageSpec =
3647     LinkageSpecDecl::Create(Importer.getToContext(),
3648                             DC,
3649                             ExternLoc,
3650                             LangLoc,
3651                             D->getLanguage(),
3652                             HasBraces);
3653 
3654   if (HasBraces) {
3655     SourceLocation RBraceLoc = Importer.Import(D->getRBraceLoc());
3656     ToLinkageSpec->setRBraceLoc(RBraceLoc);
3657   }
3658 
3659   ToLinkageSpec->setLexicalDeclContext(LexicalDC);
3660   LexicalDC->addDeclInternal(ToLinkageSpec);
3661 
3662   Importer.Imported(D, ToLinkageSpec);
3663 
3664   return ToLinkageSpec;
3665 }
3666 
ImportDefinition(ObjCInterfaceDecl * From,ObjCInterfaceDecl * To,ImportDefinitionKind Kind)3667 bool ASTNodeImporter::ImportDefinition(ObjCInterfaceDecl *From,
3668                                        ObjCInterfaceDecl *To,
3669                                        ImportDefinitionKind Kind) {
3670   if (To->getDefinition()) {
3671     // Check consistency of superclass.
3672     ObjCInterfaceDecl *FromSuper = From->getSuperClass();
3673     if (FromSuper) {
3674       FromSuper = cast_or_null<ObjCInterfaceDecl>(Importer.Import(FromSuper));
3675       if (!FromSuper)
3676         return true;
3677     }
3678 
3679     ObjCInterfaceDecl *ToSuper = To->getSuperClass();
3680     if ((bool)FromSuper != (bool)ToSuper ||
3681         (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
3682       Importer.ToDiag(To->getLocation(),
3683                       diag::err_odr_objc_superclass_inconsistent)
3684         << To->getDeclName();
3685       if (ToSuper)
3686         Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
3687           << To->getSuperClass()->getDeclName();
3688       else
3689         Importer.ToDiag(To->getLocation(),
3690                         diag::note_odr_objc_missing_superclass);
3691       if (From->getSuperClass())
3692         Importer.FromDiag(From->getSuperClassLoc(),
3693                           diag::note_odr_objc_superclass)
3694         << From->getSuperClass()->getDeclName();
3695       else
3696         Importer.FromDiag(From->getLocation(),
3697                           diag::note_odr_objc_missing_superclass);
3698     }
3699 
3700     if (shouldForceImportDeclContext(Kind))
3701       ImportDeclContext(From);
3702     return false;
3703   }
3704 
3705   // Start the definition.
3706   To->startDefinition();
3707 
3708   // If this class has a superclass, import it.
3709   if (From->getSuperClass()) {
3710     TypeSourceInfo *SuperTInfo = Importer.Import(From->getSuperClassTInfo());
3711     if (!SuperTInfo)
3712       return true;
3713 
3714     To->setSuperClass(SuperTInfo);
3715   }
3716 
3717   // Import protocols
3718   SmallVector<ObjCProtocolDecl *, 4> Protocols;
3719   SmallVector<SourceLocation, 4> ProtocolLocs;
3720   ObjCInterfaceDecl::protocol_loc_iterator
3721   FromProtoLoc = From->protocol_loc_begin();
3722 
3723   for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
3724                                          FromProtoEnd = From->protocol_end();
3725        FromProto != FromProtoEnd;
3726        ++FromProto, ++FromProtoLoc) {
3727     ObjCProtocolDecl *ToProto
3728       = cast_or_null<ObjCProtocolDecl>(Importer.Import(*FromProto));
3729     if (!ToProto)
3730       return true;
3731     Protocols.push_back(ToProto);
3732     ProtocolLocs.push_back(Importer.Import(*FromProtoLoc));
3733   }
3734 
3735   // FIXME: If we're merging, make sure that the protocol list is the same.
3736   To->setProtocolList(Protocols.data(), Protocols.size(),
3737                       ProtocolLocs.data(), Importer.getToContext());
3738 
3739   // Import categories. When the categories themselves are imported, they'll
3740   // hook themselves into this interface.
3741   for (auto *Cat : From->known_categories())
3742     Importer.Import(Cat);
3743 
3744   // If we have an @implementation, import it as well.
3745   if (From->getImplementation()) {
3746     ObjCImplementationDecl *Impl = cast_or_null<ObjCImplementationDecl>(
3747                                      Importer.Import(From->getImplementation()));
3748     if (!Impl)
3749       return true;
3750 
3751     To->setImplementation(Impl);
3752   }
3753 
3754   if (shouldForceImportDeclContext(Kind)) {
3755     // Import all of the members of this class.
3756     ImportDeclContext(From, /*ForceImport=*/true);
3757   }
3758   return false;
3759 }
3760 
3761 ObjCTypeParamList *
ImportObjCTypeParamList(ObjCTypeParamList * list)3762 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
3763   if (!list)
3764     return nullptr;
3765 
3766   SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
3767   for (auto fromTypeParam : *list) {
3768     auto toTypeParam = cast_or_null<ObjCTypeParamDecl>(
3769                          Importer.Import(fromTypeParam));
3770     if (!toTypeParam)
3771       return nullptr;
3772 
3773     toTypeParams.push_back(toTypeParam);
3774   }
3775 
3776   return ObjCTypeParamList::create(Importer.getToContext(),
3777                                    Importer.Import(list->getLAngleLoc()),
3778                                    toTypeParams,
3779                                    Importer.Import(list->getRAngleLoc()));
3780 }
3781 
VisitObjCInterfaceDecl(ObjCInterfaceDecl * D)3782 Decl *ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
3783   // If this class has a definition in the translation unit we're coming from,
3784   // but this particular declaration is not that definition, import the
3785   // definition and map to that.
3786   ObjCInterfaceDecl *Definition = D->getDefinition();
3787   if (Definition && Definition != D) {
3788     Decl *ImportedDef = Importer.Import(Definition);
3789     if (!ImportedDef)
3790       return nullptr;
3791 
3792     return Importer.Imported(D, ImportedDef);
3793   }
3794 
3795   // Import the major distinguishing characteristics of an @interface.
3796   DeclContext *DC, *LexicalDC;
3797   DeclarationName Name;
3798   SourceLocation Loc;
3799   NamedDecl *ToD;
3800   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3801     return nullptr;
3802   if (ToD)
3803     return ToD;
3804 
3805   // Look for an existing interface with the same name.
3806   ObjCInterfaceDecl *MergeWithIface = nullptr;
3807   SmallVector<NamedDecl *, 2> FoundDecls;
3808   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3809   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3810     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
3811       continue;
3812 
3813     if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecls[I])))
3814       break;
3815   }
3816 
3817   // Create an interface declaration, if one does not already exist.
3818   ObjCInterfaceDecl *ToIface = MergeWithIface;
3819   if (!ToIface) {
3820     ToIface = ObjCInterfaceDecl::Create(Importer.getToContext(), DC,
3821                                         Importer.Import(D->getAtStartLoc()),
3822                                         Name.getAsIdentifierInfo(),
3823                                         /*TypeParamList=*/nullptr,
3824                                         /*PrevDecl=*/nullptr, Loc,
3825                                         D->isImplicitInterfaceDecl());
3826     ToIface->setLexicalDeclContext(LexicalDC);
3827     LexicalDC->addDeclInternal(ToIface);
3828   }
3829   Importer.Imported(D, ToIface);
3830   // Import the type parameter list after calling Imported, to avoid
3831   // loops when bringing in their DeclContext.
3832   ToIface->setTypeParamList(ImportObjCTypeParamList(
3833                               D->getTypeParamListAsWritten()));
3834 
3835   if (D->isThisDeclarationADefinition() && ImportDefinition(D, ToIface))
3836     return nullptr;
3837 
3838   return ToIface;
3839 }
3840 
VisitObjCCategoryImplDecl(ObjCCategoryImplDecl * D)3841 Decl *ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
3842   ObjCCategoryDecl *Category = cast_or_null<ObjCCategoryDecl>(
3843                                         Importer.Import(D->getCategoryDecl()));
3844   if (!Category)
3845     return nullptr;
3846 
3847   ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
3848   if (!ToImpl) {
3849     DeclContext *DC = Importer.ImportContext(D->getDeclContext());
3850     if (!DC)
3851       return nullptr;
3852 
3853     SourceLocation CategoryNameLoc = Importer.Import(D->getCategoryNameLoc());
3854     ToImpl = ObjCCategoryImplDecl::Create(Importer.getToContext(), DC,
3855                                           Importer.Import(D->getIdentifier()),
3856                                           Category->getClassInterface(),
3857                                           Importer.Import(D->getLocation()),
3858                                           Importer.Import(D->getAtStartLoc()),
3859                                           CategoryNameLoc);
3860 
3861     DeclContext *LexicalDC = DC;
3862     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3863       LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
3864       if (!LexicalDC)
3865         return nullptr;
3866 
3867       ToImpl->setLexicalDeclContext(LexicalDC);
3868     }
3869 
3870     LexicalDC->addDeclInternal(ToImpl);
3871     Category->setImplementation(ToImpl);
3872   }
3873 
3874   Importer.Imported(D, ToImpl);
3875   ImportDeclContext(D);
3876   return ToImpl;
3877 }
3878 
VisitObjCImplementationDecl(ObjCImplementationDecl * D)3879 Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
3880   // Find the corresponding interface.
3881   ObjCInterfaceDecl *Iface = cast_or_null<ObjCInterfaceDecl>(
3882                                        Importer.Import(D->getClassInterface()));
3883   if (!Iface)
3884     return nullptr;
3885 
3886   // Import the superclass, if any.
3887   ObjCInterfaceDecl *Super = nullptr;
3888   if (D->getSuperClass()) {
3889     Super = cast_or_null<ObjCInterfaceDecl>(
3890                                           Importer.Import(D->getSuperClass()));
3891     if (!Super)
3892       return nullptr;
3893   }
3894 
3895   ObjCImplementationDecl *Impl = Iface->getImplementation();
3896   if (!Impl) {
3897     // We haven't imported an implementation yet. Create a new @implementation
3898     // now.
3899     Impl = ObjCImplementationDecl::Create(Importer.getToContext(),
3900                                   Importer.ImportContext(D->getDeclContext()),
3901                                           Iface, Super,
3902                                           Importer.Import(D->getLocation()),
3903                                           Importer.Import(D->getAtStartLoc()),
3904                                           Importer.Import(D->getSuperClassLoc()),
3905                                           Importer.Import(D->getIvarLBraceLoc()),
3906                                           Importer.Import(D->getIvarRBraceLoc()));
3907 
3908     if (D->getDeclContext() != D->getLexicalDeclContext()) {
3909       DeclContext *LexicalDC
3910         = Importer.ImportContext(D->getLexicalDeclContext());
3911       if (!LexicalDC)
3912         return nullptr;
3913       Impl->setLexicalDeclContext(LexicalDC);
3914     }
3915 
3916     // Associate the implementation with the class it implements.
3917     Iface->setImplementation(Impl);
3918     Importer.Imported(D, Iface->getImplementation());
3919   } else {
3920     Importer.Imported(D, Iface->getImplementation());
3921 
3922     // Verify that the existing @implementation has the same superclass.
3923     if ((Super && !Impl->getSuperClass()) ||
3924         (!Super && Impl->getSuperClass()) ||
3925         (Super && Impl->getSuperClass() &&
3926          !declaresSameEntity(Super->getCanonicalDecl(),
3927                              Impl->getSuperClass()))) {
3928       Importer.ToDiag(Impl->getLocation(),
3929                       diag::err_odr_objc_superclass_inconsistent)
3930         << Iface->getDeclName();
3931       // FIXME: It would be nice to have the location of the superclass
3932       // below.
3933       if (Impl->getSuperClass())
3934         Importer.ToDiag(Impl->getLocation(),
3935                         diag::note_odr_objc_superclass)
3936         << Impl->getSuperClass()->getDeclName();
3937       else
3938         Importer.ToDiag(Impl->getLocation(),
3939                         diag::note_odr_objc_missing_superclass);
3940       if (D->getSuperClass())
3941         Importer.FromDiag(D->getLocation(),
3942                           diag::note_odr_objc_superclass)
3943         << D->getSuperClass()->getDeclName();
3944       else
3945         Importer.FromDiag(D->getLocation(),
3946                           diag::note_odr_objc_missing_superclass);
3947       return nullptr;
3948     }
3949   }
3950 
3951   // Import all of the members of this @implementation.
3952   ImportDeclContext(D);
3953 
3954   return Impl;
3955 }
3956 
VisitObjCPropertyDecl(ObjCPropertyDecl * D)3957 Decl *ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
3958   // Import the major distinguishing characteristics of an @property.
3959   DeclContext *DC, *LexicalDC;
3960   DeclarationName Name;
3961   SourceLocation Loc;
3962   NamedDecl *ToD;
3963   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3964     return nullptr;
3965   if (ToD)
3966     return ToD;
3967 
3968   // Check whether we have already imported this property.
3969   SmallVector<NamedDecl *, 2> FoundDecls;
3970   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
3971   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3972     if (ObjCPropertyDecl *FoundProp
3973                                 = dyn_cast<ObjCPropertyDecl>(FoundDecls[I])) {
3974       // Check property types.
3975       if (!Importer.IsStructurallyEquivalent(D->getType(),
3976                                              FoundProp->getType())) {
3977         Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
3978           << Name << D->getType() << FoundProp->getType();
3979         Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
3980           << FoundProp->getType();
3981         return nullptr;
3982       }
3983 
3984       // FIXME: Check property attributes, getters, setters, etc.?
3985 
3986       // Consider these properties to be equivalent.
3987       Importer.Imported(D, FoundProp);
3988       return FoundProp;
3989     }
3990   }
3991 
3992   // Import the type.
3993   TypeSourceInfo *TSI = Importer.Import(D->getTypeSourceInfo());
3994   if (!TSI)
3995     return nullptr;
3996 
3997   // Create the new property.
3998   ObjCPropertyDecl *ToProperty
3999     = ObjCPropertyDecl::Create(Importer.getToContext(), DC, Loc,
4000                                Name.getAsIdentifierInfo(),
4001                                Importer.Import(D->getAtLoc()),
4002                                Importer.Import(D->getLParenLoc()),
4003                                Importer.Import(D->getType()),
4004                                TSI,
4005                                D->getPropertyImplementation());
4006   Importer.Imported(D, ToProperty);
4007   ToProperty->setLexicalDeclContext(LexicalDC);
4008   LexicalDC->addDeclInternal(ToProperty);
4009 
4010   ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4011   ToProperty->setPropertyAttributesAsWritten(
4012                                       D->getPropertyAttributesAsWritten());
4013   ToProperty->setGetterName(Importer.Import(D->getGetterName()));
4014   ToProperty->setSetterName(Importer.Import(D->getSetterName()));
4015   ToProperty->setGetterMethodDecl(
4016      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getGetterMethodDecl())));
4017   ToProperty->setSetterMethodDecl(
4018      cast_or_null<ObjCMethodDecl>(Importer.Import(D->getSetterMethodDecl())));
4019   ToProperty->setPropertyIvarDecl(
4020        cast_or_null<ObjCIvarDecl>(Importer.Import(D->getPropertyIvarDecl())));
4021   return ToProperty;
4022 }
4023 
VisitObjCPropertyImplDecl(ObjCPropertyImplDecl * D)4024 Decl *ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4025   ObjCPropertyDecl *Property = cast_or_null<ObjCPropertyDecl>(
4026                                         Importer.Import(D->getPropertyDecl()));
4027   if (!Property)
4028     return nullptr;
4029 
4030   DeclContext *DC = Importer.ImportContext(D->getDeclContext());
4031   if (!DC)
4032     return nullptr;
4033 
4034   // Import the lexical declaration context.
4035   DeclContext *LexicalDC = DC;
4036   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4037     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4038     if (!LexicalDC)
4039       return nullptr;
4040   }
4041 
4042   ObjCImplDecl *InImpl = dyn_cast<ObjCImplDecl>(LexicalDC);
4043   if (!InImpl)
4044     return nullptr;
4045 
4046   // Import the ivar (for an @synthesize).
4047   ObjCIvarDecl *Ivar = nullptr;
4048   if (D->getPropertyIvarDecl()) {
4049     Ivar = cast_or_null<ObjCIvarDecl>(
4050                                     Importer.Import(D->getPropertyIvarDecl()));
4051     if (!Ivar)
4052       return nullptr;
4053   }
4054 
4055   ObjCPropertyImplDecl *ToImpl
4056     = InImpl->FindPropertyImplDecl(Property->getIdentifier());
4057   if (!ToImpl) {
4058     ToImpl = ObjCPropertyImplDecl::Create(Importer.getToContext(), DC,
4059                                           Importer.Import(D->getLocStart()),
4060                                           Importer.Import(D->getLocation()),
4061                                           Property,
4062                                           D->getPropertyImplementation(),
4063                                           Ivar,
4064                                   Importer.Import(D->getPropertyIvarDeclLoc()));
4065     ToImpl->setLexicalDeclContext(LexicalDC);
4066     Importer.Imported(D, ToImpl);
4067     LexicalDC->addDeclInternal(ToImpl);
4068   } else {
4069     // Check that we have the same kind of property implementation (@synthesize
4070     // vs. @dynamic).
4071     if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4072       Importer.ToDiag(ToImpl->getLocation(),
4073                       diag::err_odr_objc_property_impl_kind_inconsistent)
4074         << Property->getDeclName()
4075         << (ToImpl->getPropertyImplementation()
4076                                               == ObjCPropertyImplDecl::Dynamic);
4077       Importer.FromDiag(D->getLocation(),
4078                         diag::note_odr_objc_property_impl_kind)
4079         << D->getPropertyDecl()->getDeclName()
4080         << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4081       return nullptr;
4082     }
4083 
4084     // For @synthesize, check that we have the same
4085     if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4086         Ivar != ToImpl->getPropertyIvarDecl()) {
4087       Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4088                       diag::err_odr_objc_synthesize_ivar_inconsistent)
4089         << Property->getDeclName()
4090         << ToImpl->getPropertyIvarDecl()->getDeclName()
4091         << Ivar->getDeclName();
4092       Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4093                         diag::note_odr_objc_synthesize_ivar_here)
4094         << D->getPropertyIvarDecl()->getDeclName();
4095       return nullptr;
4096     }
4097 
4098     // Merge the existing implementation with the new implementation.
4099     Importer.Imported(D, ToImpl);
4100   }
4101 
4102   return ToImpl;
4103 }
4104 
VisitTemplateTypeParmDecl(TemplateTypeParmDecl * D)4105 Decl *ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4106   // For template arguments, we adopt the translation unit as our declaration
4107   // context. This context will be fixed when the actual template declaration
4108   // is created.
4109 
4110   // FIXME: Import default argument.
4111   return TemplateTypeParmDecl::Create(Importer.getToContext(),
4112                               Importer.getToContext().getTranslationUnitDecl(),
4113                                       Importer.Import(D->getLocStart()),
4114                                       Importer.Import(D->getLocation()),
4115                                       D->getDepth(),
4116                                       D->getIndex(),
4117                                       Importer.Import(D->getIdentifier()),
4118                                       D->wasDeclaredWithTypename(),
4119                                       D->isParameterPack());
4120 }
4121 
4122 Decl *
VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl * D)4123 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4124   // Import the name of this declaration.
4125   DeclarationName Name = Importer.Import(D->getDeclName());
4126   if (D->getDeclName() && !Name)
4127     return nullptr;
4128 
4129   // Import the location of this declaration.
4130   SourceLocation Loc = Importer.Import(D->getLocation());
4131 
4132   // Import the type of this declaration.
4133   QualType T = Importer.Import(D->getType());
4134   if (T.isNull())
4135     return nullptr;
4136 
4137   // Import type-source information.
4138   TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4139   if (D->getTypeSourceInfo() && !TInfo)
4140     return nullptr;
4141 
4142   // FIXME: Import default argument.
4143 
4144   return NonTypeTemplateParmDecl::Create(Importer.getToContext(),
4145                                Importer.getToContext().getTranslationUnitDecl(),
4146                                          Importer.Import(D->getInnerLocStart()),
4147                                          Loc, D->getDepth(), D->getPosition(),
4148                                          Name.getAsIdentifierInfo(),
4149                                          T, D->isParameterPack(), TInfo);
4150 }
4151 
4152 Decl *
VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl * D)4153 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4154   // Import the name of this declaration.
4155   DeclarationName Name = Importer.Import(D->getDeclName());
4156   if (D->getDeclName() && !Name)
4157     return nullptr;
4158 
4159   // Import the location of this declaration.
4160   SourceLocation Loc = Importer.Import(D->getLocation());
4161 
4162   // Import template parameters.
4163   TemplateParameterList *TemplateParams
4164     = ImportTemplateParameterList(D->getTemplateParameters());
4165   if (!TemplateParams)
4166     return nullptr;
4167 
4168   // FIXME: Import default argument.
4169 
4170   return TemplateTemplateParmDecl::Create(Importer.getToContext(),
4171                               Importer.getToContext().getTranslationUnitDecl(),
4172                                           Loc, D->getDepth(), D->getPosition(),
4173                                           D->isParameterPack(),
4174                                           Name.getAsIdentifierInfo(),
4175                                           TemplateParams);
4176 }
4177 
VisitClassTemplateDecl(ClassTemplateDecl * D)4178 Decl *ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4179   // If this record has a definition in the translation unit we're coming from,
4180   // but this particular declaration is not that definition, import the
4181   // definition and map to that.
4182   CXXRecordDecl *Definition
4183     = cast_or_null<CXXRecordDecl>(D->getTemplatedDecl()->getDefinition());
4184   if (Definition && Definition != D->getTemplatedDecl()) {
4185     Decl *ImportedDef
4186       = Importer.Import(Definition->getDescribedClassTemplate());
4187     if (!ImportedDef)
4188       return nullptr;
4189 
4190     return Importer.Imported(D, ImportedDef);
4191   }
4192 
4193   // Import the major distinguishing characteristics of this class template.
4194   DeclContext *DC, *LexicalDC;
4195   DeclarationName Name;
4196   SourceLocation Loc;
4197   NamedDecl *ToD;
4198   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4199     return nullptr;
4200   if (ToD)
4201     return ToD;
4202 
4203   // We may already have a template of the same name; try to find and match it.
4204   if (!DC->isFunctionOrMethod()) {
4205     SmallVector<NamedDecl *, 4> ConflictingDecls;
4206     SmallVector<NamedDecl *, 2> FoundDecls;
4207     DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4208     for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4209       if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4210         continue;
4211 
4212       Decl *Found = FoundDecls[I];
4213       if (ClassTemplateDecl *FoundTemplate
4214                                         = dyn_cast<ClassTemplateDecl>(Found)) {
4215         if (IsStructuralMatch(D, FoundTemplate)) {
4216           // The class templates structurally match; call it the same template.
4217           // FIXME: We may be filling in a forward declaration here. Handle
4218           // this case!
4219           Importer.Imported(D->getTemplatedDecl(),
4220                             FoundTemplate->getTemplatedDecl());
4221           return Importer.Imported(D, FoundTemplate);
4222         }
4223       }
4224 
4225       ConflictingDecls.push_back(FoundDecls[I]);
4226     }
4227 
4228     if (!ConflictingDecls.empty()) {
4229       Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4230                                          ConflictingDecls.data(),
4231                                          ConflictingDecls.size());
4232     }
4233 
4234     if (!Name)
4235       return nullptr;
4236   }
4237 
4238   CXXRecordDecl *DTemplated = D->getTemplatedDecl();
4239 
4240   // Create the declaration that is being templated.
4241   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4242   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4243   CXXRecordDecl *D2Templated = CXXRecordDecl::Create(Importer.getToContext(),
4244                                                      DTemplated->getTagKind(),
4245                                                      DC, StartLoc, IdLoc,
4246                                                    Name.getAsIdentifierInfo());
4247   D2Templated->setAccess(DTemplated->getAccess());
4248   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4249   D2Templated->setLexicalDeclContext(LexicalDC);
4250 
4251   // Create the class template declaration itself.
4252   TemplateParameterList *TemplateParams
4253     = ImportTemplateParameterList(D->getTemplateParameters());
4254   if (!TemplateParams)
4255     return nullptr;
4256 
4257   ClassTemplateDecl *D2 = ClassTemplateDecl::Create(Importer.getToContext(), DC,
4258                                                     Loc, Name, TemplateParams,
4259                                                     D2Templated,
4260                                                     /*PrevDecl=*/nullptr);
4261   D2Templated->setDescribedClassTemplate(D2);
4262 
4263   D2->setAccess(D->getAccess());
4264   D2->setLexicalDeclContext(LexicalDC);
4265   LexicalDC->addDeclInternal(D2);
4266 
4267   // Note the relationship between the class templates.
4268   Importer.Imported(D, D2);
4269   Importer.Imported(DTemplated, D2Templated);
4270 
4271   if (DTemplated->isCompleteDefinition() &&
4272       !D2Templated->isCompleteDefinition()) {
4273     // FIXME: Import definition!
4274   }
4275 
4276   return D2;
4277 }
4278 
VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl * D)4279 Decl *ASTNodeImporter::VisitClassTemplateSpecializationDecl(
4280                                           ClassTemplateSpecializationDecl *D) {
4281   // If this record has a definition in the translation unit we're coming from,
4282   // but this particular declaration is not that definition, import the
4283   // definition and map to that.
4284   TagDecl *Definition = D->getDefinition();
4285   if (Definition && Definition != D) {
4286     Decl *ImportedDef = Importer.Import(Definition);
4287     if (!ImportedDef)
4288       return nullptr;
4289 
4290     return Importer.Imported(D, ImportedDef);
4291   }
4292 
4293   ClassTemplateDecl *ClassTemplate
4294     = cast_or_null<ClassTemplateDecl>(Importer.Import(
4295                                                  D->getSpecializedTemplate()));
4296   if (!ClassTemplate)
4297     return nullptr;
4298 
4299   // Import the context of this declaration.
4300   DeclContext *DC = ClassTemplate->getDeclContext();
4301   if (!DC)
4302     return nullptr;
4303 
4304   DeclContext *LexicalDC = DC;
4305   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4306     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4307     if (!LexicalDC)
4308       return nullptr;
4309   }
4310 
4311   // Import the location of this declaration.
4312   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4313   SourceLocation IdLoc = Importer.Import(D->getLocation());
4314 
4315   // Import template arguments.
4316   SmallVector<TemplateArgument, 2> TemplateArgs;
4317   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4318                               D->getTemplateArgs().size(),
4319                               TemplateArgs))
4320     return nullptr;
4321 
4322   // Try to find an existing specialization with these template arguments.
4323   void *InsertPos = nullptr;
4324   ClassTemplateSpecializationDecl *D2
4325     = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
4326   if (D2) {
4327     // We already have a class template specialization with these template
4328     // arguments.
4329 
4330     // FIXME: Check for specialization vs. instantiation errors.
4331 
4332     if (RecordDecl *FoundDef = D2->getDefinition()) {
4333       if (!D->isCompleteDefinition() || IsStructuralMatch(D, FoundDef)) {
4334         // The record types structurally match, or the "from" translation
4335         // unit only had a forward declaration anyway; call it the same
4336         // function.
4337         return Importer.Imported(D, FoundDef);
4338       }
4339     }
4340   } else {
4341     // Create a new specialization.
4342     D2 = ClassTemplateSpecializationDecl::Create(Importer.getToContext(),
4343                                                  D->getTagKind(), DC,
4344                                                  StartLoc, IdLoc,
4345                                                  ClassTemplate,
4346                                                  TemplateArgs.data(),
4347                                                  TemplateArgs.size(),
4348                                                  /*PrevDecl=*/nullptr);
4349     D2->setSpecializationKind(D->getSpecializationKind());
4350 
4351     // Add this specialization to the class template.
4352     ClassTemplate->AddSpecialization(D2, InsertPos);
4353 
4354     // Import the qualifier, if any.
4355     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4356 
4357     // Add the specialization to this context.
4358     D2->setLexicalDeclContext(LexicalDC);
4359     LexicalDC->addDeclInternal(D2);
4360   }
4361   Importer.Imported(D, D2);
4362 
4363   if (D->isCompleteDefinition() && ImportDefinition(D, D2))
4364     return nullptr;
4365 
4366   return D2;
4367 }
4368 
VisitVarTemplateDecl(VarTemplateDecl * D)4369 Decl *ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
4370   // If this variable has a definition in the translation unit we're coming
4371   // from,
4372   // but this particular declaration is not that definition, import the
4373   // definition and map to that.
4374   VarDecl *Definition =
4375       cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
4376   if (Definition && Definition != D->getTemplatedDecl()) {
4377     Decl *ImportedDef = Importer.Import(Definition->getDescribedVarTemplate());
4378     if (!ImportedDef)
4379       return nullptr;
4380 
4381     return Importer.Imported(D, ImportedDef);
4382   }
4383 
4384   // Import the major distinguishing characteristics of this variable template.
4385   DeclContext *DC, *LexicalDC;
4386   DeclarationName Name;
4387   SourceLocation Loc;
4388   NamedDecl *ToD;
4389   if (ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4390     return nullptr;
4391   if (ToD)
4392     return ToD;
4393 
4394   // We may already have a template of the same name; try to find and match it.
4395   assert(!DC->isFunctionOrMethod() &&
4396          "Variable templates cannot be declared at function scope");
4397   SmallVector<NamedDecl *, 4> ConflictingDecls;
4398   SmallVector<NamedDecl *, 2> FoundDecls;
4399   DC->getRedeclContext()->localUncachedLookup(Name, FoundDecls);
4400   for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4401     if (!FoundDecls[I]->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4402       continue;
4403 
4404     Decl *Found = FoundDecls[I];
4405     if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
4406       if (IsStructuralMatch(D, FoundTemplate)) {
4407         // The variable templates structurally match; call it the same template.
4408         Importer.Imported(D->getTemplatedDecl(),
4409                           FoundTemplate->getTemplatedDecl());
4410         return Importer.Imported(D, FoundTemplate);
4411       }
4412     }
4413 
4414     ConflictingDecls.push_back(FoundDecls[I]);
4415   }
4416 
4417   if (!ConflictingDecls.empty()) {
4418     Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4419                                        ConflictingDecls.data(),
4420                                        ConflictingDecls.size());
4421   }
4422 
4423   if (!Name)
4424     return nullptr;
4425 
4426   VarDecl *DTemplated = D->getTemplatedDecl();
4427 
4428   // Import the type.
4429   QualType T = Importer.Import(DTemplated->getType());
4430   if (T.isNull())
4431     return nullptr;
4432 
4433   // Create the declaration that is being templated.
4434   SourceLocation StartLoc = Importer.Import(DTemplated->getLocStart());
4435   SourceLocation IdLoc = Importer.Import(DTemplated->getLocation());
4436   TypeSourceInfo *TInfo = Importer.Import(DTemplated->getTypeSourceInfo());
4437   VarDecl *D2Templated = VarDecl::Create(Importer.getToContext(), DC, StartLoc,
4438                                          IdLoc, Name.getAsIdentifierInfo(), T,
4439                                          TInfo, DTemplated->getStorageClass());
4440   D2Templated->setAccess(DTemplated->getAccess());
4441   D2Templated->setQualifierInfo(Importer.Import(DTemplated->getQualifierLoc()));
4442   D2Templated->setLexicalDeclContext(LexicalDC);
4443 
4444   // Importer.Imported(DTemplated, D2Templated);
4445   // LexicalDC->addDeclInternal(D2Templated);
4446 
4447   // Merge the initializer.
4448   if (ImportDefinition(DTemplated, D2Templated))
4449     return nullptr;
4450 
4451   // Create the variable template declaration itself.
4452   TemplateParameterList *TemplateParams =
4453       ImportTemplateParameterList(D->getTemplateParameters());
4454   if (!TemplateParams)
4455     return nullptr;
4456 
4457   VarTemplateDecl *D2 = VarTemplateDecl::Create(
4458       Importer.getToContext(), DC, Loc, Name, TemplateParams, D2Templated);
4459   D2Templated->setDescribedVarTemplate(D2);
4460 
4461   D2->setAccess(D->getAccess());
4462   D2->setLexicalDeclContext(LexicalDC);
4463   LexicalDC->addDeclInternal(D2);
4464 
4465   // Note the relationship between the variable templates.
4466   Importer.Imported(D, D2);
4467   Importer.Imported(DTemplated, D2Templated);
4468 
4469   if (DTemplated->isThisDeclarationADefinition() &&
4470       !D2Templated->isThisDeclarationADefinition()) {
4471     // FIXME: Import definition!
4472   }
4473 
4474   return D2;
4475 }
4476 
VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl * D)4477 Decl *ASTNodeImporter::VisitVarTemplateSpecializationDecl(
4478     VarTemplateSpecializationDecl *D) {
4479   // If this record has a definition in the translation unit we're coming from,
4480   // but this particular declaration is not that definition, import the
4481   // definition and map to that.
4482   VarDecl *Definition = D->getDefinition();
4483   if (Definition && Definition != D) {
4484     Decl *ImportedDef = Importer.Import(Definition);
4485     if (!ImportedDef)
4486       return nullptr;
4487 
4488     return Importer.Imported(D, ImportedDef);
4489   }
4490 
4491   VarTemplateDecl *VarTemplate = cast_or_null<VarTemplateDecl>(
4492       Importer.Import(D->getSpecializedTemplate()));
4493   if (!VarTemplate)
4494     return nullptr;
4495 
4496   // Import the context of this declaration.
4497   DeclContext *DC = VarTemplate->getDeclContext();
4498   if (!DC)
4499     return nullptr;
4500 
4501   DeclContext *LexicalDC = DC;
4502   if (D->getDeclContext() != D->getLexicalDeclContext()) {
4503     LexicalDC = Importer.ImportContext(D->getLexicalDeclContext());
4504     if (!LexicalDC)
4505       return nullptr;
4506   }
4507 
4508   // Import the location of this declaration.
4509   SourceLocation StartLoc = Importer.Import(D->getLocStart());
4510   SourceLocation IdLoc = Importer.Import(D->getLocation());
4511 
4512   // Import template arguments.
4513   SmallVector<TemplateArgument, 2> TemplateArgs;
4514   if (ImportTemplateArguments(D->getTemplateArgs().data(),
4515                               D->getTemplateArgs().size(), TemplateArgs))
4516     return nullptr;
4517 
4518   // Try to find an existing specialization with these template arguments.
4519   void *InsertPos = nullptr;
4520   VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
4521       TemplateArgs, InsertPos);
4522   if (D2) {
4523     // We already have a variable template specialization with these template
4524     // arguments.
4525 
4526     // FIXME: Check for specialization vs. instantiation errors.
4527 
4528     if (VarDecl *FoundDef = D2->getDefinition()) {
4529       if (!D->isThisDeclarationADefinition() ||
4530           IsStructuralMatch(D, FoundDef)) {
4531         // The record types structurally match, or the "from" translation
4532         // unit only had a forward declaration anyway; call it the same
4533         // variable.
4534         return Importer.Imported(D, FoundDef);
4535       }
4536     }
4537   } else {
4538 
4539     // Import the type.
4540     QualType T = Importer.Import(D->getType());
4541     if (T.isNull())
4542       return nullptr;
4543     TypeSourceInfo *TInfo = Importer.Import(D->getTypeSourceInfo());
4544 
4545     // Create a new specialization.
4546     D2 = VarTemplateSpecializationDecl::Create(
4547         Importer.getToContext(), DC, StartLoc, IdLoc, VarTemplate, T, TInfo,
4548         D->getStorageClass(), TemplateArgs.data(), TemplateArgs.size());
4549     D2->setSpecializationKind(D->getSpecializationKind());
4550     D2->setTemplateArgsInfo(D->getTemplateArgsInfo());
4551 
4552     // Add this specialization to the class template.
4553     VarTemplate->AddSpecialization(D2, InsertPos);
4554 
4555     // Import the qualifier, if any.
4556     D2->setQualifierInfo(Importer.Import(D->getQualifierLoc()));
4557 
4558     // Add the specialization to this context.
4559     D2->setLexicalDeclContext(LexicalDC);
4560     LexicalDC->addDeclInternal(D2);
4561   }
4562   Importer.Imported(D, D2);
4563 
4564   if (D->isThisDeclarationADefinition() && ImportDefinition(D, D2))
4565     return nullptr;
4566 
4567   return D2;
4568 }
4569 
4570 //----------------------------------------------------------------------------
4571 // Import Statements
4572 //----------------------------------------------------------------------------
4573 
ImportDeclGroup(DeclGroupRef DG)4574 DeclGroupRef ASTNodeImporter::ImportDeclGroup(DeclGroupRef DG) {
4575   if (DG.isNull())
4576     return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
4577   size_t NumDecls = DG.end() - DG.begin();
4578   SmallVector<Decl *, 1> ToDecls(NumDecls);
4579   auto &_Importer = this->Importer;
4580   std::transform(DG.begin(), DG.end(), ToDecls.begin(),
4581     [&_Importer](Decl *D) -> Decl * {
4582       return _Importer.Import(D);
4583     });
4584   return DeclGroupRef::Create(Importer.getToContext(),
4585                               ToDecls.begin(),
4586                               NumDecls);
4587 }
4588 
VisitStmt(Stmt * S)4589  Stmt *ASTNodeImporter::VisitStmt(Stmt *S) {
4590    Importer.FromDiag(S->getLocStart(), diag::err_unsupported_ast_node)
4591      << S->getStmtClassName();
4592    return nullptr;
4593  }
4594 
VisitDeclStmt(DeclStmt * S)4595 Stmt *ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
4596   DeclGroupRef ToDG = ImportDeclGroup(S->getDeclGroup());
4597   for (Decl *ToD : ToDG) {
4598     if (!ToD)
4599       return nullptr;
4600   }
4601   SourceLocation ToStartLoc = Importer.Import(S->getStartLoc());
4602   SourceLocation ToEndLoc = Importer.Import(S->getEndLoc());
4603   return new (Importer.getToContext()) DeclStmt(ToDG, ToStartLoc, ToEndLoc);
4604 }
4605 
VisitNullStmt(NullStmt * S)4606 Stmt *ASTNodeImporter::VisitNullStmt(NullStmt *S) {
4607   SourceLocation ToSemiLoc = Importer.Import(S->getSemiLoc());
4608   return new (Importer.getToContext()) NullStmt(ToSemiLoc,
4609                                                 S->hasLeadingEmptyMacro());
4610 }
4611 
VisitCompoundStmt(CompoundStmt * S)4612 Stmt *ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
4613   SmallVector<Stmt *, 4> ToStmts(S->size());
4614   auto &_Importer = this->Importer;
4615   std::transform(S->body_begin(), S->body_end(), ToStmts.begin(),
4616     [&_Importer](Stmt *CS) -> Stmt * {
4617       return _Importer.Import(CS);
4618     });
4619   for (Stmt *ToS : ToStmts) {
4620     if (!ToS)
4621       return nullptr;
4622   }
4623   SourceLocation ToLBraceLoc = Importer.Import(S->getLBracLoc());
4624   SourceLocation ToRBraceLoc = Importer.Import(S->getRBracLoc());
4625   return new (Importer.getToContext()) CompoundStmt(Importer.getToContext(),
4626                                                     ToStmts,
4627                                                     ToLBraceLoc, ToRBraceLoc);
4628 }
4629 
VisitCaseStmt(CaseStmt * S)4630 Stmt *ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
4631   Expr *ToLHS = Importer.Import(S->getLHS());
4632   if (!ToLHS)
4633     return nullptr;
4634   Expr *ToRHS = Importer.Import(S->getRHS());
4635   if (!ToRHS && S->getRHS())
4636     return nullptr;
4637   SourceLocation ToCaseLoc = Importer.Import(S->getCaseLoc());
4638   SourceLocation ToEllipsisLoc = Importer.Import(S->getEllipsisLoc());
4639   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4640   return new (Importer.getToContext()) CaseStmt(ToLHS, ToRHS,
4641                                                 ToCaseLoc, ToEllipsisLoc,
4642                                                 ToColonLoc);
4643 }
4644 
VisitDefaultStmt(DefaultStmt * S)4645 Stmt *ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
4646   SourceLocation ToDefaultLoc = Importer.Import(S->getDefaultLoc());
4647   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4648   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4649   if (!ToSubStmt && S->getSubStmt())
4650     return nullptr;
4651   return new (Importer.getToContext()) DefaultStmt(ToDefaultLoc, ToColonLoc,
4652                                                    ToSubStmt);
4653 }
4654 
VisitLabelStmt(LabelStmt * S)4655 Stmt *ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
4656   SourceLocation ToIdentLoc = Importer.Import(S->getIdentLoc());
4657   LabelDecl *ToLabelDecl =
4658     cast_or_null<LabelDecl>(Importer.Import(S->getDecl()));
4659   if (!ToLabelDecl && S->getDecl())
4660     return nullptr;
4661   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4662   if (!ToSubStmt && S->getSubStmt())
4663     return nullptr;
4664   return new (Importer.getToContext()) LabelStmt(ToIdentLoc, ToLabelDecl,
4665                                                  ToSubStmt);
4666 }
4667 
VisitAttributedStmt(AttributedStmt * S)4668 Stmt *ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
4669   SourceLocation ToAttrLoc = Importer.Import(S->getAttrLoc());
4670   ArrayRef<const Attr*> FromAttrs(S->getAttrs());
4671   SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
4672   ASTContext &_ToContext = Importer.getToContext();
4673   std::transform(FromAttrs.begin(), FromAttrs.end(), ToAttrs.begin(),
4674     [&_ToContext](const Attr *A) -> const Attr * {
4675       return A->clone(_ToContext);
4676     });
4677   for (const Attr *ToA : ToAttrs) {
4678     if (!ToA)
4679       return nullptr;
4680   }
4681   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
4682   if (!ToSubStmt && S->getSubStmt())
4683     return nullptr;
4684   return AttributedStmt::Create(Importer.getToContext(), ToAttrLoc,
4685                                 ToAttrs, ToSubStmt);
4686 }
4687 
VisitIfStmt(IfStmt * S)4688 Stmt *ASTNodeImporter::VisitIfStmt(IfStmt *S) {
4689   SourceLocation ToIfLoc = Importer.Import(S->getIfLoc());
4690   VarDecl *ToConditionVariable = nullptr;
4691   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4692     ToConditionVariable =
4693       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4694     if (!ToConditionVariable)
4695       return nullptr;
4696   }
4697   Expr *ToCondition = Importer.Import(S->getCond());
4698   if (!ToCondition && S->getCond())
4699     return nullptr;
4700   Stmt *ToThenStmt = Importer.Import(S->getThen());
4701   if (!ToThenStmt && S->getThen())
4702     return nullptr;
4703   SourceLocation ToElseLoc = Importer.Import(S->getElseLoc());
4704   Stmt *ToElseStmt = Importer.Import(S->getElse());
4705   if (!ToElseStmt && S->getElse())
4706     return nullptr;
4707   return new (Importer.getToContext()) IfStmt(Importer.getToContext(),
4708                                               ToIfLoc, ToConditionVariable,
4709                                               ToCondition, ToThenStmt,
4710                                               ToElseLoc, ToElseStmt);
4711 }
4712 
VisitSwitchStmt(SwitchStmt * S)4713 Stmt *ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
4714   VarDecl *ToConditionVariable = nullptr;
4715   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4716     ToConditionVariable =
4717       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4718     if (!ToConditionVariable)
4719       return nullptr;
4720   }
4721   Expr *ToCondition = Importer.Import(S->getCond());
4722   if (!ToCondition && S->getCond())
4723     return nullptr;
4724   SwitchStmt *ToStmt = new (Importer.getToContext()) SwitchStmt(
4725                          Importer.getToContext(), ToConditionVariable,
4726                          ToCondition);
4727   Stmt *ToBody = Importer.Import(S->getBody());
4728   if (!ToBody && S->getBody())
4729     return nullptr;
4730   ToStmt->setBody(ToBody);
4731   ToStmt->setSwitchLoc(Importer.Import(S->getSwitchLoc()));
4732   // Now we have to re-chain the cases.
4733   SwitchCase *LastChainedSwitchCase = nullptr;
4734   for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
4735        SC = SC->getNextSwitchCase()) {
4736     SwitchCase *ToSC = dyn_cast_or_null<SwitchCase>(Importer.Import(SC));
4737     if (!ToSC)
4738       return nullptr;
4739     if (LastChainedSwitchCase)
4740       LastChainedSwitchCase->setNextSwitchCase(ToSC);
4741     else
4742       ToStmt->setSwitchCaseList(ToSC);
4743     LastChainedSwitchCase = ToSC;
4744   }
4745   return ToStmt;
4746 }
4747 
VisitWhileStmt(WhileStmt * S)4748 Stmt *ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
4749   VarDecl *ToConditionVariable = nullptr;
4750   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4751     ToConditionVariable =
4752       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4753     if (!ToConditionVariable)
4754       return nullptr;
4755   }
4756   Expr *ToCondition = Importer.Import(S->getCond());
4757   if (!ToCondition && S->getCond())
4758     return nullptr;
4759   Stmt *ToBody = Importer.Import(S->getBody());
4760   if (!ToBody && S->getBody())
4761     return nullptr;
4762   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4763   return new (Importer.getToContext()) WhileStmt(Importer.getToContext(),
4764                                                  ToConditionVariable,
4765                                                  ToCondition, ToBody,
4766                                                  ToWhileLoc);
4767 }
4768 
VisitDoStmt(DoStmt * S)4769 Stmt *ASTNodeImporter::VisitDoStmt(DoStmt *S) {
4770   Stmt *ToBody = Importer.Import(S->getBody());
4771   if (!ToBody && S->getBody())
4772     return nullptr;
4773   Expr *ToCondition = Importer.Import(S->getCond());
4774   if (!ToCondition && S->getCond())
4775     return nullptr;
4776   SourceLocation ToDoLoc = Importer.Import(S->getDoLoc());
4777   SourceLocation ToWhileLoc = Importer.Import(S->getWhileLoc());
4778   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4779   return new (Importer.getToContext()) DoStmt(ToBody, ToCondition,
4780                                               ToDoLoc, ToWhileLoc,
4781                                               ToRParenLoc);
4782 }
4783 
VisitForStmt(ForStmt * S)4784 Stmt *ASTNodeImporter::VisitForStmt(ForStmt *S) {
4785   Stmt *ToInit = Importer.Import(S->getInit());
4786   if (!ToInit && S->getInit())
4787     return nullptr;
4788   Expr *ToCondition = Importer.Import(S->getCond());
4789   if (!ToCondition && S->getCond())
4790     return nullptr;
4791   VarDecl *ToConditionVariable = nullptr;
4792   if (VarDecl *FromConditionVariable = S->getConditionVariable()) {
4793     ToConditionVariable =
4794       dyn_cast_or_null<VarDecl>(Importer.Import(FromConditionVariable));
4795     if (!ToConditionVariable)
4796       return nullptr;
4797   }
4798   Expr *ToInc = Importer.Import(S->getInc());
4799   if (!ToInc && S->getInc())
4800     return nullptr;
4801   Stmt *ToBody = Importer.Import(S->getBody());
4802   if (!ToBody && S->getBody())
4803     return nullptr;
4804   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4805   SourceLocation ToLParenLoc = Importer.Import(S->getLParenLoc());
4806   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4807   return new (Importer.getToContext()) ForStmt(Importer.getToContext(),
4808                                                ToInit, ToCondition,
4809                                                ToConditionVariable,
4810                                                ToInc, ToBody,
4811                                                ToForLoc, ToLParenLoc,
4812                                                ToRParenLoc);
4813 }
4814 
VisitGotoStmt(GotoStmt * S)4815 Stmt *ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
4816   LabelDecl *ToLabel = nullptr;
4817   if (LabelDecl *FromLabel = S->getLabel()) {
4818     ToLabel = dyn_cast_or_null<LabelDecl>(Importer.Import(FromLabel));
4819     if (!ToLabel)
4820       return nullptr;
4821   }
4822   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4823   SourceLocation ToLabelLoc = Importer.Import(S->getLabelLoc());
4824   return new (Importer.getToContext()) GotoStmt(ToLabel,
4825                                                 ToGotoLoc, ToLabelLoc);
4826 }
4827 
VisitIndirectGotoStmt(IndirectGotoStmt * S)4828 Stmt *ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
4829   SourceLocation ToGotoLoc = Importer.Import(S->getGotoLoc());
4830   SourceLocation ToStarLoc = Importer.Import(S->getStarLoc());
4831   Expr *ToTarget = Importer.Import(S->getTarget());
4832   if (!ToTarget && S->getTarget())
4833     return nullptr;
4834   return new (Importer.getToContext()) IndirectGotoStmt(ToGotoLoc, ToStarLoc,
4835                                                         ToTarget);
4836 }
4837 
VisitContinueStmt(ContinueStmt * S)4838 Stmt *ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
4839   SourceLocation ToContinueLoc = Importer.Import(S->getContinueLoc());
4840   return new (Importer.getToContext()) ContinueStmt(ToContinueLoc);
4841 }
4842 
VisitBreakStmt(BreakStmt * S)4843 Stmt *ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
4844   SourceLocation ToBreakLoc = Importer.Import(S->getBreakLoc());
4845   return new (Importer.getToContext()) BreakStmt(ToBreakLoc);
4846 }
4847 
VisitReturnStmt(ReturnStmt * S)4848 Stmt *ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
4849   SourceLocation ToRetLoc = Importer.Import(S->getReturnLoc());
4850   Expr *ToRetExpr = Importer.Import(S->getRetValue());
4851   if (!ToRetExpr && S->getRetValue())
4852     return nullptr;
4853   VarDecl *NRVOCandidate = const_cast<VarDecl*>(S->getNRVOCandidate());
4854   VarDecl *ToNRVOCandidate = cast_or_null<VarDecl>(Importer.Import(NRVOCandidate));
4855   if (!ToNRVOCandidate && NRVOCandidate)
4856     return nullptr;
4857   return new (Importer.getToContext()) ReturnStmt(ToRetLoc, ToRetExpr,
4858                                                   ToNRVOCandidate);
4859 }
4860 
VisitCXXCatchStmt(CXXCatchStmt * S)4861 Stmt *ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
4862   SourceLocation ToCatchLoc = Importer.Import(S->getCatchLoc());
4863   VarDecl *ToExceptionDecl = nullptr;
4864   if (VarDecl *FromExceptionDecl = S->getExceptionDecl()) {
4865     ToExceptionDecl =
4866       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4867     if (!ToExceptionDecl)
4868       return nullptr;
4869   }
4870   Stmt *ToHandlerBlock = Importer.Import(S->getHandlerBlock());
4871   if (!ToHandlerBlock && S->getHandlerBlock())
4872     return nullptr;
4873   return new (Importer.getToContext()) CXXCatchStmt(ToCatchLoc,
4874                                                     ToExceptionDecl,
4875                                                     ToHandlerBlock);
4876 }
4877 
VisitCXXTryStmt(CXXTryStmt * S)4878 Stmt *ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
4879   SourceLocation ToTryLoc = Importer.Import(S->getTryLoc());
4880   Stmt *ToTryBlock = Importer.Import(S->getTryBlock());
4881   if (!ToTryBlock && S->getTryBlock())
4882     return nullptr;
4883   SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
4884   for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
4885     CXXCatchStmt *FromHandler = S->getHandler(HI);
4886     if (Stmt *ToHandler = Importer.Import(FromHandler))
4887       ToHandlers[HI] = ToHandler;
4888     else
4889       return nullptr;
4890   }
4891   return CXXTryStmt::Create(Importer.getToContext(), ToTryLoc, ToTryBlock,
4892                             ToHandlers);
4893 }
4894 
VisitCXXForRangeStmt(CXXForRangeStmt * S)4895 Stmt *ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
4896   DeclStmt *ToRange =
4897     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getRangeStmt()));
4898   if (!ToRange && S->getRangeStmt())
4899     return nullptr;
4900   DeclStmt *ToBeginEnd =
4901     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getBeginEndStmt()));
4902   if (!ToBeginEnd && S->getBeginEndStmt())
4903     return nullptr;
4904   Expr *ToCond = Importer.Import(S->getCond());
4905   if (!ToCond && S->getCond())
4906     return nullptr;
4907   Expr *ToInc = Importer.Import(S->getInc());
4908   if (!ToInc && S->getInc())
4909     return nullptr;
4910   DeclStmt *ToLoopVar =
4911     dyn_cast_or_null<DeclStmt>(Importer.Import(S->getLoopVarStmt()));
4912   if (!ToLoopVar && S->getLoopVarStmt())
4913     return nullptr;
4914   Stmt *ToBody = Importer.Import(S->getBody());
4915   if (!ToBody && S->getBody())
4916     return nullptr;
4917   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4918   SourceLocation ToCoawaitLoc = Importer.Import(S->getCoawaitLoc());
4919   SourceLocation ToColonLoc = Importer.Import(S->getColonLoc());
4920   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4921   return new (Importer.getToContext()) CXXForRangeStmt(ToRange, ToBeginEnd,
4922                                                        ToCond, ToInc,
4923                                                        ToLoopVar, ToBody,
4924                                                        ToForLoc, ToCoawaitLoc,
4925                                                        ToColonLoc, ToRParenLoc);
4926 }
4927 
VisitObjCForCollectionStmt(ObjCForCollectionStmt * S)4928 Stmt *ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
4929   Stmt *ToElem = Importer.Import(S->getElement());
4930   if (!ToElem && S->getElement())
4931     return nullptr;
4932   Expr *ToCollect = Importer.Import(S->getCollection());
4933   if (!ToCollect && S->getCollection())
4934     return nullptr;
4935   Stmt *ToBody = Importer.Import(S->getBody());
4936   if (!ToBody && S->getBody())
4937     return nullptr;
4938   SourceLocation ToForLoc = Importer.Import(S->getForLoc());
4939   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4940   return new (Importer.getToContext()) ObjCForCollectionStmt(ToElem,
4941                                                              ToCollect,
4942                                                              ToBody, ToForLoc,
4943                                                              ToRParenLoc);
4944 }
4945 
VisitObjCAtCatchStmt(ObjCAtCatchStmt * S)4946 Stmt *ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
4947   SourceLocation ToAtCatchLoc = Importer.Import(S->getAtCatchLoc());
4948   SourceLocation ToRParenLoc = Importer.Import(S->getRParenLoc());
4949   VarDecl *ToExceptionDecl = nullptr;
4950   if (VarDecl *FromExceptionDecl = S->getCatchParamDecl()) {
4951     ToExceptionDecl =
4952       dyn_cast_or_null<VarDecl>(Importer.Import(FromExceptionDecl));
4953     if (!ToExceptionDecl)
4954       return nullptr;
4955   }
4956   Stmt *ToBody = Importer.Import(S->getCatchBody());
4957   if (!ToBody && S->getCatchBody())
4958     return nullptr;
4959   return new (Importer.getToContext()) ObjCAtCatchStmt(ToAtCatchLoc,
4960                                                        ToRParenLoc,
4961                                                        ToExceptionDecl,
4962                                                        ToBody);
4963 }
4964 
VisitObjCAtFinallyStmt(ObjCAtFinallyStmt * S)4965 Stmt *ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
4966   SourceLocation ToAtFinallyLoc = Importer.Import(S->getAtFinallyLoc());
4967   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyBody());
4968   if (!ToAtFinallyStmt && S->getFinallyBody())
4969     return nullptr;
4970   return new (Importer.getToContext()) ObjCAtFinallyStmt(ToAtFinallyLoc,
4971                                                          ToAtFinallyStmt);
4972 }
4973 
VisitObjCAtTryStmt(ObjCAtTryStmt * S)4974 Stmt *ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
4975   SourceLocation ToAtTryLoc = Importer.Import(S->getAtTryLoc());
4976   Stmt *ToAtTryStmt = Importer.Import(S->getTryBody());
4977   if (!ToAtTryStmt && S->getTryBody())
4978     return nullptr;
4979   SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
4980   for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
4981     ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
4982     if (Stmt *ToCatchStmt = Importer.Import(FromCatchStmt))
4983       ToCatchStmts[CI] = ToCatchStmt;
4984     else
4985       return nullptr;
4986   }
4987   Stmt *ToAtFinallyStmt = Importer.Import(S->getFinallyStmt());
4988   if (!ToAtFinallyStmt && S->getFinallyStmt())
4989     return nullptr;
4990   return ObjCAtTryStmt::Create(Importer.getToContext(),
4991                                ToAtTryLoc, ToAtTryStmt,
4992                                ToCatchStmts.begin(), ToCatchStmts.size(),
4993                                ToAtFinallyStmt);
4994 }
4995 
VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt * S)4996 Stmt *ASTNodeImporter::VisitObjCAtSynchronizedStmt
4997   (ObjCAtSynchronizedStmt *S) {
4998   SourceLocation ToAtSynchronizedLoc =
4999     Importer.Import(S->getAtSynchronizedLoc());
5000   Expr *ToSynchExpr = Importer.Import(S->getSynchExpr());
5001   if (!ToSynchExpr && S->getSynchExpr())
5002     return nullptr;
5003   Stmt *ToSynchBody = Importer.Import(S->getSynchBody());
5004   if (!ToSynchBody && S->getSynchBody())
5005     return nullptr;
5006   return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
5007     ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
5008 }
5009 
VisitObjCAtThrowStmt(ObjCAtThrowStmt * S)5010 Stmt *ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
5011   SourceLocation ToAtThrowLoc = Importer.Import(S->getThrowLoc());
5012   Expr *ToThrow = Importer.Import(S->getThrowExpr());
5013   if (!ToThrow && S->getThrowExpr())
5014     return nullptr;
5015   return new (Importer.getToContext()) ObjCAtThrowStmt(ToAtThrowLoc, ToThrow);
5016 }
5017 
VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt * S)5018 Stmt *ASTNodeImporter::VisitObjCAutoreleasePoolStmt
5019   (ObjCAutoreleasePoolStmt *S) {
5020   SourceLocation ToAtLoc = Importer.Import(S->getAtLoc());
5021   Stmt *ToSubStmt = Importer.Import(S->getSubStmt());
5022   if (!ToSubStmt && S->getSubStmt())
5023     return nullptr;
5024   return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(ToAtLoc,
5025                                                                ToSubStmt);
5026 }
5027 
5028 //----------------------------------------------------------------------------
5029 // Import Expressions
5030 //----------------------------------------------------------------------------
VisitExpr(Expr * E)5031 Expr *ASTNodeImporter::VisitExpr(Expr *E) {
5032   Importer.FromDiag(E->getLocStart(), diag::err_unsupported_ast_node)
5033     << E->getStmtClassName();
5034   return nullptr;
5035 }
5036 
VisitDeclRefExpr(DeclRefExpr * E)5037 Expr *ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
5038   ValueDecl *ToD = cast_or_null<ValueDecl>(Importer.Import(E->getDecl()));
5039   if (!ToD)
5040     return nullptr;
5041 
5042   NamedDecl *FoundD = nullptr;
5043   if (E->getDecl() != E->getFoundDecl()) {
5044     FoundD = cast_or_null<NamedDecl>(Importer.Import(E->getFoundDecl()));
5045     if (!FoundD)
5046       return nullptr;
5047   }
5048 
5049   QualType T = Importer.Import(E->getType());
5050   if (T.isNull())
5051     return nullptr;
5052 
5053   DeclRefExpr *DRE = DeclRefExpr::Create(Importer.getToContext(),
5054                                          Importer.Import(E->getQualifierLoc()),
5055                                    Importer.Import(E->getTemplateKeywordLoc()),
5056                                          ToD,
5057                                         E->refersToEnclosingVariableOrCapture(),
5058                                          Importer.Import(E->getLocation()),
5059                                          T, E->getValueKind(),
5060                                          FoundD,
5061                                          /*FIXME:TemplateArgs=*/nullptr);
5062   if (E->hadMultipleCandidates())
5063     DRE->setHadMultipleCandidates(true);
5064   return DRE;
5065 }
5066 
VisitIntegerLiteral(IntegerLiteral * E)5067 Expr *ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
5068   QualType T = Importer.Import(E->getType());
5069   if (T.isNull())
5070     return nullptr;
5071 
5072   return IntegerLiteral::Create(Importer.getToContext(),
5073                                 E->getValue(), T,
5074                                 Importer.Import(E->getLocation()));
5075 }
5076 
VisitCharacterLiteral(CharacterLiteral * E)5077 Expr *ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
5078   QualType T = Importer.Import(E->getType());
5079   if (T.isNull())
5080     return nullptr;
5081 
5082   return new (Importer.getToContext()) CharacterLiteral(E->getValue(),
5083                                                         E->getKind(), T,
5084                                           Importer.Import(E->getLocation()));
5085 }
5086 
VisitParenExpr(ParenExpr * E)5087 Expr *ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
5088   Expr *SubExpr = Importer.Import(E->getSubExpr());
5089   if (!SubExpr)
5090     return nullptr;
5091 
5092   return new (Importer.getToContext())
5093                                   ParenExpr(Importer.Import(E->getLParen()),
5094                                             Importer.Import(E->getRParen()),
5095                                             SubExpr);
5096 }
5097 
VisitUnaryOperator(UnaryOperator * E)5098 Expr *ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) {
5099   QualType T = Importer.Import(E->getType());
5100   if (T.isNull())
5101     return nullptr;
5102 
5103   Expr *SubExpr = Importer.Import(E->getSubExpr());
5104   if (!SubExpr)
5105     return nullptr;
5106 
5107   return new (Importer.getToContext()) UnaryOperator(SubExpr, E->getOpcode(),
5108                                                      T, E->getValueKind(),
5109                                                      E->getObjectKind(),
5110                                          Importer.Import(E->getOperatorLoc()));
5111 }
5112 
VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr * E)5113 Expr *ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(
5114                                             UnaryExprOrTypeTraitExpr *E) {
5115   QualType ResultType = Importer.Import(E->getType());
5116 
5117   if (E->isArgumentType()) {
5118     TypeSourceInfo *TInfo = Importer.Import(E->getArgumentTypeInfo());
5119     if (!TInfo)
5120       return nullptr;
5121 
5122     return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5123                                            TInfo, ResultType,
5124                                            Importer.Import(E->getOperatorLoc()),
5125                                            Importer.Import(E->getRParenLoc()));
5126   }
5127 
5128   Expr *SubExpr = Importer.Import(E->getArgumentExpr());
5129   if (!SubExpr)
5130     return nullptr;
5131 
5132   return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(E->getKind(),
5133                                           SubExpr, ResultType,
5134                                           Importer.Import(E->getOperatorLoc()),
5135                                           Importer.Import(E->getRParenLoc()));
5136 }
5137 
VisitBinaryOperator(BinaryOperator * E)5138 Expr *ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) {
5139   QualType T = Importer.Import(E->getType());
5140   if (T.isNull())
5141     return nullptr;
5142 
5143   Expr *LHS = Importer.Import(E->getLHS());
5144   if (!LHS)
5145     return nullptr;
5146 
5147   Expr *RHS = Importer.Import(E->getRHS());
5148   if (!RHS)
5149     return nullptr;
5150 
5151   return new (Importer.getToContext()) BinaryOperator(LHS, RHS, E->getOpcode(),
5152                                                       T, E->getValueKind(),
5153                                                       E->getObjectKind(),
5154                                            Importer.Import(E->getOperatorLoc()),
5155                                                       E->isFPContractable());
5156 }
5157 
VisitCompoundAssignOperator(CompoundAssignOperator * E)5158 Expr *ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) {
5159   QualType T = Importer.Import(E->getType());
5160   if (T.isNull())
5161     return nullptr;
5162 
5163   QualType CompLHSType = Importer.Import(E->getComputationLHSType());
5164   if (CompLHSType.isNull())
5165     return nullptr;
5166 
5167   QualType CompResultType = Importer.Import(E->getComputationResultType());
5168   if (CompResultType.isNull())
5169     return nullptr;
5170 
5171   Expr *LHS = Importer.Import(E->getLHS());
5172   if (!LHS)
5173     return nullptr;
5174 
5175   Expr *RHS = Importer.Import(E->getRHS());
5176   if (!RHS)
5177     return nullptr;
5178 
5179   return new (Importer.getToContext())
5180                         CompoundAssignOperator(LHS, RHS, E->getOpcode(),
5181                                                T, E->getValueKind(),
5182                                                E->getObjectKind(),
5183                                                CompLHSType, CompResultType,
5184                                            Importer.Import(E->getOperatorLoc()),
5185                                                E->isFPContractable());
5186 }
5187 
ImportCastPath(CastExpr * E,CXXCastPath & Path)5188 static bool ImportCastPath(CastExpr *E, CXXCastPath &Path) {
5189   if (E->path_empty()) return false;
5190 
5191   // TODO: import cast paths
5192   return true;
5193 }
5194 
VisitImplicitCastExpr(ImplicitCastExpr * E)5195 Expr *ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) {
5196   QualType T = Importer.Import(E->getType());
5197   if (T.isNull())
5198     return nullptr;
5199 
5200   Expr *SubExpr = Importer.Import(E->getSubExpr());
5201   if (!SubExpr)
5202     return nullptr;
5203 
5204   CXXCastPath BasePath;
5205   if (ImportCastPath(E, BasePath))
5206     return nullptr;
5207 
5208   return ImplicitCastExpr::Create(Importer.getToContext(), T, E->getCastKind(),
5209                                   SubExpr, &BasePath, E->getValueKind());
5210 }
5211 
VisitCStyleCastExpr(CStyleCastExpr * E)5212 Expr *ASTNodeImporter::VisitCStyleCastExpr(CStyleCastExpr *E) {
5213   QualType T = Importer.Import(E->getType());
5214   if (T.isNull())
5215     return nullptr;
5216 
5217   Expr *SubExpr = Importer.Import(E->getSubExpr());
5218   if (!SubExpr)
5219     return nullptr;
5220 
5221   TypeSourceInfo *TInfo = Importer.Import(E->getTypeInfoAsWritten());
5222   if (!TInfo && E->getTypeInfoAsWritten())
5223     return nullptr;
5224 
5225   CXXCastPath BasePath;
5226   if (ImportCastPath(E, BasePath))
5227     return nullptr;
5228 
5229   return CStyleCastExpr::Create(Importer.getToContext(), T,
5230                                 E->getValueKind(), E->getCastKind(),
5231                                 SubExpr, &BasePath, TInfo,
5232                                 Importer.Import(E->getLParenLoc()),
5233                                 Importer.Import(E->getRParenLoc()));
5234 }
5235 
VisitCXXConstructExpr(CXXConstructExpr * E)5236 Expr *ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) {
5237   QualType T = Importer.Import(E->getType());
5238   if (T.isNull())
5239     return nullptr;
5240 
5241   CXXConstructorDecl *ToCCD =
5242     dyn_cast<CXXConstructorDecl>(Importer.Import(E->getConstructor()));
5243   if (!ToCCD && E->getConstructor())
5244     return nullptr;
5245 
5246   size_t NumArgs = E->getNumArgs();
5247   SmallVector<Expr *, 1> ToArgs(NumArgs);
5248   ASTImporter &_Importer = Importer;
5249   std::transform(E->arg_begin(), E->arg_end(), ToArgs.begin(),
5250     [&_Importer](Expr *AE) -> Expr * {
5251       return _Importer.Import(AE);
5252     });
5253   for (Expr *ToA : ToArgs) {
5254     if (!ToA)
5255       return nullptr;
5256   }
5257 
5258   return CXXConstructExpr::Create(Importer.getToContext(), T,
5259                                   Importer.Import(E->getLocation()),
5260                                   ToCCD, E->isElidable(),
5261                                   ToArgs, E->hadMultipleCandidates(),
5262                                   E->isListInitialization(),
5263                                   E->isStdInitListInitialization(),
5264                                   E->requiresZeroInitialization(),
5265                                   E->getConstructionKind(),
5266                                   Importer.Import(E->getParenOrBraceRange()));
5267 }
5268 
VisitMemberExpr(MemberExpr * E)5269 Expr *ASTNodeImporter::VisitMemberExpr(MemberExpr *E) {
5270   QualType T = Importer.Import(E->getType());
5271   if (T.isNull())
5272     return nullptr;
5273 
5274   Expr *ToBase = Importer.Import(E->getBase());
5275   if (!ToBase && E->getBase())
5276     return nullptr;
5277 
5278   ValueDecl *ToMember = dyn_cast<ValueDecl>(Importer.Import(E->getMemberDecl()));
5279   if (!ToMember && E->getMemberDecl())
5280     return nullptr;
5281 
5282   DeclAccessPair ToFoundDecl = DeclAccessPair::make(
5283     dyn_cast<NamedDecl>(Importer.Import(E->getFoundDecl().getDecl())),
5284     E->getFoundDecl().getAccess());
5285 
5286   DeclarationNameInfo ToMemberNameInfo(
5287     Importer.Import(E->getMemberNameInfo().getName()),
5288     Importer.Import(E->getMemberNameInfo().getLoc()));
5289 
5290   if (E->hasExplicitTemplateArgs()) {
5291     return nullptr; // FIXME: handle template arguments
5292   }
5293 
5294   return MemberExpr::Create(Importer.getToContext(), ToBase,
5295                             E->isArrow(),
5296                             Importer.Import(E->getOperatorLoc()),
5297                             Importer.Import(E->getQualifierLoc()),
5298                             Importer.Import(E->getTemplateKeywordLoc()),
5299                             ToMember, ToFoundDecl, ToMemberNameInfo,
5300                             nullptr, T, E->getValueKind(),
5301                             E->getObjectKind());
5302 }
5303 
VisitCallExpr(CallExpr * E)5304 Expr *ASTNodeImporter::VisitCallExpr(CallExpr *E) {
5305   QualType T = Importer.Import(E->getType());
5306   if (T.isNull())
5307     return nullptr;
5308 
5309   Expr *ToCallee = Importer.Import(E->getCallee());
5310   if (!ToCallee && E->getCallee())
5311     return nullptr;
5312 
5313   unsigned NumArgs = E->getNumArgs();
5314 
5315   llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
5316 
5317   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai) {
5318     Expr *FromArg = E->getArg(ai);
5319     Expr *ToArg = Importer.Import(FromArg);
5320     if (!ToArg)
5321       return nullptr;
5322     ToArgs[ai] = ToArg;
5323   }
5324 
5325   Expr **ToArgs_Copied = new (Importer.getToContext())
5326     Expr*[NumArgs];
5327 
5328   for (unsigned ai = 0, ae = NumArgs; ai != ae; ++ai)
5329     ToArgs_Copied[ai] = ToArgs[ai];
5330 
5331   return new (Importer.getToContext())
5332     CallExpr(Importer.getToContext(), ToCallee,
5333              llvm::makeArrayRef(ToArgs_Copied, NumArgs), T, E->getValueKind(),
5334              Importer.Import(E->getRParenLoc()));
5335 }
5336 
ASTImporter(ASTContext & ToContext,FileManager & ToFileManager,ASTContext & FromContext,FileManager & FromFileManager,bool MinimalImport)5337 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager,
5338                          ASTContext &FromContext, FileManager &FromFileManager,
5339                          bool MinimalImport)
5340   : ToContext(ToContext), FromContext(FromContext),
5341     ToFileManager(ToFileManager), FromFileManager(FromFileManager),
5342     Minimal(MinimalImport), LastDiagFromFrom(false)
5343 {
5344   ImportedDecls[FromContext.getTranslationUnitDecl()]
5345     = ToContext.getTranslationUnitDecl();
5346 }
5347 
~ASTImporter()5348 ASTImporter::~ASTImporter() { }
5349 
Import(QualType FromT)5350 QualType ASTImporter::Import(QualType FromT) {
5351   if (FromT.isNull())
5352     return QualType();
5353 
5354   const Type *fromTy = FromT.getTypePtr();
5355 
5356   // Check whether we've already imported this type.
5357   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5358     = ImportedTypes.find(fromTy);
5359   if (Pos != ImportedTypes.end())
5360     return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers());
5361 
5362   // Import the type
5363   ASTNodeImporter Importer(*this);
5364   QualType ToT = Importer.Visit(fromTy);
5365   if (ToT.isNull())
5366     return ToT;
5367 
5368   // Record the imported type.
5369   ImportedTypes[fromTy] = ToT.getTypePtr();
5370 
5371   return ToContext.getQualifiedType(ToT, FromT.getLocalQualifiers());
5372 }
5373 
Import(TypeSourceInfo * FromTSI)5374 TypeSourceInfo *ASTImporter::Import(TypeSourceInfo *FromTSI) {
5375   if (!FromTSI)
5376     return FromTSI;
5377 
5378   // FIXME: For now we just create a "trivial" type source info based
5379   // on the type and a single location. Implement a real version of this.
5380   QualType T = Import(FromTSI->getType());
5381   if (T.isNull())
5382     return nullptr;
5383 
5384   return ToContext.getTrivialTypeSourceInfo(T,
5385            Import(FromTSI->getTypeLoc().getLocStart()));
5386 }
5387 
GetAlreadyImportedOrNull(Decl * FromD)5388 Decl *ASTImporter::GetAlreadyImportedOrNull(Decl *FromD) {
5389   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5390   if (Pos != ImportedDecls.end()) {
5391     Decl *ToD = Pos->second;
5392     ASTNodeImporter(*this).ImportDefinitionIfNeeded(FromD, ToD);
5393     return ToD;
5394   } else {
5395     return nullptr;
5396   }
5397 }
5398 
Import(Decl * FromD)5399 Decl *ASTImporter::Import(Decl *FromD) {
5400   if (!FromD)
5401     return nullptr;
5402 
5403   ASTNodeImporter Importer(*this);
5404 
5405   // Check whether we've already imported this declaration.
5406   llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(FromD);
5407   if (Pos != ImportedDecls.end()) {
5408     Decl *ToD = Pos->second;
5409     Importer.ImportDefinitionIfNeeded(FromD, ToD);
5410     return ToD;
5411   }
5412 
5413   // Import the type
5414   Decl *ToD = Importer.Visit(FromD);
5415   if (!ToD)
5416     return nullptr;
5417 
5418   // Record the imported declaration.
5419   ImportedDecls[FromD] = ToD;
5420 
5421   if (TagDecl *FromTag = dyn_cast<TagDecl>(FromD)) {
5422     // Keep track of anonymous tags that have an associated typedef.
5423     if (FromTag->getTypedefNameForAnonDecl())
5424       AnonTagsWithPendingTypedefs.push_back(FromTag);
5425   } else if (TypedefNameDecl *FromTypedef = dyn_cast<TypedefNameDecl>(FromD)) {
5426     // When we've finished transforming a typedef, see whether it was the
5427     // typedef for an anonymous tag.
5428     for (SmallVectorImpl<TagDecl *>::iterator
5429                FromTag = AnonTagsWithPendingTypedefs.begin(),
5430             FromTagEnd = AnonTagsWithPendingTypedefs.end();
5431          FromTag != FromTagEnd; ++FromTag) {
5432       if ((*FromTag)->getTypedefNameForAnonDecl() == FromTypedef) {
5433         if (TagDecl *ToTag = cast_or_null<TagDecl>(Import(*FromTag))) {
5434           // We found the typedef for an anonymous tag; link them.
5435           ToTag->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToD));
5436           AnonTagsWithPendingTypedefs.erase(FromTag);
5437           break;
5438         }
5439       }
5440     }
5441   }
5442 
5443   return ToD;
5444 }
5445 
ImportContext(DeclContext * FromDC)5446 DeclContext *ASTImporter::ImportContext(DeclContext *FromDC) {
5447   if (!FromDC)
5448     return FromDC;
5449 
5450   DeclContext *ToDC = cast_or_null<DeclContext>(Import(cast<Decl>(FromDC)));
5451   if (!ToDC)
5452     return nullptr;
5453 
5454   // When we're using a record/enum/Objective-C class/protocol as a context, we
5455   // need it to have a definition.
5456   if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
5457     RecordDecl *FromRecord = cast<RecordDecl>(FromDC);
5458     if (ToRecord->isCompleteDefinition()) {
5459       // Do nothing.
5460     } else if (FromRecord->isCompleteDefinition()) {
5461       ASTNodeImporter(*this).ImportDefinition(FromRecord, ToRecord,
5462                                               ASTNodeImporter::IDK_Basic);
5463     } else {
5464       CompleteDecl(ToRecord);
5465     }
5466   } else if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
5467     EnumDecl *FromEnum = cast<EnumDecl>(FromDC);
5468     if (ToEnum->isCompleteDefinition()) {
5469       // Do nothing.
5470     } else if (FromEnum->isCompleteDefinition()) {
5471       ASTNodeImporter(*this).ImportDefinition(FromEnum, ToEnum,
5472                                               ASTNodeImporter::IDK_Basic);
5473     } else {
5474       CompleteDecl(ToEnum);
5475     }
5476   } else if (ObjCInterfaceDecl *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
5477     ObjCInterfaceDecl *FromClass = cast<ObjCInterfaceDecl>(FromDC);
5478     if (ToClass->getDefinition()) {
5479       // Do nothing.
5480     } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
5481       ASTNodeImporter(*this).ImportDefinition(FromDef, ToClass,
5482                                               ASTNodeImporter::IDK_Basic);
5483     } else {
5484       CompleteDecl(ToClass);
5485     }
5486   } else if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
5487     ObjCProtocolDecl *FromProto = cast<ObjCProtocolDecl>(FromDC);
5488     if (ToProto->getDefinition()) {
5489       // Do nothing.
5490     } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
5491       ASTNodeImporter(*this).ImportDefinition(FromDef, ToProto,
5492                                               ASTNodeImporter::IDK_Basic);
5493     } else {
5494       CompleteDecl(ToProto);
5495     }
5496   }
5497 
5498   return ToDC;
5499 }
5500 
Import(Expr * FromE)5501 Expr *ASTImporter::Import(Expr *FromE) {
5502   if (!FromE)
5503     return nullptr;
5504 
5505   return cast_or_null<Expr>(Import(cast<Stmt>(FromE)));
5506 }
5507 
Import(Stmt * FromS)5508 Stmt *ASTImporter::Import(Stmt *FromS) {
5509   if (!FromS)
5510     return nullptr;
5511 
5512   // Check whether we've already imported this declaration.
5513   llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
5514   if (Pos != ImportedStmts.end())
5515     return Pos->second;
5516 
5517   // Import the type
5518   ASTNodeImporter Importer(*this);
5519   Stmt *ToS = Importer.Visit(FromS);
5520   if (!ToS)
5521     return nullptr;
5522 
5523   // Record the imported declaration.
5524   ImportedStmts[FromS] = ToS;
5525   return ToS;
5526 }
5527 
Import(NestedNameSpecifier * FromNNS)5528 NestedNameSpecifier *ASTImporter::Import(NestedNameSpecifier *FromNNS) {
5529   if (!FromNNS)
5530     return nullptr;
5531 
5532   NestedNameSpecifier *prefix = Import(FromNNS->getPrefix());
5533 
5534   switch (FromNNS->getKind()) {
5535   case NestedNameSpecifier::Identifier:
5536     if (IdentifierInfo *II = Import(FromNNS->getAsIdentifier())) {
5537       return NestedNameSpecifier::Create(ToContext, prefix, II);
5538     }
5539     return nullptr;
5540 
5541   case NestedNameSpecifier::Namespace:
5542     if (NamespaceDecl *NS =
5543           cast<NamespaceDecl>(Import(FromNNS->getAsNamespace()))) {
5544       return NestedNameSpecifier::Create(ToContext, prefix, NS);
5545     }
5546     return nullptr;
5547 
5548   case NestedNameSpecifier::NamespaceAlias:
5549     if (NamespaceAliasDecl *NSAD =
5550           cast<NamespaceAliasDecl>(Import(FromNNS->getAsNamespaceAlias()))) {
5551       return NestedNameSpecifier::Create(ToContext, prefix, NSAD);
5552     }
5553     return nullptr;
5554 
5555   case NestedNameSpecifier::Global:
5556     return NestedNameSpecifier::GlobalSpecifier(ToContext);
5557 
5558   case NestedNameSpecifier::Super:
5559     if (CXXRecordDecl *RD =
5560             cast<CXXRecordDecl>(Import(FromNNS->getAsRecordDecl()))) {
5561       return NestedNameSpecifier::SuperSpecifier(ToContext, RD);
5562     }
5563     return nullptr;
5564 
5565   case NestedNameSpecifier::TypeSpec:
5566   case NestedNameSpecifier::TypeSpecWithTemplate: {
5567       QualType T = Import(QualType(FromNNS->getAsType(), 0u));
5568       if (!T.isNull()) {
5569         bool bTemplate = FromNNS->getKind() ==
5570                          NestedNameSpecifier::TypeSpecWithTemplate;
5571         return NestedNameSpecifier::Create(ToContext, prefix,
5572                                            bTemplate, T.getTypePtr());
5573       }
5574     }
5575       return nullptr;
5576   }
5577 
5578   llvm_unreachable("Invalid nested name specifier kind");
5579 }
5580 
Import(NestedNameSpecifierLoc FromNNS)5581 NestedNameSpecifierLoc ASTImporter::Import(NestedNameSpecifierLoc FromNNS) {
5582   // FIXME: Implement!
5583   return NestedNameSpecifierLoc();
5584 }
5585 
Import(TemplateName From)5586 TemplateName ASTImporter::Import(TemplateName From) {
5587   switch (From.getKind()) {
5588   case TemplateName::Template:
5589     if (TemplateDecl *ToTemplate
5590                 = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5591       return TemplateName(ToTemplate);
5592 
5593     return TemplateName();
5594 
5595   case TemplateName::OverloadedTemplate: {
5596     OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate();
5597     UnresolvedSet<2> ToTemplates;
5598     for (OverloadedTemplateStorage::iterator I = FromStorage->begin(),
5599                                              E = FromStorage->end();
5600          I != E; ++I) {
5601       if (NamedDecl *To = cast_or_null<NamedDecl>(Import(*I)))
5602         ToTemplates.addDecl(To);
5603       else
5604         return TemplateName();
5605     }
5606     return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
5607                                                ToTemplates.end());
5608   }
5609 
5610   case TemplateName::QualifiedTemplate: {
5611     QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName();
5612     NestedNameSpecifier *Qualifier = Import(QTN->getQualifier());
5613     if (!Qualifier)
5614       return TemplateName();
5615 
5616     if (TemplateDecl *ToTemplate
5617         = cast_or_null<TemplateDecl>(Import(From.getAsTemplateDecl())))
5618       return ToContext.getQualifiedTemplateName(Qualifier,
5619                                                 QTN->hasTemplateKeyword(),
5620                                                 ToTemplate);
5621 
5622     return TemplateName();
5623   }
5624 
5625   case TemplateName::DependentTemplate: {
5626     DependentTemplateName *DTN = From.getAsDependentTemplateName();
5627     NestedNameSpecifier *Qualifier = Import(DTN->getQualifier());
5628     if (!Qualifier)
5629       return TemplateName();
5630 
5631     if (DTN->isIdentifier()) {
5632       return ToContext.getDependentTemplateName(Qualifier,
5633                                                 Import(DTN->getIdentifier()));
5634     }
5635 
5636     return ToContext.getDependentTemplateName(Qualifier, DTN->getOperator());
5637   }
5638 
5639   case TemplateName::SubstTemplateTemplateParm: {
5640     SubstTemplateTemplateParmStorage *subst
5641       = From.getAsSubstTemplateTemplateParm();
5642     TemplateTemplateParmDecl *param
5643       = cast_or_null<TemplateTemplateParmDecl>(Import(subst->getParameter()));
5644     if (!param)
5645       return TemplateName();
5646 
5647     TemplateName replacement = Import(subst->getReplacement());
5648     if (replacement.isNull()) return TemplateName();
5649 
5650     return ToContext.getSubstTemplateTemplateParm(param, replacement);
5651   }
5652 
5653   case TemplateName::SubstTemplateTemplateParmPack: {
5654     SubstTemplateTemplateParmPackStorage *SubstPack
5655       = From.getAsSubstTemplateTemplateParmPack();
5656     TemplateTemplateParmDecl *Param
5657       = cast_or_null<TemplateTemplateParmDecl>(
5658                                         Import(SubstPack->getParameterPack()));
5659     if (!Param)
5660       return TemplateName();
5661 
5662     ASTNodeImporter Importer(*this);
5663     TemplateArgument ArgPack
5664       = Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
5665     if (ArgPack.isNull())
5666       return TemplateName();
5667 
5668     return ToContext.getSubstTemplateTemplateParmPack(Param, ArgPack);
5669   }
5670   }
5671 
5672   llvm_unreachable("Invalid template name kind");
5673 }
5674 
Import(SourceLocation FromLoc)5675 SourceLocation ASTImporter::Import(SourceLocation FromLoc) {
5676   if (FromLoc.isInvalid())
5677     return SourceLocation();
5678 
5679   SourceManager &FromSM = FromContext.getSourceManager();
5680 
5681   // For now, map everything down to its spelling location, so that we
5682   // don't have to import macro expansions.
5683   // FIXME: Import macro expansions!
5684   FromLoc = FromSM.getSpellingLoc(FromLoc);
5685   std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
5686   SourceManager &ToSM = ToContext.getSourceManager();
5687   FileID ToFileID = Import(Decomposed.first);
5688   if (ToFileID.isInvalid())
5689     return SourceLocation();
5690   SourceLocation ret = ToSM.getLocForStartOfFile(ToFileID)
5691                            .getLocWithOffset(Decomposed.second);
5692   return ret;
5693 }
5694 
Import(SourceRange FromRange)5695 SourceRange ASTImporter::Import(SourceRange FromRange) {
5696   return SourceRange(Import(FromRange.getBegin()), Import(FromRange.getEnd()));
5697 }
5698 
Import(FileID FromID)5699 FileID ASTImporter::Import(FileID FromID) {
5700   llvm::DenseMap<FileID, FileID>::iterator Pos
5701     = ImportedFileIDs.find(FromID);
5702   if (Pos != ImportedFileIDs.end())
5703     return Pos->second;
5704 
5705   SourceManager &FromSM = FromContext.getSourceManager();
5706   SourceManager &ToSM = ToContext.getSourceManager();
5707   const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
5708   assert(FromSLoc.isFile() && "Cannot handle macro expansions yet");
5709 
5710   // Include location of this file.
5711   SourceLocation ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
5712 
5713   // Map the FileID for to the "to" source manager.
5714   FileID ToID;
5715   const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache();
5716   if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
5717     // FIXME: We probably want to use getVirtualFile(), so we don't hit the
5718     // disk again
5719     // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
5720     // than mmap the files several times.
5721     const FileEntry *Entry = ToFileManager.getFile(Cache->OrigEntry->getName());
5722     if (!Entry)
5723       return FileID();
5724     ToID = ToSM.createFileID(Entry, ToIncludeLoc,
5725                              FromSLoc.getFile().getFileCharacteristic());
5726   } else {
5727     // FIXME: We want to re-use the existing MemoryBuffer!
5728     const llvm::MemoryBuffer *
5729         FromBuf = Cache->getBuffer(FromContext.getDiagnostics(), FromSM);
5730     std::unique_ptr<llvm::MemoryBuffer> ToBuf
5731       = llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
5732                                              FromBuf->getBufferIdentifier());
5733     ToID = ToSM.createFileID(std::move(ToBuf),
5734                              FromSLoc.getFile().getFileCharacteristic());
5735   }
5736 
5737 
5738   ImportedFileIDs[FromID] = ToID;
5739   return ToID;
5740 }
5741 
ImportDefinition(Decl * From)5742 void ASTImporter::ImportDefinition(Decl *From) {
5743   Decl *To = Import(From);
5744   if (!To)
5745     return;
5746 
5747   if (DeclContext *FromDC = cast<DeclContext>(From)) {
5748     ASTNodeImporter Importer(*this);
5749 
5750     if (RecordDecl *ToRecord = dyn_cast<RecordDecl>(To)) {
5751       if (!ToRecord->getDefinition()) {
5752         Importer.ImportDefinition(cast<RecordDecl>(FromDC), ToRecord,
5753                                   ASTNodeImporter::IDK_Everything);
5754         return;
5755       }
5756     }
5757 
5758     if (EnumDecl *ToEnum = dyn_cast<EnumDecl>(To)) {
5759       if (!ToEnum->getDefinition()) {
5760         Importer.ImportDefinition(cast<EnumDecl>(FromDC), ToEnum,
5761                                   ASTNodeImporter::IDK_Everything);
5762         return;
5763       }
5764     }
5765 
5766     if (ObjCInterfaceDecl *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
5767       if (!ToIFace->getDefinition()) {
5768         Importer.ImportDefinition(cast<ObjCInterfaceDecl>(FromDC), ToIFace,
5769                                   ASTNodeImporter::IDK_Everything);
5770         return;
5771       }
5772     }
5773 
5774     if (ObjCProtocolDecl *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
5775       if (!ToProto->getDefinition()) {
5776         Importer.ImportDefinition(cast<ObjCProtocolDecl>(FromDC), ToProto,
5777                                   ASTNodeImporter::IDK_Everything);
5778         return;
5779       }
5780     }
5781 
5782     Importer.ImportDeclContext(FromDC, true);
5783   }
5784 }
5785 
Import(DeclarationName FromName)5786 DeclarationName ASTImporter::Import(DeclarationName FromName) {
5787   if (!FromName)
5788     return DeclarationName();
5789 
5790   switch (FromName.getNameKind()) {
5791   case DeclarationName::Identifier:
5792     return Import(FromName.getAsIdentifierInfo());
5793 
5794   case DeclarationName::ObjCZeroArgSelector:
5795   case DeclarationName::ObjCOneArgSelector:
5796   case DeclarationName::ObjCMultiArgSelector:
5797     return Import(FromName.getObjCSelector());
5798 
5799   case DeclarationName::CXXConstructorName: {
5800     QualType T = Import(FromName.getCXXNameType());
5801     if (T.isNull())
5802       return DeclarationName();
5803 
5804     return ToContext.DeclarationNames.getCXXConstructorName(
5805                                                ToContext.getCanonicalType(T));
5806   }
5807 
5808   case DeclarationName::CXXDestructorName: {
5809     QualType T = Import(FromName.getCXXNameType());
5810     if (T.isNull())
5811       return DeclarationName();
5812 
5813     return ToContext.DeclarationNames.getCXXDestructorName(
5814                                                ToContext.getCanonicalType(T));
5815   }
5816 
5817   case DeclarationName::CXXConversionFunctionName: {
5818     QualType T = Import(FromName.getCXXNameType());
5819     if (T.isNull())
5820       return DeclarationName();
5821 
5822     return ToContext.DeclarationNames.getCXXConversionFunctionName(
5823                                                ToContext.getCanonicalType(T));
5824   }
5825 
5826   case DeclarationName::CXXOperatorName:
5827     return ToContext.DeclarationNames.getCXXOperatorName(
5828                                           FromName.getCXXOverloadedOperator());
5829 
5830   case DeclarationName::CXXLiteralOperatorName:
5831     return ToContext.DeclarationNames.getCXXLiteralOperatorName(
5832                                    Import(FromName.getCXXLiteralIdentifier()));
5833 
5834   case DeclarationName::CXXUsingDirective:
5835     // FIXME: STATICS!
5836     return DeclarationName::getUsingDirectiveName();
5837   }
5838 
5839   llvm_unreachable("Invalid DeclarationName Kind!");
5840 }
5841 
Import(const IdentifierInfo * FromId)5842 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) {
5843   if (!FromId)
5844     return nullptr;
5845 
5846   return &ToContext.Idents.get(FromId->getName());
5847 }
5848 
Import(Selector FromSel)5849 Selector ASTImporter::Import(Selector FromSel) {
5850   if (FromSel.isNull())
5851     return Selector();
5852 
5853   SmallVector<IdentifierInfo *, 4> Idents;
5854   Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
5855   for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
5856     Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
5857   return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
5858 }
5859 
HandleNameConflict(DeclarationName Name,DeclContext * DC,unsigned IDNS,NamedDecl ** Decls,unsigned NumDecls)5860 DeclarationName ASTImporter::HandleNameConflict(DeclarationName Name,
5861                                                 DeclContext *DC,
5862                                                 unsigned IDNS,
5863                                                 NamedDecl **Decls,
5864                                                 unsigned NumDecls) {
5865   return Name;
5866 }
5867 
ToDiag(SourceLocation Loc,unsigned DiagID)5868 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) {
5869   if (LastDiagFromFrom)
5870     ToContext.getDiagnostics().notePriorDiagnosticFrom(
5871       FromContext.getDiagnostics());
5872   LastDiagFromFrom = false;
5873   return ToContext.getDiagnostics().Report(Loc, DiagID);
5874 }
5875 
FromDiag(SourceLocation Loc,unsigned DiagID)5876 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) {
5877   if (!LastDiagFromFrom)
5878     FromContext.getDiagnostics().notePriorDiagnosticFrom(
5879       ToContext.getDiagnostics());
5880   LastDiagFromFrom = true;
5881   return FromContext.getDiagnostics().Report(Loc, DiagID);
5882 }
5883 
CompleteDecl(Decl * D)5884 void ASTImporter::CompleteDecl (Decl *D) {
5885   if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
5886     if (!ID->getDefinition())
5887       ID->startDefinition();
5888   }
5889   else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
5890     if (!PD->getDefinition())
5891       PD->startDefinition();
5892   }
5893   else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
5894     if (!TD->getDefinition() && !TD->isBeingDefined()) {
5895       TD->startDefinition();
5896       TD->setCompleteDefinition(true);
5897     }
5898   }
5899   else {
5900     assert (0 && "CompleteDecl called on a Decl that can't be completed");
5901   }
5902 }
5903 
Imported(Decl * From,Decl * To)5904 Decl *ASTImporter::Imported(Decl *From, Decl *To) {
5905   ImportedDecls[From] = To;
5906   return To;
5907 }
5908 
IsStructurallyEquivalent(QualType From,QualType To,bool Complain)5909 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To,
5910                                            bool Complain) {
5911   llvm::DenseMap<const Type *, const Type *>::iterator Pos
5912    = ImportedTypes.find(From.getTypePtr());
5913   if (Pos != ImportedTypes.end() && ToContext.hasSameType(Import(From), To))
5914     return true;
5915 
5916   StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
5917                                    false, Complain);
5918   return Ctx.IsStructurallyEquivalent(From, To);
5919 }
5920