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