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