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