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