clang 19.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
371#define TYPE(Class, Base) \
372 ExpectedType Visit##Class##Type(const Class##Type *T);
373#include "clang/AST/TypeNodes.inc"
374
375 // Importing declarations
376 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
377 SourceLocation &Loc);
378 Error ImportDeclParts(
379 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
380 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
381 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
384 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
385 Error ImportDeclContext(
386 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
387 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
388
389 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
391 Expected<APValue> ImportAPValue(const APValue &FromValue);
392
394
395 /// What we should import from the definition.
397 /// Import the default subset of the definition, which might be
398 /// nothing (if minimal import is set) or might be everything (if minimal
399 /// import is not set).
401 /// Import everything.
403 /// Import only the bare bones needed to establish a valid
404 /// DeclContext.
406 };
407
409 return IDK == IDK_Everything ||
410 (IDK == IDK_Default && !Importer.isMinimalImport());
411 }
412
413 Error ImportInitializer(VarDecl *From, VarDecl *To);
414 Error ImportDefinition(
415 RecordDecl *From, RecordDecl *To,
417 Error ImportDefinition(
418 EnumDecl *From, EnumDecl *To,
420 Error ImportDefinition(
423 Error ImportDefinition(
430
431 template <typename InContainerTy>
433 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
434
435 template<typename InContainerTy>
437 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
438 const InContainerTy &Container, TemplateArgumentListInfo &Result);
439
442 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
445 FunctionDecl *FromFD);
447 DeclaratorDecl *ToD);
448
450
452
453 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
454 ParmVarDecl *ToParam);
455
458
459 template <typename T>
460 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
461
462 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true,
463 bool IgnoreTemplateParmDepth = false);
510
513
528
529 // Importing statements
549 // FIXME: MSAsmStmt
550 // FIXME: SEHExceptStmt
551 // FIXME: SEHFinallyStmt
552 // FIXME: SEHTryStmt
553 // FIXME: SEHLeaveStmt
554 // FIXME: CapturedStmt
558 // FIXME: MSDependentExistsStmt
566
567 // Importing expressions
644
645 // Helper for chaining together multiple imports. If an error is detected,
646 // subsequent imports will return default constructed nodes, so that failure
647 // can be detected with a single conditional branch after a sequence of
648 // imports.
649 template <typename T> T importChecked(Error &Err, const T &From) {
650 // Don't attempt to import nodes if we hit an error earlier.
651 if (Err)
652 return T{};
653 Expected<T> MaybeVal = import(From);
654 if (!MaybeVal) {
655 Err = MaybeVal.takeError();
656 return T{};
657 }
658 return *MaybeVal;
659 }
660
661 template<typename IIter, typename OIter>
662 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
663 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
664 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
665 Expected<ItemT> ToOrErr = import(*Ibegin);
666 if (!ToOrErr)
667 return ToOrErr.takeError();
668 *Obegin = *ToOrErr;
669 }
670 return Error::success();
671 }
672
673 // Import every item from a container structure into an output container.
674 // If error occurs, stops at first error and returns the error.
675 // The output container should have space for all needed elements (it is not
676 // expanded, new items are put into from the beginning).
677 template<typename InContainerTy, typename OutContainerTy>
679 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
680 return ImportArrayChecked(
681 InContainer.begin(), InContainer.end(), OutContainer.begin());
682 }
683
684 template<typename InContainerTy, typename OIter>
685 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
686 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
687 }
688
690 CXXMethodDecl *FromMethod);
691
693 FunctionDecl *FromFD);
694
695 // Returns true if the given function has a placeholder return type and
696 // that type is declared inside the body of the function.
697 // E.g. auto f() { struct X{}; return X(); }
699 };
700
701template <typename InContainerTy>
703 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
704 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
705 auto ToLAngleLocOrErr = import(FromLAngleLoc);
706 if (!ToLAngleLocOrErr)
707 return ToLAngleLocOrErr.takeError();
708 auto ToRAngleLocOrErr = import(FromRAngleLoc);
709 if (!ToRAngleLocOrErr)
710 return ToRAngleLocOrErr.takeError();
711
712 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
713 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
714 return Err;
715 Result = ToTAInfo;
716 return Error::success();
717}
718
719template <>
720Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
723 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
724}
725
726template <>
729 const ASTTemplateArgumentListInfo &From,
731 return ImportTemplateArgumentListInfo(
732 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
733}
734
737 FunctionDecl *FromFD) {
738 assert(FromFD->getTemplatedKind() ==
740
742
743 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
744 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
745 return std::move(Err);
746
747 // Import template arguments.
748 if (Error Err = ImportTemplateArguments(FTSInfo->TemplateArguments->asArray(),
749 std::get<1>(Result)))
750 return std::move(Err);
751
752 return Result;
753}
754
755template <>
757ASTNodeImporter::import(TemplateParameterList *From) {
759 if (Error Err = ImportContainerChecked(*From, To))
760 return std::move(Err);
761
762 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
763 if (!ToRequiresClause)
764 return ToRequiresClause.takeError();
765
766 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
767 if (!ToTemplateLocOrErr)
768 return ToTemplateLocOrErr.takeError();
769 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
770 if (!ToLAngleLocOrErr)
771 return ToLAngleLocOrErr.takeError();
772 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
773 if (!ToRAngleLocOrErr)
774 return ToRAngleLocOrErr.takeError();
775
777 Importer.getToContext(),
778 *ToTemplateLocOrErr,
779 *ToLAngleLocOrErr,
780 To,
781 *ToRAngleLocOrErr,
782 *ToRequiresClause);
783}
784
785template <>
787ASTNodeImporter::import(const TemplateArgument &From) {
788 switch (From.getKind()) {
790 return TemplateArgument();
791
793 ExpectedType ToTypeOrErr = import(From.getAsType());
794 if (!ToTypeOrErr)
795 return ToTypeOrErr.takeError();
796 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ false,
797 From.getIsDefaulted());
798 }
799
801 ExpectedType ToTypeOrErr = import(From.getIntegralType());
802 if (!ToTypeOrErr)
803 return ToTypeOrErr.takeError();
804 return TemplateArgument(From, *ToTypeOrErr);
805 }
806
808 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
809 if (!ToOrErr)
810 return ToOrErr.takeError();
811 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
812 if (!ToTypeOrErr)
813 return ToTypeOrErr.takeError();
814 return TemplateArgument(dyn_cast<ValueDecl>((*ToOrErr)->getCanonicalDecl()),
815 *ToTypeOrErr, From.getIsDefaulted());
816 }
817
819 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
820 if (!ToTypeOrErr)
821 return ToTypeOrErr.takeError();
822 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true,
823 From.getIsDefaulted());
824 }
825
827 ExpectedType ToTypeOrErr = import(From.getStructuralValueType());
828 if (!ToTypeOrErr)
829 return ToTypeOrErr.takeError();
830 Expected<APValue> ToValueOrErr = import(From.getAsStructuralValue());
831 if (!ToValueOrErr)
832 return ToValueOrErr.takeError();
833 return TemplateArgument(Importer.getToContext(), *ToTypeOrErr,
834 *ToValueOrErr);
835 }
836
838 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
839 if (!ToTemplateOrErr)
840 return ToTemplateOrErr.takeError();
841
842 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted());
843 }
844
846 Expected<TemplateName> ToTemplateOrErr =
847 import(From.getAsTemplateOrTemplatePattern());
848 if (!ToTemplateOrErr)
849 return ToTemplateOrErr.takeError();
850
851 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(),
852 From.getIsDefaulted());
853 }
854
856 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
857 return TemplateArgument(*ToExpr, From.getIsDefaulted());
858 else
859 return ToExpr.takeError();
860
863 ToPack.reserve(From.pack_size());
864 if (Error Err = ImportTemplateArguments(From.pack_elements(), ToPack))
865 return std::move(Err);
866
867 return TemplateArgument(
868 llvm::ArrayRef(ToPack).copy(Importer.getToContext()));
869 }
870 }
871
872 llvm_unreachable("Invalid template argument kind");
873}
874
875template <>
877ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
878 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
879 if (!ArgOrErr)
880 return ArgOrErr.takeError();
881 TemplateArgument Arg = *ArgOrErr;
882
883 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
884
887 ExpectedExpr E = import(FromInfo.getAsExpr());
888 if (!E)
889 return E.takeError();
890 ToInfo = TemplateArgumentLocInfo(*E);
891 } else if (Arg.getKind() == TemplateArgument::Type) {
892 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
893 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
894 else
895 return TSIOrErr.takeError();
896 } else {
897 auto ToTemplateQualifierLocOrErr =
898 import(FromInfo.getTemplateQualifierLoc());
899 if (!ToTemplateQualifierLocOrErr)
900 return ToTemplateQualifierLocOrErr.takeError();
901 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
902 if (!ToTemplateNameLocOrErr)
903 return ToTemplateNameLocOrErr.takeError();
904 auto ToTemplateEllipsisLocOrErr =
905 import(FromInfo.getTemplateEllipsisLoc());
906 if (!ToTemplateEllipsisLocOrErr)
907 return ToTemplateEllipsisLocOrErr.takeError();
909 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
910 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
911 }
912
913 return TemplateArgumentLoc(Arg, ToInfo);
914}
915
916template <>
917Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
918 if (DG.isNull())
919 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
920 size_t NumDecls = DG.end() - DG.begin();
922 ToDecls.reserve(NumDecls);
923 for (Decl *FromD : DG) {
924 if (auto ToDOrErr = import(FromD))
925 ToDecls.push_back(*ToDOrErr);
926 else
927 return ToDOrErr.takeError();
928 }
929 return DeclGroupRef::Create(Importer.getToContext(),
930 ToDecls.begin(),
931 NumDecls);
932}
933
934template <>
936ASTNodeImporter::import(const Designator &D) {
937 if (D.isFieldDesignator()) {
938 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
939
940 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
941 if (!ToDotLocOrErr)
942 return ToDotLocOrErr.takeError();
943
944 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
945 if (!ToFieldLocOrErr)
946 return ToFieldLocOrErr.takeError();
947
949 ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
950 }
951
952 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
953 if (!ToLBracketLocOrErr)
954 return ToLBracketLocOrErr.takeError();
955
956 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
957 if (!ToRBracketLocOrErr)
958 return ToRBracketLocOrErr.takeError();
959
960 if (D.isArrayDesignator())
962 *ToLBracketLocOrErr,
963 *ToRBracketLocOrErr);
964
965 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
966 if (!ToEllipsisLocOrErr)
967 return ToEllipsisLocOrErr.takeError();
968
969 assert(D.isArrayRangeDesignator());
971 D.getArrayIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
972 *ToRBracketLocOrErr);
973}
974
975template <>
976Expected<ConceptReference *> ASTNodeImporter::import(ConceptReference *From) {
977 Error Err = Error::success();
978 auto ToNNS = importChecked(Err, From->getNestedNameSpecifierLoc());
979 auto ToTemplateKWLoc = importChecked(Err, From->getTemplateKWLoc());
980 auto ToConceptNameLoc =
982 auto ToConceptName = importChecked(Err, From->getConceptNameInfo().getName());
983 auto ToFoundDecl = importChecked(Err, From->getFoundDecl());
984 auto ToNamedConcept = importChecked(Err, From->getNamedConcept());
985 if (Err)
986 return std::move(Err);
988 const auto *ASTTemplateArgs = From->getTemplateArgsAsWritten();
989 if (ASTTemplateArgs)
990 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo))
991 return std::move(Err);
992 auto *ConceptRef = ConceptReference::Create(
993 Importer.getToContext(), ToNNS, ToTemplateKWLoc,
994 DeclarationNameInfo(ToConceptName, ToConceptNameLoc), ToFoundDecl,
995 ToNamedConcept,
996 ASTTemplateArgs ? ASTTemplateArgumentListInfo::Create(
997 Importer.getToContext(), ToTAInfo)
998 : nullptr);
999 return ConceptRef;
1000}
1001
1002template <>
1003Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
1004 ValueDecl *Var = nullptr;
1005 if (From.capturesVariable()) {
1006 if (auto VarOrErr = import(From.getCapturedVar()))
1007 Var = *VarOrErr;
1008 else
1009 return VarOrErr.takeError();
1010 }
1011
1012 auto LocationOrErr = import(From.getLocation());
1013 if (!LocationOrErr)
1014 return LocationOrErr.takeError();
1015
1016 SourceLocation EllipsisLoc;
1017 if (From.isPackExpansion())
1018 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
1019 return std::move(Err);
1020
1021 return LambdaCapture(
1022 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1023 EllipsisLoc);
1024}
1025
1026template <typename T>
1028 if (Found->getLinkageInternal() != From->getLinkageInternal())
1029 return false;
1030
1031 if (From->hasExternalFormalLinkage())
1032 return Found->hasExternalFormalLinkage();
1033 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1034 return false;
1035 if (From->isInAnonymousNamespace())
1036 return Found->isInAnonymousNamespace();
1037 else
1038 return !Found->isInAnonymousNamespace() &&
1039 !Found->hasExternalFormalLinkage();
1040}
1041
1042template <>
1044 TypedefNameDecl *From) {
1045 if (Found->getLinkageInternal() != From->getLinkageInternal())
1046 return false;
1047
1048 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1049 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1050 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1051}
1052
1053} // namespace clang
1054
1055//----------------------------------------------------------------------------
1056// Import Types
1057//----------------------------------------------------------------------------
1058
1059using namespace clang;
1060
1062 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1063 << T->getTypeClassName();
1064 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1065}
1066
1067ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1068 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1069 if (!UnderlyingTypeOrErr)
1070 return UnderlyingTypeOrErr.takeError();
1071
1072 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1073}
1074
1075ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1076 switch (T->getKind()) {
1077#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1078 case BuiltinType::Id: \
1079 return Importer.getToContext().SingletonId;
1080#include "clang/Basic/OpenCLImageTypes.def"
1081#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1082 case BuiltinType::Id: \
1083 return Importer.getToContext().Id##Ty;
1084#include "clang/Basic/OpenCLExtensionTypes.def"
1085#define SVE_TYPE(Name, Id, SingletonId) \
1086 case BuiltinType::Id: \
1087 return Importer.getToContext().SingletonId;
1088#include "clang/Basic/AArch64SVEACLETypes.def"
1089#define PPC_VECTOR_TYPE(Name, Id, Size) \
1090 case BuiltinType::Id: \
1091 return Importer.getToContext().Id##Ty;
1092#include "clang/Basic/PPCTypes.def"
1093#define RVV_TYPE(Name, Id, SingletonId) \
1094 case BuiltinType::Id: \
1095 return Importer.getToContext().SingletonId;
1096#include "clang/Basic/RISCVVTypes.def"
1097#define WASM_TYPE(Name, Id, SingletonId) \
1098 case BuiltinType::Id: \
1099 return Importer.getToContext().SingletonId;
1100#include "clang/Basic/WebAssemblyReferenceTypes.def"
1101#define SHARED_SINGLETON_TYPE(Expansion)
1102#define BUILTIN_TYPE(Id, SingletonId) \
1103 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1104#include "clang/AST/BuiltinTypes.def"
1105
1106 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1107 // context supports C++.
1108
1109 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1110 // context supports ObjC.
1111
1112 case BuiltinType::Char_U:
1113 // The context we're importing from has an unsigned 'char'. If we're
1114 // importing into a context with a signed 'char', translate to
1115 // 'unsigned char' instead.
1116 if (Importer.getToContext().getLangOpts().CharIsSigned)
1117 return Importer.getToContext().UnsignedCharTy;
1118
1119 return Importer.getToContext().CharTy;
1120
1121 case BuiltinType::Char_S:
1122 // The context we're importing from has an unsigned 'char'. If we're
1123 // importing into a context with a signed 'char', translate to
1124 // 'unsigned char' instead.
1125 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1126 return Importer.getToContext().SignedCharTy;
1127
1128 return Importer.getToContext().CharTy;
1129
1130 case BuiltinType::WChar_S:
1131 case BuiltinType::WChar_U:
1132 // FIXME: If not in C++, shall we translate to the C equivalent of
1133 // wchar_t?
1134 return Importer.getToContext().WCharTy;
1135 }
1136
1137 llvm_unreachable("Invalid BuiltinType Kind!");
1138}
1139
1140ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1141 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1142 if (!ToOriginalTypeOrErr)
1143 return ToOriginalTypeOrErr.takeError();
1144
1145 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1146}
1147
1148ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1149 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1150 if (!ToElementTypeOrErr)
1151 return ToElementTypeOrErr.takeError();
1152
1153 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1154}
1155
1156ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1157 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1158 if (!ToPointeeTypeOrErr)
1159 return ToPointeeTypeOrErr.takeError();
1160
1161 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1162}
1163
1164ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1165 // FIXME: Check for blocks support in "to" context.
1166 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1167 if (!ToPointeeTypeOrErr)
1168 return ToPointeeTypeOrErr.takeError();
1169
1170 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1171}
1172
1174ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1175 // FIXME: Check for C++ support in "to" context.
1176 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1177 if (!ToPointeeTypeOrErr)
1178 return ToPointeeTypeOrErr.takeError();
1179
1180 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1181}
1182
1184ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1185 // FIXME: Check for C++0x support in "to" context.
1186 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1187 if (!ToPointeeTypeOrErr)
1188 return ToPointeeTypeOrErr.takeError();
1189
1190 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1191}
1192
1194ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1195 // FIXME: Check for C++ support in "to" context.
1196 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1197 if (!ToPointeeTypeOrErr)
1198 return ToPointeeTypeOrErr.takeError();
1199
1200 ExpectedTypePtr ClassTypeOrErr = import(T->getClass());
1201 if (!ClassTypeOrErr)
1202 return ClassTypeOrErr.takeError();
1203
1204 return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr,
1205 *ClassTypeOrErr);
1206}
1207
1209ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1210 Error Err = Error::success();
1211 auto ToElementType = importChecked(Err, T->getElementType());
1212 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1213 if (Err)
1214 return std::move(Err);
1215
1216 return Importer.getToContext().getConstantArrayType(
1217 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1218 T->getIndexTypeCVRQualifiers());
1219}
1220
1222ASTNodeImporter::VisitArrayParameterType(const ArrayParameterType *T) {
1223 ExpectedType ToArrayTypeOrErr = VisitConstantArrayType(T);
1224 if (!ToArrayTypeOrErr)
1225 return ToArrayTypeOrErr.takeError();
1226
1227 return Importer.getToContext().getArrayParameterType(*ToArrayTypeOrErr);
1228}
1229
1231ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1232 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1233 if (!ToElementTypeOrErr)
1234 return ToElementTypeOrErr.takeError();
1235
1236 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1237 T->getSizeModifier(),
1238 T->getIndexTypeCVRQualifiers());
1239}
1240
1242ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1243 Error Err = Error::success();
1244 QualType ToElementType = importChecked(Err, T->getElementType());
1245 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1246 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1247 if (Err)
1248 return std::move(Err);
1249 return Importer.getToContext().getVariableArrayType(
1250 ToElementType, ToSizeExpr, T->getSizeModifier(),
1251 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1252}
1253
1254ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1255 const DependentSizedArrayType *T) {
1256 Error Err = Error::success();
1257 QualType ToElementType = importChecked(Err, T->getElementType());
1258 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1259 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1260 if (Err)
1261 return std::move(Err);
1262 // SizeExpr may be null if size is not specified directly.
1263 // For example, 'int a[]'.
1264
1265 return Importer.getToContext().getDependentSizedArrayType(
1266 ToElementType, ToSizeExpr, T->getSizeModifier(),
1267 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1268}
1269
1270ExpectedType ASTNodeImporter::VisitDependentSizedExtVectorType(
1272 Error Err = Error::success();
1273 QualType ToElementType = importChecked(Err, T->getElementType());
1274 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1275 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1276 if (Err)
1277 return std::move(Err);
1279 ToElementType, ToSizeExpr, ToAttrLoc);
1280}
1281
1282ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1283 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1284 if (!ToElementTypeOrErr)
1285 return ToElementTypeOrErr.takeError();
1286
1287 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1288 T->getNumElements(),
1289 T->getVectorKind());
1290}
1291
1292ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1293 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1294 if (!ToElementTypeOrErr)
1295 return ToElementTypeOrErr.takeError();
1296
1297 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1298 T->getNumElements());
1299}
1300
1302ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1303 // FIXME: What happens if we're importing a function without a prototype
1304 // into C++? Should we make it variadic?
1305 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1306 if (!ToReturnTypeOrErr)
1307 return ToReturnTypeOrErr.takeError();
1308
1309 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1310 T->getExtInfo());
1311}
1312
1314ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1315 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1316 if (!ToReturnTypeOrErr)
1317 return ToReturnTypeOrErr.takeError();
1318
1319 // Import argument types
1320 SmallVector<QualType, 4> ArgTypes;
1321 for (const auto &A : T->param_types()) {
1322 ExpectedType TyOrErr = import(A);
1323 if (!TyOrErr)
1324 return TyOrErr.takeError();
1325 ArgTypes.push_back(*TyOrErr);
1326 }
1327
1328 // Import exception types
1329 SmallVector<QualType, 4> ExceptionTypes;
1330 for (const auto &E : T->exceptions()) {
1331 ExpectedType TyOrErr = import(E);
1332 if (!TyOrErr)
1333 return TyOrErr.takeError();
1334 ExceptionTypes.push_back(*TyOrErr);
1335 }
1336
1338 Error Err = Error::success();
1340 ToEPI.ExtInfo = FromEPI.ExtInfo;
1341 ToEPI.Variadic = FromEPI.Variadic;
1342 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1343 ToEPI.TypeQuals = FromEPI.TypeQuals;
1344 ToEPI.RefQualifier = FromEPI.RefQualifier;
1345 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1352 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1353
1354 if (Err)
1355 return std::move(Err);
1356
1357 return Importer.getToContext().getFunctionType(
1358 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1359}
1360
1361ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1362 const UnresolvedUsingType *T) {
1363 Error Err = Error::success();
1364 auto ToD = importChecked(Err, T->getDecl());
1365 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1366 if (Err)
1367 return std::move(Err);
1368
1369 return Importer.getToContext().getTypeDeclType(
1370 ToD, cast_or_null<TypeDecl>(ToPrevD));
1371}
1372
1373ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1374 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1375 if (!ToInnerTypeOrErr)
1376 return ToInnerTypeOrErr.takeError();
1377
1378 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1379}
1380
1382ASTNodeImporter::VisitPackIndexingType(clang::PackIndexingType const *T) {
1383
1384 ExpectedType Pattern = import(T->getPattern());
1385 if (!Pattern)
1386 return Pattern.takeError();
1387 ExpectedExpr Index = import(T->getIndexExpr());
1388 if (!Index)
1389 return Index.takeError();
1390 return Importer.getToContext().getPackIndexingType(*Pattern, *Index);
1391}
1392
1393ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1394 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1395 if (!ToDeclOrErr)
1396 return ToDeclOrErr.takeError();
1397
1398 TypedefNameDecl *ToDecl = *ToDeclOrErr;
1399 if (ToDecl->getTypeForDecl())
1400 return QualType(ToDecl->getTypeForDecl(), 0);
1401
1402 ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
1403 if (!ToUnderlyingTypeOrErr)
1404 return ToUnderlyingTypeOrErr.takeError();
1405
1406 return Importer.getToContext().getTypedefType(ToDecl, *ToUnderlyingTypeOrErr);
1407}
1408
1409ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1410 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1411 if (!ToExprOrErr)
1412 return ToExprOrErr.takeError();
1413 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr, T->getKind());
1414}
1415
1416ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1417 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnmodifiedType());
1418 if (!ToUnderlyingTypeOrErr)
1419 return ToUnderlyingTypeOrErr.takeError();
1420 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr,
1421 T->getKind());
1422}
1423
1424ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
1425 Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl());
1426 if (!FoundOrErr)
1427 return FoundOrErr.takeError();
1428 Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType());
1429 if (!UnderlyingOrErr)
1430 return UnderlyingOrErr.takeError();
1431
1432 return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr);
1433}
1434
1435ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1436 // FIXME: Make sure that the "to" context supports C++0x!
1437 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1438 if (!ToExprOrErr)
1439 return ToExprOrErr.takeError();
1440
1441 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1442 if (!ToUnderlyingTypeOrErr)
1443 return ToUnderlyingTypeOrErr.takeError();
1444
1445 return Importer.getToContext().getDecltypeType(
1446 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1447}
1448
1450ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1451 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1452 if (!ToBaseTypeOrErr)
1453 return ToBaseTypeOrErr.takeError();
1454
1455 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1456 if (!ToUnderlyingTypeOrErr)
1457 return ToUnderlyingTypeOrErr.takeError();
1458
1459 return Importer.getToContext().getUnaryTransformType(
1460 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1461}
1462
1463ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1464 // FIXME: Make sure that the "to" context supports C++11!
1465 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1466 if (!ToDeducedTypeOrErr)
1467 return ToDeducedTypeOrErr.takeError();
1468
1469 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1470 if (!ToTypeConstraintConcept)
1471 return ToTypeConstraintConcept.takeError();
1472
1473 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1474 if (Error Err = ImportTemplateArguments(T->getTypeConstraintArguments(),
1475 ToTemplateArgs))
1476 return std::move(Err);
1477
1478 return Importer.getToContext().getAutoType(
1479 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1480 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1481 ToTemplateArgs);
1482}
1483
1484ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1486 // FIXME: Make sure that the "to" context supports C++17!
1487 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1488 if (!ToTemplateNameOrErr)
1489 return ToTemplateNameOrErr.takeError();
1490 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1491 if (!ToDeducedTypeOrErr)
1492 return ToDeducedTypeOrErr.takeError();
1493
1495 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1496}
1497
1498ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1499 const InjectedClassNameType *T) {
1500 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1501 if (!ToDeclOrErr)
1502 return ToDeclOrErr.takeError();
1503
1504 // The InjectedClassNameType is created in VisitRecordDecl when the
1505 // T->getDecl() is imported. Here we can return the existing type.
1506 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl();
1507 assert(Ty && isa<InjectedClassNameType>(Ty));
1508 return QualType(Ty, 0);
1509}
1510
1511ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1512 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1513 if (!ToDeclOrErr)
1514 return ToDeclOrErr.takeError();
1515
1516 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1517}
1518
1519ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1520 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1521 if (!ToDeclOrErr)
1522 return ToDeclOrErr.takeError();
1523
1524 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1525}
1526
1527ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1528 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1529 if (!ToModifiedTypeOrErr)
1530 return ToModifiedTypeOrErr.takeError();
1531 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1532 if (!ToEquivalentTypeOrErr)
1533 return ToEquivalentTypeOrErr.takeError();
1534
1535 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1536 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1537}
1538
1540ASTNodeImporter::VisitCountAttributedType(const CountAttributedType *T) {
1541 ExpectedType ToWrappedTypeOrErr = import(T->desugar());
1542 if (!ToWrappedTypeOrErr)
1543 return ToWrappedTypeOrErr.takeError();
1544
1545 Error Err = Error::success();
1546 Expr *CountExpr = importChecked(Err, T->getCountExpr());
1547
1549 for (auto TI : T->dependent_decls()) {
1550 Expected<ValueDecl *> ToDeclOrErr = import(TI.getDecl());
1551 if (!ToDeclOrErr)
1552 return ToDeclOrErr.takeError();
1553 CoupledDecls.emplace_back(*ToDeclOrErr, TI.isDeref());
1554 }
1555
1556 return Importer.getToContext().getCountAttributedType(
1557 *ToWrappedTypeOrErr, CountExpr, T->isCountInBytes(), T->isOrNull(),
1558 ArrayRef(CoupledDecls.data(), CoupledDecls.size()));
1559}
1560
1561ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1562 const TemplateTypeParmType *T) {
1563 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1564 if (!ToDeclOrErr)
1565 return ToDeclOrErr.takeError();
1566
1567 return Importer.getToContext().getTemplateTypeParmType(
1568 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1569}
1570
1571ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1573 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1574 if (!ReplacedOrErr)
1575 return ReplacedOrErr.takeError();
1576
1577 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1578 if (!ToReplacementTypeOrErr)
1579 return ToReplacementTypeOrErr.takeError();
1580
1582 *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(),
1583 T->getPackIndex());
1584}
1585
1586ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
1588 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1589 if (!ReplacedOrErr)
1590 return ReplacedOrErr.takeError();
1591
1592 Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
1593 if (!ToArgumentPack)
1594 return ToArgumentPack.takeError();
1595
1597 *ReplacedOrErr, T->getIndex(), T->getFinal(), *ToArgumentPack);
1598}
1599
1600ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1602 auto ToTemplateOrErr = import(T->getTemplateName());
1603 if (!ToTemplateOrErr)
1604 return ToTemplateOrErr.takeError();
1605
1606 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1607 if (Error Err =
1608 ImportTemplateArguments(T->template_arguments(), ToTemplateArgs))
1609 return std::move(Err);
1610
1611 QualType ToCanonType;
1612 if (!T->isCanonicalUnqualified()) {
1613 QualType FromCanonType
1614 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1615 if (ExpectedType TyOrErr = import(FromCanonType))
1616 ToCanonType = *TyOrErr;
1617 else
1618 return TyOrErr.takeError();
1619 }
1620 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1621 ToTemplateArgs,
1622 ToCanonType);
1623}
1624
1625ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1626 // Note: the qualifier in an ElaboratedType is optional.
1627 auto ToQualifierOrErr = import(T->getQualifier());
1628 if (!ToQualifierOrErr)
1629 return ToQualifierOrErr.takeError();
1630
1631 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1632 if (!ToNamedTypeOrErr)
1633 return ToNamedTypeOrErr.takeError();
1634
1635 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1636 if (!ToOwnedTagDeclOrErr)
1637 return ToOwnedTagDeclOrErr.takeError();
1638
1639 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1640 *ToQualifierOrErr,
1641 *ToNamedTypeOrErr,
1642 *ToOwnedTagDeclOrErr);
1643}
1644
1646ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1647 ExpectedType ToPatternOrErr = import(T->getPattern());
1648 if (!ToPatternOrErr)
1649 return ToPatternOrErr.takeError();
1650
1651 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1652 T->getNumExpansions(),
1653 /*ExpactPack=*/false);
1654}
1655
1656ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1658 auto ToQualifierOrErr = import(T->getQualifier());
1659 if (!ToQualifierOrErr)
1660 return ToQualifierOrErr.takeError();
1661
1662 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1663
1665 ToPack.reserve(T->template_arguments().size());
1666 if (Error Err = ImportTemplateArguments(T->template_arguments(), ToPack))
1667 return std::move(Err);
1668
1670 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1671}
1672
1674ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1675 auto ToQualifierOrErr = import(T->getQualifier());
1676 if (!ToQualifierOrErr)
1677 return ToQualifierOrErr.takeError();
1678
1679 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1680
1681 QualType Canon;
1682 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1683 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1684 Canon = (*TyOrErr).getCanonicalType();
1685 else
1686 return TyOrErr.takeError();
1687 }
1688
1689 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1690 *ToQualifierOrErr,
1691 Name, Canon);
1692}
1693
1695ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1696 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1697 if (!ToDeclOrErr)
1698 return ToDeclOrErr.takeError();
1699
1700 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1701}
1702
1703ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1704 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1705 if (!ToBaseTypeOrErr)
1706 return ToBaseTypeOrErr.takeError();
1707
1708 SmallVector<QualType, 4> TypeArgs;
1709 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1710 if (ExpectedType TyOrErr = import(TypeArg))
1711 TypeArgs.push_back(*TyOrErr);
1712 else
1713 return TyOrErr.takeError();
1714 }
1715
1717 for (auto *P : T->quals()) {
1718 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1719 Protocols.push_back(*ProtocolOrErr);
1720 else
1721 return ProtocolOrErr.takeError();
1722
1723 }
1724
1725 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1726 Protocols,
1727 T->isKindOfTypeAsWritten());
1728}
1729
1731ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1732 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1733 if (!ToPointeeTypeOrErr)
1734 return ToPointeeTypeOrErr.takeError();
1735
1736 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1737}
1738
1740ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
1741 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1742 if (!ToUnderlyingTypeOrErr)
1743 return ToUnderlyingTypeOrErr.takeError();
1744
1745 IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
1746 return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
1747 ToIdentifier);
1748}
1749
1750ExpectedType clang::ASTNodeImporter::VisitAdjustedType(const AdjustedType *T) {
1751 Error Err = Error::success();
1752 QualType ToOriginalType = importChecked(Err, T->getOriginalType());
1753 QualType ToAdjustedType = importChecked(Err, T->getAdjustedType());
1754 if (Err)
1755 return std::move(Err);
1756
1757 return Importer.getToContext().getAdjustedType(ToOriginalType,
1758 ToAdjustedType);
1759}
1760
1761ExpectedType clang::ASTNodeImporter::VisitBitIntType(const BitIntType *T) {
1762 return Importer.getToContext().getBitIntType(T->isUnsigned(),
1763 T->getNumBits());
1764}
1765
1766ExpectedType clang::ASTNodeImporter::VisitBTFTagAttributedType(
1768 Error Err = Error::success();
1769 const BTFTypeTagAttr *ToBTFAttr = importChecked(Err, T->getAttr());
1770 QualType ToWrappedType = importChecked(Err, T->getWrappedType());
1771 if (Err)
1772 return std::move(Err);
1773
1774 return Importer.getToContext().getBTFTagAttributedType(ToBTFAttr,
1775 ToWrappedType);
1776}
1777
1778ExpectedType clang::ASTNodeImporter::VisitConstantMatrixType(
1780 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1781 if (!ToElementTypeOrErr)
1782 return ToElementTypeOrErr.takeError();
1783
1784 return Importer.getToContext().getConstantMatrixType(
1785 *ToElementTypeOrErr, T->getNumRows(), T->getNumColumns());
1786}
1787
1788ExpectedType clang::ASTNodeImporter::VisitDependentAddressSpaceType(
1790 Error Err = Error::success();
1791 QualType ToPointeeType = importChecked(Err, T->getPointeeType());
1792 Expr *ToAddrSpaceExpr = importChecked(Err, T->getAddrSpaceExpr());
1793 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1794 if (Err)
1795 return std::move(Err);
1796
1797 return Importer.getToContext().getDependentAddressSpaceType(
1798 ToPointeeType, ToAddrSpaceExpr, ToAttrLoc);
1799}
1800
1801ExpectedType clang::ASTNodeImporter::VisitDependentBitIntType(
1803 ExpectedExpr ToNumBitsExprOrErr = import(T->getNumBitsExpr());
1804 if (!ToNumBitsExprOrErr)
1805 return ToNumBitsExprOrErr.takeError();
1806 return Importer.getToContext().getDependentBitIntType(T->isUnsigned(),
1807 *ToNumBitsExprOrErr);
1808}
1809
1810ExpectedType clang::ASTNodeImporter::VisitDependentSizedMatrixType(
1812 Error Err = Error::success();
1813 QualType ToElementType = importChecked(Err, T->getElementType());
1814 Expr *ToRowExpr = importChecked(Err, T->getRowExpr());
1815 Expr *ToColumnExpr = importChecked(Err, T->getColumnExpr());
1816 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1817 if (Err)
1818 return std::move(Err);
1819
1820 return Importer.getToContext().getDependentSizedMatrixType(
1821 ToElementType, ToRowExpr, ToColumnExpr, ToAttrLoc);
1822}
1823
1824ExpectedType clang::ASTNodeImporter::VisitDependentVectorType(
1826 Error Err = Error::success();
1827 QualType ToElementType = importChecked(Err, T->getElementType());
1828 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1829 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1830 if (Err)
1831 return std::move(Err);
1832
1833 return Importer.getToContext().getDependentVectorType(
1834 ToElementType, ToSizeExpr, ToAttrLoc, T->getVectorKind());
1835}
1836
1837ExpectedType clang::ASTNodeImporter::VisitObjCTypeParamType(
1838 const clang::ObjCTypeParamType *T) {
1839 Expected<ObjCTypeParamDecl *> ToDeclOrErr = import(T->getDecl());
1840 if (!ToDeclOrErr)
1841 return ToDeclOrErr.takeError();
1842
1844 for (ObjCProtocolDecl *FromProtocol : T->getProtocols()) {
1845 Expected<ObjCProtocolDecl *> ToProtocolOrErr = import(FromProtocol);
1846 if (!ToProtocolOrErr)
1847 return ToProtocolOrErr.takeError();
1848 ToProtocols.push_back(*ToProtocolOrErr);
1849 }
1850
1851 return Importer.getToContext().getObjCTypeParamType(*ToDeclOrErr,
1852 ToProtocols);
1853}
1854
1855ExpectedType clang::ASTNodeImporter::VisitPipeType(const clang::PipeType *T) {
1856 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1857 if (!ToElementTypeOrErr)
1858 return ToElementTypeOrErr.takeError();
1859
1860 ASTContext &ToCtx = Importer.getToContext();
1861 if (T->isReadOnly())
1862 return ToCtx.getReadPipeType(*ToElementTypeOrErr);
1863 else
1864 return ToCtx.getWritePipeType(*ToElementTypeOrErr);
1865}
1866
1867//----------------------------------------------------------------------------
1868// Import Declarations
1869//----------------------------------------------------------------------------
1871 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1872 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1873 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1874 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1875 // FIXME: We could support these constructs by importing a different type of
1876 // this parameter and by importing the original type of the parameter only
1877 // after the FunctionDecl is created. See
1878 // VisitFunctionDecl::UsedDifferentProtoType.
1879 DeclContext *OrigDC = D->getDeclContext();
1880 FunctionDecl *FunDecl;
1881 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1882 FunDecl->hasBody()) {
1883 auto getLeafPointeeType = [](const Type *T) {
1884 while (T->isPointerType() || T->isArrayType()) {
1886 }
1887 return T;
1888 };
1889 for (const ParmVarDecl *P : FunDecl->parameters()) {
1890 const Type *LeafT =
1891 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1892 auto *RT = dyn_cast<RecordType>(LeafT);
1893 if (RT && RT->getDecl() == D) {
1894 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1895 << D->getDeclKindName();
1896 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1897 }
1898 }
1899 }
1900
1901 // Import the context of this declaration.
1902 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1903 return Err;
1904
1905 // Import the name of this declaration.
1906 if (Error Err = importInto(Name, D->getDeclName()))
1907 return Err;
1908
1909 // Import the location of this declaration.
1910 if (Error Err = importInto(Loc, D->getLocation()))
1911 return Err;
1912
1913 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1914 if (ToD)
1915 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1916 return Err;
1917
1918 return Error::success();
1919}
1920
1922 NamedDecl *&ToD, SourceLocation &Loc) {
1923
1924 // Import the name of this declaration.
1925 if (Error Err = importInto(Name, D->getDeclName()))
1926 return Err;
1927
1928 // Import the location of this declaration.
1929 if (Error Err = importInto(Loc, D->getLocation()))
1930 return Err;
1931
1932 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1933 if (ToD)
1934 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1935 return Err;
1936
1937 return Error::success();
1938}
1939
1941 if (!FromD)
1942 return Error::success();
1943
1944 if (!ToD)
1945 if (Error Err = importInto(ToD, FromD))
1946 return Err;
1947
1948 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1949 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1950 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1951 !ToRecord->getDefinition()) {
1952 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1953 return Err;
1954 }
1955 }
1956 return Error::success();
1957 }
1958
1959 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1960 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1961 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1962 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1963 return Err;
1964 }
1965 }
1966 return Error::success();
1967 }
1968
1969 return Error::success();
1970}
1971
1972Error
1974 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1975 // NOTE: To.Name and To.Loc are already imported.
1976 // We only have to import To.LocInfo.
1977 switch (To.getName().getNameKind()) {
1984 return Error::success();
1985
1987 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1988 To.setCXXOperatorNameRange(*ToRangeOrErr);
1989 else
1990 return ToRangeOrErr.takeError();
1991 return Error::success();
1992 }
1994 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1995 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1996 else
1997 return LocOrErr.takeError();
1998 return Error::success();
1999 }
2003 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
2004 To.setNamedTypeInfo(*ToTInfoOrErr);
2005 else
2006 return ToTInfoOrErr.takeError();
2007 return Error::success();
2008 }
2009 }
2010 llvm_unreachable("Unknown name kind.");
2011}
2012
2013Error
2015 if (Importer.isMinimalImport() && !ForceImport) {
2016 auto ToDCOrErr = Importer.ImportContext(FromDC);
2017 return ToDCOrErr.takeError();
2018 }
2019
2020 // We use strict error handling in case of records and enums, but not
2021 // with e.g. namespaces.
2022 //
2023 // FIXME Clients of the ASTImporter should be able to choose an
2024 // appropriate error handling strategy for their needs. For instance,
2025 // they may not want to mark an entire namespace as erroneous merely
2026 // because there is an ODR error with two typedefs. As another example,
2027 // the client may allow EnumConstantDecls with same names but with
2028 // different values in two distinct translation units.
2029 ChildErrorHandlingStrategy HandleChildErrors(FromDC);
2030
2031 auto MightNeedReordering = [](const Decl *D) {
2032 return isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D);
2033 };
2034
2035 // Import everything that might need reordering first.
2036 Error ChildErrors = Error::success();
2037 for (auto *From : FromDC->decls()) {
2038 if (!MightNeedReordering(From))
2039 continue;
2040
2041 ExpectedDecl ImportedOrErr = import(From);
2042
2043 // If we are in the process of ImportDefinition(...) for a RecordDecl we
2044 // want to make sure that we are also completing each FieldDecl. There
2045 // are currently cases where this does not happen and this is correctness
2046 // fix since operations such as code generation will expect this to be so.
2047 if (!ImportedOrErr) {
2048 HandleChildErrors.handleChildImportResult(ChildErrors,
2049 ImportedOrErr.takeError());
2050 continue;
2051 }
2052 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
2053 Decl *ImportedDecl = *ImportedOrErr;
2054 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
2055 if (FieldFrom && FieldTo) {
2056 Error Err = ImportFieldDeclDefinition(FieldFrom, FieldTo);
2057 HandleChildErrors.handleChildImportResult(ChildErrors, std::move(Err));
2058 }
2059 }
2060
2061 // We reorder declarations in RecordDecls because they may have another order
2062 // in the "to" context than they have in the "from" context. This may happen
2063 // e.g when we import a class like this:
2064 // struct declToImport {
2065 // int a = c + b;
2066 // int b = 1;
2067 // int c = 2;
2068 // };
2069 // During the import of `a` we import first the dependencies in sequence,
2070 // thus the order would be `c`, `b`, `a`. We will get the normal order by
2071 // first removing the already imported members and then adding them in the
2072 // order as they appear in the "from" context.
2073 //
2074 // Keeping field order is vital because it determines structure layout.
2075 //
2076 // Here and below, we cannot call field_begin() method and its callers on
2077 // ToDC if it has an external storage. Calling field_begin() will
2078 // automatically load all the fields by calling
2079 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
2080 // call ASTImporter::Import(). This is because the ExternalASTSource
2081 // interface in LLDB is implemented by the means of the ASTImporter. However,
2082 // calling an import at this point would result in an uncontrolled import, we
2083 // must avoid that.
2084
2085 auto ToDCOrErr = Importer.ImportContext(FromDC);
2086 if (!ToDCOrErr) {
2087 consumeError(std::move(ChildErrors));
2088 return ToDCOrErr.takeError();
2089 }
2090
2091 if (const auto *FromRD = dyn_cast<RecordDecl>(FromDC)) {
2092 DeclContext *ToDC = *ToDCOrErr;
2093 // Remove all declarations, which may be in wrong order in the
2094 // lexical DeclContext and then add them in the proper order.
2095 for (auto *D : FromRD->decls()) {
2096 if (!MightNeedReordering(D))
2097 continue;
2098
2099 assert(D && "DC contains a null decl");
2100 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(D)) {
2101 // Remove only the decls which we successfully imported.
2102 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
2103 // Remove the decl from its wrong place in the linked list.
2104 ToDC->removeDecl(ToD);
2105 // Add the decl to the end of the linked list.
2106 // This time it will be at the proper place because the enclosing for
2107 // loop iterates in the original (good) order of the decls.
2108 ToDC->addDeclInternal(ToD);
2109 }
2110 }
2111 }
2112
2113 // Import everything else.
2114 for (auto *From : FromDC->decls()) {
2115 if (MightNeedReordering(From))
2116 continue;
2117
2118 ExpectedDecl ImportedOrErr = import(From);
2119 if (!ImportedOrErr)
2120 HandleChildErrors.handleChildImportResult(ChildErrors,
2121 ImportedOrErr.takeError());
2122 }
2123
2124 return ChildErrors;
2125}
2126
2128 const FieldDecl *To) {
2129 RecordDecl *FromRecordDecl = nullptr;
2130 RecordDecl *ToRecordDecl = nullptr;
2131 // If we have a field that is an ArrayType we need to check if the array
2132 // element is a RecordDecl and if so we need to import the definition.
2133 QualType FromType = From->getType();
2134 QualType ToType = To->getType();
2135 if (FromType->isArrayType()) {
2136 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
2137 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2138 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2139 }
2140
2141 if (!FromRecordDecl || !ToRecordDecl) {
2142 const RecordType *RecordFrom = FromType->getAs<RecordType>();
2143 const RecordType *RecordTo = ToType->getAs<RecordType>();
2144
2145 if (RecordFrom && RecordTo) {
2146 FromRecordDecl = RecordFrom->getDecl();
2147 ToRecordDecl = RecordTo->getDecl();
2148 }
2149 }
2150
2151 if (FromRecordDecl && ToRecordDecl) {
2152 if (FromRecordDecl->isCompleteDefinition() &&
2153 !ToRecordDecl->isCompleteDefinition())
2154 return ImportDefinition(FromRecordDecl, ToRecordDecl);
2155 }
2156
2157 return Error::success();
2158}
2159
2161 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
2162 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
2163 if (!ToDCOrErr)
2164 return ToDCOrErr.takeError();
2165 ToDC = *ToDCOrErr;
2166
2167 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
2168 auto ToLexicalDCOrErr = Importer.ImportContext(
2169 FromD->getLexicalDeclContext());
2170 if (!ToLexicalDCOrErr)
2171 return ToLexicalDCOrErr.takeError();
2172 ToLexicalDC = *ToLexicalDCOrErr;
2173 } else
2174 ToLexicalDC = ToDC;
2175
2176 return Error::success();
2177}
2178
2180 const CXXRecordDecl *From, CXXRecordDecl *To) {
2181 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
2182 "Import implicit methods to or from non-definition");
2183
2184 for (CXXMethodDecl *FromM : From->methods())
2185 if (FromM->isImplicit()) {
2186 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
2187 if (!ToMOrErr)
2188 return ToMOrErr.takeError();
2189 }
2190
2191 return Error::success();
2192}
2193
2195 ASTImporter &Importer) {
2196 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
2197 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
2198 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
2199 else
2200 return ToTypedefOrErr.takeError();
2201 }
2202 return Error::success();
2203}
2204
2206 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
2207 auto DefinitionCompleter = [To]() {
2208 // There are cases in LLDB when we first import a class without its
2209 // members. The class will have DefinitionData, but no members. Then,
2210 // importDefinition is called from LLDB, which tries to get the members, so
2211 // when we get here, the class already has the DefinitionData set, so we
2212 // must unset the CompleteDefinition here to be able to complete again the
2213 // definition.
2214 To->setCompleteDefinition(false);
2215 To->completeDefinition();
2216 };
2217
2218 if (To->getDefinition() || To->isBeingDefined()) {
2219 if (Kind == IDK_Everything ||
2220 // In case of lambdas, the class already has a definition ptr set, but
2221 // the contained decls are not imported yet. Also, isBeingDefined was
2222 // set in CXXRecordDecl::CreateLambda. We must import the contained
2223 // decls here and finish the definition.
2224 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
2225 if (To->isLambda()) {
2226 auto *FromCXXRD = cast<CXXRecordDecl>(From);
2228 ToCaptures.reserve(FromCXXRD->capture_size());
2229 for (const auto &FromCapture : FromCXXRD->captures()) {
2230 if (auto ToCaptureOrErr = import(FromCapture))
2231 ToCaptures.push_back(*ToCaptureOrErr);
2232 else
2233 return ToCaptureOrErr.takeError();
2234 }
2235 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
2236 ToCaptures);
2237 }
2238
2239 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2240 // Finish the definition of the lambda, set isBeingDefined to false.
2241 if (To->isLambda())
2242 DefinitionCompleter();
2243 return Result;
2244 }
2245
2246 return Error::success();
2247 }
2248
2249 To->startDefinition();
2250 // Set the definition to complete even if it is really not complete during
2251 // import. Some AST constructs (expressions) require the record layout
2252 // to be calculated (see 'clang::computeDependence') at the time they are
2253 // constructed. Import of such AST node is possible during import of the
2254 // same record, there is no way to have a completely defined record (all
2255 // fields imported) at that time without multiple AST import passes.
2256 if (!Importer.isMinimalImport())
2257 To->setCompleteDefinition(true);
2258 // Complete the definition even if error is returned.
2259 // The RecordDecl may be already part of the AST so it is better to
2260 // have it in complete state even if something is wrong with it.
2261 auto DefinitionCompleterScopeExit =
2262 llvm::make_scope_exit(DefinitionCompleter);
2263
2264 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2265 return Err;
2266
2267 // Add base classes.
2268 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2269 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2270 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2271
2272 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2273 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2274
2275 #define FIELD(Name, Width, Merge) \
2276 ToData.Name = FromData.Name;
2277 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2278
2279 // Copy over the data stored in RecordDeclBits
2280 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2281
2283 for (const auto &Base1 : FromCXX->bases()) {
2284 ExpectedType TyOrErr = import(Base1.getType());
2285 if (!TyOrErr)
2286 return TyOrErr.takeError();
2287
2288 SourceLocation EllipsisLoc;
2289 if (Base1.isPackExpansion()) {
2290 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2291 EllipsisLoc = *LocOrErr;
2292 else
2293 return LocOrErr.takeError();
2294 }
2295
2296 // Ensure that we have a definition for the base.
2297 if (Error Err =
2298 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2299 return Err;
2300
2301 auto RangeOrErr = import(Base1.getSourceRange());
2302 if (!RangeOrErr)
2303 return RangeOrErr.takeError();
2304
2305 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2306 if (!TSIOrErr)
2307 return TSIOrErr.takeError();
2308
2309 Bases.push_back(
2310 new (Importer.getToContext()) CXXBaseSpecifier(
2311 *RangeOrErr,
2312 Base1.isVirtual(),
2313 Base1.isBaseOfClass(),
2314 Base1.getAccessSpecifierAsWritten(),
2315 *TSIOrErr,
2316 EllipsisLoc));
2317 }
2318 if (!Bases.empty())
2319 ToCXX->setBases(Bases.data(), Bases.size());
2320 }
2321
2322 if (shouldForceImportDeclContext(Kind)) {
2323 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2324 return Err;
2325 }
2326
2327 return Error::success();
2328}
2329
2331 if (To->getAnyInitializer())
2332 return Error::success();
2333
2334 Expr *FromInit = From->getInit();
2335 if (!FromInit)
2336 return Error::success();
2337
2338 ExpectedExpr ToInitOrErr = import(FromInit);
2339 if (!ToInitOrErr)
2340 return ToInitOrErr.takeError();
2341
2342 To->setInit(*ToInitOrErr);
2343 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2344 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2345 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2346 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2347 // FIXME: Also import the initializer value.
2348 }
2349
2350 // FIXME: Other bits to merge?
2351 return Error::success();
2352}
2353
2355 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2356 if (To->getDefinition() || To->isBeingDefined()) {
2357 if (Kind == IDK_Everything)
2358 return ImportDeclContext(From, /*ForceImport=*/true);
2359 return Error::success();
2360 }
2361
2362 To->startDefinition();
2363
2364 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2365 return Err;
2366
2367 ExpectedType ToTypeOrErr =
2368 import(Importer.getFromContext().getTypeDeclType(From));
2369 if (!ToTypeOrErr)
2370 return ToTypeOrErr.takeError();
2371
2372 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2373 if (!ToPromotionTypeOrErr)
2374 return ToPromotionTypeOrErr.takeError();
2375
2377 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2378 return Err;
2379
2380 // FIXME: we might need to merge the number of positive or negative bits
2381 // if the enumerator lists don't match.
2382 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2383 From->getNumPositiveBits(),
2384 From->getNumNegativeBits());
2385 return Error::success();
2386}
2387
2391 for (const auto &Arg : FromArgs) {
2392 if (auto ToOrErr = import(Arg))
2393 ToArgs.push_back(*ToOrErr);
2394 else
2395 return ToOrErr.takeError();
2396 }
2397
2398 return Error::success();
2399}
2400
2401// FIXME: Do not forget to remove this and use only 'import'.
2404 return import(From);
2405}
2406
2407template <typename InContainerTy>
2409 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2410 for (const auto &FromLoc : Container) {
2411 if (auto ToLocOrErr = import(FromLoc))
2412 ToTAInfo.addArgument(*ToLocOrErr);
2413 else
2414 return ToLocOrErr.takeError();
2415 }
2416 return Error::success();
2417}
2418
2423}
2424
2425bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
2426 bool IgnoreTemplateParmDepth) {
2427 // Eliminate a potential failure point where we attempt to re-import
2428 // something we're trying to import while completing ToRecord.
2429 Decl *ToOrigin = Importer.GetOriginalDecl(To);
2430 if (ToOrigin) {
2431 To = ToOrigin;
2432 }
2433
2435 Importer.getFromContext(), Importer.getToContext(),
2437 /*StrictTypeSpelling=*/false, Complain, /*ErrorOnTagTypeMismatch=*/false,
2438 IgnoreTemplateParmDepth);
2439 return Ctx.IsEquivalent(From, To);
2440}
2441
2443 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2444 << D->getDeclKindName();
2445 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2446}
2447
2449 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2450 << D->getDeclKindName();
2451 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2452}
2453
2455 // Import the context of this declaration.
2456 DeclContext *DC, *LexicalDC;
2457 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2458 return std::move(Err);
2459
2460 // Import the location of this declaration.
2461 ExpectedSLoc LocOrErr = import(D->getLocation());
2462 if (!LocOrErr)
2463 return LocOrErr.takeError();
2464
2465 EmptyDecl *ToD;
2466 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2467 return ToD;
2468
2469 ToD->setLexicalDeclContext(LexicalDC);
2470 LexicalDC->addDeclInternal(ToD);
2471 return ToD;
2472}
2473
2475 TranslationUnitDecl *ToD =
2477
2478 Importer.MapImported(D, ToD);
2479
2480 return ToD;
2481}
2482
2484 DeclContext *DC, *LexicalDC;
2485 DeclarationName Name;
2486 SourceLocation Loc;
2487 NamedDecl *ToND;
2488 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2489 return std::move(Err);
2490 if (ToND)
2491 return ToND;
2492
2493 BindingDecl *ToD;
2494 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2495 Name.getAsIdentifierInfo()))
2496 return ToD;
2497
2498 Error Err = Error::success();
2499 QualType ToType = importChecked(Err, D->getType());
2500 Expr *ToBinding = importChecked(Err, D->getBinding());
2501 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2502 if (Err)
2503 return std::move(Err);
2504
2505 ToD->setBinding(ToType, ToBinding);
2506 ToD->setDecomposedDecl(ToDecomposedDecl);
2507 addDeclToContexts(D, ToD);
2508
2509 return ToD;
2510}
2511
2513 ExpectedSLoc LocOrErr = import(D->getLocation());
2514 if (!LocOrErr)
2515 return LocOrErr.takeError();
2516 auto ColonLocOrErr = import(D->getColonLoc());
2517 if (!ColonLocOrErr)
2518 return ColonLocOrErr.takeError();
2519
2520 // Import the context of this declaration.
2521 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2522 if (!DCOrErr)
2523 return DCOrErr.takeError();
2524 DeclContext *DC = *DCOrErr;
2525
2526 AccessSpecDecl *ToD;
2527 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2528 DC, *LocOrErr, *ColonLocOrErr))
2529 return ToD;
2530
2531 // Lexical DeclContext and Semantic DeclContext
2532 // is always the same for the accessSpec.
2533 ToD->setLexicalDeclContext(DC);
2534 DC->addDeclInternal(ToD);
2535
2536 return ToD;
2537}
2538
2540 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2541 if (!DCOrErr)
2542 return DCOrErr.takeError();
2543 DeclContext *DC = *DCOrErr;
2544 DeclContext *LexicalDC = DC;
2545
2546 Error Err = Error::success();
2547 auto ToLocation = importChecked(Err, D->getLocation());
2548 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2549 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2550 auto ToMessage = importChecked(Err, D->getMessage());
2551 if (Err)
2552 return std::move(Err);
2553
2554 StaticAssertDecl *ToD;
2555 if (GetImportedOrCreateDecl(
2556 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2557 ToRParenLoc, D->isFailed()))
2558 return ToD;
2559
2560 ToD->setLexicalDeclContext(LexicalDC);
2561 LexicalDC->addDeclInternal(ToD);
2562 return ToD;
2563}
2564
2566 // Import the major distinguishing characteristics of this namespace.
2567 DeclContext *DC, *LexicalDC;
2568 DeclarationName Name;
2569 SourceLocation Loc;
2570 NamedDecl *ToD;
2571 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2572 return std::move(Err);
2573 if (ToD)
2574 return ToD;
2575
2576 NamespaceDecl *MergeWithNamespace = nullptr;
2577 if (!Name) {
2578 // This is an anonymous namespace. Adopt an existing anonymous
2579 // namespace if we can.
2580 // FIXME: Not testable.
2581 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2582 MergeWithNamespace = TU->getAnonymousNamespace();
2583 else
2584 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2585 } else {
2586 SmallVector<NamedDecl *, 4> ConflictingDecls;
2587 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2588 for (auto *FoundDecl : FoundDecls) {
2590 continue;
2591
2592 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2593 MergeWithNamespace = FoundNS;
2594 ConflictingDecls.clear();
2595 break;
2596 }
2597
2598 ConflictingDecls.push_back(FoundDecl);
2599 }
2600
2601 if (!ConflictingDecls.empty()) {
2602 ExpectedName NameOrErr = Importer.HandleNameConflict(
2603 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2604 ConflictingDecls.size());
2605 if (NameOrErr)
2606 Name = NameOrErr.get();
2607 else
2608 return NameOrErr.takeError();
2609 }
2610 }
2611
2612 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2613 if (!BeginLocOrErr)
2614 return BeginLocOrErr.takeError();
2615 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2616 if (!RBraceLocOrErr)
2617 return RBraceLocOrErr.takeError();
2618
2619 // Create the "to" namespace, if needed.
2620 NamespaceDecl *ToNamespace = MergeWithNamespace;
2621 if (!ToNamespace) {
2622 if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC,
2623 D->isInline(), *BeginLocOrErr, Loc,
2624 Name.getAsIdentifierInfo(),
2625 /*PrevDecl=*/nullptr, D->isNested()))
2626 return ToNamespace;
2627 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2628 ToNamespace->setLexicalDeclContext(LexicalDC);
2629 LexicalDC->addDeclInternal(ToNamespace);
2630
2631 // If this is an anonymous namespace, register it as the anonymous
2632 // namespace within its context.
2633 if (!Name) {
2634 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2635 TU->setAnonymousNamespace(ToNamespace);
2636 else
2637 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2638 }
2639 }
2640 Importer.MapImported(D, ToNamespace);
2641
2642 if (Error Err = ImportDeclContext(D))
2643 return std::move(Err);
2644
2645 return ToNamespace;
2646}
2647
2649 // Import the major distinguishing characteristics of this namespace.
2650 DeclContext *DC, *LexicalDC;
2651 DeclarationName Name;
2652 SourceLocation Loc;
2653 NamedDecl *LookupD;
2654 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2655 return std::move(Err);
2656 if (LookupD)
2657 return LookupD;
2658
2659 // NOTE: No conflict resolution is done for namespace aliases now.
2660
2661 Error Err = Error::success();
2662 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2663 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2664 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2665 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2666 auto ToNamespace = importChecked(Err, D->getNamespace());
2667 if (Err)
2668 return std::move(Err);
2669
2670 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2671
2672 NamespaceAliasDecl *ToD;
2673 if (GetImportedOrCreateDecl(
2674 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2675 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2676 return ToD;
2677
2678 ToD->setLexicalDeclContext(LexicalDC);
2679 LexicalDC->addDeclInternal(ToD);
2680
2681 return ToD;
2682}
2683
2686 // Import the major distinguishing characteristics of this typedef.
2687 DeclarationName Name;
2688 SourceLocation Loc;
2689 NamedDecl *ToD;
2690 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2691 // is created.
2692 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2693 return std::move(Err);
2694 if (ToD)
2695 return ToD;
2696
2697 DeclContext *DC = cast_or_null<DeclContext>(
2698 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2699 DeclContext *LexicalDC =
2700 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2701 cast<Decl>(D->getLexicalDeclContext())));
2702
2703 // If this typedef is not in block scope, determine whether we've
2704 // seen a typedef with the same name (that we can merge with) or any
2705 // other entity by that name (which name lookup could conflict with).
2706 // Note: Repeated typedefs are not valid in C99:
2707 // 'typedef int T; typedef int T;' is invalid
2708 // We do not care about this now.
2709 if (DC && !DC->isFunctionOrMethod()) {
2710 SmallVector<NamedDecl *, 4> ConflictingDecls;
2711 unsigned IDNS = Decl::IDNS_Ordinary;
2712 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2713 for (auto *FoundDecl : FoundDecls) {
2714 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2715 continue;
2716 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2717 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2718 continue;
2719
2720 QualType FromUT = D->getUnderlyingType();
2721 QualType FoundUT = FoundTypedef->getUnderlyingType();
2722 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2723 // If the underlying declarations are unnamed records these can be
2724 // imported as different types. We should create a distinct typedef
2725 // node in this case.
2726 // If we found an existing underlying type with a record in a
2727 // different context (than the imported), this is already reason for
2728 // having distinct typedef nodes for these.
2729 // Again this can create situation like
2730 // 'typedef int T; typedef int T;' but this is hard to avoid without
2731 // a rename strategy at import.
2732 if (!FromUT.isNull() && !FoundUT.isNull()) {
2733 RecordDecl *FromR = FromUT->getAsRecordDecl();
2734 RecordDecl *FoundR = FoundUT->getAsRecordDecl();
2735 if (FromR && FoundR &&
2736 !hasSameVisibilityContextAndLinkage(FoundR, FromR))
2737 continue;
2738 }
2739 // If the "From" context has a complete underlying type but we
2740 // already have a complete underlying type then return with that.
2741 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2742 return Importer.MapImported(D, FoundTypedef);
2743 // FIXME Handle redecl chain. When you do that make consistent changes
2744 // in ASTImporterLookupTable too.
2745 } else {
2746 ConflictingDecls.push_back(FoundDecl);
2747 }
2748 }
2749 }
2750
2751 if (!ConflictingDecls.empty()) {
2752 ExpectedName NameOrErr = Importer.HandleNameConflict(
2753 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2754 if (NameOrErr)
2755 Name = NameOrErr.get();
2756 else
2757 return NameOrErr.takeError();
2758 }
2759 }
2760
2761 Error Err = Error::success();
2763 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2764 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2765 if (Err)
2766 return std::move(Err);
2767
2768 // Create the new typedef node.
2769 // FIXME: ToUnderlyingType is not used.
2770 (void)ToUnderlyingType;
2771 TypedefNameDecl *ToTypedef;
2772 if (IsAlias) {
2773 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2774 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2775 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2776 return ToTypedef;
2777 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2778 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2779 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2780 return ToTypedef;
2781
2782 // Import the DeclContext and set it to the Typedef.
2783 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2784 return std::move(Err);
2785 ToTypedef->setDeclContext(DC);
2786 ToTypedef->setLexicalDeclContext(LexicalDC);
2787 // Add to the lookupTable because we could not do that in MapImported.
2788 Importer.AddToLookupTable(ToTypedef);
2789
2790 ToTypedef->setAccess(D->getAccess());
2791
2792 // Templated declarations should not appear in DeclContext.
2793 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2794 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2795 LexicalDC->addDeclInternal(ToTypedef);
2796
2797 return ToTypedef;
2798}
2799
2801 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2802}
2803
2805 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2806}
2807
2810 // Import the major distinguishing characteristics of this typedef.
2811 DeclContext *DC, *LexicalDC;
2812 DeclarationName Name;
2813 SourceLocation Loc;
2814 NamedDecl *FoundD;
2815 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2816 return std::move(Err);
2817 if (FoundD)
2818 return FoundD;
2819
2820 // If this typedef is not in block scope, determine whether we've
2821 // seen a typedef with the same name (that we can merge with) or any
2822 // other entity by that name (which name lookup could conflict with).
2823 if (!DC->isFunctionOrMethod()) {
2824 SmallVector<NamedDecl *, 4> ConflictingDecls;
2825 unsigned IDNS = Decl::IDNS_Ordinary;
2826 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2827 for (auto *FoundDecl : FoundDecls) {
2828 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2829 continue;
2830 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) {
2831 if (IsStructuralMatch(D, FoundAlias))
2832 return Importer.MapImported(D, FoundAlias);
2833 ConflictingDecls.push_back(FoundDecl);
2834 }
2835 }
2836
2837 if (!ConflictingDecls.empty()) {
2838 ExpectedName NameOrErr = Importer.HandleNameConflict(
2839 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2840 if (NameOrErr)
2841 Name = NameOrErr.get();
2842 else
2843 return NameOrErr.takeError();
2844 }
2845 }
2846
2847 Error Err = Error::success();
2848 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2849 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2850 if (Err)
2851 return std::move(Err);
2852
2853 TypeAliasTemplateDecl *ToAlias;
2854 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2855 Name, ToTemplateParameters, ToTemplatedDecl))
2856 return ToAlias;
2857
2858 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2859
2860 ToAlias->setAccess(D->getAccess());
2861 ToAlias->setLexicalDeclContext(LexicalDC);
2862 LexicalDC->addDeclInternal(ToAlias);
2863 if (DC != Importer.getToContext().getTranslationUnitDecl())
2864 updateLookupTableForTemplateParameters(*ToTemplateParameters);
2865 return ToAlias;
2866}
2867
2869 // Import the major distinguishing characteristics of this label.
2870 DeclContext *DC, *LexicalDC;
2871 DeclarationName Name;
2872 SourceLocation Loc;
2873 NamedDecl *ToD;
2874 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2875 return std::move(Err);
2876 if (ToD)
2877 return ToD;
2878
2879 assert(LexicalDC->isFunctionOrMethod());
2880
2881 LabelDecl *ToLabel;
2882 if (D->isGnuLocal()) {
2883 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2884 if (!BeginLocOrErr)
2885 return BeginLocOrErr.takeError();
2886 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2887 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2888 return ToLabel;
2889
2890 } else {
2891 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2892 Name.getAsIdentifierInfo()))
2893 return ToLabel;
2894
2895 }
2896
2897 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2898 if (!ToStmtOrErr)
2899 return ToStmtOrErr.takeError();
2900
2901 ToLabel->setStmt(*ToStmtOrErr);
2902 ToLabel->setLexicalDeclContext(LexicalDC);
2903 LexicalDC->addDeclInternal(ToLabel);
2904 return ToLabel;
2905}
2906
2908 // Import the major distinguishing characteristics of this enum.
2909 DeclContext *DC, *LexicalDC;
2910 DeclarationName Name;
2911 SourceLocation Loc;
2912 NamedDecl *ToD;
2913 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2914 return std::move(Err);
2915 if (ToD)
2916 return ToD;
2917
2918 // Figure out what enum name we're looking for.
2919 unsigned IDNS = Decl::IDNS_Tag;
2920 DeclarationName SearchName = Name;
2921 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2922 if (Error Err = importInto(
2923 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2924 return std::move(Err);
2925 IDNS = Decl::IDNS_Ordinary;
2926 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2927 IDNS |= Decl::IDNS_Ordinary;
2928
2929 // We may already have an enum of the same name; try to find and match it.
2930 EnumDecl *PrevDecl = nullptr;
2931 if (!DC->isFunctionOrMethod() && SearchName) {
2932 SmallVector<NamedDecl *, 4> ConflictingDecls;
2933 auto FoundDecls =
2934 Importer.findDeclsInToCtx(DC, SearchName);
2935 for (auto *FoundDecl : FoundDecls) {
2936 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2937 continue;
2938
2939 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2940 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2941 FoundDecl = Tag->getDecl();
2942 }
2943
2944 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2945 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2946 continue;
2947 if (IsStructuralMatch(D, FoundEnum)) {
2948 EnumDecl *FoundDef = FoundEnum->getDefinition();
2949 if (D->isThisDeclarationADefinition() && FoundDef)
2950 return Importer.MapImported(D, FoundDef);
2951 PrevDecl = FoundEnum->getMostRecentDecl();
2952 break;
2953 }
2954 ConflictingDecls.push_back(FoundDecl);
2955 }
2956 }
2957
2958 if (!ConflictingDecls.empty()) {
2959 ExpectedName NameOrErr = Importer.HandleNameConflict(
2960 SearchName, DC, IDNS, ConflictingDecls.data(),
2961 ConflictingDecls.size());
2962 if (NameOrErr)
2963 Name = NameOrErr.get();
2964 else
2965 return NameOrErr.takeError();
2966 }
2967 }
2968
2969 Error Err = Error::success();
2970 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2971 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2972 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2973 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2974 if (Err)
2975 return std::move(Err);
2976
2977 // Create the enum declaration.
2978 EnumDecl *D2;
2979 if (GetImportedOrCreateDecl(
2980 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2981 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2982 D->isScopedUsingClassTag(), D->isFixed()))
2983 return D2;
2984
2985 D2->setQualifierInfo(ToQualifierLoc);
2986 D2->setIntegerType(ToIntegerType);
2987 D2->setBraceRange(ToBraceRange);
2988 D2->setAccess(D->getAccess());
2989 D2->setLexicalDeclContext(LexicalDC);
2990 addDeclToContexts(D, D2);
2991
2993 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2994 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2995 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2996 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2997 else
2998 return ToInstOrErr.takeError();
2999 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
3001 else
3002 return POIOrErr.takeError();
3003 }
3004
3005 // Import the definition
3006 if (D->isCompleteDefinition())
3007 if (Error Err = ImportDefinition(D, D2))
3008 return std::move(Err);
3009
3010 return D2;
3011}
3012
3014 bool IsFriendTemplate = false;
3015 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3016 IsFriendTemplate =
3017 DCXX->getDescribedClassTemplate() &&
3018 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
3020 }
3021
3022 // Import the major distinguishing characteristics of this record.
3023 DeclContext *DC = nullptr, *LexicalDC = nullptr;
3024 DeclarationName Name;
3025 SourceLocation Loc;
3026 NamedDecl *ToD = nullptr;
3027 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3028 return std::move(Err);
3029 if (ToD)
3030 return ToD;
3031
3032 // Figure out what structure name we're looking for.
3033 unsigned IDNS = Decl::IDNS_Tag;
3034 DeclarationName SearchName = Name;
3035 if (!SearchName && D->getTypedefNameForAnonDecl()) {
3036 if (Error Err = importInto(
3037 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
3038 return std::move(Err);
3039 IDNS = Decl::IDNS_Ordinary;
3040 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
3042
3043 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
3044 : DC->isDependentContext();
3045 bool DependentFriend = IsFriendTemplate && IsDependentContext;
3046
3047 // We may already have a record of the same name; try to find and match it.
3048 RecordDecl *PrevDecl = nullptr;
3049 if (!DependentFriend && !DC->isFunctionOrMethod() && !D->isLambda()) {
3050 SmallVector<NamedDecl *, 4> ConflictingDecls;
3051 auto FoundDecls =
3052 Importer.findDeclsInToCtx(DC, SearchName);
3053 if (!FoundDecls.empty()) {
3054 // We're going to have to compare D against potentially conflicting Decls,
3055 // so complete it.
3058 }
3059
3060 for (auto *FoundDecl : FoundDecls) {
3061 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3062 continue;
3063
3064 Decl *Found = FoundDecl;
3065 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
3066 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
3067 Found = Tag->getDecl();
3068 }
3069
3070 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
3071 // Do not emit false positive diagnostic in case of unnamed
3072 // struct/union and in case of anonymous structs. Would be false
3073 // because there may be several anonymous/unnamed structs in a class.
3074 // E.g. these are both valid:
3075 // struct A { // unnamed structs
3076 // struct { struct A *next; } entry0;
3077 // struct { struct A *next; } entry1;
3078 // };
3079 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
3080 if (!SearchName)
3081 if (!IsStructuralMatch(D, FoundRecord, false))
3082 continue;
3083
3084 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
3085 continue;
3086
3087 if (IsStructuralMatch(D, FoundRecord)) {
3088 RecordDecl *FoundDef = FoundRecord->getDefinition();
3089 if (D->isThisDeclarationADefinition() && FoundDef) {
3090 // FIXME: Structural equivalence check should check for same
3091 // user-defined methods.
3092 Importer.MapImported(D, FoundDef);
3093 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3094 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
3095 assert(FoundCXX && "Record type mismatch");
3096
3097 if (!Importer.isMinimalImport())
3098 // FoundDef may not have every implicit method that D has
3099 // because implicit methods are created only if they are used.
3100 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
3101 return std::move(Err);
3102 }
3103 }
3104 PrevDecl = FoundRecord->getMostRecentDecl();
3105 break;
3106 }
3107 ConflictingDecls.push_back(FoundDecl);
3108 } // kind is RecordDecl
3109 } // for
3110
3111 if (!ConflictingDecls.empty() && SearchName) {
3112 ExpectedName NameOrErr = Importer.HandleNameConflict(
3113 SearchName, DC, IDNS, ConflictingDecls.data(),
3114 ConflictingDecls.size());
3115 if (NameOrErr)
3116 Name = NameOrErr.get();
3117 else
3118 return NameOrErr.takeError();
3119 }
3120 }
3121
3122 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
3123 if (!BeginLocOrErr)
3124 return BeginLocOrErr.takeError();
3125
3126 // Create the record declaration.
3127 RecordDecl *D2 = nullptr;
3128 CXXRecordDecl *D2CXX = nullptr;
3129 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3130 if (DCXX->isLambda()) {
3131 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
3132 if (!TInfoOrErr)
3133 return TInfoOrErr.takeError();
3134 if (GetImportedOrCreateSpecialDecl(
3135 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
3136 DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(),
3137 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
3138 return D2CXX;
3139 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering();
3140 ExpectedDecl CDeclOrErr = import(Numbering.ContextDecl);
3141 if (!CDeclOrErr)
3142 return CDeclOrErr.takeError();
3143 Numbering.ContextDecl = *CDeclOrErr;
3144 D2CXX->setLambdaNumbering(Numbering);
3145 } else if (DCXX->isInjectedClassName()) {
3146 // We have to be careful to do a similar dance to the one in
3147 // Sema::ActOnStartCXXMemberDeclarations
3148 const bool DelayTypeCreation = true;
3149 if (GetImportedOrCreateDecl(
3150 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
3151 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
3152 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
3153 return D2CXX;
3154 Importer.getToContext().getTypeDeclType(
3155 D2CXX, dyn_cast<CXXRecordDecl>(DC));
3156 } else {
3157 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
3158 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3159 Name.getAsIdentifierInfo(),
3160 cast_or_null<CXXRecordDecl>(PrevDecl)))
3161 return D2CXX;
3162 }
3163
3164 D2 = D2CXX;
3165 D2->setAccess(D->getAccess());
3166 D2->setLexicalDeclContext(LexicalDC);
3167 addDeclToContexts(D, D2);
3168
3169 if (ClassTemplateDecl *FromDescribed =
3170 DCXX->getDescribedClassTemplate()) {
3171 ClassTemplateDecl *ToDescribed;
3172 if (Error Err = importInto(ToDescribed, FromDescribed))
3173 return std::move(Err);
3174 D2CXX->setDescribedClassTemplate(ToDescribed);
3175 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
3176 // In a record describing a template the type should be an
3177 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
3178 // previously set type to the correct value here (ToDescribed is not
3179 // available at record create).
3180 CXXRecordDecl *Injected = nullptr;
3181 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
3182 auto *Record = dyn_cast<CXXRecordDecl>(Found);
3183 if (Record && Record->isInjectedClassName()) {
3184 Injected = Record;
3185 break;
3186 }
3187 }
3188 // Create an injected type for the whole redecl chain.
3189 // The chain may contain an already existing injected type at the start,
3190 // if yes this should be reused. We must ensure that only one type
3191 // object exists for the injected type (including the injected record
3192 // declaration), ASTContext does not check it.
3193 SmallVector<Decl *, 2> Redecls =
3195 const Type *FrontTy =
3196 cast<CXXRecordDecl>(Redecls.front())->getTypeForDecl();
3197 QualType InjSpec;
3198 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>())
3199 InjSpec = InjTy->getInjectedSpecializationType();
3200 else
3201 InjSpec = ToDescribed->getInjectedClassNameSpecialization();
3202 for (auto *R : Redecls) {
3203 auto *RI = cast<CXXRecordDecl>(R);
3204 if (R != Redecls.front() ||
3205 !isa<InjectedClassNameType>(RI->getTypeForDecl()))
3206 RI->setTypeForDecl(nullptr);
3207 // This function tries to get the injected type from getTypeForDecl,
3208 // then from the previous declaration if possible. If not, it creates
3209 // a new type.
3210 Importer.getToContext().getInjectedClassNameType(RI, InjSpec);
3211 }
3212 // Set the new type for the injected decl too.
3213 if (Injected) {
3214 Injected->setTypeForDecl(nullptr);
3215 // This function will copy the injected type from D2CXX into Injected.
3216 // The injected decl does not have a previous decl to copy from.
3217 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
3218 }
3219 }
3220 } else if (MemberSpecializationInfo *MemberInfo =
3221 DCXX->getMemberSpecializationInfo()) {
3223 MemberInfo->getTemplateSpecializationKind();
3225
3226 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
3227 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
3228 else
3229 return ToInstOrErr.takeError();
3230
3231 if (ExpectedSLoc POIOrErr =
3232 import(MemberInfo->getPointOfInstantiation()))
3234 *POIOrErr);
3235 else
3236 return POIOrErr.takeError();
3237 }
3238
3239 } else {
3240 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3241 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3242 Name.getAsIdentifierInfo(), PrevDecl))
3243 return D2;
3244 D2->setLexicalDeclContext(LexicalDC);
3245 addDeclToContexts(D, D2);
3246 }
3247
3248 if (auto BraceRangeOrErr = import(D->getBraceRange()))
3249 D2->setBraceRange(*BraceRangeOrErr);
3250 else
3251 return BraceRangeOrErr.takeError();
3252 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3253 D2->setQualifierInfo(*QualifierLocOrErr);
3254 else
3255 return QualifierLocOrErr.takeError();
3256
3257 if (D->isAnonymousStructOrUnion())
3258 D2->setAnonymousStructOrUnion(true);
3259
3260 if (D->isCompleteDefinition())
3261 if (Error Err = ImportDefinition(D, D2, IDK_Default))
3262 return std::move(Err);
3263
3264 return D2;
3265}
3266
3268 // Import the major distinguishing characteristics of this enumerator.
3269 DeclContext *DC, *LexicalDC;
3270 DeclarationName Name;
3271 SourceLocation Loc;
3272 NamedDecl *ToD;
3273 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3274 return std::move(Err);
3275 if (ToD)
3276 return ToD;
3277
3278 // Determine whether there are any other declarations with the same name and
3279 // in the same context.
3280 if (!LexicalDC->isFunctionOrMethod()) {
3281 SmallVector<NamedDecl *, 4> ConflictingDecls;
3282 unsigned IDNS = Decl::IDNS_Ordinary;
3283 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3284 for (auto *FoundDecl : FoundDecls) {
3285 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3286 continue;
3287
3288 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3289 if (IsStructuralMatch(D, FoundEnumConstant))
3290 return Importer.MapImported(D, FoundEnumConstant);
3291 ConflictingDecls.push_back(FoundDecl);
3292 }
3293 }
3294
3295 if (!ConflictingDecls.empty()) {
3296 ExpectedName NameOrErr = Importer.HandleNameConflict(
3297 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3298 if (NameOrErr)
3299 Name = NameOrErr.get();
3300 else
3301 return NameOrErr.takeError();
3302 }
3303 }
3304
3305 ExpectedType TypeOrErr = import(D->getType());
3306 if (!TypeOrErr)
3307 return TypeOrErr.takeError();
3308
3309 ExpectedExpr InitOrErr = import(D->getInitExpr());
3310 if (!InitOrErr)
3311 return InitOrErr.takeError();
3312
3313 EnumConstantDecl *ToEnumerator;
3314 if (GetImportedOrCreateDecl(
3315 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3316 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3317 return ToEnumerator;
3318
3319 ToEnumerator->setAccess(D->getAccess());
3320 ToEnumerator->setLexicalDeclContext(LexicalDC);
3321 LexicalDC->addDeclInternal(ToEnumerator);
3322 return ToEnumerator;
3323}
3324
3326 DeclaratorDecl *ToD) {
3327 unsigned int Num = FromD->getNumTemplateParameterLists();
3328 if (Num == 0)
3329 return Error::success();
3331 for (unsigned int I = 0; I < Num; ++I)
3332 if (Expected<TemplateParameterList *> ToTPListOrErr =
3333 import(FromD->getTemplateParameterList(I)))
3334 ToTPLists[I] = *ToTPListOrErr;
3335 else
3336 return ToTPListOrErr.takeError();
3337 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3338 return Error::success();
3339}
3340
3342 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3343 switch (FromFD->getTemplatedKind()) {
3346 return Error::success();
3347
3349 if (Expected<FunctionDecl *> InstFDOrErr =
3350 import(FromFD->getInstantiatedFromDecl()))
3351 ToFD->setInstantiatedFromDecl(*InstFDOrErr);
3352 return Error::success();
3355
3356 if (Expected<FunctionDecl *> InstFDOrErr =
3357 import(FromFD->getInstantiatedFromMemberFunction()))
3358 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3359 else
3360 return InstFDOrErr.takeError();
3361
3362 if (ExpectedSLoc POIOrErr = import(
3365 else
3366 return POIOrErr.takeError();
3367
3368 return Error::success();
3369 }
3370
3372 auto FunctionAndArgsOrErr =
3374 if (!FunctionAndArgsOrErr)
3375 return FunctionAndArgsOrErr.takeError();
3376
3378 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3379
3380 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3381 TemplateArgumentListInfo ToTAInfo;
3382 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3383 if (FromTAArgsAsWritten)
3384 if (Error Err = ImportTemplateArgumentListInfo(
3385 *FromTAArgsAsWritten, ToTAInfo))
3386 return Err;
3387
3388 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3389 if (!POIOrErr)
3390 return POIOrErr.takeError();
3391
3392 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3393 return Err;
3394
3395 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3396 ToFD->setFunctionTemplateSpecialization(
3397 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3398 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3399 return Error::success();
3400 }
3401
3403 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3404 UnresolvedSet<8> Candidates;
3405 for (FunctionTemplateDecl *FTD : FromInfo->getCandidates()) {
3406 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = import(FTD))
3407 Candidates.addDecl(*ToFTDOrErr);
3408 else
3409 return ToFTDOrErr.takeError();
3410 }
3411
3412 // Import TemplateArgumentListInfo.
3413 TemplateArgumentListInfo ToTAInfo;
3414 const auto *FromTAArgsAsWritten = FromInfo->TemplateArgumentsAsWritten;
3415 if (FromTAArgsAsWritten)
3416 if (Error Err =
3417 ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
3418 return Err;
3419
3421 Importer.getToContext(), Candidates,
3422 FromTAArgsAsWritten ? &ToTAInfo : nullptr);
3423 return Error::success();
3424 }
3425 }
3426 llvm_unreachable("All cases should be covered!");
3427}
3428
3431 auto FunctionAndArgsOrErr =
3433 if (!FunctionAndArgsOrErr)
3434 return FunctionAndArgsOrErr.takeError();
3435
3436 FunctionTemplateDecl *Template;
3437 TemplateArgsTy ToTemplArgs;
3438 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3439 void *InsertPos = nullptr;
3440 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3441 return FoundSpec;
3442}
3443
3445 FunctionDecl *ToFD) {
3446 if (Stmt *FromBody = FromFD->getBody()) {
3447 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3448 ToFD->setBody(*ToBodyOrErr);
3449 else
3450 return ToBodyOrErr.takeError();
3451 }
3452 return Error::success();
3453}
3454
3455// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3456// which is equal to the given DC, or D is equal to DC.
3457static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3458 const DeclContext *DCi = dyn_cast<DeclContext>(D);
3459 if (!DCi)
3460 DCi = D->getDeclContext();
3461 assert(DCi && "Declaration should have a context");
3462 while (DCi != D->getTranslationUnitDecl()) {
3463 if (DCi == DC)
3464 return true;
3465 DCi = DCi->getParent();
3466 }
3467 return false;
3468}
3469
3470// Check if there is a declaration that has 'DC' as parent context and is
3471// referenced from statement 'S' or one of its children. The search is done in
3472// BFS order through children of 'S'.
3473static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
3474 SmallVector<const Stmt *> ToProcess;
3475 ToProcess.push_back(S);
3476 while (!ToProcess.empty()) {
3477 const Stmt *CurrentS = ToProcess.pop_back_val();
3478 ToProcess.append(CurrentS->child_begin(), CurrentS->child_end());
3479 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CurrentS)) {
3480 if (const Decl *D = DeclRef->getDecl())
3481 if (isAncestorDeclContextOf(DC, D))
3482 return true;
3483 } else if (const auto *E =
3484 dyn_cast_or_null<SubstNonTypeTemplateParmExpr>(CurrentS)) {
3485 if (const Decl *D = E->getAssociatedDecl())
3486 if (isAncestorDeclContextOf(DC, D))
3487 return true;
3488 }
3489 }
3490 return false;
3491}
3492
3493namespace {
3494/// Check if a type has any reference to a declaration that is inside the body
3495/// of a function.
3496/// The \c CheckType(QualType) function should be used to determine
3497/// this property.
3498///
3499/// The type visitor visits one type object only (not recursive).
3500/// To find all referenced declarations we must discover all type objects until
3501/// the canonical type is reached (walk over typedef and similar objects). This
3502/// is done by loop over all "sugar" type objects. For every such type we must
3503/// check all declarations that are referenced from it. For this check the
3504/// visitor is used. In the visit functions all referenced declarations except
3505/// the one that follows in the sugar chain (if any) must be checked. For this
3506/// check the same visitor is re-used (it has no state-dependent data).
3507///
3508/// The visit functions have 3 possible return values:
3509/// - True, found a declaration inside \c ParentDC.
3510/// - False, found declarations only outside \c ParentDC and it is not possible
3511/// to find more declarations (the "sugar" chain does not continue).
3512/// - Empty optional value, found no declarations or only outside \c ParentDC,
3513/// but it is possible to find more declarations in the type "sugar" chain.
3514/// The loop over the "sugar" types can be implemented by using type visit
3515/// functions only (call \c CheckType with the desugared type). With the current
3516/// solution no visit function is needed if the type has only a desugared type
3517/// as data.
3518class IsTypeDeclaredInsideVisitor
3519 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
3520public:
3521 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
3522 : ParentDC(ParentDC) {}
3523
3524 bool CheckType(QualType T) {
3525 // Check the chain of "sugar" types.
3526 // The "sugar" types are typedef or similar types that have the same
3527 // canonical type.
3528 if (std::optional<bool> Res = Visit(T.getTypePtr()))
3529 return *Res;
3530 QualType DsT =
3531 T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3532 while (DsT != T) {
3533 if (std::optional<bool> Res = Visit(DsT.getTypePtr()))
3534 return *Res;
3535 T = DsT;
3536 DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3537 }
3538 return false;
3539 }
3540
3541 std::optional<bool> VisitTagType(const TagType *T) {
3542 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl()))
3543 for (const auto &Arg : Spec->getTemplateArgs().asArray())
3544 if (checkTemplateArgument(Arg))
3545 return true;
3546 return isAncestorDeclContextOf(ParentDC, T->getDecl());
3547 }
3548
3549 std::optional<bool> VisitPointerType(const PointerType *T) {
3550 return CheckType(T->getPointeeType());
3551 }
3552
3553 std::optional<bool> VisitReferenceType(const ReferenceType *T) {
3554 return CheckType(T->getPointeeTypeAsWritten());
3555 }
3556
3557 std::optional<bool> VisitTypedefType(const TypedefType *T) {
3558 const TypedefNameDecl *TD = T->getDecl();
3559 assert(TD);
3560 return isAncestorDeclContextOf(ParentDC, TD);
3561 }
3562
3563 std::optional<bool> VisitUsingType(const UsingType *T) {
3564 if (T->getFoundDecl() &&
3565 isAncestorDeclContextOf(ParentDC, T->getFoundDecl()))
3566 return true;
3567
3568 return {};
3569 }
3570
3571 std::optional<bool>
3572 VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
3573 for (const auto &Arg : T->template_arguments())
3574 if (checkTemplateArgument(Arg))
3575 return true;
3576 // This type is a "sugar" to a record type, it can have a desugared type.
3577 return {};
3578 }
3579
3580 std::optional<bool>
3581 VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3582 // The "associated declaration" can be the same as ParentDC.
3583 if (isAncestorDeclContextOf(ParentDC, T->getAssociatedDecl()))
3584 return true;
3585 return {};
3586 }
3587
3588 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
3589 if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr()))
3590 return true;
3591
3592 return CheckType(T->getElementType());
3593 }
3594
3595 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
3596 llvm_unreachable(
3597 "Variable array should not occur in deduced return type of a function");
3598 }
3599
3600 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
3601 llvm_unreachable("Incomplete array should not occur in deduced return type "
3602 "of a function");
3603 }
3604
3605 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
3606 llvm_unreachable("Dependent array should not occur in deduced return type "
3607 "of a function");
3608 }
3609
3610private:
3611 const DeclContext *const ParentDC;
3612
3613 bool checkTemplateArgument(const TemplateArgument &Arg) {
3614 switch (Arg.getKind()) {
3616 return false;
3618 return CheckType(Arg.getIntegralType());
3620 return CheckType(Arg.getAsType());
3622 return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr());
3624 // FIXME: The declaration in this case is not allowed to be in a function?
3625 return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl());
3627 // FIXME: The type is not allowed to be in the function?
3628 return CheckType(Arg.getNullPtrType());
3630 return CheckType(Arg.getStructuralValueType());
3632 for (const auto &PackArg : Arg.getPackAsArray())
3633 if (checkTemplateArgument(PackArg))
3634 return true;
3635 return false;
3637 // Templates can not be defined locally in functions.
3638 // A template passed as argument can be not in ParentDC.
3639 return false;
3641 // Templates can not be defined locally in functions.
3642 // A template passed as argument can be not in ParentDC.
3643 return false;
3644 }
3645 llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
3646 };
3647};
3648} // namespace
3649
3650/// This function checks if the function has 'auto' return type that contains
3651/// a reference (in any way) to a declaration inside the same function.
3653 QualType FromTy = D->getType();
3654 const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3655 assert(FromFPT && "Must be called on FunctionProtoType");
3656
3657 QualType RetT = FromFPT->getReturnType();
3658 if (isa<AutoType>(RetT.getTypePtr())) {
3659 FunctionDecl *Def = D->getDefinition();
3660 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
3661 return Visitor.CheckType(RetT);
3662 }
3663
3664 return false;
3665}
3666
3668ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3669 Expr *ExplicitExpr = ESpec.getExpr();
3670 if (ExplicitExpr)
3671 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3672 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3673}
3674
3676
3678 auto RedeclIt = Redecls.begin();
3679 // Import the first part of the decl chain. I.e. import all previous
3680 // declarations starting from the canonical decl.
3681 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3682 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3683 if (!ToRedeclOrErr)
3684 return ToRedeclOrErr.takeError();
3685 }
3686 assert(*RedeclIt == D);
3687
3688 // Import the major distinguishing characteristics of this function.
3689 DeclContext *DC, *LexicalDC;
3690 DeclarationName Name;
3691 SourceLocation Loc;
3692 NamedDecl *ToD;
3693 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3694 return std::move(Err);
3695 if (ToD)
3696 return ToD;
3697
3698 FunctionDecl *FoundByLookup = nullptr;
3700
3701 // If this is a function template specialization, then try to find the same
3702 // existing specialization in the "to" context. The lookup below will not
3703 // find any specialization, but would find the primary template; thus, we
3704 // have to skip normal lookup in case of specializations.
3705 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3706 if (D->getTemplatedKind() ==
3708 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3709 if (!FoundFunctionOrErr)
3710 return FoundFunctionOrErr.takeError();
3711 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3712 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3713 return Def;
3714 FoundByLookup = FoundFunction;
3715 }
3716 }
3717 // Try to find a function in our own ("to") context with the same name, same
3718 // type, and in the same context as the function we're importing.
3719 else if (!LexicalDC->isFunctionOrMethod()) {
3720 SmallVector<NamedDecl *, 4> ConflictingDecls;
3722 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3723 for (auto *FoundDecl : FoundDecls) {
3724 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3725 continue;
3726
3727 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3728 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3729 continue;
3730
3731 if (IsStructuralMatch(D, FoundFunction)) {
3732 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3733 return Def;
3734 FoundByLookup = FoundFunction;
3735 break;
3736 }
3737 // FIXME: Check for overloading more carefully, e.g., by boosting
3738 // Sema::IsOverload out to the AST library.
3739
3740 // Function overloading is okay in C++.
3741 if (Importer.getToContext().getLangOpts().CPlusPlus)
3742 continue;
3743
3744 // Complain about inconsistent function types.
3745 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3746 << Name << D->getType() << FoundFunction->getType();
3747 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3748 << FoundFunction->getType();
3749 ConflictingDecls.push_back(FoundDecl);
3750 }
3751 }
3752
3753 if (!ConflictingDecls.empty()) {
3754 ExpectedName NameOrErr = Importer.HandleNameConflict(
3755 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3756 if (NameOrErr)
3757 Name = NameOrErr.get();
3758 else
3759 return NameOrErr.takeError();
3760 }
3761 }
3762
3763 // We do not allow more than one in-class declaration of a function. This is
3764 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3765 // assumes there is only one in-class declaration. Building a redecl
3766 // chain would result in more than one in-class declaration for
3767 // overrides (even if they are part of the same redecl chain inside the
3768 // derived class.)
3769 if (FoundByLookup) {
3770 if (isa<CXXMethodDecl>(FoundByLookup)) {
3771 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3772 if (!D->doesThisDeclarationHaveABody()) {
3773 if (FunctionTemplateDecl *DescribedD =
3775 // Handle a "templated" function together with its described
3776 // template. This avoids need for a similar check at import of the
3777 // described template.
3778 assert(FoundByLookup->getDescribedFunctionTemplate() &&
3779 "Templated function mapped to non-templated?");
3780 Importer.MapImported(DescribedD,
3781 FoundByLookup->getDescribedFunctionTemplate());
3782 }
3783 return Importer.MapImported(D, FoundByLookup);
3784 } else {
3785 // Let's continue and build up the redecl chain in this case.
3786 // FIXME Merge the functions into one decl.
3787 }
3788 }
3789 }
3790 }
3791
3792 DeclarationNameInfo NameInfo(Name, Loc);
3793 // Import additional name location/type info.
3794 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3795 return std::move(Err);
3796
3797 QualType FromTy = D->getType();
3798 TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3799 // Set to true if we do not import the type of the function as is. There are
3800 // cases when the original type would result in an infinite recursion during
3801 // the import. To avoid an infinite recursion when importing, we create the
3802 // FunctionDecl with a simplified function type and update it only after the
3803 // relevant AST nodes are already imported.
3804 // The type is related to TypeSourceInfo (it references the type), so we must
3805 // do the same with TypeSourceInfo.
3806 bool UsedDifferentProtoType = false;
3807 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3808 QualType FromReturnTy = FromFPT->getReturnType();
3809 // Functions with auto return type may define a struct inside their body
3810 // and the return type could refer to that struct.
3811 // E.g.: auto foo() { struct X{}; return X(); }
3812 // To avoid an infinite recursion when importing, create the FunctionDecl
3813 // with a simplified return type.
3815 FromReturnTy = Importer.getFromContext().VoidTy;
3816 UsedDifferentProtoType = true;
3817 }
3818 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3819 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3820 // FunctionDecl that we are importing the FunctionProtoType for.
3821 // To avoid an infinite recursion when importing, create the FunctionDecl
3822 // with a simplified function type.
3823 if (FromEPI.ExceptionSpec.SourceDecl ||
3824 FromEPI.ExceptionSpec.SourceTemplate ||
3825 FromEPI.ExceptionSpec.NoexceptExpr) {
3827 FromEPI = DefaultEPI;
3828 UsedDifferentProtoType = true;
3829 }
3830 FromTy = Importer.getFromContext().getFunctionType(
3831 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3832 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3833 FromTy, D->getBeginLoc());
3834 }
3835
3836 Error Err = Error::success();
3837 auto T = importChecked(Err, FromTy);
3838 auto TInfo = importChecked(Err, FromTSI);
3839 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3840 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3841 auto ToDefaultLoc = importChecked(Err, D->getDefaultLoc());
3842 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3843 auto TrailingRequiresClause =
3845 if (Err)
3846 return std::move(Err);
3847
3848 // Import the function parameters.
3850 for (auto *P : D->parameters()) {
3851 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3852 Parameters.push_back(*ToPOrErr);
3853 else
3854 return ToPOrErr.takeError();
3855 }
3856
3857 // Create the imported function.
3858 FunctionDecl *ToFunction = nullptr;
3859 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3860 ExplicitSpecifier ESpec =
3861 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3862 if (Err)
3863 return std::move(Err);
3864 auto ToInheritedConstructor = InheritedConstructor();
3865 if (FromConstructor->isInheritingConstructor()) {
3866 Expected<InheritedConstructor> ImportedInheritedCtor =
3867 import(FromConstructor->getInheritedConstructor());
3868 if (!ImportedInheritedCtor)
3869 return ImportedInheritedCtor.takeError();
3870 ToInheritedConstructor = *ImportedInheritedCtor;
3871 }
3872 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3873 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3874 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3876 ToInheritedConstructor, TrailingRequiresClause))
3877 return ToFunction;
3878 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3879
3880 Error Err = Error::success();
3881 auto ToOperatorDelete = importChecked(
3882 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3883 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3884 if (Err)
3885 return std::move(Err);
3886
3887 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3888 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3889 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3891 TrailingRequiresClause))
3892 return ToFunction;
3893
3894 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3895
3896 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3897 } else if (CXXConversionDecl *FromConversion =
3898 dyn_cast<CXXConversionDecl>(D)) {
3899 ExplicitSpecifier ESpec =
3900 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3901 if (Err)
3902 return std::move(Err);
3903 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3904 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3905 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3906 D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3907 SourceLocation(), TrailingRequiresClause))
3908 return ToFunction;
3909 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3910 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3911 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3912 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3913 Method->UsesFPIntrin(), Method->isInlineSpecified(),
3914 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3915 return ToFunction;
3916 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3917 ExplicitSpecifier ESpec =
3918 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3919 CXXConstructorDecl *Ctor =
3920 importChecked(Err, Guide->getCorrespondingConstructor());
3921 if (Err)
3922 return std::move(Err);
3923 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3924 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3925 NameInfo, T, TInfo, ToEndLoc, Ctor))
3926 return ToFunction;
3927 cast<CXXDeductionGuideDecl>(ToFunction)
3928 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind());
3929 } else {
3930 if (GetImportedOrCreateDecl(
3931 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3932 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3934 D->getConstexprKind(), TrailingRequiresClause))
3935 return ToFunction;
3936 }
3937
3938 // Connect the redecl chain.
3939 if (FoundByLookup) {
3940 auto *Recent = const_cast<FunctionDecl *>(
3941 FoundByLookup->getMostRecentDecl());
3942 ToFunction->setPreviousDecl(Recent);
3943 // FIXME Probably we should merge exception specifications. E.g. In the
3944 // "To" context the existing function may have exception specification with
3945 // noexcept-unevaluated, while the newly imported function may have an
3946 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3947 // decl and its redeclarations may be required.
3948 }
3949
3950 ToFunction->setQualifierInfo(ToQualifierLoc);
3951 ToFunction->setAccess(D->getAccess());
3952 ToFunction->setLexicalDeclContext(LexicalDC);
3953 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3954 ToFunction->setTrivial(D->isTrivial());
3955 ToFunction->setIsPureVirtual(D->isPureVirtual());
3956 ToFunction->setDefaulted(D->isDefaulted());
3958 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3961 ToFunction->setRangeEnd(ToEndLoc);
3962 ToFunction->setDefaultLoc(ToDefaultLoc);
3963
3964 // Set the parameters.
3965 for (auto *Param : Parameters) {
3966 Param->setOwningFunction(ToFunction);
3967 ToFunction->addDeclInternal(Param);
3968 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3969 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3970 }
3971 ToFunction->setParams(Parameters);
3972
3973 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3974 // params it refers to.
3975 if (TInfo) {
3976 if (auto ProtoLoc =
3977 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3978 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3979 ProtoLoc.setParam(I, Parameters[I]);
3980 }
3981 }
3982
3983 // Import the describing template function, if any.
3984 if (FromFT) {
3985 auto ToFTOrErr = import(FromFT);
3986 if (!ToFTOrErr)
3987 return ToFTOrErr.takeError();
3988 }
3989
3990 // Import Ctor initializers.
3991 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3992 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3993 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3994 // Import first, then allocate memory and copy if there was no error.
3995 if (Error Err = ImportContainerChecked(
3996 FromConstructor->inits(), CtorInitializers))
3997 return std::move(Err);
3998 auto **Memory =
3999 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
4000 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
4001 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
4002 ToCtor->setCtorInitializers(Memory);
4003 ToCtor->setNumCtorInitializers(NumInitializers);
4004 }
4005 }
4006
4007 // If it is a template, import all related things.
4008 if (Error Err = ImportTemplateInformation(D, ToFunction))
4009 return std::move(Err);
4010
4011 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
4012 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
4013 FromCXXMethod))
4014 return std::move(Err);
4015
4017 Error Err = ImportFunctionDeclBody(D, ToFunction);
4018
4019 if (Err)
4020 return std::move(Err);
4021 }
4022
4023 // Import and set the original type in case we used another type.
4024 if (UsedDifferentProtoType) {
4025 if (ExpectedType TyOrErr = import(D->getType()))
4026 ToFunction->setType(*TyOrErr);
4027 else
4028 return TyOrErr.takeError();
4029 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
4030 ToFunction->setTypeSourceInfo(*TSIOrErr);
4031 else
4032 return TSIOrErr.takeError();
4033 }
4034
4035 // FIXME: Other bits to merge?
4036
4037 addDeclToContexts(D, ToFunction);
4038
4039 // Import the rest of the chain. I.e. import all subsequent declarations.
4040 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4041 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
4042 if (!ToRedeclOrErr)
4043 return ToRedeclOrErr.takeError();
4044 }
4045
4046 return ToFunction;
4047}
4048
4050 return VisitFunctionDecl(D);
4051}
4052
4054 return VisitCXXMethodDecl(D);
4055}
4056
4058 return VisitCXXMethodDecl(D);
4059}
4060
4062 return VisitCXXMethodDecl(D);
4063}
4064
4067 return VisitFunctionDecl(D);
4068}
4069
4071 // Import the major distinguishing characteristics of a variable.
4072 DeclContext *DC, *LexicalDC;
4073 DeclarationName Name;
4074 SourceLocation Loc;
4075 NamedDecl *ToD;
4076 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4077 return std::move(Err);
4078 if (ToD)
4079 return ToD;
4080
4081 // Determine whether we've already imported this field.
4082 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4083 for (auto *FoundDecl : FoundDecls) {
4084 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
4085 // For anonymous fields, match up by index.
4086 if (!Name &&
4088 ASTImporter::getFieldIndex(FoundField))
4089 continue;
4090
4091 if (Importer.IsStructurallyEquivalent(D->getType(),
4092 FoundField->getType())) {
4093 Importer.MapImported(D, FoundField);
4094 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
4095 // initializer of a FieldDecl might not had been instantiated in the
4096 // "To" context. However, the "From" context might instantiated that,
4097 // thus we have to merge that.
4098 // Note: `hasInClassInitializer()` is not the same as non-null
4099 // `getInClassInitializer()` value.
4100 if (Expr *FromInitializer = D->getInClassInitializer()) {
4101 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) {
4102 // Import of the FromInitializer may result in the setting of
4103 // InClassInitializer. If not, set it here.
4104 assert(FoundField->hasInClassInitializer() &&
4105 "Field should have an in-class initializer if it has an "
4106 "expression for it.");
4107 if (!FoundField->getInClassInitializer())
4108 FoundField->setInClassInitializer(*ToInitializerOrErr);
4109 } else {
4110 return ToInitializerOrErr.takeError();
4111 }
4112 }
4113 return FoundField;
4114 }
4115
4116 // FIXME: Why is this case not handled with calling HandleNameConflict?
4117 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4118 << Name << D->getType() << FoundField->getType();
4119 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4120 << FoundField->getType();
4121
4122 return make_error<ASTImportError>(ASTImportError::NameConflict);
4123 }
4124 }
4125
4126 Error Err = Error::success();
4127 auto ToType = importChecked(Err, D->getType());
4128 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
4129 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4130 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4131 if (Err)
4132 return std::move(Err);
4133 const Type *ToCapturedVLAType = nullptr;
4134 if (Error Err = Importer.importInto(
4135 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
4136 return std::move(Err);
4137
4138 FieldDecl *ToField;
4139 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
4140 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4141 ToType, ToTInfo, ToBitWidth, D->isMutable(),
4142 D->getInClassInitStyle()))
4143 return ToField;
4144
4145 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before
4146 // we add fields in CXXRecordDecl::addedMember, otherwise record will be
4147 // marked as having non-zero size.
4148 Err = Importer.ImportAttrs(ToField, D);
4149 if (Err)
4150 return std::move(Err);
4151 ToField->setAccess(D->getAccess());
4152 ToField->setLexicalDeclContext(LexicalDC);
4153 ToField->setImplicit(D->isImplicit());
4154 if (ToCapturedVLAType)
4155 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
4156 LexicalDC->addDeclInternal(ToField);
4157 // Import initializer only after the field was created, it may have recursive
4158 // reference to the field.
4159 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
4160 if (Err)
4161 return std::move(Err);
4162 if (ToInitializer) {
4163 auto *AlreadyImported = ToField->getInClassInitializer();
4164 if (AlreadyImported)
4165 assert(ToInitializer == AlreadyImported &&
4166 "Duplicate import of in-class initializer.");
4167 else
4168 ToField->setInClassInitializer(ToInitializer);
4169 }
4170
4171 return ToField;
4172}
4173
4175 // Import the major distinguishing characteristics of a variable.
4176 DeclContext *DC, *LexicalDC;
4177 DeclarationName Name;
4178 SourceLocation Loc;
4179 NamedDecl *ToD;
4180 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4181 return std::move(Err);
4182 if (ToD)
4183 return ToD;
4184
4185 // Determine whether we've already imported this field.
4186 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4187 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4188 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
4189 // For anonymous indirect fields, match up by index.
4190 if (!Name &&
4192 ASTImporter::getFieldIndex(FoundField))
4193 continue;
4194
4195 if (Importer.IsStructurallyEquivalent(D->getType(),
4196 FoundField->getType(),
4197 !Name.isEmpty())) {
4198 Importer.MapImported(D, FoundField);
4199 return FoundField;
4200 }
4201
4202 // If there are more anonymous fields to check, continue.
4203 if (!Name && I < N-1)
4204 continue;
4205
4206 // FIXME: Why is this case not handled with calling HandleNameConflict?
4207 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4208 << Name << D->getType() << FoundField->getType();
4209 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4210 << FoundField->getType();
4211
4212 return make_error<ASTImportError>(ASTImportError::NameConflict);
4213 }
4214 }
4215
4216 // Import the type.
4217 auto TypeOrErr = import(D->getType());
4218 if (!TypeOrErr)
4219 return TypeOrErr.takeError();
4220
4221 auto **NamedChain =
4222 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
4223
4224 unsigned i = 0;
4225 for (auto *PI : D->chain())
4226 if (Expected<NamedDecl *> ToD = import(PI))
4227 NamedChain[i++] = *ToD;
4228 else
4229 return ToD.takeError();
4230
4232 IndirectFieldDecl *ToIndirectField;
4233 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
4234 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
4235 // FIXME here we leak `NamedChain` which is allocated before
4236 return ToIndirectField;
4237
4238 ToIndirectField->setAccess(D->getAccess());
4239 ToIndirectField->setLexicalDeclContext(LexicalDC);
4240 LexicalDC->addDeclInternal(ToIndirectField);
4241 return ToIndirectField;
4242}
4243
4244/// Used as return type of getFriendCountAndPosition.
4246 /// Number of similar looking friends.
4247 unsigned int TotalCount;
4248 /// Index of the specific FriendDecl.
4249 unsigned int IndexOfDecl;
4250};
4251
4252static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1,
4253 FriendDecl *FD2) {
4254 if ((!FD1->getFriendType()) != (!FD2->getFriendType()))
4255 return false;
4256
4257 if (const TypeSourceInfo *TSI = FD1->getFriendType())
4258 return Importer.IsStructurallyEquivalent(
4259 TSI->getType(), FD2->getFriendType()->getType(), /*Complain=*/false);
4260
4261 ASTImporter::NonEquivalentDeclSet NonEquivalentDecls;
4263 FD1->getASTContext(), FD2->getASTContext(), NonEquivalentDecls,
4265 /* StrictTypeSpelling = */ false, /* Complain = */ false);
4266 return Ctx.IsEquivalent(FD1, FD2);
4267}
4268
4270 FriendDecl *FD) {
4271 unsigned int FriendCount = 0;
4272 std::optional<unsigned int> FriendPosition;
4273 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
4274
4275 for (FriendDecl *FoundFriend : RD->friends()) {
4276 if (FoundFriend == FD) {
4277 FriendPosition = FriendCount;
4278 ++FriendCount;
4279 } else if (IsEquivalentFriend(Importer, FD, FoundFriend)) {
4280 ++FriendCount;
4281 }
4282 }
4283
4284 assert(FriendPosition && "Friend decl not found in own parent.");
4285
4286 return {FriendCount, *FriendPosition};
4287}
4288
4290 // Import the major distinguishing characteristics of a declaration.
4291 DeclContext *DC, *LexicalDC;
4292 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4293 return std::move(Err);
4294
4295 // Determine whether we've already imported this decl.
4296 // FriendDecl is not a NamedDecl so we cannot use lookup.
4297 // We try to maintain order and count of redundant friend declarations.
4298 const auto *RD = cast<CXXRecordDecl>(DC);
4299 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
4300 for (FriendDecl *ImportedFriend : RD->friends())
4301 if (IsEquivalentFriend(Importer, D, ImportedFriend))
4302 ImportedEquivalentFriends.push_back(ImportedFriend);
4303
4304 FriendCountAndPosition CountAndPosition =
4305 getFriendCountAndPosition(Importer, D);
4306
4307 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
4308 "Class with non-matching friends is imported, ODR check wrong?");
4309 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
4310 return Importer.MapImported(
4311 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
4312
4313 // Not found. Create it.
4314 // The declarations will be put into order later by ImportDeclContext.
4316 if (NamedDecl *FriendD = D->getFriendDecl()) {
4317 NamedDecl *ToFriendD;
4318 if (Error Err = importInto(ToFriendD, FriendD))
4319 return std::move(Err);
4320
4321 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
4322 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
4323 ToFriendD->setObjectOfFriendDecl(false);
4324
4325 ToFU = ToFriendD;
4326 } else { // The friend is a type, not a decl.
4327 if (auto TSIOrErr = import(D->getFriendType()))
4328 ToFU = *TSIOrErr;
4329 else
4330 return TSIOrErr.takeError();
4331 }
4332
4333 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
4334 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
4335 for (unsigned I = 0; I < D->NumTPLists; I++) {
4336 if (auto ListOrErr = import(FromTPLists[I]))
4337 ToTPLists[I] = *ListOrErr;
4338 else
4339 return ListOrErr.takeError();
4340 }
4341
4342 auto LocationOrErr = import(D->getLocation());
4343 if (!LocationOrErr)
4344 return LocationOrErr.takeError();
4345 auto FriendLocOrErr = import(D->getFriendLoc());
4346 if (!FriendLocOrErr)
4347 return FriendLocOrErr.takeError();
4348
4349 FriendDecl *FrD;
4350 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
4351 *LocationOrErr, ToFU,
4352 *FriendLocOrErr, ToTPLists))
4353 return FrD;
4354
4355 FrD->setAccess(D->getAccess());
4356 FrD->setLexicalDeclContext(LexicalDC);
4357 LexicalDC->addDeclInternal(FrD);
4358 return FrD;
4359}
4360
4362 // Import the major distinguishing characteristics of an ivar.
4363 DeclContext *DC, *LexicalDC;
4364 DeclarationName Name;
4365 SourceLocation Loc;
4366 NamedDecl *ToD;
4367 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4368 return std::move(Err);
4369 if (ToD)
4370 return ToD;
4371
4372 // Determine whether we've already imported this ivar
4373 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4374 for (auto *FoundDecl : FoundDecls) {
4375 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
4376 if (Importer.IsStructurallyEquivalent(D->getType(),
4377 FoundIvar->getType())) {
4378 Importer.MapImported(D, FoundIvar);
4379 return FoundIvar;
4380 }
4381
4382 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
4383 << Name << D->getType() << FoundIvar->getType();
4384 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
4385 << FoundIvar->getType();
4386
4387 return make_error<ASTImportError>(ASTImportError::NameConflict);
4388 }
4389 }
4390
4391 Error Err = Error::success();
4392 auto ToType = importChecked(Err, D->getType());
4393 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4394 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4395 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4396 if (Err)
4397 return std::move(Err);
4398
4399 ObjCIvarDecl *ToIvar;
4400 if (GetImportedOrCreateDecl(
4401 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
4402 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4403 ToType, ToTypeSourceInfo,
4404 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
4405 return ToIvar;
4406
4407 ToIvar->setLexicalDeclContext(LexicalDC);
4408 LexicalDC->addDeclInternal(ToIvar);
4409 return ToIvar;
4410}
4411
4413
4415 auto RedeclIt = Redecls.begin();
4416 // Import the first part of the decl chain. I.e. import all previous
4417 // declarations starting from the canonical decl.
4418 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4419 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4420 if (!RedeclOrErr)
4421 return RedeclOrErr.takeError();
4422 }
4423 assert(*RedeclIt == D);
4424
4425 // Import the major distinguishing characteristics of a variable.
4426 DeclContext *DC, *LexicalDC;
4427 DeclarationName Name;
4428 SourceLocation Loc;
4429 NamedDecl *ToD;
4430 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4431 return std::move(Err);
4432 if (ToD)
4433 return ToD;
4434
4435 // Try to find a variable in our own ("to") context with the same name and
4436 // in the same context as the variable we're importing.
4437 VarDecl *FoundByLookup = nullptr;
4438 if (D->isFileVarDecl()) {
4439 SmallVector<NamedDecl *, 4> ConflictingDecls;
4440 unsigned IDNS = Decl::IDNS_Ordinary;
4441 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4442 for (auto *FoundDecl : FoundDecls) {
4443 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4444 continue;
4445
4446 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4447 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4448 continue;
4449 if (Importer.IsStructurallyEquivalent(D->getType(),
4450 FoundVar->getType())) {
4451
4452 // The VarDecl in the "From" context has a definition, but in the
4453 // "To" context we already have a definition.
4454 VarDecl *FoundDef = FoundVar->getDefinition();
4455 if (D->isThisDeclarationADefinition() && FoundDef)
4456 // FIXME Check for ODR error if the two definitions have
4457 // different initializers?
4458 return Importer.MapImported(D, FoundDef);
4459
4460 // The VarDecl in the "From" context has an initializer, but in the
4461 // "To" context we already have an initializer.
4462 const VarDecl *FoundDInit = nullptr;
4463 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4464 // FIXME Diagnose ODR error if the two initializers are different?
4465 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4466
4467 FoundByLookup = FoundVar;
4468 break;
4469 }
4470
4471 const ArrayType *FoundArray
4472 = Importer.getToContext().getAsArrayType(FoundVar->getType());
4473 const ArrayType *TArray
4474 = Importer.getToContext().getAsArrayType(D->getType());
4475 if (FoundArray && TArray) {
4476 if (isa<IncompleteArrayType>(FoundArray) &&
4477 isa<ConstantArrayType>(TArray)) {
4478 // Import the type.
4479 if (auto TyOrErr = import(D->getType()))
4480 FoundVar->setType(*TyOrErr);
4481 else
4482 return TyOrErr.takeError();
4483
4484 FoundByLookup = FoundVar;
4485 break;
4486 } else if (isa<IncompleteArrayType>(TArray) &&
4487 isa<ConstantArrayType>(FoundArray)) {
4488 FoundByLookup = FoundVar;
4489 break;
4490 }
4491 }
4492
4493 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4494 << Name << D->getType() << FoundVar->getType();
4495 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4496 << FoundVar->getType();
4497 ConflictingDecls.push_back(FoundDecl);
4498 }
4499 }
4500
4501 if (!ConflictingDecls.empty()) {
4502 ExpectedName NameOrErr = Importer.HandleNameConflict(
4503 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4504 if (NameOrErr)
4505 Name = NameOrErr.get();
4506 else
4507 return NameOrErr.takeError();
4508 }
4509 }
4510
4511 Error Err = Error::success();
4512 auto ToType = importChecked(Err, D->getType());
4513 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4514 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4515 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4516 if (Err)
4517 return std::move(Err);
4518
4519 VarDecl *ToVar;
4520 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4521 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4522 if (Error Err =
4523 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4524 return std::move(Err);
4525 DecompositionDecl *ToDecomp;
4526 if (GetImportedOrCreateDecl(
4527 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4528 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4529 return ToDecomp;
4530 ToVar = ToDecomp;
4531 } else {
4532 // Create the imported variable.
4533 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4534 ToInnerLocStart, Loc,
4535 Name.getAsIdentifierInfo(), ToType,
4536 ToTypeSourceInfo, D->getStorageClass()))
4537 return ToVar;
4538 }
4539
4540 ToVar->setTSCSpec(D->getTSCSpec());
4541 ToVar->setQualifierInfo(ToQualifierLoc);
4542 ToVar->setAccess(D->getAccess());
4543 ToVar->setLexicalDeclContext(LexicalDC);
4544 if (D->isInlineSpecified())
4545 ToVar->setInlineSpecified();
4546 if (D->isInline())
4547 ToVar->setImplicitlyInline();
4548
4549 if (FoundByLookup) {
4550 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4551 ToVar->setPreviousDecl(Recent);
4552 }
4553
4554 // Import the described template, if any.
4555 if (D->getDescribedVarTemplate()) {
4556 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4557 if (!ToVTOrErr)
4558 return ToVTOrErr.takeError();
4560 TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
4562 if (Expected<VarDecl *> ToInstOrErr = import(FromInst))
4563 ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
4564 else
4565 return ToInstOrErr.takeError();
4566 if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
4568 else
4569 return POIOrErr.takeError();
4570 }
4571
4572 if (Error Err = ImportInitializer(D, ToVar))
4573 return std::move(Err);
4574
4575 if (D->isConstexpr())
4576 ToVar->setConstexpr(true);
4577
4578 addDeclToContexts(D, ToVar);
4579
4580 // Import the rest of the chain. I.e. import all subsequent declarations.
4581 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4582 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4583 if (!RedeclOrErr)
4584 return RedeclOrErr.takeError();
4585 }
4586
4587 return ToVar;
4588}
4589
4591 // Parameters are created in the translation unit's context, then moved
4592 // into the function declaration's context afterward.
4594
4595 Error Err = Error::success();
4596 auto ToDeclName = importChecked(Err, D->getDeclName());
4597 auto ToLocation = importChecked(Err, D->getLocation());
4598 auto ToType = importChecked(Err, D->getType());
4599 if (Err)
4600 return std::move(Err);
4601
4602 // Create the imported parameter.
4603 ImplicitParamDecl *ToParm = nullptr;
4604 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4605 ToLocation, ToDeclName.getAsIdentifierInfo(),
4606 ToType, D->getParameterKind()))
4607 return ToParm;
4608 return ToParm;
4609}
4610
4612 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4615 FromParam->getExplicitObjectParamThisLoc());
4616 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4617
4618 if (FromParam->hasUninstantiatedDefaultArg()) {
4619 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4620 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4621 else
4622 return ToDefArgOrErr.takeError();
4623 } else if (FromParam->hasUnparsedDefaultArg()) {
4624 ToParam->setUnparsedDefaultArg();
4625 } else if (FromParam->hasDefaultArg()) {
4626 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4627 ToParam->setDefaultArg(*ToDefArgOrErr);
4628 else
4629 return ToDefArgOrErr.takeError();
4630 }
4631
4632 return Error::success();
4633}
4634
4637 Error Err = Error::success();
4638 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor());
4639 ConstructorUsingShadowDecl *ToShadow =
4640 importChecked(Err, From.getShadowDecl());
4641 if (Err)
4642 return std::move(Err);
4643 return InheritedConstructor(ToShadow, ToBaseCtor);
4644}
4645
4647 // Parameters are created in the translation unit's context, then moved
4648 // into the function declaration's context afterward.
4650
4651 Error Err = Error::success();
4652 auto ToDeclName = importChecked(Err, D->getDeclName());
4653 auto ToLocation = importChecked(Err, D->getLocation());
4654 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4655 auto ToType = importChecked(Err, D->getType());
4656 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4657 if (Err)
4658 return std::move(Err);
4659
4660 ParmVarDecl *ToParm;
4661 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4662 ToInnerLocStart, ToLocation,
4663 ToDeclName.getAsIdentifierInfo(), ToType,
4664 ToTypeSourceInfo, D->getStorageClass(),
4665 /*DefaultArg*/ nullptr))
4666 return ToParm;
4667
4668 // Set the default argument. It should be no problem if it was already done.
4669 // Do not import the default expression before GetImportedOrCreateDecl call
4670 // to avoid possible infinite import loop because circular dependency.
4671 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4672 return std::move(Err);
4673
4674 if (D->isObjCMethodParameter()) {
4677 } else {
4680 }
4681
4682 return ToParm;
4683}
4684
4686 // Import the major distinguishing characteristics of a method.
4687 DeclContext *DC, *LexicalDC;
4688 DeclarationName Name;
4689 SourceLocation Loc;
4690 NamedDecl *ToD;
4691 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4692 return std::move(Err);
4693 if (ToD)
4694 return ToD;
4695
4696 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4697 for (auto *FoundDecl : FoundDecls) {
4698 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4699 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4700 continue;
4701
4702 // Check return types.
4703 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4704 FoundMethod->getReturnType())) {
4705 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4706 << D->isInstanceMethod() << Name << D->getReturnType()
4707 << FoundMethod->getReturnType();
4708 Importer.ToDiag(FoundMethod->getLocation(),
4709 diag::note_odr_objc_method_here)
4710 << D->isInstanceMethod() << Name;
4711
4712 return make_error<ASTImportError>(ASTImportError::NameConflict);
4713 }
4714
4715 // Check the number of parameters.
4716 if (D->param_size() != FoundMethod->param_size()) {
4717 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4718 << D->isInstanceMethod() << Name
4719 << D->param_size() << FoundMethod->param_size();
4720 Importer.ToDiag(FoundMethod->getLocation(),
4721 diag::note_odr_objc_method_here)
4722 << D->isInstanceMethod() << Name;
4723
4724 return make_error<ASTImportError>(ASTImportError::NameConflict);
4725 }
4726
4727 // Check parameter types.
4729 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4730 P != PEnd; ++P, ++FoundP) {
4731 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4732 (*FoundP)->getType())) {
4733 Importer.FromDiag((*P)->getLocation(),
4734 diag::warn_odr_objc_method_param_type_inconsistent)
4735 << D->isInstanceMethod() << Name
4736 << (*P)->getType() << (*FoundP)->getType();
4737 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4738 << (*FoundP)->getType();
4739
4740 return make_error<ASTImportError>(ASTImportError::NameConflict);
4741 }
4742 }
4743
4744 // Check variadic/non-variadic.
4745 // Check the number of parameters.
4746 if (D->isVariadic() != FoundMethod->isVariadic()) {
4747 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4748 << D->isInstanceMethod() << Name;
4749 Importer.ToDiag(FoundMethod->getLocation(),
4750 diag::note_odr_objc_method_here)
4751 << D->isInstanceMethod() << Name;
4752
4753 return make_error<ASTImportError>(ASTImportError::NameConflict);
4754 }
4755
4756 // FIXME: Any other bits we need to merge?
4757 return Importer.MapImported(D, FoundMethod);
4758 }
4759 }
4760
4761 Error Err = Error::success();
4762 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4763 auto ToReturnType = importChecked(Err, D->getReturnType());
4764 auto ToReturnTypeSourceInfo =
4766 if (Err)
4767 return std::move(Err);
4768
4769 ObjCMethodDecl *ToMethod;
4770 if (GetImportedOrCreateDecl(
4771 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4772 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4776 return ToMethod;
4777
4778 // FIXME: When we decide to merge method definitions, we'll need to
4779 // deal with implicit parameters.
4780
4781 // Import the parameters
4783 for (auto *FromP : D->parameters()) {
4784 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4785 ToParams.push_back(*ToPOrErr);
4786 else
4787 return ToPOrErr.takeError();
4788 }
4789
4790 // Set the parameters.
4791 for (auto *ToParam : ToParams) {
4792 ToParam->setOwningFunction(ToMethod);
4793 ToMethod->addDeclInternal(ToParam);
4794 }
4795
4797 D->getSelectorLocs(FromSelLocs);
4798 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4799 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4800 return std::move(Err);
4801
4802 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4803
4804 ToMethod->setLexicalDeclContext(LexicalDC);
4805 LexicalDC->addDeclInternal(ToMethod);
4806
4807 // Implicit params are declared when Sema encounters the definition but this
4808 // never happens when the method is imported. Manually declare the implicit
4809 // params now that the MethodDecl knows its class interface.
4810 if (D->getSelfDecl())
4811 ToMethod->createImplicitParams(Importer.getToContext(),
4812 ToMethod->getClassInterface());
4813
4814 return ToMethod;
4815}
4816
4818 // Import the major distinguishing characteristics of a category.
4819 DeclContext *DC, *LexicalDC;
4820 DeclarationName Name;
4821 SourceLocation Loc;
4822 NamedDecl *ToD;
4823 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4824 return std::move(Err);
4825 if (ToD)
4826 return ToD;
4827
4828 Error Err = Error::success();
4829 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4830 auto ToLocation = importChecked(Err, D->getLocation());
4831 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4832 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4833 if (Err)
4834 return std::move(Err);
4835
4837 if (GetImportedOrCreateDecl(
4838 Result, D, Importer.getToContext(), DC, D->getVariance(),
4839 ToVarianceLoc, D->getIndex(),
4840 ToLocation, Name.getAsIdentifierInfo(),
4841 ToColonLoc, ToTypeSourceInfo))
4842 return Result;
4843
4844 // Only import 'ObjCTypeParamType' after the decl is created.
4845 auto ToTypeForDecl = importChecked(Err, D->getTypeForDecl());
4846 if (Err)
4847 return std::move(Err);
4848 Result->setTypeForDecl(ToTypeForDecl);
4849 Result->setLexicalDeclContext(LexicalDC);
4850 return Result;
4851}
4852
4854 // Import the major distinguishing characteristics of a category.
4855 DeclContext *DC, *LexicalDC;
4856 DeclarationName Name;
4857 SourceLocation Loc;
4858 NamedDecl *ToD;
4859 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4860 return std::move(Err);
4861 if (ToD)
4862 return ToD;
4863
4864 ObjCInterfaceDecl *ToInterface;
4865 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4866 return std::move(Err);
4867
4868 // Determine if we've already encountered this category.
4869 ObjCCategoryDecl *MergeWithCategory
4870 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4871 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4872 if (!ToCategory) {
4873
4874 Error Err = Error::success();
4875 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4876 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4877 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4878 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4879 if (Err)
4880 return std::move(Err);
4881
4882 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4883 ToAtStartLoc, Loc,
4884 ToCategoryNameLoc,
4885 Name.getAsIdentifierInfo(), ToInterface,
4886 /*TypeParamList=*/nullptr,
4887 ToIvarLBraceLoc,
4888 ToIvarRBraceLoc))
4889 return ToCategory;
4890
4891 ToCategory->setLexicalDeclContext(LexicalDC);
4892 LexicalDC->addDeclInternal(ToCategory);
4893 // Import the type parameter list after MapImported, to avoid
4894 // loops when bringing in their DeclContext.
4895 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4896 ToCategory->setTypeParamList(*PListOrErr);
4897 else
4898 return PListOrErr.takeError();
4899
4900 // Import protocols
4902 SmallVector<SourceLocation, 4> ProtocolLocs;
4904 = D->protocol_loc_begin();
4906 FromProtoEnd = D->protocol_end();
4907 FromProto != FromProtoEnd;
4908 ++FromProto, ++FromProtoLoc) {
4909 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4910 Protocols.push_back(*ToProtoOrErr);
4911 else
4912 return ToProtoOrErr.takeError();
4913
4914 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4915 ProtocolLocs.push_back(*ToProtoLocOrErr);
4916 else
4917 return ToProtoLocOrErr.takeError();
4918 }
4919
4920 // FIXME: If we're merging, make sure that the protocol list is the same.
4921 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4922 ProtocolLocs.data(), Importer.getToContext());
4923
4924 } else {
4925 Importer.MapImported(D, ToCategory);
4926 }
4927
4928 // Import all of the members of this category.
4929 if (Error Err = ImportDeclContext(D))
4930 return std::move(Err);
4931
4932 // If we have an implementation, import it as well.
4933 if (D->getImplementation()) {
4934 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4935 import(D->getImplementation()))
4936 ToCategory->setImplementation(*ToImplOrErr);
4937 else
4938 return ToImplOrErr.takeError();
4939 }
4940
4941 return ToCategory;
4942}
4943
4946 if (To->getDefinition()) {
4948 if (Error Err = ImportDeclContext(From))
4949 return Err;
4950 return Error::success();
4951 }
4952
4953 // Start the protocol definition
4954 To->startDefinition();
4955
4956 // Import protocols
4958 SmallVector<SourceLocation, 4> ProtocolLocs;
4960 From->protocol_loc_begin();
4961 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4962 FromProtoEnd = From->protocol_end();
4963 FromProto != FromProtoEnd;
4964 ++FromProto, ++FromProtoLoc) {
4965 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4966 Protocols.push_back(*ToProtoOrErr);
4967 else
4968 return ToProtoOrErr.takeError();
4969
4970 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4971 ProtocolLocs.push_back(*ToProtoLocOrErr);
4972 else
4973 return ToProtoLocOrErr.takeError();
4974
4975 }
4976
4977 // FIXME: If we're merging, make sure that the protocol list is the same.
4978 To->setProtocolList(Protocols.data(), Protocols.size(),
4979 ProtocolLocs.data(), Importer.getToContext());
4980
4981 if (shouldForceImportDeclContext(Kind)) {
4982 // Import all of the members of this protocol.
4983 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4984 return Err;
4985 }
4986 return Error::success();
4987}
4988
4990 // If this protocol has a definition in the translation unit we're coming
4991 // from, but this particular declaration is not that definition, import the
4992 // definition and map to that.
4994 if (Definition && Definition != D) {
4995 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4996 return Importer.MapImported(D, *ImportedDefOrErr);
4997 else
4998 return ImportedDefOrErr.takeError();
4999 }
5000
5001 // Import the major distinguishing characteristics of a protocol.
5002 DeclContext *DC, *LexicalDC;
5003 DeclarationName Name;
5004 SourceLocation Loc;
5005 NamedDecl *ToD;
5006 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5007 return std::move(Err);
5008 if (ToD)
5009 return ToD;
5010
5011 ObjCProtocolDecl *MergeWithProtocol = nullptr;
5012 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5013 for (auto *FoundDecl : FoundDecls) {
5015 continue;
5016
5017 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
5018 break;
5019 }
5020
5021 ObjCProtocolDecl *ToProto = MergeWithProtocol;