clang  14.0.0git
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"
47 #include "clang/Basic/Builtins.h"
51 #include "clang/Basic/LLVM.h"
55 #include "clang/Basic/Specifiers.h"
56 #include "llvm/ADT/APSInt.h"
57 #include "llvm/ADT/ArrayRef.h"
58 #include "llvm/ADT/DenseMap.h"
59 #include "llvm/ADT/None.h"
60 #include "llvm/ADT/Optional.h"
61 #include "llvm/ADT/ScopeExit.h"
62 #include "llvm/ADT/STLExtras.h"
63 #include "llvm/ADT/SmallVector.h"
64 #include "llvm/Support/Casting.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/MemoryBuffer.h"
67 #include <algorithm>
68 #include <cassert>
69 #include <cstddef>
70 #include <memory>
71 #include <type_traits>
72 #include <utility>
73 
74 namespace clang {
75 
76  using llvm::make_error;
77  using llvm::Error;
78  using llvm::Expected;
85 
87  // FIXME: Improve error texts.
88  switch (Error) {
89  case NameConflict:
90  return "NameConflict";
92  return "UnsupportedConstruct";
93  case Unknown:
94  return "Unknown error";
95  }
96  llvm_unreachable("Invalid error code.");
97  return "Invalid error code.";
98  }
99 
100  void ImportError::log(raw_ostream &OS) const {
101  OS << toString();
102  }
103 
104  std::error_code ImportError::convertToErrorCode() const {
105  llvm_unreachable("Function not implemented.");
106  }
107 
108  char ImportError::ID;
109 
110  template <class T>
113  SmallVector<Decl *, 2> Redecls;
114  for (auto *R : D->getFirstDecl()->redecls()) {
115  if (R != D->getFirstDecl())
116  Redecls.push_back(R);
117  }
118  Redecls.push_back(D->getFirstDecl());
119  std::reverse(Redecls.begin(), Redecls.end());
120  return Redecls;
121  }
122 
124  if (auto *FD = dyn_cast<FunctionDecl>(D))
125  return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
126  if (auto *VD = dyn_cast<VarDecl>(D))
127  return getCanonicalForwardRedeclChain<VarDecl>(VD);
128  if (auto *TD = dyn_cast<TagDecl>(D))
129  return getCanonicalForwardRedeclChain<TagDecl>(TD);
130  llvm_unreachable("Bad declaration kind");
131  }
132 
133  void updateFlags(const Decl *From, Decl *To) {
134  // Check if some flags or attrs are new in 'From' and copy into 'To'.
135  // FIXME: Other flags or attrs?
136  if (From->isUsed(false) && !To->isUsed(false))
137  To->setIsUsed();
138  }
139 
140  class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
141  public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
142  public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
143  ASTImporter &Importer;
144 
145  // Use this instead of Importer.importInto .
146  template <typename ImportT>
147  LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) {
148  return Importer.importInto(To, From);
149  }
150 
151  // Use this to import pointers of specific type.
152  template <typename ImportT>
153  LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) {
154  auto ToOrErr = Importer.Import(From);
155  if (ToOrErr)
156  To = cast_or_null<ImportT>(*ToOrErr);
157  return ToOrErr.takeError();
158  }
159 
160  // Call the import function of ASTImporter for a baseclass of type `T` and
161  // cast the return value to `T`.
162  template <typename T>
163  Expected<T *> import(T *From) {
164  auto ToOrErr = Importer.Import(From);
165  if (!ToOrErr)
166  return ToOrErr.takeError();
167  return cast_or_null<T>(*ToOrErr);
168  }
169 
170  template <typename T>
171  Expected<T *> import(const T *From) {
172  return import(const_cast<T *>(From));
173  }
174 
175  // Call the import function of ASTImporter for type `T`.
176  template <typename T>
177  Expected<T> import(const T &From) {
178  return Importer.Import(From);
179  }
180 
181  // Import an Optional<T> by importing the contained T, if any.
182  template<typename T>
183  Expected<Optional<T>> import(Optional<T> From) {
184  if (!From)
185  return Optional<T>();
186  return import(*From);
187  }
188 
189  ExplicitSpecifier importExplicitSpecifier(Error &Err,
190  ExplicitSpecifier ESpec);
191 
192  // Wrapper for an overload set.
193  template <typename ToDeclT> struct CallOverloadedCreateFun {
194  template <typename... Args> decltype(auto) operator()(Args &&... args) {
195  return ToDeclT::Create(std::forward<Args>(args)...);
196  }
197  };
198 
199  // Always use these functions to create a Decl during import. There are
200  // certain tasks which must be done after the Decl was created, e.g. we
201  // must immediately register that as an imported Decl. The parameter `ToD`
202  // will be set to the newly created Decl or if had been imported before
203  // then to the already imported Decl. Returns a bool value set to true if
204  // the `FromD` had been imported before.
205  template <typename ToDeclT, typename FromDeclT, typename... Args>
206  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
207  Args &&... args) {
208  // There may be several overloads of ToDeclT::Create. We must make sure
209  // to call the one which would be chosen by the arguments, thus we use a
210  // wrapper for the overload set.
211  CallOverloadedCreateFun<ToDeclT> OC;
212  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
213  std::forward<Args>(args)...);
214  }
215  // Use this overload if a special Type is needed to be created. E.g if we
216  // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
217  // then:
218  // TypedefNameDecl *ToTypedef;
219  // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
220  template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
221  typename... Args>
222  LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
223  Args &&... args) {
224  CallOverloadedCreateFun<NewDeclT> OC;
225  return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
226  std::forward<Args>(args)...);
227  }
228  // Use this version if a special create function must be
229  // used, e.g. CXXRecordDecl::CreateLambda .
230  template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
231  typename... Args>
232  LLVM_NODISCARD bool
233  GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
234  FromDeclT *FromD, Args &&... args) {
235  if (Importer.getImportDeclErrorIfAny(FromD)) {
236  ToD = nullptr;
237  return true; // Already imported but with error.
238  }
239  ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
240  if (ToD)
241  return true; // Already imported.
242  ToD = CreateFun(std::forward<Args>(args)...);
243  // Keep track of imported Decls.
244  Importer.RegisterImportedDecl(FromD, ToD);
245  InitializeImportedDecl(FromD, ToD);
246  return false; // A new Decl is created.
247  }
248 
249  void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
251  if (FromD->isUsed())
252  ToD->setIsUsed();
253  if (FromD->isImplicit())
254  ToD->setImplicit();
255  }
256 
257  // Check if we have found an existing definition. Returns with that
258  // definition if yes, otherwise returns null.
259  Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
260  const FunctionDecl *Definition = nullptr;
261  if (D->doesThisDeclarationHaveABody() &&
262  FoundFunction->hasBody(Definition))
263  return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
264  return nullptr;
265  }
266 
267  void addDeclToContexts(Decl *FromD, Decl *ToD) {
268  if (Importer.isMinimalImport()) {
269  // In minimal import case the decl must be added even if it is not
270  // contained in original context, for LLDB compatibility.
271  // FIXME: Check if a better solution is possible.
272  if (!FromD->getDescribedTemplate() &&
275  return;
276  }
277 
278  DeclContext *FromDC = FromD->getDeclContext();
279  DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
280  DeclContext *ToDC = ToD->getDeclContext();
281  DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
282 
283  bool Visible = false;
284  if (FromDC->containsDeclAndLoad(FromD)) {
285  ToDC->addDeclInternal(ToD);
286  Visible = true;
287  }
288  if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
289  ToLexicalDC->addDeclInternal(ToD);
290  Visible = true;
291  }
292 
293  // If the Decl was added to any context, it was made already visible.
294  // Otherwise it is still possible that it should be visible.
295  if (!Visible) {
296  if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
297  auto *ToNamed = cast<NamedDecl>(ToD);
298  DeclContextLookupResult FromLookup =
299  FromDC->lookup(FromNamed->getDeclName());
300  for (NamedDecl *ND : FromLookup)
301  if (ND == FromNamed) {
302  ToDC->makeDeclVisibleInContext(ToNamed);
303  break;
304  }
305  }
306  }
307  }
308 
309  void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
310  DeclContext *OldDC) {
311  ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
312  if (!LT)
313  return;
314 
315  for (NamedDecl *TP : Params)
316  LT->update(TP, OldDC);
317  }
318 
319  void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
320  updateLookupTableForTemplateParameters(
321  Params, Importer.getToContext().getTranslationUnitDecl());
322  }
323 
324  public:
325  explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
326 
330 
331  // Importing types
332  ExpectedType VisitType(const Type *T);
346  // FIXME: DependentSizedExtVectorType
355  // FIXME: DependentTypeOfExprType
363  // FIXME: DependentDecltypeType
369  const SubstTemplateTypeParmType *T);
373  const TemplateSpecializationType *T);
382 
383  // Importing declarations
385  SourceLocation &Loc);
387  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
388  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
389  Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
391  const DeclarationNameInfo &From, DeclarationNameInfo &To);
392  Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
394  Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
396 
398  Expected<APValue> ImportAPValue(const APValue &FromValue);
399 
401 
402  /// What we should import from the definition.
404  /// Import the default subset of the definition, which might be
405  /// nothing (if minimal import is set) or might be everything (if minimal
406  /// import is not set).
408  /// Import everything.
410  /// Import only the bare bones needed to establish a valid
411  /// DeclContext.
413  };
414 
416  return IDK == IDK_Everything ||
417  (IDK == IDK_Default && !Importer.isMinimalImport());
418  }
419 
422  RecordDecl *From, RecordDecl *To,
425  EnumDecl *From, EnumDecl *To,
434  const TemplateArgument *FromArgs, unsigned NumFromArgs,
438 
439  template <typename InContainerTy>
441  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
442 
443  template<typename InContainerTy>
445  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
446  const InContainerTy &Container, TemplateArgumentListInfo &Result);
447 
450  std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
453  FunctionDecl *FromFD);
455  DeclaratorDecl *ToD);
456 
458 
460 
462  ParmVarDecl *ToParam);
463 
464  template <typename T>
465  bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
466 
467  bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
468  bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
469  bool Complain = true);
470  bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
471  bool Complain = true);
472  bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
524 
527 
542 
543  // Importing statements
563  // FIXME: MSAsmStmt
564  // FIXME: SEHExceptStmt
565  // FIXME: SEHFinallyStmt
566  // FIXME: SEHTryStmt
567  // FIXME: SEHLeaveStmt
568  // FIXME: CapturedStmt
572  // FIXME: MSDependentExistsStmt
580 
581  // Importing expressions
655 
656  // Helper for chaining together multiple imports. If an error is detected,
657  // subsequent imports will return default constructed nodes, so that failure
658  // can be detected with a single conditional branch after a sequence of
659  // imports.
660  template <typename T> T importChecked(Error &Err, const T &From) {
661  // Don't attempt to import nodes if we hit an error earlier.
662  if (Err)
663  return T{};
664  Expected<T> MaybeVal = import(From);
665  if (!MaybeVal) {
666  Err = MaybeVal.takeError();
667  return T{};
668  }
669  return *MaybeVal;
670  }
671 
672  template<typename IIter, typename OIter>
673  Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
674  using ItemT = std::remove_reference_t<decltype(*Obegin)>;
675  for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
676  Expected<ItemT> ToOrErr = import(*Ibegin);
677  if (!ToOrErr)
678  return ToOrErr.takeError();
679  *Obegin = *ToOrErr;
680  }
681  return Error::success();
682  }
683 
684  // Import every item from a container structure into an output container.
685  // If error occurs, stops at first error and returns the error.
686  // The output container should have space for all needed elements (it is not
687  // expanded, new items are put into from the beginning).
688  template<typename InContainerTy, typename OutContainerTy>
690  const InContainerTy &InContainer, OutContainerTy &OutContainer) {
691  return ImportArrayChecked(
692  InContainer.begin(), InContainer.end(), OutContainer.begin());
693  }
694 
695  template<typename InContainerTy, typename OIter>
696  Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
697  return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
698  }
699 
701  CXXMethodDecl *FromMethod);
702 
704  FunctionDecl *FromFD);
705 
706  // Returns true if the given function has a placeholder return type and
707  // that type is declared inside the body of the function.
708  // E.g. auto f() { struct X{}; return X(); }
710  };
711 
712 template <typename InContainerTy>
714  SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
715  const InContainerTy &Container, TemplateArgumentListInfo &Result) {
716  auto ToLAngleLocOrErr = import(FromLAngleLoc);
717  if (!ToLAngleLocOrErr)
718  return ToLAngleLocOrErr.takeError();
719  auto ToRAngleLocOrErr = import(FromRAngleLoc);
720  if (!ToRAngleLocOrErr)
721  return ToRAngleLocOrErr.takeError();
722 
723  TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
724  if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
725  return Err;
726  Result = ToTAInfo;
727  return Error::success();
728 }
729 
730 template <>
731 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
732  const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
734  From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
735 }
736 
737 template <>
740  const ASTTemplateArgumentListInfo &From,
741  TemplateArgumentListInfo &Result) {
742  return ImportTemplateArgumentListInfo(
743  From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
744 }
745 
748  FunctionDecl *FromFD) {
749  assert(FromFD->getTemplatedKind() ==
751 
753 
754  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
755  if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
756  return std::move(Err);
757 
758  // Import template arguments.
759  auto TemplArgs = FTSInfo->TemplateArguments->asArray();
760  if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
761  std::get<1>(Result)))
762  return std::move(Err);
763 
764  return Result;
765 }
766 
767 template <>
769 ASTNodeImporter::import(TemplateParameterList *From) {
770  SmallVector<NamedDecl *, 4> To(From->size());
771  if (Error Err = ImportContainerChecked(*From, To))
772  return std::move(Err);
773 
774  ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
775  if (!ToRequiresClause)
776  return ToRequiresClause.takeError();
777 
778  auto ToTemplateLocOrErr = import(From->getTemplateLoc());
779  if (!ToTemplateLocOrErr)
780  return ToTemplateLocOrErr.takeError();
781  auto ToLAngleLocOrErr = import(From->getLAngleLoc());
782  if (!ToLAngleLocOrErr)
783  return ToLAngleLocOrErr.takeError();
784  auto ToRAngleLocOrErr = import(From->getRAngleLoc());
785  if (!ToRAngleLocOrErr)
786  return ToRAngleLocOrErr.takeError();
787 
789  Importer.getToContext(),
790  *ToTemplateLocOrErr,
791  *ToLAngleLocOrErr,
792  To,
793  *ToRAngleLocOrErr,
794  *ToRequiresClause);
795 }
796 
797 template <>
799 ASTNodeImporter::import(const TemplateArgument &From) {
800  switch (From.getKind()) {
802  return TemplateArgument();
803 
804  case TemplateArgument::Type: {
805  ExpectedType ToTypeOrErr = import(From.getAsType());
806  if (!ToTypeOrErr)
807  return ToTypeOrErr.takeError();
808  return TemplateArgument(*ToTypeOrErr);
809  }
810 
812  ExpectedType ToTypeOrErr = import(From.getIntegralType());
813  if (!ToTypeOrErr)
814  return ToTypeOrErr.takeError();
815  return TemplateArgument(From, *ToTypeOrErr);
816  }
817 
819  Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
820  if (!ToOrErr)
821  return ToOrErr.takeError();
822  ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
823  if (!ToTypeOrErr)
824  return ToTypeOrErr.takeError();
825  return TemplateArgument(*ToOrErr, *ToTypeOrErr);
826  }
827 
829  ExpectedType ToTypeOrErr = import(From.getNullPtrType());
830  if (!ToTypeOrErr)
831  return ToTypeOrErr.takeError();
832  return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
833  }
834 
836  Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
837  if (!ToTemplateOrErr)
838  return ToTemplateOrErr.takeError();
839 
840  return TemplateArgument(*ToTemplateOrErr);
841  }
842 
844  Expected<TemplateName> ToTemplateOrErr =
845  import(From.getAsTemplateOrTemplatePattern());
846  if (!ToTemplateOrErr)
847  return ToTemplateOrErr.takeError();
848 
849  return TemplateArgument(
850  *ToTemplateOrErr, From.getNumTemplateExpansions());
851  }
852 
854  if (ExpectedExpr ToExpr = import(From.getAsExpr()))
855  return TemplateArgument(*ToExpr);
856  else
857  return ToExpr.takeError();
858 
859  case TemplateArgument::Pack: {
861  ToPack.reserve(From.pack_size());
862  if (Error Err = ImportTemplateArguments(
863  From.pack_begin(), From.pack_size(), ToPack))
864  return std::move(Err);
865 
866  return TemplateArgument(
867  llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
868  }
869  }
870 
871  llvm_unreachable("Invalid template argument kind");
872 }
873 
874 template <>
876 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
877  Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
878  if (!ArgOrErr)
879  return ArgOrErr.takeError();
880  TemplateArgument Arg = *ArgOrErr;
881 
882  TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
883 
885  if (Arg.getKind() == TemplateArgument::Expression) {
886  ExpectedExpr E = import(FromInfo.getAsExpr());
887  if (!E)
888  return E.takeError();
889  ToInfo = TemplateArgumentLocInfo(*E);
890  } else if (Arg.getKind() == TemplateArgument::Type) {
891  if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
892  ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
893  else
894  return TSIOrErr.takeError();
895  } else {
896  auto ToTemplateQualifierLocOrErr =
897  import(FromInfo.getTemplateQualifierLoc());
898  if (!ToTemplateQualifierLocOrErr)
899  return ToTemplateQualifierLocOrErr.takeError();
900  auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
901  if (!ToTemplateNameLocOrErr)
902  return ToTemplateNameLocOrErr.takeError();
903  auto ToTemplateEllipsisLocOrErr =
904  import(FromInfo.getTemplateEllipsisLoc());
905  if (!ToTemplateEllipsisLocOrErr)
906  return ToTemplateEllipsisLocOrErr.takeError();
907  ToInfo = TemplateArgumentLocInfo(
908  Importer.getToContext(), *ToTemplateQualifierLocOrErr,
909  *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
910  }
911 
912  return TemplateArgumentLoc(Arg, ToInfo);
913 }
914 
915 template <>
916 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
917  if (DG.isNull())
918  return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
919  size_t NumDecls = DG.end() - DG.begin();
920  SmallVector<Decl *, 1> ToDecls;
921  ToDecls.reserve(NumDecls);
922  for (Decl *FromD : DG) {
923  if (auto ToDOrErr = import(FromD))
924  ToDecls.push_back(*ToDOrErr);
925  else
926  return ToDOrErr.takeError();
927  }
928  return DeclGroupRef::Create(Importer.getToContext(),
929  ToDecls.begin(),
930  NumDecls);
931 }
932 
933 template <>
935 ASTNodeImporter::import(const Designator &D) {
936  if (D.isFieldDesignator()) {
937  IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
938 
939  ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
940  if (!ToDotLocOrErr)
941  return ToDotLocOrErr.takeError();
942 
943  ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
944  if (!ToFieldLocOrErr)
945  return ToFieldLocOrErr.takeError();
946 
947  return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
948  }
949 
950  ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
951  if (!ToLBracketLocOrErr)
952  return ToLBracketLocOrErr.takeError();
953 
954  ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
955  if (!ToRBracketLocOrErr)
956  return ToRBracketLocOrErr.takeError();
957 
958  if (D.isArrayDesignator())
959  return Designator(D.getFirstExprIndex(),
960  *ToLBracketLocOrErr, *ToRBracketLocOrErr);
961 
962  ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
963  if (!ToEllipsisLocOrErr)
964  return ToEllipsisLocOrErr.takeError();
965 
966  assert(D.isArrayRangeDesignator());
967  return Designator(
968  D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
969  *ToRBracketLocOrErr);
970 }
971 
972 template <>
973 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
974  VarDecl *Var = nullptr;
975  if (From.capturesVariable()) {
976  if (auto VarOrErr = import(From.getCapturedVar()))
977  Var = *VarOrErr;
978  else
979  return VarOrErr.takeError();
980  }
981 
982  auto LocationOrErr = import(From.getLocation());
983  if (!LocationOrErr)
984  return LocationOrErr.takeError();
985 
986  SourceLocation EllipsisLoc;
987  if (From.isPackExpansion())
988  if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
989  return std::move(Err);
990 
991  return LambdaCapture(
992  *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
993  EllipsisLoc);
994 }
995 
996 template <typename T>
998  if (Found->getLinkageInternal() != From->getLinkageInternal())
999  return false;
1000 
1001  if (From->hasExternalFormalLinkage())
1002  return Found->hasExternalFormalLinkage();
1003  if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1004  return false;
1005  if (From->isInAnonymousNamespace())
1006  return Found->isInAnonymousNamespace();
1007  else
1008  return !Found->isInAnonymousNamespace() &&
1009  !Found->hasExternalFormalLinkage();
1010 }
1011 
1012 template <>
1014  TypedefNameDecl *From) {
1015  if (Found->getLinkageInternal() != From->getLinkageInternal())
1016  return false;
1017 
1018  if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1019  return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1020  return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1021 }
1022 
1023 } // namespace clang
1024 
1025 //----------------------------------------------------------------------------
1026 // Import Types
1027 //----------------------------------------------------------------------------
1028 
1029 using namespace clang;
1030 
1032  Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1033  << T->getTypeClassName();
1034  return make_error<ImportError>(ImportError::UnsupportedConstruct);
1035 }
1036 
1038  ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1039  if (!UnderlyingTypeOrErr)
1040  return UnderlyingTypeOrErr.takeError();
1041 
1042  return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1043 }
1044 
1046  switch (T->getKind()) {
1047 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1048  case BuiltinType::Id: \
1049  return Importer.getToContext().SingletonId;
1050 #include "clang/Basic/OpenCLImageTypes.def"
1051 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1052  case BuiltinType::Id: \
1053  return Importer.getToContext().Id##Ty;
1054 #include "clang/Basic/OpenCLExtensionTypes.def"
1055 #define SVE_TYPE(Name, Id, SingletonId) \
1056  case BuiltinType::Id: \
1057  return Importer.getToContext().SingletonId;
1058 #include "clang/Basic/AArch64SVEACLETypes.def"
1059 #define PPC_VECTOR_TYPE(Name, Id, Size) \
1060  case BuiltinType::Id: \
1061  return Importer.getToContext().Id##Ty;
1062 #include "clang/Basic/PPCTypes.def"
1063 #define RVV_TYPE(Name, Id, SingletonId) \
1064  case BuiltinType::Id: \
1065  return Importer.getToContext().SingletonId;
1066 #include "clang/Basic/RISCVVTypes.def"
1067 #define SHARED_SINGLETON_TYPE(Expansion)
1068 #define BUILTIN_TYPE(Id, SingletonId) \
1069  case BuiltinType::Id: return Importer.getToContext().SingletonId;
1070 #include "clang/AST/BuiltinTypes.def"
1071 
1072  // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1073  // context supports C++.
1074 
1075  // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1076  // context supports ObjC.
1077 
1078  case BuiltinType::Char_U:
1079  // The context we're importing from has an unsigned 'char'. If we're
1080  // importing into a context with a signed 'char', translate to
1081  // 'unsigned char' instead.
1082  if (Importer.getToContext().getLangOpts().CharIsSigned)
1083  return Importer.getToContext().UnsignedCharTy;
1084 
1085  return Importer.getToContext().CharTy;
1086 
1087  case BuiltinType::Char_S:
1088  // The context we're importing from has an unsigned 'char'. If we're
1089  // importing into a context with a signed 'char', translate to
1090  // 'unsigned char' instead.
1091  if (!Importer.getToContext().getLangOpts().CharIsSigned)
1092  return Importer.getToContext().SignedCharTy;
1093 
1094  return Importer.getToContext().CharTy;
1095 
1096  case BuiltinType::WChar_S:
1097  case BuiltinType::WChar_U:
1098  // FIXME: If not in C++, shall we translate to the C equivalent of
1099  // wchar_t?
1100  return Importer.getToContext().WCharTy;
1101  }
1102 
1103  llvm_unreachable("Invalid BuiltinType Kind!");
1104 }
1105 
1107  ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1108  if (!ToOriginalTypeOrErr)
1109  return ToOriginalTypeOrErr.takeError();
1110 
1111  return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1112 }
1113 
1115  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1116  if (!ToElementTypeOrErr)
1117  return ToElementTypeOrErr.takeError();
1118 
1119  return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1120 }
1121 
1123  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1124  if (!ToPointeeTypeOrErr)
1125  return ToPointeeTypeOrErr.takeError();
1126 
1127  return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1128 }
1129 
1131  // FIXME: Check for blocks support in "to" context.
1132  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1133  if (!ToPointeeTypeOrErr)
1134  return ToPointeeTypeOrErr.takeError();
1135 
1136  return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1137 }
1138 
1141  // FIXME: Check for C++ support in "to" context.
1142  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1143  if (!ToPointeeTypeOrErr)
1144  return ToPointeeTypeOrErr.takeError();
1145 
1146  return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1147 }
1148 
1151  // FIXME: Check for C++0x support in "to" context.
1152  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1153  if (!ToPointeeTypeOrErr)
1154  return ToPointeeTypeOrErr.takeError();
1155 
1156  return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1157 }
1158 
1161  // FIXME: Check for C++ support in "to" context.
1162  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1163  if (!ToPointeeTypeOrErr)
1164  return ToPointeeTypeOrErr.takeError();
1165 
1166  ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1167  if (!ClassTypeOrErr)
1168  return ClassTypeOrErr.takeError();
1169 
1170  return Importer.getToContext().getMemberPointerType(
1171  *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1172 }
1173 
1176  Error Err = Error::success();
1177  auto ToElementType = importChecked(Err, T->getElementType());
1178  auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1179  if (Err)
1180  return std::move(Err);
1181 
1182  return Importer.getToContext().getConstantArrayType(
1183  ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1185 }
1186 
1189  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1190  if (!ToElementTypeOrErr)
1191  return ToElementTypeOrErr.takeError();
1192 
1193  return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1194  T->getSizeModifier(),
1196 }
1197 
1200  Error Err = Error::success();
1201  QualType ToElementType = importChecked(Err, T->getElementType());
1202  Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1203  SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1204  if (Err)
1205  return std::move(Err);
1206  return Importer.getToContext().getVariableArrayType(
1207  ToElementType, ToSizeExpr, T->getSizeModifier(),
1208  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1209 }
1210 
1212  const DependentSizedArrayType *T) {
1213  Error Err = Error::success();
1214  QualType ToElementType = importChecked(Err, T->getElementType());
1215  Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1216  SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1217  if (Err)
1218  return std::move(Err);
1219  // SizeExpr may be null if size is not specified directly.
1220  // For example, 'int a[]'.
1221 
1222  return Importer.getToContext().getDependentSizedArrayType(
1223  ToElementType, ToSizeExpr, T->getSizeModifier(),
1224  T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1225 }
1226 
1228  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1229  if (!ToElementTypeOrErr)
1230  return ToElementTypeOrErr.takeError();
1231 
1232  return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1233  T->getNumElements(),
1234  T->getVectorKind());
1235 }
1236 
1238  ExpectedType ToElementTypeOrErr = import(T->getElementType());
1239  if (!ToElementTypeOrErr)
1240  return ToElementTypeOrErr.takeError();
1241 
1242  return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1243  T->getNumElements());
1244 }
1245 
1248  // FIXME: What happens if we're importing a function without a prototype
1249  // into C++? Should we make it variadic?
1250  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1251  if (!ToReturnTypeOrErr)
1252  return ToReturnTypeOrErr.takeError();
1253 
1254  return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1255  T->getExtInfo());
1256 }
1257 
1260  ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1261  if (!ToReturnTypeOrErr)
1262  return ToReturnTypeOrErr.takeError();
1263 
1264  // Import argument types
1265  SmallVector<QualType, 4> ArgTypes;
1266  for (const auto &A : T->param_types()) {
1267  ExpectedType TyOrErr = import(A);
1268  if (!TyOrErr)
1269  return TyOrErr.takeError();
1270  ArgTypes.push_back(*TyOrErr);
1271  }
1272 
1273  // Import exception types
1274  SmallVector<QualType, 4> ExceptionTypes;
1275  for (const auto &E : T->exceptions()) {
1276  ExpectedType TyOrErr = import(E);
1277  if (!TyOrErr)
1278  return TyOrErr.takeError();
1279  ExceptionTypes.push_back(*TyOrErr);
1280  }
1281 
1283  Error Err = Error::success();
1285  ToEPI.ExtInfo = FromEPI.ExtInfo;
1286  ToEPI.Variadic = FromEPI.Variadic;
1287  ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1288  ToEPI.TypeQuals = FromEPI.TypeQuals;
1289  ToEPI.RefQualifier = FromEPI.RefQualifier;
1290  ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1291  ToEPI.ExceptionSpec.NoexceptExpr =
1293  ToEPI.ExceptionSpec.SourceDecl =
1294  importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1297  ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1298 
1299  if (Err)
1300  return std::move(Err);
1301 
1302  return Importer.getToContext().getFunctionType(
1303  *ToReturnTypeOrErr, ArgTypes, ToEPI);
1304 }
1305 
1307  const UnresolvedUsingType *T) {
1308  Error Err = Error::success();
1309  auto ToD = importChecked(Err, T->getDecl());
1310  auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1311  if (Err)
1312  return std::move(Err);
1313 
1314  return Importer.getToContext().getTypeDeclType(
1315  ToD, cast_or_null<TypeDecl>(ToPrevD));
1316 }
1317 
1319  ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1320  if (!ToInnerTypeOrErr)
1321  return ToInnerTypeOrErr.takeError();
1322 
1323  return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1324 }
1325 
1327  Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1328  if (!ToDeclOrErr)
1329  return ToDeclOrErr.takeError();
1330 
1331  return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1332 }
1333 
1335  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1336  if (!ToExprOrErr)
1337  return ToExprOrErr.takeError();
1338 
1339  return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1340 }
1341 
1343  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1344  if (!ToUnderlyingTypeOrErr)
1345  return ToUnderlyingTypeOrErr.takeError();
1346 
1347  return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1348 }
1349 
1351  // FIXME: Make sure that the "to" context supports C++0x!
1352  ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1353  if (!ToExprOrErr)
1354  return ToExprOrErr.takeError();
1355 
1356  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1357  if (!ToUnderlyingTypeOrErr)
1358  return ToUnderlyingTypeOrErr.takeError();
1359 
1360  return Importer.getToContext().getDecltypeType(
1361  *ToExprOrErr, *ToUnderlyingTypeOrErr);
1362 }
1363 
1366  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1367  if (!ToBaseTypeOrErr)
1368  return ToBaseTypeOrErr.takeError();
1369 
1370  ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1371  if (!ToUnderlyingTypeOrErr)
1372  return ToUnderlyingTypeOrErr.takeError();
1373 
1374  return Importer.getToContext().getUnaryTransformType(
1375  *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1376 }
1377 
1379  // FIXME: Make sure that the "to" context supports C++11!
1380  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1381  if (!ToDeducedTypeOrErr)
1382  return ToDeducedTypeOrErr.takeError();
1383 
1384  ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1385  if (!ToTypeConstraintConcept)
1386  return ToTypeConstraintConcept.takeError();
1387 
1388  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1390  if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
1391  FromTemplateArgs.size(),
1392  ToTemplateArgs))
1393  return std::move(Err);
1394 
1395  return Importer.getToContext().getAutoType(
1396  *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1397  /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1398  ToTemplateArgs);
1399 }
1400 
1403  // FIXME: Make sure that the "to" context supports C++17!
1404  Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1405  if (!ToTemplateNameOrErr)
1406  return ToTemplateNameOrErr.takeError();
1407  ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1408  if (!ToDeducedTypeOrErr)
1409  return ToDeducedTypeOrErr.takeError();
1410 
1412  *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1413 }
1414 
1416  const InjectedClassNameType *T) {
1417  Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1418  if (!ToDeclOrErr)
1419  return ToDeclOrErr.takeError();
1420 
1421  ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1422  if (!ToInjTypeOrErr)
1423  return ToInjTypeOrErr.takeError();
1424 
1425  // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1426  // See comments in InjectedClassNameType definition for details
1427  // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1428  enum {
1429  TypeAlignmentInBits = 4,
1431  };
1432 
1433  return QualType(new (Importer.getToContext(), TypeAlignment)
1434  InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1435 }
1436 
1438  Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1439  if (!ToDeclOrErr)
1440  return ToDeclOrErr.takeError();
1441 
1442  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1443 }
1444 
1446  Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1447  if (!ToDeclOrErr)
1448  return ToDeclOrErr.takeError();
1449 
1450  return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1451 }
1452 
1454  ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1455  if (!ToModifiedTypeOrErr)
1456  return ToModifiedTypeOrErr.takeError();
1457  ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1458  if (!ToEquivalentTypeOrErr)
1459  return ToEquivalentTypeOrErr.takeError();
1460 
1461  return Importer.getToContext().getAttributedType(T->getAttrKind(),
1462  *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1463 }
1464 
1466  const TemplateTypeParmType *T) {
1467  Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1468  if (!ToDeclOrErr)
1469  return ToDeclOrErr.takeError();
1470 
1471  return Importer.getToContext().getTemplateTypeParmType(
1472  T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1473 }
1474 
1476  const SubstTemplateTypeParmType *T) {
1477  ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1478  if (!ReplacedOrErr)
1479  return ReplacedOrErr.takeError();
1480  const TemplateTypeParmType *Replaced =
1481  cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1482 
1483  ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1484  if (!ToReplacementTypeOrErr)
1485  return ToReplacementTypeOrErr.takeError();
1486 
1487  return Importer.getToContext().getSubstTemplateTypeParmType(
1488  Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1489 }
1490 
1492  const SubstTemplateTypeParmPackType *T) {
1493  ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1494  if (!ReplacedOrErr)
1495  return ReplacedOrErr.takeError();
1496  const TemplateTypeParmType *Replaced =
1497  cast<TemplateTypeParmType>(ReplacedOrErr->getTypePtr());
1498 
1499  Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
1500  if (!ToArgumentPack)
1501  return ToArgumentPack.takeError();
1502 
1504  Replaced, *ToArgumentPack);
1505 }
1506 
1508  const TemplateSpecializationType *T) {
1509  auto ToTemplateOrErr = import(T->getTemplateName());
1510  if (!ToTemplateOrErr)
1511  return ToTemplateOrErr.takeError();
1512 
1513  SmallVector<TemplateArgument, 2> ToTemplateArgs;
1514  if (Error Err = ImportTemplateArguments(
1515  T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1516  return std::move(Err);
1517 
1518  QualType ToCanonType;
1519  if (!QualType(T, 0).isCanonical()) {
1520  QualType FromCanonType
1521  = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1522  if (ExpectedType TyOrErr = import(FromCanonType))
1523  ToCanonType = *TyOrErr;
1524  else
1525  return TyOrErr.takeError();
1526  }
1527  return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1528  ToTemplateArgs,
1529  ToCanonType);
1530 }
1531 
1533  // Note: the qualifier in an ElaboratedType is optional.
1534  auto ToQualifierOrErr = import(T->getQualifier());
1535  if (!ToQualifierOrErr)
1536  return ToQualifierOrErr.takeError();
1537 
1538  ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1539  if (!ToNamedTypeOrErr)
1540  return ToNamedTypeOrErr.takeError();
1541 
1542  Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1543  if (!ToOwnedTagDeclOrErr)
1544  return ToOwnedTagDeclOrErr.takeError();
1545 
1546  return Importer.getToContext().getElaboratedType(T->getKeyword(),
1547  *ToQualifierOrErr,
1548  *ToNamedTypeOrErr,
1549  *ToOwnedTagDeclOrErr);
1550 }
1551 
1554  ExpectedType ToPatternOrErr = import(T->getPattern());
1555  if (!ToPatternOrErr)
1556  return ToPatternOrErr.takeError();
1557 
1558  return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1559  T->getNumExpansions(),
1560  /*ExpactPack=*/false);
1561 }
1562 
1565  auto ToQualifierOrErr = import(T->getQualifier());
1566  if (!ToQualifierOrErr)
1567  return ToQualifierOrErr.takeError();
1568 
1569  IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1570 
1572  ToPack.reserve(T->getNumArgs());
1573  if (Error Err = ImportTemplateArguments(
1574  T->getArgs(), T->getNumArgs(), ToPack))
1575  return std::move(Err);
1576 
1578  T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1579 }
1580 
1583  auto ToQualifierOrErr = import(T->getQualifier());
1584  if (!ToQualifierOrErr)
1585  return ToQualifierOrErr.takeError();
1586 
1587  IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1588 
1589  QualType Canon;
1590  if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1591  if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1592  Canon = (*TyOrErr).getCanonicalType();
1593  else
1594  return TyOrErr.takeError();
1595  }
1596 
1597  return Importer.getToContext().getDependentNameType(T->getKeyword(),
1598  *ToQualifierOrErr,
1599  Name, Canon);
1600 }
1601 
1604  Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1605  if (!ToDeclOrErr)
1606  return ToDeclOrErr.takeError();
1607 
1608  return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1609 }
1610 
1612  ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1613  if (!ToBaseTypeOrErr)
1614  return ToBaseTypeOrErr.takeError();
1615 
1616  SmallVector<QualType, 4> TypeArgs;
1617  for (auto TypeArg : T->getTypeArgsAsWritten()) {
1618  if (ExpectedType TyOrErr = import(TypeArg))
1619  TypeArgs.push_back(*TyOrErr);
1620  else
1621  return TyOrErr.takeError();
1622  }
1623 
1625  for (auto *P : T->quals()) {
1626  if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1627  Protocols.push_back(*ProtocolOrErr);
1628  else
1629  return ProtocolOrErr.takeError();
1630 
1631  }
1632 
1633  return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1634  Protocols,
1635  T->isKindOfTypeAsWritten());
1636 }
1637 
1640  ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1641  if (!ToPointeeTypeOrErr)
1642  return ToPointeeTypeOrErr.takeError();
1643 
1644  return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1645 }
1646 
1647 //----------------------------------------------------------------------------
1648 // Import Declarations
1649 //----------------------------------------------------------------------------
1651  NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1652  DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1653  // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1654  // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1655  // FIXME: We could support these constructs by importing a different type of
1656  // this parameter and by importing the original type of the parameter only
1657  // after the FunctionDecl is created. See
1658  // VisitFunctionDecl::UsedDifferentProtoType.
1659  DeclContext *OrigDC = D->getDeclContext();
1660  FunctionDecl *FunDecl;
1661  if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1662  FunDecl->hasBody()) {
1663  auto getLeafPointeeType = [](const Type *T) {
1664  while (T->isPointerType() || T->isArrayType()) {
1665  T = T->getPointeeOrArrayElementType();
1666  }
1667  return T;
1668  };
1669  for (const ParmVarDecl *P : FunDecl->parameters()) {
1670  const Type *LeafT =
1671  getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1672  auto *RT = dyn_cast<RecordType>(LeafT);
1673  if (RT && RT->getDecl() == D) {
1674  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1675  << D->getDeclKindName();
1676  return make_error<ImportError>(ImportError::UnsupportedConstruct);
1677  }
1678  }
1679  }
1680 
1681  // Import the context of this declaration.
1682  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1683  return Err;
1684 
1685  // Import the name of this declaration.
1686  if (Error Err = importInto(Name, D->getDeclName()))
1687  return Err;
1688 
1689  // Import the location of this declaration.
1690  if (Error Err = importInto(Loc, D->getLocation()))
1691  return Err;
1692 
1693  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1694  if (ToD)
1695  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1696  return Err;
1697 
1698  return Error::success();
1699 }
1700 
1702  NamedDecl *&ToD, SourceLocation &Loc) {
1703 
1704  // Import the name of this declaration.
1705  if (Error Err = importInto(Name, D->getDeclName()))
1706  return Err;
1707 
1708  // Import the location of this declaration.
1709  if (Error Err = importInto(Loc, D->getLocation()))
1710  return Err;
1711 
1712  ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1713  if (ToD)
1714  if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1715  return Err;
1716 
1717  return Error::success();
1718 }
1719 
1721  if (!FromD)
1722  return Error::success();
1723 
1724  if (!ToD)
1725  if (Error Err = importInto(ToD, FromD))
1726  return Err;
1727 
1728  if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1729  if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1730  if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1731  !ToRecord->getDefinition()) {
1732  if (Error Err = ImportDefinition(FromRecord, ToRecord))
1733  return Err;
1734  }
1735  }
1736  return Error::success();
1737  }
1738 
1739  if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1740  if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1741  if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1742  if (Error Err = ImportDefinition(FromEnum, ToEnum))
1743  return Err;
1744  }
1745  }
1746  return Error::success();
1747  }
1748 
1749  return Error::success();
1750 }
1751 
1752 Error
1754  const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1755  // NOTE: To.Name and To.Loc are already imported.
1756  // We only have to import To.LocInfo.
1757  switch (To.getName().getNameKind()) {
1764  return Error::success();
1765 
1767  if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1768  To.setCXXOperatorNameRange(*ToRangeOrErr);
1769  else
1770  return ToRangeOrErr.takeError();
1771  return Error::success();
1772  }
1774  if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1775  To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1776  else
1777  return LocOrErr.takeError();
1778  return Error::success();
1779  }
1783  if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1784  To.setNamedTypeInfo(*ToTInfoOrErr);
1785  else
1786  return ToTInfoOrErr.takeError();
1787  return Error::success();
1788  }
1789  }
1790  llvm_unreachable("Unknown name kind.");
1791 }
1792 
1793 Error
1795  if (Importer.isMinimalImport() && !ForceImport) {
1796  auto ToDCOrErr = Importer.ImportContext(FromDC);
1797  return ToDCOrErr.takeError();
1798  }
1799 
1800  // We use strict error handling in case of records and enums, but not
1801  // with e.g. namespaces.
1802  //
1803  // FIXME Clients of the ASTImporter should be able to choose an
1804  // appropriate error handling strategy for their needs. For instance,
1805  // they may not want to mark an entire namespace as erroneous merely
1806  // because there is an ODR error with two typedefs. As another example,
1807  // the client may allow EnumConstantDecls with same names but with
1808  // different values in two distinct translation units.
1809  bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1810 
1811  Error ChildErrors = Error::success();
1812  for (auto *From : FromDC->decls()) {
1813  ExpectedDecl ImportedOrErr = import(From);
1814 
1815  // If we are in the process of ImportDefinition(...) for a RecordDecl we
1816  // want to make sure that we are also completing each FieldDecl. There
1817  // are currently cases where this does not happen and this is correctness
1818  // fix since operations such as code generation will expect this to be so.
1819  if (ImportedOrErr) {
1820  FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1821  Decl *ImportedDecl = *ImportedOrErr;
1822  FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
1823  if (FieldFrom && FieldTo) {
1824  RecordDecl *FromRecordDecl = nullptr;
1825  RecordDecl *ToRecordDecl = nullptr;
1826  // If we have a field that is an ArrayType we need to check if the array
1827  // element is a RecordDecl and if so we need to import the definition.
1828  if (FieldFrom->getType()->isArrayType()) {
1829  // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
1830  FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1831  ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1832  }
1833 
1834  if (!FromRecordDecl || !ToRecordDecl) {
1835  const RecordType *RecordFrom =
1836  FieldFrom->getType()->getAs<RecordType>();
1837  const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
1838 
1839  if (RecordFrom && RecordTo) {
1840  FromRecordDecl = RecordFrom->getDecl();
1841  ToRecordDecl = RecordTo->getDecl();
1842  }
1843  }
1844 
1845  if (FromRecordDecl && ToRecordDecl) {
1846  if (FromRecordDecl->isCompleteDefinition() &&
1847  !ToRecordDecl->isCompleteDefinition()) {
1848  Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
1849 
1850  if (Err && AccumulateChildErrors)
1851  ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err));
1852  else
1853  consumeError(std::move(Err));
1854  }
1855  }
1856  }
1857  } else {
1858  if (AccumulateChildErrors)
1859  ChildErrors =
1860  joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1861  else
1862  consumeError(ImportedOrErr.takeError());
1863  }
1864  }
1865 
1866  // We reorder declarations in RecordDecls because they may have another order
1867  // in the "to" context than they have in the "from" context. This may happen
1868  // e.g when we import a class like this:
1869  // struct declToImport {
1870  // int a = c + b;
1871  // int b = 1;
1872  // int c = 2;
1873  // };
1874  // During the import of `a` we import first the dependencies in sequence,
1875  // thus the order would be `c`, `b`, `a`. We will get the normal order by
1876  // first removing the already imported members and then adding them in the
1877  // order as they apper in the "from" context.
1878  //
1879  // Keeping field order is vital because it determines structure layout.
1880  //
1881  // Here and below, we cannot call field_begin() method and its callers on
1882  // ToDC if it has an external storage. Calling field_begin() will
1883  // automatically load all the fields by calling
1884  // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1885  // call ASTImporter::Import(). This is because the ExternalASTSource
1886  // interface in LLDB is implemented by the means of the ASTImporter. However,
1887  // calling an import at this point would result in an uncontrolled import, we
1888  // must avoid that.
1889  const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1890  if (!FromRD)
1891  return ChildErrors;
1892 
1893  auto ToDCOrErr = Importer.ImportContext(FromDC);
1894  if (!ToDCOrErr) {
1895  consumeError(std::move(ChildErrors));
1896  return ToDCOrErr.takeError();
1897  }
1898 
1899  DeclContext *ToDC = *ToDCOrErr;
1900  // Remove all declarations, which may be in wrong order in the
1901  // lexical DeclContext and then add them in the proper order.
1902  for (auto *D : FromRD->decls()) {
1903  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1904  assert(D && "DC contains a null decl");
1905  Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1906  // Remove only the decls which we successfully imported.
1907  if (ToD) {
1908  assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
1909  // Remove the decl from its wrong place in the linked list.
1910  ToDC->removeDecl(ToD);
1911  // Add the decl to the end of the linked list.
1912  // This time it will be at the proper place because the enclosing for
1913  // loop iterates in the original (good) order of the decls.
1914  ToDC->addDeclInternal(ToD);
1915  }
1916  }
1917  }
1918 
1919  return ChildErrors;
1920 }
1921 
1923  Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1924  auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1925  if (!ToDCOrErr)
1926  return ToDCOrErr.takeError();
1927  ToDC = *ToDCOrErr;
1928 
1929  if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1930  auto ToLexicalDCOrErr = Importer.ImportContext(
1931  FromD->getLexicalDeclContext());
1932  if (!ToLexicalDCOrErr)
1933  return ToLexicalDCOrErr.takeError();
1934  ToLexicalDC = *ToLexicalDCOrErr;
1935  } else
1936  ToLexicalDC = ToDC;
1937 
1938  return Error::success();
1939 }
1940 
1942  const CXXRecordDecl *From, CXXRecordDecl *To) {
1943  assert(From->isCompleteDefinition() && To->getDefinition() == To &&
1944  "Import implicit methods to or from non-definition");
1945 
1946  for (CXXMethodDecl *FromM : From->methods())
1947  if (FromM->isImplicit()) {
1948  Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1949  if (!ToMOrErr)
1950  return ToMOrErr.takeError();
1951  }
1952 
1953  return Error::success();
1954 }
1955 
1957  ASTImporter &Importer) {
1958  if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1959  if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1960  To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1961  else
1962  return ToTypedefOrErr.takeError();
1963  }
1964  return Error::success();
1965 }
1966 
1969  auto DefinitionCompleter = [To]() {
1970  // There are cases in LLDB when we first import a class without its
1971  // members. The class will have DefinitionData, but no members. Then,
1972  // importDefinition is called from LLDB, which tries to get the members, so
1973  // when we get here, the class already has the DefinitionData set, so we
1974  // must unset the CompleteDefinition here to be able to complete again the
1975  // definition.
1976  To->setCompleteDefinition(false);
1977  To->completeDefinition();
1978  };
1979 
1980  if (To->getDefinition() || To->isBeingDefined()) {
1981  if (Kind == IDK_Everything ||
1982  // In case of lambdas, the class already has a definition ptr set, but
1983  // the contained decls are not imported yet. Also, isBeingDefined was
1984  // set in CXXRecordDecl::CreateLambda. We must import the contained
1985  // decls here and finish the definition.
1987  if (To->isLambda()) {
1988  auto *FromCXXRD = cast<CXXRecordDecl>(From);
1989  SmallVector<LambdaCapture, 8> ToCaptures;
1990  ToCaptures.reserve(FromCXXRD->capture_size());
1991  for (const auto &FromCapture : FromCXXRD->captures()) {
1992  if (auto ToCaptureOrErr = import(FromCapture))
1993  ToCaptures.push_back(*ToCaptureOrErr);
1994  else
1995  return ToCaptureOrErr.takeError();
1996  }
1997  cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
1998  ToCaptures);
1999  }
2000 
2001  Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2002  // Finish the definition of the lambda, set isBeingDefined to false.
2003  if (To->isLambda())
2004  DefinitionCompleter();
2005  return Result;
2006  }
2007 
2008  return Error::success();
2009  }
2010 
2011  To->startDefinition();
2012  // Complete the definition even if error is returned.
2013  // The RecordDecl may be already part of the AST so it is better to
2014  // have it in complete state even if something is wrong with it.
2015  auto DefinitionCompleterScopeExit =
2016  llvm::make_scope_exit(DefinitionCompleter);
2017 
2018  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2019  return Err;
2020 
2021  // Add base classes.
2022  auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2023  auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2024  if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2025 
2026  struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2027  struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2028 
2029  #define FIELD(Name, Width, Merge) \
2030  ToData.Name = FromData.Name;
2031  #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2032 
2033  // Copy over the data stored in RecordDeclBits
2034  ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2035 
2037  for (const auto &Base1 : FromCXX->bases()) {
2038  ExpectedType TyOrErr = import(Base1.getType());
2039  if (!TyOrErr)
2040  return TyOrErr.takeError();
2041 
2042  SourceLocation EllipsisLoc;
2043  if (Base1.isPackExpansion()) {
2044  if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2045  EllipsisLoc = *LocOrErr;
2046  else
2047  return LocOrErr.takeError();
2048  }
2049 
2050  // Ensure that we have a definition for the base.
2051  if (Error Err =
2052  ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2053  return Err;
2054 
2055  auto RangeOrErr = import(Base1.getSourceRange());
2056  if (!RangeOrErr)
2057  return RangeOrErr.takeError();
2058 
2059  auto TSIOrErr = import(Base1.getTypeSourceInfo());
2060  if (!TSIOrErr)
2061  return TSIOrErr.takeError();
2062 
2063  Bases.push_back(
2064  new (Importer.getToContext()) CXXBaseSpecifier(
2065  *RangeOrErr,
2066  Base1.isVirtual(),
2067  Base1.isBaseOfClass(),
2068  Base1.getAccessSpecifierAsWritten(),
2069  *TSIOrErr,
2070  EllipsisLoc));
2071  }
2072  if (!Bases.empty())
2073  ToCXX->setBases(Bases.data(), Bases.size());
2074  }
2075 
2077  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2078  return Err;
2079 
2080  return Error::success();
2081 }
2082 
2084  if (To->getAnyInitializer())
2085  return Error::success();
2086 
2087  Expr *FromInit = From->getInit();
2088  if (!FromInit)
2089  return Error::success();
2090 
2091  ExpectedExpr ToInitOrErr = import(FromInit);
2092  if (!ToInitOrErr)
2093  return ToInitOrErr.takeError();
2094 
2095  To->setInit(*ToInitOrErr);
2096  if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2097  EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2098  ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2099  ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2100  // FIXME: Also import the initializer value.
2101  }
2102 
2103  // FIXME: Other bits to merge?
2104  return Error::success();
2105 }
2106 
2109  if (To->getDefinition() || To->isBeingDefined()) {
2110  if (Kind == IDK_Everything)
2111  return ImportDeclContext(From, /*ForceImport=*/true);
2112  return Error::success();
2113  }
2114 
2115  To->startDefinition();
2116 
2117  if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2118  return Err;
2119 
2120  ExpectedType ToTypeOrErr =
2121  import(Importer.getFromContext().getTypeDeclType(From));
2122  if (!ToTypeOrErr)
2123  return ToTypeOrErr.takeError();
2124 
2125  ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2126  if (!ToPromotionTypeOrErr)
2127  return ToPromotionTypeOrErr.takeError();
2128 
2130  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2131  return Err;
2132 
2133  // FIXME: we might need to merge the number of positive or negative bits
2134  // if the enumerator lists don't match.
2135  To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2136  From->getNumPositiveBits(),
2137  From->getNumNegativeBits());
2138  return Error::success();
2139 }
2140 
2142  const TemplateArgument *FromArgs, unsigned NumFromArgs,
2144  for (unsigned I = 0; I != NumFromArgs; ++I) {
2145  if (auto ToOrErr = import(FromArgs[I]))
2146  ToArgs.push_back(*ToOrErr);
2147  else
2148  return ToOrErr.takeError();
2149  }
2150 
2151  return Error::success();
2152 }
2153 
2154 // FIXME: Do not forget to remove this and use only 'import'.
2157  return import(From);
2158 }
2159 
2160 template <typename InContainerTy>
2162  const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2163  for (const auto &FromLoc : Container) {
2164  if (auto ToLocOrErr = import(FromLoc))
2165  ToTAInfo.addArgument(*ToLocOrErr);
2166  else
2167  return ToLocOrErr.takeError();
2168  }
2169  return Error::success();
2170 }
2171 
2176 }
2177 
2178 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2180  Importer.getFromContext(), Importer.getToContext(),
2182  false, Complain);
2183  return Ctx.IsEquivalent(From, To);
2184 }
2185 
2187  RecordDecl *ToRecord, bool Complain) {
2188  // Eliminate a potential failure point where we attempt to re-import
2189  // something we're trying to import while completing ToRecord.
2190  Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2191  if (ToOrigin) {
2192  auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2193  if (ToOriginRecord)
2194  ToRecord = ToOriginRecord;
2195  }
2196 
2198  ToRecord->getASTContext(),
2199  Importer.getNonEquivalentDecls(),
2200  getStructuralEquivalenceKind(Importer),
2201  false, Complain);
2202  return Ctx.IsEquivalent(FromRecord, ToRecord);
2203 }
2204 
2206  bool Complain) {
2208  Importer.getFromContext(), Importer.getToContext(),
2210  false, Complain);
2211  return Ctx.IsEquivalent(FromVar, ToVar);
2212 }
2213 
2215  // Eliminate a potential failure point where we attempt to re-import
2216  // something we're trying to import while completing ToEnum.
2217  if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2218  if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2219  ToEnum = ToOriginEnum;
2220 
2222  Importer.getFromContext(), Importer.getToContext(),
2223  Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2224  return Ctx.IsEquivalent(FromEnum, ToEnum);
2225 }
2226 
2228  FunctionTemplateDecl *To) {
2230  Importer.getFromContext(), Importer.getToContext(),
2232  false, false);
2233  return Ctx.IsEquivalent(From, To);
2234 }
2235 
2238  Importer.getFromContext(), Importer.getToContext(),
2240  false, false);
2241  return Ctx.IsEquivalent(From, To);
2242 }
2243 
2245  EnumConstantDecl *ToEC) {
2246  const llvm::APSInt &FromVal = FromEC->getInitVal();
2247  const llvm::APSInt &ToVal = ToEC->getInitVal();
2248 
2249  return FromVal.isSigned() == ToVal.isSigned() &&
2250  FromVal.getBitWidth() == ToVal.getBitWidth() &&
2251  FromVal == ToVal;
2252 }
2253 
2255  ClassTemplateDecl *To) {
2257  Importer.getToContext(),
2258  Importer.getNonEquivalentDecls(),
2259  getStructuralEquivalenceKind(Importer));
2260  return Ctx.IsEquivalent(From, To);
2261 }
2262 
2264  VarTemplateDecl *To) {
2266  Importer.getToContext(),
2267  Importer.getNonEquivalentDecls(),
2268  getStructuralEquivalenceKind(Importer));
2269  return Ctx.IsEquivalent(From, To);
2270 }
2271 
2273  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2274  << D->getDeclKindName();
2275  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2276 }
2277 
2279  Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2280  << D->getDeclKindName();
2281  return make_error<ImportError>(ImportError::UnsupportedConstruct);
2282 }
2283 
2285  // Import the context of this declaration.
2286  DeclContext *DC, *LexicalDC;
2287  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2288  return std::move(Err);
2289 
2290  // Import the location of this declaration.
2291  ExpectedSLoc LocOrErr = import(D->getLocation());
2292  if (!LocOrErr)
2293  return LocOrErr.takeError();
2294 
2295  EmptyDecl *ToD;
2296  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2297  return ToD;
2298 
2299  ToD->setLexicalDeclContext(LexicalDC);
2300  LexicalDC->addDeclInternal(ToD);
2301  return ToD;
2302 }
2303 
2305  TranslationUnitDecl *ToD =
2306  Importer.getToContext().getTranslationUnitDecl();
2307 
2308  Importer.MapImported(D, ToD);
2309 
2310  return ToD;
2311 }
2312 
2314  DeclContext *DC, *LexicalDC;
2315  DeclarationName Name;
2316  SourceLocation Loc;
2317  NamedDecl *ToND;
2318  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2319  return std::move(Err);
2320  if (ToND)
2321  return ToND;
2322 
2323  BindingDecl *ToD;
2324  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2325  Name.getAsIdentifierInfo()))
2326  return ToD;
2327 
2328  Error Err = Error::success();
2329  QualType ToType = importChecked(Err, D->getType());
2330  Expr *ToBinding = importChecked(Err, D->getBinding());
2331  ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2332  if (Err)
2333  return std::move(Err);
2334 
2335  ToD->setBinding(ToType, ToBinding);
2336  ToD->setDecomposedDecl(ToDecomposedDecl);
2337  addDeclToContexts(D, ToD);
2338 
2339  return ToD;
2340 }
2341 
2343  ExpectedSLoc LocOrErr = import(D->getLocation());
2344  if (!LocOrErr)
2345  return LocOrErr.takeError();
2346  auto ColonLocOrErr = import(D->getColonLoc());
2347  if (!ColonLocOrErr)
2348  return ColonLocOrErr.takeError();
2349 
2350  // Import the context of this declaration.
2351  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2352  if (!DCOrErr)
2353  return DCOrErr.takeError();
2354  DeclContext *DC = *DCOrErr;
2355 
2356  AccessSpecDecl *ToD;
2357  if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2358  DC, *LocOrErr, *ColonLocOrErr))
2359  return ToD;
2360 
2361  // Lexical DeclContext and Semantic DeclContext
2362  // is always the same for the accessSpec.
2363  ToD->setLexicalDeclContext(DC);
2364  DC->addDeclInternal(ToD);
2365 
2366  return ToD;
2367 }
2368 
2370  auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2371  if (!DCOrErr)
2372  return DCOrErr.takeError();
2373  DeclContext *DC = *DCOrErr;
2374  DeclContext *LexicalDC = DC;
2375 
2376  Error Err = Error::success();
2377  auto ToLocation = importChecked(Err, D->getLocation());
2378  auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2379  auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2380  auto ToMessage = importChecked(Err, D->getMessage());
2381  if (Err)
2382  return std::move(Err);
2383 
2384  StaticAssertDecl *ToD;
2385  if (GetImportedOrCreateDecl(
2386  ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2387  ToRParenLoc, D->isFailed()))
2388  return ToD;
2389 
2390  ToD->setLexicalDeclContext(LexicalDC);
2391  LexicalDC->addDeclInternal(ToD);
2392  return ToD;
2393 }
2394 
2396  // Import the major distinguishing characteristics of this namespace.
2397  DeclContext *DC, *LexicalDC;
2398  DeclarationName Name;
2399  SourceLocation Loc;
2400  NamedDecl *ToD;
2401  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2402  return std::move(Err);
2403  if (ToD)
2404  return ToD;
2405 
2406  NamespaceDecl *MergeWithNamespace = nullptr;
2407  if (!Name) {
2408  // This is an anonymous namespace. Adopt an existing anonymous
2409  // namespace if we can.
2410  // FIXME: Not testable.
2411  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2412  MergeWithNamespace = TU->getAnonymousNamespace();
2413  else
2414  MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2415  } else {
2416  SmallVector<NamedDecl *, 4> ConflictingDecls;
2417  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2418  for (auto *FoundDecl : FoundDecls) {
2420  continue;
2421 
2422  if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2423  MergeWithNamespace = FoundNS;
2424  ConflictingDecls.clear();
2425  break;
2426  }
2427 
2428  ConflictingDecls.push_back(FoundDecl);
2429  }
2430 
2431  if (!ConflictingDecls.empty()) {
2432  ExpectedName NameOrErr = Importer.HandleNameConflict(
2433  Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2434  ConflictingDecls.size());
2435  if (NameOrErr)
2436  Name = NameOrErr.get();
2437  else
2438  return NameOrErr.takeError();
2439  }
2440  }
2441 
2442  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2443  if (!BeginLocOrErr)
2444  return BeginLocOrErr.takeError();
2445  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2446  if (!RBraceLocOrErr)
2447  return RBraceLocOrErr.takeError();
2448 
2449  // Create the "to" namespace, if needed.
2450  NamespaceDecl *ToNamespace = MergeWithNamespace;
2451  if (!ToNamespace) {
2452  if (GetImportedOrCreateDecl(
2453  ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2454  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2455  /*PrevDecl=*/nullptr))
2456  return ToNamespace;
2457  ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2458  ToNamespace->setLexicalDeclContext(LexicalDC);
2459  LexicalDC->addDeclInternal(ToNamespace);
2460 
2461  // If this is an anonymous namespace, register it as the anonymous
2462  // namespace within its context.
2463  if (!Name) {
2464  if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2465  TU->setAnonymousNamespace(ToNamespace);
2466  else
2467  cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2468  }
2469  }
2470  Importer.MapImported(D, ToNamespace);
2471 
2472  if (Error Err = ImportDeclContext(D))
2473  return std::move(Err);
2474 
2475  return ToNamespace;
2476 }
2477 
2479  // Import the major distinguishing characteristics of this namespace.
2480  DeclContext *DC, *LexicalDC;
2481  DeclarationName Name;
2482  SourceLocation Loc;
2483  NamedDecl *LookupD;
2484  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2485  return std::move(Err);
2486  if (LookupD)
2487  return LookupD;
2488 
2489  // NOTE: No conflict resolution is done for namespace aliases now.
2490 
2491  Error Err = Error::success();
2492  auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2493  auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2494  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2495  auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2496  auto ToNamespace = importChecked(Err, D->getNamespace());
2497  if (Err)
2498  return std::move(Err);
2499 
2500  IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2501 
2502  NamespaceAliasDecl *ToD;
2503  if (GetImportedOrCreateDecl(
2504  ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2505  ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2506  return ToD;
2507 
2508  ToD->setLexicalDeclContext(LexicalDC);
2509  LexicalDC->addDeclInternal(ToD);
2510 
2511  return ToD;
2512 }
2513 
2516  // Import the major distinguishing characteristics of this typedef.
2517  DeclarationName Name;
2518  SourceLocation Loc;
2519  NamedDecl *ToD;
2520  // Do not import the DeclContext, we will import it once the TypedefNameDecl
2521  // is created.
2522  if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2523  return std::move(Err);
2524  if (ToD)
2525  return ToD;
2526 
2527  DeclContext *DC = cast_or_null<DeclContext>(
2528  Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2529  DeclContext *LexicalDC =
2530  cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2531  cast<Decl>(D->getLexicalDeclContext())));
2532 
2533  // If this typedef is not in block scope, determine whether we've
2534  // seen a typedef with the same name (that we can merge with) or any
2535  // other entity by that name (which name lookup could conflict with).
2536  // Note: Repeated typedefs are not valid in C99:
2537  // 'typedef int T; typedef int T;' is invalid
2538  // We do not care about this now.
2539  if (DC && !DC->isFunctionOrMethod()) {
2540  SmallVector<NamedDecl *, 4> ConflictingDecls;
2541  unsigned IDNS = Decl::IDNS_Ordinary;
2542  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2543  for (auto *FoundDecl : FoundDecls) {
2544  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2545  continue;
2546  if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2547  if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2548  continue;
2549 
2550  QualType FromUT = D->getUnderlyingType();
2551  QualType FoundUT = FoundTypedef->getUnderlyingType();
2552  if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2553  // If the "From" context has a complete underlying type but we
2554  // already have a complete underlying type then return with that.
2555  if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2556  return Importer.MapImported(D, FoundTypedef);
2557  // FIXME Handle redecl chain. When you do that make consistent changes
2558  // in ASTImporterLookupTable too.
2559  } else {
2560  ConflictingDecls.push_back(FoundDecl);
2561  }
2562  }
2563  }
2564 
2565  if (!ConflictingDecls.empty()) {
2566  ExpectedName NameOrErr = Importer.HandleNameConflict(
2567  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2568  if (NameOrErr)
2569  Name = NameOrErr.get();
2570  else
2571  return NameOrErr.takeError();
2572  }
2573  }
2574 
2575  Error Err = Error::success();
2577  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2578  auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2579  if (Err)
2580  return std::move(Err);
2581 
2582  // Create the new typedef node.
2583  // FIXME: ToUnderlyingType is not used.
2584  (void)ToUnderlyingType;
2585  TypedefNameDecl *ToTypedef;
2586  if (IsAlias) {
2587  if (GetImportedOrCreateDecl<TypeAliasDecl>(
2588  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2589  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2590  return ToTypedef;
2591  } else if (GetImportedOrCreateDecl<TypedefDecl>(
2592  ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2593  Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2594  return ToTypedef;
2595 
2596  // Import the DeclContext and set it to the Typedef.
2597  if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2598  return std::move(Err);
2599  ToTypedef->setDeclContext(DC);
2600  ToTypedef->setLexicalDeclContext(LexicalDC);
2601  // Add to the lookupTable because we could not do that in MapImported.
2602  Importer.AddToLookupTable(ToTypedef);
2603 
2604  ToTypedef->setAccess(D->getAccess());
2605 
2606  // Templated declarations should not appear in DeclContext.
2607  TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2608  if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2609  LexicalDC->addDeclInternal(ToTypedef);
2610 
2611  return ToTypedef;
2612 }
2613 
2615  return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2616 }
2617 
2619  return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2620 }
2621 
2624  // Import the major distinguishing characteristics of this typedef.
2625  DeclContext *DC, *LexicalDC;
2626  DeclarationName Name;
2627  SourceLocation Loc;
2628  NamedDecl *FoundD;
2629  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2630  return std::move(Err);
2631  if (FoundD)
2632  return FoundD;
2633 
2634  // If this typedef is not in block scope, determine whether we've
2635  // seen a typedef with the same name (that we can merge with) or any
2636  // other entity by that name (which name lookup could conflict with).
2637  if (!DC->isFunctionOrMethod()) {
2638  SmallVector<NamedDecl *, 4> ConflictingDecls;
2639  unsigned IDNS = Decl::IDNS_Ordinary;
2640  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2641  for (auto *FoundDecl : FoundDecls) {
2642  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2643  continue;
2644  if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2645  return Importer.MapImported(D, FoundAlias);
2646  ConflictingDecls.push_back(FoundDecl);
2647  }
2648 
2649  if (!ConflictingDecls.empty()) {
2650  ExpectedName NameOrErr = Importer.HandleNameConflict(
2651  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2652  if (NameOrErr)
2653  Name = NameOrErr.get();
2654  else
2655  return NameOrErr.takeError();
2656  }
2657  }
2658 
2659  Error Err = Error::success();
2660  auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2661  auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2662  if (Err)
2663  return std::move(Err);
2664 
2665  TypeAliasTemplateDecl *ToAlias;
2666  if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2667  Name, ToTemplateParameters, ToTemplatedDecl))
2668  return ToAlias;
2669 
2670  ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2671 
2672  ToAlias->setAccess(D->getAccess());
2673  ToAlias->setLexicalDeclContext(LexicalDC);
2674  LexicalDC->addDeclInternal(ToAlias);
2675  if (DC != Importer.getToContext().getTranslationUnitDecl())
2676  updateLookupTableForTemplateParameters(*ToTemplateParameters);
2677  return ToAlias;
2678 }
2679 
2681  // Import the major distinguishing characteristics of this label.
2682  DeclContext *DC, *LexicalDC;
2683  DeclarationName Name;
2684  SourceLocation Loc;
2685  NamedDecl *ToD;
2686  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2687  return std::move(Err);
2688  if (ToD)
2689  return ToD;
2690 
2691  assert(LexicalDC->isFunctionOrMethod());
2692 
2693  LabelDecl *ToLabel;
2694  if (D->isGnuLocal()) {
2695  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2696  if (!BeginLocOrErr)
2697  return BeginLocOrErr.takeError();
2698  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2699  Name.getAsIdentifierInfo(), *BeginLocOrErr))
2700  return ToLabel;
2701 
2702  } else {
2703  if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2704  Name.getAsIdentifierInfo()))
2705  return ToLabel;
2706 
2707  }
2708 
2709  Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2710  if (!ToStmtOrErr)
2711  return ToStmtOrErr.takeError();
2712 
2713  ToLabel->setStmt(*ToStmtOrErr);
2714  ToLabel->setLexicalDeclContext(LexicalDC);
2715  LexicalDC->addDeclInternal(ToLabel);
2716  return ToLabel;
2717 }
2718 
2720  // Import the major distinguishing characteristics of this enum.
2721  DeclContext *DC, *LexicalDC;
2722  DeclarationName Name;
2723  SourceLocation Loc;
2724  NamedDecl *ToD;
2725  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2726  return std::move(Err);
2727  if (ToD)
2728  return ToD;
2729 
2730  // Figure out what enum name we're looking for.
2731  unsigned IDNS = Decl::IDNS_Tag;
2732  DeclarationName SearchName = Name;
2733  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2734  if (Error Err = importInto(
2735  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2736  return std::move(Err);
2737  IDNS = Decl::IDNS_Ordinary;
2738  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2739  IDNS |= Decl::IDNS_Ordinary;
2740 
2741  // We may already have an enum of the same name; try to find and match it.
2742  EnumDecl *PrevDecl = nullptr;
2743  if (!DC->isFunctionOrMethod() && SearchName) {
2744  SmallVector<NamedDecl *, 4> ConflictingDecls;
2745  auto FoundDecls =
2746  Importer.findDeclsInToCtx(DC, SearchName);
2747  for (auto *FoundDecl : FoundDecls) {
2748  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2749  continue;
2750 
2751  if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2752  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2753  FoundDecl = Tag->getDecl();
2754  }
2755 
2756  if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2757  if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2758  continue;
2759  if (IsStructuralMatch(D, FoundEnum)) {
2760  EnumDecl *FoundDef = FoundEnum->getDefinition();
2761  if (D->isThisDeclarationADefinition() && FoundDef)
2762  return Importer.MapImported(D, FoundDef);
2763  PrevDecl = FoundEnum->getMostRecentDecl();
2764  break;
2765  }
2766  ConflictingDecls.push_back(FoundDecl);
2767  }
2768  }
2769 
2770  if (!ConflictingDecls.empty()) {
2771  ExpectedName NameOrErr = Importer.HandleNameConflict(
2772  SearchName, DC, IDNS, ConflictingDecls.data(),
2773  ConflictingDecls.size());
2774  if (NameOrErr)
2775  Name = NameOrErr.get();
2776  else
2777  return NameOrErr.takeError();
2778  }
2779  }
2780 
2781  Error Err = Error::success();
2782  auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2783  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2784  auto ToIntegerType = importChecked(Err, D->getIntegerType());
2785  auto ToBraceRange = importChecked(Err, D->getBraceRange());
2786  if (Err)
2787  return std::move(Err);
2788 
2789  // Create the enum declaration.
2790  EnumDecl *D2;
2791  if (GetImportedOrCreateDecl(
2792  D2, D, Importer.getToContext(), DC, ToBeginLoc,
2793  Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2794  D->isScopedUsingClassTag(), D->isFixed()))
2795  return D2;
2796 
2797  D2->setQualifierInfo(ToQualifierLoc);
2798  D2->setIntegerType(ToIntegerType);
2799  D2->setBraceRange(ToBraceRange);
2800  D2->setAccess(D->getAccess());
2801  D2->setLexicalDeclContext(LexicalDC);
2802  addDeclToContexts(D, D2);
2803 
2804  if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2805  TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2806  EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2807  if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2808  D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2809  else
2810  return ToInstOrErr.takeError();
2811  if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
2813  else
2814  return POIOrErr.takeError();
2815  }
2816 
2817  // Import the definition
2818  if (D->isCompleteDefinition())
2819  if (Error Err = ImportDefinition(D, D2))
2820  return std::move(Err);
2821 
2822  return D2;
2823 }
2824 
2826  bool IsFriendTemplate = false;
2827  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2828  IsFriendTemplate =
2829  DCXX->getDescribedClassTemplate() &&
2830  DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2832  }
2833 
2834  // Import the major distinguishing characteristics of this record.
2835  DeclContext *DC = nullptr, *LexicalDC = nullptr;
2836  DeclarationName Name;
2837  SourceLocation Loc;
2838  NamedDecl *ToD = nullptr;
2839  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2840  return std::move(Err);
2841  if (ToD)
2842  return ToD;
2843 
2844  // Figure out what structure name we're looking for.
2845  unsigned IDNS = Decl::IDNS_Tag;
2846  DeclarationName SearchName = Name;
2847  if (!SearchName && D->getTypedefNameForAnonDecl()) {
2848  if (Error Err = importInto(
2849  SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2850  return std::move(Err);
2851  IDNS = Decl::IDNS_Ordinary;
2852  } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2854 
2855  // We may already have a record of the same name; try to find and match it.
2856  RecordDecl *PrevDecl = nullptr;
2857  if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2858  SmallVector<NamedDecl *, 4> ConflictingDecls;
2859  auto FoundDecls =
2860  Importer.findDeclsInToCtx(DC, SearchName);
2861  if (!FoundDecls.empty()) {
2862  // We're going to have to compare D against potentially conflicting Decls,
2863  // so complete it.
2866  }
2867 
2868  for (auto *FoundDecl : FoundDecls) {
2869  if (!FoundDecl->isInIdentifierNamespace(IDNS))
2870  continue;
2871 
2872  Decl *Found = FoundDecl;
2873  if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2874  if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2875  Found = Tag->getDecl();
2876  }
2877 
2878  if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2879  // Do not emit false positive diagnostic in case of unnamed
2880  // struct/union and in case of anonymous structs. Would be false
2881  // because there may be several anonymous/unnamed structs in a class.
2882  // E.g. these are both valid:
2883  // struct A { // unnamed structs
2884  // struct { struct A *next; } entry0;
2885  // struct { struct A *next; } entry1;
2886  // };
2887  // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2888  if (!SearchName)
2889  if (!IsStructuralMatch(D, FoundRecord, false))
2890  continue;
2891 
2892  if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
2893  continue;
2894 
2895  if (IsStructuralMatch(D, FoundRecord)) {
2896  RecordDecl *FoundDef = FoundRecord->getDefinition();
2897  if (D->isThisDeclarationADefinition() && FoundDef) {
2898  // FIXME: Structural equivalence check should check for same
2899  // user-defined methods.
2900  Importer.MapImported(D, FoundDef);
2901  if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2902  auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2903  assert(FoundCXX && "Record type mismatch");
2904 
2905  if (!Importer.isMinimalImport())
2906  // FoundDef may not have every implicit method that D has
2907  // because implicit methods are created only if they are used.
2908  if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2909  return std::move(Err);
2910  }
2911  }
2912  PrevDecl = FoundRecord->getMostRecentDecl();
2913  break;
2914  }
2915  ConflictingDecls.push_back(FoundDecl);
2916  } // kind is RecordDecl
2917  } // for
2918 
2919  if (!ConflictingDecls.empty() && SearchName) {
2920  ExpectedName NameOrErr = Importer.HandleNameConflict(
2921  SearchName, DC, IDNS, ConflictingDecls.data(),
2922  ConflictingDecls.size());
2923  if (NameOrErr)
2924  Name = NameOrErr.get();
2925  else
2926  return NameOrErr.takeError();
2927  }
2928  }
2929 
2930  ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2931  if (!BeginLocOrErr)
2932  return BeginLocOrErr.takeError();
2933 
2934  // Create the record declaration.
2935  RecordDecl *D2 = nullptr;
2936  CXXRecordDecl *D2CXX = nullptr;
2937  if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2938  if (DCXX->isLambda()) {
2939  auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2940  if (!TInfoOrErr)
2941  return TInfoOrErr.takeError();
2942  if (GetImportedOrCreateSpecialDecl(
2943  D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2944  DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2945  DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2946  return D2CXX;
2947  ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2948  if (!CDeclOrErr)
2949  return CDeclOrErr.takeError();
2950  D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
2951  DCXX->hasKnownLambdaInternalLinkage());
2953  DCXX->getDeviceLambdaManglingNumber());
2954  } else if (DCXX->isInjectedClassName()) {
2955  // We have to be careful to do a similar dance to the one in
2956  // Sema::ActOnStartCXXMemberDeclarations
2957  const bool DelayTypeCreation = true;
2958  if (GetImportedOrCreateDecl(
2959  D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2960  *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2961  cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2962  return D2CXX;
2963  Importer.getToContext().getTypeDeclType(
2964  D2CXX, dyn_cast<CXXRecordDecl>(DC));
2965  } else {
2966  if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2967  D->getTagKind(), DC, *BeginLocOrErr, Loc,
2968  Name.getAsIdentifierInfo(),
2969  cast_or_null<CXXRecordDecl>(PrevDecl)))
2970  return D2CXX;
2971  }
2972 
2973  D2 = D2CXX;
2974  D2->setAccess(D->getAccess());
2975  D2->setLexicalDeclContext(LexicalDC);
2976  addDeclToContexts(D, D2);
2977 
2978  if (ClassTemplateDecl *FromDescribed =
2979  DCXX->getDescribedClassTemplate()) {
2980  ClassTemplateDecl *ToDescribed;
2981  if (Error Err = importInto(ToDescribed, FromDescribed))
2982  return std::move(Err);
2983  D2CXX->setDescribedClassTemplate(ToDescribed);
2984  if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2985  // In a record describing a template the type should be an
2986  // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2987  // previously set type to the correct value here (ToDescribed is not
2988  // available at record create).
2989  // FIXME: The previous type is cleared but not removed from
2990  // ASTContext's internal storage.
2991  CXXRecordDecl *Injected = nullptr;
2992  for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2993  auto *Record = dyn_cast<CXXRecordDecl>(Found);
2994  if (Record && Record->isInjectedClassName()) {
2995  Injected = Record;
2996  break;
2997  }
2998  }
2999  // Create an injected type for the whole redecl chain.
3000  SmallVector<Decl *, 2> Redecls =
3002  for (auto *R : Redecls) {
3003  auto *RI = cast<CXXRecordDecl>(R);
3004  RI->setTypeForDecl(nullptr);
3005  // Below we create a new injected type and assign that to the
3006  // canonical decl, subsequent declarations in the chain will reuse
3007  // that type.
3009  RI, ToDescribed->getInjectedClassNameSpecialization());
3010  }
3011  // Set the new type for the previous injected decl too.
3012  if (Injected) {
3013  Injected->setTypeForDecl(nullptr);
3014  Importer.getToContext().getTypeDeclType(Injected, D2CXX);
3015  }
3016  }
3017  } else if (MemberSpecializationInfo *MemberInfo =
3018  DCXX->getMemberSpecializationInfo()) {
3020  MemberInfo->getTemplateSpecializationKind();
3021  CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
3022 
3023  if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
3024  D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
3025  else
3026  return ToInstOrErr.takeError();
3027 
3028  if (ExpectedSLoc POIOrErr =
3029  import(MemberInfo->getPointOfInstantiation()))
3031  *POIOrErr);
3032  else
3033  return POIOrErr.takeError();
3034  }
3035 
3036  } else {
3037  if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3038  D->getTagKind(), DC, *BeginLocOrErr, Loc,
3039  Name.getAsIdentifierInfo(), PrevDecl))
3040  return D2;
3041  D2->setLexicalDeclContext(LexicalDC);
3042  addDeclToContexts(D, D2);
3043  }
3044 
3045  if (auto BraceRangeOrErr = import(D->getBraceRange()))
3046  D2->setBraceRange(*BraceRangeOrErr);
3047  else
3048  return BraceRangeOrErr.takeError();
3049  if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3050  D2->setQualifierInfo(*QualifierLocOrErr);
3051  else
3052  return QualifierLocOrErr.takeError();
3053 
3054  if (D->isAnonymousStructOrUnion())
3055  D2->setAnonymousStructOrUnion(true);
3056 
3057  if (D->isCompleteDefinition())
3058  if (Error Err = ImportDefinition(D, D2, IDK_Default))
3059  return std::move(Err);
3060 
3061  return D2;
3062 }
3063 
3065  // Import the major distinguishing characteristics of this enumerator.
3066  DeclContext *DC, *LexicalDC;
3067  DeclarationName Name;
3068  SourceLocation Loc;
3069  NamedDecl *ToD;
3070  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3071  return std::move(Err);
3072  if (ToD)
3073  return ToD;
3074 
3075  // Determine whether there are any other declarations with the same name and
3076  // in the same context.
3077  if (!LexicalDC->isFunctionOrMethod()) {
3078  SmallVector<NamedDecl *, 4> ConflictingDecls;
3079  unsigned IDNS = Decl::IDNS_Ordinary;
3080  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3081  for (auto *FoundDecl : FoundDecls) {
3082  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3083  continue;
3084 
3085  if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3086  if (IsStructuralMatch(D, FoundEnumConstant))
3087  return Importer.MapImported(D, FoundEnumConstant);
3088  ConflictingDecls.push_back(FoundDecl);
3089  }
3090  }
3091 
3092  if (!ConflictingDecls.empty()) {
3093  ExpectedName NameOrErr = Importer.HandleNameConflict(
3094  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3095  if (NameOrErr)
3096  Name = NameOrErr.get();
3097  else
3098  return NameOrErr.takeError();
3099  }
3100  }
3101 
3102  ExpectedType TypeOrErr = import(D->getType());
3103  if (!TypeOrErr)
3104  return TypeOrErr.takeError();
3105 
3106  ExpectedExpr InitOrErr = import(D->getInitExpr());
3107  if (!InitOrErr)
3108  return InitOrErr.takeError();
3109 
3110  EnumConstantDecl *ToEnumerator;
3111  if (GetImportedOrCreateDecl(
3112  ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3113  Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3114  return ToEnumerator;
3115 
3116  ToEnumerator->setAccess(D->getAccess());
3117  ToEnumerator->setLexicalDeclContext(LexicalDC);
3118  LexicalDC->addDeclInternal(ToEnumerator);
3119  return ToEnumerator;
3120 }
3121 
3123  DeclaratorDecl *ToD) {
3124  unsigned int Num = FromD->getNumTemplateParameterLists();
3125  if (Num == 0)
3126  return Error::success();
3128  for (unsigned int I = 0; I < Num; ++I)
3129  if (Expected<TemplateParameterList *> ToTPListOrErr =
3130  import(FromD->getTemplateParameterList(I)))
3131  ToTPLists[I] = *ToTPListOrErr;
3132  else
3133  return ToTPListOrErr.takeError();
3134  ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3135  return Error::success();
3136 }
3137 
3139  FunctionDecl *FromFD, FunctionDecl *ToFD) {
3140  switch (FromFD->getTemplatedKind()) {
3143  return Error::success();
3144 
3147 
3148  if (Expected<FunctionDecl *> InstFDOrErr =
3149  import(FromFD->getInstantiatedFromMemberFunction()))
3150  ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3151  else
3152  return InstFDOrErr.takeError();
3153 
3154  if (ExpectedSLoc POIOrErr = import(
3157  else
3158  return POIOrErr.takeError();
3159 
3160  return Error::success();
3161  }
3162 
3164  auto FunctionAndArgsOrErr =
3166  if (!FunctionAndArgsOrErr)
3167  return FunctionAndArgsOrErr.takeError();
3168 
3170  Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3171 
3172  auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3173  TemplateArgumentListInfo ToTAInfo;
3174  const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3175  if (FromTAArgsAsWritten)
3177  *FromTAArgsAsWritten, ToTAInfo))
3178  return Err;
3179 
3180  ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3181  if (!POIOrErr)
3182  return POIOrErr.takeError();
3183 
3184  if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3185  return Err;
3186 
3187  TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3188  ToFD->setFunctionTemplateSpecialization(
3189  std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3190  TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3191  return Error::success();
3192  }
3193 
3195  auto *FromInfo = FromFD->getDependentSpecializationInfo();
3196  UnresolvedSet<8> TemplDecls;
3197  unsigned NumTemplates = FromInfo->getNumTemplates();
3198  for (unsigned I = 0; I < NumTemplates; I++) {
3199  if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3200  import(FromInfo->getTemplate(I)))
3201  TemplDecls.addDecl(*ToFTDOrErr);
3202  else
3203  return ToFTDOrErr.takeError();
3204  }
3205 
3206  // Import TemplateArgumentListInfo.
3207  TemplateArgumentListInfo ToTAInfo;
3209  FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3210  llvm::makeArrayRef(
3211  FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3212  ToTAInfo))
3213  return Err;
3214 
3216  TemplDecls, ToTAInfo);
3217  return Error::success();
3218  }
3219  }
3220  llvm_unreachable("All cases should be covered!");
3221 }
3222 
3225  auto FunctionAndArgsOrErr =
3227  if (!FunctionAndArgsOrErr)
3228  return FunctionAndArgsOrErr.takeError();
3229 
3230  FunctionTemplateDecl *Template;
3231  TemplateArgsTy ToTemplArgs;
3232  std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3233  void *InsertPos = nullptr;
3234  auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3235  return FoundSpec;
3236 }
3237 
3239  FunctionDecl *ToFD) {
3240  if (Stmt *FromBody = FromFD->getBody()) {
3241  if (ExpectedStmt ToBodyOrErr = import(FromBody))
3242  ToFD->setBody(*ToBodyOrErr);
3243  else
3244  return ToBodyOrErr.takeError();
3245  }
3246  return Error::success();
3247 }
3248 
3249 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3250 // which is equal to the given DC.
3251 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3252  const DeclContext *DCi = D->getDeclContext();
3253  while (DCi != D->getTranslationUnitDecl()) {
3254  if (DCi == DC)
3255  return true;
3256  DCi = DCi->getParent();
3257  }
3258  return false;
3259 }
3260 
3262  QualType FromTy = D->getType();
3263  const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>();
3264  assert(FromFPT && "Must be called on FunctionProtoType");
3265  if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) {
3266  QualType DeducedT = AutoT->getDeducedType();
3267  if (const RecordType *RecordT =
3268  DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) {
3269  RecordDecl *RD = RecordT->getDecl();
3270  assert(RD);
3271  if (isAncestorDeclContextOf(D, RD)) {
3272  assert(RD->getLexicalDeclContext() == RD->getDeclContext());
3273  return true;
3274  }
3275  }
3276  }
3277  if (const TypedefType *TypedefT =
3278  dyn_cast<TypedefType>(FromFPT->getReturnType())) {
3279  TypedefNameDecl *TD = TypedefT->getDecl();
3280  assert(TD);
3281  if (isAncestorDeclContextOf(D, TD)) {
3282  assert(TD->getLexicalDeclContext() == TD->getDeclContext());
3283  return true;
3284  }
3285  }
3286  return false;
3287 }
3288 
3290 ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3291  Expr *ExplicitExpr = ESpec.getExpr();
3292  if (ExplicitExpr)
3293  ExplicitExpr = importChecked(Err, ESpec.getExpr());
3294  return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3295 }
3296 
3298 
3300  auto RedeclIt = Redecls.begin();
3301  // Import the first part of the decl chain. I.e. import all previous
3302  // declarations starting from the canonical decl.
3303  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3304  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3305  if (!ToRedeclOrErr)
3306  return ToRedeclOrErr.takeError();
3307  }
3308  assert(*RedeclIt == D);
3309 
3310  // Import the major distinguishing characteristics of this function.
3311  DeclContext *DC, *LexicalDC;
3312  DeclarationName Name;
3313  SourceLocation Loc;
3314  NamedDecl *ToD;
3315  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3316  return std::move(Err);
3317  if (ToD)
3318  return ToD;
3319 
3320  FunctionDecl *FoundByLookup = nullptr;
3322 
3323  // If this is a function template specialization, then try to find the same
3324  // existing specialization in the "to" context. The lookup below will not
3325  // find any specialization, but would find the primary template; thus, we
3326  // have to skip normal lookup in case of specializations.
3327  // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3328  if (D->getTemplatedKind() ==
3330  auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3331  if (!FoundFunctionOrErr)
3332  return FoundFunctionOrErr.takeError();
3333  if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3334  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3335  return Def;
3336  FoundByLookup = FoundFunction;
3337  }
3338  }
3339  // Try to find a function in our own ("to") context with the same name, same
3340  // type, and in the same context as the function we're importing.
3341  else if (!LexicalDC->isFunctionOrMethod()) {
3342  SmallVector<NamedDecl *, 4> ConflictingDecls;
3344  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3345  for (auto *FoundDecl : FoundDecls) {
3346  if (!FoundDecl->isInIdentifierNamespace(IDNS))
3347  continue;
3348 
3349  if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3350  if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3351  continue;
3352 
3353  if (IsStructuralMatch(D, FoundFunction)) {
3354  if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3355  return Def;
3356  FoundByLookup = FoundFunction;
3357  break;
3358  }
3359  // FIXME: Check for overloading more carefully, e.g., by boosting
3360  // Sema::IsOverload out to the AST library.
3361 
3362  // Function overloading is okay in C++.
3363  if (Importer.getToContext().getLangOpts().CPlusPlus)
3364  continue;
3365 
3366  // Complain about inconsistent function types.
3367  Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3368  << Name << D->getType() << FoundFunction->getType();
3369  Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3370  << FoundFunction->getType();
3371  ConflictingDecls.push_back(FoundDecl);
3372  }
3373  }
3374 
3375  if (!ConflictingDecls.empty()) {
3376  ExpectedName NameOrErr = Importer.HandleNameConflict(
3377  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3378  if (NameOrErr)
3379  Name = NameOrErr.get();
3380  else
3381  return NameOrErr.takeError();
3382  }
3383  }
3384 
3385  // We do not allow more than one in-class declaration of a function. This is
3386  // because AST clients like VTableBuilder asserts on this. VTableBuilder
3387  // assumes there is only one in-class declaration. Building a redecl
3388  // chain would result in more than one in-class declaration for
3389  // overrides (even if they are part of the same redecl chain inside the
3390  // derived class.)
3391  if (FoundByLookup) {
3392  if (isa<CXXMethodDecl>(FoundByLookup)) {
3393  if (D->getLexicalDeclContext() == D->getDeclContext()) {
3394  if (!D->doesThisDeclarationHaveABody()) {
3395  if (FunctionTemplateDecl *DescribedD =
3397  // Handle a "templated" function together with its described
3398  // template. This avoids need for a similar check at import of the
3399  // described template.
3400  assert(FoundByLookup->getDescribedFunctionTemplate() &&
3401  "Templated function mapped to non-templated?");
3402  Importer.MapImported(DescribedD,
3403  FoundByLookup->getDescribedFunctionTemplate());
3404  }
3405  return Importer.MapImported(D, FoundByLookup);
3406  } else {
3407  // Let's continue and build up the redecl chain in this case.
3408  // FIXME Merge the functions into one decl.
3409  }
3410  }
3411  }
3412  }
3413 
3414  DeclarationNameInfo NameInfo(Name, Loc);
3415  // Import additional name location/type info.
3416  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3417  return std::move(Err);
3418 
3419  QualType FromTy = D->getType();
3420  // Set to true if we do not import the type of the function as is. There are
3421  // cases when the original type would result in an infinite recursion during
3422  // the import. To avoid an infinite recursion when importing, we create the
3423  // FunctionDecl with a simplified function type and update it only after the
3424  // relevant AST nodes are already imported.
3425  bool UsedDifferentProtoType = false;
3426  if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3427  QualType FromReturnTy = FromFPT->getReturnType();
3428  // Functions with auto return type may define a struct inside their body
3429  // and the return type could refer to that struct.
3430  // E.g.: auto foo() { struct X{}; return X(); }
3431  // To avoid an infinite recursion when importing, create the FunctionDecl
3432  // with a simplified return type.
3434  FromReturnTy = Importer.getFromContext().VoidTy;
3435  UsedDifferentProtoType = true;
3436  }
3437  FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3438  // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3439  // FunctionDecl that we are importing the FunctionProtoType for.
3440  // To avoid an infinite recursion when importing, create the FunctionDecl
3441  // with a simplified function type.
3442  if (FromEPI.ExceptionSpec.SourceDecl ||
3443  FromEPI.ExceptionSpec.SourceTemplate ||
3444  FromEPI.ExceptionSpec.NoexceptExpr) {
3446  FromEPI = DefaultEPI;
3447  UsedDifferentProtoType = true;
3448  }
3449  FromTy = Importer.getFromContext().getFunctionType(
3450  FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3451  }
3452 
3453  Error Err = Error::success();
3454  auto T = importChecked(Err, FromTy);
3455  auto TInfo = importChecked(Err, D->getTypeSourceInfo());
3456  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3457  auto ToEndLoc = importChecked(Err, D->getEndLoc());
3458  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3459  auto TrailingRequiresClause =
3461  if (Err)
3462  return std::move(Err);
3463 
3464  // Import the function parameters.
3465  SmallVector<ParmVarDecl *, 8> Parameters;
3466  for (auto P : D->parameters()) {
3467  if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3468  Parameters.push_back(*ToPOrErr);
3469  else
3470  return ToPOrErr.takeError();
3471  }
3472 
3473  // Create the imported function.
3474  FunctionDecl *ToFunction = nullptr;
3475  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3476  ExplicitSpecifier ESpec =
3477  importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3478  if (Err)
3479  return std::move(Err);
3480  if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3481  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3482  ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3484  InheritedConstructor(), // FIXME: Properly import inherited
3485  // constructor info
3486  TrailingRequiresClause))
3487  return ToFunction;
3488  } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3489 
3490  Error Err = Error::success();
3491  auto ToOperatorDelete = importChecked(
3492  Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3493  auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3494  if (Err)
3495  return std::move(Err);
3496 
3497  if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3498  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3499  ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3501  TrailingRequiresClause))
3502  return ToFunction;
3503 
3504  CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3505 
3506  ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3507  } else if (CXXConversionDecl *FromConversion =
3508  dyn_cast<CXXConversionDecl>(D)) {
3509  ExplicitSpecifier ESpec =
3510  importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3511  if (Err)
3512  return std::move(Err);
3513  if (GetImportedOrCreateDecl<CXXConversionDecl>(
3514  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3515  ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3516  D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3517  SourceLocation(), TrailingRequiresClause))
3518  return ToFunction;
3519  } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3520  if (GetImportedOrCreateDecl<CXXMethodDecl>(
3521  ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3522  ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3523  Method->UsesFPIntrin(), Method->isInlineSpecified(),
3524  D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3525  return ToFunction;
3526  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3527  ExplicitSpecifier ESpec =
3528  importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3529  CXXConstructorDecl *Ctor =
3530  importChecked(Err, Guide->getCorrespondingConstructor());
3531  if (Err)
3532  return std::move(Err);
3533  if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3534  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3535  NameInfo, T, TInfo, ToEndLoc, Ctor))
3536  return ToFunction;
3537  cast<CXXDeductionGuideDecl>(ToFunction)
3538  ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
3539  } else {
3540  if (GetImportedOrCreateDecl(
3541  ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3542  NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3544  D->getConstexprKind(), TrailingRequiresClause))
3545  return ToFunction;
3546  }
3547 
3548  // Connect the redecl chain.
3549  if (FoundByLookup) {
3550  auto *Recent = const_cast<FunctionDecl *>(
3551  FoundByLookup->getMostRecentDecl());
3552  ToFunction->setPreviousDecl(Recent);
3553  // FIXME Probably we should merge exception specifications. E.g. In the
3554  // "To" context the existing function may have exception specification with
3555  // noexcept-unevaluated, while the newly imported function may have an
3556  // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3557  // decl and its redeclarations may be required.
3558  }
3559 
3560  ToFunction->setQualifierInfo(ToQualifierLoc);
3561  ToFunction->setAccess(D->getAccess());
3562  ToFunction->setLexicalDeclContext(LexicalDC);
3563  ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3564  ToFunction->setTrivial(D->isTrivial());
3565  ToFunction->setPure(D->isPure());
3566  ToFunction->setDefaulted(D->isDefaulted());
3568  ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3569  ToFunction->setRangeEnd(ToEndLoc);
3570 
3571  // Set the parameters.
3572  for (auto *Param : Parameters) {
3573  Param->setOwningFunction(ToFunction);
3574  ToFunction->addDeclInternal(Param);
3575  if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3576  LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3577  }
3578  ToFunction->setParams(Parameters);
3579 
3580  // We need to complete creation of FunctionProtoTypeLoc manually with setting
3581  // params it refers to.
3582  if (TInfo) {
3583  if (auto ProtoLoc =
3584  TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3585  for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3586  ProtoLoc.setParam(I, Parameters[I]);
3587  }
3588  }
3589 
3590  // Import the describing template function, if any.
3591  if (FromFT) {
3592  auto ToFTOrErr = import(FromFT);
3593  if (!ToFTOrErr)
3594  return ToFTOrErr.takeError();
3595  }
3596 
3597  // Import Ctor initializers.
3598  if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3599  if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3600  SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3601  // Import first, then allocate memory and copy if there was no error.
3602  if (Error Err = ImportContainerChecked(
3603  FromConstructor->inits(), CtorInitializers))
3604  return std::move(Err);
3605  auto **Memory =
3606  new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3607  std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3608  auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3609  ToCtor->setCtorInitializers(Memory);
3610  ToCtor->setNumCtorInitializers(NumInitializers);
3611  }
3612  }
3613 
3614  if (D->doesThisDeclarationHaveABody()) {
3615  Error Err = ImportFunctionDeclBody(D, ToFunction);
3616 
3617  if (Err)
3618  return std::move(Err);
3619  }
3620 
3621  // Import and set the original type in case we used another type.
3622  if (UsedDifferentProtoType) {
3623  if (ExpectedType TyOrErr = import(D->getType()))
3624  ToFunction->setType(*TyOrErr);
3625  else
3626  return TyOrErr.takeError();
3627  }
3628 
3629  // FIXME: Other bits to merge?
3630 
3631  // If it is a template, import all related things.
3632  if (Error Err = ImportTemplateInformation(D, ToFunction))
3633  return std::move(Err);
3634 
3635  addDeclToContexts(D, ToFunction);
3636 
3637  if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3638  if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3639  FromCXXMethod))
3640  return std::move(Err);
3641 
3642  // Import the rest of the chain. I.e. import all subsequent declarations.
3643  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3644  ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3645  if (!ToRedeclOrErr)
3646  return ToRedeclOrErr.takeError();
3647  }
3648 
3649  return ToFunction;
3650 }
3651 
3653  return VisitFunctionDecl(D);
3654 }
3655 
3657  return VisitCXXMethodDecl(D);
3658 }
3659 
3661  return VisitCXXMethodDecl(D);
3662 }
3663 
3665  return VisitCXXMethodDecl(D);
3666 }
3667 
3670  return VisitFunctionDecl(D);
3671 }
3672 
3674  // Import the major distinguishing characteristics of a variable.
3675  DeclContext *DC, *LexicalDC;
3676  DeclarationName Name;
3677  SourceLocation Loc;
3678  NamedDecl *ToD;
3679  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3680  return std::move(Err);
3681  if (ToD)
3682  return ToD;
3683 
3684  // Determine whether we've already imported this field.
3685  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3686  for (auto *FoundDecl : FoundDecls) {
3687  if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3688  // For anonymous fields, match up by index.
3689  if (!Name &&
3691  ASTImporter::getFieldIndex(FoundField))
3692  continue;
3693 
3694  if (Importer.IsStructurallyEquivalent(D->getType(),
3695  FoundField->getType())) {
3696  Importer.MapImported(D, FoundField);
3697  // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3698  // initializer of a FieldDecl might not had been instantiated in the
3699  // "To" context. However, the "From" context might instantiated that,
3700  // thus we have to merge that.
3701  if (Expr *FromInitializer = D->getInClassInitializer()) {
3702  // We don't have yet the initializer set.
3703  if (FoundField->hasInClassInitializer() &&
3704  !FoundField->getInClassInitializer()) {
3705  if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3706  FoundField->setInClassInitializer(*ToInitializerOrErr);
3707  else {
3708  // We can't return error here,
3709  // since we already mapped D as imported.
3710  // FIXME: warning message?
3711  consumeError(ToInitializerOrErr.takeError());
3712  return FoundField;
3713  }
3714  }
3715  }
3716  return FoundField;
3717  }
3718 
3719  // FIXME: Why is this case not handled with calling HandleNameConflict?
3720  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3721  << Name << D->getType() << FoundField->getType();
3722  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3723  << FoundField->getType();
3724 
3725  return make_error<ImportError>(ImportError::NameConflict);
3726  }
3727  }
3728 
3729  Error Err = Error::success();
3730  auto ToType = importChecked(Err, D->getType());
3731  auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
3732  auto ToBitWidth = importChecked(Err, D->getBitWidth());
3733  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3734  auto ToInitializer = importChecked(Err, D->getInClassInitializer());
3735  if (Err)
3736  return std::move(Err);
3737  const Type *ToCapturedVLAType = nullptr;
3738  if (Error Err = Importer.importInto(
3739  ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
3740  return std::move(Err);
3741 
3742  FieldDecl *ToField;
3743  if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3744  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3745  ToType, ToTInfo, ToBitWidth, D->isMutable(),
3746  D->getInClassInitStyle()))
3747  return ToField;
3748 
3749  ToField->setAccess(D->getAccess());
3750  ToField->setLexicalDeclContext(LexicalDC);
3751  if (ToInitializer)
3752  ToField->setInClassInitializer(ToInitializer);
3753  ToField->setImplicit(D->isImplicit());
3754  if (ToCapturedVLAType)
3755  ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
3756  LexicalDC->addDeclInternal(ToField);
3757  return ToField;
3758 }
3759 
3761  // Import the major distinguishing characteristics of a variable.
3762  DeclContext *DC, *LexicalDC;
3763  DeclarationName Name;
3764  SourceLocation Loc;
3765  NamedDecl *ToD;
3766  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3767  return std::move(Err);
3768  if (ToD)
3769  return ToD;
3770 
3771  // Determine whether we've already imported this field.
3772  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3773  for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3774  if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3775  // For anonymous indirect fields, match up by index.
3776  if (!Name &&
3778  ASTImporter::getFieldIndex(FoundField))
3779  continue;
3780 
3781  if (Importer.IsStructurallyEquivalent(D->getType(),
3782  FoundField->getType(),
3783  !Name.isEmpty())) {
3784  Importer.MapImported(D, FoundField);
3785  return FoundField;
3786  }
3787 
3788  // If there are more anonymous fields to check, continue.
3789  if (!Name && I < N-1)
3790  continue;
3791 
3792  // FIXME: Why is this case not handled with calling HandleNameConflict?
3793  Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3794  << Name << D->getType() << FoundField->getType();
3795  Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3796  << FoundField->getType();
3797 
3798  return make_error<ImportError>(ImportError::NameConflict);
3799  }
3800  }
3801 
3802  // Import the type.
3803  auto TypeOrErr = import(D->getType());
3804  if (!TypeOrErr)
3805  return TypeOrErr.takeError();
3806 
3807  auto **NamedChain =
3808  new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3809 
3810  unsigned i = 0;
3811  for (auto *PI : D->chain())
3812  if (Expected<NamedDecl *> ToD = import(PI))
3813  NamedChain[i++] = *ToD;
3814  else
3815  return ToD.takeError();
3816 
3817  llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3818  IndirectFieldDecl *ToIndirectField;
3819  if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3820  Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3821  // FIXME here we leak `NamedChain` which is allocated before
3822  return ToIndirectField;
3823 
3824  ToIndirectField->setAccess(D->getAccess());
3825  ToIndirectField->setLexicalDeclContext(LexicalDC);
3826  LexicalDC->addDeclInternal(ToIndirectField);
3827  return ToIndirectField;
3828 }
3829 
3830 /// Used as return type of getFriendCountAndPosition.
3832  /// Number of similar looking friends.
3833  unsigned int TotalCount;
3834  /// Index of the specific FriendDecl.
3835  unsigned int IndexOfDecl;
3836 };
3837 
3838 template <class T>
3840  const FriendDecl *FD,
3841  llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
3842  unsigned int FriendCount = 0;
3843  llvm::Optional<unsigned int> FriendPosition;
3844  const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
3845 
3846  T TypeOrDecl = GetCanTypeOrDecl(FD);
3847 
3848  for (const FriendDecl *FoundFriend : RD->friends()) {
3849  if (FoundFriend == FD) {
3850  FriendPosition = FriendCount;
3851  ++FriendCount;
3852  } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
3853  GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
3854  ++FriendCount;
3855  }
3856  }
3857 
3858  assert(FriendPosition && "Friend decl not found in own parent.");
3859 
3860  return {FriendCount, *FriendPosition};
3861 }
3862 
3864  if (FD->getFriendType())
3865  return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
3866  if (TypeSourceInfo *TSI = F->getFriendType())
3867  return TSI->getType().getCanonicalType();
3868  llvm_unreachable("Wrong friend object type.");
3869  });
3870  else
3871  return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
3872  if (Decl *D = F->getFriendDecl())
3873  return D->getCanonicalDecl();
3874  llvm_unreachable("Wrong friend object type.");
3875  });
3876 }
3877 
3879  // Import the major distinguishing characteristics of a declaration.
3880  DeclContext *DC, *LexicalDC;
3881  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3882  return std::move(Err);
3883 
3884  // Determine whether we've already imported this decl.
3885  // FriendDecl is not a NamedDecl so we cannot use lookup.
3886  // We try to maintain order and count of redundant friend declarations.
3887  const auto *RD = cast<CXXRecordDecl>(DC);
3888  FriendDecl *ImportedFriend = RD->getFirstFriend();
3889  SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
3890 
3891  while (ImportedFriend) {
3892  bool Match = false;
3893  if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3894  Match =
3895  IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3896  /*Complain=*/false);
3897  } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3898  Match = Importer.IsStructurallyEquivalent(
3899  D->getFriendType()->getType(),
3900  ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
3901  }
3902  if (Match)
3903  ImportedEquivalentFriends.push_back(ImportedFriend);
3904 
3905  ImportedFriend = ImportedFriend->getNextFriend();
3906  }
3907  FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
3908 
3909  assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
3910  "Class with non-matching friends is imported, ODR check wrong?");
3911  if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
3912  return Importer.MapImported(
3913  D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
3914 
3915  // Not found. Create it.
3916  // The declarations will be put into order later by ImportDeclContext.
3918  if (NamedDecl *FriendD = D->getFriendDecl()) {
3919  NamedDecl *ToFriendD;
3920  if (Error Err = importInto(ToFriendD, FriendD))
3921  return std::move(Err);
3922 
3923  if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3924  !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3925  ToFriendD->setObjectOfFriendDecl(false);
3926 
3927  ToFU = ToFriendD;
3928  } else { // The friend is a type, not a decl.
3929  if (auto TSIOrErr = import(D->getFriendType()))
3930  ToFU = *TSIOrErr;
3931  else
3932  return TSIOrErr.takeError();
3933  }
3934 
3935  SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3936  auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3937  for (unsigned I = 0; I < D->NumTPLists; I++) {
3938  if (auto ListOrErr = import(FromTPLists[I]))
3939  ToTPLists[I] = *ListOrErr;
3940  else
3941  return ListOrErr.takeError();
3942  }
3943 
3944  auto LocationOrErr = import(D->getLocation());
3945  if (!LocationOrErr)
3946  return LocationOrErr.takeError();
3947  auto FriendLocOrErr = import(D->getFriendLoc());
3948  if (!FriendLocOrErr)
3949  return FriendLocOrErr.takeError();
3950 
3951  FriendDecl *FrD;
3952  if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3953  *LocationOrErr, ToFU,
3954  *FriendLocOrErr, ToTPLists))
3955  return FrD;
3956 
3957  FrD->setAccess(D->getAccess());
3958  FrD->setLexicalDeclContext(LexicalDC);
3959  LexicalDC->addDeclInternal(FrD);
3960  return FrD;
3961 }
3962 
3964  // Import the major distinguishing characteristics of an ivar.
3965  DeclContext *DC, *LexicalDC;
3966  DeclarationName Name;
3967  SourceLocation Loc;
3968  NamedDecl *ToD;
3969  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3970  return std::move(Err);
3971  if (ToD)
3972  return ToD;
3973 
3974  // Determine whether we've already imported this ivar
3975  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3976  for (auto *FoundDecl : FoundDecls) {
3977  if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3978  if (Importer.IsStructurallyEquivalent(D->getType(),
3979  FoundIvar->getType())) {
3980  Importer.MapImported(D, FoundIvar);
3981  return FoundIvar;
3982  }
3983 
3984  Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3985  << Name << D->getType() << FoundIvar->getType();
3986  Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3987  << FoundIvar->getType();
3988 
3989  return make_error<ImportError>(ImportError::NameConflict);
3990  }
3991  }
3992 
3993  Error Err = Error::success();
3994  auto ToType = importChecked(Err, D->getType());
3995  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
3996  auto ToBitWidth = importChecked(Err, D->getBitWidth());
3997  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3998  if (Err)
3999  return std::move(Err);
4000 
4001  ObjCIvarDecl *ToIvar;
4002  if (GetImportedOrCreateDecl(
4003  ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
4004  ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4005  ToType, ToTypeSourceInfo,
4006  D->getAccessControl(),ToBitWidth, D->getSynthesize()))
4007  return ToIvar;
4008 
4009  ToIvar->setLexicalDeclContext(LexicalDC);
4010  LexicalDC->addDeclInternal(ToIvar);
4011  return ToIvar;
4012 }
4013 
4015 
4017  auto RedeclIt = Redecls.begin();
4018  // Import the first part of the decl chain. I.e. import all previous
4019  // declarations starting from the canonical decl.
4020  for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4021  ExpectedDecl RedeclOrErr = import(*RedeclIt);
4022  if (!RedeclOrErr)
4023  return RedeclOrErr.takeError();
4024  }
4025  assert(*RedeclIt == D);
4026 
4027  // Import the major distinguishing characteristics of a variable.
4028  DeclContext *DC, *LexicalDC;
4029  DeclarationName Name;
4030  SourceLocation Loc;
4031  NamedDecl *ToD;
4032  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4033  return std::move(Err);
4034  if (ToD)
4035  return ToD;
4036 
4037  // Try to find a variable in our own ("to") context with the same name and
4038  // in the same context as the variable we're importing.
4039  VarDecl *FoundByLookup = nullptr;
4040  if (D->isFileVarDecl()) {
4041  SmallVector<NamedDecl *, 4> ConflictingDecls;
4042  unsigned IDNS = Decl::IDNS_Ordinary;
4043  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4044  for (auto *FoundDecl : FoundDecls) {
4045  if (!FoundDecl->isInIdentifierNamespace(IDNS))
4046  continue;
4047 
4048  if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4049  if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4050  continue;
4051  if (Importer.IsStructurallyEquivalent(D->getType(),
4052  FoundVar->getType())) {
4053 
4054  // The VarDecl in the "From" context has a definition, but in the
4055  // "To" context we already have a definition.
4056  VarDecl *FoundDef = FoundVar->getDefinition();
4057  if (D->isThisDeclarationADefinition() && FoundDef)
4058  // FIXME Check for ODR error if the two definitions have
4059  // different initializers?
4060  return Importer.MapImported(D, FoundDef);
4061 
4062  // The VarDecl in the "From" context has an initializer, but in the
4063  // "To" context we already have an initializer.
4064  const VarDecl *FoundDInit = nullptr;
4065  if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4066  // FIXME Diagnose ODR error if the two initializers are different?
4067  return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4068 
4069  FoundByLookup = FoundVar;
4070  break;
4071  }
4072 
4073  const ArrayType *FoundArray
4074  = Importer.getToContext().getAsArrayType(FoundVar->getType());
4075  const ArrayType *TArray
4076  = Importer.getToContext().getAsArrayType(D->getType());
4077  if (FoundArray && TArray) {
4078  if (isa<IncompleteArrayType>(FoundArray) &&
4079  isa<ConstantArrayType>(TArray)) {
4080  // Import the type.
4081  if (auto TyOrErr = import(D->getType()))
4082  FoundVar->setType(*TyOrErr);
4083  else
4084  return TyOrErr.takeError();
4085 
4086  FoundByLookup = FoundVar;
4087  break;
4088  } else if (isa<IncompleteArrayType>(TArray) &&
4089  isa<ConstantArrayType>(FoundArray)) {
4090  FoundByLookup = FoundVar;
4091  break;
4092  }
4093  }
4094 
4095  Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4096  << Name << D->getType() << FoundVar->getType();
4097  Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4098  << FoundVar->getType();
4099  ConflictingDecls.push_back(FoundDecl);
4100  }
4101  }
4102 
4103  if (!ConflictingDecls.empty()) {
4104  ExpectedName NameOrErr = Importer.HandleNameConflict(
4105  Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4106  if (NameOrErr)
4107  Name = NameOrErr.get();
4108  else
4109  return NameOrErr.takeError();
4110  }
4111  }
4112 
4113  Error Err = Error::success();
4114  auto ToType = importChecked(Err, D->getType());
4115  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4116  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4117  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4118  if (Err)
4119  return std::move(Err);
4120 
4121  VarDecl *ToVar;
4122  if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4123  SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4124  if (Error Err =
4125  ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4126  return std::move(Err);
4127  DecompositionDecl *ToDecomp;
4128  if (GetImportedOrCreateDecl(
4129  ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4130  Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4131  return ToDecomp;
4132  ToVar = ToDecomp;
4133  } else {
4134  // Create the imported variable.
4135  if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4136  ToInnerLocStart, Loc,
4137  Name.getAsIdentifierInfo(), ToType,
4138  ToTypeSourceInfo, D->getStorageClass()))
4139  return ToVar;
4140  }
4141 
4142  ToVar->setTSCSpec(D->getTSCSpec());
4143  ToVar->setQualifierInfo(ToQualifierLoc);
4144  ToVar->setAccess(D->getAccess());
4145  ToVar->setLexicalDeclContext(LexicalDC);
4146 
4147  if (FoundByLookup) {
4148  auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4149  ToVar->setPreviousDecl(Recent);
4150  }
4151 
4152  // Import the described template, if any.
4153  if (D->getDescribedVarTemplate()) {
4154  auto ToVTOrErr = import(D->getDescribedVarTemplate());
4155  if (!ToVTOrErr)
4156  return ToVTOrErr.takeError();
4157  }
4158 
4159  if (Error Err = ImportInitializer(D, ToVar))
4160  return std::move(Err);
4161 
4162  if (D->isConstexpr())
4163  ToVar->setConstexpr(true);
4164 
4165  addDeclToContexts(D, ToVar);
4166 
4167  // Import the rest of the chain. I.e. import all subsequent declarations.
4168  for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4169  ExpectedDecl RedeclOrErr = import(*RedeclIt);
4170  if (!RedeclOrErr)
4171  return RedeclOrErr.takeError();
4172  }
4173 
4174  return ToVar;
4175 }
4176 
4178  // Parameters are created in the translation unit's context, then moved
4179  // into the function declaration's context afterward.
4180  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4181 
4182  Error Err = Error::success();
4183  auto ToDeclName = importChecked(Err, D->getDeclName());
4184  auto ToLocation = importChecked(Err, D->getLocation());
4185  auto ToType = importChecked(Err, D->getType());
4186  if (Err)
4187  return std::move(Err);
4188 
4189  // Create the imported parameter.
4190  ImplicitParamDecl *ToParm = nullptr;
4191  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4192  ToLocation, ToDeclName.getAsIdentifierInfo(),
4193  ToType, D->getParameterKind()))
4194  return ToParm;
4195  return ToParm;
4196 }
4197 
4199  const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4200  ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4201  ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4202 
4203  if (FromParam->hasUninstantiatedDefaultArg()) {
4204  if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4205  ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4206  else
4207  return ToDefArgOrErr.takeError();
4208  } else if (FromParam->hasUnparsedDefaultArg()) {
4209  ToParam->setUnparsedDefaultArg();
4210  } else if (FromParam->hasDefaultArg()) {
4211  if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4212  ToParam->setDefaultArg(*ToDefArgOrErr);
4213  else
4214  return ToDefArgOrErr.takeError();
4215  }
4216 
4217  return Error::success();
4218 }
4219 
4221  // Parameters are created in the translation unit's context, then moved
4222  // into the function declaration's context afterward.
4223  DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4224 
4225  Error Err = Error::success();
4226  auto ToDeclName = importChecked(Err, D->getDeclName());
4227  auto ToLocation = importChecked(Err, D->getLocation());
4228  auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4229  auto ToType = importChecked(Err, D->getType());
4230  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4231  if (Err)
4232  return std::move(Err);
4233 
4234  ParmVarDecl *ToParm;
4235  if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4236  ToInnerLocStart, ToLocation,
4237  ToDeclName.getAsIdentifierInfo(), ToType,
4238  ToTypeSourceInfo, D->getStorageClass(),
4239  /*DefaultArg*/ nullptr))
4240  return ToParm;
4241 
4242  // Set the default argument. It should be no problem if it was already done.
4243  // Do not import the default expression before GetImportedOrCreateDecl call
4244  // to avoid possible infinite import loop because circular dependency.
4245  if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4246  return std::move(Err);
4247 
4248  if (D->isObjCMethodParameter()) {
4251  } else {
4252  ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4253  D->getFunctionScopeIndex());
4254  }
4255 
4256  return ToParm;
4257 }
4258 
4260  // Import the major distinguishing characteristics of a method.
4261  DeclContext *DC, *LexicalDC;
4262  DeclarationName Name;
4263  SourceLocation Loc;
4264  NamedDecl *ToD;
4265  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4266  return std::move(Err);
4267  if (ToD)
4268  return ToD;
4269 
4270  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4271  for (auto *FoundDecl : FoundDecls) {
4272  if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4273  if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4274  continue;
4275 
4276  // Check return types.
4277  if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4278  FoundMethod->getReturnType())) {
4279  Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4280  << D->isInstanceMethod() << Name << D->getReturnType()
4281  << FoundMethod->getReturnType();
4282  Importer.ToDiag(FoundMethod->getLocation(),
4283  diag::note_odr_objc_method_here)
4284  << D->isInstanceMethod() << Name;
4285 
4286  return make_error<ImportError>(ImportError::NameConflict);
4287  }
4288 
4289  // Check the number of parameters.
4290  if (D->param_size() != FoundMethod->param_size()) {
4291  Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4292  << D->isInstanceMethod() << Name
4293  << D->param_size() << FoundMethod->param_size();
4294  Importer.ToDiag(FoundMethod->getLocation(),
4295  diag::note_odr_objc_method_here)
4296  << D->isInstanceMethod() << Name;
4297 
4298  return make_error<ImportError>(ImportError::NameConflict);
4299  }
4300 
4301  // Check parameter types.
4303  PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4304  P != PEnd; ++P, ++FoundP) {
4305  if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4306  (*FoundP)->getType())) {
4307  Importer.FromDiag((*P)->getLocation(),
4308  diag::warn_odr_objc_method_param_type_inconsistent)
4309  << D->isInstanceMethod() << Name
4310  << (*P)->getType() << (*FoundP)->getType();
4311  Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4312  << (*FoundP)->getType();
4313 
4314  return make_error<ImportError>(ImportError::NameConflict);
4315  }
4316  }
4317 
4318  // Check variadic/non-variadic.
4319  // Check the number of parameters.
4320  if (D->isVariadic() != FoundMethod->isVariadic()) {
4321  Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4322  << D->isInstanceMethod() << Name;
4323  Importer.ToDiag(FoundMethod->getLocation(),
4324  diag::note_odr_objc_method_here)
4325  << D->isInstanceMethod() << Name;
4326 
4327  return make_error<ImportError>(ImportError::NameConflict);
4328  }
4329 
4330  // FIXME: Any other bits we need to merge?
4331  return Importer.MapImported(D, FoundMethod);
4332  }
4333  }
4334 
4335  Error Err = Error::success();
4336  auto ToEndLoc = importChecked(Err, D->getEndLoc());
4337  auto ToReturnType = importChecked(Err, D->getReturnType());
4338  auto ToReturnTypeSourceInfo =
4340  if (Err)
4341  return std::move(Err);
4342 
4343  ObjCMethodDecl *ToMethod;
4344  if (GetImportedOrCreateDecl(
4345  ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4346  Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4350  return ToMethod;
4351 
4352  // FIXME: When we decide to merge method definitions, we'll need to
4353  // deal with implicit parameters.
4354 
4355  // Import the parameters
4357  for (auto *FromP : D->parameters()) {
4358  if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4359  ToParams.push_back(*ToPOrErr);
4360  else
4361  return ToPOrErr.takeError();
4362  }
4363 
4364  // Set the parameters.
4365  for (auto *ToParam : ToParams) {
4366  ToParam->setOwningFunction(ToMethod);
4367  ToMethod->addDeclInternal(ToParam);
4368  }
4369 
4370  SmallVector<SourceLocation, 12> FromSelLocs;
4371  D->getSelectorLocs(FromSelLocs);
4372  SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4373  if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4374  return std::move(Err);
4375 
4376  ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4377 
4378  ToMethod->setLexicalDeclContext(LexicalDC);
4379  LexicalDC->addDeclInternal(ToMethod);
4380 
4381  // Implicit params are declared when Sema encounters the definition but this
4382  // never happens when the method is imported. Manually declare the implicit
4383  // params now that the MethodDecl knows its class interface.
4384  if (D->getSelfDecl())
4385  ToMethod->createImplicitParams(Importer.getToContext(),
4386  ToMethod->getClassInterface());
4387 
4388  return ToMethod;
4389 }
4390 
4392  // Import the major distinguishing characteristics of a category.
4393  DeclContext *DC, *LexicalDC;
4394  DeclarationName Name;
4395  SourceLocation Loc;
4396  NamedDecl *ToD;
4397  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4398  return std::move(Err);
4399  if (ToD)
4400  return ToD;
4401 
4402  Error Err = Error::success();
4403  auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4404  auto ToLocation = importChecked(Err, D->getLocation());
4405  auto ToColonLoc = importChecked(Err, D->getColonLoc());
4406  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4407  if (Err)
4408  return std::move(Err);
4409 
4410  ObjCTypeParamDecl *Result;
4411  if (GetImportedOrCreateDecl(
4412  Result, D, Importer.getToContext(), DC, D->getVariance(),
4413  ToVarianceLoc, D->getIndex(),
4414  ToLocation, Name.getAsIdentifierInfo(),
4415  ToColonLoc, ToTypeSourceInfo))
4416  return Result;
4417 
4418  Result->setLexicalDeclContext(LexicalDC);
4419  return Result;
4420 }
4421 
4423  // Import the major distinguishing characteristics of a category.
4424  DeclContext *DC, *LexicalDC;
4425  DeclarationName Name;
4426  SourceLocation Loc;
4427  NamedDecl *ToD;
4428  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4429  return std::move(Err);
4430  if (ToD)
4431  return ToD;
4432 
4433  ObjCInterfaceDecl *ToInterface;
4434  if (Error Err = importInto(ToInterface, D->getClassInterface()))
4435  return std::move(Err);
4436 
4437  // Determine if we've already encountered this category.
4438  ObjCCategoryDecl *MergeWithCategory
4439  = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4440  ObjCCategoryDecl *ToCategory = MergeWithCategory;
4441  if (!ToCategory) {
4442 
4443  Error Err = Error::success();
4444  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4445  auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4446  auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4447  auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4448  if (Err)
4449  return std::move(Err);
4450 
4451  if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4452  ToAtStartLoc, Loc,
4453  ToCategoryNameLoc,
4454  Name.getAsIdentifierInfo(), ToInterface,
4455  /*TypeParamList=*/nullptr,
4456  ToIvarLBraceLoc,
4457  ToIvarRBraceLoc))
4458  return ToCategory;
4459 
4460  ToCategory->setLexicalDeclContext(LexicalDC);
4461  LexicalDC->addDeclInternal(ToCategory);
4462  // Import the type parameter list after MapImported, to avoid
4463  // loops when bringing in their DeclContext.
4464  if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4465  ToCategory->setTypeParamList(*PListOrErr);
4466  else
4467  return PListOrErr.takeError();
4468 
4469  // Import protocols
4471  SmallVector<SourceLocation, 4> ProtocolLocs;
4473  = D->protocol_loc_begin();
4475  FromProtoEnd = D->protocol_end();
4476  FromProto != FromProtoEnd;
4477  ++FromProto, ++FromProtoLoc) {
4478  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4479  Protocols.push_back(*ToProtoOrErr);
4480  else
4481  return ToProtoOrErr.takeError();
4482 
4483  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4484  ProtocolLocs.push_back(*ToProtoLocOrErr);
4485  else
4486  return ToProtoLocOrErr.takeError();
4487  }
4488 
4489  // FIXME: If we're merging, make sure that the protocol list is the same.
4490  ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4491  ProtocolLocs.data(), Importer.getToContext());
4492 
4493  } else {
4494  Importer.MapImported(D, ToCategory);
4495  }
4496 
4497  // Import all of the members of this category.
4498  if (Error Err = ImportDeclContext(D))
4499  return std::move(Err);
4500 
4501  // If we have an implementation, import it as well.
4502  if (D->getImplementation()) {
4503  if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4504  import(D->getImplementation()))
4505  ToCategory->setImplementation(*ToImplOrErr);
4506  else
4507  return ToImplOrErr.takeError();
4508  }
4509 
4510  return ToCategory;
4511 }
4512 
4515  if (To->getDefinition()) {
4517  if (Error Err = ImportDeclContext(From))
4518  return Err;
4519  return Error::success();
4520  }
4521 
4522  // Start the protocol definition
4523  To->startDefinition();
4524 
4525  // Import protocols
4527  SmallVector<SourceLocation, 4> ProtocolLocs;
4529  From->protocol_loc_begin();
4530  for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4531  FromProtoEnd = From->protocol_end();
4532  FromProto != FromProtoEnd;
4533  ++FromProto, ++FromProtoLoc) {
4534  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4535  Protocols.push_back(*ToProtoOrErr);
4536  else
4537  return ToProtoOrErr.takeError();
4538 
4539  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4540  ProtocolLocs.push_back(*ToProtoLocOrErr);
4541  else
4542  return ToProtoLocOrErr.takeError();
4543 
4544  }
4545 
4546  // FIXME: If we're merging, make sure that the protocol list is the same.
4547  To->setProtocolList(Protocols.data(), Protocols.size(),
4548  ProtocolLocs.data(), Importer.getToContext());
4549 
4551  // Import all of the members of this protocol.
4552  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4553  return Err;
4554  }
4555  return Error::success();
4556 }
4557 
4559  // If this protocol has a definition in the translation unit we're coming
4560  // from, but this particular declaration is not that definition, import the
4561  // definition and map to that.
4562  ObjCProtocolDecl *Definition = D->getDefinition();
4563  if (Definition && Definition != D) {
4564  if (ExpectedDecl ImportedDefOrErr = import(Definition))
4565  return Importer.MapImported(D, *ImportedDefOrErr);
4566  else
4567  return ImportedDefOrErr.takeError();
4568  }
4569 
4570  // Import the major distinguishing characteristics of a protocol.
4571  DeclContext *DC, *LexicalDC;
4572  DeclarationName Name;
4573  SourceLocation Loc;
4574  NamedDecl *ToD;
4575  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4576  return std::move(Err);
4577  if (ToD)
4578  return ToD;
4579 
4580  ObjCProtocolDecl *MergeWithProtocol = nullptr;
4581  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4582  for (auto *FoundDecl : FoundDecls) {
4584  continue;
4585 
4586  if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4587  break;
4588  }
4589 
4590  ObjCProtocolDecl *ToProto = MergeWithProtocol;
4591  if (!ToProto) {
4592  auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4593  if (!ToAtBeginLocOrErr)
4594  return ToAtBeginLocOrErr.takeError();
4595 
4596  if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4597  Name.getAsIdentifierInfo(), Loc,
4598  *ToAtBeginLocOrErr,
4599  /*PrevDecl=*/nullptr))
4600  return ToProto;
4601  ToProto->setLexicalDeclContext(LexicalDC);
4602  LexicalDC->addDeclInternal(ToProto);
4603  }
4604 
4605  Importer.MapImported(D, ToProto);
4606 
4608  if (Error Err = ImportDefinition(D, ToProto))
4609  return std::move(Err);
4610 
4611  return ToProto;
4612 }
4613 
4615  DeclContext *DC, *LexicalDC;
4616  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4617  return std::move(Err);
4618 
4619  ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4620  if (!ExternLocOrErr)
4621  return ExternLocOrErr.takeError();
4622 
4623  ExpectedSLoc LangLocOrErr = import(D->getLocation());
4624  if (!LangLocOrErr)
4625  return LangLocOrErr.takeError();
4626 
4627  bool HasBraces = D->hasBraces();
4628 
4629  LinkageSpecDecl *ToLinkageSpec;
4630  if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4631  *ExternLocOrErr, *LangLocOrErr,
4632  D->getLanguage(), HasBraces))
4633  return ToLinkageSpec;
4634 
4635  if (HasBraces) {
4636  ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4637  if (!RBraceLocOrErr)
4638  return RBraceLocOrErr.takeError();
4639  ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4640  }
4641 
4642  ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4643  LexicalDC->addDeclInternal(ToLinkageSpec);
4644 
4645  return ToLinkageSpec;
4646 }
4647 
4649  BaseUsingDecl *ToSI) {
4650  for (UsingShadowDecl *FromShadow : D->shadows()) {
4651  if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4652  ToSI->addShadowDecl(*ToShadowOrErr);
4653  else
4654  // FIXME: We return error here but the definition is already created
4655  // and available with lookups. How to fix this?..
4656  return ToShadowOrErr.takeError();
4657  }
4658  return ToSI;
4659 }
4660 
4662  DeclContext *DC, *LexicalDC;
4663  DeclarationName Name;
4664  SourceLocation Loc;
4665  NamedDecl *ToD = nullptr;
4666  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4667  return std::move(Err);
4668  if (ToD)
4669  return ToD;
4670 
4671  Error Err = Error::success();
4672  auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4673  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4674  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4675  if (Err)
4676  return std::move(Err);
4677 
4678  DeclarationNameInfo NameInfo(Name, ToLoc);
4679  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4680  return std::move(Err);
4681 
4682  UsingDecl *ToUsing;
4683  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4684  ToUsingLoc, ToQualifierLoc, NameInfo,
4685  D->hasTypename()))
4686  return ToUsing;
4687 
4688  ToUsing->setLexicalDeclContext(LexicalDC);
4689  LexicalDC->addDeclInternal(ToUsing);
4690 
4691  if (NamedDecl *FromPattern =
4693  if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4695  ToUsing, *ToPatternOrErr);
4696  else
4697  return ToPatternOrErr.takeError();
4698  }
4699 
4700  return ImportUsingShadowDecls(D, ToUsing);
4701 }
4702 
4704  DeclContext *DC, *LexicalDC;
4705  DeclarationName Name;
4706  SourceLocation Loc;
4707  NamedDecl *ToD = nullptr;
4708  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4709  return std::move(Err);
4710  if (ToD)
4711  return ToD;
4712 
4713  Error Err = Error::success();
4714  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4715  auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
4716  auto ToEnumDecl = importChecked(Err, D->getEnumDecl());
4717  if (Err)
4718  return std::move(Err);
4719 
4720  UsingEnumDecl *ToUsingEnum;
4721  if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
4722  ToUsingLoc, ToEnumLoc, Loc, ToEnumDecl))
4723  return ToUsingEnum;
4724 
4725  ToUsingEnum->setLexicalDeclContext(LexicalDC);
4726  LexicalDC->addDeclInternal(ToUsingEnum);
4727 
4728  if (UsingEnumDecl *FromPattern =
4730  if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
4731  Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
4732  *ToPatternOrErr);
4733  else
4734  return ToPatternOrErr.takeError();
4735  }
4736 
4737  return ImportUsingShadowDecls(D, ToUsingEnum);
4738 }
4739 
4741  DeclContext *DC, *LexicalDC;
4742  DeclarationName Name;
4743  SourceLocation Loc;
4744  NamedDecl *ToD = nullptr;
4745  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4746  return std::move(Err);
4747  if (ToD)
4748  return ToD;
4749 
4750  Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
4751  if (!ToIntroducerOrErr)
4752  return ToIntroducerOrErr.takeError();
4753 
4754  Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4755  if (!ToTargetOrErr)
4756  return ToTargetOrErr.takeError();
4757 
4758  UsingShadowDecl *ToShadow;
4759  if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4760  Name, *ToIntroducerOrErr, *ToTargetOrErr))
4761  return ToShadow;
4762 
4763  ToShadow->setLexicalDeclContext(LexicalDC);
4764  ToShadow->setAccess(D->getAccess());
4765 
4766  if (UsingShadowDecl *FromPattern =
4768  if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4770  ToShadow, *ToPatternOrErr);
4771  else
4772  // FIXME: We return error here but the definition is already created
4773  // and available with lookups. How to fix this?..
4774  return ToPatternOrErr.takeError();
4775  }
4776 
4777  LexicalDC->addDeclInternal(ToShadow);
4778 
4779  return ToShadow;
4780 }
4781 
4783  DeclContext *DC, *LexicalDC;
4784  DeclarationName Name;
4785  SourceLocation Loc;
4786  NamedDecl *ToD = nullptr;
4787  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4788  return std::move(Err);
4789  if (ToD)
4790  return ToD;
4791 
4792  auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4793  if (!ToComAncestorOrErr)
4794  return ToComAncestorOrErr.takeError();
4795 
4796  Error Err = Error::success();
4797  auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
4798  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4799  auto ToNamespaceKeyLocation =
4801  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4802  auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
4803  if (Err)
4804  return std::move(Err);
4805 
4806  UsingDirectiveDecl *ToUsingDir;
4807  if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4808  ToUsingLoc,
4809  ToNamespaceKeyLocation,
4810  ToQualifierLoc,
4811  ToIdentLocation,
4812  ToNominatedNamespace, *ToComAncestorOrErr))
4813  return ToUsingDir;
4814 
4815  ToUsingDir->setLexicalDeclContext(LexicalDC);
4816  LexicalDC->addDeclInternal(ToUsingDir);
4817 
4818  return ToUsingDir;
4819 }
4820 
4823  DeclContext *DC, *LexicalDC;
4824  DeclarationName Name;
4825  SourceLocation Loc;
4826  NamedDecl *ToD = nullptr;
4827  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4828  return std::move(Err);
4829  if (ToD)
4830  return ToD;
4831 
4832  Error Err = Error::success();
4833  auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4834  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4835  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4836  auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4837  if (Err)
4838  return std::move(Err);
4839 
4840  DeclarationNameInfo NameInfo(Name, ToLoc);
4841  if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4842  return std::move(Err);
4843 
4844  UnresolvedUsingValueDecl *ToUsingValue;
4845  if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4846  ToUsingLoc, ToQualifierLoc, NameInfo,
4847  ToEllipsisLoc))
4848  return ToUsingValue;
4849 
4850  ToUsingValue->setAccess(D->getAccess());
4851  ToUsingValue->setLexicalDeclContext(LexicalDC);
4852  LexicalDC->addDeclInternal(ToUsingValue);
4853 
4854  return ToUsingValue;
4855 }
4856 
4859  DeclContext *DC, *LexicalDC;
4860  DeclarationName Name;
4861  SourceLocation Loc;
4862  NamedDecl *ToD = nullptr;
4863  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4864  return std::move(Err);
4865  if (ToD)
4866  return ToD;
4867 
4868  Error Err = Error::success();
4869  auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4870  auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
4871  auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4872  auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4873  if (Err)
4874  return std::move(Err);
4875 
4876  UnresolvedUsingTypenameDecl *ToUsing;
4877  if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4878  ToUsingLoc, ToTypenameLoc,
4879  ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4880  return ToUsing;
4881 
4882  ToUsing->setAccess(D->getAccess());
4883  ToUsing->setLexicalDeclContext(LexicalDC);
4884  LexicalDC->addDeclInternal(ToUsing);
4885 
4886  return ToUsing;
4887 }
4888 
4890  Decl* ToD = nullptr;
4891  switch (D->getBuiltinTemplateKind()) {
4893  ToD = Importer.getToContext().getMakeIntegerSeqDecl();
4894  break;
4896  ToD = Importer.getToContext().getTypePackElementDecl();
4897  break;
4898  }
4899  assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
4900  Importer.MapImported(D, ToD);
4901  return ToD;
4902 }
4903 
4906  if (To->getDefinition()) {
4907  // Check consistency of superclass.
4908  ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4909  if (FromSuper) {
4910  if (auto FromSuperOrErr = import(FromSuper))
4911  FromSuper = *FromSuperOrErr;
4912  else
4913  return FromSuperOrErr.takeError();
4914  }
4915 
4916  ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4917  if ((bool)FromSuper != (bool)ToSuper ||
4918  (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4919  Importer.ToDiag(To->getLocation(),
4920  diag::warn_odr_objc_superclass_inconsistent)
4921  << To->getDeclName();
4922  if (ToSuper)
4923  Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4924  << To->getSuperClass()->getDeclName();
4925  else
4926  Importer.ToDiag(To->getLocation(),
4927  diag::note_odr_objc_missing_superclass);
4928  if (From->getSuperClass())
4929  Importer.FromDiag(From->getSuperClassLoc(),
4930  diag::note_odr_objc_superclass)
4931  << From->getSuperClass()->getDeclName();
4932  else
4933  Importer.FromDiag(From->getLocation(),
4934  diag::note_odr_objc_missing_superclass);
4935  }
4936 
4938  if (Error Err = ImportDeclContext(From))
4939  return Err;
4940  return Error::success();
4941  }
4942 
4943  // Start the definition.
4944  To->startDefinition();
4945 
4946  // If this class has a superclass, import it.
4947  if (From->getSuperClass()) {
4948  if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4949  To->setSuperClass(*SuperTInfoOrErr);
4950  else
4951  return SuperTInfoOrErr.takeError();
4952  }
4953 
4954  // Import protocols
4956  SmallVector<SourceLocation, 4> ProtocolLocs;
4958  From->protocol_loc_begin();
4959 
4960  for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4961  FromProtoEnd = From->protocol_end();
4962  FromProto != FromProtoEnd;
4963  ++FromProto, ++FromProtoLoc) {
4964  if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4965  Protocols.push_back(*ToProtoOrErr);
4966  else
4967  return ToProtoOrErr.takeError();
4968 
4969  if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4970  ProtocolLocs.push_back(*ToProtoLocOrErr);
4971  else
4972  return ToProtoLocOrErr.takeError();
4973 
4974  }
4975 
4976  // FIXME: If we're merging, make sure that the protocol list is the same.
4977  To->setProtocolList(Protocols.data(), Protocols.size(),
4978  ProtocolLocs.data(), Importer.getToContext());
4979 
4980  // Import categories. When the categories themselves are imported, they'll
4981  // hook themselves into this interface.
4982  for (auto *Cat : From->known_categories()) {
4983  auto ToCatOrErr = import(Cat);
4984  if (!ToCatOrErr)
4985  return ToCatOrErr.takeError();
4986  }
4987 
4988  // If we have an @implementation, import it as well.
4989  if (From->getImplementation()) {
4990  if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4991  import(From->getImplementation()))
4992  To->setImplementation(*ToImplOrErr);
4993  else
4994  return ToImplOrErr.takeError();
4995  }
4996 
4997  // Import all of the members of this class.
4998  if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4999  return Err;
5000 
5001  return Error::success();
5002 }
5003 
5006  if (!list)
5007  return nullptr;
5008 
5010  for (auto *fromTypeParam : *list) {
5011  if (auto toTypeParamOrErr = import(fromTypeParam))
5012  toTypeParams.push_back(*toTypeParamOrErr);
5013  else
5014  return toTypeParamOrErr.takeError();
5015  }
5016 
5017  auto LAngleLocOrErr = import(list->getLAngleLoc());
5018  if (!LAngleLocOrErr)
5019  return LAngleLocOrErr.takeError();
5020 
5021  auto RAngleLocOrErr = import(list->getRAngleLoc());
5022  if (!RAngleLocOrErr)
5023  return RAngleLocOrErr.takeError();
5024 
5025  return ObjCTypeParamList::create(Importer.getToContext(),
5026  *LAngleLocOrErr,
5027  toTypeParams,
5028  *RAngleLocOrErr);
5029 }
5030 
5032  // If this class has a definition in the translation unit we're coming from,
5033  // but this particular declaration is not that definition, import the
5034  // definition and map to that.
5035  ObjCInterfaceDecl *Definition = D->getDefinition();
5036  if (Definition && Definition != D) {
5037  if (ExpectedDecl ImportedDefOrErr = import(Definition))
5038  return Importer.MapImported(D, *ImportedDefOrErr);
5039  else
5040  return ImportedDefOrErr.takeError();
5041  }
5042 
5043  // Import the major distinguishing characteristics of an @interface.
5044  DeclContext *DC, *LexicalDC;
5045  DeclarationName Name;
5046  SourceLocation Loc;
5047  NamedDecl *ToD;
5048  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5049  return std::move(Err);
5050  if (ToD)
5051  return ToD;
5052 
5053  // Look for an existing interface with the same name.
5054  ObjCInterfaceDecl *MergeWithIface = nullptr;
5055  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5056  for (auto *FoundDecl : FoundDecls) {
5058  continue;
5059 
5060  if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
5061  break;
5062  }
5063 
5064  // Create an interface declaration, if one does not already exist.
5065  ObjCInterfaceDecl *ToIface = MergeWithIface;
5066  if (!ToIface) {
5067  ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5068  if (!AtBeginLocOrErr)
5069  return AtBeginLocOrErr.takeError();
5070 
5071  if (GetImportedOrCreateDecl(
5072  ToIface, D, Importer.getToContext(), DC,
5073  *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
5074  /*TypeParamList=*/nullptr,
5075  /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
5076  return ToIface;
5077  ToIface->setLexicalDeclContext(LexicalDC);
5078  LexicalDC->addDeclInternal(ToIface);
5079  }
5080  Importer.MapImported(D, ToIface);
5081  // Import the type parameter list after MapImported, to avoid
5082  // loops when bringing in their DeclContext.
5083  if (auto ToPListOrErr =
5085  ToIface->setTypeParamList(*ToPListOrErr);
5086  else
5087  return ToPListOrErr.takeError();
5088 
5090  if (Error Err = ImportDefinition(D, ToIface))
5091  return std::move(Err);
5092 
5093  return ToIface;
5094 }
5095 
5099  if (Error Err = importInto(Category, D->getCategoryDecl()))
5100  return std::move(Err);
5101 
5102  ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5103  if (!ToImpl) {
5104  DeclContext *DC, *LexicalDC;
5105  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5106  return std::move(Err);
5107 
5108  Error Err = Error::success();
5109  auto ToLocation = importChecked(Err, D->getLocation());
5110  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5111  auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5112  if (Err)
5113  return std::move(Err);
5114 
5115  if (GetImportedOrCreateDecl(
5116  ToImpl, D, Importer.getToContext(), DC,
5117  Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5118  ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5119  return ToImpl;
5120 
5121  ToImpl->setLexicalDeclContext(LexicalDC);
5122  LexicalDC->addDeclInternal(ToImpl);
5123  Category->setImplementation(ToImpl);
5124  }
5125 
5126  Importer.MapImported(D, ToImpl);
5127  if (Error Err = ImportDeclContext(D))
5128  return std::move(Err);
5129 
5130  return ToImpl;
5131 }
5132 
5135  // Find the corresponding interface.
5136  ObjCInterfaceDecl *Iface;
5137  if (Error Err = importInto(Iface, D->getClassInterface()))
5138  return std::move(Err);
5139 
5140  // Import the superclass, if any.
5141  ObjCInterfaceDecl *Super;
5142  if (Error Err = importInto(Super, D->getSuperClass()))
5143  return std::move(Err);
5144 
5145  ObjCImplementationDecl *Impl = Iface->getImplementation();
5146  if (!Impl) {
5147  // We haven't imported an implementation yet. Create a new @implementation
5148  // now.
5149  DeclContext *DC, *LexicalDC;
5150  if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5151  return std::move(Err);
5152 
5153  Error Err = Error::success();
5154  auto ToLocation = importChecked(Err, D->getLocation());
5155  auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5156  auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5157  auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5158  auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5159  if (Err)
5160  return std::move(Err);
5161 
5162  if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5163  DC, Iface, Super,
5164  ToLocation,
5165  ToAtStartLoc,
5166  ToSuperClassLoc,
5167  ToIvarLBraceLoc,
5168  ToIvarRBraceLoc))
5169  return Impl;
5170 
5171  Impl->setLexicalDeclContext(LexicalDC);
5172 
5173  // Associate the implementation with the class it implements.
5174  Iface->setImplementation(Impl);
5175  Importer.MapImported(D, Iface->getImplementation());
5176  } else {
5177  Importer.MapImported(D, Iface->getImplementation());
5178 
5179  // Verify that the existing @implementation has the same superclass.
5180  if ((Super && !Impl->getSuperClass()) ||
5181  (!Super && Impl->getSuperClass()) ||
5182  (Super && Impl->getSuperClass() &&
5184  Impl->getSuperClass()))) {
5185  Importer.ToDiag(Impl->getLocation(),
5186  diag::warn_odr_objc_superclass_inconsistent)
5187  << Iface->getDeclName();
5188  // FIXME: It would be nice to have the location of the superclass
5189  // below.
5190  if (Impl->getSuperClass())
5191  Importer.ToDiag(Impl->getLocation(),
5192  diag::note_odr_objc_superclass)
5193  << Impl->getSuperClass()->getDeclName();
5194  else
5195  Importer.ToDiag(Impl->getLocation(),
5196  diag::note_odr_objc_missing_superclass);
5197  if (D->getSuperClass())
5198  Importer.FromDiag(D->getLocation(),
5199  diag::note_odr_objc_superclass)
5200  << D->getSuperClass()->getDeclName();
5201  else
5202  Importer.FromDiag(D->getLocation(),
5203  diag::note_odr_objc_missing_superclass);
5204 
5205  return make_error<ImportError>(ImportError::NameConflict);
5206  }
5207  }
5208 
5209  // Import all of the members of this @implementation.
5210  if (Error Err = ImportDeclContext(D))
5211  return std::move(Err);
5212 
5213  return Impl;
5214 }
5215 
5217  // Import the major distinguishing characteristics of an @property.
5218  DeclContext *DC, *LexicalDC;
5219  DeclarationName Name;
5220  SourceLocation Loc;
5221  NamedDecl *ToD;
5222  if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5223  return std::move(Err);
5224  if (ToD)
5225  return ToD;
5226 
5227  // Check whether we have already imported this property.
5228  auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5229  for (auto *FoundDecl : FoundDecls) {
5230  if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5231  // Instance and class properties can share the same name but are different
5232  // declarations.
5233  if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5234  continue;
5235 
5236  // Check property types.
5237  if (!Importer.IsStructurallyEquivalent(D->getType(),
5238  FoundProp->getType())) {
5239  Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5240  << Name << D->getType() << FoundProp->getType();
5241  Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5242  << FoundProp->getType();
5243 
5244  return make_error<ImportError>(ImportError::NameConflict);
5245  }
5246 
5247  // FIXME: Check property attributes, getters, setters, etc.?
5248 
5249  // Consider these properties to be equivalent.
5250  Importer.MapImported(D, FoundProp);
5251  return FoundProp;
5252  }
5253  }
5254 
5255  Error Err = Error::success();
5256  auto ToType = importChecked(Err, D->getType());
5257  auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5258  auto ToAtLoc = importChecked(Err, D->getAtLoc());
5259  auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5260  if (Err)
5261  return std::move(Err);
5262 
5263  // Create the new property.
5264  ObjCPropertyDecl *ToProperty;
5265  if (GetImportedOrCreateDecl(
5266  ToProperty, D, Importer.getToContext(), DC, Loc,
5267  Name.getAsIdentifierInfo(), ToAtLoc,
5268  ToLParenLoc, ToType,
5269  ToTypeSourceInfo, D->getPropertyImplementation()))
5270  return ToPro