clang  9.0.0svn
ASTImporter.cpp
Go to the documentation of this file.
1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the ASTImporter class which imports AST nodes from one
10 // context into another context.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/ASTImporter.h"
16 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclBase.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclFriend.h"
25 #include "clang/AST/DeclGroup.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/DeclTemplate.h"
28 #include "clang/AST/DeclVisitor.h"
30 #include "clang/AST/Expr.h"
31 #include "clang/AST/ExprCXX.h"
32 #include "clang/AST/ExprObjC.h"
37 #include "clang/AST/Stmt.h"
38 #include "clang/AST/StmtCXX.h"
39 #include "clang/AST/StmtObjC.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TemplateBase.h"
42 #include "clang/AST/TemplateName.h"
43 #include "clang/AST/Type.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/AST/TypeVisitor.h"
50 #include "clang/Basic/LLVM.h"
54 #include "clang/Basic/Specifiers.h"
55 #include "llvm/ADT/APSInt.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/ADT/DenseMap.h"
58 #include "llvm/ADT/None.h"
59 #include "llvm/ADT/Optional.h"
60 #include "llvm/ADT/STLExtras.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/MemoryBuffer.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <memory>
69 #include <type_traits>
70 #include <utility>
71 
72 namespace clang {
73 
74  using llvm::make_error;
75  using llvm::Error;
76  using llvm::Expected;
82 
83  std::string ImportError::toString() const {
84  // FIXME: Improve error texts.
85  switch (Error) {
86  case NameConflict:
87  return "NameConflict";
89  return "UnsupportedConstruct";
90  case Unknown:
91  return "Unknown error";
92  }
93  llvm_unreachable("Invalid error code.");
94  return "Invalid error code.";
95  }
96 
97  void ImportError::log(raw_ostream &OS) const {
98  OS << toString();
99  }
100 
101  std::error_code ImportError::convertToErrorCode() const {
102  llvm_unreachable("Function not implemented.");
103  }
104 
105  char ImportError::ID;
106 
107  template <class T>
110  SmallVector<Decl *, 2> Redecls;
111  for (auto *R : D->getFirstDecl()->redecls()) {
112  if (R != D->getFirstDecl())
113  Redecls.push_back(R);
114  }
115  Redecls.push_back(D->getFirstDecl());
116  std::reverse(Redecls.begin(), Redecls.end());
117  return Redecls;
118  }
119 
121  if (auto *FD = dyn_cast<FunctionDecl>(D))
122  return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
123  if (auto *VD = dyn_cast<VarDecl>(D))
124  return getCanonicalForwardRedeclChain<VarDecl>(VD);
125  if (auto *TD = dyn_cast<TagDecl>(D))
126  return getCanonicalForwardRedeclChain<TagDecl>(TD);
127  llvm_unreachable("Bad declaration kind");
128  }
129 
130  void updateFlags(const Decl *From, Decl *To) {
131  // Check if some flags or attrs are new in 'From' and copy into 'To'.
132  // FIXME: Other flags or attrs?
133  if (From->isUsed(false) && !To->isUsed(false))
134  To->setIsUsed();
135  }
136 
137  // FIXME: Temporary until every import returns Expected.
138  template <>
139  LLVM_NODISCARD Error
141  To = Import(From);
142  if (From.isValid() && To.isInvalid())
143  return llvm::make_error<ImportError>();
144  return Error::success();
145  }
146  // FIXME: Temporary until every import returns Expected.
147  template <>
148  LLVM_NODISCARD Error
150  To = Import(From);
151  if (!From.isNull() && To.isNull())
152  return llvm::make_error<ImportError>();
153  return Error::success();
154  }
155 
156  class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
157  public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
158  public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
159  ASTImporter &Importer;
160 
161  // Use this instead of Importer.importInto .
162  template <typename ImportT>
163  LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
164  return Importer.importInto(To, From);
165  }
166 
167  // Use this to import pointers of specific type.
168  template <typename ImportT>
169  LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
170  auto ToI = Importer.Import(From);
171  if (!ToI && From)
172  return make_error<ImportError>();
173  To = cast_or_null<ImportT>(ToI);
174  return Error::success();
175  // FIXME: This should be the final code.
176  //auto ToOrErr = Importer.Import(From);
177  //if (ToOrErr) {
178  // To = cast_or_null<ImportT>(*ToOrErr);
179  //}
180  //return ToOrErr.takeError();
181  }
182 
183  // Call the import function of ASTImporter for a baseclass of type `T` and
184  // cast the return value to `T`.
185  template <typename T>
186  Expected<T *> import(T *From) {
187  auto *To = Importer.Import(From);
188  if (!To && From)
189  return make_error<ImportError>();
190  return cast_or_null<T>(To);
191  // FIXME: This should be the final code.
192  //auto ToOrErr = Importer.Import(From);
193  //if (!ToOrErr)
194  // return ToOrErr.takeError();
195  //return cast_or_null<T>(*ToOrErr);
196  }
197 
198  template <typename T>
199  Expected<T *> import(const T *From) {
200  return import(const_cast<T *>(From));
201  }
202 
203  // Call the import function of ASTImporter for type `T`.
204  template <typename T>
205  Expected<T> import(const T &From) {
206  T To = Importer.Import(From);
207  T DefaultT;
208  if (To == DefaultT && !(From == DefaultT))
209  return make_error<ImportError>();
210  return To;
211  // FIXME: This should be the final code.
212  //return Importer.Import(From);
213  }
214 
215  template <class T>
217  importSeq(const T &From) {
218  Expected<T> ToOrErr = import(From);
219  if (!ToOrErr)
220  return ToOrErr.takeError();
221  return std::make_tuple<T>(std::move(*ToOrErr));
222  }
223 
224  // Import multiple objects with a single function call.
225  // This should work for every type for which a variant of `import` exists.
226  // The arguments are processed from left to right and import is stopped on
227  // first error.
228  template <class THead, class... TTail>
229  Expected<std::tuple<THead, TTail...>>
230  importSeq(const THead &FromHead, const TTail &...FromTail) {
231  Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead);
232  if (!ToHeadOrErr)
233  return ToHeadOrErr.takeError();
234  Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...);
235  if (!ToTailOrErr)
236  return ToTailOrErr.takeError();
237  return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr);
238  }
239 
240 // Wrapper for an overload set.
241  template <typename ToDeclT> struct CallOverloadedCreateFun {
242  template <typename... Args>
243  auto operator()(Args &&... args)
244  -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
245  return ToDeclT::Create(std::forward<Args>(args)...);
246  }
247  };
248 
249  // Always use these functions to create a Decl during import. There are
250  // certain tasks which must be done after the Decl was created, e.g. we
251  // must immediately register that as an imported Decl. The parameter `ToD`
252  // will be set to the newly created Decl or if had been imported before
253  // then to the already imported Decl. Returns a bool value set to true if
254  // the `FromD` had been imported before.
255  template <typename ToDeclT, typename FromDeclT, typename... Args>
256  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
257  Args &&... args) {
258  // There may be several overloads of ToDeclT::Create. We must make sure
259  // to call the one which would be chosen by the arguments, thus we use a
260  // wrapper for the overload set.
261  CallOverloadedCreateFun<ToDeclT> OC;
262  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
263  std::forward<Args>(args)...);
264  }
265  // Use this overload if a special Type is needed to be created. E.g if we
266  // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
267  // then:
268  // TypedefNameDecl *ToTypedef;
269  // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
270  template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
271  typename... Args>
272  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
273  Args &&... args) {
274  CallOverloadedCreateFun<NewDeclT> OC;
275  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
276  std::forward<Args>(args)...);
277  }
278  // Use this version if a special create function must be
279  // used, e.g. CXXRecordDecl::CreateLambda .
280  template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
281  typename... Args>
282  LLVM_NODISCARD bool
283  GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
284  FromDeclT *FromD, Args &&... args) {
285  // FIXME: This code is needed later.
286  //if (Importer.getImportDeclErrorIfAny(FromD)) {
287  // ToD = nullptr;
288  // return true; // Already imported but with error.
289  //}
290  ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
291  if (ToD)
292  return true; // Already imported.
293  ToD = CreateFun(std::forward<Args>(args)...);
294  // Keep track of imported Decls.
295  Importer.MapImported(FromD, ToD);
296  Importer.AddToLookupTable(ToD);
297  InitializeImportedDecl(FromD, ToD);
298  return false; // A new Decl is created.
299  }
300 
301  void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
303  if (FromD->hasAttrs())
304  for (const Attr *FromAttr : FromD->getAttrs())
305  ToD->addAttr(Importer.Import(FromAttr));
306  if (FromD->isUsed())
307  ToD->setIsUsed();
308  if (FromD->isImplicit())
309  ToD->setImplicit();
310  }
311 
312  public:
313  explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
314 
318 
319  // Importing types
320  ExpectedType VisitType(const Type *T);
321  ExpectedType VisitAtomicType(const AtomicType *T);
322  ExpectedType VisitBuiltinType(const BuiltinType *T);
323  ExpectedType VisitDecayedType(const DecayedType *T);
324  ExpectedType VisitComplexType(const ComplexType *T);
325  ExpectedType VisitPointerType(const PointerType *T);
326  ExpectedType VisitBlockPointerType(const BlockPointerType *T);
327  ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
328  ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
329  ExpectedType VisitMemberPointerType(const MemberPointerType *T);
330  ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
331  ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
332  ExpectedType VisitVariableArrayType(const VariableArrayType *T);
333  ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
334  // FIXME: DependentSizedExtVectorType
335  ExpectedType VisitVectorType(const VectorType *T);
336  ExpectedType VisitExtVectorType(const ExtVectorType *T);
337  ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
338  ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
339  ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
340  ExpectedType VisitParenType(const ParenType *T);
341  ExpectedType VisitTypedefType(const TypedefType *T);
342  ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
343  // FIXME: DependentTypeOfExprType
344  ExpectedType VisitTypeOfType(const TypeOfType *T);
345  ExpectedType VisitDecltypeType(const DecltypeType *T);
346  ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
347  ExpectedType VisitAutoType(const AutoType *T);
348  ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
349  // FIXME: DependentDecltypeType
350  ExpectedType VisitRecordType(const RecordType *T);
351  ExpectedType VisitEnumType(const EnumType *T);
352  ExpectedType VisitAttributedType(const AttributedType *T);
353  ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
354  ExpectedType VisitSubstTemplateTypeParmType(
355  const SubstTemplateTypeParmType *T);
356  ExpectedType VisitTemplateSpecializationType(
357  const TemplateSpecializationType *T);
358  ExpectedType VisitElaboratedType(const ElaboratedType *T);
359  ExpectedType VisitDependentNameType(const DependentNameType *T);
360  ExpectedType VisitPackExpansionType(const PackExpansionType *T);
361  ExpectedType VisitDependentTemplateSpecializationType(
363  ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
364  ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
365  ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
366 
367  // Importing declarations
368  Error ImportDeclParts(
369  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
370  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
371  Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
372  Error ImportDeclarationNameLoc(
373  const DeclarationNameInfo &From, DeclarationNameInfo &To);
374  Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
375  Error ImportDeclContext(
376  Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
377  Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
378 
379  Expected<CXXCastPath> ImportCastPath(CastExpr *E);
380 
382 
383  /// What we should import from the definition.
385  /// Import the default subset of the definition, which might be
386  /// nothing (if minimal import is set) or might be everything (if minimal
387  /// import is not set).
389  /// Import everything.
391  /// Import only the bare bones needed to establish a valid
392  /// DeclContext.
393  IDK_Basic
394  };
395 
397  return IDK == IDK_Everything ||
398  (IDK == IDK_Default && !Importer.isMinimalImport());
399  }
400 
401  Error ImportInitializer(VarDecl *From, VarDecl *To);
402  Error ImportDefinition(
403  RecordDecl *From, RecordDecl *To,
404  ImportDefinitionKind Kind = IDK_Default);
405  Error ImportDefinition(
406  EnumDecl *From, EnumDecl *To,
407  ImportDefinitionKind Kind = IDK_Default);
408  Error ImportDefinition(
410  ImportDefinitionKind Kind = IDK_Default);
411  Error ImportDefinition(
413  ImportDefinitionKind Kind = IDK_Default);
414  Expected<TemplateParameterList *> ImportTemplateParameterList(
415  TemplateParameterList *Params);
416  Error ImportTemplateArguments(
417  const TemplateArgument *FromArgs, unsigned NumFromArgs,
420  ImportTemplateArgument(const TemplateArgument &From);
421 
422  template <typename InContainerTy>
423  Error ImportTemplateArgumentListInfo(
424  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
425 
426  template<typename InContainerTy>
427  Error ImportTemplateArgumentListInfo(
428  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
429  const InContainerTy &Container, TemplateArgumentListInfo &Result);
430 
433  std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
435  ImportFunctionTemplateWithTemplateArgsFromSpecialization(
436  FunctionDecl *FromFD);
437 
438  Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
439 
440  bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
441  bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
442  bool Complain = true);
443  bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
444  bool Complain = true);
445  bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
446  bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
447  bool IsStructuralMatch(FunctionTemplateDecl *From,
449  bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
450  bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
451  bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
452  ExpectedDecl VisitDecl(Decl *D);
453  ExpectedDecl VisitImportDecl(ImportDecl *D);
454  ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
455  ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
456  ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
457  ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
458  ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
459  ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
460  ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
461  ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
462  ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
463  ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
464  ExpectedDecl VisitLabelDecl(LabelDecl *D);
465  ExpectedDecl VisitEnumDecl(EnumDecl *D);
466  ExpectedDecl VisitRecordDecl(RecordDecl *D);
467  ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
468  ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
469  ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
470  ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
471  ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
472  ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
473  ExpectedDecl VisitFieldDecl(FieldDecl *D);
474  ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
475  ExpectedDecl VisitFriendDecl(FriendDecl *D);
476  ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
477  ExpectedDecl VisitVarDecl(VarDecl *D);
478  ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
479  ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
480  ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
481  ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
482  ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
483  ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
484  ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
485  ExpectedDecl VisitUsingDecl(UsingDecl *D);
486  ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
487  ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
488  ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
489  ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
490 
492  ImportObjCTypeParamList(ObjCTypeParamList *list);
493 
494  ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
495  ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
496  ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
497  ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
498  ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
499  ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
500  ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
501  ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
502  ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
503  ExpectedDecl VisitClassTemplateSpecializationDecl(
505  ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
506  ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
507  ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
508 
509  // Importing statements
510  ExpectedStmt VisitStmt(Stmt *S);
511  ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
512  ExpectedStmt VisitDeclStmt(DeclStmt *S);
513  ExpectedStmt VisitNullStmt(NullStmt *S);
514  ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
515  ExpectedStmt VisitCaseStmt(CaseStmt *S);
516  ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
517  ExpectedStmt VisitLabelStmt(LabelStmt *S);
518  ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
519  ExpectedStmt VisitIfStmt(IfStmt *S);
520  ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
521  ExpectedStmt VisitWhileStmt(WhileStmt *S);
522  ExpectedStmt VisitDoStmt(DoStmt *S);
523  ExpectedStmt VisitForStmt(ForStmt *S);
524  ExpectedStmt VisitGotoStmt(GotoStmt *S);
525  ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
526  ExpectedStmt VisitContinueStmt(ContinueStmt *S);
527  ExpectedStmt VisitBreakStmt(BreakStmt *S);
528  ExpectedStmt VisitReturnStmt(ReturnStmt *S);
529  // FIXME: MSAsmStmt
530  // FIXME: SEHExceptStmt
531  // FIXME: SEHFinallyStmt
532  // FIXME: SEHTryStmt
533  // FIXME: SEHLeaveStmt
534  // FIXME: CapturedStmt
535  ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
536  ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
537  ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
538  // FIXME: MSDependentExistsStmt
539  ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
540  ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
541  ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
542  ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
543  ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
544  ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
545  ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
546 
547  // Importing expressions
548  ExpectedStmt VisitExpr(Expr *E);
549  ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
550  ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
551  ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
552  ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
553  ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
554  ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
555  ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
556  ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
557  ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
558  ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
559  ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
560  ExpectedStmt VisitStringLiteral(StringLiteral *E);
561  ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
562  ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
563  ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
564  ExpectedStmt VisitConstantExpr(ConstantExpr *E);
565  ExpectedStmt VisitParenExpr(ParenExpr *E);
566  ExpectedStmt VisitParenListExpr(ParenListExpr *E);
567  ExpectedStmt VisitStmtExpr(StmtExpr *E);
568  ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
569  ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
570  ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
571  ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
572  ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
573  ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
574  ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
575  ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
576  ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
577  ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
578  ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
579  ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
580  ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
581  ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
582  ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
583  ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
584  ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
585  ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
586  ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
587  ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
588  ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
589  ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
590  ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
591  ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
592  ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
593  ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
594  ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
595  ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
596  ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
597  ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
598  ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
599  ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
600  ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
601  ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
602  ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
603  ExpectedStmt VisitMemberExpr(MemberExpr *E);
604  ExpectedStmt VisitCallExpr(CallExpr *E);
605  ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
606  ExpectedStmt VisitInitListExpr(InitListExpr *E);
607  ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
608  ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
609  ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
610  ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
611  ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
612  ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
613  ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
614  ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
615  ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
616 
617  template<typename IIter, typename OIter>
618  Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
619  using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
620  for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
621  Expected<ItemT> ToOrErr = import(*Ibegin);
622  if (!ToOrErr)
623  return ToOrErr.takeError();
624  *Obegin = *ToOrErr;
625  }
626  return Error::success();
627  }
628 
629  // Import every item from a container structure into an output container.
630  // If error occurs, stops at first error and returns the error.
631  // The output container should have space for all needed elements (it is not
632  // expanded, new items are put into from the beginning).
633  template<typename InContainerTy, typename OutContainerTy>
635  const InContainerTy &InContainer, OutContainerTy &OutContainer) {
636  return ImportArrayChecked(
637  InContainer.begin(), InContainer.end(), OutContainer.begin());
638  }
639 
640  template<typename InContainerTy, typename OIter>
641  Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
642  return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
643  }
644 
645  void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
646 
647  Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
648  FunctionDecl *FromFD);
649  };
650 
651 // FIXME: Temporary until every import returns Expected.
652 template <>
653 Expected<TemplateName> ASTNodeImporter::import(const TemplateName &From) {
654  TemplateName To = Importer.Import(From);
655  if (To.isNull() && !From.isNull())
656  return make_error<ImportError>();
657  return To;
658 }
659 
660 template <typename InContainerTy>
662  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
663  const InContainerTy &Container, TemplateArgumentListInfo &Result) {
664  auto ToLAngleLocOrErr = import(FromLAngleLoc);
665  if (!ToLAngleLocOrErr)
666  return ToLAngleLocOrErr.takeError();
667  auto ToRAngleLocOrErr = import(FromRAngleLoc);
668  if (!ToRAngleLocOrErr)
669  return ToRAngleLocOrErr.takeError();
670 
671  TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
672  if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
673  return Err;
674  Result = ToTAInfo;
675  return Error::success();
676 }
677 
678 template <>
679 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
681  return ImportTemplateArgumentListInfo(
682  From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
683 }
684 
685 template <>
688  const ASTTemplateArgumentListInfo &From,
690  return ImportTemplateArgumentListInfo(
691  From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
692 }
693 
696  FunctionDecl *FromFD) {
697  assert(FromFD->getTemplatedKind() ==
699 
701 
702  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
703  if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
704  return std::move(Err);
705 
706  // Import template arguments.
707  auto TemplArgs = FTSInfo->TemplateArguments->asArray();
708  if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
709  std::get<1>(Result)))
710  return std::move(Err);
711 
712  return Result;
713 }
714 
715 template <>
717 ASTNodeImporter::import(TemplateParameterList *From) {
718  SmallVector<NamedDecl *, 4> To(From->size());
719  if (Error Err = ImportContainerChecked(*From, To))
720  return std::move(Err);
721 
722  ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
723  if (!ToRequiresClause)
724  return ToRequiresClause.takeError();
725 
726  auto ToTemplateLocOrErr = import(From->getTemplateLoc());
727  if (!ToTemplateLocOrErr)
728  return ToTemplateLocOrErr.takeError();
729  auto ToLAngleLocOrErr = import(From->getLAngleLoc());
730  if (!ToLAngleLocOrErr)
731  return ToLAngleLocOrErr.takeError();
732  auto ToRAngleLocOrErr = import(From->getRAngleLoc());
733  if (!ToRAngleLocOrErr)
734  return ToRAngleLocOrErr.takeError();
735 
737  Importer.getToContext(),
738  *ToTemplateLocOrErr,
739  *ToLAngleLocOrErr,
740  To,
741  *ToRAngleLocOrErr,
742  *ToRequiresClause);
743 }
744 
745 template <>
747 ASTNodeImporter::import(const TemplateArgument &From) {
748  switch (From.getKind()) {
750  return TemplateArgument();
751 
752  case TemplateArgument::Type: {
753  ExpectedType ToTypeOrErr = import(From.getAsType());
754  if (!ToTypeOrErr)
755  return ToTypeOrErr.takeError();
756  return TemplateArgument(*ToTypeOrErr);
757  }
758 
760  ExpectedType ToTypeOrErr = import(From.getIntegralType());
761  if (!ToTypeOrErr)
762  return ToTypeOrErr.takeError();
763  return TemplateArgument(From, *ToTypeOrErr);
764  }
765 
767  Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
768  if (!ToOrErr)
769  return ToOrErr.takeError();
770  ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
771  if (!ToTypeOrErr)
772  return ToTypeOrErr.takeError();
773  return TemplateArgument(*ToOrErr, *ToTypeOrErr);
774  }
775 
777  ExpectedType ToTypeOrErr = import(From.getNullPtrType());
778  if (!ToTypeOrErr)
779  return ToTypeOrErr.takeError();
780  return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
781  }
782 
784  Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
785  if (!ToTemplateOrErr)
786  return ToTemplateOrErr.takeError();
787 
788  return TemplateArgument(*ToTemplateOrErr);
789  }
790 
792  Expected<TemplateName> ToTemplateOrErr =
793  import(From.getAsTemplateOrTemplatePattern());
794  if (!ToTemplateOrErr)
795  return ToTemplateOrErr.takeError();
796 
797  return TemplateArgument(
798  *ToTemplateOrErr, From.getNumTemplateExpansions());
799  }
800 
802  if (ExpectedExpr ToExpr = import(From.getAsExpr()))
803  return TemplateArgument(*ToExpr);
804  else
805  return ToExpr.takeError();
806 
807  case TemplateArgument::Pack: {
809  ToPack.reserve(From.pack_size());
810  if (Error Err = ImportTemplateArguments(
811  From.pack_begin(), From.pack_size(), ToPack))
812  return std::move(Err);
813 
814  return TemplateArgument(
815  llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
816  }
817  }
818 
819  llvm_unreachable("Invalid template argument kind");
820 }
821 
822 template <>
824 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
825  Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
826  if (!ArgOrErr)
827  return ArgOrErr.takeError();
828  TemplateArgument Arg = *ArgOrErr;
829 
830  TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
831 
833  if (Arg.getKind() == TemplateArgument::Expression) {
834  ExpectedExpr E = import(FromInfo.getAsExpr());
835  if (!E)
836  return E.takeError();
837  ToInfo = TemplateArgumentLocInfo(*E);
838  } else if (Arg.getKind() == TemplateArgument::Type) {
839  if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
840  ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
841  else
842  return TSIOrErr.takeError();
843  } else {
844  auto ToTemplateQualifierLocOrErr =
845  import(FromInfo.getTemplateQualifierLoc());
846  if (!ToTemplateQualifierLocOrErr)
847  return ToTemplateQualifierLocOrErr.takeError();
848  auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
849  if (!ToTemplateNameLocOrErr)
850  return ToTemplateNameLocOrErr.takeError();
851  auto ToTemplateEllipsisLocOrErr =
852  import(FromInfo.getTemplateEllipsisLoc());
853  if (!ToTemplateEllipsisLocOrErr)
854  return ToTemplateEllipsisLocOrErr.takeError();
855 
856  ToInfo = TemplateArgumentLocInfo(
857  *ToTemplateQualifierLocOrErr,
858  *ToTemplateNameLocOrErr,
859  *ToTemplateEllipsisLocOrErr);
860  }
861 
862  return TemplateArgumentLoc(Arg, ToInfo);
863 }
864 
865 template <>
866 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
867  if (DG.isNull())
868  return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
869  size_t NumDecls = DG.end() - DG.begin();
870  SmallVector<Decl *, 1> ToDecls;
871  ToDecls.reserve(NumDecls);
872  for (Decl *FromD : DG) {
873  if (auto ToDOrErr = import(FromD))
874  ToDecls.push_back(*ToDOrErr);
875  else
876  return ToDOrErr.takeError();
877  }
878  return DeclGroupRef::Create(Importer.getToContext(),
879  ToDecls.begin(),
880  NumDecls);
881 }
882 
883 template <>
885 ASTNodeImporter::import(const Designator &D) {
886  if (D.isFieldDesignator()) {
887  IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
888 
889  ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
890  if (!ToDotLocOrErr)
891  return ToDotLocOrErr.takeError();
892 
893  ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
894  if (!ToFieldLocOrErr)
895  return ToFieldLocOrErr.takeError();
896 
897  return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
898  }
899 
900  ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
901  if (!ToLBracketLocOrErr)
902  return ToLBracketLocOrErr.takeError();
903 
904  ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
905  if (!ToRBracketLocOrErr)
906  return ToRBracketLocOrErr.takeError();
907 
908  if (D.isArrayDesignator())
909  return Designator(D.getFirstExprIndex(),
910  *ToLBracketLocOrErr, *ToRBracketLocOrErr);
911 
912  ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
913  if (!ToEllipsisLocOrErr)
914  return ToEllipsisLocOrErr.takeError();
915 
916  assert(D.isArrayRangeDesignator());
917  return Designator(
918  D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
919  *ToRBracketLocOrErr);
920 }
921 
922 template <>
923 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
924  VarDecl *Var = nullptr;
925  if (From.capturesVariable()) {
926  if (auto VarOrErr = import(From.getCapturedVar()))
927  Var = *VarOrErr;
928  else
929  return VarOrErr.takeError();
930  }
931 
932  auto LocationOrErr = import(From.getLocation());
933  if (!LocationOrErr)
934  return LocationOrErr.takeError();
935 
936  SourceLocation EllipsisLoc;
937  if (From.isPackExpansion())
938  if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
939  return std::move(Err);
940 
941  return LambdaCapture(
942  *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
943  EllipsisLoc);
944 }
945 
946 } // namespace clang
947 
948 //----------------------------------------------------------------------------
949 // Import Types
950 //----------------------------------------------------------------------------
951 
952 using namespace clang;
953 
955  Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
956  << T->getTypeClassName();
957  return make_error<ImportError>(ImportError::UnsupportedConstruct);
958 }
959 
961  ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
962  if (!UnderlyingTypeOrErr)
963  return UnderlyingTypeOrErr.takeError();
964 
965  return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
966 }
967 
969  switch (T->getKind()) {
970 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
971  case BuiltinType::Id: \
972  return Importer.getToContext().SingletonId;
973 #include "clang/Basic/OpenCLImageTypes.def"
974 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
975  case BuiltinType::Id: \
976  return Importer.getToContext().Id##Ty;
977 #include "clang/Basic/OpenCLExtensionTypes.def"
978 #define SHARED_SINGLETON_TYPE(Expansion)
979 #define BUILTIN_TYPE(Id, SingletonId) \
980  case BuiltinType::Id: return Importer.getToContext().SingletonId;
981 #include "clang/AST/BuiltinTypes.def"
982 
983  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
984  // context supports C++.
985 
986  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
987  // context supports ObjC.
988 
989  case BuiltinType::Char_U:
990  // The context we're importing from has an unsigned 'char'. If we're
991  // importing into a context with a signed 'char', translate to
992  // 'unsigned char' instead.
993  if (Importer.getToContext().getLangOpts().CharIsSigned)
994  return Importer.getToContext().UnsignedCharTy;
995 
996  return Importer.getToContext().CharTy;
997 
998  case BuiltinType::Char_S:
999  // The context we're importing from has an unsigned 'char'. If we're
1000  // importing into a context with a signed 'char', translate to
1001  // 'unsigned char' instead.
1002  if (!Importer.getToContext().getLangOpts().CharIsSigned)
1003  return Importer.getToContext().SignedCharTy;
1004 
1005  return Importer.getToContext().CharTy;
1006 
1007  case BuiltinType::WChar_S:
1008  case BuiltinType::WChar_U:
1009  // FIXME: If not in C++, shall we translate to the C equivalent of
1010  // wchar_t?
1011  return Importer.getToContext().WCharTy;
1012  }
1013 
1014  llvm_unreachable("Invalid BuiltinType Kind!");
1015 }
1016 
1018  ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1019  if (!ToOriginalTypeOrErr)
1020  return ToOriginalTypeOrErr.takeError();
1021 
1022  return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1023 }
1024 
1026  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1027  if (!ToElementTypeOrErr)
1028  return ToElementTypeOrErr.takeError();
1029 
1030  return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1031 }
1032 
1034  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1035  if (!ToPointeeTypeOrErr)
1036  return ToPointeeTypeOrErr.takeError();
1037 
1038  return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1039 }
1040 
1042  // FIXME: Check for blocks support in "to" context.
1043  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1044  if (!ToPointeeTypeOrErr)
1045  return ToPointeeTypeOrErr.takeError();
1046 
1047  return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1048 }
1049 
1052  // FIXME: Check for C++ support in "to" context.
1053  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1054  if (!ToPointeeTypeOrErr)
1055  return ToPointeeTypeOrErr.takeError();
1056 
1057  return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1058 }
1059 
1062  // FIXME: Check for C++0x support in "to" context.
1063  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1064  if (!ToPointeeTypeOrErr)
1065  return ToPointeeTypeOrErr.takeError();
1066 
1067  return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1068 }
1069 
1072  // FIXME: Check for C++ support in "to" context.
1073  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1074  if (!ToPointeeTypeOrErr)
1075  return ToPointeeTypeOrErr.takeError();
1076 
1077  ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1078  if (!ClassTypeOrErr)
1079  return ClassTypeOrErr.takeError();
1080 
1081  return Importer.getToContext().getMemberPointerType(
1082  *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1083 }
1084 
1087  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1088  if (!ToElementTypeOrErr)
1089  return ToElementTypeOrErr.takeError();
1090 
1091  return Importer.getToContext().getConstantArrayType(*ToElementTypeOrErr,
1092  T->getSize(),
1093  T->getSizeModifier(),
1095 }
1096 
1099  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1100  if (!ToElementTypeOrErr)
1101  return ToElementTypeOrErr.takeError();
1102 
1103  return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1104  T->getSizeModifier(),
1106 }
1107 
1110  QualType ToElementType;
1111  Expr *ToSizeExpr;
1112  SourceRange ToBracketsRange;
1113  if (auto Imp = importSeq(
1114  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1115  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1116  else
1117  return Imp.takeError();
1118 
1119  return Importer.getToContext().getVariableArrayType(
1120  ToElementType, ToSizeExpr, T->getSizeModifier(),
1121  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1122 }
1123 
1125  const DependentSizedArrayType *T) {
1126  QualType ToElementType;
1127  Expr *ToSizeExpr;
1128  SourceRange ToBracketsRange;
1129  if (auto Imp = importSeq(
1130  T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1131  std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1132  else
1133  return Imp.takeError();
1134  // SizeExpr may be null if size is not specified directly.
1135  // For example, 'int a[]'.
1136 
1137  return Importer.getToContext().getDependentSizedArrayType(
1138  ToElementType, ToSizeExpr, T->getSizeModifier(),
1139  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1140 }
1141 
1143  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1144  if (!ToElementTypeOrErr)
1145  return ToElementTypeOrErr.takeError();
1146 
1147  return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1148  T->getNumElements(),
1149  T->getVectorKind());
1150 }
1151 
1153  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1154  if (!ToElementTypeOrErr)
1155  return ToElementTypeOrErr.takeError();
1156 
1157  return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1158  T->getNumElements());
1159 }
1160 
1163  // FIXME: What happens if we're importing a function without a prototype
1164  // into C++? Should we make it variadic?
1165  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1166  if (!ToReturnTypeOrErr)
1167  return ToReturnTypeOrErr.takeError();
1168 
1169  return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1170  T->getExtInfo());
1171 }
1172 
1175  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1176  if (!ToReturnTypeOrErr)
1177  return ToReturnTypeOrErr.takeError();
1178 
1179  // Import argument types
1180  SmallVector<QualType, 4> ArgTypes;
1181  for (const auto &A : T->param_types()) {
1182  ExpectedType TyOrErr = import(A);
1183  if (!TyOrErr)
1184  return TyOrErr.takeError();
1185  ArgTypes.push_back(*TyOrErr);
1186  }
1187 
1188  // Import exception types
1189  SmallVector<QualType, 4> ExceptionTypes;
1190  for (const auto &E : T->exceptions()) {
1191  ExpectedType TyOrErr = import(E);
1192  if (!TyOrErr)
1193  return TyOrErr.takeError();
1194  ExceptionTypes.push_back(*TyOrErr);
1195  }
1196 
1199 
1200  auto Imp = importSeq(
1201  FromEPI.ExceptionSpec.NoexceptExpr,
1202  FromEPI.ExceptionSpec.SourceDecl,
1203  FromEPI.ExceptionSpec.SourceTemplate);
1204  if (!Imp)
1205  return Imp.takeError();
1206 
1207  ToEPI.ExtInfo = FromEPI.ExtInfo;
1208  ToEPI.Variadic = FromEPI.Variadic;
1209  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1210  ToEPI.TypeQuals = FromEPI.TypeQuals;
1211  ToEPI.RefQualifier = FromEPI.RefQualifier;
1212  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1213  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1214  std::tie(
1216  ToEPI.ExceptionSpec.SourceDecl,
1217  ToEPI.ExceptionSpec.SourceTemplate) = *Imp;
1218 
1219  return Importer.getToContext().getFunctionType(
1220  *ToReturnTypeOrErr, ArgTypes, ToEPI);
1221 }
1222 
1224  const UnresolvedUsingType *T) {
1226  Decl *ToPrevD;
1227  if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl()))
1228  std::tie(ToD, ToPrevD) = *Imp;
1229  else
1230  return Imp.takeError();
1231 
1232  return Importer.getToContext().getTypeDeclType(
1233  ToD, cast_or_null<TypeDecl>(ToPrevD));
1234 }
1235 
1237  ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1238  if (!ToInnerTypeOrErr)
1239  return ToInnerTypeOrErr.takeError();
1240 
1241  return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1242 }
1243 
1245  Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1246  if (!ToDeclOrErr)
1247  return ToDeclOrErr.takeError();
1248 
1249  return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1250 }
1251 
1253  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1254  if (!ToExprOrErr)
1255  return ToExprOrErr.takeError();
1256 
1257  return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1258 }
1259 
1261  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1262  if (!ToUnderlyingTypeOrErr)
1263  return ToUnderlyingTypeOrErr.takeError();
1264 
1265  return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1266 }
1267 
1269  // FIXME: Make sure that the "to" context supports C++0x!
1270  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1271  if (!ToExprOrErr)
1272  return ToExprOrErr.takeError();
1273 
1274  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1275  if (!ToUnderlyingTypeOrErr)
1276  return ToUnderlyingTypeOrErr.takeError();
1277 
1278  return Importer.getToContext().getDecltypeType(
1279  *ToExprOrErr, *ToUnderlyingTypeOrErr);
1280 }
1281 
1284  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1285  if (!ToBaseTypeOrErr)
1286  return ToBaseTypeOrErr.takeError();
1287 
1288  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1289  if (!ToUnderlyingTypeOrErr)
1290  return ToUnderlyingTypeOrErr.takeError();
1291 
1292  return Importer.getToContext().getUnaryTransformType(
1293  *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1294 }
1295 
1297  // FIXME: Make sure that the "to" context supports C++11!
1298  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1299  if (!ToDeducedTypeOrErr)
1300  return ToDeducedTypeOrErr.takeError();
1301 
1302  return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr,
1303  T->getKeyword(),
1304  /*IsDependent*/false);
1305 }
1306 
1308  const InjectedClassNameType *T) {
1309  Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1310  if (!ToDeclOrErr)
1311  return ToDeclOrErr.takeError();
1312 
1313  ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1314  if (!ToInjTypeOrErr)
1315  return ToInjTypeOrErr.takeError();
1316 
1317  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1318  // See comments in InjectedClassNameType definition for details
1319  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1320  enum {
1321  TypeAlignmentInBits = 4,
1323  };
1324 
1325  return QualType(new (Importer.getToContext(), TypeAlignment)
1326  InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1327 }
1328 
1330  Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1331  if (!ToDeclOrErr)
1332  return ToDeclOrErr.takeError();
1333 
1334  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1335 }
1336 
1338  Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1339  if (!ToDeclOrErr)
1340  return ToDeclOrErr.takeError();
1341 
1342  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1343 }
1344 
1346  ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1347  if (!ToModifiedTypeOrErr)
1348  return ToModifiedTypeOrErr.takeError();
1349  ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1350  if (!ToEquivalentTypeOrErr)
1351  return ToEquivalentTypeOrErr.takeError();
1352 
1353  return Importer.getToContext().getAttributedType(T->getAttrKind(),
1354  *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1355 }
1356 
1358  const TemplateTypeParmType *T) {
1359  Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1360  if (!ToDeclOrErr)
1361  return ToDeclOrErr.takeError();
1362 
1363  return Importer.getToContext().getTemplateTypeParmType(
1364  T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1365 }
1366 
1368  const SubstTemplateTypeParmType *T) {
1369  ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1370  if (!ReplacedOrErr)
1371  return ReplacedOrErr.takeError();
1372  const TemplateTypeParmType *Replaced =
1373  cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1374 
1375  ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1376  if (!ToReplacementTypeOrErr)
1377  return ToReplacementTypeOrErr.takeError();
1378 
1379  return Importer.getToContext().getSubstTemplateTypeParmType(
1380  Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1381 }
1382 
1384  const TemplateSpecializationType *T) {
1385  auto ToTemplateOrErr = import(T->getTemplateName());
1386  if (!ToTemplateOrErr)
1387  return ToTemplateOrErr.takeError();
1388 
1389  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1390  if (Error Err = ImportTemplateArguments(
1391  T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1392  return std::move(Err);
1393 
1394  QualType ToCanonType;
1395  if (!QualType(T, 0).isCanonical()) {
1396  QualType FromCanonType
1397  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1398  if (ExpectedType TyOrErr = import(FromCanonType))
1399  ToCanonType = *TyOrErr;
1400  else
1401  return TyOrErr.takeError();
1402  }
1403  return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1404  ToTemplateArgs,
1405  ToCanonType);
1406 }
1407 
1409  // Note: the qualifier in an ElaboratedType is optional.
1410  auto ToQualifierOrErr = import(T->getQualifier());
1411  if (!ToQualifierOrErr)
1412  return ToQualifierOrErr.takeError();
1413 
1414  ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1415  if (!ToNamedTypeOrErr)
1416  return ToNamedTypeOrErr.takeError();
1417 
1418  Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1419  if (!ToOwnedTagDeclOrErr)
1420  return ToOwnedTagDeclOrErr.takeError();
1421 
1422  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1423  *ToQualifierOrErr,
1424  *ToNamedTypeOrErr,
1425  *ToOwnedTagDeclOrErr);
1426 }
1427 
1430  ExpectedType ToPatternOrErr = import(T->getPattern());
1431  if (!ToPatternOrErr)
1432  return ToPatternOrErr.takeError();
1433 
1434  return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1435  T->getNumExpansions());
1436 }
1437 
1440  auto ToQualifierOrErr = import(T->getQualifier());
1441  if (!ToQualifierOrErr)
1442  return ToQualifierOrErr.takeError();
1443 
1444  IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1445 
1447  ToPack.reserve(T->getNumArgs());
1448  if (Error Err = ImportTemplateArguments(
1449  T->getArgs(), T->getNumArgs(), ToPack))
1450  return std::move(Err);
1451 
1452  return Importer.getToContext().getDependentTemplateSpecializationType(
1453  T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1454 }
1455 
1458  auto ToQualifierOrErr = import(T->getQualifier());
1459  if (!ToQualifierOrErr)
1460  return ToQualifierOrErr.takeError();
1461 
1462  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1463 
1464  QualType Canon;
1465  if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1466  if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1467  Canon = (*TyOrErr).getCanonicalType();
1468  else
1469  return TyOrErr.takeError();
1470  }
1471 
1472  return Importer.getToContext().getDependentNameType(T->getKeyword(),
1473  *ToQualifierOrErr,
1474  Name, Canon);
1475 }
1476 
1479  Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1480  if (!ToDeclOrErr)
1481  return ToDeclOrErr.takeError();
1482 
1483  return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1484 }
1485 
1487  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1488  if (!ToBaseTypeOrErr)
1489  return ToBaseTypeOrErr.takeError();
1490 
1491  SmallVector<QualType, 4> TypeArgs;
1492  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1493  if (ExpectedType TyOrErr = import(TypeArg))
1494  TypeArgs.push_back(*TyOrErr);
1495  else
1496  return TyOrErr.takeError();
1497  }
1498 
1500  for (auto *P : T->quals()) {
1501  if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1502  Protocols.push_back(*ProtocolOrErr);
1503  else
1504  return ProtocolOrErr.takeError();
1505 
1506  }
1507 
1508  return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1509  Protocols,
1510  T->isKindOfTypeAsWritten());
1511 }
1512 
1515  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1516  if (!ToPointeeTypeOrErr)
1517  return ToPointeeTypeOrErr.takeError();
1518 
1519  return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1520 }
1521 
1522 //----------------------------------------------------------------------------
1523 // Import Declarations
1524 //----------------------------------------------------------------------------
1526  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1527  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1528  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1529  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1530  DeclContext *OrigDC = D->getDeclContext();
1531  FunctionDecl *FunDecl;
1532  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1533  FunDecl->hasBody()) {
1534  auto getLeafPointeeType = [](const Type *T) {
1535  while (T->isPointerType() || T->isArrayType()) {
1536  T = T->getPointeeOrArrayElementType();
1537  }
1538  return T;
1539  };
1540  for (const ParmVarDecl *P : FunDecl->parameters()) {
1541  const Type *LeafT =
1542  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1543  auto *RT = dyn_cast<RecordType>(LeafT);
1544  if (RT && RT->getDecl() == D) {
1545  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1546  << D->getDeclKindName();
1547  return make_error<ImportError>(ImportError::UnsupportedConstruct);
1548  }
1549  }
1550  }
1551 
1552  // Import the context of this declaration.
1553  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1554  return Err;
1555 
1556  // Import the name of this declaration.
1557  if (Error Err = importInto(Name, D->getDeclName()))
1558  return Err;
1559 
1560  // Import the location of this declaration.
1561  if (Error Err = importInto(Loc, D->getLocation()))
1562  return Err;
1563 
1564  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1565  if (ToD)
1566  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1567  return Err;
1568 
1569  return Error::success();
1570 }
1571 
1573  if (!FromD)
1574  return Error::success();
1575 
1576  if (!ToD)
1577  if (Error Err = importInto(ToD, FromD))
1578  return Err;
1579 
1580  if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1581  if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1582  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1583  !ToRecord->getDefinition()) {
1584  if (Error Err = ImportDefinition(FromRecord, ToRecord))
1585  return Err;
1586  }
1587  }
1588  return Error::success();
1589  }
1590 
1591  if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1592  if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1593  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1594  if (Error Err = ImportDefinition(FromEnum, ToEnum))
1595  return Err;
1596  }
1597  }
1598  return Error::success();
1599  }
1600 
1601  return Error::success();
1602 }
1603 
1604 Error
1606  const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1607  // NOTE: To.Name and To.Loc are already imported.
1608  // We only have to import To.LocInfo.
1609  switch (To.getName().getNameKind()) {
1616  return Error::success();
1617 
1619  if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1620  To.setCXXOperatorNameRange(*ToRangeOrErr);
1621  else
1622  return ToRangeOrErr.takeError();
1623  return Error::success();
1624  }
1626  if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1627  To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1628  else
1629  return LocOrErr.takeError();
1630  return Error::success();
1631  }
1635  if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1636  To.setNamedTypeInfo(*ToTInfoOrErr);
1637  else
1638  return ToTInfoOrErr.takeError();
1639  return Error::success();
1640  }
1641  }
1642  llvm_unreachable("Unknown name kind.");
1643 }
1644 
1645 Error
1647  if (Importer.isMinimalImport() && !ForceImport) {
1648  auto ToDCOrErr = Importer.ImportContext(FromDC);
1649  return ToDCOrErr.takeError();
1650  }
1651  llvm::SmallVector<Decl *, 8> ImportedDecls;
1652  for (auto *From : FromDC->decls()) {
1653  ExpectedDecl ImportedOrErr = import(From);
1654  if (!ImportedOrErr)
1655  // Ignore the error, continue with next Decl.
1656  // FIXME: Handle this case somehow better.
1657  consumeError(ImportedOrErr.takeError());
1658  }
1659 
1660  return Error::success();
1661 }
1662 
1664  Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1665  auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1666  if (!ToDCOrErr)
1667  return ToDCOrErr.takeError();
1668  ToDC = *ToDCOrErr;
1669 
1670  if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1671  auto ToLexicalDCOrErr = Importer.ImportContext(
1672  FromD->getLexicalDeclContext());
1673  if (!ToLexicalDCOrErr)
1674  return ToLexicalDCOrErr.takeError();
1675  ToLexicalDC = *ToLexicalDCOrErr;
1676  } else
1677  ToLexicalDC = ToDC;
1678 
1679  return Error::success();
1680 }
1681 
1683  const CXXRecordDecl *From, CXXRecordDecl *To) {
1684  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1685  "Import implicit methods to or from non-definition");
1686 
1687  for (CXXMethodDecl *FromM : From->methods())
1688  if (FromM->isImplicit()) {
1689  Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1690  if (!ToMOrErr)
1691  return ToMOrErr.takeError();
1692  }
1693 
1694  return Error::success();
1695 }
1696 
1698  ASTImporter &Importer) {
1699  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1700  Decl *ToTypedef = Importer.Import(FromTypedef);
1701  if (!ToTypedef)
1702  return make_error<ImportError>();
1703  To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(ToTypedef));
1704  // FIXME: This should be the final code.
1705  //if (Expected<Decl *> ToTypedefOrErr = Importer.Import(FromTypedef))
1706  // To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1707  //else
1708  // return ToTypedefOrErr.takeError();
1709  }
1710  return Error::success();
1711 }
1712 
1715  if (To->getDefinition() || To->isBeingDefined()) {
1716  if (Kind == IDK_Everything)
1717  return ImportDeclContext(From, /*ForceImport=*/true);
1718 
1719  return Error::success();
1720  }
1721 
1722  To->startDefinition();
1723 
1724  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1725  return Err;
1726 
1727  // Add base classes.
1728  auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1729  auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1730  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1731 
1732  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1733  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1734  ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1735  ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1736  ToData.Aggregate = FromData.Aggregate;
1737  ToData.PlainOldData = FromData.PlainOldData;
1738  ToData.Empty = FromData.Empty;
1739  ToData.Polymorphic = FromData.Polymorphic;
1740  ToData.Abstract = FromData.Abstract;
1741  ToData.IsStandardLayout = FromData.IsStandardLayout;
1742  ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1743  ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1744  ToData.HasBasesWithNonStaticDataMembers =
1745  FromData.HasBasesWithNonStaticDataMembers;
1746  ToData.HasPrivateFields = FromData.HasPrivateFields;
1747  ToData.HasProtectedFields = FromData.HasProtectedFields;
1748  ToData.HasPublicFields = FromData.HasPublicFields;
1749  ToData.HasMutableFields = FromData.HasMutableFields;
1750  ToData.HasVariantMembers = FromData.HasVariantMembers;
1751  ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1752  ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1753  ToData.HasUninitializedReferenceMember
1754  = FromData.HasUninitializedReferenceMember;
1755  ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1756  ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1757  ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1758  ToData.NeedOverloadResolutionForCopyConstructor
1759  = FromData.NeedOverloadResolutionForCopyConstructor;
1760  ToData.NeedOverloadResolutionForMoveConstructor
1761  = FromData.NeedOverloadResolutionForMoveConstructor;
1762  ToData.NeedOverloadResolutionForMoveAssignment
1763  = FromData.NeedOverloadResolutionForMoveAssignment;
1764  ToData.NeedOverloadResolutionForDestructor
1765  = FromData.NeedOverloadResolutionForDestructor;
1766  ToData.DefaultedCopyConstructorIsDeleted
1767  = FromData.DefaultedCopyConstructorIsDeleted;
1768  ToData.DefaultedMoveConstructorIsDeleted
1769  = FromData.DefaultedMoveConstructorIsDeleted;
1770  ToData.DefaultedMoveAssignmentIsDeleted
1771  = FromData.DefaultedMoveAssignmentIsDeleted;
1772  ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1773  ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1774  ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1775  ToData.HasConstexprNonCopyMoveConstructor
1776  = FromData.HasConstexprNonCopyMoveConstructor;
1777  ToData.HasDefaultedDefaultConstructor
1778  = FromData.HasDefaultedDefaultConstructor;
1779  ToData.DefaultedDefaultConstructorIsConstexpr
1780  = FromData.DefaultedDefaultConstructorIsConstexpr;
1781  ToData.HasConstexprDefaultConstructor
1782  = FromData.HasConstexprDefaultConstructor;
1783  ToData.HasNonLiteralTypeFieldsOrBases
1784  = FromData.HasNonLiteralTypeFieldsOrBases;
1785  // ComputedVisibleConversions not imported.
1786  ToData.UserProvidedDefaultConstructor
1787  = FromData.UserProvidedDefaultConstructor;
1788  ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1789  ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1790  = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1791  ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1792  = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1793  ToData.ImplicitCopyAssignmentHasConstParam
1794  = FromData.ImplicitCopyAssignmentHasConstParam;
1795  ToData.HasDeclaredCopyConstructorWithConstParam
1796  = FromData.HasDeclaredCopyConstructorWithConstParam;
1797  ToData.HasDeclaredCopyAssignmentWithConstParam
1798  = FromData.HasDeclaredCopyAssignmentWithConstParam;
1799 
1801  for (const auto &Base1 : FromCXX->bases()) {
1802  ExpectedType TyOrErr = import(Base1.getType());
1803  if (!TyOrErr)
1804  return TyOrErr.takeError();
1805 
1806  SourceLocation EllipsisLoc;
1807  if (Base1.isPackExpansion()) {
1808  if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1809  EllipsisLoc = *LocOrErr;
1810  else
1811  return LocOrErr.takeError();
1812  }
1813 
1814  // Ensure that we have a definition for the base.
1815  if (Error Err =
1816  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1817  return Err;
1818 
1819  auto RangeOrErr = import(Base1.getSourceRange());
1820  if (!RangeOrErr)
1821  return RangeOrErr.takeError();
1822 
1823  auto TSIOrErr = import(Base1.getTypeSourceInfo());
1824  if (!TSIOrErr)
1825  return TSIOrErr.takeError();
1826 
1827  Bases.push_back(
1828  new (Importer.getToContext()) CXXBaseSpecifier(
1829  *RangeOrErr,
1830  Base1.isVirtual(),
1831  Base1.isBaseOfClass(),
1832  Base1.getAccessSpecifierAsWritten(),
1833  *TSIOrErr,
1834  EllipsisLoc));
1835  }
1836  if (!Bases.empty())
1837  ToCXX->setBases(Bases.data(), Bases.size());
1838  }
1839 
1840  if (shouldForceImportDeclContext(Kind))
1841  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1842  return Err;
1843 
1844  To->completeDefinition();
1845  return Error::success();
1846 }
1847 
1849  if (To->getAnyInitializer())
1850  return Error::success();
1851 
1852  Expr *FromInit = From->getInit();
1853  if (!FromInit)
1854  return Error::success();
1855 
1856  ExpectedExpr ToInitOrErr = import(FromInit);
1857  if (!ToInitOrErr)
1858  return ToInitOrErr.takeError();
1859 
1860  To->setInit(*ToInitOrErr);
1861  if (From->isInitKnownICE()) {
1862  EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1863  Eval->CheckedICE = true;
1864  Eval->IsICE = From->isInitICE();
1865  }
1866 
1867  // FIXME: Other bits to merge?
1868  return Error::success();
1869 }
1870 
1873  if (To->getDefinition() || To->isBeingDefined()) {
1874  if (Kind == IDK_Everything)
1875  return ImportDeclContext(From, /*ForceImport=*/true);
1876  return Error::success();
1877  }
1878 
1879  To->startDefinition();
1880 
1881  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1882  return Err;
1883 
1884  ExpectedType ToTypeOrErr =
1885  import(Importer.getFromContext().getTypeDeclType(From));
1886  if (!ToTypeOrErr)
1887  return ToTypeOrErr.takeError();
1888 
1889  ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
1890  if (!ToPromotionTypeOrErr)
1891  return ToPromotionTypeOrErr.takeError();
1892 
1893  if (shouldForceImportDeclContext(Kind))
1894  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1895  return Err;
1896 
1897  // FIXME: we might need to merge the number of positive or negative bits
1898  // if the enumerator lists don't match.
1899  To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
1900  From->getNumPositiveBits(),
1901  From->getNumNegativeBits());
1902  return Error::success();
1903 }
1904 
1905 // FIXME: Remove this, use `import` instead.
1907  TemplateParameterList *Params) {
1908  SmallVector<NamedDecl *, 4> ToParams(Params->size());
1909  if (Error Err = ImportContainerChecked(*Params, ToParams))
1910  return std::move(Err);
1911 
1912  Expr *ToRequiresClause;
1913  if (Expr *const R = Params->getRequiresClause()) {
1914  if (Error Err = importInto(ToRequiresClause, R))
1915  return std::move(Err);
1916  } else {
1917  ToRequiresClause = nullptr;
1918  }
1919 
1920  auto ToTemplateLocOrErr = import(Params->getTemplateLoc());
1921  if (!ToTemplateLocOrErr)
1922  return ToTemplateLocOrErr.takeError();
1923  auto ToLAngleLocOrErr = import(Params->getLAngleLoc());
1924  if (!ToLAngleLocOrErr)
1925  return ToLAngleLocOrErr.takeError();
1926  auto ToRAngleLocOrErr = import(Params->getRAngleLoc());
1927  if (!ToRAngleLocOrErr)
1928  return ToRAngleLocOrErr.takeError();
1929 
1931  Importer.getToContext(),
1932  *ToTemplateLocOrErr,
1933  *ToLAngleLocOrErr,
1934  ToParams,
1935  *ToRAngleLocOrErr,
1936  ToRequiresClause);
1937 }
1938 
1940  const TemplateArgument *FromArgs, unsigned NumFromArgs,
1942  for (unsigned I = 0; I != NumFromArgs; ++I) {
1943  if (auto ToOrErr = import(FromArgs[I]))
1944  ToArgs.push_back(*ToOrErr);
1945  else
1946  return ToOrErr.takeError();
1947  }
1948 
1949  return Error::success();
1950 }
1951 
1952 // FIXME: Do not forget to remove this and use only 'import'.
1955  return import(From);
1956 }
1957 
1958 template <typename InContainerTy>
1960  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1961  for (const auto &FromLoc : Container) {
1962  if (auto ToLocOrErr = import(FromLoc))
1963  ToTAInfo.addArgument(*ToLocOrErr);
1964  else
1965  return ToLocOrErr.takeError();
1966  }
1967  return Error::success();
1968 }
1969 
1974 }
1975 
1976 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1978  Importer.getFromContext(), Importer.getToContext(),
1979  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1980  false, Complain);
1981  return Ctx.IsEquivalent(From, To);
1982 }
1983 
1985  RecordDecl *ToRecord, bool Complain) {
1986  // Eliminate a potential failure point where we attempt to re-import
1987  // something we're trying to import while completing ToRecord.
1988  Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1989  if (ToOrigin) {
1990  auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1991  if (ToOriginRecord)
1992  ToRecord = ToOriginRecord;
1993  }
1994 
1995  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1996  ToRecord->getASTContext(),
1997  Importer.getNonEquivalentDecls(),
1998  getStructuralEquivalenceKind(Importer),
1999  false, Complain);
2000  return Ctx.IsEquivalent(FromRecord, ToRecord);
2001 }
2002 
2004  bool Complain) {
2006  Importer.getFromContext(), Importer.getToContext(),
2007  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2008  false, Complain);
2009  return Ctx.IsEquivalent(FromVar, ToVar);
2010 }
2011 
2014  Importer.getFromContext(), Importer.getToContext(),
2015  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2016  return Ctx.IsEquivalent(FromEnum, ToEnum);
2017 }
2018 
2020  FunctionTemplateDecl *To) {
2022  Importer.getFromContext(), Importer.getToContext(),
2023  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2024  false, false);
2025  return Ctx.IsEquivalent(From, To);
2026 }
2027 
2030  Importer.getFromContext(), Importer.getToContext(),
2031  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2032  false, false);
2033  return Ctx.IsEquivalent(From, To);
2034 }
2035 
2037  EnumConstantDecl *ToEC) {
2038  const llvm::APSInt &FromVal = FromEC->getInitVal();
2039  const llvm::APSInt &ToVal = ToEC->getInitVal();
2040 
2041  return FromVal.isSigned() == ToVal.isSigned() &&
2042  FromVal.getBitWidth() == ToVal.getBitWidth() &&
2043  FromVal == ToVal;
2044 }
2045 
2047  ClassTemplateDecl *To) {
2048  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2049  Importer.getToContext(),
2050  Importer.getNonEquivalentDecls(),
2051  getStructuralEquivalenceKind(Importer));
2052  return Ctx.IsEquivalent(From, To);
2053 }
2054 
2056  VarTemplateDecl *To) {
2057  StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2058  Importer.getToContext(),
2059  Importer.getNonEquivalentDecls(),
2060  getStructuralEquivalenceKind(Importer));
2061  return Ctx.IsEquivalent(From, To);
2062 }
2063 
2065  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2066  << D->getDeclKindName();
2067  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2068 }
2069 
2071  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2072  << D->getDeclKindName();
2073  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2074 }
2075 
2077  // Import the context of this declaration.
2078  DeclContext *DC, *LexicalDC;
2079  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2080  return std::move(Err);
2081 
2082  // Import the location of this declaration.
2083  ExpectedSLoc LocOrErr = import(D->getLocation());
2084  if (!LocOrErr)
2085  return LocOrErr.takeError();
2086 
2087  EmptyDecl *ToD;
2088  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2089  return ToD;
2090 
2091  ToD->setLexicalDeclContext(LexicalDC);
2092  LexicalDC->addDeclInternal(ToD);
2093  return ToD;
2094 }
2095 
2097  TranslationUnitDecl *ToD =
2098  Importer.getToContext().getTranslationUnitDecl();
2099 
2100  Importer.MapImported(D, ToD);
2101 
2102  return ToD;
2103 }
2104 
2106  ExpectedSLoc LocOrErr = import(D->getLocation());
2107  if (!LocOrErr)
2108  return LocOrErr.takeError();
2109  auto ColonLocOrErr = import(D->getColonLoc());
2110  if (!ColonLocOrErr)
2111  return ColonLocOrErr.takeError();
2112 
2113  // Import the context of this declaration.
2114  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2115  if (!DCOrErr)
2116  return DCOrErr.takeError();
2117  DeclContext *DC = *DCOrErr;
2118 
2119  AccessSpecDecl *ToD;
2120  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2121  DC, *LocOrErr, *ColonLocOrErr))
2122  return ToD;
2123 
2124  // Lexical DeclContext and Semantic DeclContext
2125  // is always the same for the accessSpec.
2126  ToD->setLexicalDeclContext(DC);
2127  DC->addDeclInternal(ToD);
2128 
2129  return ToD;
2130 }
2131 
2133  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2134  if (!DCOrErr)
2135  return DCOrErr.takeError();
2136  DeclContext *DC = *DCOrErr;
2137  DeclContext *LexicalDC = DC;
2138 
2139  SourceLocation ToLocation, ToRParenLoc;
2140  Expr *ToAssertExpr;
2141  StringLiteral *ToMessage;
2142  if (auto Imp = importSeq(
2143  D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc()))
2144  std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp;
2145  else
2146  return Imp.takeError();
2147 
2148  StaticAssertDecl *ToD;
2149  if (GetImportedOrCreateDecl(
2150  ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2151  ToRParenLoc, D->isFailed()))
2152  return ToD;
2153 
2154  ToD->setLexicalDeclContext(LexicalDC);
2155  LexicalDC->addDeclInternal(ToD);
2156  return ToD;
2157 }
2158 
2160  // Import the major distinguishing characteristics of this namespace.
2161  DeclContext *DC, *LexicalDC;
2162  DeclarationName Name;
2163  SourceLocation Loc;
2164  NamedDecl *ToD;
2165  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2166  return std::move(Err);
2167  if (ToD)
2168  return ToD;
2169 
2170  NamespaceDecl *MergeWithNamespace = nullptr;
2171  if (!Name) {
2172  // This is an anonymous namespace. Adopt an existing anonymous
2173  // namespace if we can.
2174  // FIXME: Not testable.
2175  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2176  MergeWithNamespace = TU->getAnonymousNamespace();
2177  else
2178  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2179  } else {
2180  SmallVector<NamedDecl *, 4> ConflictingDecls;
2181  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2182  for (auto *FoundDecl : FoundDecls) {
2184  continue;
2185 
2186  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2187  MergeWithNamespace = FoundNS;
2188  ConflictingDecls.clear();
2189  break;
2190  }
2191 
2192  ConflictingDecls.push_back(FoundDecl);
2193  }
2194 
2195  if (!ConflictingDecls.empty()) {
2196  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2197  ConflictingDecls.data(),
2198  ConflictingDecls.size());
2199  if (!Name)
2200  return make_error<ImportError>(ImportError::NameConflict);
2201  }
2202  }
2203 
2204  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2205  if (!BeginLocOrErr)
2206  return BeginLocOrErr.takeError();
2207 
2208  // Create the "to" namespace, if needed.
2209  NamespaceDecl *ToNamespace = MergeWithNamespace;
2210  if (!ToNamespace) {
2211  if (GetImportedOrCreateDecl(
2212  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2213  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2214  /*PrevDecl=*/nullptr))
2215  return ToNamespace;
2216  ToNamespace->setLexicalDeclContext(LexicalDC);
2217  LexicalDC->addDeclInternal(ToNamespace);
2218 
2219  // If this is an anonymous namespace, register it as the anonymous
2220  // namespace within its context.
2221  if (!Name) {
2222  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2223  TU->setAnonymousNamespace(ToNamespace);
2224  else
2225  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2226  }
2227  }
2228  Importer.MapImported(D, ToNamespace);
2229 
2230  if (Error Err = ImportDeclContext(D))
2231  return std::move(Err);
2232 
2233  return ToNamespace;
2234 }
2235 
2237  // Import the major distinguishing characteristics of this namespace.
2238  DeclContext *DC, *LexicalDC;
2239  DeclarationName Name;
2240  SourceLocation Loc;
2241  NamedDecl *LookupD;
2242  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2243  return std::move(Err);
2244  if (LookupD)
2245  return LookupD;
2246 
2247  // NOTE: No conflict resolution is done for namespace aliases now.
2248 
2249  SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc;
2250  NestedNameSpecifierLoc ToQualifierLoc;
2251  NamespaceDecl *ToNamespace;
2252  if (auto Imp = importSeq(
2253  D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(),
2254  D->getTargetNameLoc(), D->getNamespace()))
2255  std::tie(
2256  ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc,
2257  ToNamespace) = *Imp;
2258  else
2259  return Imp.takeError();
2260  IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2261 
2262  NamespaceAliasDecl *ToD;
2263  if (GetImportedOrCreateDecl(
2264  ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2265  ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2266  return ToD;
2267 
2268  ToD->setLexicalDeclContext(LexicalDC);
2269  LexicalDC->addDeclInternal(ToD);
2270 
2271  return ToD;
2272 }
2273 
2276  // Import the major distinguishing characteristics of this typedef.
2277  DeclContext *DC, *LexicalDC;
2278  DeclarationName Name;
2279  SourceLocation Loc;
2280  NamedDecl *ToD;
2281  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2282  return std::move(Err);
2283  if (ToD)
2284  return ToD;
2285 
2286  // If this typedef is not in block scope, determine whether we've
2287  // seen a typedef with the same name (that we can merge with) or any
2288  // other entity by that name (which name lookup could conflict with).
2289  if (!DC->isFunctionOrMethod()) {
2290  SmallVector<NamedDecl *, 4> ConflictingDecls;
2291  unsigned IDNS = Decl::IDNS_Ordinary;
2292  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2293  for (auto *FoundDecl : FoundDecls) {
2294  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2295  continue;
2296  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2297  QualType FromUT = D->getUnderlyingType();
2298  QualType FoundUT = FoundTypedef->getUnderlyingType();
2299  if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2300  // If the "From" context has a complete underlying type but we
2301  // already have a complete underlying type then return with that.
2302  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2303  return Importer.MapImported(D, FoundTypedef);
2304  }
2305  // FIXME Handle redecl chain.
2306  break;
2307  }
2308 
2309  ConflictingDecls.push_back(FoundDecl);
2310  }
2311 
2312  if (!ConflictingDecls.empty()) {
2313  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2314  ConflictingDecls.data(),
2315  ConflictingDecls.size());
2316  if (!Name)
2317  return make_error<ImportError>(ImportError::NameConflict);
2318  }
2319  }
2320 
2321  QualType ToUnderlyingType;
2322  TypeSourceInfo *ToTypeSourceInfo;
2323  SourceLocation ToBeginLoc;
2324  if (auto Imp = importSeq(
2326  std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp;
2327  else
2328  return Imp.takeError();
2329 
2330  // Create the new typedef node.
2331  // FIXME: ToUnderlyingType is not used.
2332  TypedefNameDecl *ToTypedef;
2333  if (IsAlias) {
2334  if (GetImportedOrCreateDecl<TypeAliasDecl>(
2335  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2336  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2337  return ToTypedef;
2338  } else if (GetImportedOrCreateDecl<TypedefDecl>(
2339  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2340  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2341  return ToTypedef;
2342 
2343  ToTypedef->setAccess(D->getAccess());
2344  ToTypedef->setLexicalDeclContext(LexicalDC);
2345 
2346  // Templated declarations should not appear in DeclContext.
2347  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2348  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2349  LexicalDC->addDeclInternal(ToTypedef);
2350 
2351  return ToTypedef;
2352 }
2353 
2355  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2356 }
2357 
2359  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2360 }
2361 
2364  // Import the major distinguishing characteristics of this typedef.
2365  DeclContext *DC, *LexicalDC;
2366  DeclarationName Name;
2367  SourceLocation Loc;
2368  NamedDecl *FoundD;
2369  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2370  return std::move(Err);
2371  if (FoundD)
2372  return FoundD;
2373 
2374  // If this typedef is not in block scope, determine whether we've
2375  // seen a typedef with the same name (that we can merge with) or any
2376  // other entity by that name (which name lookup could conflict with).
2377  if (!DC->isFunctionOrMethod()) {
2378  SmallVector<NamedDecl *, 4> ConflictingDecls;
2379  unsigned IDNS = Decl::IDNS_Ordinary;
2380  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2381  for (auto *FoundDecl : FoundDecls) {
2382  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2383  continue;
2384  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2385  return Importer.MapImported(D, FoundAlias);
2386  ConflictingDecls.push_back(FoundDecl);
2387  }
2388 
2389  if (!ConflictingDecls.empty()) {
2390  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2391  ConflictingDecls.data(),
2392  ConflictingDecls.size());
2393  if (!Name)
2394  return make_error<ImportError>(ImportError::NameConflict);
2395  }
2396  }
2397 
2398  TemplateParameterList *ToTemplateParameters;
2399  TypeAliasDecl *ToTemplatedDecl;
2400  if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl()))
2401  std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp;
2402  else
2403  return Imp.takeError();
2404 
2405  TypeAliasTemplateDecl *ToAlias;
2406  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2407  Name, ToTemplateParameters, ToTemplatedDecl))
2408  return ToAlias;
2409 
2410  ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2411 
2412  ToAlias->setAccess(D->getAccess());
2413  ToAlias->setLexicalDeclContext(LexicalDC);
2414  LexicalDC->addDeclInternal(ToAlias);
2415  return ToAlias;
2416 }
2417 
2419  // Import the major distinguishing characteristics of this label.
2420  DeclContext *DC, *LexicalDC;
2421  DeclarationName Name;
2422  SourceLocation Loc;
2423  NamedDecl *ToD;
2424  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2425  return std::move(Err);
2426  if (ToD)
2427  return ToD;
2428 
2429  assert(LexicalDC->isFunctionOrMethod());
2430 
2431  LabelDecl *ToLabel;
2432  if (D->isGnuLocal()) {
2433  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2434  if (!BeginLocOrErr)
2435  return BeginLocOrErr.takeError();
2436  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2437  Name.getAsIdentifierInfo(), *BeginLocOrErr))
2438  return ToLabel;
2439 
2440  } else {
2441  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2442  Name.getAsIdentifierInfo()))
2443  return ToLabel;
2444 
2445  }
2446 
2447  Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2448  if (!ToStmtOrErr)
2449  return ToStmtOrErr.takeError();
2450 
2451  ToLabel->setStmt(*ToStmtOrErr);
2452  ToLabel->setLexicalDeclContext(LexicalDC);
2453  LexicalDC->addDeclInternal(ToLabel);
2454  return ToLabel;
2455 }
2456 
2458  // Import the major distinguishing characteristics of this enum.
2459  DeclContext *DC, *LexicalDC;
2460  DeclarationName Name;
2461  SourceLocation Loc;
2462  NamedDecl *ToD;
2463  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2464  return std::move(Err);
2465  if (ToD)
2466  return ToD;
2467 
2468  // Figure out what enum name we're looking for.
2469  unsigned IDNS = Decl::IDNS_Tag;
2470  DeclarationName SearchName = Name;
2471  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2472  if (Error Err = importInto(
2473  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2474  return std::move(Err);
2475  IDNS = Decl::IDNS_Ordinary;
2476  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2477  IDNS |= Decl::IDNS_Ordinary;
2478 
2479  // We may already have an enum of the same name; try to find and match it.
2480  if (!DC->isFunctionOrMethod() && SearchName) {
2481  SmallVector<NamedDecl *, 4> ConflictingDecls;
2482  auto FoundDecls =
2483  Importer.findDeclsInToCtx(DC, SearchName);
2484  for (auto *FoundDecl : FoundDecls) {
2485  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2486  continue;
2487 
2488  if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2489  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2490  FoundDecl = Tag->getDecl();
2491  }
2492 
2493  if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2494  if (IsStructuralMatch(D, FoundEnum))
2495  return Importer.MapImported(D, FoundEnum);
2496  }
2497 
2498  ConflictingDecls.push_back(FoundDecl);
2499  }
2500 
2501  if (!ConflictingDecls.empty()) {
2502  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2503  ConflictingDecls.data(),
2504  ConflictingDecls.size());
2505  if (!Name)
2506  return make_error<ImportError>(ImportError::NameConflict);
2507  }
2508  }
2509 
2510  SourceLocation ToBeginLoc;
2511  NestedNameSpecifierLoc ToQualifierLoc;
2512  QualType ToIntegerType;
2513  if (auto Imp = importSeq(
2514  D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType()))
2515  std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp;
2516  else
2517  return Imp.takeError();
2518 
2519  // Create the enum declaration.
2520  EnumDecl *D2;
2521  if (GetImportedOrCreateDecl(
2522  D2, D, Importer.getToContext(), DC, ToBeginLoc,
2523  Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2524  D->isScopedUsingClassTag(), D->isFixed()))
2525  return D2;
2526 
2527  D2->setQualifierInfo(ToQualifierLoc);
2528  D2->setIntegerType(ToIntegerType);
2529  D2->setAccess(D->getAccess());
2530  D2->setLexicalDeclContext(LexicalDC);
2531  LexicalDC->addDeclInternal(D2);
2532 
2533  // Import the definition
2534  if (D->isCompleteDefinition())
2535  if (Error Err = ImportDefinition(D, D2))
2536  return std::move(Err);
2537 
2538  return D2;
2539 }
2540 
2542  bool IsFriendTemplate = false;
2543  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2544  IsFriendTemplate =
2545  DCXX->getDescribedClassTemplate() &&
2546  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2548  }
2549 
2550  // If this record has a definition in the translation unit we're coming from,
2551  // but this particular declaration is not that definition, import the
2552  // definition and map to that.
2553  TagDecl *Definition = D->getDefinition();
2554  if (Definition && Definition != D &&
2555  // Friend template declaration must be imported on its own.
2556  !IsFriendTemplate &&
2557  // In contrast to a normal CXXRecordDecl, the implicit
2558  // CXXRecordDecl of ClassTemplateSpecializationDecl is its redeclaration.
2559  // The definition of the implicit CXXRecordDecl in this case is the
2560  // ClassTemplateSpecializationDecl itself. Thus, we start with an extra
2561  // condition in order to be able to import the implict Decl.
2562  !D->isImplicit()) {
2563  ExpectedDecl ImportedDefOrErr = import(Definition);
2564  if (!ImportedDefOrErr)
2565  return ImportedDefOrErr.takeError();
2566 
2567  return Importer.MapImported(D, *ImportedDefOrErr);
2568  }
2569 
2570  // Import the major distinguishing characteristics of this record.
2571  DeclContext *DC, *LexicalDC;
2572  DeclarationName Name;
2573  SourceLocation Loc;
2574  NamedDecl *ToD;
2575  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2576  return std::move(Err);
2577  if (ToD)
2578  return ToD;
2579 
2580  // Figure out what structure name we're looking for.
2581  unsigned IDNS = Decl::IDNS_Tag;
2582  DeclarationName SearchName = Name;
2583  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2584  if (Error Err = importInto(
2585  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2586  return std::move(Err);
2587  IDNS = Decl::IDNS_Ordinary;
2588  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2590 
2591  // We may already have a record of the same name; try to find and match it.
2592  RecordDecl *PrevDecl = nullptr;
2593  if (!DC->isFunctionOrMethod()) {
2594  SmallVector<NamedDecl *, 4> ConflictingDecls;
2595  auto FoundDecls =
2596  Importer.findDeclsInToCtx(DC, SearchName);
2597  if (!FoundDecls.empty()) {
2598  // We're going to have to compare D against potentially conflicting Decls, so complete it.
2601  }
2602 
2603  for (auto *FoundDecl : FoundDecls) {
2604  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2605  continue;
2606 
2607  Decl *Found = FoundDecl;
2608  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2609  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2610  Found = Tag->getDecl();
2611  }
2612 
2613  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2614  // Do not emit false positive diagnostic in case of unnamed
2615  // struct/union and in case of anonymous structs. Would be false
2616  // because there may be several anonymous/unnamed structs in a class.
2617  // E.g. these are both valid:
2618  // struct A { // unnamed structs
2619  // struct { struct A *next; } entry0;
2620  // struct { struct A *next; } entry1;
2621  // };
2622  // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2623  if (!SearchName)
2624  if (!IsStructuralMatch(D, FoundRecord, false))
2625  continue;
2626 
2627  if (IsStructuralMatch(D, FoundRecord)) {
2628  RecordDecl *FoundDef = FoundRecord->getDefinition();
2629  if (D->isThisDeclarationADefinition() && FoundDef) {
2630  // FIXME: Structural equivalence check should check for same
2631  // user-defined methods.
2632  Importer.MapImported(D, FoundDef);
2633  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2634  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2635  assert(FoundCXX && "Record type mismatch");
2636 
2637  if (!Importer.isMinimalImport())
2638  // FoundDef may not have every implicit method that D has
2639  // because implicit methods are created only if they are used.
2640  if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2641  return std::move(Err);
2642  }
2643  }
2644  PrevDecl = FoundRecord->getMostRecentDecl();
2645  break;
2646  }
2647  }
2648 
2649  ConflictingDecls.push_back(FoundDecl);
2650  } // for
2651 
2652  if (!ConflictingDecls.empty() && SearchName) {
2653  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2654  ConflictingDecls.data(),
2655  ConflictingDecls.size());
2656  if (!Name)
2657  return make_error<ImportError>(ImportError::NameConflict);
2658  }
2659  }
2660 
2661  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2662  if (!BeginLocOrErr)
2663  return BeginLocOrErr.takeError();
2664 
2665  // Create the record declaration.
2666  RecordDecl *D2 = nullptr;
2667  CXXRecordDecl *D2CXX = nullptr;
2668  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2669  if (DCXX->isLambda()) {
2670  auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2671  if (!TInfoOrErr)
2672  return TInfoOrErr.takeError();
2673  if (GetImportedOrCreateSpecialDecl(
2674  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2675  DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2676  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2677  return D2CXX;
2678  ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2679  if (!CDeclOrErr)
2680  return CDeclOrErr.takeError();
2681  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr);
2682  } else if (DCXX->isInjectedClassName()) {
2683  // We have to be careful to do a similar dance to the one in
2684  // Sema::ActOnStartCXXMemberDeclarations
2685  const bool DelayTypeCreation = true;
2686  if (GetImportedOrCreateDecl(
2687  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2688  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2689  cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2690  return D2CXX;
2691  Importer.getToContext().getTypeDeclType(
2692  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2693  } else {
2694  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2695  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2696  Name.getAsIdentifierInfo(),
2697  cast_or_null<CXXRecordDecl>(PrevDecl)))
2698  return D2CXX;
2699  }
2700 
2701  D2 = D2CXX;
2702  D2->setAccess(D->getAccess());
2703  D2->setLexicalDeclContext(LexicalDC);
2704  if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2705  LexicalDC->addDeclInternal(D2);
2706 
2707  if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend))
2708  DC->makeDeclVisibleInContext(D2);
2709 
2710  if (ClassTemplateDecl *FromDescribed =
2711  DCXX->getDescribedClassTemplate()) {
2712  ClassTemplateDecl *ToDescribed;
2713  if (Error Err = importInto(ToDescribed, FromDescribed))
2714  return std::move(Err);
2715  D2CXX->setDescribedClassTemplate(ToDescribed);
2716  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2717  // In a record describing a template the type should be an
2718  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2719  // previously set type to the correct value here (ToDescribed is not
2720  // available at record create).
2721  // FIXME: The previous type is cleared but not removed from
2722  // ASTContext's internal storage.
2723  CXXRecordDecl *Injected = nullptr;
2724  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2725  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2726  if (Record && Record->isInjectedClassName()) {
2727  Injected = Record;
2728  break;
2729  }
2730  }
2731  // Create an injected type for the whole redecl chain.
2732  SmallVector<Decl *, 2> Redecls =
2734  for (auto *R : Redecls) {
2735  auto *RI = cast<CXXRecordDecl>(R);
2736  RI->setTypeForDecl(nullptr);
2737  // Below we create a new injected type and assign that to the
2738  // canonical decl, subsequent declarations in the chain will reuse
2739  // that type.
2740  Importer.getToContext().getInjectedClassNameType(
2741  RI, ToDescribed->getInjectedClassNameSpecialization());
2742  }
2743  // Set the new type for the previous injected decl too.
2744  if (Injected) {
2745  Injected->setTypeForDecl(nullptr);
2746  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2747  }
2748  }
2749  } else if (MemberSpecializationInfo *MemberInfo =
2750  DCXX->getMemberSpecializationInfo()) {
2752  MemberInfo->getTemplateSpecializationKind();
2753  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2754 
2755  if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2756  D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2757  else
2758  return ToInstOrErr.takeError();
2759 
2760  if (ExpectedSLoc POIOrErr =
2761  import(MemberInfo->getPointOfInstantiation()))
2763  *POIOrErr);
2764  else
2765  return POIOrErr.takeError();
2766  }
2767 
2768  } else {
2769  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2770  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2771  Name.getAsIdentifierInfo(), PrevDecl))
2772  return D2;
2773  D2->setLexicalDeclContext(LexicalDC);
2774  LexicalDC->addDeclInternal(D2);
2775  }
2776 
2777  if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2778  D2->setQualifierInfo(*QualifierLocOrErr);
2779  else
2780  return QualifierLocOrErr.takeError();
2781 
2782  if (D->isAnonymousStructOrUnion())
2783  D2->setAnonymousStructOrUnion(true);
2784 
2785  if (D->isCompleteDefinition())
2786  if (Error Err = ImportDefinition(D, D2, IDK_Default))
2787  return std::move(Err);
2788 
2789  return D2;
2790 }
2791 
2793  // Import the major distinguishing characteristics of this enumerator.
2794  DeclContext *DC, *LexicalDC;
2795  DeclarationName Name;
2796  SourceLocation Loc;
2797  NamedDecl *ToD;
2798  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2799  return std::move(Err);
2800  if (ToD)
2801  return ToD;
2802 
2803  // Determine whether there are any other declarations with the same name and
2804  // in the same context.
2805  if (!LexicalDC->isFunctionOrMethod()) {
2806  SmallVector<NamedDecl *, 4> ConflictingDecls;
2807  unsigned IDNS = Decl::IDNS_Ordinary;
2808  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2809  for (auto *FoundDecl : FoundDecls) {
2810  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2811  continue;
2812 
2813  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2814  if (IsStructuralMatch(D, FoundEnumConstant))
2815  return Importer.MapImported(D, FoundEnumConstant);
2816  }
2817 
2818  ConflictingDecls.push_back(FoundDecl);
2819  }
2820 
2821  if (!ConflictingDecls.empty()) {
2822  Name = Importer.HandleNameConflict(Name, DC, IDNS,
2823  ConflictingDecls.data(),
2824  ConflictingDecls.size());
2825  if (!Name)
2826  return make_error<ImportError>(ImportError::NameConflict);
2827  }
2828  }
2829 
2830  ExpectedType TypeOrErr = import(D->getType());
2831  if (!TypeOrErr)
2832  return TypeOrErr.takeError();
2833 
2834  ExpectedExpr InitOrErr = import(D->getInitExpr());
2835  if (!InitOrErr)
2836  return InitOrErr.takeError();
2837 
2838  EnumConstantDecl *ToEnumerator;
2839  if (GetImportedOrCreateDecl(
2840  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2841  Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
2842  return ToEnumerator;
2843 
2844  ToEnumerator->setAccess(D->getAccess());
2845  ToEnumerator->setLexicalDeclContext(LexicalDC);
2846  LexicalDC->addDeclInternal(ToEnumerator);
2847  return ToEnumerator;
2848 }
2849 
2851  FunctionDecl *FromFD, FunctionDecl *ToFD) {
2852  switch (FromFD->getTemplatedKind()) {
2855  return Error::success();
2856 
2859 
2860  if (Expected<FunctionDecl *> InstFDOrErr =
2861  import(FromFD->getInstantiatedFromMemberFunction()))
2862  ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
2863  else
2864  return InstFDOrErr.takeError();
2865 
2866  if (ExpectedSLoc POIOrErr = import(
2869  else
2870  return POIOrErr.takeError();
2871 
2872  return Error::success();
2873  }
2874 
2876  auto FunctionAndArgsOrErr =
2877  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2878  if (!FunctionAndArgsOrErr)
2879  return FunctionAndArgsOrErr.takeError();
2880 
2882  Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
2883 
2884  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2885  TemplateArgumentListInfo ToTAInfo;
2886  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2887  if (FromTAArgsAsWritten)
2888  if (Error Err = ImportTemplateArgumentListInfo(
2889  *FromTAArgsAsWritten, ToTAInfo))
2890  return Err;
2891 
2892  ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
2893  if (!POIOrErr)
2894  return POIOrErr.takeError();
2895 
2896  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2897  ToFD->setFunctionTemplateSpecialization(
2898  std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
2899  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
2900  return Error::success();
2901  }
2902 
2904  auto *FromInfo = FromFD->getDependentSpecializationInfo();
2905  UnresolvedSet<8> TemplDecls;
2906  unsigned NumTemplates = FromInfo->getNumTemplates();
2907  for (unsigned I = 0; I < NumTemplates; I++) {
2908  if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
2909  import(FromInfo->getTemplate(I)))
2910  TemplDecls.addDecl(*ToFTDOrErr);
2911  else
2912  return ToFTDOrErr.takeError();
2913  }
2914 
2915  // Import TemplateArgumentListInfo.
2916  TemplateArgumentListInfo ToTAInfo;
2917  if (Error Err = ImportTemplateArgumentListInfo(
2918  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2919  llvm::makeArrayRef(
2920  FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
2921  ToTAInfo))
2922  return Err;
2923 
2924  ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2925  TemplDecls, ToTAInfo);
2926  return Error::success();
2927  }
2928  }
2929  llvm_unreachable("All cases should be covered!");
2930 }
2931 
2934  auto FunctionAndArgsOrErr =
2935  ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2936  if (!FunctionAndArgsOrErr)
2937  return FunctionAndArgsOrErr.takeError();
2938 
2939  FunctionTemplateDecl *Template;
2940  TemplateArgsTy ToTemplArgs;
2941  std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
2942  void *InsertPos = nullptr;
2943  auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
2944  return FoundSpec;
2945 }
2946 
2948 
2950  auto RedeclIt = Redecls.begin();
2951  // Import the first part of the decl chain. I.e. import all previous
2952  // declarations starting from the canonical decl.
2953  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
2954  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
2955  if (!ToRedeclOrErr)
2956  return ToRedeclOrErr.takeError();
2957  }
2958  assert(*RedeclIt == D);
2959 
2960  // Import the major distinguishing characteristics of this function.
2961  DeclContext *DC, *LexicalDC;
2962  DeclarationName Name;
2963  SourceLocation Loc;
2964  NamedDecl *ToD;
2965  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2966  return std::move(Err);
2967  if (ToD)
2968  return ToD;
2969 
2970  const FunctionDecl *FoundByLookup = nullptr;
2972 
2973  // If this is a function template specialization, then try to find the same
2974  // existing specialization in the "to" context. The lookup below will not
2975  // find any specialization, but would find the primary template; thus, we
2976  // have to skip normal lookup in case of specializations.
2977  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
2978  if (D->getTemplatedKind() ==
2980  auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
2981  if (!FoundFunctionOrErr)
2982  return FoundFunctionOrErr.takeError();
2983  if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
2984  if (D->doesThisDeclarationHaveABody() && FoundFunction->hasBody())
2985  return Importer.MapImported(D, FoundFunction);
2986  FoundByLookup = FoundFunction;
2987  }
2988  }
2989  // Try to find a function in our own ("to") context with the same name, same
2990  // type, and in the same context as the function we're importing.
2991  else if (!LexicalDC->isFunctionOrMethod()) {
2992  SmallVector<NamedDecl *, 4> ConflictingDecls;
2994  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2995  for (auto *FoundDecl : FoundDecls) {
2996  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2997  continue;
2998 
2999  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3000  if (FoundFunction->hasExternalFormalLinkage() &&
3001  D->hasExternalFormalLinkage()) {
3002  if (IsStructuralMatch(D, FoundFunction)) {
3003  const FunctionDecl *Definition = nullptr;
3004  if (D->doesThisDeclarationHaveABody() &&
3005  FoundFunction->hasBody(Definition)) {
3006  return Importer.MapImported(
3007  D, const_cast<FunctionDecl *>(Definition));
3008  }
3009  FoundByLookup = FoundFunction;
3010  break;
3011  }
3012 
3013  // FIXME: Check for overloading more carefully, e.g., by boosting
3014  // Sema::IsOverload out to the AST library.
3015 
3016  // Function overloading is okay in C++.
3017  if (Importer.getToContext().getLangOpts().CPlusPlus)
3018  continue;
3019 
3020  // Complain about inconsistent function types.
3021  Importer.ToDiag(Loc, diag::err_odr_function_type_inconsistent)
3022  << Name << D->getType() << FoundFunction->getType();
3023  Importer.ToDiag(FoundFunction->getLocation(),
3024  diag::note_odr_value_here)
3025  << FoundFunction->getType();
3026  }
3027  }
3028 
3029  ConflictingDecls.push_back(FoundDecl);
3030  }
3031 
3032  if (!ConflictingDecls.empty()) {
3033  Name = Importer.HandleNameConflict(Name, DC, IDNS,
3034  ConflictingDecls.data(),
3035  ConflictingDecls.size());
3036  if (!Name)
3037  return make_error<ImportError>(ImportError::NameConflict);
3038  }
3039  }
3040 
3041  DeclarationNameInfo NameInfo(Name, Loc);
3042  // Import additional name location/type info.
3043  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3044  return std::move(Err);
3045 
3046  QualType FromTy = D->getType();
3047  bool usedDifferentExceptionSpec = false;
3048 
3049  if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3050  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3051  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3052  // FunctionDecl that we are importing the FunctionProtoType for.
3053  // To avoid an infinite recursion when importing, create the FunctionDecl
3054  // with a simplified function type and update it afterwards.
3055  if (FromEPI.ExceptionSpec.SourceDecl ||
3056  FromEPI.ExceptionSpec.SourceTemplate ||
3057  FromEPI.ExceptionSpec.NoexceptExpr) {
3059  FromTy = Importer.getFromContext().getFunctionType(
3060  FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3061  usedDifferentExceptionSpec = true;
3062  }
3063  }
3064 
3065  QualType T;
3066  TypeSourceInfo *TInfo;
3067  SourceLocation ToInnerLocStart, ToEndLoc;
3068  NestedNameSpecifierLoc ToQualifierLoc;
3069  if (auto Imp = importSeq(
3070  FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(),
3071  D->getQualifierLoc(), D->getEndLoc()))
3072  std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp;
3073  else
3074  return Imp.takeError();
3075 
3076  // Import the function parameters.
3077  SmallVector<ParmVarDecl *, 8> Parameters;
3078  for (auto P : D->parameters()) {
3079  if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3080  Parameters.push_back(*ToPOrErr);
3081  else
3082  return ToPOrErr.takeError();
3083  }
3084 
3085  // Create the imported function.
3086  FunctionDecl *ToFunction = nullptr;
3087  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3088  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3089  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3090  ToInnerLocStart, NameInfo, T, TInfo,
3091  FromConstructor->isExplicit(),
3092  D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
3093  return ToFunction;
3094  } else if (isa<CXXDestructorDecl>(D)) {
3095  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3096  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3097  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3098  D->isImplicit()))
3099  return ToFunction;
3100  } else if (CXXConversionDecl *FromConversion =
3101  dyn_cast<CXXConversionDecl>(D)) {
3102  if (GetImportedOrCreateDecl<CXXConversionDecl>(
3103  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3104  ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3105  FromConversion->isExplicit(), D->isConstexpr(), SourceLocation()))
3106  return ToFunction;
3107  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3108  if (GetImportedOrCreateDecl<CXXMethodDecl>(
3109  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3110  ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3111  Method->isInlineSpecified(), D->isConstexpr(), SourceLocation()))
3112  return ToFunction;
3113  } else {
3114  if (GetImportedOrCreateDecl(ToFunction, D, Importer.getToContext(), DC,
3115  ToInnerLocStart, NameInfo, T, TInfo,
3117  D->hasWrittenPrototype(), D->isConstexpr()))
3118  return ToFunction;
3119  }
3120 
3121  // Connect the redecl chain.
3122  if (FoundByLookup) {
3123  auto *Recent = const_cast<FunctionDecl *>(
3124  FoundByLookup->getMostRecentDecl());
3125  ToFunction->setPreviousDecl(Recent);
3126  }
3127 
3128  // Import Ctor initializers.
3129  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3130  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3131  SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3132  // Import first, then allocate memory and copy if there was no error.
3133  if (Error Err = ImportContainerChecked(
3134  FromConstructor->inits(), CtorInitializers))
3135  return std::move(Err);
3136  auto **Memory =
3137  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3138  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3139  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3140  ToCtor->setCtorInitializers(Memory);
3141  ToCtor->setNumCtorInitializers(NumInitializers);
3142  }
3143  }
3144 
3145  ToFunction->setQualifierInfo(ToQualifierLoc);
3146  ToFunction->setAccess(D->getAccess());
3147  ToFunction->setLexicalDeclContext(LexicalDC);
3148  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3149  ToFunction->setTrivial(D->isTrivial());
3150  ToFunction->setPure(D->isPure());
3151  ToFunction->setRangeEnd(ToEndLoc);
3152 
3153  // Set the parameters.
3154  for (auto *Param : Parameters) {
3155  Param->setOwningFunction(ToFunction);
3156  ToFunction->addDeclInternal(Param);
3157  }
3158  ToFunction->setParams(Parameters);
3159 
3160  // We need to complete creation of FunctionProtoTypeLoc manually with setting
3161  // params it refers to.
3162  if (TInfo) {
3163  if (auto ProtoLoc =
3165  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3166  ProtoLoc.setParam(I, Parameters[I]);
3167  }
3168  }
3169 
3170  if (usedDifferentExceptionSpec) {
3171  // Update FunctionProtoType::ExtProtoInfo.
3172  if (ExpectedType TyOrErr = import(D->getType()))
3173  ToFunction->setType(*TyOrErr);
3174  else
3175  return TyOrErr.takeError();
3176  }
3177 
3178  // Import the describing template function, if any.
3179  if (FromFT) {
3180  auto ToFTOrErr = import(FromFT);
3181  if (!ToFTOrErr)
3182  return ToFTOrErr.takeError();
3183  }
3184 
3185  if (D->doesThisDeclarationHaveABody()) {
3186  if (Stmt *FromBody = D->getBody()) {
3187  if (ExpectedStmt ToBodyOrErr = import(FromBody))
3188  ToFunction->setBody(*ToBodyOrErr);
3189  else
3190  return ToBodyOrErr.takeError();
3191  }
3192  }
3193 
3194  // FIXME: Other bits to merge?
3195 
3196  // If it is a template, import all related things.
3197  if (Error Err = ImportTemplateInformation(D, ToFunction))
3198  return std::move(Err);
3199 
3201 
3202  // TODO Can we generalize this approach to other AST nodes as well?
3203  if (D->getDeclContext()->containsDeclAndLoad(D))
3204  DC->addDeclInternal(ToFunction);
3205  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3206  LexicalDC->addDeclInternal(ToFunction);
3207 
3208  // Friend declaration's lexical context is the befriending class, but the
3209  // semantic context is the enclosing scope of the befriending class.
3210  // We want the friend functions to be found in the semantic context by lookup.
3211  // FIXME should we handle this generically in VisitFriendDecl?
3212  // In Other cases when LexicalDC != DC we don't want it to be added,
3213  // e.g out-of-class definitions like void B::f() {} .
3214  if (LexicalDC != DC && IsFriend) {
3215  DC->makeDeclVisibleInContext(ToFunction);
3216  }
3217 
3218  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3219  ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
3220 
3221  // Import the rest of the chain. I.e. import all subsequent declarations.
3222  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3223  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3224  if (!ToRedeclOrErr)
3225  return ToRedeclOrErr.takeError();
3226  }
3227 
3228  return ToFunction;
3229 }
3230 
3232  return VisitFunctionDecl(D);
3233 }
3234 
3236  return VisitCXXMethodDecl(D);
3237 }
3238 
3240  return VisitCXXMethodDecl(D);
3241 }
3242 
3244  return VisitCXXMethodDecl(D);
3245 }
3246 
3248  // Import the major distinguishing characteristics of a variable.
3249  DeclContext *DC, *LexicalDC;
3250  DeclarationName Name;
3251  SourceLocation Loc;
3252  NamedDecl *ToD;
3253  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3254  return std::move(Err);
3255  if (ToD)
3256  return ToD;
3257 
3258  // Determine whether we've already imported this field.
3259  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3260  for (auto *FoundDecl : FoundDecls) {
3261  if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3262  // For anonymous fields, match up by index.
3263  if (!Name &&
3265  ASTImporter::getFieldIndex(FoundField))
3266  continue;
3267 
3268  if (Importer.IsStructurallyEquivalent(D->getType(),
3269  FoundField->getType())) {
3270  Importer.MapImported(D, FoundField);
3271  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3272  // initializer of a FieldDecl might not had been instantiated in the
3273  // "To" context. However, the "From" context might instantiated that,
3274  // thus we have to merge that.
3275  if (Expr *FromInitializer = D->getInClassInitializer()) {
3276  // We don't have yet the initializer set.
3277  if (FoundField->hasInClassInitializer() &&
3278  !FoundField->getInClassInitializer()) {
3279  if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3280  FoundField->setInClassInitializer(*ToInitializerOrErr);
3281  else {
3282  // We can't return error here,
3283  // since we already mapped D as imported.
3284  // FIXME: warning message?
3285  consumeError(ToInitializerOrErr.takeError());
3286  return FoundField;
3287  }
3288  }
3289  }
3290  return FoundField;
3291  }
3292 
3293  // FIXME: Why is this case not handled with calling HandleNameConflict?
3294  Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3295  << Name << D->getType() << FoundField->getType();
3296  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3297  << FoundField->getType();
3298 
3299  return make_error<ImportError>(ImportError::NameConflict);
3300  }
3301  }
3302 
3303  QualType ToType;
3304  TypeSourceInfo *ToTInfo;
3305  Expr *ToBitWidth;
3306  SourceLocation ToInnerLocStart;
3307  Expr *ToInitializer;
3308  if (auto Imp = importSeq(
3309  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(),
3311  std::tie(
3312  ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp;
3313  else
3314  return Imp.takeError();
3315 
3316  FieldDecl *ToField;
3317  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3318  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3319  ToType, ToTInfo, ToBitWidth, D->isMutable(),
3320  D->getInClassInitStyle()))
3321  return ToField;
3322 
3323  ToField->setAccess(D->getAccess());
3324  ToField->setLexicalDeclContext(LexicalDC);
3325  if (ToInitializer)
3326  ToField->setInClassInitializer(ToInitializer);
3327  ToField->setImplicit(D->isImplicit());
3328  LexicalDC->addDeclInternal(ToField);
3329  return ToField;
3330 }
3331 
3333  // Import the major distinguishing characteristics of a variable.
3334  DeclContext *DC, *LexicalDC;
3335  DeclarationName Name;
3336  SourceLocation Loc;
3337  NamedDecl *ToD;
3338  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3339  return std::move(Err);
3340  if (ToD)
3341  return ToD;
3342 
3343  // Determine whether we've already imported this field.
3344  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3345  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3346  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3347  // For anonymous indirect fields, match up by index.
3348  if (!Name &&
3350  ASTImporter::getFieldIndex(FoundField))
3351  continue;
3352 
3353  if (Importer.IsStructurallyEquivalent(D->getType(),
3354  FoundField->getType(),
3355  !Name.isEmpty())) {
3356  Importer.MapImported(D, FoundField);
3357  return FoundField;
3358  }
3359 
3360  // If there are more anonymous fields to check, continue.
3361  if (!Name && I < N-1)
3362  continue;
3363 
3364  // FIXME: Why is this case not handled with calling HandleNameConflict?
3365  Importer.ToDiag(Loc, diag::err_odr_field_type_inconsistent)
3366  << Name << D->getType() << FoundField->getType();
3367  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3368  << FoundField->getType();
3369 
3370  return make_error<ImportError>(ImportError::NameConflict);
3371  }
3372  }
3373 
3374  // Import the type.
3375  auto TypeOrErr = import(D->getType());
3376  if (!TypeOrErr)
3377  return TypeOrErr.takeError();
3378 
3379  auto **NamedChain =
3380  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3381 
3382  unsigned i = 0;
3383  for (auto *PI : D->chain())
3384  if (Expected<NamedDecl *> ToD = import(PI))
3385  NamedChain[i++] = *ToD;
3386  else
3387  return ToD.takeError();
3388 
3389  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3390  IndirectFieldDecl *ToIndirectField;
3391  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3392  Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3393  // FIXME here we leak `NamedChain` which is allocated before
3394  return ToIndirectField;
3395 
3396  for (const auto *Attr : D->attrs())
3397  ToIndirectField->addAttr(Importer.Import(Attr));
3398 
3399  ToIndirectField->setAccess(D->getAccess());
3400  ToIndirectField->setLexicalDeclContext(LexicalDC);
3401  LexicalDC->addDeclInternal(ToIndirectField);
3402  return ToIndirectField;
3403 }
3404 
3406  // Import the major distinguishing characteristics of a declaration.
3407  DeclContext *DC, *LexicalDC;
3408  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3409  return std::move(Err);
3410 
3411  // Determine whether we've already imported this decl.
3412  // FriendDecl is not a NamedDecl so we cannot use lookup.
3413  auto *RD = cast<CXXRecordDecl>(DC);
3414  FriendDecl *ImportedFriend = RD->getFirstFriend();
3415 
3416  while (ImportedFriend) {
3417  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3418  if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3419  /*Complain=*/false))
3420  return Importer.MapImported(D, ImportedFriend);
3421 
3422  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3423  if (Importer.IsStructurallyEquivalent(
3424  D->getFriendType()->getType(),
3425  ImportedFriend->getFriendType()->getType(), true))
3426  return Importer.MapImported(D, ImportedFriend);
3427  }
3428  ImportedFriend = ImportedFriend->getNextFriend();
3429  }
3430 
3431  // Not found. Create it.
3433  if (NamedDecl *FriendD = D->getFriendDecl()) {
3434  NamedDecl *ToFriendD;
3435  if (Error Err = importInto(ToFriendD, FriendD))
3436  return std::move(Err);
3437 
3438  if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3439  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3440  ToFriendD->setObjectOfFriendDecl(false);
3441 
3442  ToFU = ToFriendD;
3443  } else { // The friend is a type, not a decl.
3444  if (auto TSIOrErr = import(D->getFriendType()))
3445  ToFU = *TSIOrErr;
3446  else
3447  return TSIOrErr.takeError();
3448  }
3449 
3450  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3451  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3452  for (unsigned I = 0; I < D->NumTPLists; I++) {
3453  if (auto ListOrErr = ImportTemplateParameterList(FromTPLists[I]))
3454  ToTPLists[I] = *ListOrErr;
3455  else
3456  return ListOrErr.takeError();
3457  }
3458 
3459  auto LocationOrErr = import(D->getLocation());
3460  if (!LocationOrErr)
3461  return LocationOrErr.takeError();
3462  auto FriendLocOrErr = import(D->getFriendLoc());
3463  if (!FriendLocOrErr)
3464  return FriendLocOrErr.takeError();
3465 
3466  FriendDecl *FrD;
3467  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3468  *LocationOrErr, ToFU,
3469  *FriendLocOrErr, ToTPLists))
3470  return FrD;
3471 
3472  FrD->setAccess(D->getAccess());
3473  FrD->setLexicalDeclContext(LexicalDC);
3474  LexicalDC->addDeclInternal(FrD);
3475  return FrD;
3476 }
3477 
3479  // Import the major distinguishing characteristics of an ivar.
3480  DeclContext *DC, *LexicalDC;
3481  DeclarationName Name;
3482  SourceLocation Loc;
3483  NamedDecl *ToD;
3484  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3485  return std::move(Err);
3486  if (ToD)
3487  return ToD;
3488 
3489  // Determine whether we've already imported this ivar
3490  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3491  for (auto *FoundDecl : FoundDecls) {
3492  if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3493  if (Importer.IsStructurallyEquivalent(D->getType(),
3494  FoundIvar->getType())) {
3495  Importer.MapImported(D, FoundIvar);
3496  return FoundIvar;
3497  }
3498 
3499  Importer.ToDiag(Loc, diag::err_odr_ivar_type_inconsistent)
3500  << Name << D->getType() << FoundIvar->getType();
3501  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3502  << FoundIvar->getType();
3503 
3504  return make_error<ImportError>(ImportError::NameConflict);
3505  }
3506  }
3507 
3508  QualType ToType;
3509  TypeSourceInfo *ToTypeSourceInfo;
3510  Expr *ToBitWidth;
3511  SourceLocation ToInnerLocStart;
3512  if (auto Imp = importSeq(
3513  D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart()))
3514  std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp;
3515  else
3516  return Imp.takeError();
3517 
3518  ObjCIvarDecl *ToIvar;
3519  if (GetImportedOrCreateDecl(
3520  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3521  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3522  ToType, ToTypeSourceInfo,
3523  D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3524  return ToIvar;
3525 
3526  ToIvar->setLexicalDeclContext(LexicalDC);
3527  LexicalDC->addDeclInternal(ToIvar);
3528  return ToIvar;
3529 }
3530 
3532 
3534  auto RedeclIt = Redecls.begin();
3535  // Import the first part of the decl chain. I.e. import all previous
3536  // declarations starting from the canonical decl.
3537  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3538  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3539  if (!RedeclOrErr)
3540  return RedeclOrErr.takeError();
3541  }
3542  assert(*RedeclIt == D);
3543 
3544  // Import the major distinguishing characteristics of a variable.
3545  DeclContext *DC, *LexicalDC;
3546  DeclarationName Name;
3547  SourceLocation Loc;
3548  NamedDecl *ToD;
3549  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3550  return std::move(Err);
3551  if (ToD)
3552  return ToD;
3553 
3554  // Try to find a variable in our own ("to") context with the same name and
3555  // in the same context as the variable we're importing.
3556  VarDecl *FoundByLookup = nullptr;
3557  if (D->isFileVarDecl()) {
3558  SmallVector<NamedDecl *, 4> ConflictingDecls;
3559  unsigned IDNS = Decl::IDNS_Ordinary;
3560  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3561  for (auto *FoundDecl : FoundDecls) {
3562  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3563  continue;
3564 
3565  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3566  // We have found a variable that we may need to merge with. Check it.
3567  if (FoundVar->hasExternalFormalLinkage() &&
3568  D->hasExternalFormalLinkage()) {
3569  if (Importer.IsStructurallyEquivalent(D->getType(),
3570  FoundVar->getType())) {
3571 
3572  // The VarDecl in the "From" context has a definition, but in the
3573  // "To" context we already have a definition.
3574  VarDecl *FoundDef = FoundVar->getDefinition();
3575  if (D->isThisDeclarationADefinition() && FoundDef)
3576  // FIXME Check for ODR error if the two definitions have
3577  // different initializers?
3578  return Importer.MapImported(D, FoundDef);
3579 
3580  // The VarDecl in the "From" context has an initializer, but in the
3581  // "To" context we already have an initializer.
3582  const VarDecl *FoundDInit = nullptr;
3583  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3584  // FIXME Diagnose ODR error if the two initializers are different?
3585  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3586 
3587  FoundByLookup = FoundVar;
3588  break;
3589  }
3590 
3591  const ArrayType *FoundArray
3592  = Importer.getToContext().getAsArrayType(FoundVar->getType());
3593  const ArrayType *TArray
3594  = Importer.getToContext().getAsArrayType(D->getType());
3595  if (FoundArray && TArray) {
3596  if (isa<IncompleteArrayType>(FoundArray) &&
3597  isa<ConstantArrayType>(TArray)) {
3598  // Import the type.
3599  if (auto TyOrErr = import(D->getType()))
3600  FoundVar->setType(*TyOrErr);
3601  else
3602  return TyOrErr.takeError();
3603 
3604  FoundByLookup = FoundVar;
3605  break;
3606  } else if (isa<IncompleteArrayType>(TArray) &&
3607  isa<ConstantArrayType>(FoundArray)) {
3608  FoundByLookup = FoundVar;
3609  break;
3610  }
3611  }
3612 
3613  Importer.ToDiag(Loc, diag::err_odr_variable_type_inconsistent)
3614  << Name << D->getType() << FoundVar->getType();
3615  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3616  << FoundVar->getType();
3617  }
3618  }
3619 
3620  ConflictingDecls.push_back(FoundDecl);
3621  }
3622 
3623  if (!ConflictingDecls.empty()) {
3624  Name = Importer.HandleNameConflict(Name, DC, IDNS,
3625  ConflictingDecls.data(),
3626  ConflictingDecls.size());
3627  if (!Name)
3628  return make_error<ImportError>(ImportError::NameConflict);
3629  }
3630  }
3631 
3632  QualType ToType;
3633  TypeSourceInfo *ToTypeSourceInfo;
3634  SourceLocation ToInnerLocStart;
3635  NestedNameSpecifierLoc ToQualifierLoc;
3636  if (auto Imp = importSeq(
3637  D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(),
3638  D->getQualifierLoc()))
3639  std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp;
3640  else
3641  return Imp.takeError();
3642 
3643  // Create the imported variable.
3644  VarDecl *ToVar;
3645  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3646  ToInnerLocStart, Loc,
3647  Name.getAsIdentifierInfo(),
3648  ToType, ToTypeSourceInfo,
3649  D->getStorageClass()))
3650  return ToVar;
3651 
3652  ToVar->setQualifierInfo(ToQualifierLoc);
3653  ToVar->setAccess(D->getAccess());
3654  ToVar->setLexicalDeclContext(LexicalDC);
3655 
3656  if (FoundByLookup) {
3657  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3658  ToVar->setPreviousDecl(Recent);
3659  }
3660 
3661  if (Error Err = ImportInitializer(D, ToVar))
3662  return std::move(Err);
3663 
3664  if (D->isConstexpr())
3665  ToVar->setConstexpr(true);
3666 
3667  if (D->getDeclContext()->containsDeclAndLoad(D))
3668  DC->addDeclInternal(ToVar);
3669  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3670  LexicalDC->addDeclInternal(ToVar);
3671 
3672  // Import the rest of the chain. I.e. import all subsequent declarations.
3673  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3674  ExpectedDecl RedeclOrErr = import(*RedeclIt);
3675  if (!RedeclOrErr)
3676  return RedeclOrErr.takeError();
3677  }
3678 
3679  return ToVar;
3680 }
3681 
3683  // Parameters are created in the translation unit's context, then moved
3684  // into the function declaration's context afterward.
3685  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3686 
3687  DeclarationName ToDeclName;
3688  SourceLocation ToLocation;
3689  QualType ToType;
3690  if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType()))
3691  std::tie(ToDeclName, ToLocation, ToType) = *Imp;
3692  else
3693  return Imp.takeError();
3694 
3695  // Create the imported parameter.
3696  ImplicitParamDecl *ToParm = nullptr;
3697  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3698  ToLocation, ToDeclName.getAsIdentifierInfo(),
3699  ToType, D->getParameterKind()))
3700  return ToParm;
3701  return ToParm;
3702 }
3703 
3705  // Parameters are created in the translation unit's context, then moved
3706  // into the function declaration's context afterward.
3707  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3708 
3709  DeclarationName ToDeclName;
3710  SourceLocation ToLocation, ToInnerLocStart;
3711  QualType ToType;
3712  TypeSourceInfo *ToTypeSourceInfo;
3713  if (auto Imp = importSeq(
3714  D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(),
3715  D->getTypeSourceInfo()))
3716  std::tie(
3717  ToDeclName, ToLocation, ToType, ToInnerLocStart,
3718  ToTypeSourceInfo) = *Imp;
3719  else
3720  return Imp.takeError();
3721 
3722  ParmVarDecl *ToParm;
3723  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3724  ToInnerLocStart, ToLocation,
3725  ToDeclName.getAsIdentifierInfo(), ToType,
3726  ToTypeSourceInfo, D->getStorageClass(),
3727  /*DefaultArg*/ nullptr))
3728  return ToParm;
3729 
3730  // Set the default argument.
3732  ToParm->setKNRPromoted(D->isKNRPromoted());
3733 
3734  if (D->hasUninstantiatedDefaultArg()) {
3735  if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg()))
3736  ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr);
3737  else
3738  return ToDefArgOrErr.takeError();
3739  } else if (D->hasUnparsedDefaultArg()) {
3740  ToParm->setUnparsedDefaultArg();
3741  } else if (D->hasDefaultArg()) {
3742  if (auto ToDefArgOrErr = import(D->getDefaultArg()))
3743  ToParm->setDefaultArg(*ToDefArgOrErr);
3744  else
3745  return ToDefArgOrErr.takeError();
3746  }
3747 
3748  if (D->isObjCMethodParameter()) {
3751  } else {
3752  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3753  D->getFunctionScopeIndex());
3754  }
3755 
3756  return ToParm;
3757 }
3758 
3760  // Import the major distinguishing characteristics of a method.
3761  DeclContext *DC, *LexicalDC;
3762  DeclarationName Name;
3763  SourceLocation Loc;
3764  NamedDecl *ToD;
3765  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3766  return std::move(Err);
3767  if (ToD)
3768  return ToD;
3769 
3770  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3771  for (auto *FoundDecl : FoundDecls) {
3772  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3773  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3774  continue;
3775 
3776  // Check return types.
3777  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3778  FoundMethod->getReturnType())) {
3779  Importer.ToDiag(Loc, diag::err_odr_objc_method_result_type_inconsistent)
3780  << D->isInstanceMethod() << Name << D->getReturnType()
3781  << FoundMethod->getReturnType();
3782  Importer.ToDiag(FoundMethod->getLocation(),
3783  diag::note_odr_objc_method_here)
3784  << D->isInstanceMethod() << Name;
3785 
3786  return make_error<ImportError>(ImportError::NameConflict);
3787  }
3788 
3789  // Check the number of parameters.
3790  if (D->param_size() != FoundMethod->param_size()) {
3791  Importer.ToDiag(Loc, diag::err_odr_objc_method_num_params_inconsistent)
3792  << D->isInstanceMethod() << Name
3793  << D->param_size() << FoundMethod->param_size();
3794  Importer.ToDiag(FoundMethod->getLocation(),
3795  diag::note_odr_objc_method_here)
3796  << D->isInstanceMethod() << Name;
3797 
3798  return make_error<ImportError>(ImportError::NameConflict);
3799  }
3800 
3801  // Check parameter types.
3803  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3804  P != PEnd; ++P, ++FoundP) {
3805  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3806  (*FoundP)->getType())) {
3807  Importer.FromDiag((*P)->getLocation(),
3808  diag::err_odr_objc_method_param_type_inconsistent)
3809  << D->isInstanceMethod() << Name
3810  << (*P)->getType() << (*FoundP)->getType();
3811  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3812  << (*FoundP)->getType();
3813 
3814  return make_error<ImportError>(ImportError::NameConflict);
3815  }
3816  }
3817 
3818  // Check variadic/non-variadic.
3819  // Check the number of parameters.
3820  if (D->isVariadic() != FoundMethod->isVariadic()) {
3821  Importer.ToDiag(Loc, diag::err_odr_objc_method_variadic_inconsistent)
3822  << D->isInstanceMethod() << Name;
3823  Importer.ToDiag(FoundMethod->getLocation(),
3824  diag::note_odr_objc_method_here)
3825  << D->isInstanceMethod() << Name;
3826 
3827  return make_error<ImportError>(ImportError::NameConflict);
3828  }
3829 
3830  // FIXME: Any other bits we need to merge?
3831  return Importer.MapImported(D, FoundMethod);
3832  }
3833  }
3834 
3835  SourceLocation ToEndLoc;
3836  QualType ToReturnType;
3837  TypeSourceInfo *ToReturnTypeSourceInfo;
3838  if (auto Imp = importSeq(
3840  std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp;
3841  else
3842  return Imp.takeError();
3843 
3844  ObjCMethodDecl *ToMethod;
3845  if (GetImportedOrCreateDecl(
3846  ToMethod, D, Importer.getToContext(), Loc,
3847  ToEndLoc, Name.getObjCSelector(), ToReturnType,
3848  ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3849  D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3851  return ToMethod;
3852 
3853  // FIXME: When we decide to merge method definitions, we'll need to
3854  // deal with implicit parameters.
3855 
3856  // Import the parameters
3858  for (auto *FromP : D->parameters()) {
3859  if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
3860  ToParams.push_back(*ToPOrErr);
3861  else
3862  return ToPOrErr.takeError();
3863  }
3864 
3865  // Set the parameters.
3866  for (auto *ToParam : ToParams) {
3867  ToParam->setOwningFunction(ToMethod);
3868  ToMethod->addDeclInternal(ToParam);
3869  }
3870 
3871  SmallVector<SourceLocation, 12> FromSelLocs;
3872  D->getSelectorLocs(FromSelLocs);
3873  SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
3874  if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
3875  return std::move(Err);
3876 
3877  ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
3878 
3879  ToMethod->setLexicalDeclContext(LexicalDC);
3880  LexicalDC->addDeclInternal(ToMethod);
3881  return ToMethod;
3882 }
3883 
3885  // Import the major distinguishing characteristics of a category.
3886  DeclContext *DC, *LexicalDC;
3887  DeclarationName Name;
3888  SourceLocation Loc;
3889  NamedDecl *ToD;
3890  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3891  return std::move(Err);
3892  if (ToD)
3893  return ToD;
3894 
3895  SourceLocation ToVarianceLoc, ToLocation, ToColonLoc;
3896  TypeSourceInfo *ToTypeSourceInfo;
3897  if (auto Imp = importSeq(
3898  D->getVarianceLoc(), D->getLocation(), D->getColonLoc(),
3899  D->getTypeSourceInfo()))
3900  std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp;
3901  else
3902  return Imp.takeError();
3903 
3905  if (GetImportedOrCreateDecl(
3906  Result, D, Importer.getToContext(), DC, D->getVariance(),
3907  ToVarianceLoc, D->getIndex(),
3908  ToLocation, Name.getAsIdentifierInfo(),
3909  ToColonLoc, ToTypeSourceInfo))
3910  return Result;
3911 
3912  Result->setLexicalDeclContext(LexicalDC);
3913  return Result;
3914 }
3915 
3917  // Import the major distinguishing characteristics of a category.
3918  DeclContext *DC, *LexicalDC;
3919  DeclarationName Name;
3920  SourceLocation Loc;
3921  NamedDecl *ToD;
3922  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3923  return std::move(Err);
3924  if (ToD)
3925  return ToD;
3926 
3927  ObjCInterfaceDecl *ToInterface;
3928  if (Error Err = importInto(ToInterface, D->getClassInterface()))
3929  return std::move(Err);
3930 
3931  // Determine if we've already encountered this category.
3932  ObjCCategoryDecl *MergeWithCategory
3933  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3934  ObjCCategoryDecl *ToCategory = MergeWithCategory;
3935  if (!ToCategory) {
3936  SourceLocation ToAtStartLoc, ToCategoryNameLoc;
3937  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
3938  if (auto Imp = importSeq(
3939  D->getAtStartLoc(), D->getCategoryNameLoc(),
3940  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
3941  std::tie(
3942  ToAtStartLoc, ToCategoryNameLoc,
3943  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
3944  else
3945  return Imp.takeError();
3946 
3947  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
3948  ToAtStartLoc, Loc,
3949  ToCategoryNameLoc,
3950  Name.getAsIdentifierInfo(), ToInterface,
3951  /*TypeParamList=*/nullptr,
3952  ToIvarLBraceLoc,
3953  ToIvarRBraceLoc))
3954  return ToCategory;
3955 
3956  ToCategory->setLexicalDeclContext(LexicalDC);
3957  LexicalDC->addDeclInternal(ToCategory);
3958  // Import the type parameter list after MapImported, to avoid
3959  // loops when bringing in their DeclContext.
3960  if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
3961  ToCategory->setTypeParamList(*PListOrErr);
3962  else
3963  return PListOrErr.takeError();
3964 
3965  // Import protocols
3967  SmallVector<SourceLocation, 4> ProtocolLocs;
3969  = D->protocol_loc_begin();
3971  FromProtoEnd = D->protocol_end();
3972  FromProto != FromProtoEnd;
3973  ++FromProto, ++FromProtoLoc) {
3974  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
3975  Protocols.push_back(*ToProtoOrErr);
3976  else
3977  return ToProtoOrErr.takeError();
3978 
3979  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
3980  ProtocolLocs.push_back(*ToProtoLocOrErr);
3981  else
3982  return ToProtoLocOrErr.takeError();
3983  }
3984 
3985  // FIXME: If we're merging, make sure that the protocol list is the same.
3986  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
3987  ProtocolLocs.data(), Importer.getToContext());
3988 
3989  } else {
3990  Importer.MapImported(D, ToCategory);
3991  }
3992 
3993  // Import all of the members of this category.
3994  if (Error Err = ImportDeclContext(D))
3995  return std::move(Err);
3996 
3997  // If we have an implementation, import it as well.
3998  if (D->getImplementation()) {
3999  if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4000  import(D->getImplementation()))
4001  ToCategory->setImplementation(*ToImplOrErr);
4002  else
4003  return ToImplOrErr.takeError();
4004  }
4005 
4006  return ToCategory;
4007 }
4008 
4011  if (To->getDefinition()) {
4012  if (shouldForceImportDeclContext(Kind))
4013  if (Error Err = ImportDeclContext(From))
4014  return Err;
4015  return Error::success();
4016  }
4017 
4018  // Start the protocol definition
4019  To->startDefinition();
4020 
4021  // Import protocols
4023  SmallVector<SourceLocation, 4> ProtocolLocs;
4025  From->protocol_loc_begin();
4026  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4027  FromProtoEnd = From->protocol_end();
4028  FromProto != FromProtoEnd;
4029  ++FromProto, ++FromProtoLoc) {
4030  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4031  Protocols.push_back(*ToProtoOrErr);
4032  else
4033  return ToProtoOrErr.takeError();
4034 
4035  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4036  ProtocolLocs.push_back(*ToProtoLocOrErr);
4037  else
4038  return ToProtoLocOrErr.takeError();
4039 
4040  }
4041 
4042  // FIXME: If we're merging, make sure that the protocol list is the same.
4043  To->setProtocolList(Protocols.data(), Protocols.size(),
4044  ProtocolLocs.data(), Importer.getToContext());
4045 
4046  if (shouldForceImportDeclContext(Kind)) {
4047  // Import all of the members of this protocol.
4048  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4049  return Err;
4050  }
4051  return Error::success();
4052 }
4053 
4055  // If this protocol has a definition in the translation unit we're coming
4056  // from, but this particular declaration is not that definition, import the
4057  // definition and map to that.
4058  ObjCProtocolDecl *Definition = D->getDefinition();
4059  if (Definition && Definition != D) {
4060  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4061  return Importer.MapImported(D, *ImportedDefOrErr);
4062  else
4063  return ImportedDefOrErr.takeError();
4064  }
4065 
4066  // Import the major distinguishing characteristics of a protocol.
4067  DeclContext *DC, *LexicalDC;
4068  DeclarationName Name;
4069  SourceLocation Loc;
4070  NamedDecl *ToD;
4071  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4072  return std::move(Err);
4073  if (ToD)
4074  return ToD;
4075 
4076  ObjCProtocolDecl *MergeWithProtocol = nullptr;
4077  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4078  for (auto *FoundDecl : FoundDecls) {
4080  continue;
4081 
4082  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4083  break;
4084  }
4085 
4086  ObjCProtocolDecl *ToProto = MergeWithProtocol;
4087  if (!ToProto) {
4088  auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4089  if (!ToAtBeginLocOrErr)
4090  return ToAtBeginLocOrErr.takeError();
4091 
4092  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4093  Name.getAsIdentifierInfo(), Loc,
4094  *ToAtBeginLocOrErr,
4095  /*PrevDecl=*/nullptr))
4096  return ToProto;
4097  ToProto->setLexicalDeclContext(LexicalDC);
4098  LexicalDC->addDeclInternal(ToProto);
4099  }
4100 
4101  Importer.MapImported(D, ToProto);
4102 
4104  if (Error Err = ImportDefinition(D, ToProto))
4105  return std::move(Err);
4106 
4107  return ToProto;
4108 }
4109 
4111  DeclContext *DC, *LexicalDC;
4112  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4113  return std::move(Err);
4114 
4115  ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4116  if (!ExternLocOrErr)
4117  return ExternLocOrErr.takeError();
4118 
4119  ExpectedSLoc LangLocOrErr = import(D->getLocation());
4120  if (!LangLocOrErr)
4121  return LangLocOrErr.takeError();
4122 
4123  bool HasBraces = D->hasBraces();
4124 
4125  LinkageSpecDecl *ToLinkageSpec;
4126  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4127  *ExternLocOrErr, *LangLocOrErr,
4128  D->getLanguage(), HasBraces))
4129  return ToLinkageSpec;
4130 
4131  if (HasBraces) {
4132  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4133  if (!RBraceLocOrErr)
4134  return RBraceLocOrErr.takeError();
4135  ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4136  }
4137 
4138  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4139  LexicalDC->addDeclInternal(ToLinkageSpec);
4140 
4141  return ToLinkageSpec;
4142 }
4143 
4145  DeclContext *DC, *LexicalDC;
4146  DeclarationName Name;
4147  SourceLocation Loc;
4148  NamedDecl *ToD = nullptr;
4149  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4150  return std::move(Err);
4151  if (ToD)
4152  return ToD;
4153 
4154  SourceLocation ToLoc, ToUsingLoc;
4155  NestedNameSpecifierLoc ToQualifierLoc;
4156  if (auto Imp = importSeq(
4157  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc()))
4158  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp;
4159  else
4160  return Imp.takeError();
4161 
4162  DeclarationNameInfo NameInfo(Name, ToLoc);
4163  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4164  return std::move(Err);
4165 
4166  UsingDecl *ToUsing;
4167  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4168  ToUsingLoc, ToQualifierLoc, NameInfo,
4169  D->hasTypename()))
4170  return ToUsing;
4171 
4172  ToUsing->setLexicalDeclContext(LexicalDC);
4173  LexicalDC->addDeclInternal(ToUsing);
4174 
4175  if (NamedDecl *FromPattern =
4176  Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4177  if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4178  Importer.getToContext().setInstantiatedFromUsingDecl(
4179  ToUsing, *ToPatternOrErr);
4180  else
4181  return ToPatternOrErr.takeError();
4182  }
4183 
4184  for (UsingShadowDecl *FromShadow : D->shadows()) {
4185  if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4186  ToUsing->addShadowDecl(*ToShadowOrErr);
4187  else
4188  // FIXME: We return error here but the definition is already created
4189  // and available with lookups. How to fix this?..
4190  return ToShadowOrErr.takeError();
4191  }
4192  return ToUsing;
4193 }
4194 
4196  DeclContext *DC, *LexicalDC;
4197  DeclarationName Name;
4198  SourceLocation Loc;
4199  NamedDecl *ToD = nullptr;
4200  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4201  return std::move(Err);
4202  if (ToD)
4203  return ToD;
4204 
4205  Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4206  if (!ToUsingOrErr)
4207  return ToUsingOrErr.takeError();
4208 
4209  Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4210  if (!ToTargetOrErr)
4211  return ToTargetOrErr.takeError();
4212 
4213  UsingShadowDecl *ToShadow;
4214  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4215  *ToUsingOrErr, *ToTargetOrErr))
4216  return ToShadow;
4217 
4218  ToShadow->setLexicalDeclContext(LexicalDC);
4219  ToShadow->setAccess(D->getAccess());
4220 
4221  if (UsingShadowDecl *FromPattern =
4222  Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4223  if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4224  Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4225  ToShadow, *ToPatternOrErr);
4226  else
4227  // FIXME: We return error here but the definition is already created
4228  // and available with lookups. How to fix this?..
4229  return ToPatternOrErr.takeError();
4230  }
4231 
4232  LexicalDC->addDeclInternal(ToShadow);
4233 
4234  return ToShadow;
4235 }
4236 
4238  DeclContext *DC, *LexicalDC;
4239  DeclarationName Name;
4240  SourceLocation Loc;
4241  NamedDecl *ToD = nullptr;
4242  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4243  return std::move(Err);
4244  if (ToD)
4245  return ToD;
4246 
4247  auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4248  if (!ToComAncestorOrErr)
4249  return ToComAncestorOrErr.takeError();
4250 
4251  NamespaceDecl *ToNominatedNamespace;
4252  SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation;
4253  NestedNameSpecifierLoc ToQualifierLoc;
4254  if (auto Imp = importSeq(
4257  D->getIdentLocation()))
4258  std::tie(
4259  ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation,
4260  ToQualifierLoc, ToIdentLocation) = *Imp;
4261  else
4262  return Imp.takeError();
4263 
4264  UsingDirectiveDecl *ToUsingDir;
4265  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4266  ToUsingLoc,
4267  ToNamespaceKeyLocation,
4268  ToQualifierLoc,
4269  ToIdentLocation,
4270  ToNominatedNamespace, *ToComAncestorOrErr))
4271  return ToUsingDir;
4272 
4273  ToUsingDir->setLexicalDeclContext(LexicalDC);
4274  LexicalDC->addDeclInternal(ToUsingDir);
4275 
4276  return ToUsingDir;
4277 }
4278 
4281  DeclContext *DC, *LexicalDC;
4282  DeclarationName Name;
4283  SourceLocation Loc;
4284  NamedDecl *ToD = nullptr;
4285  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4286  return std::move(Err);
4287  if (ToD)
4288  return ToD;
4289 
4290  SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc;
4291  NestedNameSpecifierLoc ToQualifierLoc;
4292  if (auto Imp = importSeq(
4293  D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(),
4294  D->getEllipsisLoc()))
4295  std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4296  else
4297  return Imp.takeError();
4298 
4299  DeclarationNameInfo NameInfo(Name, ToLoc);
4300  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4301  return std::move(Err);
4302 
4303  UnresolvedUsingValueDecl *ToUsingValue;
4304  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4305  ToUsingLoc, ToQualifierLoc, NameInfo,
4306  ToEllipsisLoc))
4307  return ToUsingValue;
4308 
4309  ToUsingValue->setAccess(D->getAccess());
4310  ToUsingValue->setLexicalDeclContext(LexicalDC);
4311  LexicalDC->addDeclInternal(ToUsingValue);
4312 
4313  return ToUsingValue;
4314 }
4315 
4318  DeclContext *DC, *LexicalDC;
4319  DeclarationName Name;
4320  SourceLocation Loc;
4321  NamedDecl *ToD = nullptr;
4322  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4323  return std::move(Err);
4324  if (ToD)
4325  return ToD;
4326 
4327  SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc;
4328  NestedNameSpecifierLoc ToQualifierLoc;
4329  if (auto Imp = importSeq(
4330  D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(),
4331  D->getEllipsisLoc()))
4332  std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4333  else
4334  return Imp.takeError();
4335 
4336  UnresolvedUsingTypenameDecl *ToUsing;
4337  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4338  ToUsingLoc, ToTypenameLoc,
4339  ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4340  return ToUsing;
4341 
4342  ToUsing->setAccess(D->getAccess());
4343  ToUsing->setLexicalDeclContext(LexicalDC);
4344  LexicalDC->addDeclInternal(ToUsing);
4345 
4346  return ToUsing;
4347 }
4348 
4349 
4352  if (To->getDefinition()) {
4353  // Check consistency of superclass.
4354  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4355  if (FromSuper) {
4356  if (auto FromSuperOrErr = import(FromSuper))
4357  FromSuper = *FromSuperOrErr;
4358  else
4359  return FromSuperOrErr.takeError();
4360  }
4361 
4362  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4363  if ((bool)FromSuper != (bool)ToSuper ||
4364  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4365  Importer.ToDiag(To->getLocation(),
4366  diag::err_odr_objc_superclass_inconsistent)
4367  << To->getDeclName();
4368  if (ToSuper)
4369  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4370  << To->getSuperClass()->getDeclName();
4371  else
4372  Importer.ToDiag(To->getLocation(),
4373  diag::note_odr_objc_missing_superclass);
4374  if (From->getSuperClass())
4375  Importer.FromDiag(From->getSuperClassLoc(),
4376  diag::note_odr_objc_superclass)
4377  << From->getSuperClass()->getDeclName();
4378  else
4379  Importer.FromDiag(From->getLocation(),
4380  diag::note_odr_objc_missing_superclass);
4381  }
4382 
4383  if (shouldForceImportDeclContext(Kind))
4384  if (Error Err = ImportDeclContext(From))
4385  return Err;
4386  return Error::success();
4387  }
4388 
4389  // Start the definition.
4390  To->startDefinition();
4391 
4392  // If this class has a superclass, import it.
4393  if (From->getSuperClass()) {
4394  if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4395  To->setSuperClass(*SuperTInfoOrErr);
4396  else
4397  return SuperTInfoOrErr.takeError();
4398  }
4399 
4400  // Import protocols
4402  SmallVector<SourceLocation, 4> ProtocolLocs;
4404  From->protocol_loc_begin();
4405 
4406  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4407  FromProtoEnd = From->protocol_end();
4408  FromProto != FromProtoEnd;
4409  ++FromProto, ++FromProtoLoc) {
4410  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4411  Protocols.push_back(*ToProtoOrErr);
4412  else
4413  return ToProtoOrErr.takeError();
4414 
4415  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4416  ProtocolLocs.push_back(*ToProtoLocOrErr);
4417  else
4418  return ToProtoLocOrErr.takeError();
4419 
4420  }
4421 
4422  // FIXME: If we're merging, make sure that the protocol list is the same.
4423  To->setProtocolList(Protocols.data(), Protocols.size(),
4424  ProtocolLocs.data(), Importer.getToContext());
4425 
4426  // Import categories. When the categories themselves are imported, they'll
4427  // hook themselves into this interface.
4428  for (auto *Cat : From->known_categories()) {
4429  auto ToCatOrErr = import(Cat);
4430  if (!ToCatOrErr)
4431  return ToCatOrErr.takeError();
4432  }
4433 
4434  // If we have an @implementation, import it as well.
4435  if (From->getImplementation()) {
4436  if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4437  import(From->getImplementation()))
4438  To->setImplementation(*ToImplOrErr);
4439  else
4440  return ToImplOrErr.takeError();
4441  }
4442 
4443  if (shouldForceImportDeclContext(Kind)) {
4444  // Import all of the members of this class.
4445  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4446  return Err;
4447  }
4448  return Error::success();
4449 }
4450 
4453  if (!list)
4454  return nullptr;
4455 
4457  for (auto *fromTypeParam : *list) {
4458  if (auto toTypeParamOrErr = import(fromTypeParam))
4459  toTypeParams.push_back(*toTypeParamOrErr);
4460  else
4461  return toTypeParamOrErr.takeError();
4462  }
4463 
4464  auto LAngleLocOrErr = import(list->getLAngleLoc());
4465  if (!LAngleLocOrErr)
4466  return LAngleLocOrErr.takeError();
4467 
4468  auto RAngleLocOrErr = import(list->getRAngleLoc());
4469  if (!RAngleLocOrErr)
4470  return RAngleLocOrErr.takeError();
4471 
4472  return ObjCTypeParamList::create(Importer.getToContext(),
4473  *LAngleLocOrErr,
4474  toTypeParams,
4475  *RAngleLocOrErr);
4476 }
4477 
4479  // If this class has a definition in the translation unit we're coming from,
4480  // but this particular declaration is not that definition, import the
4481  // definition and map to that.
4482  ObjCInterfaceDecl *Definition = D->getDefinition();
4483  if (Definition && Definition != D) {
4484  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4485  return Importer.MapImported(D, *ImportedDefOrErr);
4486  else
4487  return ImportedDefOrErr.takeError();
4488  }
4489 
4490  // Import the major distinguishing characteristics of an @interface.
4491  DeclContext *DC, *LexicalDC;
4492  DeclarationName Name;
4493  SourceLocation Loc;
4494  NamedDecl *ToD;
4495  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4496  return std::move(Err);
4497  if (ToD)
4498  return ToD;
4499 
4500  // Look for an existing interface with the same name.
4501  ObjCInterfaceDecl *MergeWithIface = nullptr;
4502  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4503  for (auto *FoundDecl : FoundDecls) {
4505  continue;
4506 
4507  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4508  break;
4509  }
4510 
4511  // Create an interface declaration, if one does not already exist.
4512  ObjCInterfaceDecl *ToIface = MergeWithIface;
4513  if (!ToIface) {
4514  ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4515  if (!AtBeginLocOrErr)
4516  return AtBeginLocOrErr.takeError();
4517 
4518  if (GetImportedOrCreateDecl(
4519  ToIface, D, Importer.getToContext(), DC,
4520  *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4521  /*TypeParamList=*/nullptr,
4522  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4523  return ToIface;
4524  ToIface->setLexicalDeclContext(LexicalDC);
4525  LexicalDC->addDeclInternal(ToIface);
4526  }
4527  Importer.MapImported(D, ToIface);
4528  // Import the type parameter list after MapImported, to avoid
4529  // loops when bringing in their DeclContext.
4530  if (auto ToPListOrErr =
4531  ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4532  ToIface->setTypeParamList(*ToPListOrErr);
4533  else
4534  return ToPListOrErr.takeError();
4535 
4537  if (Error Err = ImportDefinition(D, ToIface))
4538  return std::move(Err);
4539 
4540  return ToIface;
4541 }
4542 
4546  if (Error Err = importInto(Category, D->getCategoryDecl()))
4547  return std::move(Err);
4548 
4549  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4550  if (!ToImpl) {
4551  DeclContext *DC, *LexicalDC;
4552  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4553  return std::move(Err);
4554 
4555  SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc;
4556  if (auto Imp = importSeq(
4557  D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc()))
4558  std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp;
4559  else
4560  return Imp.takeError();
4561 
4562  if (GetImportedOrCreateDecl(
4563  ToImpl, D, Importer.getToContext(), DC,
4564  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4565  ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4566  return ToImpl;
4567 
4568  ToImpl->setLexicalDeclContext(LexicalDC);
4569  LexicalDC->addDeclInternal(ToImpl);
4570  Category->setImplementation(ToImpl);
4571  }
4572 
4573  Importer.MapImported(D, ToImpl);
4574  if (Error Err = ImportDeclContext(D))
4575  return std::move(Err);
4576 
4577  return ToImpl;
4578 }
4579 
4582  // Find the corresponding interface.
4583  ObjCInterfaceDecl *Iface;
4584  if (Error Err = importInto(Iface, D->getClassInterface()))
4585  return std::move(Err);
4586 
4587  // Import the superclass, if any.
4588  ObjCInterfaceDecl *Super;
4589  if (Error Err = importInto(Super, D->getSuperClass()))
4590  return std::move(Err);
4591 
4592  ObjCImplementationDecl *Impl = Iface->getImplementation();
4593  if (!Impl) {
4594  // We haven't imported an implementation yet. Create a new @implementation
4595  // now.
4596  DeclContext *DC, *LexicalDC;
4597  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4598  return std::move(Err);
4599 
4600  SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc;
4601  SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4602  if (auto Imp = importSeq(
4603  D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(),
4604  D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4605  std::tie(
4606  ToLocation, ToAtStartLoc, ToSuperClassLoc,
4607  ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4608  else
4609  return Imp.takeError();
4610 
4611  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4612  DC, Iface, Super,
4613  ToLocation,
4614  ToAtStartLoc,
4615  ToSuperClassLoc,
4616  ToIvarLBraceLoc,
4617  ToIvarRBraceLoc))
4618  return Impl;
4619 
4620  Impl->setLexicalDeclContext(LexicalDC);
4621 
4622  // Associate the implementation with the class it implements.
4623  Iface->setImplementation(Impl);
4624  Importer.MapImported(D, Iface->getImplementation());
4625  } else {
4626  Importer.MapImported(D, Iface->getImplementation());
4627 
4628  // Verify that the existing @implementation has the same superclass.
4629  if ((Super && !Impl->getSuperClass()) ||
4630  (!Super && Impl->getSuperClass()) ||
4631  (Super && Impl->getSuperClass() &&
4633  Impl->getSuperClass()))) {
4634  Importer.ToDiag(Impl->getLocation(),
4635  diag::err_odr_objc_superclass_inconsistent)
4636  << Iface->getDeclName();
4637  // FIXME: It would be nice to have the location of the superclass
4638  // below.
4639  if (Impl->getSuperClass())
4640  Importer.ToDiag(Impl->getLocation(),
4641  diag::note_odr_objc_superclass)
4642  << Impl->getSuperClass()->getDeclName();
4643  else
4644  Importer.ToDiag(Impl->getLocation(),
4645  diag::note_odr_objc_missing_superclass);
4646  if (D->getSuperClass())
4647  Importer.FromDiag(D->getLocation(),
4648  diag::note_odr_objc_superclass)
4649  << D->getSuperClass()->getDeclName();
4650  else
4651  Importer.FromDiag(D->getLocation(),
4652  diag::note_odr_objc_missing_superclass);
4653 
4654  return make_error<ImportError>(ImportError::NameConflict);
4655  }
4656  }
4657 
4658  // Import all of the members of this @implementation.
4659  if (Error Err = ImportDeclContext(D))
4660  return std::move(Err);
4661 
4662  return Impl;
4663 }
4664 
4666  // Import the major distinguishing characteristics of an @property.
4667  DeclContext *DC, *LexicalDC;
4668  DeclarationName Name;
4669  SourceLocation Loc;
4670  NamedDecl *ToD;
4671  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4672  return std::move(Err);
4673  if (ToD)
4674  return ToD;
4675 
4676  // Check whether we have already imported this property.
4677  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4678  for (auto *FoundDecl : FoundDecls) {
4679  if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4680  // Check property types.
4681  if (!Importer.IsStructurallyEquivalent(D->getType(),
4682  FoundProp->getType())) {
4683  Importer.ToDiag(Loc, diag::err_odr_objc_property_type_inconsistent)
4684  << Name << D->getType() << FoundProp->getType();
4685  Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4686  << FoundProp->getType();
4687 
4688  return make_error<ImportError>(ImportError::NameConflict);
4689  }
4690 
4691  // FIXME: Check property attributes, getters, setters, etc.?
4692 
4693  // Consider these properties to be equivalent.
4694  Importer.MapImported(D, FoundProp);
4695  return FoundProp;
4696  }
4697  }
4698 
4699  QualType ToType;
4700  TypeSourceInfo *ToTypeSourceInfo;
4701  SourceLocation ToAtLoc, ToLParenLoc;
4702  if (auto Imp = importSeq(
4703  D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc()))
4704  std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp;
4705  else
4706  return Imp.takeError();
4707 
4708  // Create the new property.
4709  ObjCPropertyDecl *ToProperty;
4710  if (GetImportedOrCreateDecl(
4711  ToProperty, D, Importer.getToContext(), DC, Loc,
4712  Name.getAsIdentifierInfo(), ToAtLoc,
4713  ToLParenLoc, ToType,
4714  ToTypeSourceInfo, D->getPropertyImplementation()))
4715  return ToProperty;
4716 
4717  Selector ToGetterName, ToSetterName;
4718  SourceLocation ToGetterNameLoc, ToSetterNameLoc;
4719  ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl;
4720  ObjCIvarDecl *ToPropertyIvarDecl;
4721  if (auto Imp = importSeq(
4722  D->getGetterName(), D->getSetterName(),
4725  D->getPropertyIvarDecl()))
4726  std::tie(
4727  ToGetterName, ToSetterName,
4728  ToGetterNameLoc, ToSetterNameLoc,
4729  ToGetterMethodDecl, ToSetterMethodDecl,
4730  ToPropertyIvarDecl) = *Imp;
4731  else
4732  return Imp.takeError();
4733 
4734  ToProperty->setLexicalDeclContext(LexicalDC);
4735  LexicalDC->addDeclInternal(ToProperty);
4736 
4737  ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4738  ToProperty->setPropertyAttributesAsWritten(
4740  ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
4741  ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
4742  ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
4743  ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
4744  ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
4745  return ToProperty;
4746 }
4747 
4751  if (Error Err = importInto(Property, D->getPropertyDecl()))
4752  return std::move(Err);
4753 
4754  DeclContext *DC, *LexicalDC;
4755  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4756  return std::move(Err);
4757 
4758  auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
4759 
4760  // Import the ivar (for an @synthesize).
4761  ObjCIvarDecl *Ivar = nullptr;
4762  if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
4763  return std::move(Err);
4764 
4765  ObjCPropertyImplDecl *ToImpl
4766  = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4767  Property->getQueryKind());
4768  if (!ToImpl) {
4769  SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc;
4770  if (auto Imp = importSeq(
4772  std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp;
4773  else
4774  return Imp.takeError();
4775 
4776  if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4777  ToBeginLoc,
4778  ToLocation, Property,
4779  D->getPropertyImplementation(), Ivar,
4780  ToPropertyIvarDeclLoc))
4781  return ToImpl;
4782 
4783  ToImpl->setLexicalDeclContext(LexicalDC);
4784  LexicalDC->addDeclInternal(ToImpl);
4785  } else {
4786  // Check that we have the same kind of property implementation (@synthesize
4787  // vs. @dynamic).
4788  if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4789  Importer.ToDiag(ToImpl->getLocation(),
4790  diag::err_odr_objc_property_impl_kind_inconsistent)
4791  << Property->getDeclName()
4792  << (ToImpl->getPropertyImplementation()
4794  Importer.FromDiag(D->getLocation(),
4795  diag::note_odr_objc_property_impl_kind)
4796  << D->getPropertyDecl()->getDeclName()
4798 
4799  return make_error<ImportError>(ImportError::NameConflict);
4800  }
4801 
4802  // For @synthesize, check that we have the same
4804  Ivar != ToImpl->getPropertyIvarDecl()) {
4805  Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4806  diag::err_odr_objc_synthesize_ivar_inconsistent)
4807  << Property->getDeclName()
4808  << ToImpl->getPropertyIvarDecl()->getDeclName()
4809  << Ivar->getDeclName();
4810  Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4811  diag::note_odr_objc_synthesize_ivar_here)
4812  << D->getPropertyIvarDecl()->getDeclName();
4813 
4814  return make_error<ImportError>(ImportError::NameConflict);
4815  }
4816 
4817  // Merge the existing implementation with the new implementation.
4818  Importer.MapImported(D, ToImpl);
4819  }
4820 
4821  return ToImpl;
4822 }
4823 
4826  // For template arguments, we adopt the translation unit as our declaration
4827  // context. This context will be fixed when the actual template declaration
4828  // is created.
4829 
4830  // FIXME: Import default argument.
4831 
4832  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
4833  if (!BeginLocOrErr)
4834  return BeginLocOrErr.takeError();
4835 
4836  ExpectedSLoc LocationOrErr = import(D->getLocation());
4837  if (!LocationOrErr)
4838  return LocationOrErr.takeError();
4839 
4840  TemplateTypeParmDecl *ToD = nullptr;
4841  (void)GetImportedOrCreateDecl(
4842  ToD, D, Importer.getToContext(),
4843  Importer.getToContext().getTranslationUnitDecl(),
4844  *BeginLocOrErr, *LocationOrErr,
4845  D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4847  return ToD;
4848 }
4849 
4852  DeclarationName ToDeclName;
4853  SourceLocation ToLocation, ToInnerLocStart;
4854  QualType ToType;
4855  TypeSourceInfo *ToTypeSourceInfo;
4856  if (auto Imp = importSeq(
4857  D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(),
4858  D->getInnerLocStart()))
4859  std::tie(
4860  ToDeclName, ToLocation, ToType, ToTypeSourceInfo,
4861  ToInnerLocStart) = *Imp;
4862  else
4863  return Imp.takeError();
4864 
4865  // FIXME: Import default argument.
4866 
4867  NonTypeTemplateParmDecl *ToD = nullptr;
4868  (void)GetImportedOrCreateDecl(
4869  ToD, D, Importer.getToContext(),
4870  Importer.getToContext().getTranslationUnitDecl(),
4871  ToInnerLocStart, ToLocation, D->getDepth(),
4872  D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType,
4873  D->isParameterPack(), ToTypeSourceInfo);
4874  return ToD;
4875 }
4876 
4879  // Import the name of this declaration.
4880  auto NameOrErr = import(D->getDeclName());
4881  if (!NameOrErr)
4882  return NameOrErr.takeError();
4883 
4884  // Import the location of this declaration.
4885  ExpectedSLoc LocationOrErr = import(D->getLocation());
4886  if (!LocationOrErr)
4887  return LocationOrErr.takeError();
4888 
4889  // Import template parameters.
4890  auto TemplateParamsOrErr = ImportTemplateParameterList(
4891  D->getTemplateParameters());
4892  if (!TemplateParamsOrErr)
4893  return TemplateParamsOrErr.takeError();
4894 
4895  // FIXME: Import default argument.
4896 
4897  TemplateTemplateParmDecl *ToD = nullptr;
4898  (void)GetImportedOrCreateDecl(
4899  ToD, D, Importer.getToContext(),
4900  Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
4901  D->getDepth(), D->getPosition(), D->isParameterPack(),
4902  (*NameOrErr).getAsIdentifierInfo(),
4903  *TemplateParamsOrErr);
4904  return ToD;
4905 }
4906 
4907 // Returns the definition for a (forward) declaration of a ClassTemplateDecl, if
4908 // it has any definition in the redecl chain.
4910  CXXRecordDecl *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
4911  if (!ToTemplatedDef)
4912  return nullptr;
4913  ClassTemplateDecl *TemplateWithDef =
4914  ToTemplatedDef->getDescribedClassTemplate();
4915  return TemplateWithDef;
4916 }
4917 
4919  bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
4920 
4921  // If this template has a definition in the translation unit we're coming
4922  // from, but this particular declaration is not that definition, import the
4923  // definition and map to that.
4924  ClassTemplateDecl *Definition = getDefinition(D);
4925  if (Definition && Definition != D && !IsFriend) {
4926  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4927  return Importer.MapImported(D, *ImportedDefOrErr);
4928  else
4929  return ImportedDefOrErr.takeError();
4930  }
4931 
4932  // Import the major distinguishing characteristics of this class template.
4933  DeclContext *DC, *LexicalDC;
4934  DeclarationName Name;
4935  SourceLocation Loc;
4936  NamedDecl *ToD;
4937  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4938  return std::move(Err);
4939  if (ToD)
4940  return ToD;
4941 
4942  ClassTemplateDecl *FoundByLookup = nullptr;
4943 
4944  // We may already have a template of the same name; try to find and match it.
4945  if (!DC->isFunctionOrMethod()) {
4946  SmallVector<NamedDecl *, 4> ConflictingDecls;
4947  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4948  for (auto *FoundDecl : FoundDecls) {
4951  continue;
4952 
4953  Decl *Found = FoundDecl;
4954  auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
4955  if (FoundTemplate) {
4956 
4957  if (IsStructuralMatch(D, FoundTemplate)) {
4958  ClassTemplateDecl *TemplateWithDef = getDefinition(FoundTemplate);
4959  if (D->isThisDeclarationADefinition() && TemplateWithDef) {
4960  return Importer.MapImported(D, TemplateWithDef);
4961  }
4962  FoundByLookup = FoundTemplate;
4963  break;
4964  }
4965  }
4966 
4967  ConflictingDecls.push_back(FoundDecl);
4968  }
4969 
4970  if (!ConflictingDecls.empty()) {
4971  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4972  ConflictingDecls.data(),
4973  ConflictingDecls.size());
4974  }
4975 
4976  if (!Name)
4977  return make_error<ImportError>(ImportError::NameConflict);
4978  }
4979 
4980  CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
4981 
4982  // Create the declaration that is being templated.
4983  CXXRecordDecl *ToTemplated;
4984  if (Error Err = importInto(ToTemplated, FromTemplated))
4985  return std::move(Err);
4986 
4987  // Create the class template declaration itself.
4988  auto TemplateParamsOrErr = ImportTemplateParameterList(
4989  D->getTemplateParameters());
4990  if (!TemplateParamsOrErr)
4991  return TemplateParamsOrErr.takeError();
4992 
4993  ClassTemplateDecl *D2;
4994  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
4995  *TemplateParamsOrErr, ToTemplated))
4996  return D2;
4997 
4998  ToTemplated->setDescribedClassTemplate(D2);
4999 
5000  D2->setAccess(D->getAccess());
5001  D2->setLexicalDeclContext(LexicalDC);
5002 
5003  if (D->getDeclContext()->containsDeclAndLoad(D))
5004  DC->addDeclInternal(D2);
5005  if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
5006  LexicalDC->addDeclInternal(D2);
5007 
5008  if (FoundByLookup) {
5009  auto *Recent =
5010  const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5011 
5012  // It is possible that during the import of the class template definition
5013  // we start the import of a fwd friend decl of the very same class template
5014  // and we add the fwd friend decl to the lookup table. But the ToTemplated
5015  // had been created earlier and by that time the lookup could not find
5016  // anything existing, so it has no previous decl. Later, (still during the
5017  // import of the fwd friend decl) we start to import the definition again
5018  // and this time the lookup finds the previous fwd friend class template.
5019  // In this case we must set up the previous decl for the templated decl.
5020  if (!ToTemplated->getPreviousDecl()) {
5021  CXXRecordDecl *PrevTemplated =
5022  FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5023  if (ToTemplated != PrevTemplated)
5024  ToTemplated->setPreviousDecl(PrevTemplated);
5025  }
5026 
5027  D2->setPreviousDecl(Recent);
5028  }
5029 
5030  if (LexicalDC != DC && IsFriend)
5031  DC->makeDeclVisibleInContext(D2);
5032 
5033  if (FromTemplated->isCompleteDefinition() &&
5034  !ToTemplated->isCompleteDefinition()) {
5035  // FIXME: Import definition!
5036  }
5037 
5038  return D2;
5039 }
5040 
5043  // If this record has a definition in the translation unit we're coming from,
5044  // but this particular declaration is not that definition, import the
5045  // definition and map to that.
5046  TagDecl *Definition = D->getDefinition();
5047  if (Definition && Definition != D) {
5048  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5049  return Importer.MapImported(D, *ImportedDefOrErr);
5050  else
5051  return ImportedDefOrErr.takeError();
5052  }
5053 
5054  ClassTemplateDecl *ClassTemplate;
5055  if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5056  return std::move(Err);
5057 
5058  // Import the context of this declaration.
5059  DeclContext *DC, *LexicalDC;
5060  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5061  return std::move(Err);
5062 
5063  // Import template arguments.
5064  SmallVector<TemplateArgument, 2> TemplateArgs;
5065  if (Error Err = ImportTemplateArguments(
5066  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5067  return std::move(Err);
5068 
5069  // Try to find an existing specialization with these template arguments.
5070  void *InsertPos = nullptr;
5071  ClassTemplateSpecializationDecl *D2 = nullptr;
5074  if (PartialSpec)
5075  D2 = ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
5076  else
5077  D2 = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5078  ClassTemplateSpecializationDecl * const PrevDecl = D2;
5079  RecordDecl *FoundDef = D2 ? D2->getDefinition() : nullptr;
5080  if (FoundDef) {
5081  if (!D->isCompleteDefinition()) {
5082  // The "From" translation unit only had a forward declaration; call it
5083  // the same declaration.
5084  // TODO Handle the redecl chain properly!
5085  return Importer.MapImported(D, FoundDef);
5086  }
5087 
5088  if (IsStructuralMatch(D, FoundDef)) {
5089 
5090  Importer.MapImported(D, FoundDef);
5091 
5092  // Import those those default field initializers which have been
5093  // instantiated in the "From" context, but not in the "To" context.
5094  for (auto *FromField : D->fields()) {
5095  auto ToOrErr = import(FromField);
5096  if (!ToOrErr)
5097  // FIXME: return the error?
5098  consumeError(ToOrErr.takeError());
5099  }
5100 
5101  // Import those methods which have been instantiated in the
5102  // "From" context, but not in the "To" context.
5103  for (CXXMethodDecl *FromM : D->methods()) {
5104  auto ToOrErr = import(FromM);
5105  if (!ToOrErr)
5106  // FIXME: return the error?
5107  consumeError(ToOrErr.takeError());
5108  }
5109 
5110  // TODO Import instantiated default arguments.
5111  // TODO Import instantiated exception specifications.
5112  //
5113  // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint what
5114  // else could be fused during an AST merge.
5115 
5116  return FoundDef;
5117  }
5118  } else { // We either couldn't find any previous specialization in the "To"
5119  // context, or we found one but without definition. Let's create a
5120  // new specialization and register that at the class template.
5121 
5122  // Import the location of this declaration.
5123  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5124  if (!BeginLocOrErr)
5125  return BeginLocOrErr.takeError();
5126  ExpectedSLoc IdLocOrErr = import(D->getLocation());
5127  if (!IdLocOrErr)
5128  return IdLocOrErr.takeError();
5129 
5130  if (PartialSpec) {
5131  // Import TemplateArgumentListInfo.
5132  TemplateArgumentListInfo ToTAInfo;
5133  const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5134  if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5135  return std::move(Err);
5136 
5137  QualType CanonInjType;
5138  if (Error Err = importInto(
5139  CanonInjType, PartialSpec->getInjectedSpecializationType()))
5140  return std::move(Err);
5141  CanonInjType = CanonInjType.getCanonicalType();
5142 
5143  auto ToTPListOrErr = ImportTemplateParameterList(
5144  PartialSpec->getTemplateParameters());
5145  if (!ToTPListOrErr)
5146  return ToTPListOrErr.takeError();
5147 
5148  if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5149  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5150  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate,
5151  llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5152  ToTAInfo, CanonInjType,
5153  cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5154  return D2;
5155 
5156  // Update InsertPos, because preceding import calls may have invalidated
5157  // it by adding new specializations.
5158  if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
5159  // Add this partial specialization to the class template.
5160  ClassTemplate->AddPartialSpecialization(
5161  cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
5162 
5163  } else { // Not a partial specialization.
5164  if (GetImportedOrCreateDecl(
5165  D2, D, Importer.getToContext(), D->getTagKind(), DC,
5166  *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5167  PrevDecl))
5168  return D2;
5169 
5170  // Update InsertPos, because preceding import calls may have invalidated
5171  // it by adding new specializations.
5172  if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5173  // Add this specialization to the class template.
5174  ClassTemplate->AddSpecialization(D2, InsertPos);
5175  }
5176 
5178 
5179  // Import the qualifier, if any.
5180  if (auto LocOrErr = import(D->getQualifierLoc()))
5181  D2->setQualifierInfo(*LocOrErr);
5182  else
5183  return LocOrErr.takeError();
5184 
5185  if (auto *TSI = D->getTypeAsWritten()) {
5186  if (auto TInfoOrErr = import(TSI))
5187  D2->setTypeAsWritten(*TInfoOrErr);
5188  else
5189  return TInfoOrErr.takeError();
5190 
5191  if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5192  D2->setTemplateKeywordLoc(*LocOrErr);
5193  else
5194  return LocOrErr.takeError();
5195 
5196  if (auto LocOrErr = import(D->getExternLoc()))
5197  D2->setExternLoc(*LocOrErr);
5198  else
5199  return LocOrErr.takeError();
5200  }
5201 
5202  if (D->getPointOfInstantiation().isValid()) {
5203  if (auto POIOrErr = import(D->getPointOfInstantiation()))
5204  D2->setPointOfInstantiation(*POIOrErr);
5205  else
5206  return POIOrErr.takeError();
5207  }
5208 
5210 
5211  // Set the context of this specialization/instantiation.
5212  D2->setLexicalDeclContext(LexicalDC);
5213 
5214  // Add to the DC only if it was an explicit specialization/instantiation.
5216  LexicalDC->addDeclInternal(D2);
5217  }
5218  }
5219  if (D->isCompleteDefinition())
5220  if (Error Err = ImportDefinition(D, D2))
5221  return std::move(Err);
5222 
5223  return D2;
5224 }
5225 
5227  // If this variable has a definition in the translation unit we're coming
5228  // from,
5229  // but this particular declaration is not that definition, import the
5230  // definition and map to that.
5231  auto *Definition =
5232  cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
5233  if (Definition && Definition != D->getTemplatedDecl()) {
5234  if (ExpectedDecl ImportedDefOrErr = import(
5235  Definition->getDescribedVarTemplate()))
5236  return Importer.MapImported(D, *ImportedDefOrErr);
5237  else
5238  return ImportedDefOrErr.takeError();
5239  }
5240 
5241  // Import the major distinguishing characteristics of this variable template.
5242  DeclContext *DC, *LexicalDC;
5243  DeclarationName Name;
5244  SourceLocation Loc;
5245  NamedDecl *ToD;
5246  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5247  return std::move(Err);
5248  if (ToD)
5249  return ToD;
5250 
5251  // We may already have a template of the same name; try to find and match it.
5252  assert(!DC->isFunctionOrMethod() &&
5253  "Variable templates cannot be declared at function scope");
5254  SmallVector<NamedDecl *, 4> ConflictingDecls;
5255  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5256  for (auto *FoundDecl : FoundDecls) {
5258  continue;
5259 
5260  Decl *Found = FoundDecl;
5261  if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
5262  if (IsStructuralMatch(D, FoundTemplate)) {
5263  // The variable templates structurally match; call it the same template.
5264  Importer.MapImported(D->getTemplatedDecl(),
5265  FoundTemplate->getTemplatedDecl());
5266  return Importer.MapImported(D, FoundTemplate);
5267  }
5268  }
5269 
5270  ConflictingDecls.push_back(FoundDecl);
5271  }
5272 
5273  if (!ConflictingDecls.empty()) {
5274  Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
5275  ConflictingDecls.data(),
5276  ConflictingDecls.size());
5277  }
5278 
5279  if (!Name)
5280  // FIXME: Is it possible to get other error than name conflict?
5281  // (Put this `if` into the previous `if`?)
5282  return make_error<ImportError>(ImportError::NameConflict);
5283 
5284  VarDecl *DTemplated = D->getTemplatedDecl();
5285 
5286  // Import the type.
5287  // FIXME: Value not used?
5288  ExpectedType TypeOrErr = import(DTemplated->getType());
5289  if (!TypeOrErr)
5290  return TypeOrErr.takeError();
5291 
5292  // Create the declaration that is being templated.
5293  VarDecl *ToTemplated;
5294  if (Error Err = importInto(ToTemplated, DTemplated))
5295  return std::move(Err);
5296 
5297  // Create the variable template declaration itself.
5298  auto TemplateParamsOrErr = ImportTemplateParameterList(
5299  D->getTemplateParameters());
5300  if (!TemplateParamsOrErr)
5301  return TemplateParamsOrErr.takeError();
5302 
5303  VarTemplateDecl *ToVarTD;
5304  if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5305  Name, *TemplateParamsOrErr, ToTemplated))
5306  return ToVarTD;
5307 
5308  ToTemplated->setDescribedVarTemplate(ToVarTD);
5309 
5310  ToVarTD->setAccess(D->getAccess());
5311  ToVarTD->setLexicalDeclContext(LexicalDC);
5312  LexicalDC->addDeclInternal(ToVarTD);
5313 
5314  if (DTemplated->isThisDeclarationADefinition() &&
5315  !ToTemplated->isThisDeclarationADefinition()) {
5316  // FIXME: Import definition!
5317  }
5318 
5319  return ToVarTD;
5320 }
5321 
5324  // If this record has a definition in the translation unit we're coming from,
5325  // but this particular declaration is not that definition, import the
5326  // definition and map to that.
5327  VarDecl *Definition = D->getDefinition();
5328  if (Definition && Definition != D) {
5329  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5330  return Importer.MapImported(D, *ImportedDefOrErr);
5331  else
5332  return ImportedDefOrErr.takeError();
5333  }
5334 
5335  VarTemplateDecl *VarTemplate;
5336  if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5337  return std::move(Err);
5338 
5339  // Import the context of this declaration.
5340  DeclContext *DC, *LexicalDC;
5341  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5342  return std::move(Err);
5343 
5344  // Import the location of this declaration.
5345  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5346  if (!BeginLocOrErr)
5347  return BeginLocOrErr.takeError();
5348 
5349  auto IdLocOrErr = import(D->getLocation());
5350  if (!IdLocOrErr)
5351  return IdLocOrErr.takeError();
5352 
5353  // Import template arguments.
5354  SmallVector<TemplateArgument, 2> TemplateArgs;
5355  if (Error Err = ImportTemplateArguments(
5356  D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5357  return std::move(Err);
5358 
5359  // Try to find an existing specialization with these template arguments.
5360  void *InsertPos = nullptr;
5362  TemplateArgs, InsertPos);
5363  if (D2) {
5364  // We already have a variable template specialization with these template
5365  // arguments.
5366 
5367  // FIXME: Check for specialization vs. instantiation errors.
5368 
5369  if (VarDecl *FoundDef = D2->getDefinition()) {
5370  if (!D->isThisDeclarationADefinition() ||
5371  IsStructuralMatch(D, FoundDef)) {
5372  // The record types structurally match, or the "from" translation
5373  // unit only had a forward declaration anyway; call it the same
5374  // variable.
5375  return Importer.MapImported(D, FoundDef);
5376  }
5377  }
5378  } else {
5379  // Import the type.
5380  QualType T;
5381  if (Error Err = importInto(T, D->getType()))
5382  return std::move(Err);
5383 
5384  auto TInfoOrErr = import(D->getTypeSourceInfo());
5385  if (!TInfoOrErr)
5386  return TInfoOrErr.takeError();
5387 
5388  TemplateArgumentListInfo ToTAInfo;
5389  if (Error Err = ImportTemplateArgumentListInfo(
5390  D->getTemplateArgsInfo(), ToTAInfo))
5391  return std::move(Err);
5392 
5393  using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5394  // Create a new specialization.
5395  if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5396  // Import TemplateArgumentListInfo
5397  TemplateArgumentListInfo ArgInfos;
5398  const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5399  // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5400  if (Error Err = ImportTemplateArgumentListInfo(
5401  *FromTAArgsAsWritten, ArgInfos))
5402  return std::move(Err);
5403 
5404  auto ToTPListOrErr = ImportTemplateParameterList(
5405  FromPartial->getTemplateParameters());
5406  if (!ToTPListOrErr)
5407  return ToTPListOrErr.takeError();
5408 
5409  PartVarSpecDecl *ToPartial;
5410  if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5411  *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5412  VarTemplate, T, *TInfoOrErr,
5413  D->getStorageClass(), TemplateArgs, ArgInfos))
5414  return ToPartial;
5415 
5416  if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5417  FromPartial->getInstantiatedFromMember()))
5418  ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5419  else
5420  return ToInstOrErr.takeError();
5421 
5422  if (FromPartial->isMemberSpecialization())
5423  ToPartial->setMemberSpecialization();
5424 
5425  D2 = ToPartial;
5426 
5427  } else { // Full specialization
5428  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5429  *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5430  T, *TInfoOrErr,
5431  D->getStorageClass(), TemplateArgs))
5432  return D2;
5433  }
5434 
5435  if (D->getPointOfInstantiation().isValid()) {
5436  if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5437  D2->setPointOfInstantiation(*POIOrErr);
5438  else
5439  return POIOrErr.takeError();
5440  }
5441 
5443  D2->setTemplateArgsInfo(ToTAInfo);
5444 
5445  // Add this specialization to the class template.
5446  VarTemplate->AddSpecialization(D2, InsertPos);
5447 
5448  // Import the qualifier, if any.
5449  if (auto LocOrErr = import(D->getQualifierLoc()))
5450  D2->setQualifierInfo(*LocOrErr);
5451  else
5452  return LocOrErr.takeError();
5453 
5454  if (D->isConstexpr())
5455  D2->setConstexpr(true);
5456 
5457  // Add the specialization to this context.
5458  D2->setLexicalDeclContext(LexicalDC);
5459  LexicalDC->addDeclInternal(D2);
5460 
5461  D2->setAccess(D->getAccess());
5462  }
5463 
5464  if (Error Err = ImportInitializer(D, D2))
5465  return std::move(Err);
5466 
5467  return D2;
5468 }
5469 
5472  DeclContext *DC, *LexicalDC;
5473  DeclarationName Name;
5474  SourceLocation Loc;
5475  NamedDecl *ToD;
5476 
5477  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5478  return std::move(Err);
5479 
5480  if (ToD)
5481  return ToD;
5482 
5483  // Try to find a function in our own ("to") context with the same name, same
5484  // type, and in the same context as the function we're importing.
5485  if (!LexicalDC->isFunctionOrMethod()) {
5486  unsigned IDNS = Decl::IDNS_Ordinary;
5487  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5488  for (auto *FoundDecl : FoundDecls) {
5489  if (!FoundDecl->isInIdentifierNamespace(IDNS))
5490  continue;
5491 
5492  if (auto *FoundFunction =
5493  dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5494  if (FoundFunction->hasExternalFormalLinkage() &&
5495  D->hasExternalFormalLinkage()) {
5496  if (IsStructuralMatch(D, FoundFunction)) {
5497  Importer.MapImported(D, FoundFunction);
5498  // FIXME: Actually try to merge the body and other attributes.
5499  return FoundFunction;
5500  }
5501  }
5502  }
5503  // TODO: handle conflicting names
5504  }
5505  }
5506 
5507  auto ParamsOrErr = ImportTemplateParameterList(
5508  D->getTemplateParameters());
5509  if (!ParamsOrErr)
5510  return ParamsOrErr.takeError();
5511 
5512  FunctionDecl *TemplatedFD;
5513  if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5514  return std::move(Err);
5515 
5516  FunctionTemplateDecl *ToFunc;
5517  if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5518  *ParamsOrErr, TemplatedFD))
5519  return ToFunc;
5520 
5521  TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5522  ToFunc->setAccess(D->getAccess());
5523  ToFunc->setLexicalDeclContext(LexicalDC);
5524 
5525  LexicalDC->addDeclInternal(ToFunc);
5526  return ToFunc;
5527 }
5528 
5529 //----------------------------------------------------------------------------
5530 // Import Statements
5531 //----------------------------------------------------------------------------
5532 
5534  Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5535  << S->getStmtClassName();
5536  return make_error<ImportError>(ImportError::UnsupportedConstruct);
5537 }
5538 
5539 
5542  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5543  IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5544  // ToII is nullptr when no symbolic name is given for output operand
5545  // see ParseStmtAsm::ParseAsmOperandsOpt
5546  Names.push_back(ToII);
5547  }
5548 
5549  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5550  IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5551  // ToII is nullptr when no symbolic name is given for input operand
5552  // see ParseStmtAsm::ParseAsmOperandsOpt
5553  Names.push_back(ToII);
5554  }
5555 
5557  for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5558  if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5559  Clobbers.push_back(*ClobberOrErr);
5560  else
5561  return ClobberOrErr.takeError();
5562 
5563  }
5564 
5565  SmallVector<StringLiteral *, 4> Constraints;
5566  for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5567  if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5568  Constraints.push_back(*OutputOrErr);
5569  else
5570  return OutputOrErr.takeError();
5571  }
5572 
5573  for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5574  if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
5575  Constraints.push_back(*InputOrErr);
5576  else
5577  return InputOrErr.takeError();
5578  }
5579 
5581  if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
5582  return std::move(Err);
5583 
5584  if (Error Err = ImportArrayChecked(
5585  S->inputs(), Exprs.begin() + S->getNumOutputs()))
5586  return std::move(Err);
5587 
5588  ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
5589  if (!AsmLocOrErr)
5590  return AsmLocOrErr.takeError();
5591  auto AsmStrOrErr = import(S->getAsmString());
5592  if (!AsmStrOrErr)
5593  return AsmStrOrErr.takeError();
5594  ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
5595  if (!RParenLocOrErr)
5596  return RParenLocOrErr.takeError();
5597 
5598  return new (Importer.getToContext()) GCCAsmStmt(
5599  Importer.getToContext(),
5600  *AsmLocOrErr,
5601  S->isSimple(),
5602  S->isVolatile(),
5603  S->getNumOutputs(),
5604  S->getNumInputs(),
5605  Names.data(),
5606  Constraints.data(),
5607  Exprs.data(),
5608  *AsmStrOrErr,
5609  S->getNumClobbers(),
5610  Clobbers.data(),
5611  *RParenLocOrErr);
5612 }
5613 
5615  auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc());
5616  if (!Imp)
5617  return Imp.takeError();
5618 
5619  DeclGroupRef ToDG;
5620  SourceLocation ToBeginLoc, ToEndLoc;
5621  std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp;
5622 
5623  return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
5624 }
5625 
5627  ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
5628  if (!ToSemiLocOrErr)
5629  return ToSemiLocOrErr.takeError();
5630  return new (Importer.getToContext()) NullStmt(
5631  *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
5632 }
5633 
5635  SmallVector<Stmt *, 8> ToStmts(S->size());
5636 
5637  if (Error Err = ImportContainerChecked(S->body(), ToStmts))
5638  return std::move(Err);
5639 
5640  ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
5641  if (!ToLBracLocOrErr)
5642  return ToLBracLocOrErr.takeError();
5643 
5644  ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
5645  if (!ToRBracLocOrErr)
5646  return ToRBracLocOrErr.takeError();
5647 
5648  return CompoundStmt::Create(
5649  Importer.getToContext(), ToStmts,
5650  *ToLBracLocOrErr, *ToRBracLocOrErr);
5651 }
5652 
5654  auto Imp = importSeq(
5655  S->getLHS(), S->getRHS(), S->getSubStmt(), S->getCaseLoc(),
5656  S->getEllipsisLoc(), S->getColonLoc());
5657  if (!Imp)
5658  return Imp.takeError();
5659 
5660  Expr *ToLHS, *ToRHS;
5661  Stmt *ToSubStmt;
5662  SourceLocation ToCaseLoc, ToEllipsisLoc, ToColonLoc;
5663  std::tie(ToLHS, ToRHS, ToSubStmt, ToCaseLoc, ToEllipsisLoc, ToColonLoc) =
5664  *Imp;
5665 
5666  auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
5667  ToCaseLoc, ToEllipsisLoc, ToColonLoc);
5668  ToStmt->setSubStmt(ToSubStmt);
5669 
5670  return ToStmt;
5671 }
5672 
5674  auto Imp = importSeq(S->getDefaultLoc(), S->getColonLoc(), S->getSubStmt());
5675  if (!Imp)
5676  return Imp.takeError();
5677 
5678  SourceLocation ToDefaultLoc, ToColonLoc;
5679  Stmt *ToSubStmt;
5680  std::tie(ToDefaultLoc, ToColonLoc, ToSubStmt) = *Imp;
5681 
5682  return new (Importer.getToContext()) DefaultStmt(
5683  ToDefaultLoc, ToColonLoc, ToSubStmt);
5684 }
5685 
5687  auto Imp = importSeq(S->getIdentLoc(), S->getDecl(), S->getSubStmt());
5688  if (!Imp)
5689  return Imp.takeError();
5690 
5691  SourceLocation ToIdentLoc;
5692  LabelDecl *ToLabelDecl;
5693  Stmt *ToSubStmt;
5694  std::tie(ToIdentLoc, ToLabelDecl, ToSubStmt) = *Imp;
5695 
5696  return new (Importer.getToContext()) LabelStmt(
5697  ToIdentLoc, ToLabelDecl, ToSubStmt);
5698 }
5699 
5701  ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
5702  if (!ToAttrLocOrErr)
5703  return ToAttrLocOrErr.takeError();
5704  ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5705  SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5706  if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
5707  return std::move(Err);
5708  ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
5709  if (!ToSubStmtOrErr)
5710  return ToSubStmtOrErr.takeError();
5711 
5712  return AttributedStmt::Create(
5713  Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
5714 }
5715 
5717  auto Imp = importSeq(
5718  S->getIfLoc(), S->getInit(), S->getConditionVariable(), S->getCond(),
5719  S->getThen(), S->getElseLoc(), S->getElse());
5720  if (!Imp)
5721  return Imp.takeError();
5722 
5723  SourceLocation ToIfLoc, ToElseLoc;
5724  Stmt *ToInit, *ToThen, *ToElse;
5725  VarDecl *ToConditionVariable;
5726  Expr *ToCond;
5727  std::tie(
5728  ToIfLoc, ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, ToElse) =
5729  *Imp;
5730 
5731  return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(),
5732  ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc,
5733  ToElse);
5734 }
5735 
5737  auto Imp = importSeq(
5738  S->getInit(), S->getConditionVariable(), S->getCond(),
5739  S->getBody(), S->getSwitchLoc());
5740  if (!Imp)
5741  return Imp.takeError();
5742 
5743  Stmt *ToInit, *ToBody;
5744  VarDecl *ToConditionVariable;
5745  Expr *ToCond;
5746  SourceLocation ToSwitchLoc;
5747  std::tie(ToInit, ToConditionVariable, ToCond, ToBody, ToSwitchLoc) = *Imp;
5748 
5749  auto *ToStmt = SwitchStmt::Create(Importer.getToContext(), ToInit,
5750  ToConditionVariable, ToCond);
5751  ToStmt->setBody(ToBody);
5752  ToStmt->setSwitchLoc(ToSwitchLoc);
5753 
5754  // Now we have to re-chain the cases.
5755  SwitchCase *LastChainedSwitchCase = nullptr;
5756  for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5757  SC = SC->getNextSwitchCase()) {
5758  Expected<SwitchCase *> ToSCOrErr = import(SC);
5759  if (!ToSCOrErr)
5760  return ToSCOrErr.takeError();
5761  if (LastChainedSwitchCase)
5762  LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
5763  else
5764  ToStmt->setSwitchCaseList(*ToSCOrErr);
5765  LastChainedSwitchCase = *ToSCOrErr;
5766  }
5767 
5768  return ToStmt;
5769 }
5770 
5772  auto Imp = importSeq(
5773  S->getConditionVar