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