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