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