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