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