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/APSInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/ScopeExit.h"
61#include "llvm/ADT/SmallVector.h"
62#include "llvm/Support/Casting.h"
63#include "llvm/Support/ErrorHandling.h"
64#include "llvm/Support/MemoryBuffer.h"
65#include <algorithm>
66#include <cassert>
67#include <cstddef>
68#include <memory>
69#include <optional>
70#include <type_traits>
71#include <utility>
72
73namespace clang {
74
75 using llvm::make_error;
76 using llvm::Error;
77 using llvm::Expected;
85
86 std::string ASTImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
95 }
96 llvm_unreachable("Invalid error code.");
97 return "Invalid error code.";
98 }
99
100 void ASTImportError::log(raw_ostream &OS) const { OS << toString(); }
101
102 std::error_code ASTImportError::convertToErrorCode() const {
103 llvm_unreachable("Function not implemented.");
104 }
105
107
108 template <class T>
112 for (auto *R : D->getFirstDecl()->redecls()) {
113 if (R != D->getFirstDecl())
114 Redecls.push_back(R);
115 }
116 Redecls.push_back(D->getFirstDecl());
117 std::reverse(Redecls.begin(), Redecls.end());
118 return Redecls;
119 }
120
122 if (auto *FD = dyn_cast<FunctionDecl>(D))
123 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
124 if (auto *VD = dyn_cast<VarDecl>(D))
125 return getCanonicalForwardRedeclChain<VarDecl>(VD);
126 if (auto *TD = dyn_cast<TagDecl>(D))
127 return getCanonicalForwardRedeclChain<TagDecl>(TD);
128 llvm_unreachable("Bad declaration kind");
129 }
130
131 void updateFlags(const Decl *From, Decl *To) {
132 // Check if some flags or attrs are new in 'From' and copy into 'To'.
133 // FIXME: Other flags or attrs?
134 if (From->isUsed(false) && !To->isUsed(false))
135 To->setIsUsed();
136 }
137
138 /// How to handle import errors that occur when import of a child declaration
139 /// of a DeclContext fails.
141 /// This context is imported (in the 'from' domain).
142 /// It is nullptr if a non-DeclContext is imported.
143 const DeclContext *const FromDC;
144 /// Ignore import errors of the children.
145 /// If true, the context can be imported successfully if a child
146 /// of it failed to import. Otherwise the import errors of the child nodes
147 /// are accumulated (joined) into the import error object of the parent.
148 /// (Import of a parent can fail in other ways.)
149 bool const IgnoreChildErrors;
150
151 public:
153 : FromDC(FromDC), IgnoreChildErrors(!isa<TagDecl>(FromDC)) {}
155 : FromDC(dyn_cast<DeclContext>(FromD)),
156 IgnoreChildErrors(!isa<TagDecl>(FromD)) {}
157
158 /// Process the import result of a child (of the current declaration).
159 /// \param ResultErr The import error that can be used as result of
160 /// importing the parent. This may be changed by the function.
161 /// \param ChildErr Result of importing a child. Can be success or error.
162 void handleChildImportResult(Error &ResultErr, Error &&ChildErr) {
163 if (ChildErr && !IgnoreChildErrors)
164 ResultErr = joinErrors(std::move(ResultErr), std::move(ChildErr));
165 else
166 consumeError(std::move(ChildErr));
167 }
168
169 /// Determine if import failure of a child does not cause import failure of
170 /// its parent.
171 bool ignoreChildErrorOnParent(Decl *FromChildD) const {
172 if (!IgnoreChildErrors || !FromDC)
173 return false;
174 return FromDC->containsDecl(FromChildD);
175 }
176 };
177
178 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
179 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
180 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
181 ASTImporter &Importer;
182
183 // Use this instead of Importer.importInto .
184 template <typename ImportT>
185 [[nodiscard]] Error importInto(ImportT &To, const ImportT &From) {
186 return Importer.importInto(To, From);
187 }
188
189 // Use this to import pointers of specific type.
190 template <typename ImportT>
191 [[nodiscard]] Error importInto(ImportT *&To, ImportT *From) {
192 auto ToOrErr = Importer.Import(From);
193 if (ToOrErr)
194 To = cast_or_null<ImportT>(*ToOrErr);
195 return ToOrErr.takeError();
196 }
197
198 // Call the import function of ASTImporter for a baseclass of type `T` and
199 // cast the return value to `T`.
200 template <typename T>
201 auto import(T *From)
202 -> std::conditional_t<std::is_base_of_v<Type, T>, Expected<const T *>,
204 auto ToOrErr = Importer.Import(From);
205 if (!ToOrErr)
206 return ToOrErr.takeError();
207 return cast_or_null<T>(*ToOrErr);
208 }
209
210 template <typename T>
211 auto import(const T *From) {
212 return import(const_cast<T *>(From));
213 }
214
215 // Call the import function of ASTImporter for type `T`.
216 template <typename T>
217 Expected<T> import(const T &From) {
218 return Importer.Import(From);
219 }
220
221 // Import an std::optional<T> by importing the contained T, if any.
222 template <typename T>
223 Expected<std::optional<T>> import(std::optional<T> From) {
224 if (!From)
225 return std::nullopt;
226 return import(*From);
227 }
228
229 ExplicitSpecifier importExplicitSpecifier(Error &Err,
230 ExplicitSpecifier ESpec);
231
232 // Wrapper for an overload set.
233 template <typename ToDeclT> struct CallOverloadedCreateFun {
234 template <typename... Args> decltype(auto) operator()(Args &&... args) {
235 return ToDeclT::Create(std::forward<Args>(args)...);
236 }
237 };
238
239 // Always use these functions to create a Decl during import. There are
240 // certain tasks which must be done after the Decl was created, e.g. we
241 // must immediately register that as an imported Decl. The parameter `ToD`
242 // will be set to the newly created Decl or if had been imported before
243 // then to the already imported Decl. Returns a bool value set to true if
244 // the `FromD` had been imported before.
245 template <typename ToDeclT, typename FromDeclT, typename... Args>
246 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
247 Args &&...args) {
248 // There may be several overloads of ToDeclT::Create. We must make sure
249 // to call the one which would be chosen by the arguments, thus we use a
250 // wrapper for the overload set.
251 CallOverloadedCreateFun<ToDeclT> OC;
252 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
253 std::forward<Args>(args)...);
254 }
255 // Use this overload if a special Type is needed to be created. E.g if we
256 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
257 // then:
258 // TypedefNameDecl *ToTypedef;
259 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
260 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
261 typename... Args>
262 [[nodiscard]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
263 Args &&...args) {
264 CallOverloadedCreateFun<NewDeclT> OC;
265 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
266 std::forward<Args>(args)...);
267 }
268 // Use this version if a special create function must be
269 // used, e.g. CXXRecordDecl::CreateLambda .
270 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
271 typename... Args>
272 [[nodiscard]] bool
273 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
274 FromDeclT *FromD, Args &&...args) {
275 if (Importer.getImportDeclErrorIfAny(FromD)) {
276 ToD = nullptr;
277 return true; // Already imported but with error.
278 }
279 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
280 if (ToD)
281 return true; // Already imported.
282 ToD = CreateFun(std::forward<Args>(args)...);
283 // Keep track of imported Decls.
284 Importer.RegisterImportedDecl(FromD, ToD);
285 Importer.SharedState->markAsNewDecl(ToD);
286 InitializeImportedDecl(FromD, ToD);
287 return false; // A new Decl is created.
288 }
289
290 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
291 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
292 if (FromD->isUsed())
293 ToD->setIsUsed();
294 if (FromD->isImplicit())
295 ToD->setImplicit();
296 }
297
298 // Check if we have found an existing definition. Returns with that
299 // definition if yes, otherwise returns null.
300 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
301 const FunctionDecl *Definition = nullptr;
302 if (D->doesThisDeclarationHaveABody() &&
303 FoundFunction->hasBody(Definition))
304 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
305 return nullptr;
306 }
307
308 void addDeclToContexts(Decl *FromD, Decl *ToD) {
309 if (Importer.isMinimalImport()) {
310 // In minimal import case the decl must be added even if it is not
311 // contained in original context, for LLDB compatibility.
312 // FIXME: Check if a better solution is possible.
313 if (!FromD->getDescribedTemplate() &&
314 FromD->getFriendObjectKind() == Decl::FOK_None)
316 return;
317 }
318
319 DeclContext *FromDC = FromD->getDeclContext();
320 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
321 DeclContext *ToDC = ToD->getDeclContext();
322 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
323
324 bool Visible = false;
325 if (FromDC->containsDeclAndLoad(FromD)) {
326 ToDC->addDeclInternal(ToD);
327 Visible = true;
328 }
329 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
330 ToLexicalDC->addDeclInternal(ToD);
331 Visible = true;
332 }
333
334 // If the Decl was added to any context, it was made already visible.
335 // Otherwise it is still possible that it should be visible.
336 if (!Visible) {
337 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
338 auto *ToNamed = cast<NamedDecl>(ToD);
339 DeclContextLookupResult FromLookup =
340 FromDC->lookup(FromNamed->getDeclName());
341 if (llvm::is_contained(FromLookup, FromNamed))
342 ToDC->makeDeclVisibleInContext(ToNamed);
343 }
344 }
345 }
346
347 void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
348 DeclContext *OldDC) {
349 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
350 if (!LT)
351 return;
352
353 for (NamedDecl *TP : Params)
354 LT->update(TP, OldDC);
355 }
356
357 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
358 updateLookupTableForTemplateParameters(
359 Params, Importer.getToContext().getTranslationUnitDecl());
360 }
361
362 public:
363 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
364
368
369 // Importing types
371#define TYPE(Class, Base) \
372 ExpectedType Visit##Class##Type(const Class##Type *T);
373#include "clang/AST/TypeNodes.inc"
374
375 // Importing declarations
378 Error ImportDeclParts(
379 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
381 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
384 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
385 Error ImportDeclContext(
386 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
387 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
388
389 Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To);
391 Expected<APValue> ImportAPValue(const APValue &FromValue);
392
394
395 /// What we should import from the definition.
397 /// Import the default subset of the definition, which might be
398 /// nothing (if minimal import is set) or might be everything (if minimal
399 /// import is not set).
401 /// Import everything.
403 /// Import only the bare bones needed to establish a valid
404 /// DeclContext.
406 };
407
409 return IDK == IDK_Everything ||
410 (IDK == IDK_Default && !Importer.isMinimalImport());
411 }
412
413 Error ImportInitializer(VarDecl *From, VarDecl *To);
414 Error ImportDefinition(
415 RecordDecl *From, RecordDecl *To,
417 Error ImportDefinition(
418 EnumDecl *From, EnumDecl *To,
420 Error ImportDefinition(
423 Error ImportDefinition(
430
431 template <typename InContainerTy>
433 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
434
435 template<typename InContainerTy>
437 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
438 const InContainerTy &Container, TemplateArgumentListInfo &Result);
439
442 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
445 FunctionDecl *FromFD);
446
447 template <typename DeclTy>
448 Error ImportTemplateParameterLists(const DeclTy *FromD, DeclTy *ToD);
449
451
453
454 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
455 ParmVarDecl *ToParam);
456
459
460 template <typename T>
462
463 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain = true,
464 bool IgnoreTemplateParmDepth = false);
511
514
529
530 // Importing statements
550 // FIXME: MSAsmStmt
551 // FIXME: SEHExceptStmt
552 // FIXME: SEHFinallyStmt
553 // FIXME: SEHTryStmt
554 // FIXME: SEHLeaveStmt
555 // FIXME: CapturedStmt
559 // FIXME: MSDependentExistsStmt
567
568 // Importing expressions
645
646 // Helper for chaining together multiple imports. If an error is detected,
647 // subsequent imports will return default constructed nodes, so that failure
648 // can be detected with a single conditional branch after a sequence of
649 // imports.
650 template <typename T> T importChecked(Error &Err, const T &From) {
651 // Don't attempt to import nodes if we hit an error earlier.
652 if (Err)
653 return T{};
654 Expected<T> MaybeVal = import(From);
655 if (!MaybeVal) {
656 Err = MaybeVal.takeError();
657 return T{};
658 }
659 return *MaybeVal;
660 }
661
662 template<typename IIter, typename OIter>
663 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
664 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
665 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
666 Expected<ItemT> ToOrErr = import(*Ibegin);
667 if (!ToOrErr)
668 return ToOrErr.takeError();
669 *Obegin = *ToOrErr;
670 }
671 return Error::success();
672 }
673
674 // Import every item from a container structure into an output container.
675 // If error occurs, stops at first error and returns the error.
676 // The output container should have space for all needed elements (it is not
677 // expanded, new items are put into from the beginning).
678 template<typename InContainerTy, typename OutContainerTy>
680 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
681 return ImportArrayChecked(
682 InContainer.begin(), InContainer.end(), OutContainer.begin());
683 }
684
685 template<typename InContainerTy, typename OIter>
686 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
687 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
688 }
689
691 CXXMethodDecl *FromMethod);
692
694 FunctionDecl *FromFD);
695
696 // Returns true if the given function has a placeholder return type and
697 // that type is declared inside the body of the function.
698 // E.g. auto f() { struct X{}; return X(); }
700 };
701
702template <typename InContainerTy>
704 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
705 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
706 auto ToLAngleLocOrErr = import(FromLAngleLoc);
707 if (!ToLAngleLocOrErr)
708 return ToLAngleLocOrErr.takeError();
709 auto ToRAngleLocOrErr = import(FromRAngleLoc);
710 if (!ToRAngleLocOrErr)
711 return ToRAngleLocOrErr.takeError();
712
713 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
714 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
715 return Err;
716 Result = ToTAInfo;
717 return Error::success();
718}
719
720template <>
721Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
724 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
725}
726
727template <>
730 const ASTTemplateArgumentListInfo &From,
732 return ImportTemplateArgumentListInfo(
733 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
734}
735
738 FunctionDecl *FromFD) {
739 assert(FromFD->getTemplatedKind() ==
741
743
744 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
745 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
746 return std::move(Err);
747
748 // Import template arguments.
749 if (Error Err = ImportTemplateArguments(FTSInfo->TemplateArguments->asArray(),
750 std::get<1>(Result)))
751 return std::move(Err);
752
753 return Result;
754}
755
756template <>
758ASTNodeImporter::import(TemplateParameterList *From) {
760 if (Error Err = ImportContainerChecked(*From, To))
761 return std::move(Err);
762
763 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
764 if (!ToRequiresClause)
765 return ToRequiresClause.takeError();
766
767 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
768 if (!ToTemplateLocOrErr)
769 return ToTemplateLocOrErr.takeError();
770 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
771 if (!ToLAngleLocOrErr)
772 return ToLAngleLocOrErr.takeError();
773 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
774 if (!ToRAngleLocOrErr)
775 return ToRAngleLocOrErr.takeError();
776
778 Importer.getToContext(),
779 *ToTemplateLocOrErr,
780 *ToLAngleLocOrErr,
781 To,
782 *ToRAngleLocOrErr,
783 *ToRequiresClause);
784}
785
786template <>
788ASTNodeImporter::import(const TemplateArgument &From) {
789 switch (From.getKind()) {
791 return TemplateArgument();
792
794 ExpectedType ToTypeOrErr = import(From.getAsType());
795 if (!ToTypeOrErr)
796 return ToTypeOrErr.takeError();
797 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ false,
798 From.getIsDefaulted());
799 }
800
802 ExpectedType ToTypeOrErr = import(From.getIntegralType());
803 if (!ToTypeOrErr)
804 return ToTypeOrErr.takeError();
805 return TemplateArgument(From, *ToTypeOrErr);
806 }
807
809 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
810 if (!ToOrErr)
811 return ToOrErr.takeError();
812 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
813 if (!ToTypeOrErr)
814 return ToTypeOrErr.takeError();
815 return TemplateArgument(dyn_cast<ValueDecl>((*ToOrErr)->getCanonicalDecl()),
816 *ToTypeOrErr, From.getIsDefaulted());
817 }
818
820 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
821 if (!ToTypeOrErr)
822 return ToTypeOrErr.takeError();
823 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/ true,
824 From.getIsDefaulted());
825 }
826
828 ExpectedType ToTypeOrErr = import(From.getStructuralValueType());
829 if (!ToTypeOrErr)
830 return ToTypeOrErr.takeError();
831 Expected<APValue> ToValueOrErr = import(From.getAsStructuralValue());
832 if (!ToValueOrErr)
833 return ToValueOrErr.takeError();
834 return TemplateArgument(Importer.getToContext(), *ToTypeOrErr,
835 *ToValueOrErr);
836 }
837
839 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
840 if (!ToTemplateOrErr)
841 return ToTemplateOrErr.takeError();
842
843 return TemplateArgument(*ToTemplateOrErr, From.getIsDefaulted());
844 }
845
847 Expected<TemplateName> ToTemplateOrErr =
848 import(From.getAsTemplateOrTemplatePattern());
849 if (!ToTemplateOrErr)
850 return ToTemplateOrErr.takeError();
851
852 return TemplateArgument(*ToTemplateOrErr, From.getNumTemplateExpansions(),
853 From.getIsDefaulted());
854 }
855
857 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
858 return TemplateArgument(*ToExpr, From.getIsDefaulted());
859 else
860 return ToExpr.takeError();
861
864 ToPack.reserve(From.pack_size());
865 if (Error Err = ImportTemplateArguments(From.pack_elements(), ToPack))
866 return std::move(Err);
867
868 return TemplateArgument(
869 llvm::ArrayRef(ToPack).copy(Importer.getToContext()));
870 }
871 }
872
873 llvm_unreachable("Invalid template argument kind");
874}
875
876template <>
878ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
879 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
880 if (!ArgOrErr)
881 return ArgOrErr.takeError();
882 TemplateArgument Arg = *ArgOrErr;
883
884 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
885
888 ExpectedExpr E = import(FromInfo.getAsExpr());
889 if (!E)
890 return E.takeError();
891 ToInfo = TemplateArgumentLocInfo(*E);
892 } else if (Arg.getKind() == TemplateArgument::Type) {
893 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
894 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
895 else
896 return TSIOrErr.takeError();
897 } else {
898 auto ToTemplateQualifierLocOrErr =
899 import(FromInfo.getTemplateQualifierLoc());
900 if (!ToTemplateQualifierLocOrErr)
901 return ToTemplateQualifierLocOrErr.takeError();
902 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
903 if (!ToTemplateNameLocOrErr)
904 return ToTemplateNameLocOrErr.takeError();
905 auto ToTemplateEllipsisLocOrErr =
906 import(FromInfo.getTemplateEllipsisLoc());
907 if (!ToTemplateEllipsisLocOrErr)
908 return ToTemplateEllipsisLocOrErr.takeError();
910 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
911 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
912 }
913
914 return TemplateArgumentLoc(Arg, ToInfo);
915}
916
917template <>
918Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
919 if (DG.isNull())
920 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
921 size_t NumDecls = DG.end() - DG.begin();
923 ToDecls.reserve(NumDecls);
924 for (Decl *FromD : DG) {
925 if (auto ToDOrErr = import(FromD))
926 ToDecls.push_back(*ToDOrErr);
927 else
928 return ToDOrErr.takeError();
929 }
930 return DeclGroupRef::Create(Importer.getToContext(),
931 ToDecls.begin(),
932 NumDecls);
933}
934
935template <>
937ASTNodeImporter::import(const Designator &D) {
938 if (D.isFieldDesignator()) {
939 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
940
941 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
942 if (!ToDotLocOrErr)
943 return ToDotLocOrErr.takeError();
944
945 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
946 if (!ToFieldLocOrErr)
947 return ToFieldLocOrErr.takeError();
948
950 ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
951 }
952
953 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
954 if (!ToLBracketLocOrErr)
955 return ToLBracketLocOrErr.takeError();
956
957 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
958 if (!ToRBracketLocOrErr)
959 return ToRBracketLocOrErr.takeError();
960
961 if (D.isArrayDesignator())
962 return Designator::CreateArrayDesignator(D.getArrayIndex(),
963 *ToLBracketLocOrErr,
964 *ToRBracketLocOrErr);
965
966 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
967 if (!ToEllipsisLocOrErr)
968 return ToEllipsisLocOrErr.takeError();
969
970 assert(D.isArrayRangeDesignator());
972 D.getArrayIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
973 *ToRBracketLocOrErr);
974}
975
976template <>
977Expected<ConceptReference *> ASTNodeImporter::import(ConceptReference *From) {
978 Error Err = Error::success();
979 auto ToNNS = importChecked(Err, From->getNestedNameSpecifierLoc());
980 auto ToTemplateKWLoc = importChecked(Err, From->getTemplateKWLoc());
981 auto ToConceptNameLoc =
983 auto ToConceptName = importChecked(Err, From->getConceptNameInfo().getName());
984 auto ToFoundDecl = importChecked(Err, From->getFoundDecl());
985 auto ToNamedConcept = importChecked(Err, From->getNamedConcept());
986 if (Err)
987 return std::move(Err);
989 const auto *ASTTemplateArgs = From->getTemplateArgsAsWritten();
990 if (ASTTemplateArgs)
991 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo))
992 return std::move(Err);
993 auto *ConceptRef = ConceptReference::Create(
994 Importer.getToContext(), ToNNS, ToTemplateKWLoc,
995 DeclarationNameInfo(ToConceptName, ToConceptNameLoc), ToFoundDecl,
996 ToNamedConcept,
997 ASTTemplateArgs ? ASTTemplateArgumentListInfo::Create(
998 Importer.getToContext(), ToTAInfo)
999 : nullptr);
1000 return ConceptRef;
1001}
1002
1003template <>
1004Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
1005 ValueDecl *Var = nullptr;
1006 if (From.capturesVariable()) {
1007 if (auto VarOrErr = import(From.getCapturedVar()))
1008 Var = *VarOrErr;
1009 else
1010 return VarOrErr.takeError();
1011 }
1012
1013 auto LocationOrErr = import(From.getLocation());
1014 if (!LocationOrErr)
1015 return LocationOrErr.takeError();
1016
1017 SourceLocation EllipsisLoc;
1018 if (From.isPackExpansion())
1019 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
1020 return std::move(Err);
1021
1022 return LambdaCapture(
1023 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
1024 EllipsisLoc);
1025}
1026
1027template <typename T>
1029 if (Found->getLinkageInternal() != From->getLinkageInternal())
1030 return false;
1031
1032 if (From->hasExternalFormalLinkage())
1033 return Found->hasExternalFormalLinkage();
1034 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1035 return false;
1036 if (From->isInAnonymousNamespace())
1037 return Found->isInAnonymousNamespace();
1038 else
1039 return !Found->isInAnonymousNamespace() &&
1040 !Found->hasExternalFormalLinkage();
1041}
1042
1043template <>
1045 TypedefNameDecl *From) {
1046 if (Found->getLinkageInternal() != From->getLinkageInternal())
1047 return false;
1048
1049 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1050 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1051 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1052}
1053
1054} // namespace clang
1055
1056//----------------------------------------------------------------------------
1057// Import Types
1058//----------------------------------------------------------------------------
1059
1060using namespace clang;
1061
1063 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1064 << T->getTypeClassName();
1065 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1066}
1067
1068ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1069 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1070 if (!UnderlyingTypeOrErr)
1071 return UnderlyingTypeOrErr.takeError();
1072
1073 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1074}
1075
1076ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1077 switch (T->getKind()) {
1078#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1079 case BuiltinType::Id: \
1080 return Importer.getToContext().SingletonId;
1081#include "clang/Basic/OpenCLImageTypes.def"
1082#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1083 case BuiltinType::Id: \
1084 return Importer.getToContext().Id##Ty;
1085#include "clang/Basic/OpenCLExtensionTypes.def"
1086#define SVE_TYPE(Name, Id, SingletonId) \
1087 case BuiltinType::Id: \
1088 return Importer.getToContext().SingletonId;
1089#include "clang/Basic/AArch64SVEACLETypes.def"
1090#define PPC_VECTOR_TYPE(Name, Id, Size) \
1091 case BuiltinType::Id: \
1092 return Importer.getToContext().Id##Ty;
1093#include "clang/Basic/PPCTypes.def"
1094#define RVV_TYPE(Name, Id, SingletonId) \
1095 case BuiltinType::Id: \
1096 return Importer.getToContext().SingletonId;
1097#include "clang/Basic/RISCVVTypes.def"
1098#define WASM_TYPE(Name, Id, SingletonId) \
1099 case BuiltinType::Id: \
1100 return Importer.getToContext().SingletonId;
1101#include "clang/Basic/WebAssemblyReferenceTypes.def"
1102#define AMDGPU_TYPE(Name, Id, SingletonId) \
1103 case BuiltinType::Id: \
1104 return Importer.getToContext().SingletonId;
1105#include "clang/Basic/AMDGPUTypes.def"
1106#define SHARED_SINGLETON_TYPE(Expansion)
1107#define BUILTIN_TYPE(Id, SingletonId) \
1108 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1109#include "clang/AST/BuiltinTypes.def"
1110
1111 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1112 // context supports C++.
1113
1114 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1115 // context supports ObjC.
1116
1117 case BuiltinType::Char_U:
1118 // The context we're importing from has an unsigned 'char'. If we're
1119 // importing into a context with a signed 'char', translate to
1120 // 'unsigned char' instead.
1121 if (Importer.getToContext().getLangOpts().CharIsSigned)
1122 return Importer.getToContext().UnsignedCharTy;
1123
1124 return Importer.getToContext().CharTy;
1125
1126 case BuiltinType::Char_S:
1127 // The context we're importing from has an unsigned 'char'. If we're
1128 // importing into a context with a signed 'char', translate to
1129 // 'unsigned char' instead.
1130 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1131 return Importer.getToContext().SignedCharTy;
1132
1133 return Importer.getToContext().CharTy;
1134
1135 case BuiltinType::WChar_S:
1136 case BuiltinType::WChar_U:
1137 // FIXME: If not in C++, shall we translate to the C equivalent of
1138 // wchar_t?
1139 return Importer.getToContext().WCharTy;
1140 }
1141
1142 llvm_unreachable("Invalid BuiltinType Kind!");
1143}
1144
1145ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1146 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1147 if (!ToOriginalTypeOrErr)
1148 return ToOriginalTypeOrErr.takeError();
1149
1150 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1151}
1152
1153ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1154 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1155 if (!ToElementTypeOrErr)
1156 return ToElementTypeOrErr.takeError();
1157
1158 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1159}
1160
1161ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1162 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1163 if (!ToPointeeTypeOrErr)
1164 return ToPointeeTypeOrErr.takeError();
1165
1166 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1167}
1168
1169ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1170 // FIXME: Check for blocks support in "to" context.
1171 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1172 if (!ToPointeeTypeOrErr)
1173 return ToPointeeTypeOrErr.takeError();
1174
1175 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1176}
1177
1179ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1180 // FIXME: Check for C++ support in "to" context.
1181 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1182 if (!ToPointeeTypeOrErr)
1183 return ToPointeeTypeOrErr.takeError();
1184
1185 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1186}
1187
1189ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1190 // FIXME: Check for C++0x support in "to" context.
1191 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1192 if (!ToPointeeTypeOrErr)
1193 return ToPointeeTypeOrErr.takeError();
1194
1195 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1196}
1197
1199ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1200 // FIXME: Check for C++ support in "to" context.
1201 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1202 if (!ToPointeeTypeOrErr)
1203 return ToPointeeTypeOrErr.takeError();
1204
1205 ExpectedTypePtr ClassTypeOrErr = import(T->getClass());
1206 if (!ClassTypeOrErr)
1207 return ClassTypeOrErr.takeError();
1208
1209 return Importer.getToContext().getMemberPointerType(*ToPointeeTypeOrErr,
1210 *ClassTypeOrErr);
1211}
1212
1214ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1215 Error Err = Error::success();
1216 auto ToElementType = importChecked(Err, T->getElementType());
1217 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1218 if (Err)
1219 return std::move(Err);
1220
1221 return Importer.getToContext().getConstantArrayType(
1222 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1223 T->getIndexTypeCVRQualifiers());
1224}
1225
1227ASTNodeImporter::VisitArrayParameterType(const ArrayParameterType *T) {
1228 ExpectedType ToArrayTypeOrErr = VisitConstantArrayType(T);
1229 if (!ToArrayTypeOrErr)
1230 return ToArrayTypeOrErr.takeError();
1231
1232 return Importer.getToContext().getArrayParameterType(*ToArrayTypeOrErr);
1233}
1234
1236ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1237 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1238 if (!ToElementTypeOrErr)
1239 return ToElementTypeOrErr.takeError();
1240
1241 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1242 T->getSizeModifier(),
1243 T->getIndexTypeCVRQualifiers());
1244}
1245
1247ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1248 Error Err = Error::success();
1249 QualType ToElementType = importChecked(Err, T->getElementType());
1250 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1251 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1252 if (Err)
1253 return std::move(Err);
1254 return Importer.getToContext().getVariableArrayType(
1255 ToElementType, ToSizeExpr, T->getSizeModifier(),
1256 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1257}
1258
1259ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1260 const DependentSizedArrayType *T) {
1261 Error Err = Error::success();
1262 QualType ToElementType = importChecked(Err, T->getElementType());
1263 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1264 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1265 if (Err)
1266 return std::move(Err);
1267 // SizeExpr may be null if size is not specified directly.
1268 // For example, 'int a[]'.
1269
1270 return Importer.getToContext().getDependentSizedArrayType(
1271 ToElementType, ToSizeExpr, T->getSizeModifier(),
1272 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1273}
1274
1275ExpectedType ASTNodeImporter::VisitDependentSizedExtVectorType(
1277 Error Err = Error::success();
1278 QualType ToElementType = importChecked(Err, T->getElementType());
1279 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1280 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1281 if (Err)
1282 return std::move(Err);
1284 ToElementType, ToSizeExpr, ToAttrLoc);
1285}
1286
1287ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1288 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1289 if (!ToElementTypeOrErr)
1290 return ToElementTypeOrErr.takeError();
1291
1292 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1293 T->getNumElements(),
1294 T->getVectorKind());
1295}
1296
1297ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1298 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1299 if (!ToElementTypeOrErr)
1300 return ToElementTypeOrErr.takeError();
1301
1302 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1303 T->getNumElements());
1304}
1305
1307ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1308 // FIXME: What happens if we're importing a function without a prototype
1309 // into C++? Should we make it variadic?
1310 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1311 if (!ToReturnTypeOrErr)
1312 return ToReturnTypeOrErr.takeError();
1313
1314 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1315 T->getExtInfo());
1316}
1317
1319ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1320 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1321 if (!ToReturnTypeOrErr)
1322 return ToReturnTypeOrErr.takeError();
1323
1324 // Import argument types
1325 SmallVector<QualType, 4> ArgTypes;
1326 for (const auto &A : T->param_types()) {
1327 ExpectedType TyOrErr = import(A);
1328 if (!TyOrErr)
1329 return TyOrErr.takeError();
1330 ArgTypes.push_back(*TyOrErr);
1331 }
1332
1333 // Import exception types
1334 SmallVector<QualType, 4> ExceptionTypes;
1335 for (const auto &E : T->exceptions()) {
1336 ExpectedType TyOrErr = import(E);
1337 if (!TyOrErr)
1338 return TyOrErr.takeError();
1339 ExceptionTypes.push_back(*TyOrErr);
1340 }
1341
1343 Error Err = Error::success();
1345 ToEPI.ExtInfo = FromEPI.ExtInfo;
1346 ToEPI.Variadic = FromEPI.Variadic;
1347 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1348 ToEPI.TypeQuals = FromEPI.TypeQuals;
1349 ToEPI.RefQualifier = FromEPI.RefQualifier;
1350 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1357 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1358
1359 if (Err)
1360 return std::move(Err);
1361
1362 return Importer.getToContext().getFunctionType(
1363 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1364}
1365
1366ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1367 const UnresolvedUsingType *T) {
1368 Error Err = Error::success();
1369 auto ToD = importChecked(Err, T->getDecl());
1370 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1371 if (Err)
1372 return std::move(Err);
1373
1374 return Importer.getToContext().getTypeDeclType(
1375 ToD, cast_or_null<TypeDecl>(ToPrevD));
1376}
1377
1378ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1379 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1380 if (!ToInnerTypeOrErr)
1381 return ToInnerTypeOrErr.takeError();
1382
1383 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1384}
1385
1387ASTNodeImporter::VisitPackIndexingType(clang::PackIndexingType const *T) {
1388
1389 ExpectedType Pattern = import(T->getPattern());
1390 if (!Pattern)
1391 return Pattern.takeError();
1392 ExpectedExpr Index = import(T->getIndexExpr());
1393 if (!Index)
1394 return Index.takeError();
1395 return Importer.getToContext().getPackIndexingType(*Pattern, *Index);
1396}
1397
1398ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1399 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1400 if (!ToDeclOrErr)
1401 return ToDeclOrErr.takeError();
1402
1403 TypedefNameDecl *ToDecl = *ToDeclOrErr;
1404 if (ToDecl->getTypeForDecl())
1405 return QualType(ToDecl->getTypeForDecl(), 0);
1406
1407 ExpectedType ToUnderlyingTypeOrErr = import(T->desugar());
1408 if (!ToUnderlyingTypeOrErr)
1409 return ToUnderlyingTypeOrErr.takeError();
1410
1411 return Importer.getToContext().getTypedefType(ToDecl, *ToUnderlyingTypeOrErr);
1412}
1413
1414ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1415 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1416 if (!ToExprOrErr)
1417 return ToExprOrErr.takeError();
1418 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr, T->getKind());
1419}
1420
1421ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1422 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnmodifiedType());
1423 if (!ToUnderlyingTypeOrErr)
1424 return ToUnderlyingTypeOrErr.takeError();
1425 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr,
1426 T->getKind());
1427}
1428
1429ExpectedType ASTNodeImporter::VisitUsingType(const UsingType *T) {
1430 Expected<UsingShadowDecl *> FoundOrErr = import(T->getFoundDecl());
1431 if (!FoundOrErr)
1432 return FoundOrErr.takeError();
1433 Expected<QualType> UnderlyingOrErr = import(T->getUnderlyingType());
1434 if (!UnderlyingOrErr)
1435 return UnderlyingOrErr.takeError();
1436
1437 return Importer.getToContext().getUsingType(*FoundOrErr, *UnderlyingOrErr);
1438}
1439
1440ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1441 // FIXME: Make sure that the "to" context supports C++0x!
1442 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1443 if (!ToExprOrErr)
1444 return ToExprOrErr.takeError();
1445
1446 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1447 if (!ToUnderlyingTypeOrErr)
1448 return ToUnderlyingTypeOrErr.takeError();
1449
1450 return Importer.getToContext().getDecltypeType(
1451 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1452}
1453
1455ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1456 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1457 if (!ToBaseTypeOrErr)
1458 return ToBaseTypeOrErr.takeError();
1459
1460 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1461 if (!ToUnderlyingTypeOrErr)
1462 return ToUnderlyingTypeOrErr.takeError();
1463
1464 return Importer.getToContext().getUnaryTransformType(
1465 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1466}
1467
1468ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1469 // FIXME: Make sure that the "to" context supports C++11!
1470 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1471 if (!ToDeducedTypeOrErr)
1472 return ToDeducedTypeOrErr.takeError();
1473
1474 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1475 if (!ToTypeConstraintConcept)
1476 return ToTypeConstraintConcept.takeError();
1477
1478 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1479 if (Error Err = ImportTemplateArguments(T->getTypeConstraintArguments(),
1480 ToTemplateArgs))
1481 return std::move(Err);
1482
1483 return Importer.getToContext().getAutoType(
1484 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1485 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1486 ToTemplateArgs);
1487}
1488
1489ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1491 // FIXME: Make sure that the "to" context supports C++17!
1492 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1493 if (!ToTemplateNameOrErr)
1494 return ToTemplateNameOrErr.takeError();
1495 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1496 if (!ToDeducedTypeOrErr)
1497 return ToDeducedTypeOrErr.takeError();
1498
1500 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1501}
1502
1503ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1504 const InjectedClassNameType *T) {
1505 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1506 if (!ToDeclOrErr)
1507 return ToDeclOrErr.takeError();
1508
1509 // The InjectedClassNameType is created in VisitRecordDecl when the
1510 // T->getDecl() is imported. Here we can return the existing type.
1511 const Type *Ty = (*ToDeclOrErr)->getTypeForDecl();
1512 assert(isa_and_nonnull<InjectedClassNameType>(Ty));
1513 return QualType(Ty, 0);
1514}
1515
1516ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1517 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1518 if (!ToDeclOrErr)
1519 return ToDeclOrErr.takeError();
1520
1521 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1522}
1523
1524ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1525 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1526 if (!ToDeclOrErr)
1527 return ToDeclOrErr.takeError();
1528
1529 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1530}
1531
1532ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1533 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1534 if (!ToModifiedTypeOrErr)
1535 return ToModifiedTypeOrErr.takeError();
1536 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1537 if (!ToEquivalentTypeOrErr)
1538 return ToEquivalentTypeOrErr.takeError();
1539
1540 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1541 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1542}
1543
1545ASTNodeImporter::VisitCountAttributedType(const CountAttributedType *T) {
1546 ExpectedType ToWrappedTypeOrErr = import(T->desugar());
1547 if (!ToWrappedTypeOrErr)
1548 return ToWrappedTypeOrErr.takeError();
1549
1550 Error Err = Error::success();
1551 Expr *CountExpr = importChecked(Err, T->getCountExpr());
1552
1554 for (const TypeCoupledDeclRefInfo &TI : T->dependent_decls()) {
1555 Expected<ValueDecl *> ToDeclOrErr = import(TI.getDecl());
1556 if (!ToDeclOrErr)
1557 return ToDeclOrErr.takeError();
1558 CoupledDecls.emplace_back(*ToDeclOrErr, TI.isDeref());
1559 }
1560
1561 return Importer.getToContext().getCountAttributedType(
1562 *ToWrappedTypeOrErr, CountExpr, T->isCountInBytes(), T->isOrNull(),
1563 ArrayRef(CoupledDecls.data(), CoupledDecls.size()));
1564}
1565
1566ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1567 const TemplateTypeParmType *T) {
1568 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1569 if (!ToDeclOrErr)
1570 return ToDeclOrErr.takeError();
1571
1572 return Importer.getToContext().getTemplateTypeParmType(
1573 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1574}
1575
1576ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1578 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1579 if (!ReplacedOrErr)
1580 return ReplacedOrErr.takeError();
1581
1582 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1583 if (!ToReplacementTypeOrErr)
1584 return ToReplacementTypeOrErr.takeError();
1585
1587 *ToReplacementTypeOrErr, *ReplacedOrErr, T->getIndex(),
1588 T->getPackIndex());
1589}
1590
1591ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmPackType(
1593 Expected<Decl *> ReplacedOrErr = import(T->getAssociatedDecl());
1594 if (!ReplacedOrErr)
1595 return ReplacedOrErr.takeError();
1596
1597 Expected<TemplateArgument> ToArgumentPack = import(T->getArgumentPack());
1598 if (!ToArgumentPack)
1599 return ToArgumentPack.takeError();
1600
1602 *ReplacedOrErr, T->getIndex(), T->getFinal(), *ToArgumentPack);
1603}
1604
1605ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1607 auto ToTemplateOrErr = import(T->getTemplateName());
1608 if (!ToTemplateOrErr)
1609 return ToTemplateOrErr.takeError();
1610
1611 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1612 if (Error Err =
1613 ImportTemplateArguments(T->template_arguments(), ToTemplateArgs))
1614 return std::move(Err);
1615
1616 QualType ToCanonType;
1617 if (!T->isCanonicalUnqualified()) {
1618 QualType FromCanonType
1619 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1620 if (ExpectedType TyOrErr = import(FromCanonType))
1621 ToCanonType = *TyOrErr;
1622 else
1623 return TyOrErr.takeError();
1624 }
1625 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1626 ToTemplateArgs,
1627 ToCanonType);
1628}
1629
1630ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1631 // Note: the qualifier in an ElaboratedType is optional.
1632 auto ToQualifierOrErr = import(T->getQualifier());
1633 if (!ToQualifierOrErr)
1634 return ToQualifierOrErr.takeError();
1635
1636 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1637 if (!ToNamedTypeOrErr)
1638 return ToNamedTypeOrErr.takeError();
1639
1640 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1641 if (!ToOwnedTagDeclOrErr)
1642 return ToOwnedTagDeclOrErr.takeError();
1643
1644 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1645 *ToQualifierOrErr,
1646 *ToNamedTypeOrErr,
1647 *ToOwnedTagDeclOrErr);
1648}
1649
1651ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1652 ExpectedType ToPatternOrErr = import(T->getPattern());
1653 if (!ToPatternOrErr)
1654 return ToPatternOrErr.takeError();
1655
1656 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1657 T->getNumExpansions(),
1658 /*ExpactPack=*/false);
1659}
1660
1661ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1663 auto ToQualifierOrErr = import(T->getQualifier());
1664 if (!ToQualifierOrErr)
1665 return ToQualifierOrErr.takeError();
1666
1667 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1668
1670 ToPack.reserve(T->template_arguments().size());
1671 if (Error Err = ImportTemplateArguments(T->template_arguments(), ToPack))
1672 return std::move(Err);
1673
1675 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1676}
1677
1679ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1680 auto ToQualifierOrErr = import(T->getQualifier());
1681 if (!ToQualifierOrErr)
1682 return ToQualifierOrErr.takeError();
1683
1684 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1685
1686 QualType Canon;
1687 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1688 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1689 Canon = (*TyOrErr).getCanonicalType();
1690 else
1691 return TyOrErr.takeError();
1692 }
1693
1694 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1695 *ToQualifierOrErr,
1696 Name, Canon);
1697}
1698
1700ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1701 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1702 if (!ToDeclOrErr)
1703 return ToDeclOrErr.takeError();
1704
1705 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1706}
1707
1708ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1709 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1710 if (!ToBaseTypeOrErr)
1711 return ToBaseTypeOrErr.takeError();
1712
1713 SmallVector<QualType, 4> TypeArgs;
1714 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1715 if (ExpectedType TyOrErr = import(TypeArg))
1716 TypeArgs.push_back(*TyOrErr);
1717 else
1718 return TyOrErr.takeError();
1719 }
1720
1722 for (auto *P : T->quals()) {
1723 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1724 Protocols.push_back(*ProtocolOrErr);
1725 else
1726 return ProtocolOrErr.takeError();
1727
1728 }
1729
1730 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1731 Protocols,
1732 T->isKindOfTypeAsWritten());
1733}
1734
1736ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1737 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1738 if (!ToPointeeTypeOrErr)
1739 return ToPointeeTypeOrErr.takeError();
1740
1741 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1742}
1743
1745ASTNodeImporter::VisitMacroQualifiedType(const MacroQualifiedType *T) {
1746 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1747 if (!ToUnderlyingTypeOrErr)
1748 return ToUnderlyingTypeOrErr.takeError();
1749
1750 IdentifierInfo *ToIdentifier = Importer.Import(T->getMacroIdentifier());
1751 return Importer.getToContext().getMacroQualifiedType(*ToUnderlyingTypeOrErr,
1752 ToIdentifier);
1753}
1754
1755ExpectedType clang::ASTNodeImporter::VisitAdjustedType(const AdjustedType *T) {
1756 Error Err = Error::success();
1757 QualType ToOriginalType = importChecked(Err, T->getOriginalType());
1758 QualType ToAdjustedType = importChecked(Err, T->getAdjustedType());
1759 if (Err)
1760 return std::move(Err);
1761
1762 return Importer.getToContext().getAdjustedType(ToOriginalType,
1763 ToAdjustedType);
1764}
1765
1766ExpectedType clang::ASTNodeImporter::VisitBitIntType(const BitIntType *T) {
1767 return Importer.getToContext().getBitIntType(T->isUnsigned(),
1768 T->getNumBits());
1769}
1770
1771ExpectedType clang::ASTNodeImporter::VisitBTFTagAttributedType(
1773 Error Err = Error::success();
1774 const BTFTypeTagAttr *ToBTFAttr = importChecked(Err, T->getAttr());
1775 QualType ToWrappedType = importChecked(Err, T->getWrappedType());
1776 if (Err)
1777 return std::move(Err);
1778
1779 return Importer.getToContext().getBTFTagAttributedType(ToBTFAttr,
1780 ToWrappedType);
1781}
1782
1783ExpectedType clang::ASTNodeImporter::VisitConstantMatrixType(
1785 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1786 if (!ToElementTypeOrErr)
1787 return ToElementTypeOrErr.takeError();
1788
1789 return Importer.getToContext().getConstantMatrixType(
1790 *ToElementTypeOrErr, T->getNumRows(), T->getNumColumns());
1791}
1792
1793ExpectedType clang::ASTNodeImporter::VisitDependentAddressSpaceType(
1795 Error Err = Error::success();
1796 QualType ToPointeeType = importChecked(Err, T->getPointeeType());
1797 Expr *ToAddrSpaceExpr = importChecked(Err, T->getAddrSpaceExpr());
1798 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1799 if (Err)
1800 return std::move(Err);
1801
1802 return Importer.getToContext().getDependentAddressSpaceType(
1803 ToPointeeType, ToAddrSpaceExpr, ToAttrLoc);
1804}
1805
1806ExpectedType clang::ASTNodeImporter::VisitDependentBitIntType(
1808 ExpectedExpr ToNumBitsExprOrErr = import(T->getNumBitsExpr());
1809 if (!ToNumBitsExprOrErr)
1810 return ToNumBitsExprOrErr.takeError();
1811 return Importer.getToContext().getDependentBitIntType(T->isUnsigned(),
1812 *ToNumBitsExprOrErr);
1813}
1814
1815ExpectedType clang::ASTNodeImporter::VisitDependentSizedMatrixType(
1817 Error Err = Error::success();
1818 QualType ToElementType = importChecked(Err, T->getElementType());
1819 Expr *ToRowExpr = importChecked(Err, T->getRowExpr());
1820 Expr *ToColumnExpr = importChecked(Err, T->getColumnExpr());
1821 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1822 if (Err)
1823 return std::move(Err);
1824
1825 return Importer.getToContext().getDependentSizedMatrixType(
1826 ToElementType, ToRowExpr, ToColumnExpr, ToAttrLoc);
1827}
1828
1829ExpectedType clang::ASTNodeImporter::VisitDependentVectorType(
1831 Error Err = Error::success();
1832 QualType ToElementType = importChecked(Err, T->getElementType());
1833 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1834 SourceLocation ToAttrLoc = importChecked(Err, T->getAttributeLoc());
1835 if (Err)
1836 return std::move(Err);
1837
1838 return Importer.getToContext().getDependentVectorType(
1839 ToElementType, ToSizeExpr, ToAttrLoc, T->getVectorKind());
1840}
1841
1842ExpectedType clang::ASTNodeImporter::VisitObjCTypeParamType(
1843 const clang::ObjCTypeParamType *T) {
1844 Expected<ObjCTypeParamDecl *> ToDeclOrErr = import(T->getDecl());
1845 if (!ToDeclOrErr)
1846 return ToDeclOrErr.takeError();
1847
1849 for (ObjCProtocolDecl *FromProtocol : T->getProtocols()) {
1850 Expected<ObjCProtocolDecl *> ToProtocolOrErr = import(FromProtocol);
1851 if (!ToProtocolOrErr)
1852 return ToProtocolOrErr.takeError();
1853 ToProtocols.push_back(*ToProtocolOrErr);
1854 }
1855
1856 return Importer.getToContext().getObjCTypeParamType(*ToDeclOrErr,
1857 ToProtocols);
1858}
1859
1860ExpectedType clang::ASTNodeImporter::VisitPipeType(const clang::PipeType *T) {
1861 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1862 if (!ToElementTypeOrErr)
1863 return ToElementTypeOrErr.takeError();
1864
1865 ASTContext &ToCtx = Importer.getToContext();
1866 if (T->isReadOnly())
1867 return ToCtx.getReadPipeType(*ToElementTypeOrErr);
1868 else
1869 return ToCtx.getWritePipeType(*ToElementTypeOrErr);
1870}
1871
1872//----------------------------------------------------------------------------
1873// Import Declarations
1874//----------------------------------------------------------------------------
1876 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1878 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1879 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1880 // FIXME: We could support these constructs by importing a different type of
1881 // this parameter and by importing the original type of the parameter only
1882 // after the FunctionDecl is created. See
1883 // VisitFunctionDecl::UsedDifferentProtoType.
1884 DeclContext *OrigDC = D->getDeclContext();
1885 FunctionDecl *FunDecl;
1886 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1887 FunDecl->hasBody()) {
1888 auto getLeafPointeeType = [](const Type *T) {
1889 while (T->isPointerType() || T->isArrayType()) {
1891 }
1892 return T;
1893 };
1894 for (const ParmVarDecl *P : FunDecl->parameters()) {
1895 const Type *LeafT =
1896 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1897 auto *RT = dyn_cast<RecordType>(LeafT);
1898 if (RT && RT->getDecl() == D) {
1899 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1900 << D->getDeclKindName();
1901 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
1902 }
1903 }
1904 }
1905
1906 // Import the context of this declaration.
1907 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1908 return Err;
1909
1910 // Import the name of this declaration.
1911 if (Error Err = importInto(Name, D->getDeclName()))
1912 return Err;
1913
1914 // Import the location of this declaration.
1915 if (Error Err = importInto(Loc, D->getLocation()))
1916 return Err;
1917
1918 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1919 if (ToD)
1920 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1921 return Err;
1922
1923 return Error::success();
1924}
1925
1927 NamedDecl *&ToD, SourceLocation &Loc) {
1928
1929 // Import the name of this declaration.
1930 if (Error Err = importInto(Name, D->getDeclName()))
1931 return Err;
1932
1933 // Import the location of this declaration.
1934 if (Error Err = importInto(Loc, D->getLocation()))
1935 return Err;
1936
1937 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1938 if (ToD)
1939 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1940 return Err;
1941
1942 return Error::success();
1943}
1944
1946 if (!FromD)
1947 return Error::success();
1948
1949 if (!ToD)
1950 if (Error Err = importInto(ToD, FromD))
1951 return Err;
1952
1953 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1954 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1955 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1956 !ToRecord->getDefinition()) {
1957 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1958 return Err;
1959 }
1960 }
1961 return Error::success();
1962 }
1963
1964 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1965 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1966 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1967 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1968 return Err;
1969 }
1970 }
1971 return Error::success();
1972 }
1973
1974 return Error::success();
1975}
1976
1977Error
1979 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1980 // NOTE: To.Name and To.Loc are already imported.
1981 // We only have to import To.LocInfo.
1982 switch (To.getName().getNameKind()) {
1989 return Error::success();
1990
1992 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1993 To.setCXXOperatorNameRange(*ToRangeOrErr);
1994 else
1995 return ToRangeOrErr.takeError();
1996 return Error::success();
1997 }
1999 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
2000 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
2001 else
2002 return LocOrErr.takeError();
2003 return Error::success();
2004 }
2008 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
2009 To.setNamedTypeInfo(*ToTInfoOrErr);
2010 else
2011 return ToTInfoOrErr.takeError();
2012 return Error::success();
2013 }
2014 }
2015 llvm_unreachable("Unknown name kind.");
2016}
2017
2018Error
2020 if (Importer.isMinimalImport() && !ForceImport) {
2021 auto ToDCOrErr = Importer.ImportContext(FromDC);
2022 return ToDCOrErr.takeError();
2023 }
2024
2025 // We use strict error handling in case of records and enums, but not
2026 // with e.g. namespaces.
2027 //
2028 // FIXME Clients of the ASTImporter should be able to choose an
2029 // appropriate error handling strategy for their needs. For instance,
2030 // they may not want to mark an entire namespace as erroneous merely
2031 // because there is an ODR error with two typedefs. As another example,
2032 // the client may allow EnumConstantDecls with same names but with
2033 // different values in two distinct translation units.
2034 ChildErrorHandlingStrategy HandleChildErrors(FromDC);
2035
2036 auto MightNeedReordering = [](const Decl *D) {
2037 return isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D);
2038 };
2039
2040 // Import everything that might need reordering first.
2041 Error ChildErrors = Error::success();
2042 for (auto *From : FromDC->decls()) {
2043 if (!MightNeedReordering(From))
2044 continue;
2045
2046 ExpectedDecl ImportedOrErr = import(From);
2047
2048 // If we are in the process of ImportDefinition(...) for a RecordDecl we
2049 // want to make sure that we are also completing each FieldDecl. There
2050 // are currently cases where this does not happen and this is correctness
2051 // fix since operations such as code generation will expect this to be so.
2052 if (!ImportedOrErr) {
2053 HandleChildErrors.handleChildImportResult(ChildErrors,
2054 ImportedOrErr.takeError());
2055 continue;
2056 }
2057 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
2058 Decl *ImportedDecl = *ImportedOrErr;
2059 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
2060 if (FieldFrom && FieldTo) {
2061 Error Err = ImportFieldDeclDefinition(FieldFrom, FieldTo);
2062 HandleChildErrors.handleChildImportResult(ChildErrors, std::move(Err));
2063 }
2064 }
2065
2066 // We reorder declarations in RecordDecls because they may have another order
2067 // in the "to" context than they have in the "from" context. This may happen
2068 // e.g when we import a class like this:
2069 // struct declToImport {
2070 // int a = c + b;
2071 // int b = 1;
2072 // int c = 2;
2073 // };
2074 // During the import of `a` we import first the dependencies in sequence,
2075 // thus the order would be `c`, `b`, `a`. We will get the normal order by
2076 // first removing the already imported members and then adding them in the
2077 // order as they appear in the "from" context.
2078 //
2079 // Keeping field order is vital because it determines structure layout.
2080 //
2081 // Here and below, we cannot call field_begin() method and its callers on
2082 // ToDC if it has an external storage. Calling field_begin() will
2083 // automatically load all the fields by calling
2084 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
2085 // call ASTImporter::Import(). This is because the ExternalASTSource
2086 // interface in LLDB is implemented by the means of the ASTImporter. However,
2087 // calling an import at this point would result in an uncontrolled import, we
2088 // must avoid that.
2089
2090 auto ToDCOrErr = Importer.ImportContext(FromDC);
2091 if (!ToDCOrErr) {
2092 consumeError(std::move(ChildErrors));
2093 return ToDCOrErr.takeError();
2094 }
2095
2096 if (const auto *FromRD = dyn_cast<RecordDecl>(FromDC)) {
2097 DeclContext *ToDC = *ToDCOrErr;
2098 // Remove all declarations, which may be in wrong order in the
2099 // lexical DeclContext and then add them in the proper order.
2100 for (auto *D : FromRD->decls()) {
2101 if (!MightNeedReordering(D))
2102 continue;
2103
2104 assert(D && "DC contains a null decl");
2105 if (Decl *ToD = Importer.GetAlreadyImportedOrNull(D)) {
2106 // Remove only the decls which we successfully imported.
2107 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD));
2108 // Remove the decl from its wrong place in the linked list.
2109 ToDC->removeDecl(ToD);
2110 // Add the decl to the end of the linked list.
2111 // This time it will be at the proper place because the enclosing for
2112 // loop iterates in the original (good) order of the decls.
2113 ToDC->addDeclInternal(ToD);
2114 }
2115 }
2116 }
2117
2118 // Import everything else.
2119 for (auto *From : FromDC->decls()) {
2120 if (MightNeedReordering(From))
2121 continue;
2122
2123 ExpectedDecl ImportedOrErr = import(From);
2124 if (!ImportedOrErr)
2125 HandleChildErrors.handleChildImportResult(ChildErrors,
2126 ImportedOrErr.takeError());
2127 }
2128
2129 return ChildErrors;
2130}
2131
2133 const FieldDecl *To) {
2134 RecordDecl *FromRecordDecl = nullptr;
2135 RecordDecl *ToRecordDecl = nullptr;
2136 // If we have a field that is an ArrayType we need to check if the array
2137 // element is a RecordDecl and if so we need to import the definition.
2138 QualType FromType = From->getType();
2139 QualType ToType = To->getType();
2140 if (FromType->isArrayType()) {
2141 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
2142 FromRecordDecl = FromType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2143 ToRecordDecl = ToType->getBaseElementTypeUnsafe()->getAsRecordDecl();
2144 }
2145
2146 if (!FromRecordDecl || !ToRecordDecl) {
2147 const RecordType *RecordFrom = FromType->getAs<RecordType>();
2148 const RecordType *RecordTo = ToType->getAs<RecordType>();
2149
2150 if (RecordFrom && RecordTo) {
2151 FromRecordDecl = RecordFrom->getDecl();
2152 ToRecordDecl = RecordTo->getDecl();
2153 }
2154 }
2155
2156 if (FromRecordDecl && ToRecordDecl) {
2157 if (FromRecordDecl->isCompleteDefinition() &&
2158 !ToRecordDecl->isCompleteDefinition())
2159 return ImportDefinition(FromRecordDecl, ToRecordDecl);
2160 }
2161
2162 return Error::success();
2163}
2164
2166 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
2167 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
2168 if (!ToDCOrErr)
2169 return ToDCOrErr.takeError();
2170 ToDC = *ToDCOrErr;
2171
2172 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
2173 auto ToLexicalDCOrErr = Importer.ImportContext(
2174 FromD->getLexicalDeclContext());
2175 if (!ToLexicalDCOrErr)
2176 return ToLexicalDCOrErr.takeError();
2177 ToLexicalDC = *ToLexicalDCOrErr;
2178 } else
2179 ToLexicalDC = ToDC;
2180
2181 return Error::success();
2182}
2183
2185 const CXXRecordDecl *From, CXXRecordDecl *To) {
2186 assert(From->isCompleteDefinition() && To->getDefinition() == To &&
2187 "Import implicit methods to or from non-definition");
2188
2189 for (CXXMethodDecl *FromM : From->methods())
2190 if (FromM->isImplicit()) {
2191 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
2192 if (!ToMOrErr)
2193 return ToMOrErr.takeError();
2194 }
2195
2196 return Error::success();
2197}
2198
2200 ASTImporter &Importer) {
2201 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
2202 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
2203 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
2204 else
2205 return ToTypedefOrErr.takeError();
2206 }
2207 return Error::success();
2208}
2209
2211 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
2212 auto DefinitionCompleter = [To]() {
2213 // There are cases in LLDB when we first import a class without its
2214 // members. The class will have DefinitionData, but no members. Then,
2215 // importDefinition is called from LLDB, which tries to get the members, so
2216 // when we get here, the class already has the DefinitionData set, so we
2217 // must unset the CompleteDefinition here to be able to complete again the
2218 // definition.
2219 To->setCompleteDefinition(false);
2220 To->completeDefinition();
2221 };
2222
2223 if (To->getDefinition() || To->isBeingDefined()) {
2224 if (Kind == IDK_Everything ||
2225 // In case of lambdas, the class already has a definition ptr set, but
2226 // the contained decls are not imported yet. Also, isBeingDefined was
2227 // set in CXXRecordDecl::CreateLambda. We must import the contained
2228 // decls here and finish the definition.
2229 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
2230 if (To->isLambda()) {
2231 auto *FromCXXRD = cast<CXXRecordDecl>(From);
2233 ToCaptures.reserve(FromCXXRD->capture_size());
2234 for (const auto &FromCapture : FromCXXRD->captures()) {
2235 if (auto ToCaptureOrErr = import(FromCapture))
2236 ToCaptures.push_back(*ToCaptureOrErr);
2237 else
2238 return ToCaptureOrErr.takeError();
2239 }
2240 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
2241 ToCaptures);
2242 }
2243
2244 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
2245 // Finish the definition of the lambda, set isBeingDefined to false.
2246 if (To->isLambda())
2247 DefinitionCompleter();
2248 return Result;
2249 }
2250
2251 return Error::success();
2252 }
2253
2254 To->startDefinition();
2255 // Set the definition to complete even if it is really not complete during
2256 // import. Some AST constructs (expressions) require the record layout
2257 // to be calculated (see 'clang::computeDependence') at the time they are
2258 // constructed. Import of such AST node is possible during import of the
2259 // same record, there is no way to have a completely defined record (all
2260 // fields imported) at that time without multiple AST import passes.
2261 if (!Importer.isMinimalImport())
2262 To->setCompleteDefinition(true);
2263 // Complete the definition even if error is returned.
2264 // The RecordDecl may be already part of the AST so it is better to
2265 // have it in complete state even if something is wrong with it.
2266 auto DefinitionCompleterScopeExit =
2267 llvm::make_scope_exit(DefinitionCompleter);
2268
2269 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2270 return Err;
2271
2272 // Add base classes.
2273 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2274 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2275 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2276
2277 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2278 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2279
2280 #define FIELD(Name, Width, Merge) \
2281 ToData.Name = FromData.Name;
2282 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2283
2284 // Copy over the data stored in RecordDeclBits
2285 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2286
2288 for (const auto &Base1 : FromCXX->bases()) {
2289 ExpectedType TyOrErr = import(Base1.getType());
2290 if (!TyOrErr)
2291 return TyOrErr.takeError();
2292
2293 SourceLocation EllipsisLoc;
2294 if (Base1.isPackExpansion()) {
2295 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2296 EllipsisLoc = *LocOrErr;
2297 else
2298 return LocOrErr.takeError();
2299 }
2300
2301 // Ensure that we have a definition for the base.
2302 if (Error Err =
2303 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2304 return Err;
2305
2306 auto RangeOrErr = import(Base1.getSourceRange());
2307 if (!RangeOrErr)
2308 return RangeOrErr.takeError();
2309
2310 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2311 if (!TSIOrErr)
2312 return TSIOrErr.takeError();
2313
2314 Bases.push_back(
2315 new (Importer.getToContext()) CXXBaseSpecifier(
2316 *RangeOrErr,
2317 Base1.isVirtual(),
2318 Base1.isBaseOfClass(),
2319 Base1.getAccessSpecifierAsWritten(),
2320 *TSIOrErr,
2321 EllipsisLoc));
2322 }
2323 if (!Bases.empty())
2324 ToCXX->setBases(Bases.data(), Bases.size());
2325 }
2326
2328 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2329 return Err;
2330 }
2331
2332 return Error::success();
2333}
2334
2336 if (To->getAnyInitializer())
2337 return Error::success();
2338
2339 Expr *FromInit = From->getInit();
2340 if (!FromInit)
2341 return Error::success();
2342
2343 ExpectedExpr ToInitOrErr = import(FromInit);
2344 if (!ToInitOrErr)
2345 return ToInitOrErr.takeError();
2346
2347 To->setInit(*ToInitOrErr);
2348 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2349 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2350 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2351 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2352 // FIXME: Also import the initializer value.
2353 }
2354
2355 // FIXME: Other bits to merge?
2356 return Error::success();
2357}
2358
2361 if (To->getDefinition() || To->isBeingDefined()) {
2362 if (Kind == IDK_Everything)
2363 return ImportDeclContext(From, /*ForceImport=*/true);
2364 return Error::success();
2365 }
2366
2367 To->startDefinition();
2368
2369 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2370 return Err;
2371
2372 ExpectedType ToTypeOrErr =
2373 import(Importer.getFromContext().getTypeDeclType(From));
2374 if (!ToTypeOrErr)
2375 return ToTypeOrErr.takeError();
2376
2377 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2378 if (!ToPromotionTypeOrErr)
2379 return ToPromotionTypeOrErr.takeError();
2380
2382 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2383 return Err;
2384
2385 // FIXME: we might need to merge the number of positive or negative bits
2386 // if the enumerator lists don't match.
2387 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2388 From->getNumPositiveBits(),
2389 From->getNumNegativeBits());
2390 return Error::success();
2391}
2392
2396 for (const auto &Arg : FromArgs) {
2397 if (auto ToOrErr = import(Arg))
2398 ToArgs.push_back(*ToOrErr);
2399 else
2400 return ToOrErr.takeError();
2401 }
2402
2403 return Error::success();
2404}
2405
2406// FIXME: Do not forget to remove this and use only 'import'.
2409 return import(From);
2410}
2411
2412template <typename InContainerTy>
2414 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2415 for (const auto &FromLoc : Container) {
2416 if (auto ToLocOrErr = import(FromLoc))
2417 ToTAInfo.addArgument(*ToLocOrErr);
2418 else
2419 return ToLocOrErr.takeError();
2420 }
2421 return Error::success();
2422}
2423
2428}
2429
2430bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain,
2431 bool IgnoreTemplateParmDepth) {
2432 // Eliminate a potential failure point where we attempt to re-import
2433 // something we're trying to import while completing ToRecord.
2434 Decl *ToOrigin = Importer.GetOriginalDecl(To);
2435 if (ToOrigin) {
2436 To = ToOrigin;
2437 }
2438
2440 Importer.getFromContext(), Importer.getToContext(),
2442 /*StrictTypeSpelling=*/false, Complain, /*ErrorOnTagTypeMismatch=*/false,
2443 IgnoreTemplateParmDepth);
2444 return Ctx.IsEquivalent(From, To);
2445}
2446
2448 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2449 << D->getDeclKindName();
2450 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2451}
2452
2454 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2455 << D->getDeclKindName();
2456 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
2457}
2458
2460 // Import the context of this declaration.
2461 DeclContext *DC, *LexicalDC;
2462 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2463 return std::move(Err);
2464
2465 // Import the location of this declaration.
2466 ExpectedSLoc LocOrErr = import(D->getLocation());
2467 if (!LocOrErr)
2468 return LocOrErr.takeError();
2469
2470 EmptyDecl *ToD;
2471 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2472 return ToD;
2473
2474 ToD->setLexicalDeclContext(LexicalDC);
2475 LexicalDC->addDeclInternal(ToD);
2476 return ToD;
2477}
2478
2480 TranslationUnitDecl *ToD =
2482
2483 Importer.MapImported(D, ToD);
2484
2485 return ToD;
2486}
2487
2489 DeclContext *DC, *LexicalDC;
2490 DeclarationName Name;
2492 NamedDecl *ToND;
2493 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2494 return std::move(Err);
2495 if (ToND)
2496 return ToND;
2497
2498 BindingDecl *ToD;
2499 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2500 Name.getAsIdentifierInfo()))
2501 return ToD;
2502
2503 Error Err = Error::success();
2504 QualType ToType = importChecked(Err, D->getType());
2505 Expr *ToBinding = importChecked(Err, D->getBinding());
2506 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2507 if (Err)
2508 return std::move(Err);
2509
2510 ToD->setBinding(ToType, ToBinding);
2511 ToD->setDecomposedDecl(ToDecomposedDecl);
2512 addDeclToContexts(D, ToD);
2513
2514 return ToD;
2515}
2516
2518 ExpectedSLoc LocOrErr = import(D->getLocation());
2519 if (!LocOrErr)
2520 return LocOrErr.takeError();
2521 auto ColonLocOrErr = import(D->getColonLoc());
2522 if (!ColonLocOrErr)
2523 return ColonLocOrErr.takeError();
2524
2525 // Import the context of this declaration.
2526 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2527 if (!DCOrErr)
2528 return DCOrErr.takeError();
2529 DeclContext *DC = *DCOrErr;
2530
2531 AccessSpecDecl *ToD;
2532 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2533 DC, *LocOrErr, *ColonLocOrErr))
2534 return ToD;
2535
2536 // Lexical DeclContext and Semantic DeclContext
2537 // is always the same for the accessSpec.
2538 ToD->setLexicalDeclContext(DC);
2539 DC->addDeclInternal(ToD);
2540
2541 return ToD;
2542}
2543
2545 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2546 if (!DCOrErr)
2547 return DCOrErr.takeError();
2548 DeclContext *DC = *DCOrErr;
2549 DeclContext *LexicalDC = DC;
2550
2551 Error Err = Error::success();
2552 auto ToLocation = importChecked(Err, D->getLocation());
2553 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2554 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2555 auto ToMessage = importChecked(Err, D->getMessage());
2556 if (Err)
2557 return std::move(Err);
2558
2559 StaticAssertDecl *ToD;
2560 if (GetImportedOrCreateDecl(
2561 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2562 ToRParenLoc, D->isFailed()))
2563 return ToD;
2564
2565 ToD->setLexicalDeclContext(LexicalDC);
2566 LexicalDC->addDeclInternal(ToD);
2567 return ToD;
2568}
2569
2571 // Import the major distinguishing characteristics of this namespace.
2572 DeclContext *DC, *LexicalDC;
2573 DeclarationName Name;
2575 NamedDecl *ToD;
2576 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2577 return std::move(Err);
2578 if (ToD)
2579 return ToD;
2580
2581 NamespaceDecl *MergeWithNamespace = nullptr;
2582 if (!Name) {
2583 // This is an anonymous namespace. Adopt an existing anonymous
2584 // namespace if we can.
2585 // FIXME: Not testable.
2586 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2587 MergeWithNamespace = TU->getAnonymousNamespace();
2588 else
2589 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2590 } else {
2591 SmallVector<NamedDecl *, 4> ConflictingDecls;
2592 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2593 for (auto *FoundDecl : FoundDecls) {
2595 continue;
2596
2597 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2598 MergeWithNamespace = FoundNS;
2599 ConflictingDecls.clear();
2600 break;
2601 }
2602
2603 ConflictingDecls.push_back(FoundDecl);
2604 }
2605
2606 if (!ConflictingDecls.empty()) {
2607 ExpectedName NameOrErr = Importer.HandleNameConflict(
2608 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2609 ConflictingDecls.size());
2610 if (NameOrErr)
2611 Name = NameOrErr.get();
2612 else
2613 return NameOrErr.takeError();
2614 }
2615 }
2616
2617 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2618 if (!BeginLocOrErr)
2619 return BeginLocOrErr.takeError();
2620 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2621 if (!RBraceLocOrErr)
2622 return RBraceLocOrErr.takeError();
2623
2624 // Create the "to" namespace, if needed.
2625 NamespaceDecl *ToNamespace = MergeWithNamespace;
2626 if (!ToNamespace) {
2627 if (GetImportedOrCreateDecl(ToNamespace, D, Importer.getToContext(), DC,
2628 D->isInline(), *BeginLocOrErr, Loc,
2629 Name.getAsIdentifierInfo(),
2630 /*PrevDecl=*/nullptr, D->isNested()))
2631 return ToNamespace;
2632 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2633 ToNamespace->setLexicalDeclContext(LexicalDC);
2634 LexicalDC->addDeclInternal(ToNamespace);
2635
2636 // If this is an anonymous namespace, register it as the anonymous
2637 // namespace within its context.
2638 if (!Name) {
2639 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2640 TU->setAnonymousNamespace(ToNamespace);
2641 else
2642 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2643 }
2644 }
2645 Importer.MapImported(D, ToNamespace);
2646
2647 if (Error Err = ImportDeclContext(D))
2648 return std::move(Err);
2649
2650 return ToNamespace;
2651}
2652
2654 // Import the major distinguishing characteristics of this namespace.
2655 DeclContext *DC, *LexicalDC;
2656 DeclarationName Name;
2658 NamedDecl *LookupD;
2659 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2660 return std::move(Err);
2661 if (LookupD)
2662 return LookupD;
2663
2664 // NOTE: No conflict resolution is done for namespace aliases now.
2665
2666 Error Err = Error::success();
2667 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2668 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2669 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2670 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2671 auto ToNamespace = importChecked(Err, D->getNamespace());
2672 if (Err)
2673 return std::move(Err);
2674
2675 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2676
2677 NamespaceAliasDecl *ToD;
2678 if (GetImportedOrCreateDecl(
2679 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2680 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2681 return ToD;
2682
2683 ToD->setLexicalDeclContext(LexicalDC);
2684 LexicalDC->addDeclInternal(ToD);
2685
2686 return ToD;
2687}
2688
2691 // Import the major distinguishing characteristics of this typedef.
2692 DeclarationName Name;
2694 NamedDecl *ToD;
2695 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2696 // is created.
2697 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2698 return std::move(Err);
2699 if (ToD)
2700 return ToD;
2701
2702 DeclContext *DC = cast_or_null<DeclContext>(
2703 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2704 DeclContext *LexicalDC =
2705 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2706 cast<Decl>(D->getLexicalDeclContext())));
2707
2708 // If this typedef is not in block scope, determine whether we've
2709 // seen a typedef with the same name (that we can merge with) or any
2710 // other entity by that name (which name lookup could conflict with).
2711 // Note: Repeated typedefs are not valid in C99:
2712 // 'typedef int T; typedef int T;' is invalid
2713 // We do not care about this now.
2714 if (DC && !DC->isFunctionOrMethod()) {
2715 SmallVector<NamedDecl *, 4> ConflictingDecls;
2716 unsigned IDNS = Decl::IDNS_Ordinary;
2717 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2718 for (auto *FoundDecl : FoundDecls) {
2719 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2720 continue;
2721 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2722 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2723 continue;
2724
2725 QualType FromUT = D->getUnderlyingType();
2726 QualType FoundUT = FoundTypedef->getUnderlyingType();
2727 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2728 // If the underlying declarations are unnamed records these can be
2729 // imported as different types. We should create a distinct typedef
2730 // node in this case.
2731 // If we found an existing underlying type with a record in a
2732 // different context (than the imported), this is already reason for
2733 // having distinct typedef nodes for these.
2734 // Again this can create situation like
2735 // 'typedef int T; typedef int T;' but this is hard to avoid without
2736 // a rename strategy at import.
2737 if (!FromUT.isNull() && !FoundUT.isNull()) {
2738 RecordDecl *FromR = FromUT->getAsRecordDecl();
2739 RecordDecl *FoundR = FoundUT->getAsRecordDecl();
2740 if (FromR && FoundR &&
2741 !hasSameVisibilityContextAndLinkage(FoundR, FromR))
2742 continue;
2743 }
2744 // If the "From" context has a complete underlying type but we
2745 // already have a complete underlying type then return with that.
2746 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2747 return Importer.MapImported(D, FoundTypedef);
2748 // FIXME Handle redecl chain. When you do that make consistent changes
2749 // in ASTImporterLookupTable too.
2750 } else {
2751 ConflictingDecls.push_back(FoundDecl);
2752 }
2753 }
2754 }
2755
2756 if (!ConflictingDecls.empty()) {
2757 ExpectedName NameOrErr = Importer.HandleNameConflict(
2758 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2759 if (NameOrErr)
2760 Name = NameOrErr.get();
2761 else
2762 return NameOrErr.takeError();
2763 }
2764 }
2765
2766 Error Err = Error::success();
2767 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
2768 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2769 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2770 if (Err)
2771 return std::move(Err);
2772
2773 // Create the new typedef node.
2774 // FIXME: ToUnderlyingType is not used.
2775 (void)ToUnderlyingType;
2776 TypedefNameDecl *ToTypedef;
2777 if (IsAlias) {
2778 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2779 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2780 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2781 return ToTypedef;
2782 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2783 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2784 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2785 return ToTypedef;
2786
2787 // Import the DeclContext and set it to the Typedef.
2788 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2789 return std::move(Err);
2790 ToTypedef->setDeclContext(DC);
2791 ToTypedef->setLexicalDeclContext(LexicalDC);
2792 // Add to the lookupTable because we could not do that in MapImported.
2793 Importer.AddToLookupTable(ToTypedef);
2794
2795 ToTypedef->setAccess(D->getAccess());
2796
2797 // Templated declarations should not appear in DeclContext.
2798 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2799 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2800 LexicalDC->addDeclInternal(ToTypedef);
2801
2802 return ToTypedef;
2803}
2804
2806 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2807}
2808
2810 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2811}
2812
2815 // Import the major distinguishing characteristics of this typedef.
2816 DeclContext *DC, *LexicalDC;
2817 DeclarationName Name;
2819 NamedDecl *FoundD;
2820 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2821 return std::move(Err);
2822 if (FoundD)
2823 return FoundD;
2824
2825 // If this typedef is not in block scope, determine whether we've
2826 // seen a typedef with the same name (that we can merge with) or any
2827 // other entity by that name (which name lookup could conflict with).
2828 if (!DC->isFunctionOrMethod()) {
2829 SmallVector<NamedDecl *, 4> ConflictingDecls;
2830 unsigned IDNS = Decl::IDNS_Ordinary;
2831 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2832 for (auto *FoundDecl : FoundDecls) {
2833 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2834 continue;
2835 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) {
2836 if (IsStructuralMatch(D, FoundAlias))
2837 return Importer.MapImported(D, FoundAlias);
2838 ConflictingDecls.push_back(FoundDecl);
2839 }
2840 }
2841
2842 if (!ConflictingDecls.empty()) {
2843 ExpectedName NameOrErr = Importer.HandleNameConflict(
2844 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2845 if (NameOrErr)
2846 Name = NameOrErr.get();
2847 else
2848 return NameOrErr.takeError();
2849 }
2850 }
2851
2852 Error Err = Error::success();
2853 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2854 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2855 if (Err)
2856 return std::move(Err);
2857
2858 TypeAliasTemplateDecl *ToAlias;
2859 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2860 Name, ToTemplateParameters, ToTemplatedDecl))
2861 return ToAlias;
2862
2863 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2864
2865 ToAlias->setAccess(D->getAccess());
2866 ToAlias->setLexicalDeclContext(LexicalDC);
2867 LexicalDC->addDeclInternal(ToAlias);
2868 if (DC != Importer.getToContext().getTranslationUnitDecl())
2869 updateLookupTableForTemplateParameters(*ToTemplateParameters);
2870 return ToAlias;
2871}
2872
2874 // Import the major distinguishing characteristics of this label.
2875 DeclContext *DC, *LexicalDC;
2876 DeclarationName Name;
2878 NamedDecl *ToD;
2879 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2880 return std::move(Err);
2881 if (ToD)
2882 return ToD;
2883
2884 assert(LexicalDC->isFunctionOrMethod());
2885
2886 LabelDecl *ToLabel;
2887 if (D->isGnuLocal()) {
2888 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2889 if (!BeginLocOrErr)
2890 return BeginLocOrErr.takeError();
2891 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2892 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2893 return ToLabel;
2894
2895 } else {
2896 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2897 Name.getAsIdentifierInfo()))
2898 return ToLabel;
2899
2900 }
2901
2902 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2903 if (!ToStmtOrErr)
2904 return ToStmtOrErr.takeError();
2905
2906 ToLabel->setStmt(*ToStmtOrErr);
2907 ToLabel->setLexicalDeclContext(LexicalDC);
2908 LexicalDC->addDeclInternal(ToLabel);
2909 return ToLabel;
2910}
2911
2913 // Import the major distinguishing characteristics of this enum.
2914 DeclContext *DC, *LexicalDC;
2915 DeclarationName Name;
2917 NamedDecl *ToD;
2918 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2919 return std::move(Err);
2920 if (ToD)
2921 return ToD;
2922
2923 // Figure out what enum name we're looking for.
2924 unsigned IDNS = Decl::IDNS_Tag;
2925 DeclarationName SearchName = Name;
2926 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2927 if (Error Err = importInto(
2928 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2929 return std::move(Err);
2930 IDNS = Decl::IDNS_Ordinary;
2931 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2932 IDNS |= Decl::IDNS_Ordinary;
2933
2934 // We may already have an enum of the same name; try to find and match it.
2935 EnumDecl *PrevDecl = nullptr;
2936 if (!DC->isFunctionOrMethod()) {
2937 SmallVector<NamedDecl *, 4> ConflictingDecls;
2938 auto FoundDecls =
2939 Importer.findDeclsInToCtx(DC, SearchName);
2940 for (auto *FoundDecl : FoundDecls) {
2941 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2942 continue;
2943
2944 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2945 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2946 FoundDecl = Tag->getDecl();
2947 }
2948
2949 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2950 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2951 continue;
2952 if (IsStructuralMatch(D, FoundEnum, !SearchName.isEmpty())) {
2953 EnumDecl *FoundDef = FoundEnum->getDefinition();
2954 if (D->isThisDeclarationADefinition() && FoundDef)
2955 return Importer.MapImported(D, FoundDef);
2956 PrevDecl = FoundEnum->getMostRecentDecl();
2957 break;
2958 }
2959 ConflictingDecls.push_back(FoundDecl);
2960 }
2961 }
2962
2963 // In case of unnamed enums, we try to find an existing similar one, if none
2964 // was found, perform the import always.
2965 // Structural in-equivalence is not detected in this way here, but it may
2966 // be found when the parent decl is imported (if the enum is part of a
2967 // class). To make this totally exact a more difficult solution is needed.
2968 if (SearchName && !ConflictingDecls.empty()) {
2969 ExpectedName NameOrErr = Importer.HandleNameConflict(
2970 SearchName, DC, IDNS, ConflictingDecls.data(),
2971 ConflictingDecls.size());
2972 if (NameOrErr)
2973 Name = NameOrErr.get();
2974 else
2975 return NameOrErr.takeError();
2976 }
2977 }
2978
2979 Error Err = Error::success();
2980 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2981 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2982 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2983 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2984 if (Err)
2985 return std::move(Err);
2986
2987 // Create the enum declaration.
2988 EnumDecl *D2;
2989 if (GetImportedOrCreateDecl(
2990 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2991 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2992 D->isScopedUsingClassTag(), D->isFixed()))
2993 return D2;
2994
2995 D2->setQualifierInfo(ToQualifierLoc);
2996 D2->setIntegerType(ToIntegerType);
2997 D2->setBraceRange(ToBraceRange);
2998 D2->setAccess(D->getAccess());
2999 D2->setLexicalDeclContext(LexicalDC);
3000 addDeclToContexts(D, D2);
3001
3002 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
3003 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
3004 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
3005 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
3006 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
3007 else
3008 return ToInstOrErr.takeError();
3009 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
3011 else
3012 return POIOrErr.takeError();
3013 }
3014
3015 // Import the definition
3016 if (D->isCompleteDefinition())
3017 if (Error Err = ImportDefinition(D, D2))
3018 return std::move(Err);
3019
3020 return D2;
3021}
3022
3024 bool IsFriendTemplate = false;
3025 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3026 IsFriendTemplate =
3027 DCXX->getDescribedClassTemplate() &&
3028 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
3030 }
3031
3032 // Import the major distinguishing characteristics of this record.
3033 DeclContext *DC = nullptr, *LexicalDC = nullptr;
3034 DeclarationName Name;
3036 NamedDecl *ToD = nullptr;
3037 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3038 return std::move(Err);
3039 if (ToD)
3040 return ToD;
3041
3042 // Figure out what structure name we're looking for.
3043 unsigned IDNS = Decl::IDNS_Tag;
3044 DeclarationName SearchName = Name;
3045 if (!SearchName && D->getTypedefNameForAnonDecl()) {
3046 if (Error Err = importInto(
3047 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
3048 return std::move(Err);
3049 IDNS = Decl::IDNS_Ordinary;
3050 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
3052
3053 bool IsDependentContext = DC != LexicalDC ? LexicalDC->isDependentContext()
3054 : DC->isDependentContext();
3055 bool DependentFriend = IsFriendTemplate && IsDependentContext;
3056
3057 // We may already have a record of the same name; try to find and match it.
3058 RecordDecl *PrevDecl = nullptr;
3059 if (!DependentFriend && !DC->isFunctionOrMethod() && !D->isLambda()) {
3060 SmallVector<NamedDecl *, 4> ConflictingDecls;
3061 auto FoundDecls =
3062 Importer.findDeclsInToCtx(DC, SearchName);
3063 if (!FoundDecls.empty()) {
3064 // We're going to have to compare D against potentially conflicting Decls,
3065 // so complete it.
3066 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
3068 }
3069
3070 for (auto *FoundDecl : FoundDecls) {
3071 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3072 continue;
3073
3074 Decl *Found = FoundDecl;
3075 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
3076 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
3077 Found = Tag->getDecl();
3078 }
3079
3080 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
3081 // Do not emit false positive diagnostic in case of unnamed
3082 // struct/union and in case of anonymous structs. Would be false
3083 // because there may be several anonymous/unnamed structs in a class.
3084 // E.g. these are both valid:
3085 // struct A { // unnamed structs
3086 // struct { struct A *next; } entry0;
3087 // struct { struct A *next; } entry1;
3088 // };
3089 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
3090 if (!SearchName)
3091 if (!IsStructuralMatch(D, FoundRecord, false))
3092 continue;
3093
3094 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
3095 continue;
3096
3097 if (IsStructuralMatch(D, FoundRecord)) {
3098 RecordDecl *FoundDef = FoundRecord->getDefinition();
3099 if (D->isThisDeclarationADefinition() && FoundDef) {
3100 // FIXME: Structural equivalence check should check for same
3101 // user-defined methods.
3102 Importer.MapImported(D, FoundDef);
3103 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3104 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
3105 assert(FoundCXX && "Record type mismatch");
3106
3107 if (!Importer.isMinimalImport())
3108 // FoundDef may not have every implicit method that D has
3109 // because implicit methods are created only if they are used.
3110 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
3111 return std::move(Err);
3112 }
3113 }
3114 PrevDecl = FoundRecord->getMostRecentDecl();
3115 break;
3116 }
3117 ConflictingDecls.push_back(FoundDecl);
3118 } // kind is RecordDecl
3119 } // for
3120
3121 if (!ConflictingDecls.empty() && SearchName) {
3122 ExpectedName NameOrErr = Importer.HandleNameConflict(
3123 SearchName, DC, IDNS, ConflictingDecls.data(),
3124 ConflictingDecls.size());
3125 if (NameOrErr)
3126 Name = NameOrErr.get();
3127 else
3128 return NameOrErr.takeError();
3129 }
3130 }
3131
3132 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
3133 if (!BeginLocOrErr)
3134 return BeginLocOrErr.takeError();
3135
3136 // Create the record declaration.
3137 RecordDecl *D2 = nullptr;
3138 CXXRecordDecl *D2CXX = nullptr;
3139 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
3140 if (DCXX->isLambda()) {
3141 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
3142 if (!TInfoOrErr)
3143 return TInfoOrErr.takeError();
3144 if (GetImportedOrCreateSpecialDecl(
3145 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
3146 DC, *TInfoOrErr, Loc, DCXX->getLambdaDependencyKind(),
3147 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
3148 return D2CXX;
3149 CXXRecordDecl::LambdaNumbering Numbering = DCXX->getLambdaNumbering();
3150 ExpectedDecl CDeclOrErr = import(Numbering.ContextDecl);
3151 if (!CDeclOrErr)
3152 return CDeclOrErr.takeError();
3153 Numbering.ContextDecl = *CDeclOrErr;
3154 D2CXX->setLambdaNumbering(Numbering);
3155 } else if (DCXX->isInjectedClassName()) {
3156 // We have to be careful to do a similar dance to the one in
3157 // Sema::ActOnStartCXXMemberDeclarations
3158 const bool DelayTypeCreation = true;
3159 if (GetImportedOrCreateDecl(
3160 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
3161 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
3162 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
3163 return D2CXX;
3164 Importer.getToContext().getTypeDeclType(
3165 D2CXX, dyn_cast<CXXRecordDecl>(DC));
3166 } else {
3167 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
3168 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3169 Name.getAsIdentifierInfo(),
3170 cast_or_null<CXXRecordDecl>(PrevDecl)))
3171 return D2CXX;
3172 }
3173
3174 D2 = D2CXX;
3175 D2->setAccess(D->getAccess());
3176 D2->setLexicalDeclContext(LexicalDC);
3177 addDeclToContexts(D, D2);
3178
3179 if (ClassTemplateDecl *FromDescribed =
3180 DCXX->getDescribedClassTemplate()) {
3181 ClassTemplateDecl *ToDescribed;
3182 if (Error Err = importInto(ToDescribed, FromDescribed))
3183 return std::move(Err);
3184 D2CXX->setDescribedClassTemplate(ToDescribed);
3185 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
3186 // In a record describing a template the type should be an
3187 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
3188 // previously set type to the correct value here (ToDescribed is not
3189 // available at record create).
3190 CXXRecordDecl *Injected = nullptr;
3191 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
3192 auto *Record = dyn_cast<CXXRecordDecl>(Found);
3193 if (Record && Record->isInjectedClassName()) {
3194 Injected = Record;
3195 break;
3196 }
3197 }
3198 // Create an injected type for the whole redecl chain.
3199 // The chain may contain an already existing injected type at the start,
3200 // if yes this should be reused. We must ensure that only one type
3201 // object exists for the injected type (including the injected record
3202 // declaration), ASTContext does not check it.
3203 SmallVector<Decl *, 2> Redecls =
3205 const Type *FrontTy =
3206 cast<CXXRecordDecl>(Redecls.front())->getTypeForDecl();
3207 QualType InjSpec;
3208 if (auto *InjTy = FrontTy->getAs<InjectedClassNameType>())
3209 InjSpec = InjTy->getInjectedSpecializationType();
3210 else
3211 InjSpec = ToDescribed->getInjectedClassNameSpecialization();
3212 for (auto *R : Redecls) {
3213 auto *RI = cast<CXXRecordDecl>(R);
3214 if (R != Redecls.front() ||
3215 !isa<InjectedClassNameType>(RI->getTypeForDecl()))
3216 RI->setTypeForDecl(nullptr);
3217 // This function tries to get the injected type from getTypeForDecl,
3218 // then from the previous declaration if possible. If not, it creates
3219 // a new type.
3220 Importer.getToContext().getInjectedClassNameType(RI, InjSpec);
3221 }
3222 // Set the new type for the injected decl too.
3223 if (Injected) {
3224 Injected->setTypeForDecl(nullptr);
3225 // This function will copy the injected type from D2CXX into Injected.
3226 // The injected decl does not have a previous decl to copy from.
3227 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
3228 }
3229 }
3230 } else if (MemberSpecializationInfo *MemberInfo =
3231 DCXX->getMemberSpecializationInfo()) {
3233 MemberInfo->getTemplateSpecializationKind();
3235
3236 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
3237 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
3238 else
3239 return ToInstOrErr.takeError();
3240
3241 if (ExpectedSLoc POIOrErr =
3242 import(MemberInfo->getPointOfInstantiation()))
3244 *POIOrErr);
3245 else
3246 return POIOrErr.takeError();
3247 }
3248
3249 } else {
3250 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3251 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3252 Name.getAsIdentifierInfo(), PrevDecl))
3253 return D2;
3254 D2->setLexicalDeclContext(LexicalDC);
3255 addDeclToContexts(D, D2);
3256 }
3257
3258 if (auto BraceRangeOrErr = import(D->getBraceRange()))
3259 D2->setBraceRange(*BraceRangeOrErr);
3260 else
3261 return BraceRangeOrErr.takeError();
3262 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3263 D2->setQualifierInfo(*QualifierLocOrErr);
3264 else
3265 return QualifierLocOrErr.takeError();
3266
3267 if (D->isAnonymousStructOrUnion())
3268 D2->setAnonymousStructOrUnion(true);
3269
3270 if (D->isCompleteDefinition())
3271 if (Error Err = ImportDefinition(D, D2, IDK_Default))
3272 return std::move(Err);
3273
3274 return D2;
3275}
3276
3278 // Import the major distinguishing characteristics of this enumerator.
3279 DeclContext *DC, *LexicalDC;
3280 DeclarationName Name;
3282 NamedDecl *ToD;
3283 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3284 return std::move(Err);
3285 if (ToD)
3286 return ToD;
3287
3288 // Determine whether there are any other declarations with the same name and
3289 // in the same context.
3290 if (!LexicalDC->isFunctionOrMethod()) {
3291 SmallVector<NamedDecl *, 4> ConflictingDecls;
3292 unsigned IDNS = Decl::IDNS_Ordinary;
3293 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3294 for (auto *FoundDecl : FoundDecls) {
3295 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3296 continue;
3297
3298 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3299 if (IsStructuralMatch(D, FoundEnumConstant))
3300 return Importer.MapImported(D, FoundEnumConstant);
3301 ConflictingDecls.push_back(FoundDecl);
3302 }
3303 }
3304
3305 if (!ConflictingDecls.empty()) {
3306 ExpectedName NameOrErr = Importer.HandleNameConflict(
3307 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3308 if (NameOrErr)
3309 Name = NameOrErr.get();
3310 else
3311 return NameOrErr.takeError();
3312 }
3313 }
3314
3315 ExpectedType TypeOrErr = import(D->getType());
3316 if (!TypeOrErr)
3317 return TypeOrErr.takeError();
3318
3319 ExpectedExpr InitOrErr = import(D->getInitExpr());
3320 if (!InitOrErr)
3321 return InitOrErr.takeError();
3322
3323 EnumConstantDecl *ToEnumerator;
3324 if (GetImportedOrCreateDecl(
3325 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3326 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3327 return ToEnumerator;
3328
3329 ToEnumerator->setAccess(D->getAccess());
3330 ToEnumerator->setLexicalDeclContext(LexicalDC);
3331 LexicalDC->addDeclInternal(ToEnumerator);
3332 return ToEnumerator;
3333}
3334
3335template <typename DeclTy>
3337 DeclTy *ToD) {
3338 unsigned int Num = FromD->getNumTemplateParameterLists();
3339 if (Num == 0)
3340 return Error::success();
3342 for (unsigned int I = 0; I < Num; ++I)
3343 if (Expected<TemplateParameterList *> ToTPListOrErr =
3344 import(FromD->getTemplateParameterList(I)))
3345 ToTPLists[I] = *ToTPListOrErr;
3346 else
3347 return ToTPListOrErr.takeError();
3348 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3349 return Error::success();
3350}
3351
3353 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3354 switch (FromFD->getTemplatedKind()) {
3357 return Error::success();
3358
3360 if (Expected<FunctionDecl *> InstFDOrErr =
3361 import(FromFD->getInstantiatedFromDecl()))
3362 ToFD->setInstantiatedFromDecl(*InstFDOrErr);
3363 return Error::success();
3366
3367 if (Expected<FunctionDecl *> InstFDOrErr =
3368 import(FromFD->getInstantiatedFromMemberFunction()))
3369 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3370 else
3371 return InstFDOrErr.takeError();
3372
3373 if (ExpectedSLoc POIOrErr = import(
3376 else
3377 return POIOrErr.takeError();
3378
3379 return Error::success();
3380 }
3381
3383 auto FunctionAndArgsOrErr =
3385 if (!FunctionAndArgsOrErr)
3386 return FunctionAndArgsOrErr.takeError();
3387
3389 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3390
3391 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3392 TemplateArgumentListInfo ToTAInfo;
3393 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3394 if (FromTAArgsAsWritten)
3395 if (Error Err = ImportTemplateArgumentListInfo(
3396 *FromTAArgsAsWritten, ToTAInfo))
3397 return Err;
3398
3399 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3400 if (!POIOrErr)
3401 return POIOrErr.takeError();
3402
3403 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3404 return Err;
3405
3406 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3407 ToFD->setFunctionTemplateSpecialization(
3408 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3409 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3410 return Error::success();
3411 }
3412
3414 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3415 UnresolvedSet<8> Candidates;
3416 for (FunctionTemplateDecl *FTD : FromInfo->getCandidates()) {
3417 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = import(FTD))
3418 Candidates.addDecl(*ToFTDOrErr);
3419 else
3420 return ToFTDOrErr.takeError();
3421 }
3422
3423 // Import TemplateArgumentListInfo.
3424 TemplateArgumentListInfo ToTAInfo;
3425 const auto *FromTAArgsAsWritten = FromInfo->TemplateArgumentsAsWritten;
3426 if (FromTAArgsAsWritten)
3427 if (Error Err =
3428 ImportTemplateArgumentListInfo(*FromTAArgsAsWritten, ToTAInfo))
3429 return Err;
3430
3432 Importer.getToContext(), Candidates,
3433 FromTAArgsAsWritten ? &ToTAInfo : nullptr);
3434 return Error::success();
3435 }
3436 }
3437 llvm_unreachable("All cases should be covered!");
3438}
3439
3442 auto FunctionAndArgsOrErr =
3444 if (!FunctionAndArgsOrErr)
3445 return FunctionAndArgsOrErr.takeError();
3446
3447 FunctionTemplateDecl *Template;
3448 TemplateArgsTy ToTemplArgs;
3449 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3450 void *InsertPos = nullptr;
3451 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3452 return FoundSpec;
3453}
3454
3456 FunctionDecl *ToFD) {
3457 if (Stmt *FromBody = FromFD->getBody()) {
3458 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3459 ToFD->setBody(*ToBodyOrErr);
3460 else
3461 return ToBodyOrErr.takeError();
3462 }
3463 return Error::success();
3464}
3465
3466// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3467// which is equal to the given DC, or D is equal to DC.
3468static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3469 const DeclContext *DCi = dyn_cast<DeclContext>(D);
3470 if (!DCi)
3471 DCi = D->getDeclContext();
3472 assert(DCi && "Declaration should have a context");
3473 while (DCi != D->getTranslationUnitDecl()) {
3474 if (DCi == DC)
3475 return true;
3476 DCi = DCi->getParent();
3477 }
3478 return false;
3479}
3480
3481// Check if there is a declaration that has 'DC' as parent context and is
3482// referenced from statement 'S' or one of its children. The search is done in
3483// BFS order through children of 'S'.
3484static bool isAncestorDeclContextOf(const DeclContext *DC, const Stmt *S) {
3485 SmallVector<const Stmt *> ToProcess;
3486 ToProcess.push_back(S);
3487 while (!ToProcess.empty()) {
3488 const Stmt *CurrentS = ToProcess.pop_back_val();
3489 ToProcess.append(CurrentS->child_begin(), CurrentS->child_end());
3490 if (const auto *DeclRef = dyn_cast<DeclRefExpr>(CurrentS)) {
3491 if (const Decl *D = DeclRef->getDecl())
3492 if (isAncestorDeclContextOf(DC, D))
3493 return true;
3494 } else if (const auto *E =
3495 dyn_cast_or_null<SubstNonTypeTemplateParmExpr>(CurrentS)) {
3496 if (const Decl *D = E->getAssociatedDecl())
3497 if (isAncestorDeclContextOf(DC, D))
3498 return true;
3499 }
3500 }
3501 return false;
3502}
3503
3504namespace {
3505/// Check if a type has any reference to a declaration that is inside the body
3506/// of a function.
3507/// The \c CheckType(QualType) function should be used to determine
3508/// this property.
3509///
3510/// The type visitor visits one type object only (not recursive).
3511/// To find all referenced declarations we must discover all type objects until
3512/// the canonical type is reached (walk over typedef and similar objects). This
3513/// is done by loop over all "sugar" type objects. For every such type we must
3514/// check all declarations that are referenced from it. For this check the
3515/// visitor is used. In the visit functions all referenced declarations except
3516/// the one that follows in the sugar chain (if any) must be checked. For this
3517/// check the same visitor is re-used (it has no state-dependent data).
3518///
3519/// The visit functions have 3 possible return values:
3520/// - True, found a declaration inside \c ParentDC.
3521/// - False, found declarations only outside \c ParentDC and it is not possible
3522/// to find more declarations (the "sugar" chain does not continue).
3523/// - Empty optional value, found no declarations or only outside \c ParentDC,
3524/// but it is possible to find more declarations in the type "sugar" chain.
3525/// The loop over the "sugar" types can be implemented by using type visit
3526/// functions only (call \c CheckType with the desugared type). With the current
3527/// solution no visit function is needed if the type has only a desugared type
3528/// as data.
3529class IsTypeDeclaredInsideVisitor
3530 : public TypeVisitor<IsTypeDeclaredInsideVisitor, std::optional<bool>> {
3531public:
3532 IsTypeDeclaredInsideVisitor(const FunctionDecl *ParentDC)
3533 : ParentDC(ParentDC) {}
3534
3535 bool CheckType(QualType T) {
3536 // Check the chain of "sugar" types.
3537 // The "sugar" types are typedef or similar types that have the same
3538 // canonical type.
3539 if (std::optional<bool> Res = Visit(T.getTypePtr()))
3540 return *Res;
3541 QualType DsT =
3542 T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3543 while (DsT != T) {
3544 if (std::optional<bool> Res = Visit(DsT.getTypePtr()))
3545 return *Res;
3546 T = DsT;
3547 DsT = T.getSingleStepDesugaredType(ParentDC->getParentASTContext());
3548 }
3549 return false;
3550 }
3551
3552 std::optional<bool> VisitTagType(const TagType *T) {
3553 if (auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(T->getDecl()))
3554 for (const auto &Arg : Spec->getTemplateArgs().asArray())
3555 if (checkTemplateArgument(Arg))
3556 return true;
3557 return isAncestorDeclContextOf(ParentDC, T->getDecl());
3558 }
3559
3560 std::optional<bool> VisitPointerType(const PointerType *T) {
3561 return CheckType(T->getPointeeType());
3562 }
3563
3564 std::optional<bool> VisitReferenceType(const ReferenceType *T) {
3565 return CheckType(T->getPointeeTypeAsWritten());
3566 }
3567
3568 std::optional<bool> VisitTypedefType(const TypedefType *T) {
3569 const TypedefNameDecl *TD = T->getDecl();
3570 assert(TD);
3571 return isAncestorDeclContextOf(ParentDC, TD);
3572 }
3573
3574 std::optional<bool> VisitUsingType(const UsingType *T) {
3575 if (T->getFoundDecl() &&
3576 isAncestorDeclContextOf(ParentDC, T->getFoundDecl()))
3577 return true;
3578
3579 return {};
3580 }
3581
3582 std::optional<bool>
3583 VisitTemplateSpecializationType(const TemplateSpecializationType *T) {
3584 for (const auto &Arg : T->template_arguments())
3585 if (checkTemplateArgument(Arg))
3586 return true;
3587 // This type is a "sugar" to a record type, it can have a desugared type.
3588 return {};
3589 }
3590
3591 std::optional<bool>
3592 VisitSubstTemplateTypeParmType(const SubstTemplateTypeParmType *T) {
3593 // The "associated declaration" can be the same as ParentDC.
3594 if (isAncestorDeclContextOf(ParentDC, T->getAssociatedDecl()))
3595 return true;
3596 return {};
3597 }
3598
3599 std::optional<bool> VisitConstantArrayType(const ConstantArrayType *T) {
3600 if (T->getSizeExpr() && isAncestorDeclContextOf(ParentDC, T->getSizeExpr()))
3601 return true;
3602
3603 return CheckType(T->getElementType());
3604 }
3605
3606 std::optional<bool> VisitVariableArrayType(const VariableArrayType *T) {
3607 llvm_unreachable(
3608 "Variable array should not occur in deduced return type of a function");
3609 }
3610
3611 std::optional<bool> VisitIncompleteArrayType(const IncompleteArrayType *T) {
3612 llvm_unreachable("Incomplete array should not occur in deduced return type "
3613 "of a function");
3614 }
3615
3616 std::optional<bool> VisitDependentArrayType(const IncompleteArrayType *T) {
3617 llvm_unreachable("Dependent array should not occur in deduced return type "
3618 "of a function");
3619 }
3620
3621private:
3622 const DeclContext *const ParentDC;
3623
3624 bool checkTemplateArgument(const TemplateArgument &Arg) {
3625 switch (Arg.getKind()) {
3627 return false;
3629 return CheckType(Arg.getIntegralType());
3631 return CheckType(Arg.getAsType());
3633 return isAncestorDeclContextOf(ParentDC, Arg.getAsExpr());
3635 // FIXME: The declaration in this case is not allowed to be in a function?
3636 return isAncestorDeclContextOf(ParentDC, Arg.getAsDecl());
3638 // FIXME: The type is not allowed to be in the function?
3639 return CheckType(Arg.getNullPtrType());
3641 return CheckType(Arg.getStructuralValueType());
3643 for (const auto &PackArg : Arg.getPackAsArray())
3644 if (checkTemplateArgument(PackArg))
3645 return true;
3646 return false;
3648 // Templates can not be defined locally in functions.
3649 // A template passed as argument can be not in ParentDC.
3650 return false;
3652 // Templates can not be defined locally in functions.
3653 // A template passed as argument can be not in ParentDC.
3654 return false;
3655 }
3656 llvm_unreachable("Unknown TemplateArgument::ArgKind enum");
3657 };
3658};
3659} // namespace
3660
3661/// This function checks if the given function has a return type that contains
3662/// a reference (in any way) to a declaration inside the same function.
3664 QualType FromTy = D->getType();
3665 const auto *FromFPT = FromTy->getAs<FunctionProtoType>();
3666 assert(FromFPT && "Must be called on FunctionProtoType");
3667
3668 auto IsCXX11LambdaWithouTrailingReturn = [&]() {
3669 if (Importer.FromContext.getLangOpts().CPlusPlus14) // C++14 or later
3670 return false;
3671
3672 if (FromFPT->hasTrailingReturn())
3673 return false;
3674
3675 if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
3676 return cast<CXXRecordDecl>(MD->getDeclContext())->isLambda();
3677
3678 return false;
3679 };
3680
3681 QualType RetT = FromFPT->getReturnType();
3682 if (isa<AutoType>(RetT.getTypePtr()) || IsCXX11LambdaWithouTrailingReturn()) {
3683 FunctionDecl *Def = D->getDefinition();
3684 IsTypeDeclaredInsideVisitor Visitor(Def ? Def : D);
3685 return Visitor.CheckType(RetT);
3686 }
3687
3688 return false;
3689}
3690
3692ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3693 Expr *ExplicitExpr = ESpec.getExpr();
3694 if (ExplicitExpr)
3695 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3696 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3697}
3698
3700
3702 auto RedeclIt = Redecls.begin();
3703 // Import the first part of the decl chain. I.e. import all previous
3704 // declarations starting from the canonical decl.
3705 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3706 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3707 if (!ToRedeclOrErr)
3708 return ToRedeclOrErr.takeError();
3709 }
3710 assert(*RedeclIt == D);
3711
3712 // Import the major distinguishing characteristics of this function.
3713 DeclContext *DC, *LexicalDC;
3714 DeclarationName Name;
3716 NamedDecl *ToD;
3717 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3718 return std::move(Err);
3719 if (ToD)
3720 return ToD;
3721
3722 FunctionDecl *FoundByLookup = nullptr;
3723 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3724
3725 // If this is a function template specialization, then try to find the same
3726 // existing specialization in the "to" context. The lookup below will not
3727 // find any specialization, but would find the primary template; thus, we
3728 // have to skip normal lookup in case of specializations.
3729 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3730 if (D->getTemplatedKind() ==
3732 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3733 if (!FoundFunctionOrErr)
3734 return FoundFunctionOrErr.takeError();
3735 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3736 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3737 return Def;
3738 FoundByLookup = FoundFunction;
3739 }
3740 }
3741 // Try to find a function in our own ("to") context with the same name, same
3742 // type, and in the same context as the function we're importing.
3743 else if (!LexicalDC->isFunctionOrMethod()) {
3744 SmallVector<NamedDecl *, 4> ConflictingDecls;
3746 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3747 for (auto *FoundDecl : FoundDecls) {
3748 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3749 continue;
3750
3751 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3752 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3753 continue;
3754
3755 if (IsStructuralMatch(D, FoundFunction)) {
3756 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3757 return Def;
3758 FoundByLookup = FoundFunction;
3759 break;
3760 }
3761 // FIXME: Check for overloading more carefully, e.g., by boosting
3762 // Sema::IsOverload out to the AST library.
3763
3764 // Function overloading is okay in C++.
3765 if (Importer.getToContext().getLangOpts().CPlusPlus)
3766 continue;
3767
3768 // Complain about inconsistent function types.
3769 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3770 << Name << D->getType() << FoundFunction->getType();
3771 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3772 << FoundFunction->getType();
3773 ConflictingDecls.push_back(FoundDecl);
3774 }
3775 }
3776
3777 if (!ConflictingDecls.empty()) {
3778 ExpectedName NameOrErr = Importer.HandleNameConflict(
3779 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3780 if (NameOrErr)
3781 Name = NameOrErr.get();
3782 else
3783 return NameOrErr.takeError();
3784 }
3785 }
3786
3787 // We do not allow more than one in-class declaration of a function. This is
3788 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3789 // assumes there is only one in-class declaration. Building a redecl
3790 // chain would result in more than one in-class declaration for
3791 // overrides (even if they are part of the same redecl chain inside the
3792 // derived class.)
3793 if (FoundByLookup) {
3794 if (isa<CXXMethodDecl>(FoundByLookup)) {
3795 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3796 if (!D->doesThisDeclarationHaveABody()) {
3797 if (FunctionTemplateDecl *DescribedD =
3798 D->getDescribedFunctionTemplate()) {
3799 // Handle a "templated" function together with its described
3800 // template. This avoids need for a similar check at import of the
3801 // described template.
3802 assert(FoundByLookup->getDescribedFunctionTemplate() &&
3803 "Templated function mapped to non-templated?");
3804 Importer.MapImported(DescribedD,
3805 FoundByLookup->getDescribedFunctionTemplate());
3806 }
3807 return Importer.MapImported(D, FoundByLookup);
3808 } else {
3809 // Let's continue and build up the redecl chain in this case.
3810 // FIXME Merge the functions into one decl.
3811 }
3812 }
3813 }
3814 }
3815
3816 DeclarationNameInfo NameInfo(Name, Loc);
3817 // Import additional name location/type info.
3818 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3819 return std::move(Err);
3820
3821 QualType FromTy = D->getType();
3822 TypeSourceInfo *FromTSI = D->getTypeSourceInfo();
3823 // Set to true if we do not import the type of the function as is. There are
3824 // cases when the original type would result in an infinite recursion during
3825 // the import. To avoid an infinite recursion when importing, we create the
3826 // FunctionDecl with a simplified function type and update it only after the
3827 // relevant AST nodes are already imported.
3828 // The type is related to TypeSourceInfo (it references the type), so we must
3829 // do the same with TypeSourceInfo.
3830 bool UsedDifferentProtoType = false;
3831 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3832 QualType FromReturnTy = FromFPT->getReturnType();
3833 // Functions with auto return type may define a struct inside their body
3834 // and the return type could refer to that struct.
3835 // E.g.: auto foo() { struct X{}; return X(); }
3836 // To avoid an infinite recursion when importing, create the FunctionDecl
3837 // with a simplified return type.
3839 FromReturnTy = Importer.getFromContext().VoidTy;
3840 UsedDifferentProtoType = true;
3841 }
3842 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3843 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3844 // FunctionDecl that we are importing the FunctionProtoType for.
3845 // To avoid an infinite recursion when importing, create the FunctionDecl
3846 // with a simplified function type.
3847 if (FromEPI.ExceptionSpec.SourceDecl ||
3848 FromEPI.ExceptionSpec.SourceTemplate ||
3849 FromEPI.ExceptionSpec.NoexceptExpr) {
3851 FromEPI = DefaultEPI;
3852 UsedDifferentProtoType = true;
3853 }
3854 FromTy = Importer.getFromContext().getFunctionType(
3855 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3856 FromTSI = Importer.getFromContext().getTrivialTypeSourceInfo(
3857 FromTy, D->getBeginLoc());
3858 }
3859
3860 Error Err = Error::success();
3861 auto T = importChecked(Err, FromTy);
3862 auto TInfo = importChecked(Err, FromTSI);
3863 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3864 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3865 auto ToDefaultLoc = importChecked(Err, D->getDefaultLoc());
3866 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3867 auto TrailingRequiresClause =
3868 importChecked(Err, D->getTrailingRequiresClause());
3869 if (Err)
3870 return std::move(Err);
3871
3872 // Import the function parameters.
3874 for (auto *P : D->parameters()) {
3875 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3876 Parameters.push_back(*ToPOrErr);
3877 else
3878 return ToPOrErr.takeError();
3879 }
3880
3881 // Create the imported function.
3882 FunctionDecl *ToFunction = nullptr;
3883 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3884 ExplicitSpecifier ESpec =
3885 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3886 if (Err)
3887 return std::move(Err);
3888 auto ToInheritedConstructor = InheritedConstructor();
3889 if (FromConstructor->isInheritingConstructor()) {
3890 Expected<InheritedConstructor> ImportedInheritedCtor =
3891 import(FromConstructor->getInheritedConstructor());
3892 if (!ImportedInheritedCtor)
3893 return ImportedInheritedCtor.takeError();
3894 ToInheritedConstructor = *ImportedInheritedCtor;
3895 }
3896 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3897 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3898 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3899 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3900 ToInheritedConstructor, TrailingRequiresClause))
3901 return ToFunction;
3902 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3903
3904 Error Err = Error::success();
3905 auto ToOperatorDelete = importChecked(
3906 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3907 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3908 if (Err)
3909 return std::move(Err);
3910
3911 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3912 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3913 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3914 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3915 TrailingRequiresClause))
3916 return ToFunction;
3917
3918 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3919
3920 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3921 } else if (CXXConversionDecl *FromConversion =
3922 dyn_cast<CXXConversionDecl>(D)) {
3923 ExplicitSpecifier ESpec =
3924 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3925 if (Err)
3926 return std::move(Err);
3927 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3928 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3929 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3930 D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3931 SourceLocation(), TrailingRequiresClause))
3932 return ToFunction;
3933 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3934 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3935 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3936 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3937 Method->UsesFPIntrin(), Method->isInlineSpecified(),
3938 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3939 return ToFunction;
3940 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3941 ExplicitSpecifier ESpec =
3942 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3943 CXXConstructorDecl *Ctor =
3944 importChecked(Err, Guide->getCorrespondingConstructor());
3945 if (Err)
3946 return std::move(Err);
3947 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3948 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3949 NameInfo, T, TInfo, ToEndLoc, Ctor))
3950 return ToFunction;
3951 cast<CXXDeductionGuideDecl>(ToFunction)
3952 ->setDeductionCandidateKind(Guide->getDeductionCandidateKind());
3953 } else {
3954 if (GetImportedOrCreateDecl(
3955 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3956 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3957 D->isInlineSpecified(), D->hasWrittenPrototype(),
3958 D->getConstexprKind(), TrailingRequiresClause))
3959 return ToFunction;
3960 }
3961
3962 // Connect the redecl chain.
3963 if (FoundByLookup) {
3964 auto *Recent = const_cast<FunctionDecl *>(
3965 FoundByLookup->getMostRecentDecl());
3966 ToFunction->setPreviousDecl(Recent);
3967 // FIXME Probably we should merge exception specifications. E.g. In the
3968 // "To" context the existing function may have exception specification with
3969 // noexcept-unevaluated, while the newly imported function may have an
3970 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3971 // decl and its redeclarations may be required.
3972 }
3973
3974 StringLiteral *Msg = D->getDeletedMessage();
3975 if (Msg) {
3976 auto Imported = import(Msg);
3977 if (!Imported)
3978 return Imported.takeError();
3979 Msg = *Imported;
3980 }
3981
3982 ToFunction->setQualifierInfo(ToQualifierLoc);
3983 ToFunction->setAccess(D->getAccess());
3984 ToFunction->setLexicalDeclContext(LexicalDC);
3985 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3986 ToFunction->setTrivial(D->isTrivial());
3987 ToFunction->setIsPureVirtual(D->isPureVirtual());
3988 ToFunction->setDefaulted(D->isDefaulted());
3989 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3990 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3992 D->FriendConstraintRefersToEnclosingTemplate());
3993 ToFunction->setRangeEnd(ToEndLoc);
3994 ToFunction->setDefaultLoc(ToDefaultLoc);
3995
3996 if (Msg)
3997 ToFunction->setDefaultedOrDeletedInfo(
3999 Importer.getToContext(), {}, Msg));
4000
4001 // Set the parameters.
4002 for (auto *Param : Parameters) {
4003 Param->setOwningFunction(ToFunction);
4004 ToFunction->addDeclInternal(Param);
4005 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
4006 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
4007 }
4008 ToFunction->setParams(Parameters);
4009
4010 // We need to complete creation of FunctionProtoTypeLoc manually with setting
4011 // params it refers to.
4012 if (TInfo) {
4013 if (auto ProtoLoc =
4014 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
4015 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
4016 ProtoLoc.setParam(I, Parameters[I]);
4017 }
4018 }
4019
4020 // Import the describing template function, if any.
4021 if (FromFT) {
4022 auto ToFTOrErr = import(FromFT);
4023 if (!ToFTOrErr)
4024 return ToFTOrErr.takeError();
4025 }
4026
4027 // Import Ctor initializers.
4028 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
4029 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
4030 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
4031 // Import first, then allocate memory and copy if there was no error.
4032 if (Error Err = ImportContainerChecked(
4033 FromConstructor->inits(), CtorInitializers))
4034 return std::move(Err);
4035 auto **Memory =
4036 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
4037 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
4038 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
4039 ToCtor->setCtorInitializers(Memory);
4040 ToCtor->setNumCtorInitializers(NumInitializers);
4041 }
4042 }
4043
4044 // If it is a template, import all related things.
4045 if (Error Err = ImportTemplateInformation(D, ToFunction))
4046 return std::move(Err);
4047
4048 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
4049 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
4050 FromCXXMethod))
4051 return std::move(Err);
4052
4053 if (D->doesThisDeclarationHaveABody()) {
4054 Error Err = ImportFunctionDeclBody(D, ToFunction);
4055
4056 if (Err)
4057 return std::move(Err);
4058 }
4059
4060 // Import and set the original type in case we used another type.
4061 if (UsedDifferentProtoType) {
4062 if (ExpectedType TyOrErr = import(D->getType()))
4063 ToFunction->setType(*TyOrErr);
4064 else
4065 return TyOrErr.takeError();
4066 if (Expected<TypeSourceInfo *> TSIOrErr = import(D->getTypeSourceInfo()))
4067 ToFunction->setTypeSourceInfo(*TSIOrErr);
4068 else
4069 return TSIOrErr.takeError();
4070 }
4071
4072 // FIXME: Other bits to merge?
4073
4074 addDeclToContexts(D, ToFunction);
4075
4076 // Import the rest of the chain. I.e. import all subsequent declarations.
4077 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4078 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
4079 if (!ToRedeclOrErr)
4080 return ToRedeclOrErr.takeError();
4081 }
4082
4083 return ToFunction;
4084}
4085
4087 return VisitFunctionDecl(D);
4088}
4089
4091 return VisitCXXMethodDecl(D);
4092}
4093
4095 return VisitCXXMethodDecl(D);
4096}
4097
4099 return VisitCXXMethodDecl(D);
4100}
4101
4104 return VisitFunctionDecl(D);
4105}
4106
4108 // Import the major distinguishing characteristics of a variable.
4109 DeclContext *DC, *LexicalDC;
4110 DeclarationName Name;
4112 NamedDecl *ToD;
4113 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4114 return std::move(Err);
4115 if (ToD)
4116 return ToD;
4117
4118 // Determine whether we've already imported this field.
4119 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4120 for (auto *FoundDecl : FoundDecls) {
4121 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
4122 // For anonymous fields, match up by index.
4123 if (!Name &&
4125 ASTImporter::getFieldIndex(FoundField))
4126 continue;
4127
4128 if (Importer.IsStructurallyEquivalent(D->getType(),
4129 FoundField->getType())) {
4130 Importer.MapImported(D, FoundField);
4131 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
4132 // initializer of a FieldDecl might not had been instantiated in the
4133 // "To" context. However, the "From" context might instantiated that,
4134 // thus we have to merge that.
4135 // Note: `hasInClassInitializer()` is not the same as non-null
4136 // `getInClassInitializer()` value.
4137 if (Expr *FromInitializer = D->getInClassInitializer()) {
4138 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) {
4139 // Import of the FromInitializer may result in the setting of
4140 // InClassInitializer. If not, set it here.
4141 assert(FoundField->hasInClassInitializer() &&
4142 "Field should have an in-class initializer if it has an "
4143 "expression for it.");
4144 if (!FoundField->getInClassInitializer())
4145 FoundField->setInClassInitializer(*ToInitializerOrErr);
4146 } else {
4147 return ToInitializerOrErr.takeError();
4148 }
4149 }
4150 return FoundField;
4151 }
4152
4153 // FIXME: Why is this case not handled with calling HandleNameConflict?
4154 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4155 << Name << D->getType() << FoundField->getType();
4156 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4157 << FoundField->getType();
4158
4159 return make_error<ASTImportError>(ASTImportError::NameConflict);
4160 }
4161 }
4162
4163 Error Err = Error::success();
4164 auto ToType = importChecked(Err, D->getType());
4165 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
4166 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4167 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4168 if (Err)
4169 return std::move(Err);
4170 const Type *ToCapturedVLAType = nullptr;
4171 if (Error Err = Importer.importInto(
4172 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
4173 return std::move(Err);
4174
4175 FieldDecl *ToField;
4176 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
4177 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4178 ToType, ToTInfo, ToBitWidth, D->isMutable(),
4179 D->getInClassInitStyle()))
4180 return ToField;
4181
4182 // We need [[no_unqiue_address]] attributes to be added to FieldDecl, before
4183 // we add fields in CXXRecordDecl::addedMember, otherwise record will be
4184 // marked as having non-zero size.
4185 Err = Importer.ImportAttrs(ToField, D);
4186 if (Err)
4187 return std::move(Err);
4188 ToField->setAccess(D->getAccess());
4189 ToField->setLexicalDeclContext(LexicalDC);
4190 ToField->setImplicit(D->isImplicit());
4191 if (ToCapturedVLAType)
4192 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
4193 LexicalDC->addDeclInternal(ToField);
4194 // Import initializer only after the field was created, it may have recursive
4195 // reference to the field.
4196 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
4197 if (Err)
4198 return std::move(Err);
4199 if (ToInitializer) {
4200 auto *AlreadyImported = ToField->getInClassInitializer();
4201 if (AlreadyImported)
4202 assert(ToInitializer == AlreadyImported &&
4203 "Duplicate import of in-class initializer.");
4204 else
4205 ToField->setInClassInitializer(ToInitializer);
4206 }
4207
4208 return ToField;
4209}
4210
4212 // Import the major distinguishing characteristics of a variable.
4213 DeclContext *DC, *LexicalDC;
4214 DeclarationName Name;
4216 NamedDecl *ToD;
4217 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4218 return std::move(Err);
4219 if (ToD)
4220 return ToD;
4221
4222 // Determine whether we've already imported this field.
4223 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4224 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
4225 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
4226 // For anonymous indirect fields, match up by index.
4227 if (!Name &&
4229 ASTImporter::getFieldIndex(FoundField))
4230 continue;
4231
4232 if (Importer.IsStructurallyEquivalent(D->getType(),
4233 FoundField->getType(),
4234 !Name.isEmpty())) {
4235 Importer.MapImported(D, FoundField);
4236 return FoundField;
4237 }
4238
4239 // If there are more anonymous fields to check, continue.
4240 if (!Name && I < N-1)
4241 continue;
4242
4243 // FIXME: Why is this case not handled with calling HandleNameConflict?
4244 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
4245 << Name << D->getType() << FoundField->getType();
4246 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
4247 << FoundField->getType();
4248
4249 return make_error<ASTImportError>(ASTImportError::NameConflict);
4250 }
4251 }
4252
4253 // Import the type.
4254 auto TypeOrErr = import(D->getType());
4255 if (!TypeOrErr)
4256 return TypeOrErr.takeError();
4257
4258 auto **NamedChain =
4259 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
4260
4261 unsigned i = 0;
4262 for (auto *PI : D->chain())
4263 if (Expected<NamedDecl *> ToD = import(PI))
4264 NamedChain[i++] = *ToD;
4265 else
4266 return ToD.takeError();
4267
4268 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
4269 IndirectFieldDecl *ToIndirectField;
4270 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
4271 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
4272 // FIXME here we leak `NamedChain` which is allocated before
4273 return ToIndirectField;
4274
4275 ToIndirectField->setAccess(D->getAccess());
4276 ToIndirectField->setLexicalDeclContext(LexicalDC);
4277 LexicalDC->addDeclInternal(ToIndirectField);
4278 return ToIndirectField;
4279}
4280
4281/// Used as return type of getFriendCountAndPosition.
4283 /// Number of similar looking friends.
4284 unsigned int TotalCount;
4285 /// Index of the specific FriendDecl.
4286 unsigned int IndexOfDecl;
4287};
4288
4289static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1,
4290 FriendDecl *FD2) {
4291 if ((!FD1->getFriendType()) != (!FD2->getFriendType()))
4292 return false;
4293
4294 if (const TypeSourceInfo *TSI = FD1->getFriendType())
4295 return Importer.IsStructurallyEquivalent(
4296 TSI->getType(), FD2->getFriendType()->getType(), /*Complain=*/false);
4297
4298 ASTImporter::NonEquivalentDeclSet NonEquivalentDecls;
4300 FD1->getASTContext(), FD2->getASTContext(), NonEquivalentDecls,
4302 /* StrictTypeSpelling = */ false, /* Complain = */ false);
4303 return Ctx.IsEquivalent(FD1, FD2);
4304}
4305
4307 FriendDecl *FD) {
4308 unsigned int FriendCount = 0;
4309 std::optional<unsigned int> FriendPosition;
4310 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
4311
4312 for (FriendDecl *FoundFriend : RD->friends()) {
4313 if (FoundFriend == FD) {
4314 FriendPosition = FriendCount;
4315 ++FriendCount;
4316 } else if (IsEquivalentFriend(Importer, FD, FoundFriend)) {
4317 ++FriendCount;
4318 }
4319 }
4320
4321 assert(FriendPosition && "Friend decl not found in own parent.");
4322
4323 return {FriendCount, *FriendPosition};
4324}
4325
4327 // Import the major distinguishing characteristics of a declaration.
4328 DeclContext *DC, *LexicalDC;
4329 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4330 return std::move(Err);
4331
4332 // Determine whether we've already imported this decl.
4333 // FriendDecl is not a NamedDecl so we cannot use lookup.
4334 // We try to maintain order and count of redundant friend declarations.
4335 const auto *RD = cast<CXXRecordDecl>(DC);
4336 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
4337 for (FriendDecl *ImportedFriend : RD->friends())
4338 if (IsEquivalentFriend(Importer, D, ImportedFriend))
4339 ImportedEquivalentFriends.push_back(ImportedFriend);
4340
4341 FriendCountAndPosition CountAndPosition =
4342 getFriendCountAndPosition(Importer, D);
4343
4344 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&
4345 "Class with non-matching friends is imported, ODR check wrong?");
4346 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
4347 return Importer.MapImported(
4348 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
4349
4350 // Not found. Create it.
4351 // The declarations will be put into order later by ImportDeclContext.
4353 if (NamedDecl *FriendD = D->getFriendDecl()) {
4354 NamedDecl *ToFriendD;
4355 if (Error Err = importInto(ToFriendD, FriendD))
4356 return std::move(Err);
4357
4358 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
4359 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
4360 ToFriendD->setObjectOfFriendDecl(false);
4361
4362 ToFU = ToFriendD;
4363 } else { // The friend is a type, not a decl.
4364 if (auto TSIOrErr = import(D->getFriendType()))
4365 ToFU = *TSIOrErr;
4366 else
4367 return TSIOrErr.takeError();
4368 }
4369
4370 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
4371 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
4372 for (unsigned I = 0; I < D->NumTPLists; I++) {
4373 if (auto ListOrErr = import(FromTPLists[I]))
4374 ToTPLists[I] = *ListOrErr;
4375 else
4376 return ListOrErr.takeError();
4377 }
4378
4379 auto LocationOrErr = import(D->getLocation());
4380 if (!LocationOrErr)
4381 return LocationOrErr.takeError();
4382 auto FriendLocOrErr = import(D->getFriendLoc());
4383 if (!FriendLocOrErr)
4384 return FriendLocOrErr.takeError();
4385
4386 FriendDecl *FrD;
4387 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
4388 *LocationOrErr, ToFU,
4389 *FriendLocOrErr, ToTPLists))
4390 return FrD;
4391
4392 FrD->setAccess(D->getAccess());
4393 FrD->setLexicalDeclContext(LexicalDC);
4394 LexicalDC->addDeclInternal(FrD);
4395 return FrD;
4396}
4397
4399 // Import the major distinguishing characteristics of an ivar.
4400 DeclContext *DC, *LexicalDC;
4401 DeclarationName Name;
4403 NamedDecl *ToD;
4404 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4405 return std::move(Err);
4406 if (ToD)
4407 return ToD;
4408
4409 // Determine whether we've already imported this ivar
4410 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4411 for (auto *FoundDecl : FoundDecls) {
4412 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
4413 if (Importer.IsStructurallyEquivalent(D->getType(),
4414 FoundIvar->getType())) {
4415 Importer.MapImported(D, FoundIvar);
4416 return FoundIvar;
4417 }
4418
4419 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
4420 << Name << D->getType() << FoundIvar->getType();
4421 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
4422 << FoundIvar->getType();
4423
4424 return make_error<ASTImportError>(ASTImportError::NameConflict);
4425 }
4426 }
4427
4428 Error Err = Error::success();
4429 auto ToType = importChecked(Err, D->getType());
4430 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4431 auto ToBitWidth = importChecked(Err, D->getBitWidth());
4432 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4433 if (Err)
4434 return std::move(Err);
4435
4436 ObjCIvarDecl *ToIvar;
4437 if (GetImportedOrCreateDecl(
4438 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
4439 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
4440 ToType, ToTypeSourceInfo,
4441 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
4442 return ToIvar;
4443
4444 ToIvar->setLexicalDeclContext(LexicalDC);
4445 LexicalDC->addDeclInternal(ToIvar);
4446 return ToIvar;
4447}
4448
4450
4452 auto RedeclIt = Redecls.begin();
4453 // Import the first part of the decl chain. I.e. import all previous
4454 // declarations starting from the canonical decl.
4455 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4456 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4457 if (!RedeclOrErr)
4458 return RedeclOrErr.takeError();
4459 }
4460 assert(*RedeclIt == D);
4461
4462 // Import the major distinguishing characteristics of a variable.
4463 DeclContext *DC, *LexicalDC;
4464 DeclarationName Name;
4466 NamedDecl *ToD;
4467 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4468 return std::move(Err);
4469 if (ToD)
4470 return ToD;
4471
4472 // Try to find a variable in our own ("to") context with the same name and
4473 // in the same context as the variable we're importing.
4474 VarDecl *FoundByLookup = nullptr;
4475 if (D->isFileVarDecl()) {
4476 SmallVector<NamedDecl *, 4> ConflictingDecls;
4477 unsigned IDNS = Decl::IDNS_Ordinary;
4478 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4479 for (auto *FoundDecl : FoundDecls) {
4480 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4481 continue;
4482
4483 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4484 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4485 continue;
4486 if (Importer.IsStructurallyEquivalent(D->getType(),
4487 FoundVar->getType())) {
4488
4489 // The VarDecl in the "From" context has a definition, but in the
4490 // "To" context we already have a definition.
4491 VarDecl *FoundDef = FoundVar->getDefinition();
4492 if (D->isThisDeclarationADefinition() && FoundDef)
4493 // FIXME Check for ODR error if the two definitions have
4494 // different initializers?
4495 return Importer.MapImported(D, FoundDef);
4496
4497 // The VarDecl in the "From" context has an initializer, but in the
4498 // "To" context we already have an initializer.
4499 const VarDecl *FoundDInit = nullptr;
4500 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4501 // FIXME Diagnose ODR error if the two initializers are different?
4502 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4503
4504 FoundByLookup = FoundVar;
4505 break;
4506 }
4507
4508 const ArrayType *FoundArray
4509 = Importer.getToContext().getAsArrayType(FoundVar->getType());
4510 const ArrayType *TArray
4511 = Importer.getToContext().getAsArrayType(D->getType());
4512 if (FoundArray && TArray) {
4513 if (isa<IncompleteArrayType>(FoundArray) &&
4514 isa<ConstantArrayType>(TArray)) {
4515 // Import the type.
4516 if (auto TyOrErr = import(D->getType()))
4517 FoundVar->setType(*TyOrErr);
4518 else
4519 return TyOrErr.takeError();
4520
4521 FoundByLookup = FoundVar;
4522 break;
4523 } else if (isa<IncompleteArrayType>(TArray) &&
4524 isa<ConstantArrayType>(FoundArray)) {
4525 FoundByLookup = FoundVar;
4526 break;
4527 }
4528 }
4529
4530 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4531 << Name << D->getType() << FoundVar->getType();
4532 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4533 << FoundVar->getType();
4534 ConflictingDecls.push_back(FoundDecl);
4535 }
4536 }
4537
4538 if (!ConflictingDecls.empty()) {
4539 ExpectedName NameOrErr = Importer.HandleNameConflict(
4540 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4541 if (NameOrErr)
4542 Name = NameOrErr.get();
4543 else
4544 return NameOrErr.takeError();
4545 }
4546 }
4547
4548 Error Err = Error::success();
4549 auto ToType = importChecked(Err, D->getType());
4550 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4551 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4552 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4553 if (Err)
4554 return std::move(Err);
4555
4556 VarDecl *ToVar;
4557 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4558 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4559 if (Error Err =
4560 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4561 return std::move(Err);
4562 DecompositionDecl *ToDecomp;
4563 if (GetImportedOrCreateDecl(
4564 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4565 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4566 return ToDecomp;
4567 ToVar = ToDecomp;
4568 } else {
4569 // Create the imported variable.
4570 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4571 ToInnerLocStart, Loc,
4572 Name.getAsIdentifierInfo(), ToType,
4573 ToTypeSourceInfo, D->getStorageClass()))
4574 return ToVar;
4575 }
4576
4577 ToVar->setTSCSpec(D->getTSCSpec());
4578 ToVar->setQualifierInfo(ToQualifierLoc);
4579 ToVar->setAccess(D->getAccess());
4580 ToVar->setLexicalDeclContext(LexicalDC);
4581 if (D->isInlineSpecified())
4582 ToVar->setInlineSpecified();
4583 if (D->isInline())
4584 ToVar->setImplicitlyInline();
4585
4586 if (FoundByLookup) {
4587 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4588 ToVar->setPreviousDecl(Recent);
4589 }
4590
4591 // Import the described template, if any.
4592 if (D->getDescribedVarTemplate()) {
4593 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4594 if (!ToVTOrErr)
4595 return ToVTOrErr.takeError();
4596 } else if (MemberSpecializationInfo *MSI = D->getMemberSpecializationInfo()) {
4597 TemplateSpecializationKind SK = MSI->getTemplateSpecializationKind();
4598 VarDecl *FromInst = D->getInstantiatedFromStaticDataMember();
4599 if (Expected<VarDecl *> ToInstOrErr = import(FromInst))
4600 ToVar->setInstantiationOfStaticDataMember(*ToInstOrErr, SK);
4601 else
4602 return ToInstOrErr.takeError();
4603 if (ExpectedSLoc POIOrErr = import(MSI->getPointOfInstantiation()))
4605 else
4606 return POIOrErr.takeError();
4607 }
4608
4609 if (Error Err = ImportInitializer(D, ToVar))
4610 return std::move(Err);
4611
4612 if (D->isConstexpr())
4613 ToVar->setConstexpr(true);
4614
4615 addDeclToContexts(D, ToVar);
4616
4617 // Import the rest of the chain. I.e. import all subsequent declarations.
4618 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4619 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4620 if (!RedeclOrErr)
4621 return RedeclOrErr.takeError();
4622 }
4623
4624 return ToVar;
4625}
4626
4628 // Parameters are created in the translation unit's context, then moved
4629 // into the function declaration's context afterward.
4631
4632 Error Err = Error::success();
4633 auto ToDeclName = importChecked(Err, D->getDeclName());
4634 auto ToLocation = importChecked(Err, D->getLocation());
4635 auto ToType = importChecked(Err, D->getType());
4636 if (Err)
4637 return std::move(Err);
4638
4639 // Create the imported parameter.
4640 ImplicitParamDecl *ToParm = nullptr;
4641 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4642 ToLocation, ToDeclName.getAsIdentifierInfo(),
4643 ToType, D->getParameterKind()))
4644 return ToParm;
4645 return ToParm;
4646}
4647
4649 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4652 FromParam->getExplicitObjectParamThisLoc());
4653 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4654
4655 if (FromParam->hasUninstantiatedDefaultArg()) {
4656 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4657 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4658 else
4659 return ToDefArgOrErr.takeError();
4660 } else if (FromParam->hasUnparsedDefaultArg()) {
4661 ToParam->setUnparsedDefaultArg();
4662 } else if (FromParam->hasDefaultArg()) {
4663 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4664 ToParam->setDefaultArg(*ToDefArgOrErr);
4665 else
4666 return ToDefArgOrErr.takeError();
4667 }
4668
4669 return Error::success();
4670}
4671
4674 Error Err = Error::success();
4675 CXXConstructorDecl *ToBaseCtor = importChecked(Err, From.getConstructor());
4676 ConstructorUsingShadowDecl *ToShadow =
4677 importChecked(Err, From.getShadowDecl());
4678 if (Err)
4679 return std::move(Err);
4680 return InheritedConstructor(ToShadow, ToBaseCtor);
4681}
4682
4684 // Parameters are created in the translation unit's context, then moved
4685 // into the function declaration's context afterward.
4687
4688 Error Err = Error::success();
4689 auto ToDeclName = importChecked(Err, D->getDeclName());
4690 auto ToLocation = importChecked(Err, D->getLocation());
4691 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4692 auto ToType = importChecked(Err, D->getType());
4693 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4694 if (Err)
4695 return std::move(Err);
4696
4697 ParmVarDecl *ToParm;
4698 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4699 ToInnerLocStart, ToLocation,
4700 ToDeclName.getAsIdentifierInfo(), ToType,
4701 ToTypeSourceInfo, D->getStorageClass(),
4702 /*DefaultArg*/ nullptr))
4703 return ToParm;
4704
4705 // Set the default argument. It should be no problem if it was already done.
4706 // Do not import the default expression before GetImportedOrCreateDecl call
4707 // to avoid possible infinite import loop because circular dependency.
4708 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4709 return std::move(Err);
4710
4711 if (D->isObjCMethodParameter()) {
4712 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4713 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4714 } else {
4715 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4716 D->getFunctionScopeIndex());
4717 }
4718
4719 return ToParm;
4720}
4721
4723 // Import the major distinguishing characteristics of a method.
4724 DeclContext *DC, *LexicalDC;
4725 DeclarationName Name;
4727 NamedDecl *ToD;
4728 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4729 return std::move(Err);
4730 if (ToD)
4731 return ToD;
4732
4733 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4734 for (auto *FoundDecl : FoundDecls) {
4735 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4736 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4737 continue;
4738
4739 // Check return types.
4740 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4741 FoundMethod->getReturnType())) {
4742 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4743 << D->isInstanceMethod() << Name << D->getReturnType()
4744 << FoundMethod->getReturnType();
4745 Importer.ToDiag(FoundMethod->getLocation(),
4746 diag::note_odr_objc_method_here)
4747 << D->isInstanceMethod() << Name;
4748
4749 return make_error<ASTImportError>(ASTImportError::NameConflict);
4750 }
4751
4752 // Check the number of parameters.
4753 if (D->param_size() != FoundMethod->param_size()) {
4754 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4755 << D->isInstanceMethod() << Name
4756 << D->param_size() << FoundMethod->param_size();
4757 Importer.ToDiag(FoundMethod->getLocation(),
4758 diag::note_odr_objc_method_here)
4759 << D->isInstanceMethod() << Name;
4760
4761 return make_error<ASTImportError>(ASTImportError::NameConflict);
4762 }
4763
4764 // Check parameter types.
4765 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4766 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4767 P != PEnd; ++P, ++FoundP) {
4768 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4769 (*FoundP)->getType())) {
4770 Importer.FromDiag((*P)->getLocation(),
4771 diag::warn_odr_objc_method_param_type_inconsistent)
4772 << D->isInstanceMethod() << Name
4773 << (*P)->getType() << (*FoundP)->getType();
4774 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4775 << (*FoundP)->getType();
4776
4777 return make_error<ASTImportError>(ASTImportError::NameConflict);
4778 }
4779 }
4780
4781 // Check variadic/non-variadic.
4782 // Check the number of parameters.
4783 if (D->isVariadic() != FoundMethod->isVariadic()) {
4784 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4785 << D->isInstanceMethod() << Name;
4786 Importer.ToDiag(FoundMethod->getLocation(),
4787 diag::note_odr_objc_method_here)
4788 << D->isInstanceMethod() << Name;
4789
4790 return make_error<ASTImportError>(ASTImportError::NameConflict);
4791 }
4792
4793 // FIXME: Any other bits we need to merge?
4794 return Importer.MapImported(D, FoundMethod);
4795 }
4796 }
4797
4798 Error Err = Error::success();
4799 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4800 auto ToReturnType = importChecked(Err, D->getReturnType());
4801 auto ToReturnTypeSourceInfo =
4802 importChecked(Err, D->getReturnTypeSourceInfo());
4803 if (Err)
4804 return std::move(Err);
4805
4806 ObjCMethodDecl *ToMethod;
4807 if (GetImportedOrCreateDecl(
4808 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4809 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4810 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4811 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4812 D->getImplementationControl(), D->hasRelatedResultType()))
4813 return ToMethod;
4814
4815 // FIXME: When we decide to merge method definitions, we'll need to
4816 // deal with implicit parameters.
4817
4818 // Import the parameters
4820 for (auto *FromP : D->parameters()) {
4821 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4822 ToParams.push_back(*ToPOrErr);
4823 else
4824 return ToPOrErr.takeError();
4825 }
4826
4827 // Set the parameters.
4828 for (auto *ToParam : ToParams) {
4829 ToParam->setOwningFunction(ToMethod);
4830 ToMethod->addDeclInternal(ToParam);
4831 }
4832
4834 D->getSelectorLocs(FromSelLocs);
4835 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4836 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4837 return std::move(Err);
4838
4839 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4840
4841 ToMethod->setLexicalDeclContext(LexicalDC);
4842 LexicalDC->addDeclInternal(ToMethod);
4843
4844 // Implicit params are declared when Sema encounters the definition but this
4845 // never happens when the method is imported. Manually declare the implicit
4846 // params now that the MethodDecl knows its class interface.
4847 if (D->getSelfDecl())
4848 ToMethod->createImplicitParams(Importer.getToContext(),
4849 ToMethod->getClassInterface());
4850
4851 return ToMethod;
4852}
4853
4855 // Import the major distinguishing characteristics of a category.
4856 DeclContext *DC, *LexicalDC;
4857 DeclarationName Name;
4859 NamedDecl *ToD;
4860 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4861 return std::move(Err);
4862 if (ToD)
4863 return ToD;
4864
4865 Error Err = Error::success();
4866 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4867 auto ToLocation = importChecked(Err, D->getLocation());
4868 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4869 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4870 if (Err)
4871 return std::move(Err);
4872
4874 if (GetImportedOrCreateDecl(
4875 Result, D, Importer.getToContext(), DC, D->getVariance(),
4876 ToVarianceLoc, D->getIndex(),
4877 ToLocation, Name.getAsIdentifierInfo(),
4878 ToColonLoc, ToTypeSourceInfo))
4879 return Result;
4880
4881 // Only import 'ObjCTypeParamType' after the decl is created.
4882 auto ToTypeForDecl = importChecked(Err, D->getTypeForDecl());
4883 if (Err)
4884 return std::move(Err);
4885 Result->setTypeForDecl(ToTypeForDecl);
4886 Result->setLexicalDeclContext(LexicalDC);
4887 return Result;
4888}
4889
4891 // Import the major distinguishing characteristics of a category.
4892 DeclContext *DC, *LexicalDC;
4893 DeclarationName Name;
4895 NamedDecl *ToD;
4896 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4897 return std::move(Err);
4898 if (ToD)
4899 return ToD;
4900
4901 ObjCInterfaceDecl *ToInterface;
4902 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4903 return std::move(Err);
4904
4905 // Determine if we've already encountered this category.
4906 ObjCCategoryDecl *MergeWithCategory
4907 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4908 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4909 if (!ToCategory) {
4910
4911 Error Err = Error::success();
4912 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4913 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4914 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4915 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4916 if (Err)
4917 return std::move(Err);
4918
4919 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4920 ToAtStartLoc, Loc,
4921 ToCategoryNameLoc,
4922 Name.getAsIdentifierInfo(), ToInterface,
4923 /*TypeParamList=*/nullptr,
4924 ToIvarLBraceLoc,
4925 ToIvarRBraceLoc))
4926 return ToCategory;
4927
4928 ToCategory->setLexicalDeclContext(LexicalDC);
4929 LexicalDC->addDeclInternal(ToCategory);
4930 // Import the type parameter list after MapImported, to avoid
4931 // loops when bringing in their DeclContext.
4932 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4933 ToCategory->setTypeParamList(*PListOrErr);
4934 else
4935 return PListOrErr.takeError();
4936
4937 // Import protocols
4939 SmallVector<SourceLocation, 4> ProtocolLocs;
4941 = D->protocol_loc_begin();
4942 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4943 FromProtoEnd = D->protocol_end();
4944 FromProto != FromProtoEnd;
4945 ++FromProto, ++FromProtoLoc) {
4946 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4947 Protocols.push_back(*ToProtoOrErr);
4948 else
4949 return ToProtoOrErr.takeError();
4950
4951 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4952 ProtocolLocs.push_back(*ToProtoLocOrErr);
4953 else
4954 return ToProtoLocOrErr.takeError();
4955 }
4956
4957 // FIXME: If we're merging, make sure that the protocol list is the same.
4958 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4959 ProtocolLocs.data(), Importer.getToContext());
4960
4961 } else {
4962 Importer.MapImported(D, ToCategory);
4963 }
4964
4965 // Import all of the members of this category.
4966 if (Error Err = ImportDeclContext(D))
4967 return std::move(Err);
4968
4969 // If we have an implementation, import it as well.
4970 if (D->getImplementation()) {
4971 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4972 import(D->getImplementation()))
4973 ToCategory->setImplementation(*ToImplOrErr);
4974 else
4975 return ToImplOrErr.takeError();
4976 }
4977
4978 return ToCategory;
4979}
4980
4983 if (To->getDefinition()) {
4985 if (Error Err = ImportDeclContext(From))
4986 return Err;
4987 return Error::success();
4988 }
4989
4990 // Start the protocol definition
4991 To->startDefinition();
4992
4993 // Import protocols
4995 SmallVector<SourceLocation, 4> ProtocolLocs;
4997 From->protocol_loc_begin();
4998 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4999 FromProtoEnd = From->protocol_end();
5000 FromProto != FromProtoEnd;
5001 ++FromProto, ++FromProtoLoc) {
5002 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
5003 Protocols.push_back(*ToProtoOrErr);
5004 else
5005 return ToProtoOrErr.takeError();
5006
5007 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
5008 ProtocolLocs.push_back(*ToProtoLocOrErr);
5009 else
5010 return ToProtoLocOrErr.takeError();
5011
5012 }
5013
5014 // FIXME: If we're merging, make sure that the protocol list is the same.
5015 To->setProtocolList(Protocols.data(), Protocols.size(),
5016 ProtocolLocs.data(), Importer.getToContext());
5017
5018 if (shouldForceImportDeclContext(Kind)) {
5019 // Import all of the members of this protocol.
5020 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5021 return Err;
5022 }
5023 return Error::success();
5024}
5025
5027 // If this protocol has a definition in the translation unit we're coming
5028 // from, but this particular declaration is not that definition, import the
5029 // definition and map to that.
5030 ObjCProtocolDecl *Definition = D->getDefinition();
5031 if (Definition && Definition != D) {
5032 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5033 return Importer.MapImported(D, *ImportedDefOrErr);
5034 else
5035 return ImportedDefOrErr.takeError();
5036 }
5037
5038 // Import the major distinguishing characteristics of a protocol.
5039 DeclContext *DC, *LexicalDC;
5040 DeclarationName Name;
5042 NamedDecl *ToD;
5043 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5044 return std::move(Err);
5045 if (ToD)
5046 return ToD;
5047
5048 ObjCProtocolDecl *MergeWithProtocol = nullptr;
5049 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5050 for (auto *FoundDecl : FoundDecls) {
5052 continue;
5053
5054 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
5055 break;
5056 }
5057
5058 ObjCProtocolDecl *ToProto = MergeWithProtocol;
5059 if (!ToProto) {
5060 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
5061 if (!ToAtBeginLocOrErr)
5062 return ToAtBeginLocOrErr.takeError();
5063
5064 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
5065 Name.getAsIdentifierInfo(), Loc,
5066 *ToAtBeginLocOrErr,
5067 /*PrevDecl=*/nullptr))
5068 return ToProto;
5069 ToProto->setLexicalDeclContext(LexicalDC);
5070 LexicalDC->addDeclInternal(ToProto);
5071 }
5072
5073 Importer.MapImported(D, ToProto);
5074
5075 if (D->isThisDeclarationADefinition())
5076 if (Error Err = ImportDefinition(D, ToProto))
5077 return std::move(Err);
5078
5079 return ToProto;
5080}
5081
5083 DeclContext *DC, *LexicalDC;
5084 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5085 return std::move(Err);
5086
5087 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
5088 if (!ExternLocOrErr)
5089 return ExternLocOrErr.takeError();
5090
5091 ExpectedSLoc LangLocOrErr = import(D->getLocation());
5092 if (!LangLocOrErr)
5093 return LangLocOrErr.takeError();
5094
5095 bool HasBraces = D->hasBraces();
5096
5097 LinkageSpecDecl *ToLinkageSpec;
5098 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
5099 *ExternLocOrErr, *LangLocOrErr,
5100 D->getLanguage(), HasBraces))
5101 return ToLinkageSpec;
5102
5103 if (HasBraces) {
5104 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
5105 if (!RBraceLocOrErr)
5106 return RBraceLocOrErr.takeError();
5107 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
5108 }
5109
5110 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
5111 LexicalDC->addDeclInternal(ToLinkageSpec);
5112
5113 return ToLinkageSpec;
5114}
5115
5117 BaseUsingDecl *ToSI) {
5118 for (UsingShadowDecl *FromShadow : D->shadows()) {
5119 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
5120 ToSI->addShadowDecl(*ToShadowOrErr);
5121 else
5122 // FIXME: We return error here but the definition is already created
5123 // and available with lookups. How to fix this?..
5124 return ToShadowOrErr.takeError();
5125 }
5126 return ToSI;
5127}
5128
5130 DeclContext *DC, *LexicalDC;
5131 DeclarationName Name;
5133 NamedDecl *ToD = nullptr;
5134 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5135 return std::move(Err);
5136 if (ToD)
5137 return ToD;
5138
5139 Error Err = Error::success();
5140 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
5141 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5142 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5143 if (Err)
5144 return std::move(Err);
5145
5146 DeclarationNameInfo NameInfo(Name, ToLoc);
5147 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
5148 return std::move(Err);
5149
5150 UsingDecl *ToUsing;
5151 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
5152 ToUsingLoc, ToQualifierLoc, NameInfo,
5153 D->hasTypename()))
5154 return ToUsing;
5155
5156 ToUsing->setLexicalDeclContext(LexicalDC);
5157 LexicalDC->addDeclInternal(ToUsing);
5158
5159 if (NamedDecl *FromPattern =
5161 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
5163 ToUsing, *ToPatternOrErr);
5164 else
5165 return ToPatternOrErr.takeError();
5166 }
5167
5168 return ImportUsingShadowDecls(D, ToUsing);
5169}
5170
5172 DeclContext *DC, *LexicalDC;
5173 DeclarationName Name;
5175 NamedDecl *ToD = nullptr;
5176 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5177 return std::move(Err);
5178 if (ToD)
5179 return ToD;
5180
5181 Error Err = Error::success();
5182 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5183 auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
5184 auto ToNameLoc = importChecked(Err, D->getLocation());
5185 auto *ToEnumType = importChecked(Err, D->getEnumType());
5186 if (Err)
5187 return std::move(Err);
5188
5189 UsingEnumDecl *ToUsingEnum;
5190 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
5191 ToUsingLoc, ToEnumLoc, ToNameLoc, ToEnumType))
5192 return ToUsingEnum;
5193
5194 ToUsingEnum->setLexicalDeclContext(LexicalDC);
5195 LexicalDC->addDeclInternal(ToUsingEnum);
5196
5197 if (UsingEnumDecl *FromPattern =
5199 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
5200 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
5201 *ToPatternOrErr);
5202 else
5203 return ToPatternOrErr.takeError();
5204 }
5205
5206 return ImportUsingShadowDecls(D, ToUsingEnum);
5207}
5208
5210 DeclContext *DC, *LexicalDC;
5211 DeclarationName Name;
5213 NamedDecl *ToD = nullptr;
5214 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5215 return std::move(Err);
5216 if (ToD)
5217 return ToD;
5218
5219 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
5220 if (!ToIntroducerOrErr)
5221 return ToIntroducerOrErr.takeError();
5222
5223 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
5224 if (!ToTargetOrErr)
5225 return ToTargetOrErr.takeError();
5226
5227 UsingShadowDecl *ToShadow;
5228 if (auto *FromConstructorUsingShadow =
5229 dyn_cast<ConstructorUsingShadowDecl>(D)) {
5230 Error Err = Error::success();
5232 Err, FromConstructorUsingShadow->getNominatedBaseClassShadowDecl());
5233 if (Err)
5234 return std::move(Err);
5235 // The 'Target' parameter of ConstructorUsingShadowDecl constructor
5236 // is really the "NominatedBaseClassShadowDecl" value if it exists
5237 // (see code of ConstructorUsingShadowDecl::ConstructorUsingShadowDecl).
5238 // We should pass the NominatedBaseClassShadowDecl to it (if non-null) to
5239 // get the correct values.
5240 if (GetImportedOrCreateDecl<ConstructorUsingShadowDecl>(
5241 ToShadow, D, Importer.getToContext(), DC, Loc,
5242 cast<UsingDecl>(*ToIntroducerOrErr),
5243 Nominated ? Nominated : *ToTargetOrErr,
5244 FromConstructorUsingShadow->constructsVirtualBase()))
5245 return ToShadow;
5246 } else {
5247 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
5248 Name, *ToIntroducerOrErr, *ToTargetOrErr))
5249 return ToShadow;
5250 }
5251
5252 ToShadow->setLexicalDeclContext(LexicalDC);
5253 ToShadow->setAccess(D->getAccess());
5254
5255 if (UsingShadowDecl *FromPattern =
5257 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
5259 ToShadow, *ToPatternOrErr);
5260 else
5261 // FIXME: We return error here but the definition is already created
5262 // and available with lookups. How to fix this?..
5263 return ToPatternOrErr.takeError();
5264 }
5265
5266 LexicalDC->addDeclInternal(ToShadow);
5267
5268 return ToShadow;
5269}
5270
5272 DeclContext *DC, *LexicalDC;
5273 DeclarationName Name;
5275 NamedDecl *ToD = nullptr;
5276 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5277 return std::move(Err);
5278 if (ToD)
5279 return ToD;
5280
5281 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
5282 if (!ToComAncestorOrErr)
5283 return ToComAncestorOrErr.takeError();
5284
5285 Error Err = Error::success();
5286 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
5287 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5288 auto ToNamespaceKeyLocation =
5289 importChecked(Err, D->getNamespaceKeyLocation());
5290 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5291 auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
5292 if (Err)
5293 return std::move(Err);
5294
5295 UsingDirectiveDecl *ToUsingDir;
5296 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
5297 ToUsingLoc,
5298 ToNamespaceKeyLocation,
5299 ToQualifierLoc,
5300 ToIdentLocation,
5301 ToNominatedNamespace, *ToComAncestorOrErr))
5302 return ToUsingDir;
5303
5304 ToUsingDir->setLexicalDeclContext(LexicalDC);
5305 LexicalDC->addDeclInternal(ToUsingDir);
5306
5307 return ToUsingDir;
5308}
5309
5311 DeclContext *DC, *LexicalDC;
5312 DeclarationName Name;
5314 NamedDecl *ToD = nullptr;
5315 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5316 return std::move(Err);
5317 if (ToD)
5318 return ToD;
5319
5320 auto ToInstantiatedFromUsingOrErr =
5321 Importer.Import(D->getInstantiatedFromUsingDecl());
5322 if (!ToInstantiatedFromUsingOrErr)
5323 return ToInstantiatedFromUsingOrErr.takeError();
5324 SmallVector<NamedDecl *, 4> Expansions(D->expansions().size());
5325 if (Error Err = ImportArrayChecked(D->expansions(), Expansions.begin()))
5326 return std::move(Err);
5327
5328 UsingPackDecl *ToUsingPack;
5329 if (GetImportedOrCreateDecl(ToUsingPack, D, Importer.getToContext(), DC,
5330 cast<NamedDecl>(*ToInstantiatedFromUsingOrErr),
5331 Expansions))
5332 return ToUsingPack;
5333
5334 addDeclToContexts(D, ToUsingPack);
5335
5336 return ToUsingPack;
5337}
5338
5341 DeclContext *DC, *LexicalDC;
5342 DeclarationName Name;
5344 NamedDecl *ToD = nullptr;
5345 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5346 return std::move(Err);
5347 if (ToD)
5348 return ToD;
5349
5350 Error Err = Error::success();
5351 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
5352 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5353 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5354 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
5355 if (Err)
5356 return std::move(Err);
5357
5358 DeclarationNameInfo NameInfo(Name, ToLoc);
5359 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
5360 return std::move(Err);
5361
5362 UnresolvedUsingValueDecl *ToUsingValue;
5363 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
5364 ToUsingLoc, ToQualifierLoc, NameInfo,
5365 ToEllipsisLoc))
5366 return ToUsingValue;
5367
5368 ToUsingValue->setAccess(D->getAccess());
5369 ToUsingValue->setLexicalDeclContext(LexicalDC);
5370 LexicalDC->addDeclInternal(ToUsingValue);
5371
5372 return ToUsingValue;
5373}
5374
5377 DeclContext *DC, *LexicalDC;
5378 DeclarationName Name;
5380 NamedDecl *ToD = nullptr;
5381 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5382 return std::move(Err);
5383 if (ToD)
5384 return ToD;
5385
5386 Error Err = Error::success();
5387 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
5388 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
5389 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
5390 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
5391 if (Err)
5392 return std::move(Err);
5393
5395 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
5396 ToUsingLoc, ToTypenameLoc,
5397 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
5398 return ToUsing;
5399
5400 ToUsing->setAccess(D->getAccess());
5401 ToUsing->setLexicalDeclContext(LexicalDC);
5402 LexicalDC->addDeclInternal(ToUsing);
5403
5404 return ToUsing;
5405}
5406
5408 Decl* ToD = nullptr;
5409 switch (D->getBuiltinTemplateKind()) {
5411 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
5412 break;
5414 ToD = Importer.getToContext().getTypePackElementDecl();
5415 break;
5416 }
5417 assert(ToD && "BuiltinTemplateDecl of unsupported kind!");
5418 Importer.MapImported(D, ToD);
5419 return ToD;
5420}
5421
5424 if (To->getDefinition()) {
5425 // Check consistency of superclass.
5426 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
5427 if (FromSuper) {
5428 if (auto FromSuperOrErr = import(FromSuper))
5429 FromSuper = *FromSuperOrErr;
5430 else
5431 return FromSuperOrErr.takeError();
5432 }
5433
5434 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
5435 if ((bool)FromSuper != (bool)ToSuper ||
5436 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
5437 Importer.ToDiag(To->getLocation(),
5438 diag::warn_odr_objc_superclass_inconsistent)
5439 << To->getDeclName();
5440 if (ToSuper)
5441 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
5442 << To->getSuperClass()->getDeclName();
5443 else
5444 Importer.ToDiag(To->getLocation(),
5445 diag::note_odr_objc_missing_superclass);
5446 if (From->getSuperClass())
5447 Importer.FromDiag(From->getSuperClassLoc(),
5448 diag::note_odr_objc_superclass)
5449 << From->getSuperClass()->getDeclName();
5450 else
5451 Importer.FromDiag(From->getLocation(),
5452 diag::note_odr_objc_missing_superclass);
5453 }
5454
5456 if (Error Err = ImportDeclContext(From))
5457 return Err;
5458 return Error::success();
5459 }
5460
5461 // Start the definition.
5462 To->startDefinition();
5463
5464 // If this class has a superclass, import it.
5465 if (From->getSuperClass()) {
5466 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
5467 To->setSuperClass(*SuperTInfoOrErr);
5468 else
5469 return SuperTInfoOrErr.takeError();
5470 }
5471
5472 // Import protocols
5474 SmallVector<SourceLocation, 4> ProtocolLocs;
5476 From->protocol_loc_begin();
5477
5479 FromProtoEnd = From->protocol_end();
5480 FromProto != FromProtoEnd;
5481 ++FromProto, ++FromProtoLoc) {
5482 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
5483 Protocols.push_back(*ToProtoOrErr);
5484 else
5485 return ToProtoOrErr.takeError();
5486
5487 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
5488 ProtocolLocs.push_back(*ToProtoLocOrErr);
5489 else
5490 return ToProtoLocOrErr.takeError();
5491
5492 }
5493
5494 // FIXME: If we're merging, make sure that the protocol list is the same.
5495 To->setProtocolList(Protocols.data(), Protocols.size(),
5496 ProtocolLocs.data(), Importer.getToContext());
5497
5498 // Import categories. When the categories themselves are imported, they'll
5499 // hook themselves into this interface.
5500 for (auto *Cat : From->known_categories()) {
5501 auto ToCatOrErr = import(Cat);
5502 if (!ToCatOrErr)
5503 return ToCatOrErr.takeError();
5504 }
5505
5506 // If we have an @implementation, import it as well.
5507 if (From->getImplementation()) {
5508 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
5509 import(From->getImplementation()))
5510 To->setImplementation(*ToImplOrErr);
5511 else
5512 return ToImplOrErr.takeError();
5513 }
5514
5515 // Import all of the members of this class.
5516 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
5517 return Err;
5518
5519 return Error::success();
5520}
5521
5524 if (!list)
5525 return nullptr;
5526
5528 for (auto *fromTypeParam : *list) {
5529 if (auto toTypeParamOrErr = import(fromTypeParam))
5530 toTypeParams.push_back(*toTypeParamOrErr);
5531 else
5532 return toTypeParamOrErr.takeError();
5533 }
5534
5535 auto LAngleLocOrErr = import(list->getLAngleLoc());
5536 if (!LAngleLocOrErr)
5537 return LAngleLocOrErr.takeError();
5538
5539 auto RAngleLocOrErr = import(list->getRAngleLoc());
5540 if (!RAngleLocOrErr)
5541 return RAngleLocOrErr.takeError();
5542
5543 return ObjCTypeParamList::create(Importer.getToContext(),
5544 *LAngleLocOrErr,
5545 toTypeParams,
5546 *RAngleLocOrErr);
5547}
5548
5550 // If this class has a definition in the translation unit we're coming from,
5551 // but this particular declaration is not that definition, import the
5552 // definition and map to that.
5553 ObjCInterfaceDecl *Definition = D->getDefinition();
5554 if (Definition && Definition != D) {
5555 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5556 return Importer.MapImported(D, *ImportedDefOrErr);
5557 else
5558 return ImportedDefOrErr.takeError();
5559 }
5560
5561 // Import the major distinguishing characteristics of an @interface.
5562 DeclContext *DC, *LexicalDC;
5563 DeclarationName Name;
5565 NamedDecl *ToD;
5566 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5567 return std::move(Err);
5568 if (ToD)
5569 return ToD;
5570
5571 // Look for an existing interface with the same name.
5572 ObjCInterfaceDecl *MergeWithIface = nullptr;
5573 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5574 for (auto *FoundDecl : FoundDecls) {
5576 continue;
5577
5578 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
5579 break;
5580 }
5581
5582 // Create an interface declaration, if one does not already exist.
5583 ObjCInterfaceDecl *ToIface = MergeWithIface;
5584 if (!ToIface) {
5585 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5586 if (!AtBeginLocOrErr)
5587 return AtBeginLocOrErr.takeError();
5588
5589 if (GetImportedOrCreateDecl(
5590 ToIface, D, Importer.getToContext(), DC,
5591 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
5592 /*TypeParamList=*/nullptr,
5593 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
5594 return ToIface;
5595 ToIface->setLexicalDeclContext(LexicalDC);
5596 LexicalDC->addDeclInternal(ToIface);
5597 }
5598 Importer.MapImported(D, ToIface);
5599 // Import the type parameter list after MapImported, to avoid
5600 // loops when bringing in their DeclContext.
5601 if (auto ToPListOrErr =
5602 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
5603 ToIface->setTypeParamList(*ToPListOrErr);
5604 else
5605 return ToPListOrErr.takeError();
5606
5607 if (D->isThisDeclarationADefinition())
5608 if (Error Err = ImportDefinition(D, ToIface))
5609 return std::move(Err);
5610
5611 return ToIface;
5612}
5613
5617 if (Error Err = importInto(Category, D->getCategoryDecl()))
5618 return std::move(Err);
5619
5620 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5621 if (!ToImpl) {
5622 DeclContext *DC, *LexicalDC;
5623 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5624 return std::move(Err);
5625
5626 Error Err = Error::success();
5627 auto ToLocation = importChecked(Err, D->getLocation());
5628 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5629 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5630 if (Err)
5631 return std::move(Err);
5632
5633 if (GetImportedOrCreateDecl(
5634 ToImpl, D, Importer.getToContext(), DC,
5635 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5636 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5637 return ToImpl;
5638
5639 ToImpl->setLexicalDeclContext(LexicalDC);
5640 LexicalDC->addDeclInternal(ToImpl);
5641 Category->setImplementation(ToImpl);
5642 }
5643
5644 Importer.MapImported(D, ToImpl);
5645 if (Error Err = ImportDeclContext(D))
5646 return std::move(Err);
5647
5648 return ToImpl;
5649}
5650
5653 // Find the corresponding interface.
5654 ObjCInterfaceDecl *Iface;
5655 if (Error Err = importInto(Iface, D->getClassInterface()))
5656 return std::move(Err);
5657
5658 // Import the superclass, if any.
5659 ObjCInterfaceDecl *Super;
5660 if (Error Err = importInto(Super, D->getSuperClass()))
5661 return std::move(Err);
5662
5664 if (!Impl) {
5665 // We haven't imported an implementation yet. Create a new @implementation
5666 // now.
5667 DeclContext *DC, *LexicalDC;
5668 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5669 return std::move(Err);
5670
5671 Error Err = Error::success();
5672 auto ToLocation = importChecked(Err, D->getLocation());
5673 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5674 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5675 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5676 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5677 if (Err)
5678 return std::move(Err);
5679
5680 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5681 DC, Iface, Super,
5682 ToLocation,
5683 ToAtStartLoc,
5684 ToSuperClassLoc,
5685 ToIvarLBraceLoc,
5686 ToIvarRBraceLoc))
5687 return Impl;
5688
5689 Impl->setLexicalDeclContext(LexicalDC);
5690
5691 // Associate the implementation with the class it implements.
5692 Iface->setImplementation(Impl);
5693 Importer.MapImported(D, Iface->getImplementation());
5694 } else {
5695 Importer.MapImported(D, Iface->getImplementation());
5696
5697 // Verify that the existing @implementation has the same superclass.
5698 if ((Super && !Impl->getSuperClass()) ||
5699 (!Super && Impl->getSuperClass()) ||
5700 (Super && Impl->getSuperClass() &&
5702 Impl->getSuperClass()))) {
5703 Importer.ToDiag(Impl->getLocation(),
5704 diag::warn_odr_objc_superclass_inconsistent)
5705 << Iface->getDeclName();
5706 // FIXME: It would be nice to have the location of the superclass
5707 // below.
5708 if (Impl->getSuperClass())
5709 Importer.ToDiag(Impl->getLocation(),
5710 diag::note_odr_objc_superclass)
5711 << Impl->getSuperClass()->getDeclName();
5712 else
5713 Importer.ToDiag(Impl->getLocation(),
5714 diag::note_odr_objc_missing_superclass);
5715 if (D->getSuperClass())
5716 Importer.FromDiag(D->getLocation(),
5717 diag::note_odr_objc_superclass)
5718 << D->getSuperClass()->getDeclName();
5719 else
5720 Importer.FromDiag(D->getLocation(),
5721 diag::note_odr_objc_missing_superclass);
5722
5723 return make_error<ASTImportError>(ASTImportError::NameConflict);
5724 }
5725 }
5726
5727 // Import all of the members of this @implementation.
5728 if (Error Err = ImportDeclContext(D))
5729 return std::move(Err);
5730
5731 return Impl;
5732}
5733
5735 // Import the major distinguishing characteristics of an @property.
5736 DeclContext *DC, *LexicalDC;
5737 DeclarationName Name;
5739 NamedDecl *ToD;
5740 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5741 return std::move(Err);
5742 if (ToD)
5743 return ToD;
5744
5745 // Check whether we have already imported this property.
5746 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5747 for (auto *FoundDecl : FoundDecls) {
5748 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5749 // Instance and class properties can share the same name but are different
5750 // declarations.
5751 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5752 continue;
5753
5754 // Check property types.
5755 if (!Importer.IsStructurallyEquivalent(D->getType(),
5756 FoundProp->getType())) {
5757 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5758 << Name << D->getType() << FoundProp->getType();
5759 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5760 << FoundProp->getType();
5761
5762 return make_error<ASTImportError>(ASTImportError::NameConflict);
5763 }
5764
5765 // FIXME: Check property attributes, getters, setters, etc.?
5766
5767 // Consider these properties to be equivalent.
5768 Importer.MapImported(D, FoundProp);
5769 return FoundProp;
5770 }
5771 }
5772
5773 Error Err = Error::success();
5774 auto ToType = importChecked(Err, D->getType());
5775 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5776 auto ToAtLoc = importChecked(Err, D->getAtLoc());
5777 auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5778 if (Err)
5779 return std::move(Err);
5780
5781 // Create the new property.
5782 ObjCPropertyDecl *ToProperty;
5783 if (GetImportedOrCreateDecl(
5784 ToProperty, D, Importer.getToContext(), DC, Loc,
5785 Name.getAsIdentifierInfo(), ToAtLoc,
5786 ToLParenLoc, ToType,
5787 ToTypeSourceInfo, D->getPropertyImplementation()))
5788 return ToProperty;
5789
5790 auto ToGetterName = importChecked(Err, D->getGetterName());
5791 auto ToSetterName = importChecked(Err, D->getSetterName());
5792 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
5793 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
5794 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
5795 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
5796 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
5797 if (Err)
5798 return std::move(Err);
5799
5800 ToProperty->setLexicalDeclContext(LexicalDC);
5801 LexicalDC->addDeclInternal(ToProperty);
5802
5803 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5805 D->getPropertyAttributesAsWritten());
5806 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
5807 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
5808 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5809 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5810 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5811 return ToProperty;
5812}
5813
5817 if (Error Err = importInto(Property, D->getPropertyDecl()))
5818 return std::move(Err);
5819
5820 DeclContext *DC, *LexicalDC;
5821 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5822 return std::move(Err);
5823
5824 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
5825
5826 // Import the ivar (for an @synthesize).
5827 ObjCIvarDecl *Ivar = nullptr;
5828 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
5829 return std::move(Err);
5830
5831 ObjCPropertyImplDecl *ToImpl
5832 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
5833 Property->getQueryKind());
5834 if (!ToImpl) {
5835
5836 Error Err = Error::success();
5837 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
5838 auto ToLocation = importChecked(Err, D->getLocation());
5839 auto ToPropertyIvarDeclLoc =
5840 importChecked(Err, D->getPropertyIvarDeclLoc());
5841 if (Err)
5842 return std::move(Err);
5843
5844 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5845 ToBeginLoc,
5846 ToLocation, Property,
5847 D->getPropertyImplementation(), Ivar,
5848 ToPropertyIvarDeclLoc))
5849 return ToImpl;
5850
5851 ToImpl->setLexicalDeclContext(LexicalDC);
5852 LexicalDC->addDeclInternal(ToImpl);
5853 } else {
5854 // Check that we have the same kind of property implementation (@synthesize
5855 // vs. @dynamic).
5856 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5857 Importer.ToDiag(ToImpl->getLocation(),
5858 diag::warn_odr_objc_property_impl_kind_inconsistent)
5859 << Property->getDeclName()
5860 << (ToImpl->getPropertyImplementation()
5862 Importer.FromDiag(D->getLocation(),
5863 diag::note_odr_objc_property_impl_kind)
5864 << D->getPropertyDecl()->getDeclName()
5865 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5866
5867 return make_error<ASTImportError>(ASTImportError::NameConflict);
5868 }
5869
5870 // For @synthesize, check that we have the same
5871 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5872 Ivar != ToImpl->getPropertyIvarDecl()) {
5873 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5874 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5875 << Property->getDeclName()
5876 << ToImpl->getPropertyIvarDecl()->getDeclName()
5877 << Ivar->getDeclName();
5878 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5879 diag::note_odr_objc_synthesize_ivar_here)
5880 << D->getPropertyIvarDecl()->getDeclName();
5881
5882 return make_error<ASTImportError>(ASTImportError::NameConflict);
5883 }
5884
5885 // Merge the existing implementation with the new implementation.
5886 Importer.MapImported(D, ToImpl);
5887 }
5888
5889 return ToImpl;
5890}
5891
5894 // For template arguments, we adopt the translation unit as our declaration
5895 // context. This context will be fixed when the actual template declaration
5896 // is created.
5897
5898 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5899 if (!BeginLocOrErr)
5900 return BeginLocOrErr.takeError();
5901
5902 ExpectedSLoc LocationOrErr = import(D->getLocation());
5903 if (!LocationOrErr)
5904 return LocationOrErr.takeError();
5905
5906 TemplateTypeParmDecl *ToD = nullptr;
5907 if (GetImportedOrCreateDecl(
5908 ToD, D, Importer.getToContext(),
5910 *BeginLocOrErr, *LocationOrErr,
5911 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5912 D->wasDeclaredWithTypename(), D->isParameterPack(),
5913 D->hasTypeConstraint()))
5914 return ToD;
5915
5916 // Import the type-constraint
5917 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5918
5919 Error Err = Error::success();
5920 auto ToConceptRef = importChecked(Err, TC->getConceptReference());
5921 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
5922 if (Err)
5923 return std::move(Err);
5924
5925 ToD->setTypeConstraint(ToConceptRef, ToIDC);
5926 }
5927
5928 if (D->hasDefaultArgument()) {
5929 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5930 import(D->getDefaultArgument());
5931 if (!ToDefaultArgOrErr)
5932 return ToDefaultArgOrErr.takeError();
5933 ToD->setDefaultArgument(ToD->getASTContext(), *ToDefaultArgOrErr);
5934 }
5935
5936 return ToD;
5937}
5938
5941
5942 Error Err = Error::success();
5943 auto ToDeclName = importChecked(Err, D->getDeclName());
5944 auto ToLocation = importChecked(Err, D->getLocation());
5945 auto ToType = importChecked(Err, D->getType());
5946 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5947 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5948 if (Err)
5949 return std::move(Err);
5950
5951 NonTypeTemplateParmDecl *ToD = nullptr;
5952 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5954 ToInnerLocStart, ToLocation, D->getDepth(),
5955 D->getPosition(),
5956 ToDeclName.getAsIdentifierInfo(), ToType,
5957 D->isParameterPack(), ToTypeSourceInfo))
5958 return ToD;
5959
5960 if (D->hasDefaultArgument()) {
5961 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5962 import(D->getDefaultArgument());
5963 if (!ToDefaultArgOrErr)
5964 return ToDefaultArgOrErr.takeError();
5965 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
5966 }
5967
5968 return ToD;
5969}
5970
5973 // Import the name of this declaration.
5974 auto NameOrErr = import(D->getDeclName());
5975 if (!NameOrErr)
5976 return NameOrErr.takeError();
5977
5978 // Import the location of this declaration.
5979 ExpectedSLoc LocationOrErr = import(D->getLocation());
5980 if (!LocationOrErr)
5981 return LocationOrErr.takeError();
5982
5983 // Import template parameters.
5984 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5985 if (!TemplateParamsOrErr)
5986 return TemplateParamsOrErr.takeError();
5987
5988 TemplateTemplateParmDecl *ToD = nullptr;
5989 if (GetImportedOrCreateDecl(
5990 ToD, D, Importer.getToContext(),
5991 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5992 D->getDepth(), D->getPosition(), D->isParameterPack(),
5993 (*NameOrErr).getAsIdentifierInfo(), D->wasDeclaredWithTypename(),
5994 *TemplateParamsOrErr))
5995 return ToD;
5996
5997 if (D->hasDefaultArgument()) {
5998 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5999 import(D->getDefaultArgument());
6000 if (!ToDefaultArgOrErr)
6001 return ToDefaultArgOrErr.takeError();
6002 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
6003 }
6004
6005 return ToD;
6006}
6007
6008// Returns the definition for a (forward) declaration of a TemplateDecl, if
6009// it has any definition in the redecl chain.
6010template <typename T> static auto getTemplateDefinition(T *D) -> T * {
6011 assert(D->getTemplatedDecl() && "Should be called on templates only");
6012 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
6013 if (!ToTemplatedDef)
6014 return nullptr;
6015 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
6016 return cast_or_null<T>(TemplateWithDef);
6017}
6018
6020
6021 // Import the major distinguishing characteristics of this class template.
6022 DeclContext *DC, *LexicalDC;
6023 DeclarationName Name;
6025 NamedDecl *ToD;
6026 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6027 return std::move(Err);
6028 if (ToD)
6029 return ToD;
6030
6031 // Should check if a declaration is friend in a dependent context.
6032 // Such templates are not linked together in a declaration chain.
6033 // The ASTImporter strategy is to map existing forward declarations to
6034 // imported ones only if strictly necessary, otherwise import these as new
6035 // forward declarations. In case of the "dependent friend" declarations, new
6036 // declarations are created, but not linked in a declaration chain.
6037 auto IsDependentFriend = [](ClassTemplateDecl *TD) {
6038 return TD->getFriendObjectKind() != Decl::FOK_None &&
6040 };
6041 bool DependentFriend = IsDependentFriend(D);
6042
6043 ClassTemplateDecl *FoundByLookup = nullptr;
6044
6045 // We may already have a template of the same name; try to find and match it.
6046 if (!DC->isFunctionOrMethod()) {
6047 SmallVector<NamedDecl *, 4> ConflictingDecls;
6048 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6049 for (auto *FoundDecl : FoundDecls) {
6052 continue;
6053
6054 Decl *Found = FoundDecl;
6055 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
6056 if (FoundTemplate) {
6057 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6058 continue;
6059
6060 // FIXME: sufficient conditon for 'IgnoreTemplateParmDepth'?
6061 bool IgnoreTemplateParmDepth =
6062 (FoundTemplate->getFriendObjectKind() != Decl::FOK_None) !=
6064 if (IsStructuralMatch(D, FoundTemplate, /*Complain=*/true,
6065 IgnoreTemplateParmDepth)) {
6066 if (DependentFriend || IsDependentFriend(FoundTemplate))
6067 continue;
6068
6069 ClassTemplateDecl *TemplateWithDef =
6070 getTemplateDefinition(FoundTemplate);
6071 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6072 return Importer.MapImported(D, TemplateWithDef);
6073 if (!FoundByLookup)
6074 FoundByLookup = FoundTemplate;
6075 // Search in all matches because there may be multiple decl chains,
6076 // see ASTTests test ImportExistingFriendClassTemplateDef.
6077 continue;
6078 }
6079 ConflictingDecls.push_back(FoundDecl);
6080 }
6081 }
6082
6083 if (!ConflictingDecls.empty()) {
6084 ExpectedName NameOrErr = Importer.HandleNameConflict(
6085 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
6086 ConflictingDecls.size());
6087 if (NameOrErr)
6088 Name = NameOrErr.get();
6089 else
6090 return NameOrErr.takeError();
6091 }
6092 }
6093
6094 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
6095
6096 auto TemplateParamsOrErr = import(D->getTemplateParameters());
6097 if (!TemplateParamsOrErr)
6098 return TemplateParamsOrErr.takeError();
6099
6100 // Create the declaration that is being templated.
6101 CXXRecordDecl *ToTemplated;
6102 if (Error Err = importInto(ToTemplated, FromTemplated))
6103 return std::move(Err);
6104
6105 // Create the class template declaration itself.
6107 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
6108 *TemplateParamsOrErr, ToTemplated))
6109 return D2;
6110
6111 ToTemplated->setDescribedClassTemplate(D2);
6112
6113 D2->setAccess(D->getAccess());
6114 D2->setLexicalDeclContext(LexicalDC);
6115
6116 addDeclToContexts(D, D2);
6117 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
6118
6119 if (FoundByLookup) {
6120 auto *Recent =
6121 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6122
6123 // It is possible that during the import of the class template definition
6124 // we start the import of a fwd friend decl of the very same class template
6125 // and we add the fwd friend decl to the lookup table. But the ToTemplated
6126 // had been created earlier and by that time the lookup could not find
6127 // anything existing, so it has no previous decl. Later, (still during the
6128 // import of the fwd friend decl) we start to import the definition again
6129 // and this time the lookup finds the previous fwd friend class template.
6130 // In this case we must set up the previous decl for the templated decl.
6131 if (!ToTemplated->getPreviousDecl()) {
6132 assert(FoundByLookup->getTemplatedDecl() &&
6133 "Found decl must have its templated decl set");
6134 CXXRecordDecl *PrevTemplated =
6135 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6136 if (ToTemplated != PrevTemplated)
6137 ToTemplated->setPreviousDecl(PrevTemplated);
6138 }
6139
6140 D2->setPreviousDecl(Recent);
6141 }
6142
6143 return D2;
6144}
6145
6148 ClassTemplateDecl *ClassTemplate;
6149 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
6150 return std::move(Err);
6151
6152 // Import the context of this declaration.
6153 DeclContext *DC, *LexicalDC;
6154 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6155 return std::move(Err);
6156
6157 // Import template arguments.
6159 if (Error Err =
6160 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
6161 return std::move(Err);
6162 // Try to find an existing specialization with these template arguments and
6163 // template parameter list.
6164 void *InsertPos = nullptr;
6165 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
6167 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
6168
6169 // Import template parameters.
6170 TemplateParameterList *ToTPList = nullptr;
6171
6172 if (PartialSpec) {
6173 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
6174 if (!ToTPListOrErr)
6175 return ToTPListOrErr.takeError();
6176 ToTPList = *ToTPListOrErr;
6177 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
6178 *ToTPListOrErr,
6179 InsertPos);
6180 } else
6181 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
6182
6183 if (PrevDecl) {
6184 if (IsStructuralMatch(D, PrevDecl)) {
6185 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
6186 if (D->isThisDeclarationADefinition() && PrevDefinition) {
6187 Importer.MapImported(D, PrevDefinition);
6188 // Import those default field initializers which have been
6189 // instantiated in the "From" context, but not in the "To" context.
6190 for (auto *FromField : D->fields()) {
6191 auto ToOrErr = import(FromField);
6192 if (!ToOrErr)
6193 return ToOrErr.takeError();
6194 }
6195
6196 // Import those methods which have been instantiated in the
6197 // "From" context, but not in the "To" context.
6198 for (CXXMethodDecl *FromM : D->methods()) {
6199 auto ToOrErr = import(FromM);
6200 if (!ToOrErr)
6201 return ToOrErr.takeError();
6202 }
6203
6204 // TODO Import instantiated default arguments.
6205 // TODO Import instantiated exception specifications.
6206 //
6207 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
6208 // what else could be fused during an AST merge.
6209 return PrevDefinition;
6210 }
6211 } else { // ODR violation.
6212 // FIXME HandleNameConflict
6213 return make_error<ASTImportError>(ASTImportError::NameConflict);
6214 }
6215 }
6216
6217 // Import the location of this declaration.
6218 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6219 if (!BeginLocOrErr)
6220 return BeginLocOrErr.takeError();
6221 ExpectedSLoc IdLocOrErr = import(D->getLocation());
6222 if (!IdLocOrErr)
6223 return IdLocOrErr.takeError();
6224
6225 // Import TemplateArgumentListInfo.
6226 TemplateArgumentListInfo ToTAInfo;
6227 if (const auto *ASTTemplateArgs = D->getTemplateArgsAsWritten()) {
6228 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, ToTAInfo))
6229 return std::move(Err);
6230 }
6231
6232 // Create the specialization.
6233 ClassTemplateSpecializationDecl *D2 = nullptr;
6234 if (PartialSpec) {
6235 QualType CanonInjType;
6236 if (Error Err = importInto(
6237 CanonInjType, PartialSpec->getInjectedSpecializationType()))
6238 return std::move(Err);
6239 CanonInjType = CanonInjType.getCanonicalType();
6240
6241 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
6242 D2, D, Importer.getToContext(), D->getTagKind(), DC, *BeginLocOrErr,
6243 *IdLocOrErr, ToTPList, ClassTemplate,
6244 llvm::ArrayRef(TemplateArgs.data(), TemplateArgs.size()),
6245 CanonInjType,
6246 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
6247 return D2;
6248
6249 // Update InsertPos, because preceding import calls may have invalidated
6250 // it by adding new specializations.
6251 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
6252 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
6253 InsertPos))
6254 // Add this partial specialization to the class template.
6255 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
6257 import(PartialSpec->getInstantiatedFromMember()))
6258 PartSpec2->setInstantiatedFromMember(*ToInstOrErr);
6259 else
6260 return ToInstOrErr.takeError();
6261
6262 updateLookupTableForTemplateParameters(*ToTPList);
6263 } else { // Not a partial specialization.
6264 if (GetImportedOrCreateDecl(
6265 D2, D, Importer.getToContext(), D->getTagKind(), DC,
6266 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
6267 PrevDecl))
6268 return D2;
6269
6270 // Update InsertPos, because preceding import calls may have invalidated
6271 // it by adding new specializations.
6272 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
6273 // Add this specialization to the class template.
6274 ClassTemplate->AddSpecialization(D2, InsertPos);
6275 }
6276
6277 D2->setSpecializationKind(D->getSpecializationKind());
6278
6279 // Set the context of this specialization/instantiation.
6280 D2->setLexicalDeclContext(LexicalDC);
6281
6282 // Add to the DC only if it was an explicit specialization/instantiation.
6284 LexicalDC->addDeclInternal(D2);
6285 }
6286
6287 if (auto BraceRangeOrErr = import(D->getBraceRange()))
6288 D2->setBraceRange(*BraceRangeOrErr);
6289 else
6290 return BraceRangeOrErr.takeError();
6291
6292 if (Error Err = ImportTemplateParameterLists(D, D2))
6293 return std::move(Err);
6294
6295 // Import the qualifier, if any.
6296 if (auto LocOrErr = import(D->getQualifierLoc()))
6297 D2->setQualifierInfo(*LocOrErr);
6298 else
6299 return LocOrErr.takeError();
6300
6301 if (D->getTemplateArgsAsWritten())
6302 D2->setTemplateArgsAsWritten(ToTAInfo);
6303
6304 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
6305 D2->setTemplateKeywordLoc(*LocOrErr);
6306 else
6307 return LocOrErr.takeError();
6308
6309 if (auto LocOrErr = import(D->getExternKeywordLoc()))
6310 D2->setExternKeywordLoc(*LocOrErr);
6311 else
6312 return LocOrErr.takeError();
6313
6314 if (D->getPointOfInstantiation().isValid()) {
6315 if (auto POIOrErr = import(D->getPointOfInstantiation()))
6316 D2->setPointOfInstantiation(*POIOrErr);
6317 else
6318 return POIOrErr.takeError();
6319 }
6320
6321 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
6322
6323 if (auto P = D->getInstantiatedFrom()) {
6324 if (auto *CTD = P.dyn_cast<ClassTemplateDecl *>()) {
6325 if (auto CTDorErr = import(CTD))
6326 D2->setInstantiationOf(*CTDorErr);
6327 } else {
6328 auto *CTPSD = cast<ClassTemplatePartialSpecializationDecl *>(P);
6329 auto CTPSDOrErr = import(CTPSD);
6330 if (!CTPSDOrErr)
6331 return CTPSDOrErr.takeError();
6332 const TemplateArgumentList &DArgs = D->getTemplateInstantiationArgs();
6333 SmallVector<TemplateArgument, 2> D2ArgsVec(DArgs.size());
6334 for (unsigned I = 0; I < DArgs.size(); ++I) {
6335 const TemplateArgument &DArg = DArgs[I];
6336 if (auto ArgOrErr = import(DArg))
6337 D2ArgsVec[I] = *ArgOrErr;
6338 else
6339 return ArgOrErr.takeError();
6340 }
6342 *CTPSDOrErr,
6343 TemplateArgumentList::CreateCopy(Importer.getToContext(), D2ArgsVec));
6344 }
6345 }
6346
6347 if (D->isCompleteDefinition())
6348 if (Error Err = ImportDefinition(D, D2))
6349 return std::move(Err);
6350
6351 return D2;
6352}
6353
6355 // Import the major distinguishing characteristics of this variable template.
6356 DeclContext *DC, *LexicalDC;
6357 DeclarationName Name;
6359 NamedDecl *ToD;
6360 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6361 return std::move(Err);
6362 if (ToD)
6363 return ToD;
6364
6365 // We may already have a template of the same name; try to find and match it.
6366 assert(!DC->isFunctionOrMethod() &&
6367 "Variable templates cannot be declared at function scope");
6368
6369 SmallVector<NamedDecl *, 4> ConflictingDecls;
6370 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6371 VarTemplateDecl *FoundByLookup = nullptr;
6372 for (auto *FoundDecl : FoundDecls) {
6374 continue;
6375
6376 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
6377 // Use the templated decl, some linkage flags are set only there.
6378 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
6379 D->getTemplatedDecl()))
6380 continue;
6381 if (IsStructuralMatch(D, FoundTemplate)) {
6382 // FIXME Check for ODR error if the two definitions have
6383 // different initializers?
6384 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
6385 if (D->getDeclContext()->isRecord()) {
6386 assert(FoundTemplate->getDeclContext()->isRecord() &&
6387 "Member variable template imported as non-member, "
6388 "inconsistent imported AST?");
6389 if (FoundDef)
6390 return Importer.MapImported(D, FoundDef);
6391 if (!D->isThisDeclarationADefinition())
6392 return Importer.MapImported(D, FoundTemplate);
6393 } else {
6394 if (FoundDef && D->isThisDeclarationADefinition())
6395 return Importer.MapImported(D, FoundDef);
6396 }
6397 FoundByLookup = FoundTemplate;
6398 break;
6399 }
6400 ConflictingDecls.push_back(FoundDecl);
6401 }
6402 }
6403
6404 if (!ConflictingDecls.empty()) {
6405 ExpectedName NameOrErr = Importer.HandleNameConflict(
6406 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
6407 ConflictingDecls.size());
6408 if (NameOrErr)
6409 Name = NameOrErr.get();
6410 else
6411 return NameOrErr.takeError();
6412 }
6413
6414 VarDecl *DTemplated = D->getTemplatedDecl();
6415
6416 // Import the type.
6417 // FIXME: Value not used?
6418 ExpectedType TypeOrErr = import(DTemplated->getType());
6419 if (!TypeOrErr)
6420 return TypeOrErr.takeError();
6421
6422 // Create the declaration that is being templated.
6423 VarDecl *ToTemplated;
6424 if (Error Err = importInto(ToTemplated, DTemplated))
6425 return std::move(Err);
6426
6427 // Create the variable template declaration itself.
6428 auto TemplateParamsOrErr = import(D->getTemplateParameters());
6429 if (!TemplateParamsOrErr)
6430 return TemplateParamsOrErr.takeError();
6431
6432 VarTemplateDecl *ToVarTD;
6433 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
6434 Name, *TemplateParamsOrErr, ToTemplated))
6435 return ToVarTD;
6436
6437 ToTemplated->setDescribedVarTemplate(ToVarTD);
6438
6439 ToVarTD->setAccess(D->getAccess());
6440 ToVarTD->setLexicalDeclContext(LexicalDC);
6441 LexicalDC->addDeclInternal(ToVarTD);
6442 if (DC != Importer.getToContext().getTranslationUnitDecl())
6443 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
6444
6445 if (FoundByLookup) {
6446 auto *Recent =
6447 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6448 if (!ToTemplated->getPreviousDecl()) {
6449 auto *PrevTemplated =
6450 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6451 if (ToTemplated != PrevTemplated)
6452 ToTemplated->setPreviousDecl(PrevTemplated);
6453 }
6454 ToVarTD->setPreviousDecl(Recent);
6455 }
6456
6457 return ToVarTD;
6458}
6459
6462 // A VarTemplateSpecializationDecl inherits from VarDecl, the import is done
6463 // in an analog way (but specialized for this case).
6464
6466 auto RedeclIt = Redecls.begin();
6467 // Import the first part of the decl chain. I.e. import all previous
6468 // declarations starting from the canonical decl.
6469 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
6470 ExpectedDecl RedeclOrErr = import(*RedeclIt);
6471 if (!RedeclOrErr)
6472 return RedeclOrErr.takeError();
6473 }
6474 assert(*RedeclIt == D);
6475
6476 VarTemplateDecl *VarTemplate = nullptr;
6477 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
6478 return std::move(Err);
6479
6480 // Import the context of this declaration.
6481 DeclContext *DC, *LexicalDC;
6482 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
6483 return std::move(Err);
6484
6485 // Import the location of this declaration.
6486 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
6487 if (!BeginLocOrErr)
6488 return BeginLocOrErr.takeError();
6489
6490 auto IdLocOrErr = import(D->getLocation());
6491 if (!IdLocOrErr)
6492 return IdLocOrErr.takeError();
6493
6494 // Import template arguments.
6496 if (Error Err =
6497 ImportTemplateArguments(D->getTemplateArgs().asArray(), TemplateArgs))
6498 return std::move(Err);
6499
6500 // Try to find an existing specialization with these template arguments.
6501 void *InsertPos = nullptr;
6502 VarTemplateSpecializationDecl *FoundSpecialization =
6503 VarTemplate->findSpecialization(TemplateArgs, InsertPos);
6504 if (FoundSpecialization) {
6505 if (IsStructuralMatch(D, FoundSpecialization)) {
6506 VarDecl *FoundDef = FoundSpecialization->getDefinition();
6507 if (D->getDeclContext()->isRecord()) {
6508 // In a record, it is allowed only to have one optional declaration and
6509 // one definition of the (static or constexpr) variable template.
6510 assert(
6511 FoundSpecialization->getDeclContext()->isRecord() &&
6512 "Member variable template specialization imported as non-member, "
6513 "inconsistent imported AST?");
6514 if (FoundDef)
6515 return Importer.MapImported(D, FoundDef);
6516 if (!D->isThisDeclarationADefinition())
6517 return Importer.MapImported(D, FoundSpecialization);
6518 } else {
6519 // If definition is imported and there is already one, map to it.
6520 // Otherwise create a new variable and link it to the existing.
6521 if (FoundDef && D->isThisDeclarationADefinition())
6522 return Importer.MapImported(D, FoundDef);
6523 }
6524 } else {
6525 return make_error<ASTImportError>(ASTImportError::NameConflict);
6526 }
6527 }
6528
6529 VarTemplateSpecializationDecl *D2 = nullptr;
6530
6531 TemplateArgumentListInfo ToTAInfo;
6532 if (const auto *Args = D->getTemplateArgsAsWritten()) {
6533 if (Error Err = ImportTemplateArgumentListInfo(*Args, ToTAInfo))
6534 return std::move(Err);
6535 }
6536
6537 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
6538 // Create a new specialization.
6539 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
6540 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
6541 if (!ToTPListOrErr)
6542 return ToTPListOrErr.takeError();
6543
6544 PartVarSpecDecl *ToPartial;
6545 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
6546 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
6547 VarTemplate, QualType(), nullptr,
6548 D->getStorageClass(), TemplateArgs))
6549 return ToPartial;
6550
6551 if (Expected<PartVarSpecDecl *> ToInstOrErr =
6552 import(FromPartial->getInstantiatedFromMember()))
6553 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
6554 else
6555 return ToInstOrErr.takeError();
6556
6557 if (FromPartial->isMemberSpecialization())
6558 ToPartial->setMemberSpecialization();
6559
6560 D2 = ToPartial;
6561
6562 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
6563 // to adopt template parameters.
6564 // updateLookupTableForTemplateParameters(**ToTPListOrErr);
6565 } else { // Full specialization
6566 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
6567 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
6568 QualType(), nullptr, D->getStorageClass(),
6569 TemplateArgs))
6570 return D2;
6571 }
6572
6573 // Update InsertPos, because preceding import calls may have invalidated
6574 // it by adding new specializations.
6575 if (!VarTemplate->findSpecialization(TemplateArgs, InsertPos))
6576 VarTemplate->AddSpecialization(D2, InsertPos);
6577
6578 QualType T;
6579 if (Error Err = importInto(T, D->getType()))
6580 return std::move(Err);
6581 D2->setType(T);
6582
6583 auto TInfoOrErr = import(D->getTypeSourceInfo());
6584 if (!TInfoOrErr)
6585 return TInfoOrErr.takeError();
6586 D2->setTypeSourceInfo(*TInfoOrErr);
6587
6588 if (D->getPointOfInstantiation().isValid()) {
6589 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
6590 D2->setPointOfInstantiation(*POIOrErr);
6591 else
6592 return POIOrErr.takeError();
6593 }
6594
6595 D2->setSpecializationKind(D->getSpecializationKind());
6596
6597 if (D->getTemplateArgsAsWritten())
6598 D2->setTemplateArgsAsWritten(ToTAInfo);
6599
6600 if (auto LocOrErr = import(D->getQualifierLoc()))
6601 D2->setQualifierInfo(*LocOrErr);
6602 else
6603 return LocOrErr.takeError();
6604
6605 if (D->isConstexpr())
6606 D2->setConstexpr(true);
6607
6608 D2->setAccess(D->getAccess());
6609
6610 if (Error Err = ImportInitializer(D, D2))
6611 return std::move(Err);
6612
6613 if (FoundSpecialization)
6614 D2->setPreviousDecl(FoundSpecialization->getMostRecentDecl());
6615
6616 addDeclToContexts(D, D2);
6617
6618 // Import the rest of the chain. I.e. import all subsequent declarations.
6619 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
6620 ExpectedDecl RedeclOrErr = import(*RedeclIt);
6621 if (!RedeclOrErr)
6622 return RedeclOrErr.takeError();
6623 }
6624
6625 return D2;
6626}
6627
6630 DeclContext *DC, *LexicalDC;
6631 DeclarationName Name;
6633 NamedDecl *ToD;
6634
6635 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6636 return std::move(Err);
6637
6638 if (ToD)
6639 return ToD;
6640
6641 const FunctionTemplateDecl *FoundByLookup = nullptr;
6642
6643 // Try to find a function in our own ("to") context with the same name, same
6644 // type, and in the same context as the function we're importing.
6645 // FIXME Split this into a separate function.
6646 if (!LexicalDC->isFunctionOrMethod()) {
6648 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6649 for (auto *FoundDecl : FoundDecls) {
6650 if (!FoundDecl->isInIdentifierNamespace(IDNS))
6651 continue;
6652
6653 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
6654 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6655 continue;
6656 if (IsStructuralMatch(D, FoundTemplate)) {
6657 FunctionTemplateDecl *TemplateWithDef =
6658 getTemplateDefinition(FoundTemplate);
6659 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6660 return Importer.MapImported(D, TemplateWithDef);
6661
6662 FoundByLookup = FoundTemplate;
6663 break;
6664 // TODO: handle conflicting names
6665 }
6666 }
6667 }
6668 }
6669
6670 auto ParamsOrErr = import(D->getTemplateParameters());
6671 if (!ParamsOrErr)
6672 return ParamsOrErr.takeError();
6673 TemplateParameterList *Params = *ParamsOrErr;
6674
6675 FunctionDecl *TemplatedFD;
6676 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
6677 return std::move(Err);
6678
6679 // At creation of the template the template parameters are "adopted"
6680 // (DeclContext is changed). After this possible change the lookup table
6681 // must be updated.
6682 // At deduction guides the DeclContext of the template parameters may be
6683 // different from what we would expect, it may be the class template, or a
6684 // probably different CXXDeductionGuideDecl. This may come from the fact that
6685 // the template parameter objects may be shared between deduction guides or
6686 // the class template, and at creation of multiple FunctionTemplateDecl
6687 // objects (for deduction guides) the same parameters are re-used. The
6688 // "adoption" happens multiple times with different parent, even recursively
6689 // for TemplateTemplateParmDecl. The same happens at import when the
6690 // FunctionTemplateDecl objects are created, but in different order.
6691 // In this way the DeclContext of these template parameters is not necessarily
6692 // the same as in the "from" context.
6694 OldParamDC.reserve(Params->size());
6695 llvm::transform(*Params, std::back_inserter(OldParamDC),
6696 [](NamedDecl *ND) { return ND->getDeclContext(); });
6697
6698 FunctionTemplateDecl *ToFunc;
6699 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
6700 Params, TemplatedFD))
6701 return ToFunc;
6702
6703 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6704
6705 ToFunc->setAccess(D->getAccess());
6706 ToFunc->setLexicalDeclContext(LexicalDC);
6707 addDeclToContexts(D, ToFunc);
6708
6709 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
6710 if (LT && !OldParamDC.empty()) {
6711 for (unsigned int I = 0; I < OldParamDC.size(); ++I)
6712 LT->updateForced(Params->getParam(I), OldParamDC[I]);
6713 }
6714
6715 if (FoundByLookup) {
6716 auto *Recent =
6717 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6718 if (!TemplatedFD->getPreviousDecl()) {
6719 assert(FoundByLookup->getTemplatedDecl() &&
6720 "Found decl must have its templated decl set");
6721 auto *PrevTemplated =
6722 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6723 if (TemplatedFD != PrevTemplated)
6724 TemplatedFD->setPreviousDecl(PrevTemplated);
6725 }
6726 ToFunc->setPreviousDecl(Recent);
6727 }
6728
6729 return ToFunc;
6730}
6731
6732//----------------------------------------------------------------------------
6733// Import Statements
6734//----------------------------------------------------------------------------
6735
6737 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
6738 << S->getStmtClassName();
6739 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
6740}
6741
6742
6744 if (Importer.returnWithErrorInTest())
6745 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
6747 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6748 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
6749 // ToII is nullptr when no symbolic name is given for output operand
6750 // see ParseStmtAsm::ParseAsmOperandsOpt
6751 Names.push_back(ToII);
6752 }
6753
6754 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6755 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
6756 // ToII is nullptr when no symbolic name is given for input operand
6757 // see ParseStmtAsm::ParseAsmOperandsOpt
6758 Names.push_back(ToII);
6759 }
6760
6762 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
6763 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
6764 Clobbers.push_back(*ClobberOrErr);
6765 else
6766 return ClobberOrErr.takeError();
6767
6768 }
6769
6771 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
6772 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
6773 Constraints.push_back(*OutputOrErr);
6774 else
6775 return OutputOrErr.takeError();
6776 }
6777
6778 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
6779 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
6780 Constraints.push_back(*InputOrErr);
6781 else
6782 return InputOrErr.takeError();
6783 }
6784
6785 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
6786 S->getNumLabels());
6787 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
6788 return std::move(Err);
6789
6790 if (Error Err =
6791 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
6792 return std::move(Err);
6793
6794 if (Error Err = ImportArrayChecked(
6795 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
6796 return std::move(Err);
6797
6798 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
6799 if (!AsmLocOrErr)
6800 return AsmLocOrErr.takeError();
6801 auto AsmStrOrErr = import(S->getAsmString());
6802 if (!AsmStrOrErr)
6803 return AsmStrOrErr.takeError();
6804 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
6805 if (!RParenLocOrErr)
6806 return RParenLocOrErr.takeError();
6807
6808 return new (Importer.getToContext()) GCCAsmStmt(
6809 Importer.getToContext(),
6810 *AsmLocOrErr,
6811 S->isSimple(),
6812 S->isVolatile(),
6813 S->getNumOutputs(),
6814 S->getNumInputs(),
6815 Names.data(),
6816 Constraints.data(),
6817 Exprs.data(),
6818 *AsmStrOrErr,
6819 S->getNumClobbers(),
6820 Clobbers.data(),
6821 S->getNumLabels(),
6822 *RParenLocOrErr);
6823}
6824
6826
6827 Error Err = Error::success();
6828 auto ToDG = importChecked(Err, S->getDeclGroup());
6829 auto ToBeginLoc = importChecked(Err, S->getBeginLoc());
6830 auto ToEndLoc = importChecked(Err, S->getEndLoc());
6831 if (Err)
6832 return std::move(Err);
6833 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
6834}
6835
6837 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
6838 if (!ToSemiLocOrErr)
6839 return ToSemiLocOrErr.takeError();
6840 return new (Importer.getToContext()) NullStmt(
6841 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
6842}
6843
6845 SmallVector<Stmt *, 8> ToStmts(S->size());
6846
6847 if (Error Err = ImportContainerChecked(S->body(), ToStmts))
6848 return std::move(Err);
6849
6850 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
6851 if (!ToLBracLocOrErr)
6852 return ToLBracLocOrErr.takeError();
6853
6854 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
6855 if (!ToRBracLocOrErr)
6856 return ToRBracLocOrErr.takeError();
6857
6858 FPOptionsOverride FPO =
6859 S->hasStoredFPFeatures() ? S->getStoredFPFeatures() : FPOptionsOverride();
6860 return CompoundStmt::Create(Importer.getToContext(), ToStmts, FPO,
6861 *ToLBracLocOrErr, *ToRBracLocOrErr);
6862}
6863
6865
6866 Error Err = Error::success();
6867 auto ToLHS = importChecked(Err, S->getLHS());
6868 auto ToRHS = importChecked(Err, S->getRHS());
6869 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6870 auto ToCaseLoc = importChecked(Err, S->getCaseLoc());
6871 auto ToEllipsisLoc = importChecked(Err, S->getEllipsisLoc());
6872 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6873 if (Err)
6874 return std::move(Err);
6875
6876 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
6877 ToCaseLoc, ToEllipsisLoc, ToColonLoc);
6878 ToStmt->setSubStmt(ToSubStmt);
6879
6880 return ToStmt;
6881}
6882
6884
6885 Error Err = Error::success();
6886 auto ToDefaultLoc = importChecked(Err, S->getDefaultLoc());
6887 auto ToColonLoc = importChecked(Err, S->getColonLoc());
6888 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6889 if (Err)
6890 return std::move(Err);
6891
6892 return new (Importer.getToContext()) DefaultStmt(
6893 ToDefaultLoc, ToColonLoc, ToSubStmt);
6894}
6895
6897
6898 Error Err = Error::success();
6899 auto ToIdentLoc = importChecked(Err, S->getIdentLoc());
6900 auto ToLabelDecl = importChecked(Err, S->getDecl());
6901 auto ToSubStmt = importChecked(Err, S->getSubStmt());
6902 if (Err)
6903 return std::move(Err);
6904
6905 return new (Importer.getToContext()) LabelStmt(
6906 ToIdentLoc, ToLabelDecl, ToSubStmt);
6907}
6908
6910 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
6911 if (!ToAttrLocOrErr)
6912 return ToAttrLocOrErr.takeError();
6913 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
6914 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
6915 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
6916 return std::move(Err);
6917 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
6918 if (!ToSubStmtOrErr)
6919 return ToSubStmtOrErr.takeError();
6920
6922 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
6923}
6924
6926
6927 Error Err = Error::success();
6928 auto ToIfLoc = importChecked(Err, S->getIfLoc());
6929 auto ToInit = importChecked(Err, S->getInit());
6930 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6931 auto ToCond = importChecked(Err, S->getCond());
6932 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6933 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6934 auto ToThen = importChecked(Err, S->getThen());
6935 auto ToElseLoc = importChecked(Err, S->getElseLoc());
6936 auto ToElse = importChecked(Err, S->getElse());
6937 if (Err)
6938 return std::move(Err);
6939
6940 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->getStatementKind(),
6941 ToInit, ToConditionVariable, ToCond, ToLParenLoc,
6942 ToRParenLoc, ToThen, ToElseLoc, ToElse);
6943}
6944
6946
6947 Error Err = Error::success();
6948 auto ToInit = importChecked(Err, S->getInit());
6949 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6950 auto ToCond = importChecked(Err, S->getCond());
6951 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6952 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6953 auto ToBody = importChecked(Err, S->getBody());
6954 auto ToSwitchLoc = importChecked(Err, S->getSwitchLoc());
6955 if (Err)
6956 return std::move(Err);
6957
6958 auto *ToStmt =
6959 SwitchStmt::Create(Importer.getToContext(), ToInit, ToConditionVariable,
6960 ToCond, ToLParenLoc, ToRParenLoc);
6961 ToStmt->setBody(ToBody);
6962 ToStmt->setSwitchLoc(ToSwitchLoc);
6963
6964 // Now we have to re-chain the cases.
6965 SwitchCase *LastChainedSwitchCase = nullptr;
6966 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
6967 SC = SC->getNextSwitchCase()) {
6968 Expected<SwitchCase *> ToSCOrErr = import(SC);
6969 if (!ToSCOrErr)
6970 return ToSCOrErr.takeError();
6971 if (LastChainedSwitchCase)
6972 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
6973 else
6974 ToStmt->setSwitchCaseList(*ToSCOrErr);
6975 LastChainedSwitchCase = *ToSCOrErr;
6976 }
6977
6978 return ToStmt;
6979}
6980
6982
6983 Error Err = Error::success();
6984 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
6985 auto ToCond = importChecked(Err, S->getCond());
6986 auto ToBody = importChecked(Err, S->getBody());
6987 auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
6988 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
6989 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
6990 if (Err)
6991 return std::move(Err);
6992
6993 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
6994 ToBody, ToWhileLoc, ToLParenLoc, ToRParenLoc);
6995}
6996
6998
6999 Error Err = Error::success();
7000 auto ToBody = importChecked(Err, S->getBody());
7001 auto ToCond = importChecked(Err, S->getCond());
7002 auto ToDoLoc = importChecked(Err, S->getDoLoc());
7003 auto ToWhileLoc = importChecked(Err, S->getWhileLoc());
7004 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7005 if (Err)
7006 return std::move(Err);
7007
7008 return new (Importer.getToContext()) DoStmt(
7009 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
7010}
7011
7013
7014 Error Err = Error::success();
7015 auto ToInit = importChecked(Err, S->getInit());
7016 auto ToCond = importChecked(Err, S->getCond());
7017 auto ToConditionVariable = importChecked(Err, S->getConditionVariable());
7018 auto ToInc = importChecked(Err, S->getInc());
7019 auto ToBody = importChecked(Err, S->getBody());
7020 auto ToForLoc = importChecked(Err, S->getForLoc());
7021 auto ToLParenLoc = importChecked(Err, S->getLParenLoc());
7022 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7023 if (Err)
7024 return std::move(Err);
7025
7026 return new (Importer.getToContext()) ForStmt(
7027 Importer.getToContext(),
7028 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
7029 ToRParenLoc);
7030}
7031
7033
7034 Error Err = Error::success();
7035 auto ToLabel = importChecked(Err, S->getLabel());
7036 auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
7037 auto ToLabelLoc = importChecked(Err, S->getLabelLoc());
7038 if (Err)
7039 return std::move(Err);
7040
7041 return new (Importer.getToContext()) GotoStmt(
7042 ToLabel, ToGotoLoc, ToLabelLoc);
7043}
7044
7046
7047 Error Err = Error::success();
7048 auto ToGotoLoc = importChecked(Err, S->getGotoLoc());
7049 auto ToStarLoc = importChecked(Err, S->getStarLoc());
7050 auto ToTarget = importChecked(Err, S->getTarget());
7051 if (Err)
7052 return std::move(Err);
7053
7054 return new (Importer.getToContext()) IndirectGotoStmt(
7055 ToGotoLoc, ToStarLoc, ToTarget);
7056}
7057
7059 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
7060 if (!ToContinueLocOrErr)
7061 return ToContinueLocOrErr.takeError();
7062 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
7063}
7064
7066 auto ToBreakLocOrErr = import(S->getBreakLoc());
7067 if (!ToBreakLocOrErr)
7068 return ToBreakLocOrErr.takeError();
7069 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
7070}
7071
7073
7074 Error Err = Error::success();
7075 auto ToReturnLoc = importChecked(Err, S->getReturnLoc());
7076 auto ToRetValue = importChecked(Err, S->getRetValue());
7077 auto ToNRVOCandidate = importChecked(Err, S->getNRVOCandidate());
7078 if (Err)
7079 return std::move(Err);
7080
7081 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
7082 ToNRVOCandidate);
7083}
7084
7086
7087 Error Err = Error::success();
7088 auto ToCatchLoc = importChecked(Err, S->getCatchLoc());
7089 auto ToExceptionDecl = importChecked(Err, S->getExceptionDecl());
7090 auto ToHandlerBlock = importChecked(Err, S->getHandlerBlock());
7091 if (Err)
7092 return std::move(Err);
7093
7094 return new (Importer.getToContext()) CXXCatchStmt (
7095 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
7096}
7097
7099 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
7100 if (!ToTryLocOrErr)
7101 return ToTryLocOrErr.takeError();
7102
7103 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
7104 if (!ToTryBlockOrErr)
7105 return ToTryBlockOrErr.takeError();
7106
7107 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
7108 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
7109 CXXCatchStmt *FromHandler = S->getHandler(HI);
7110 if (auto ToHandlerOrErr = import(FromHandler))
7111 ToHandlers[HI] = *ToHandlerOrErr;
7112 else
7113 return ToHandlerOrErr.takeError();
7114 }
7115
7116 return CXXTryStmt::Create(Importer.getToContext(), *ToTryLocOrErr,
7117 cast<CompoundStmt>(*ToTryBlockOrErr), ToHandlers);
7118}
7119
7121
7122 Error Err = Error::success();
7123 auto ToInit = importChecked(Err, S->getInit());
7124 auto ToRangeStmt = importChecked(Err, S->getRangeStmt());
7125 auto ToBeginStmt = importChecked(Err, S->getBeginStmt());
7126 auto ToEndStmt = importChecked(Err, S->getEndStmt());
7127 auto ToCond = importChecked(Err, S->getCond());
7128 auto ToInc = importChecked(Err, S->getInc());
7129 auto ToLoopVarStmt = importChecked(Err, S->getLoopVarStmt());
7130 auto ToBody = importChecked(Err, S->getBody());
7131 auto ToForLoc = importChecked(Err, S->getForLoc());
7132 auto ToCoawaitLoc = importChecked(Err, S->getCoawaitLoc());
7133 auto ToColonLoc = importChecked(Err, S->getColonLoc());
7134 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7135 if (Err)
7136 return std::move(Err);
7137
7138 return new (Importer.getToContext()) CXXForRangeStmt(
7139 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
7140 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
7141}
7142
7145 Error Err = Error::success();
7146 auto ToElement = importChecked(Err, S->getElement());
7147 auto ToCollection = importChecked(Err, S->getCollection());
7148 auto ToBody = importChecked(Err, S->getBody());
7149 auto ToForLoc = importChecked(Err, S->getForLoc());
7150 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7151 if (Err)
7152 return std::move(Err);
7153
7154 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
7155 ToCollection,
7156 ToBody,
7157 ToForLoc,
7158 ToRParenLoc);
7159}
7160
7162
7163 Error Err = Error::success();
7164 auto ToAtCatchLoc = importChecked(Err, S->getAtCatchLoc());
7165 auto ToRParenLoc = importChecked(Err, S->getRParenLoc());
7166 auto ToCatchParamDecl = importChecked(Err, S->getCatchParamDecl());
7167 auto ToCatchBody = importChecked(Err, S->getCatchBody());
7168 if (Err)
7169 return std::move(Err);
7170
7171 return new (Importer.getToContext()) ObjCAtCatchStmt (
7172 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
7173}
7174
7176 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
7177 if (!ToAtFinallyLocOrErr)
7178 return ToAtFinallyLocOrErr.takeError();
7179 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
7180 if (!ToAtFinallyStmtOrErr)
7181 return ToAtFinallyStmtOrErr.takeError();
7182 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
7183 *ToAtFinallyStmtOrErr);
7184}
7185
7187
7188 Error Err = Error::success();
7189 auto ToAtTryLoc = importChecked(Err, S->getAtTryLoc());
7190 auto ToTryBody = importChecked(Err, S->getTryBody());
7191 auto ToFinallyStmt = importChecked(Err, S->getFinallyStmt());
7192 if (Err)
7193 return std::move(Err);
7194
7195 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
7196 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
7197 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
7198 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
7199 ToCatchStmts[CI] = *ToCatchStmtOrErr;
7200 else
7201 return ToCatchStmtOrErr.takeError();
7202 }
7203
7204 return ObjCAtTryStmt::Create(Importer.getToContext(),
7205 ToAtTryLoc, ToTryBody,
7206 ToCatchStmts.begin(), ToCatchStmts.size(),
7207 ToFinallyStmt);
7208}
7209
7212
7213 Error Err = Error::success();
7214 auto ToAtSynchronizedLoc = importChecked(Err, S->getAtSynchronizedLoc());
7215 auto ToSynchExpr = importChecked(Err, S->getSynchExpr());
7216 auto ToSynchBody = importChecked(Err, S->getSynchBody());
7217 if (Err)
7218 return std::move(Err);
7219
7220 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
7221 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
7222}
7223
7225 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
7226 if (!ToThrowLocOrErr)
7227 return ToThrowLocOrErr.takeError();
7228 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
7229 if (!ToThrowExprOrErr)
7230 return ToThrowExprOrErr.takeError();
7231 return new (Importer.getToContext()) ObjCAtThrowStmt(
7232 *ToThrowLocOrErr, *ToThrowExprOrErr);
7233}
7234
7237 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
7238 if (!ToAtLocOrErr)
7239 return ToAtLocOrErr.takeError();
7240 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
7241 if (!ToSubStmtOrErr)
7242 return ToSubStmtOrErr.takeError();
7243 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
7244 *ToSubStmtOrErr);
7245}
7246
7247//----------------------------------------------------------------------------
7248// Import Expressions
7249//----------------------------------------------------------------------------
7251 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
7252 << E->getStmtClassName();
7253 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
7254}
7255
7257 Error Err = Error::success();
7258 auto ToType = importChecked(Err, E->getType());
7259 auto BLoc = importChecked(Err, E->getBeginLoc());
7260 auto RParenLoc = importChecked(Err, E->getEndLoc());
7261 if (Err)
7262 return std::move(Err);
7263 auto ParentContextOrErr = Importer.ImportContext(E->getParentContext());
7264 if (!ParentContextOrErr)
7265 return ParentContextOrErr.takeError();
7266
7267 return new (Importer.getToContext())
7268 SourceLocExpr(Importer.getToContext(), E->getIdentKind(), ToType, BLoc,
7269 RParenLoc, *ParentContextOrErr);
7270}
7271
7273
7274 Error Err = Error::success();
7275 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7276 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7277 auto ToWrittenTypeInfo = importChecked(Err, E->getWrittenTypeInfo());
7278 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7279 auto ToType = importChecked(Err, E->getType());
7280 if (Err)
7281 return std::move(Err);
7282
7283 return new (Importer.getToContext()) VAArgExpr(
7284 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
7285 E->isMicrosoftABI());
7286}
7287
7289
7290 Error Err = Error::success();
7291 auto ToCond = importChecked(Err, E->getCond());
7292 auto ToLHS = importChecked(Err, E->getLHS());
7293 auto ToRHS = importChecked(Err, E->getRHS());
7294 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7295 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7296 auto ToType = importChecked(Err, E->getType());
7297 if (Err)
7298 return std::move(Err);
7299
7302
7303 // The value of CondIsTrue only matters if the value is not
7304 // condition-dependent.
7305 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
7306
7307 return new (Importer.getToContext())
7308 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
7309 ToRParenLoc, CondIsTrue);
7310}
7311
7313 Error Err = Error::success();
7314 auto *ToSrcExpr = importChecked(Err, E->getSrcExpr());
7315 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7316 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7317 auto ToType = importChecked(Err, E->getType());
7318 auto *ToTSI = importChecked(Err, E->getTypeSourceInfo());
7319 if (Err)
7320 return std::move(Err);
7321
7322 return new (Importer.getToContext())
7323 ConvertVectorExpr(ToSrcExpr, ToTSI, ToType, E->getValueKind(),
7324 E->getObjectKind(), ToBuiltinLoc, ToRParenLoc);
7325}
7326
7328 Error Err = Error::success();
7329 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7330 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7331 auto ToType = importChecked(Err, E->getType());
7332 const unsigned NumSubExprs = E->getNumSubExprs();
7333
7335 llvm::ArrayRef<Expr *> FromSubExprs(E->getSubExprs(), NumSubExprs);
7336 ToSubExprs.resize(NumSubExprs);
7337
7338 if ((Err = ImportContainerChecked(FromSubExprs, ToSubExprs)))
7339 return std::move(Err);
7340
7341 return new (Importer.getToContext()) ShuffleVectorExpr(
7342 Importer.getToContext(), ToSubExprs, ToType, ToBeginLoc, ToRParenLoc);
7343}
7344
7346 ExpectedType TypeOrErr = import(E->getType());
7347 if (!TypeOrErr)
7348 return TypeOrErr.takeError();
7349
7350 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
7351 if (!BeginLocOrErr)
7352 return BeginLocOrErr.takeError();
7353
7354 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
7355}
7356
7359 Error Err = Error::success();
7360 auto ToGenericLoc = importChecked(Err, E->getGenericLoc());
7361 Expr *ToControllingExpr = nullptr;
7362 TypeSourceInfo *ToControllingType = nullptr;
7363 if (E->isExprPredicate())
7364 ToControllingExpr = importChecked(Err, E->getControllingExpr());
7365 else
7366 ToControllingType = importChecked(Err, E->getControllingType());
7367 assert((ToControllingExpr || ToControllingType) &&
7368 "Either the controlling expr or type must be nonnull");
7369 auto ToDefaultLoc = importChecked(Err, E->getDefaultLoc());
7370 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7371 if (Err)
7372 return std::move(Err);
7373
7374 ArrayRef<const TypeSourceInfo *> FromAssocTypes(E->getAssocTypeSourceInfos());
7375 SmallVector<TypeSourceInfo *, 1> ToAssocTypes(FromAssocTypes.size());
7376 if (Error Err = ImportContainerChecked(FromAssocTypes, ToAssocTypes))
7377 return std::move(Err);
7378
7379 ArrayRef<const Expr *> FromAssocExprs(E->getAssocExprs());
7380 SmallVector<Expr *, 1> ToAssocExprs(FromAssocExprs.size());
7381 if (Error Err = ImportContainerChecked(FromAssocExprs, ToAssocExprs))
7382 return std::move(Err);
7383
7384 const ASTContext &ToCtx = Importer.getToContext();
7385 if (E->isResultDependent()) {
7386 if (ToControllingExpr) {
7388 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7389 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7391 }
7393 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7394 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7396 }
7397
7398 if (ToControllingExpr) {
7400 ToCtx, ToGenericLoc, ToControllingExpr, llvm::ArrayRef(ToAssocTypes),
7401 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7402 E->containsUnexpandedParameterPack(), E->getResultIndex());
7403 }
7405 ToCtx, ToGenericLoc, ToControllingType, llvm::ArrayRef(ToAssocTypes),
7406 llvm::ArrayRef(ToAssocExprs), ToDefaultLoc, ToRParenLoc,
7407 E->containsUnexpandedParameterPack(), E->getResultIndex());
7408}
7409
7411
7412 Error Err = Error::success();
7413 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7414 auto ToType = importChecked(Err, E->getType());
7415 auto ToFunctionName = importChecked(Err, E->getFunctionName());
7416 if (Err)
7417 return std::move(Err);
7418
7419 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
7420 E->getIdentKind(), E->isTransparent(),
7421 ToFunctionName);
7422}
7423
7425
7426 Error Err = Error::success();
7427 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
7428 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
7429 auto ToDecl = importChecked(Err, E->getDecl());
7430 auto ToLocation = importChecked(Err, E->getLocation());
7431 auto ToType = importChecked(Err, E->getType());
7432 if (Err)
7433 return std::move(Err);
7434
7435 NamedDecl *ToFoundD = nullptr;
7436 if (E->getDecl() != E->getFoundDecl()) {
7437 auto FoundDOrErr = import(E->getFoundDecl());
7438 if (!FoundDOrErr)
7439 return FoundDOrErr.takeError();
7440 ToFoundD = *FoundDOrErr;
7441 }
7442
7443 TemplateArgumentListInfo ToTAInfo;
7444 TemplateArgumentListInfo *ToResInfo = nullptr;
7445 if (E->hasExplicitTemplateArgs()) {
7446 if (Error Err =
7447 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
7448 E->template_arguments(), ToTAInfo))
7449 return std::move(Err);
7450 ToResInfo = &ToTAInfo;
7451 }
7452
7453 auto *ToE = DeclRefExpr::Create(
7454 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
7455 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
7456 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse());
7457 if (E->hadMultipleCandidates())
7458 ToE->setHadMultipleCandidates(true);
7459 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
7460 return ToE;
7461}
7462
7464 ExpectedType TypeOrErr = import(E->getType());
7465 if (!TypeOrErr)
7466 return TypeOrErr.takeError();
7467
7468 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
7469}
7470
7472 ExpectedExpr ToInitOrErr = import(E->getInit());
7473 if (!ToInitOrErr)
7474 return ToInitOrErr.takeError();
7475
7476 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
7477 if (!ToEqualOrColonLocOrErr)
7478 return ToEqualOrColonLocOrErr.takeError();
7479
7480 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
7481 // List elements from the second, the first is Init itself
7482 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
7483 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
7484 ToIndexExprs[I - 1] = *ToArgOrErr;
7485 else
7486 return ToArgOrErr.takeError();
7487 }
7488
7489 SmallVector<Designator, 4> ToDesignators(E->size());
7490 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
7491 return std::move(Err);
7492
7494 Importer.getToContext(), ToDesignators,
7495 ToIndexExprs, *ToEqualOrColonLocOrErr,
7496 E->usesGNUSyntax(), *ToInitOrErr);
7497}
7498
7501 ExpectedType ToTypeOrErr = import(E->getType());
7502 if (!ToTypeOrErr)
7503 return ToTypeOrErr.takeError();
7504
7505 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7506 if (!ToLocationOrErr)
7507 return ToLocationOrErr.takeError();
7508
7509 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
7510 *ToTypeOrErr, *ToLocationOrErr);
7511}
7512
7514 ExpectedType ToTypeOrErr = import(E->getType());
7515 if (!ToTypeOrErr)
7516 return ToTypeOrErr.takeError();
7517
7518 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7519 if (!ToLocationOrErr)
7520 return ToLocationOrErr.takeError();
7521
7523 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
7524}
7525
7526
7528 ExpectedType ToTypeOrErr = import(E->getType());
7529 if (!ToTypeOrErr)
7530 return ToTypeOrErr.takeError();
7531
7532 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7533 if (!ToLocationOrErr)
7534 return ToLocationOrErr.takeError();
7535
7537 Importer.getToContext(), E->getValue(), E->isExact(),
7538 *ToTypeOrErr, *ToLocationOrErr);
7539}
7540
7542 auto ToTypeOrErr = import(E->getType());
7543 if (!ToTypeOrErr)
7544 return ToTypeOrErr.takeError();
7545
7546 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7547 if (!ToSubExprOrErr)
7548 return ToSubExprOrErr.takeError();
7549
7550 return new (Importer.getToContext()) ImaginaryLiteral(
7551 *ToSubExprOrErr, *ToTypeOrErr);
7552}
7553
7555 auto ToTypeOrErr = import(E->getType());
7556 if (!ToTypeOrErr)
7557 return ToTypeOrErr.takeError();
7558
7559 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7560 if (!ToLocationOrErr)
7561 return ToLocationOrErr.takeError();
7562
7563 return new (Importer.getToContext()) FixedPointLiteral(
7564 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr,
7565 Importer.getToContext().getFixedPointScale(*ToTypeOrErr));
7566}
7567
7569 ExpectedType ToTypeOrErr = import(E->getType());
7570 if (!ToTypeOrErr)
7571 return ToTypeOrErr.takeError();
7572
7573 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
7574 if (!ToLocationOrErr)
7575 return ToLocationOrErr.takeError();
7576
7577 return new (Importer.getToContext()) CharacterLiteral(
7578 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
7579}
7580
7582 ExpectedType ToTypeOrErr = import(E->getType());
7583 if (!ToTypeOrErr)
7584 return ToTypeOrErr.takeError();
7585
7586 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
7587 if (Error Err = ImportArrayChecked(
7588 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
7589 return std::move(Err);
7590
7591 return StringLiteral::Create(
7592 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
7593 *ToTypeOrErr, ToLocations.data(), ToLocations.size());
7594}
7595
7597
7598 Error Err = Error::success();
7599 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
7600 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
7601 auto ToType = importChecked(Err, E->getType());
7602 auto ToInitializer = importChecked(Err, E->getInitializer());
7603 if (Err)
7604 return std::move(Err);
7605
7606 return new (Importer.getToContext()) CompoundLiteralExpr(
7607 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
7608 ToInitializer, E->isFileScope());
7609}
7610
7612
7613 Error Err = Error::success();
7614 auto ToBuiltinLoc = importChecked(Err, E->getBuiltinLoc());
7615 auto ToType = importChecked(Err, E->getType());
7616 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7617 if (Err)
7618 return std::move(Err);
7619
7620 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
7621 if (Error Err = ImportArrayChecked(
7622 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
7623 ToExprs.begin()))
7624 return std::move(Err);
7625
7626 return new (Importer.getToContext()) AtomicExpr(
7627
7628 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
7629}
7630
7632 Error Err = Error::success();
7633 auto ToAmpAmpLoc = importChecked(Err, E->getAmpAmpLoc());
7634 auto ToLabelLoc = importChecked(Err, E->getLabelLoc());
7635 auto ToLabel = importChecked(Err, E->getLabel());
7636 auto ToType = importChecked(Err, E->getType());
7637 if (Err)
7638 return std::move(Err);
7639
7640 return new (Importer.getToContext()) AddrLabelExpr(
7641 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
7642}
7644 Error Err = Error::success();
7645 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7646 auto ToResult = importChecked(Err, E->getAPValueResult());
7647 if (Err)
7648 return std::move(Err);
7649
7650 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, ToResult);
7651}
7653 Error Err = Error::success();
7654 auto ToLParen = importChecked(Err, E->getLParen());
7655 auto ToRParen = importChecked(Err, E->getRParen());
7656 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7657 if (Err)
7658 return std::move(Err);
7659
7660 return new (Importer.getToContext())
7661 ParenExpr(ToLParen, ToRParen, ToSubExpr);
7662}
7663
7665 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
7666 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
7667 return std::move(Err);
7668
7669 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
7670 if (!ToLParenLocOrErr)
7671 return ToLParenLocOrErr.takeError();
7672
7673 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
7674 if (!ToRParenLocOrErr)
7675 return ToRParenLocOrErr.takeError();
7676
7677 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
7678 ToExprs, *ToRParenLocOrErr);
7679}
7680
7682 Error Err = Error::success();
7683 auto ToSubStmt = importChecked(Err, E->getSubStmt());
7684 auto ToType = importChecked(Err, E->getType());
7685 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
7686 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7687 if (Err)
7688 return std::move(Err);
7689
7690 return new (Importer.getToContext())
7691 StmtExpr(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc,
7692 E->getTemplateDepth());
7693}
7694
7696 Error Err = Error::success();
7697 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7698 auto ToType = importChecked(Err, E->getType());
7699 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7700 if (Err)
7701 return std::move(Err);
7702
7703 auto *UO = UnaryOperator::CreateEmpty(Importer.getToContext(),
7704 E->hasStoredFPFeatures());
7705 UO->setType(ToType);
7706 UO->setSubExpr(ToSubExpr);
7707 UO->setOpcode(E->getOpcode());
7708 UO->setOperatorLoc(ToOperatorLoc);
7709 UO->setCanOverflow(E->canOverflow());
7710 if (E->hasStoredFPFeatures())
7711 UO->setStoredFPFeatures(E->getStoredFPFeatures());
7712
7713 return UO;
7714}
7715
7717
7719 Error Err = Error::success();
7720 auto ToType = importChecked(Err, E->getType());
7721 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7722 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
7723 if (Err)
7724 return std::move(Err);
7725
7726 if (E->isArgumentType()) {
7727 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr =
7728 import(E->getArgumentTypeInfo());
7729 if (!ToArgumentTypeInfoOrErr)
7730 return ToArgumentTypeInfoOrErr.takeError();
7731
7732 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7733 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc,
7734 ToRParenLoc);
7735 }
7736
7737 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr());
7738 if (!ToArgumentExprOrErr)
7739 return ToArgumentExprOrErr.takeError();
7740
7741 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr(
7742 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc);
7743}
7744
7746 Error Err = Error::success();
7747 auto ToLHS = importChecked(Err, E->getLHS());
7748 auto ToRHS = importChecked(Err, E->getRHS());
7749 auto ToType = importChecked(Err, E->getType());
7750 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7751 if (Err)
7752 return std::move(Err);
7753
7755 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
7756 E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
7757 E->getFPFeatures());
7758}
7759
7761 Error Err = Error::success();
7762 auto ToCond = importChecked(Err, E->getCond());
7763 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7764 auto ToLHS = importChecked(Err, E->getLHS());
7765 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7766 auto ToRHS = importChecked(Err, E->getRHS());
7767 auto ToType = importChecked(Err, E->getType());
7768 if (Err)
7769 return std::move(Err);
7770
7771 return new (Importer.getToContext()) ConditionalOperator(
7772 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType,
7773 E->getValueKind(), E->getObjectKind());
7774}
7775
7778 Error Err = Error::success();
7779 auto ToCommon = importChecked(Err, E->getCommon());
7780 auto ToOpaqueValue = importChecked(Err, E->getOpaqueValue());
7781 auto ToCond = importChecked(Err, E->getCond());
7782 auto ToTrueExpr = importChecked(Err, E->getTrueExpr());
7783 auto ToFalseExpr = importChecked(Err, E->getFalseExpr());
7784 auto ToQuestionLoc = importChecked(Err, E->getQuestionLoc());
7785 auto ToColonLoc = importChecked(Err, E->getColonLoc());
7786 auto ToType = importChecked(Err, E->getType());
7787 if (Err)
7788 return std::move(Err);
7789
7790 return new (Importer.getToContext()) BinaryConditionalOperator(
7791 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr,
7792 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(),
7793 E->getObjectKind());
7794}
7795
7798 Error Err = Error::success();
7799 auto ToSemanticForm = importChecked(Err, E->getSemanticForm());
7800 if (Err)
7801 return std::move(Err);
7802
7803 return new (Importer.getToContext())
7804 CXXRewrittenBinaryOperator(ToSemanticForm, E->isReversed());
7805}
7806
7808 Error Err = Error::success();
7809 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7810 auto ToQueriedTypeSourceInfo =
7811 importChecked(Err, E->getQueriedTypeSourceInfo());
7812 auto ToDimensionExpression = importChecked(Err, E->getDimensionExpression());
7813 auto ToEndLoc = importChecked(Err, E->getEndLoc());
7814 auto ToType = importChecked(Err, E->getType());
7815 if (Err)
7816 return std::move(Err);
7817
7818 return new (Importer.getToContext()) ArrayTypeTraitExpr(
7819 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(),
7820 ToDimensionExpression, ToEndLoc, ToType);
7821}
7822
7824 Error Err = Error::success();
7825 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
7826 auto ToQueriedExpression = importChecked(Err, E->getQueriedExpression());
7827 auto ToEndLoc = importChecked(Err, E->getEndLoc());
7828 auto ToType = importChecked(Err, E->getType());
7829 if (Err)
7830 return std::move(Err);
7831
7832 return new (Importer.getToContext()) ExpressionTraitExpr(
7833 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(),
7834 ToEndLoc, ToType);
7835}
7836
7838 Error Err = Error::success();
7839 auto ToLocation = importChecked(Err, E->getLocation());
7840 auto ToType = importChecked(Err, E->getType());
7841 auto ToSourceExpr = importChecked(Err, E->getSourceExpr());
7842 if (Err)
7843 return std::move(Err);
7844
7845 return new (Importer.getToContext()) OpaqueValueExpr(
7846 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr);
7847}
7848
7850 Error Err = Error::success();
7851 auto ToLHS = importChecked(Err, E->getLHS());
7852 auto ToRHS = importChecked(Err, E->getRHS());
7853 auto ToType = importChecked(Err, E->getType());
7854 auto ToRBracketLoc = importChecked(Err, E->getRBracketLoc());
7855 if (Err)
7856 return std::move(Err);
7857
7858 return new (Importer.getToContext()) ArraySubscriptExpr(
7859 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(),
7860 ToRBracketLoc);
7861}
7862
7865 Error Err = Error::success();
7866 auto ToLHS = importChecked(Err, E->getLHS());
7867 auto ToRHS = importChecked(Err, E->getRHS());
7868 auto ToType = importChecked(Err, E->getType());
7869 auto ToComputationLHSType = importChecked(Err, E->getComputationLHSType());
7870 auto ToComputationResultType =
7871 importChecked(Err, E->getComputationResultType());
7872 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
7873 if (Err)
7874 return std::move(Err);
7875
7877 Importer.getToContext(), ToLHS, ToRHS, E->getOpcode(), ToType,
7878 E->getValueKind(), E->getObjectKind(), ToOperatorLoc,
7879 E->getFPFeatures(),
7880 ToComputationLHSType, ToComputationResultType);
7881}
7882
7886 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) {
7887 if (auto SpecOrErr = import(*I))
7888 Path.push_back(*SpecOrErr);
7889 else
7890 return SpecOrErr.takeError();
7891 }
7892 return Path;
7893}
7894
7896 ExpectedType ToTypeOrErr = import(E->getType());
7897 if (!ToTypeOrErr)
7898 return ToTypeOrErr.takeError();
7899
7900 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
7901 if (!ToSubExprOrErr)
7902 return ToSubExprOrErr.takeError();
7903
7904 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7905 if (!ToBasePathOrErr)
7906 return ToBasePathOrErr.takeError();
7907
7909 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr,
7910 &(*ToBasePathOrErr), E->getValueKind(), E->getFPFeatures());
7911}
7912
7914 Error Err = Error::success();
7915 auto ToType = importChecked(Err, E->getType());
7916 auto ToSubExpr = importChecked(Err, E->getSubExpr());
7917 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
7918 if (Err)
7919 return std::move(Err);
7920
7921 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E);
7922 if (!ToBasePathOrErr)
7923 return ToBasePathOrErr.takeError();
7924 CXXCastPath *ToBasePath = &(*ToBasePathOrErr);
7925
7926 switch (E->getStmtClass()) {
7927 case Stmt::CStyleCastExprClass: {
7928 auto *CCE = cast<CStyleCastExpr>(E);
7929 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc());
7930 if (!ToLParenLocOrErr)
7931 return ToLParenLocOrErr.takeError();
7932 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc());
7933 if (!ToRParenLocOrErr)
7934 return ToRParenLocOrErr.takeError();
7936 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(),
7937 ToSubExpr, ToBasePath, CCE->getFPFeatures(), ToTypeInfoAsWritten,
7938 *ToLParenLocOrErr, *ToRParenLocOrErr);
7939 }
7940
7941 case Stmt::CXXFunctionalCastExprClass: {
7942 auto *FCE = cast<CXXFunctionalCastExpr>(E);
7943 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc());
7944 if (!ToLParenLocOrErr)
7945 return ToLParenLocOrErr.takeError();
7946 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc());
7947 if (!ToRParenLocOrErr)
7948 return ToRParenLocOrErr.takeError();
7950 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten,
7951 E->getCastKind(), ToSubExpr, ToBasePath, FCE->getFPFeatures(),
7952 *ToLParenLocOrErr, *ToRParenLocOrErr);
7953 }
7954
7955 case Stmt::ObjCBridgedCastExprClass: {
7956 auto *OCE = cast<ObjCBridgedCastExpr>(E);
7957 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc());
7958 if (!ToLParenLocOrErr)
7959 return ToLParenLocOrErr.takeError();
7960 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc());
7961 if (!ToBridgeKeywordLocOrErr)
7962 return ToBridgeKeywordLocOrErr.takeError();
7963 return new (Importer.getToContext()) ObjCBridgedCastExpr(
7964 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(),
7965 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr);
7966 }
7967 case Stmt::BuiltinBitCastExprClass: {
7968 auto *BBC = cast<BuiltinBitCastExpr>(E);
7969 ExpectedSLoc ToKWLocOrErr = import(BBC->getBeginLoc());
7970 if (!ToKWLocOrErr)
7971 return ToKWLocOrErr.takeError();
7972 ExpectedSLoc ToRParenLocOrErr = import(BBC->getEndLoc());
7973 if (!ToRParenLocOrErr)
7974 return ToRParenLocOrErr.takeError();
7975 return new (Importer.getToContext()) BuiltinBitCastExpr(
7976 ToType, E->getValueKind(), E->getCastKind(), ToSubExpr,
7977 ToTypeInfoAsWritten, *ToKWLocOrErr, *ToRParenLocOrErr);
7978 }
7979 default:
7980 llvm_unreachable("Cast expression of unsupported type!");
7981 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
7982 }
7983}
7984
7987 for (int I = 0, N = E->getNumComponents(); I < N; ++I) {
7988 const OffsetOfNode &FromNode = E->getComponent(I);
7989
7990 SourceLocation ToBeginLoc, ToEndLoc;
7991
7992 if (FromNode.getKind() != OffsetOfNode::Base) {
7993 Error Err = Error::success();
7994 ToBeginLoc = importChecked(Err, FromNode.getBeginLoc());
7995 ToEndLoc = importChecked(Err, FromNode.getEndLoc());
7996 if (Err)
7997 return std::move(Err);
7998 }
7999
8000 switch (FromNode.getKind()) {
8002 ToNodes.push_back(
8003 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc));
8004 break;
8005 case OffsetOfNode::Base: {
8006 auto ToBSOrErr = import(FromNode.getBase());
8007 if (!ToBSOrErr)
8008 return ToBSOrErr.takeError();
8009 ToNodes.push_back(OffsetOfNode(*ToBSOrErr));
8010 break;
8011 }
8012 case OffsetOfNode::Field: {
8013 auto ToFieldOrErr = import(FromNode.getField());
8014 if (!ToFieldOrErr)
8015 return ToFieldOrErr.takeError();
8016 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc));
8017 break;
8018 }
8020 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName());
8021 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc));
8022 break;
8023 }
8024 }
8025 }
8026
8027 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions());
8028 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) {
8029 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I));
8030 if (!ToIndexExprOrErr)
8031 return ToIndexExprOrErr.takeError();
8032 ToExprs[I] = *ToIndexExprOrErr;
8033 }
8034
8035 Error Err = Error::success();
8036 auto ToType = importChecked(Err, E->getType());
8037 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
8038 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8039 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8040 if (Err)
8041 return std::move(Err);
8042
8043 return OffsetOfExpr::Create(
8044 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes,
8045 ToExprs, ToRParenLoc);
8046}
8047
8049 Error Err = Error::success();
8050 auto ToType = importChecked(Err, E->getType());
8051 auto ToOperand = importChecked(Err, E->getOperand());
8052 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
8053 auto ToEndLoc = importChecked(Err, E->getEndLoc());
8054 if (Err)
8055 return std::move(Err);
8056
8057 CanThrowResult ToCanThrow;
8058 if (E->isValueDependent())
8059 ToCanThrow = CT_Dependent;
8060 else
8061 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot;
8062
8063 return new (Importer.getToContext()) CXXNoexceptExpr(
8064 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc);
8065}
8066
8068 Error Err = Error::success();
8069 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8070 auto ToType = importChecked(Err, E->getType());
8071 auto ToThrowLoc = importChecked(Err, E->getThrowLoc());
8072 if (Err)
8073 return std::move(Err);
8074
8075 return new (Importer.getToContext()) CXXThrowExpr(
8076 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope());
8077}
8078
8080 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation());
8081 if (!ToUsedLocOrErr)
8082 return ToUsedLocOrErr.takeError();
8083
8084 auto ToParamOrErr = import(E->getParam());
8085 if (!ToParamOrErr)
8086 return ToParamOrErr.takeError();
8087
8088 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
8089 if (!UsedContextOrErr)
8090 return UsedContextOrErr.takeError();
8091
8092 // Import the default arg if it was not imported yet.
8093 // This is needed because it can happen that during the import of the
8094 // default expression (from VisitParmVarDecl) the same ParmVarDecl is
8095 // encountered here. The default argument for a ParmVarDecl is set in the
8096 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here,
8097 // see VisitParmVarDecl).
8098 ParmVarDecl *ToParam = *ToParamOrErr;
8099 if (!ToParam->getDefaultArg()) {
8100 std::optional<ParmVarDecl *> FromParam =
8101 Importer.getImportedFromDecl(ToParam);
8102 assert(FromParam && "ParmVarDecl was not imported?");
8103
8104 if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam))
8105 return std::move(Err);
8106 }
8107 Expr *RewrittenInit = nullptr;
8108 if (E->hasRewrittenInit()) {
8109 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
8110 if (!ExprOrErr)
8111 return ExprOrErr.takeError();
8112 RewrittenInit = ExprOrErr.get();
8113 }
8114 return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
8115 *ToParamOrErr, RewrittenInit,
8116 *UsedContextOrErr);
8117}
8118
8121 Error Err = Error::success();
8122 auto ToType = importChecked(Err, E->getType());
8123 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
8124 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8125 if (Err)
8126 return std::move(Err);
8127
8128 return new (Importer.getToContext()) CXXScalarValueInitExpr(
8129 ToType, ToTypeSourceInfo, ToRParenLoc);
8130}
8131
8134 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8135 if (!ToSubExprOrErr)
8136 return ToSubExprOrErr.takeError();
8137
8138 auto ToDtorOrErr = import(E->getTemporary()->getDestructor());
8139 if (!ToDtorOrErr)
8140 return ToDtorOrErr.takeError();
8141
8142 ASTContext &ToCtx = Importer.getToContext();
8143 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr);
8144 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr);
8145}
8146
8148
8150 Error Err = Error::success();
8151 auto ToConstructor = importChecked(Err, E->getConstructor());
8152 auto ToType = importChecked(Err, E->getType());
8153 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
8154 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
8155 if (Err)
8156 return std::move(Err);
8157
8158 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8159 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8160 return std::move(Err);
8161
8163 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs,
8164 ToParenOrBraceRange, E->hadMultipleCandidates(),
8165 E->isListInitialization(), E->isStdInitListInitialization(),
8166 E->requiresZeroInitialization());
8167}
8168
8171 DeclContext *DC, *LexicalDC;
8172 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
8173 return std::move(Err);
8174
8175 Error Err = Error::success();
8176 auto Temporary = importChecked(Err, D->getTemporaryExpr());
8177 auto ExtendingDecl = importChecked(Err, D->getExtendingDecl());
8178 if (Err)
8179 return std::move(Err);
8180 // FIXME: Should ManglingNumber get numbers associated with 'to' context?
8181
8183 if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl,
8184 D->getManglingNumber()))
8185 return To;
8186
8187 To->setLexicalDeclContext(LexicalDC);
8188 LexicalDC->addDeclInternal(To);
8189 return To;
8190}
8191
8194 Error Err = Error::success();
8195 auto ToType = importChecked(Err, E->getType());
8196 Expr *ToTemporaryExpr = importChecked(
8197 Err, E->getLifetimeExtendedTemporaryDecl() ? nullptr : E->getSubExpr());
8198 auto ToMaterializedDecl =
8199 importChecked(Err, E->getLifetimeExtendedTemporaryDecl());
8200 if (Err)
8201 return std::move(Err);
8202
8203 if (!ToTemporaryExpr)
8204 ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr());
8205
8206 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr(
8207 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(),
8208 ToMaterializedDecl);
8209
8210 return ToMTE;
8211}
8212
8214 Error Err = Error::success();
8215 auto ToType = importChecked(Err, E->getType());
8216 auto ToPattern = importChecked(Err, E->getPattern());
8217 auto ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
8218 if (Err)
8219 return std::move(Err);
8220
8221 return new (Importer.getToContext()) PackExpansionExpr(
8222 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions());
8223}
8224
8226 Error Err = Error::success();
8227 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8228 auto ToPack = importChecked(Err, E->getPack());
8229 auto ToPackLoc = importChecked(Err, E->getPackLoc());
8230 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8231 if (Err)
8232 return std::move(Err);
8233
8234 std::optional<unsigned> Length;
8235 if (!E->isValueDependent())
8236 Length = E->getPackLength();
8237
8238 SmallVector<TemplateArgument, 8> ToPartialArguments;
8239 if (E->isPartiallySubstituted()) {
8240 if (Error Err = ImportTemplateArguments(E->getPartialArguments(),
8241 ToPartialArguments))
8242 return std::move(Err);
8243 }
8244
8246 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc,
8247 Length, ToPartialArguments);
8248}
8249
8250
8252 Error Err = Error::success();
8253 auto ToOperatorNew = importChecked(Err, E->getOperatorNew());
8254 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
8255 auto ToTypeIdParens = importChecked(Err, E->getTypeIdParens());
8256 auto ToArraySize = importChecked(Err, E->getArraySize());
8257 auto ToInitializer = importChecked(Err, E->getInitializer());
8258 auto ToType = importChecked(Err, E->getType());
8259 auto ToAllocatedTypeSourceInfo =
8260 importChecked(Err, E->getAllocatedTypeSourceInfo());
8261 auto ToSourceRange = importChecked(Err, E->getSourceRange());
8262 auto ToDirectInitRange = importChecked(Err, E->getDirectInitRange());
8263 if (Err)
8264 return std::move(Err);
8265
8266 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs());
8267 if (Error Err =
8268 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs))
8269 return std::move(Err);
8270
8271 return CXXNewExpr::Create(
8272 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew,
8273 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(),
8274 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(),
8275 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange,
8276 ToDirectInitRange);
8277}
8278
8280 Error Err = Error::success();
8281 auto ToType = importChecked(Err, E->getType());
8282 auto ToOperatorDelete = importChecked(Err, E->getOperatorDelete());
8283 auto ToArgument = importChecked(Err, E->getArgument());
8284 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
8285 if (Err)
8286 return std::move(Err);
8287
8288 return new (Importer.getToContext()) CXXDeleteExpr(
8289 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(),
8290 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument,
8291 ToBeginLoc);
8292}
8293
8295 Error Err = Error::success();
8296 auto ToType = importChecked(Err, E->getType());
8297 auto ToLocation = importChecked(Err, E->getLocation());
8298 auto ToConstructor = importChecked(Err, E->getConstructor());
8299 auto ToParenOrBraceRange = importChecked(Err, E->getParenOrBraceRange());
8300 if (Err)
8301 return std::move(Err);
8302
8303 SmallVector<Expr *, 6> ToArgs(E->getNumArgs());
8304 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8305 return std::move(Err);
8306
8308 Importer.getToContext(), ToType, ToLocation, ToConstructor,
8309 E->isElidable(), ToArgs, E->hadMultipleCandidates(),
8310 E->isListInitialization(), E->isStdInitListInitialization(),
8311 E->requiresZeroInitialization(), E->getConstructionKind(),
8312 ToParenOrBraceRange);
8313 ToE->setIsImmediateEscalating(E->isImmediateEscalating());
8314 return ToE;
8315}
8316
8318 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8319 if (!ToSubExprOrErr)
8320 return ToSubExprOrErr.takeError();
8321
8322 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects());
8323 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects))
8324 return std::move(Err);
8325
8327 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(),
8328 ToObjects);
8329}
8330
8332 Error Err = Error::success();
8333 auto ToCallee = importChecked(Err, E->getCallee());
8334 auto ToType = importChecked(Err, E->getType());
8335 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8336 if (Err)
8337 return std::move(Err);
8338
8339 SmallVector<Expr *, 4> ToArgs(E->getNumArgs());
8340 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8341 return std::move(Err);
8342
8343 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs,
8344 ToType, E->getValueKind(), ToRParenLoc,
8345 E->getFPFeatures());
8346}
8347
8349 ExpectedType ToTypeOrErr = import(E->getType());
8350 if (!ToTypeOrErr)
8351 return ToTypeOrErr.takeError();
8352
8353 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
8354 if (!ToLocationOrErr)
8355 return ToLocationOrErr.takeError();
8356
8357 return CXXThisExpr::Create(Importer.getToContext(), *ToLocationOrErr,
8358 *ToTypeOrErr, E->isImplicit());
8359}
8360
8362 ExpectedType ToTypeOrErr = import(E->getType());
8363 if (!ToTypeOrErr)
8364 return ToTypeOrErr.takeError();
8365
8366 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
8367 if (!ToLocationOrErr)
8368 return ToLocationOrErr.takeError();
8369
8370 return CXXBoolLiteralExpr::Create(Importer.getToContext(), E->getValue(),
8371 *ToTypeOrErr, *ToLocationOrErr);
8372}
8373
8375 Error Err = Error::success();
8376 auto ToBase = importChecked(Err, E->getBase());
8377 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8378 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8379 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8380 auto ToMemberDecl = importChecked(Err, E->getMemberDecl());
8381 auto ToType = importChecked(Err, E->getType());
8382 auto ToDecl = importChecked(Err, E->getFoundDecl().getDecl());
8383 auto ToName = importChecked(Err, E->getMemberNameInfo().getName());
8384 auto ToLoc = importChecked(Err, E->getMemberNameInfo().getLoc());
8385 if (Err)
8386 return std::move(Err);
8387
8388 DeclAccessPair ToFoundDecl =
8389 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess());
8390
8391 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc);
8392
8393 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8394 if (E->hasExplicitTemplateArgs()) {
8395 if (Error Err =
8396 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
8397 E->template_arguments(), ToTAInfo))
8398 return std::move(Err);
8399 ResInfo = &ToTAInfo;
8400 }
8401
8402 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(),
8403 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
8404 ToMemberDecl, ToFoundDecl, ToMemberNameInfo,
8405 ResInfo, ToType, E->getValueKind(),
8406 E->getObjectKind(), E->isNonOdrUse());
8407}
8408
8411 Error Err = Error::success();
8412 auto ToBase = importChecked(Err, E->getBase());
8413 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8414 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8415 auto ToScopeTypeInfo = importChecked(Err, E->getScopeTypeInfo());
8416 auto ToColonColonLoc = importChecked(Err, E->getColonColonLoc());
8417 auto ToTildeLoc = importChecked(Err, E->getTildeLoc());
8418 if (Err)
8419 return std::move(Err);
8420
8422 if (const IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) {
8423 const IdentifierInfo *ToII = Importer.Import(FromII);
8424 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc());
8425 if (!ToDestroyedTypeLocOrErr)
8426 return ToDestroyedTypeLocOrErr.takeError();
8427 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr);
8428 } else {
8429 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo()))
8430 Storage = PseudoDestructorTypeStorage(*ToTIOrErr);
8431 else
8432 return ToTIOrErr.takeError();
8433 }
8434
8435 return new (Importer.getToContext()) CXXPseudoDestructorExpr(
8436 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc,
8437 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage);
8438}
8439
8442 Error Err = Error::success();
8443 auto ToType = importChecked(Err, E->getType());
8444 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8445 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8446 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8447 auto ToFirstQualifierFoundInScope =
8448 importChecked(Err, E->getFirstQualifierFoundInScope());
8449 if (Err)
8450 return std::move(Err);
8451
8452 Expr *ToBase = nullptr;
8453 if (!E->isImplicitAccess()) {
8454 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
8455 ToBase = *ToBaseOrErr;
8456 else
8457 return ToBaseOrErr.takeError();
8458 }
8459
8460 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr;
8461
8462 if (E->hasExplicitTemplateArgs()) {
8463 if (Error Err =
8464 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(),
8465 E->template_arguments(), ToTAInfo))
8466 return std::move(Err);
8467 ResInfo = &ToTAInfo;
8468 }
8469 auto ToMember = importChecked(Err, E->getMember());
8470 auto ToMemberLoc = importChecked(Err, E->getMemberLoc());
8471 if (Err)
8472 return std::move(Err);
8473 DeclarationNameInfo ToMemberNameInfo(ToMember, ToMemberLoc);
8474
8475 // Import additional name location/type info.
8476 if (Error Err =
8477 ImportDeclarationNameLoc(E->getMemberNameInfo(), ToMemberNameInfo))
8478 return std::move(Err);
8479
8481 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc,
8482 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope,
8483 ToMemberNameInfo, ResInfo);
8484}
8485
8488 Error Err = Error::success();
8489 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8490 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8491 auto ToDeclName = importChecked(Err, E->getDeclName());
8492 auto ToNameLoc = importChecked(Err, E->getNameInfo().getLoc());
8493 auto ToLAngleLoc = importChecked(Err, E->getLAngleLoc());
8494 auto ToRAngleLoc = importChecked(Err, E->getRAngleLoc());
8495 if (Err)
8496 return std::move(Err);
8497
8498 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc);
8499 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8500 return std::move(Err);
8501
8502 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc);
8503 TemplateArgumentListInfo *ResInfo = nullptr;
8504 if (E->hasExplicitTemplateArgs()) {
8505 if (Error Err =
8506 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
8507 return std::move(Err);
8508 ResInfo = &ToTAInfo;
8509 }
8510
8512 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc,
8513 ToNameInfo, ResInfo);
8514}
8515
8518 Error Err = Error::success();
8519 auto ToLParenLoc = importChecked(Err, E->getLParenLoc());
8520 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8521 auto ToType = importChecked(Err, E->getType());
8522 auto ToTypeSourceInfo = importChecked(Err, E->getTypeSourceInfo());
8523 if (Err)
8524 return std::move(Err);
8525
8526 SmallVector<Expr *, 8> ToArgs(E->getNumArgs());
8527 if (Error Err =
8528 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin()))
8529 return std::move(Err);
8530
8532 Importer.getToContext(), ToType, ToTypeSourceInfo, ToLParenLoc,
8533 llvm::ArrayRef(ToArgs), ToRParenLoc, E->isListInitialization());
8534}
8535
8538 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass());
8539 if (!ToNamingClassOrErr)
8540 return ToNamingClassOrErr.takeError();
8541
8542 auto ToQualifierLocOrErr = import(E->getQualifierLoc());
8543 if (!ToQualifierLocOrErr)
8544 return ToQualifierLocOrErr.takeError();
8545
8546 Error Err = Error::success();
8547 auto ToName = importChecked(Err, E->getName());
8548 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8549 if (Err)
8550 return std::move(Err);
8551 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8552
8553 // Import additional name location/type info.
8554 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8555 return std::move(Err);
8556
8557 UnresolvedSet<8> ToDecls;
8558 for (auto *D : E->decls())
8559 if (auto ToDOrErr = import(D))
8560 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8561 else
8562 return ToDOrErr.takeError();
8563
8564 if (E->hasExplicitTemplateArgs()) {
8565 TemplateArgumentListInfo ToTAInfo;
8566 if (Error Err = ImportTemplateArgumentListInfo(
8567 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(),
8568 ToTAInfo))
8569 return std::move(Err);
8570
8571 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc());
8572 if (!ToTemplateKeywordLocOrErr)
8573 return ToTemplateKeywordLocOrErr.takeError();
8574
8575 const bool KnownDependent =
8576 (E->getDependence() & ExprDependence::TypeValue) ==
8577 ExprDependence::TypeValue;
8579 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8580 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo,
8581 ToDecls.begin(), ToDecls.end(), KnownDependent);
8582 }
8583
8585 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
8586 ToNameInfo, E->requiresADL(), ToDecls.begin(), ToDecls.end(),
8587 /*KnownDependent=*/E->isTypeDependent());
8588}
8589
8592 Error Err = Error::success();
8593 auto ToType = importChecked(Err, E->getType());
8594 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8595 auto ToQualifierLoc = importChecked(Err, E->getQualifierLoc());
8596 auto ToTemplateKeywordLoc = importChecked(Err, E->getTemplateKeywordLoc());
8597 auto ToName = importChecked(Err, E->getName());
8598 auto ToNameLoc = importChecked(Err, E->getNameLoc());
8599 if (Err)
8600 return std::move(Err);
8601
8602 DeclarationNameInfo ToNameInfo(ToName, ToNameLoc);
8603 // Import additional name location/type info.
8604 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo))
8605 return std::move(Err);
8606
8607 UnresolvedSet<8> ToDecls;
8608 for (Decl *D : E->decls())
8609 if (auto ToDOrErr = import(D))
8610 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr));
8611 else
8612 return ToDOrErr.takeError();
8613
8614 TemplateArgumentListInfo ToTAInfo;
8615 TemplateArgumentListInfo *ResInfo = nullptr;
8616 if (E->hasExplicitTemplateArgs()) {
8617 TemplateArgumentListInfo FromTAInfo;
8618 E->copyTemplateArgumentsInto(FromTAInfo);
8619 if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo))
8620 return std::move(Err);
8621 ResInfo = &ToTAInfo;
8622 }
8623
8624 Expr *ToBase = nullptr;
8625 if (!E->isImplicitAccess()) {
8626 if (ExpectedExpr ToBaseOrErr = import(E->getBase()))
8627 ToBase = *ToBaseOrErr;
8628 else
8629 return ToBaseOrErr.takeError();
8630 }
8631
8633 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType,
8634 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc,
8635 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end());
8636}
8637
8639 Error Err = Error::success();
8640 auto ToCallee = importChecked(Err, E->getCallee());
8641 auto ToType = importChecked(Err, E->getType());
8642 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8643 if (Err)
8644 return std::move(Err);
8645
8646 unsigned NumArgs = E->getNumArgs();
8647 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs);
8648 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs))
8649 return std::move(Err);
8650
8651 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
8653 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType,
8654 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(),
8655 OCE->getADLCallKind());
8656 }
8657
8658 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType,
8659 E->getValueKind(), ToRParenLoc, E->getFPFeatures(),
8660 /*MinNumArgs=*/0, E->getADLCallKind());
8661}
8662
8664 CXXRecordDecl *FromClass = E->getLambdaClass();
8665 auto ToClassOrErr = import(FromClass);
8666 if (!ToClassOrErr)
8667 return ToClassOrErr.takeError();
8668 CXXRecordDecl *ToClass = *ToClassOrErr;
8669
8670 auto ToCallOpOrErr = import(E->getCallOperator());
8671 if (!ToCallOpOrErr)
8672 return ToCallOpOrErr.takeError();
8673
8674 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size());
8675 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits))
8676 return std::move(Err);
8677
8678 Error Err = Error::success();
8679 auto ToIntroducerRange = importChecked(Err, E->getIntroducerRange());
8680 auto ToCaptureDefaultLoc = importChecked(Err, E->getCaptureDefaultLoc());
8681 auto ToEndLoc = importChecked(Err, E->getEndLoc());
8682 if (Err)
8683 return std::move(Err);
8684
8685 return LambdaExpr::Create(Importer.getToContext(), ToClass, ToIntroducerRange,
8686 E->getCaptureDefault(), ToCaptureDefaultLoc,
8687 E->hasExplicitParameters(),
8688 E->hasExplicitResultType(), ToCaptureInits,
8689 ToEndLoc, E->containsUnexpandedParameterPack());
8690}
8691
8692
8694 Error Err = Error::success();
8695 auto ToLBraceLoc = importChecked(Err, E->getLBraceLoc());
8696 auto ToRBraceLoc = importChecked(Err, E->getRBraceLoc());
8697 auto ToType = importChecked(Err, E->getType());
8698 if (Err)
8699 return std::move(Err);
8700
8701 SmallVector<Expr *, 4> ToExprs(E->getNumInits());
8702 if (Error Err = ImportContainerChecked(E->inits(), ToExprs))
8703 return std::move(Err);
8704
8705 ASTContext &ToCtx = Importer.getToContext();
8706 InitListExpr *To = new (ToCtx) InitListExpr(
8707 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc);
8708 To->setType(ToType);
8709
8710 if (E->hasArrayFiller()) {
8711 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller()))
8712 To->setArrayFiller(*ToFillerOrErr);
8713 else
8714 return ToFillerOrErr.takeError();
8715 }
8716
8717 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) {
8718 if (auto ToFDOrErr = import(FromFD))
8719 To->setInitializedFieldInUnion(*ToFDOrErr);
8720 else
8721 return ToFDOrErr.takeError();
8722 }
8723
8724 if (InitListExpr *SyntForm = E->getSyntacticForm()) {
8725 if (auto ToSyntFormOrErr = import(SyntForm))
8726 To->setSyntacticForm(*ToSyntFormOrErr);
8727 else
8728 return ToSyntFormOrErr.takeError();
8729 }
8730
8731 // Copy InitListExprBitfields, which are not handled in the ctor of
8732 // InitListExpr.
8733 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator());
8734
8735 return To;
8736}
8737
8740 ExpectedType ToTypeOrErr = import(E->getType());
8741 if (!ToTypeOrErr)
8742 return ToTypeOrErr.takeError();
8743
8744 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
8745 if (!ToSubExprOrErr)
8746 return ToSubExprOrErr.takeError();
8747
8748 return new (Importer.getToContext()) CXXStdInitializerListExpr(
8749 *ToTypeOrErr, *ToSubExprOrErr);
8750}
8751
8754 Error Err = Error::success();
8755 auto ToLocation = importChecked(Err, E->getLocation());
8756 auto ToType = importChecked(Err, E->getType());
8757 auto ToConstructor = importChecked(Err, E->getConstructor());
8758 if (Err)
8759 return std::move(Err);
8760
8761 return new (Importer.getToContext()) CXXInheritedCtorInitExpr(
8762 ToLocation, ToType, ToConstructor, E->constructsVBase(),
8763 E->inheritedFromVBase());
8764}
8765
8767 Error Err = Error::success();
8768 auto ToType = importChecked(Err, E->getType());
8769 auto ToCommonExpr = importChecked(Err, E->getCommonExpr());
8770 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8771 if (Err)
8772 return std::move(Err);
8773
8774 return new (Importer.getToContext()) ArrayInitLoopExpr(
8775 ToType, ToCommonExpr, ToSubExpr);
8776}
8777
8779 ExpectedType ToTypeOrErr = import(E->getType());
8780 if (!ToTypeOrErr)
8781 return ToTypeOrErr.takeError();
8782 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr);
8783}
8784
8786 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc());
8787 if (!ToBeginLocOrErr)
8788 return ToBeginLocOrErr.takeError();
8789
8790 auto ToFieldOrErr = import(E->getField());
8791 if (!ToFieldOrErr)
8792 return ToFieldOrErr.takeError();
8793
8794 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext());
8795 if (!UsedContextOrErr)
8796 return UsedContextOrErr.takeError();
8797
8798 FieldDecl *ToField = *ToFieldOrErr;
8799 assert(ToField->hasInClassInitializer() &&
8800 "Field should have in-class initializer if there is a default init "
8801 "expression that uses it.");
8802 if (!ToField->getInClassInitializer()) {
8803 // The in-class initializer may be not yet set in "To" AST even if the
8804 // field is already there. This must be set here to make construction of
8805 // CXXDefaultInitExpr work.
8806 auto ToInClassInitializerOrErr =
8807 import(E->getField()->getInClassInitializer());
8808 if (!ToInClassInitializerOrErr)
8809 return ToInClassInitializerOrErr.takeError();
8810 ToField->setInClassInitializer(*ToInClassInitializerOrErr);
8811 }
8812
8813 Expr *RewrittenInit = nullptr;
8814 if (E->hasRewrittenInit()) {
8815 ExpectedExpr ExprOrErr = import(E->getRewrittenExpr());
8816 if (!ExprOrErr)
8817 return ExprOrErr.takeError();
8818 RewrittenInit = ExprOrErr.get();
8819 }
8820
8821 return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr,
8822 ToField, *UsedContextOrErr, RewrittenInit);
8823}
8824
8826 Error Err = Error::success();
8827 auto ToType = importChecked(Err, E->getType());
8828 auto ToSubExpr = importChecked(Err, E->getSubExpr());
8829 auto ToTypeInfoAsWritten = importChecked(Err, E->getTypeInfoAsWritten());
8830 auto ToOperatorLoc = importChecked(Err, E->getOperatorLoc());
8831 auto ToRParenLoc = importChecked(Err, E->getRParenLoc());
8832 auto ToAngleBrackets = importChecked(Err, E->getAngleBrackets());
8833 if (Err)
8834 return std::move(Err);
8835
8837 CastKind CK = E->getCastKind();
8838 auto ToBasePathOrErr = ImportCastPath(E);
8839 if (!ToBasePathOrErr)
8840 return ToBasePathOrErr.takeError();
8841
8842 if (auto CCE = dyn_cast<CXXStaticCastExpr>(E)) {
8844 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8845 ToTypeInfoAsWritten, CCE->getFPFeatures(), ToOperatorLoc, ToRParenLoc,
8846 ToAngleBrackets);
8847 } else if (isa<CXXDynamicCastExpr>(E)) {
8849 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8850 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8851 } else if (isa<CXXReinterpretCastExpr>(E)) {
8853 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr),
8854 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8855 } else if (isa<CXXConstCastExpr>(E)) {
8857 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten,
8858 ToOperatorLoc, ToRParenLoc, ToAngleBrackets);
8859 } else {
8860 llvm_unreachable("Unknown cast type");
8861 return make_error<ASTImportError>();
8862 }
8863}
8864
8867 Error Err = Error::success();
8868 auto ToType = importChecked(Err, E->getType());
8869 auto ToExprLoc = importChecked(Err, E->getExprLoc());
8870 auto ToAssociatedDecl = importChecked(Err, E->getAssociatedDecl());
8871 auto ToReplacement = importChecked(Err, E->getReplacement());
8872 if (Err)
8873 return std::move(Err);
8874
8875 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr(
8876 ToType, E->getValueKind(), ToExprLoc, ToReplacement, ToAssociatedDecl,
8877 E->getIndex(), E->getPackIndex(), E->isReferenceParameter());
8878}
8879
8881 Error Err = Error::success();
8882 auto ToType = importChecked(Err, E->getType());
8883 auto ToBeginLoc = importChecked(Err, E->getBeginLoc());
8884 auto ToEndLoc = importChecked(Err, E->getEndLoc());
8885 if (Err)
8886 return std::move(Err);
8887
8888 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs());
8889 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs))
8890 return std::move(Err);
8891
8892 // According to Sema::BuildTypeTrait(), if E is value-dependent,
8893 // Value is always false.
8894 bool ToValue = (E->isValueDependent() ? false : E->getValue());
8895
8896 return TypeTraitExpr::Create(
8897 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs,
8898 ToEndLoc, ToValue);
8899}
8900
8902 ExpectedType ToTypeOrErr = import(E->getType());
8903 if (!ToTypeOrErr)
8904 return ToTypeOrErr.takeError();
8905
8906 auto ToSourceRangeOrErr = import(E->getSourceRange());
8907 if (!ToSourceRangeOrErr)
8908 return ToSourceRangeOrErr.takeError();
8909
8910 if (E->isTypeOperand()) {
8911 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo()))
8912 return new (Importer.getToContext()) CXXTypeidExpr(
8913 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr);
8914 else
8915 return ToTSIOrErr.takeError();
8916 }
8917
8918 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand());
8919 if (!ToExprOperandOrErr)
8920 return ToExprOperandOrErr.takeError();
8921
8922 return new (Importer.getToContext()) CXXTypeidExpr(
8923 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr);
8924}
8925
8927 Error Err = Error::success();
8928
8929 QualType ToType = importChecked(Err, E->getType());
8930 UnresolvedLookupExpr *ToCallee = importChecked(Err, E->getCallee());
8931 SourceLocation ToLParenLoc = importChecked(Err, E->getLParenLoc());
8932 Expr *ToLHS = importChecked(Err, E->getLHS());
8933 SourceLocation ToEllipsisLoc = importChecked(Err, E->getEllipsisLoc());
8934 Expr *ToRHS = importChecked(Err, E->getRHS());
8935 SourceLocation ToRParenLoc = importChecked(Err, E->getRParenLoc());
8936
8937 if (Err)
8938 return std::move(Err);
8939
8940 return new (Importer.getToContext())
8941 CXXFoldExpr(ToType, ToCallee, ToLParenLoc, ToLHS, E->getOperator(),
8942 ToEllipsisLoc, ToRHS, ToRParenLoc, E->getNumExpansions());
8943}
8944
8946 CXXMethodDecl *FromMethod) {
8947 Error ImportErrors = Error::success();
8948 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) {
8949 if (auto ImportedOrErr = import(FromOverriddenMethod))
8950 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>(
8951 (*ImportedOrErr)->getCanonicalDecl()));
8952 else
8953 ImportErrors =
8954 joinErrors(std::move(ImportErrors), ImportedOrErr.takeError());
8955 }
8956 return ImportErrors;
8957}
8958
8960 ASTContext &FromContext, FileManager &FromFileManager,
8961 bool MinimalImport,
8962 std::shared_ptr<ASTImporterSharedState> SharedState)
8963 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext),
8964 ToFileManager(ToFileManager), FromFileManager(FromFileManager),
8965 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) {
8966
8967 // Create a default state without the lookup table: LLDB case.
8968 if (!SharedState) {
8969 this->SharedState = std::make_shared<ASTImporterSharedState>();
8970 }
8971
8972 ImportedDecls[FromContext.getTranslationUnitDecl()] =
8973 ToContext.getTranslationUnitDecl();
8974}
8975
8976ASTImporter::~ASTImporter() = default;
8977
8978std::optional<unsigned> ASTImporter::getFieldIndex(Decl *F) {
8979 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) &&
8980 "Try to get field index for non-field.");
8981
8982 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext());
8983 if (!Owner)
8984 return std::nullopt;
8985
8986 unsigned Index = 0;
8987 for (const auto *D : Owner->decls()) {
8988 if (D == F)
8989 return Index;
8990
8991 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D))
8992 ++Index;
8993 }
8994
8995 llvm_unreachable("Field was not found in its parent context.");
8996
8997 return std::nullopt;
8998}
8999
9001ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) {
9002 // We search in the redecl context because of transparent contexts.
9003 // E.g. a simple C language enum is a transparent context:
9004 // enum E { A, B };
9005 // Now if we had a global variable in the TU
9006 // int A;
9007 // then the enum constant 'A' and the variable 'A' violates ODR.
9008 // We can diagnose this only if we search in the redecl context.
9009 DeclContext *ReDC = DC->getRedeclContext();
9010 if (SharedState->getLookupTable()) {
9012 SharedState->getLookupTable()->lookup(ReDC, Name);
9013 return FoundDeclsTy(LookupResult.begin(), LookupResult.end());
9014 } else {
9015 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name);
9016 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end());
9017 // We must search by the slow case of localUncachedLookup because that is
9018 // working even if there is no LookupPtr for the DC. We could use
9019 // DC::buildLookup() to create the LookupPtr, but that would load external
9020 // decls again, we must avoid that case.
9021 // Also, even if we had the LookupPtr, we must find Decls which are not
9022 // in the LookupPtr, so we need the slow case.
9023 // These cases are handled in ASTImporterLookupTable, but we cannot use
9024 // that with LLDB since that traverses through the AST which initiates the
9025 // load of external decls again via DC::decls(). And again, we must avoid
9026 // loading external decls during the import.
9027 if (Result.empty())
9028 ReDC->localUncachedLookup(Name, Result);
9029 return Result;
9030 }
9031}
9032
9033void ASTImporter::AddToLookupTable(Decl *ToD) {
9034 SharedState->addDeclToLookup(ToD);
9035}
9036
9038 // Import the decl using ASTNodeImporter.
9039 ASTNodeImporter Importer(*this);
9040 return Importer.Visit(FromD);
9041}
9042
9044 MapImported(FromD, ToD);
9045}
9046
9049 if (auto *CLE = From.dyn_cast<CompoundLiteralExpr *>()) {
9050 if (Expected<Expr *> R = Import(CLE))
9051 return ExprWithCleanups::CleanupObject(cast<CompoundLiteralExpr>(*R));
9052 }
9053
9054 // FIXME: Handle BlockDecl when we implement importing BlockExpr in
9055 // ASTNodeImporter.
9056 return make_error<ASTImportError>(ASTImportError::UnsupportedConstruct);
9057}
9058
9060 if (!FromT)
9061 return FromT;
9062
9063 // Check whether we've already imported this type.
9064 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
9065 ImportedTypes.find(FromT);
9066 if (Pos != ImportedTypes.end())
9067 return Pos->second;
9068
9069 // Import the type.
9070 ASTNodeImporter Importer(*this);
9071 ExpectedType ToTOrErr = Importer.Visit(FromT);
9072 if (!ToTOrErr)
9073 return ToTOrErr.takeError();
9074
9075 // Record the imported type.
9076 ImportedTypes[FromT] = ToTOrErr->getTypePtr();
9077
9078 return ToTOrErr->getTypePtr();
9079}
9080
9082 if (FromT.isNull())
9083 return QualType{};
9084
9085 ExpectedTypePtr ToTyOrErr = Import(FromT.getTypePtr());
9086 if (!ToTyOrErr)
9087 return ToTyOrErr.takeError();
9088
9089 return ToContext.getQualifiedType(*ToTyOrErr, FromT.getLocalQualifiers());
9090}
9091
9093 if (!FromTSI)
9094 return FromTSI;
9095
9096 // FIXME: For now we just create a "trivial" type source info based
9097 // on the type and a single location. Implement a real version of this.
9098 ExpectedType TOrErr = Import(FromTSI->getType());
9099 if (!TOrErr)
9100 return TOrErr.takeError();
9101 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc());
9102 if (!BeginLocOrErr)
9103 return BeginLocOrErr.takeError();
9104
9105 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr);
9106}
9107
9108namespace {
9109// To use this object, it should be created before the new attribute is created,
9110// and destructed after it is created. The construction already performs the
9111// import of the data.
9112template <typename T> struct AttrArgImporter {
9113 AttrArgImporter(const AttrArgImporter<T> &) = delete;
9114 AttrArgImporter(AttrArgImporter<T> &&) = default;
9115 AttrArgImporter<T> &operator=(const AttrArgImporter<T> &) = delete;
9116 AttrArgImporter<T> &operator=(AttrArgImporter<T> &&) = default;
9117
9118 AttrArgImporter(ASTNodeImporter &I, Error &Err, const T &From)
9119 : To(I.importChecked(Err, From)) {}
9120
9121 const T &value() { return To; }
9122
9123private:
9124 T To;
9125};
9126
9127// To use this object, it should be created before the new attribute is created,
9128// and destructed after it is created. The construction already performs the
9129// import of the data. The array data is accessible in a pointer form, this form
9130// is used by the attribute classes. This object should be created once for the
9131// array data to be imported (the array size is not imported, just copied).
9132template <typename T> struct AttrArgArrayImporter {
9133 AttrArgArrayImporter(const AttrArgArrayImporter<T> &) = delete;
9134 AttrArgArrayImporter(AttrArgArrayImporter<T> &&) = default;
9135 AttrArgArrayImporter<T> &operator=(const AttrArgArrayImporter<T> &) = delete;
9136 AttrArgArrayImporter<T> &operator=(AttrArgArrayImporter<T> &&) = default;
9137
9138 AttrArgArrayImporter(ASTNodeImporter &I, Error &Err,
9139 const llvm::iterator_range<T *> &From,
9140 unsigned ArraySize) {
9141 if (Err)
9142 return;
9143 To.reserve(ArraySize);
9144 Err = I.ImportContainerChecked(From, To);
9145 }
9146
9147 T *value() { return To.data(); }
9148
9149private:
9151};
9152
9153class AttrImporter {
9154 Error Err{Error::success()};
9155 Attr *ToAttr = nullptr;
9156 ASTImporter &Importer;
9157 ASTNodeImporter NImporter;
9158
9159public:
9160 AttrImporter(ASTImporter &I) : Importer(I), NImporter(I) {}
9161
9162 // Useful for accessing the imported attribute.
9163 template <typename T> T *castAttrAs() { return cast<T>(ToAttr); }
9164 template <typename T> const T *castAttrAs() const { return cast<T>(ToAttr); }
9165
9166 // Create an "importer" for an attribute parameter.
9167 // Result of the 'value()' of that object is to be passed to the function
9168 // 'importAttr', in the order that is expected by the attribute class.
9169 template <class T> AttrArgImporter<T> importArg(const T &From) {
9170 return AttrArgImporter<T>(NImporter, Err, From);
9171 }
9172
9173 // Create an "importer" for an attribute parameter that has array type.
9174 // Result of the 'value()' of that object is to be passed to the function
9175 // 'importAttr', then the size of the array as next argument.
9176 template <typename T>
9177 AttrArgArrayImporter<T> importArrayArg(const llvm::iterator_range<T *> &From,
9178 unsigned ArraySize) {
9179 return AttrArgArrayImporter<T>(NImporter, Err, From, ArraySize);
9180 }
9181
9182 // Create an attribute object with the specified arguments.
9183 // The 'FromAttr' is the original (not imported) attribute, the 'ImportedArg'
9184 // should be values that are passed to the 'Create' function of the attribute.
9185 // (The 'Create' with 'ASTContext' first and 'AttributeCommonInfo' last is
9186 // used here.) As much data is copied or imported from the old attribute
9187 // as possible. The passed arguments should be already imported.
9188 // If an import error happens, the internal error is set to it, and any
9189 // further import attempt is ignored.
9190 template <typename T, typename... Arg>
9191 void importAttr(const T *FromAttr, Arg &&...ImportedArg) {
9192 static_assert(std::is_base_of<Attr, T>::value,
9193 "T should be subclass of Attr.");
9194 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9195
9196 const IdentifierInfo *ToAttrName = Importer.Import(FromAttr->getAttrName());
9197 const IdentifierInfo *ToScopeName =
9198 Importer.Import(FromAttr->getScopeName());
9199 SourceRange ToAttrRange =
9200 NImporter.importChecked(Err, FromAttr->getRange());
9201 SourceLocation ToScopeLoc =
9202 NImporter.importChecked(Err, FromAttr->getScopeLoc());
9203
9204 if (Err)
9205 return;
9206
9207 AttributeCommonInfo ToI(ToAttrName, ToScopeName, ToAttrRange, ToScopeLoc,
9208 FromAttr->getParsedKind(), FromAttr->getForm());
9209 // The "SemanticSpelling" is not needed to be passed to the constructor.
9210 // That value is recalculated from the SpellingListIndex if needed.
9211 ToAttr = T::Create(Importer.getToContext(),
9212 std::forward<Arg>(ImportedArg)..., ToI);
9213
9214 ToAttr->setImplicit(FromAttr->isImplicit());
9215 ToAttr->setPackExpansion(FromAttr->isPackExpansion());
9216 if (auto *ToInheritableAttr = dyn_cast<InheritableAttr>(ToAttr))
9217 ToInheritableAttr->setInherited(FromAttr->isInherited());
9218 }
9219
9220 // Create a clone of the 'FromAttr' and import its source range only.
9221 // This causes objects with invalid references to be created if the 'FromAttr'
9222 // contains other data that should be imported.
9223 void cloneAttr(const Attr *FromAttr) {
9224 assert(!ToAttr && "Use one AttrImporter to import one Attribute object.");
9225
9226 SourceRange ToRange = NImporter.importChecked(Err, FromAttr->getRange());
9227 if (Err)
9228 return;
9229
9230 ToAttr = FromAttr->clone(Importer.getToContext());
9231 ToAttr->setRange(ToRange);
9232 ToAttr->setAttrName(Importer.Import(FromAttr->getAttrName()));
9233 }
9234
9235 // Get the result of the previous import attempt (can be used only once).
9236 llvm::Expected<Attr *> getResult() && {
9237 if (Err)
9238 return std::move(Err);
9239 assert(ToAttr && "Attribute should be created.");
9240 return ToAttr;
9241 }
9242};
9243} // namespace
9244
9246 AttrImporter AI(*this);
9247
9248 // FIXME: Is there some kind of AttrVisitor to use here?
9249 switch (FromAttr->getKind()) {
9250 case attr::Aligned: {
9251 auto *From = cast<AlignedAttr>(FromAttr);
9252 if (From->isAlignmentExpr())
9253 AI.importAttr(From, true, AI.importArg(From->getAlignmentExpr()).value());
9254 else
9255 AI.importAttr(From, false,
9256 AI.importArg(From->getAlignmentType()).value());
9257 break;
9258 }
9259
9260 case attr::AlignValue: {
9261 auto *From = cast<AlignValueAttr>(FromAttr);
9262 AI.importAttr(From, AI.importArg(From->getAlignment()).value());
9263 break;
9264 }
9265
9266 case attr::Format: {
9267 const auto *From = cast<FormatAttr>(FromAttr);
9268 AI.importAttr(From, Import(From->getType()), From->getFormatIdx(),
9269 From->getFirstArg());
9270 break;
9271 }
9272
9273 case attr::EnableIf: {
9274 const auto *From = cast<EnableIfAttr>(FromAttr);
9275 AI.importAttr(From, AI.importArg(From->getCond()).value(),
9276 From->getMessage());
9277 break;
9278 }
9279
9280 case attr::AssertCapability: {
9281 const auto *From = cast<AssertCapabilityAttr>(FromAttr);
9282 AI.importAttr(From,
9283 AI.importArrayArg(From->args(), From->args_size()).value(),
9284 From->args_size());
9285 break;
9286 }
9287 case attr::AcquireCapability: {
9288 const auto *From = cast<AcquireCapabilityAttr>(FromAttr);
9289 AI.importAttr(From,
9290 AI.importArrayArg(From->args(), From->args_size()).value(),
9291 From->args_size());
9292 break;
9293 }
9294 case attr::TryAcquireCapability: {
9295 const auto *From = cast<TryAcquireCapabilityAttr>(FromAttr);
9296 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9297 AI.importArrayArg(From->args(), From->args_size()).value(),
9298 From->args_size());
9299 break;
9300 }
9301 case attr::ReleaseCapability: {
9302 const auto *From = cast<ReleaseCapabilityAttr>(FromAttr);
9303 AI.importAttr(From,
9304 AI.importArrayArg(From->args(), From->args_size()).value(),
9305 From->args_size());
9306 break;
9307 }
9308 case attr::RequiresCapability: {
9309 const auto *From = cast<RequiresCapabilityAttr>(FromAttr);
9310 AI.importAttr(From,
9311 AI.importArrayArg(From->args(), From->args_size()).value(),
9312 From->args_size());
9313 break;
9314 }
9315 case attr::GuardedBy: {
9316 const auto *From = cast<GuardedByAttr>(FromAttr);
9317 AI.importAttr(From, AI.importArg(From->getArg()).value());
9318 break;
9319 }
9320 case attr::PtGuardedBy: {
9321 const auto *From = cast<PtGuardedByAttr>(FromAttr);
9322 AI.importAttr(From, AI.importArg(From->getArg()).value());
9323 break;
9324 }
9325 case attr::AcquiredAfter: {
9326 const auto *From = cast<AcquiredAfterAttr>(FromAttr);
9327 AI.importAttr(From,
9328 AI.importArrayArg(From->args(), From->args_size()).value(),
9329 From->args_size());
9330 break;
9331 }
9332 case attr::AcquiredBefore: {
9333 const auto *From = cast<AcquiredBeforeAttr>(FromAttr);
9334 AI.importAttr(From,
9335 AI.importArrayArg(From->args(), From->args_size()).value(),
9336 From->args_size());
9337 break;
9338 }
9339 case attr::AssertExclusiveLock: {
9340 const auto *From = cast<AssertExclusiveLockAttr>(FromAttr);
9341 AI.importAttr(From,
9342 AI.importArrayArg(From->args(), From->args_size()).value(),
9343 From->args_size());
9344 break;
9345 }
9346 case attr::AssertSharedLock: {
9347 const auto *From = cast<AssertSharedLockAttr>(FromAttr);
9348 AI.importAttr(From,
9349 AI.importArrayArg(From->args(), From->args_size()).value(),
9350 From->args_size());
9351 break;
9352 }
9353 case attr::ExclusiveTrylockFunction: {
9354 const auto *From = cast<ExclusiveTrylockFunctionAttr>(FromAttr);
9355 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9356 AI.importArrayArg(From->args(), From->args_size()).value(),
9357 From->args_size());
9358 break;
9359 }
9360 case attr::SharedTrylockFunction: {
9361 const auto *From = cast<SharedTrylockFunctionAttr>(FromAttr);
9362 AI.importAttr(From, AI.importArg(From->getSuccessValue()).value(),
9363 AI.importArrayArg(From->args(), From->args_size()).value(),
9364 From->args_size());
9365 break;
9366 }
9367 case attr::LockReturned: {
9368 const auto *From = cast<LockReturnedAttr>(FromAttr);
9369 AI.importAttr(From, AI.importArg(From->getArg()).value());
9370 break;
9371 }
9372 case attr::LocksExcluded: {
9373 const auto *From = cast<LocksExcludedAttr>(FromAttr);
9374 AI.importAttr(From,
9375 AI.importArrayArg(From->args(), From->args_size()).value(),
9376 From->args_size());
9377 break;
9378 }
9379 default: {
9380 // The default branch works for attributes that have no arguments to import.
9381 // FIXME: Handle every attribute type that has arguments of type to import
9382 // (most often Expr* or Decl* or type) in the switch above.
9383 AI.cloneAttr(FromAttr);
9384 break;
9385 }
9386 }
9387
9388 return std::move(AI).getResult();
9389}
9390
9392 return ImportedDecls.lookup(FromD);
9393}
9394
9396 auto FromDPos = ImportedFromDecls.find(ToD);
9397 if (FromDPos == ImportedFromDecls.end())
9398 return nullptr;
9399 return FromDPos->second->getTranslationUnitDecl();
9400}
9401
9402Error ASTImporter::ImportAttrs(Decl *ToD, Decl *FromD) {
9403 if (!FromD->hasAttrs() || ToD->hasAttrs())
9404 return Error::success();
9405 for (const Attr *FromAttr : FromD->getAttrs()) {
9406 auto ToAttrOrErr = Import(FromAttr);
9407 if (ToAttrOrErr)
9408 ToD->addAttr(*ToAttrOrErr);
9409 else
9410 return ToAttrOrErr.takeError();
9411 }
9412 return Error::success();
9413}
9414
9416 if (!FromD)
9417 return nullptr;
9418
9419 // Push FromD to the stack, and remove that when we return.
9420 ImportPath.push(FromD);
9421 auto ImportPathBuilder =
9422 llvm::make_scope_exit([this]() { ImportPath.pop(); });
9423
9424 // Check whether there was a previous failed import.
9425 // If yes return the existing error.
9426 if (auto Error = getImportDeclErrorIfAny(FromD))
9427 return make_error<ASTImportError>(*Error);
9428
9429 // Check whether we've already imported this declaration.
9430 Decl *ToD = GetAlreadyImportedOrNull(FromD);
9431 if (ToD) {
9432 // Already imported (possibly from another TU) and with an error.
9433 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9434 setImportDeclError(FromD, *Error);
9435 return make_error<ASTImportError>(*Error);
9436 }
9437
9438 // If FromD has some updated flags after last import, apply it.
9439 updateFlags(FromD, ToD);
9440 // If we encounter a cycle during an import then we save the relevant part
9441 // of the import path associated to the Decl.
9442 if (ImportPath.hasCycleAtBack())
9443 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack());
9444 return ToD;
9445 }
9446
9447 // Import the declaration.
9448 ExpectedDecl ToDOrErr = ImportImpl(FromD);
9449 if (!ToDOrErr) {
9450 // Failed to import.
9451
9452 auto Pos = ImportedDecls.find(FromD);
9453 if (Pos != ImportedDecls.end()) {
9454 // Import failed after the object was created.
9455 // Remove all references to it.
9456 auto *ToD = Pos->second;
9457 ImportedDecls.erase(Pos);
9458
9459 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen
9460 // (e.g. with namespaces) that several decls from the 'from' context are
9461 // mapped to the same decl in the 'to' context. If we removed entries
9462 // from the LookupTable here then we may end up removing them multiple
9463 // times.
9464
9465 // The Lookuptable contains decls only which are in the 'to' context.
9466 // Remove from the Lookuptable only if it is *imported* into the 'to'
9467 // context (and do not remove it if it was added during the initial
9468 // traverse of the 'to' context).
9469 auto PosF = ImportedFromDecls.find(ToD);
9470 if (PosF != ImportedFromDecls.end()) {
9471 // In the case of TypedefNameDecl we create the Decl first and only
9472 // then we import and set its DeclContext. So, the DC might not be set
9473 // when we reach here.
9474 if (ToD->getDeclContext())
9475 SharedState->removeDeclFromLookup(ToD);
9476 ImportedFromDecls.erase(PosF);
9477 }
9478
9479 // FIXME: AST may contain remaining references to the failed object.
9480 // However, the ImportDeclErrors in the shared state contains all the
9481 // failed objects together with their error.
9482 }
9483
9484 // Error encountered for the first time.
9485 // After takeError the error is not usable any more in ToDOrErr.
9486 // Get a copy of the error object (any more simple solution for this?).
9487 ASTImportError ErrOut;
9488 handleAllErrors(ToDOrErr.takeError(),
9489 [&ErrOut](const ASTImportError &E) { ErrOut = E; });
9490 setImportDeclError(FromD, ErrOut);
9491 // Set the error for the mapped to Decl, which is in the "to" context.
9492 if (Pos != ImportedDecls.end())
9493 SharedState->setImportDeclError(Pos->second, ErrOut);
9494
9495 // Set the error for all nodes which have been created before we
9496 // recognized the error.
9497 for (const auto &Path : SavedImportPaths[FromD]) {
9498 // The import path contains import-dependency nodes first.
9499 // Save the node that was imported as dependency of the current node.
9500 Decl *PrevFromDi = FromD;
9501 for (Decl *FromDi : Path) {
9502 // Begin and end of the path equals 'FromD', skip it.
9503 if (FromDi == FromD)
9504 continue;
9505 // We should not set import error on a node and all following nodes in
9506 // the path if child import errors are ignored.
9507 if (ChildErrorHandlingStrategy(FromDi).ignoreChildErrorOnParent(
9508 PrevFromDi))
9509 break;
9510 PrevFromDi = FromDi;
9511 setImportDeclError(FromDi, ErrOut);
9512 //FIXME Should we remove these Decls from ImportedDecls?
9513 // Set the error for the mapped to Decl, which is in the "to" context.
9514 auto Ii = ImportedDecls.find(FromDi);
9515 if (Ii != ImportedDecls.end())
9516 SharedState->setImportDeclError(Ii->second, ErrOut);
9517 // FIXME Should we remove these Decls from the LookupTable,
9518 // and from ImportedFromDecls?
9519 }
9520 }
9521 SavedImportPaths.erase(FromD);
9522
9523 // Do not return ToDOrErr, error was taken out of it.
9524 return make_error<ASTImportError>(ErrOut);
9525 }
9526
9527 ToD = *ToDOrErr;
9528
9529 // FIXME: Handle the "already imported with error" case. We can get here
9530 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a
9531 // previously failed create was requested).
9532 // Later GetImportedOrCreateDecl can be updated to return the error.
9533 if (!ToD) {
9534 auto Err = getImportDeclErrorIfAny(FromD);
9535 assert(Err);
9536 return make_error<ASTImportError>(*Err);
9537 }
9538
9539 // We could import from the current TU without error. But previously we
9540 // already had imported a Decl as `ToD` from another TU (with another
9541 // ASTImporter object) and with an error.
9542 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) {
9543 setImportDeclError(FromD, *Error);
9544 return make_error<ASTImportError>(*Error);
9545 }
9546 // Make sure that ImportImpl registered the imported decl.
9547 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?");
9548 if (auto Error = ImportAttrs(ToD, FromD))
9549 return std::move(Error);
9550
9551 // Notify subclasses.
9552 Imported(FromD, ToD);
9553
9554 updateFlags(FromD, ToD);
9555 SavedImportPaths.erase(FromD);
9556 return ToDOrErr;
9557}
9558
9561 return ASTNodeImporter(*this).ImportInheritedConstructor(From);
9562}
9563
9565 if (!FromDC)
9566 return FromDC;
9567
9568 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC));
9569 if (!ToDCOrErr)
9570 return ToDCOrErr.takeError();
9571 auto *ToDC = cast<DeclContext>(*ToDCOrErr);
9572
9573 // When we're using a record/enum/Objective-C class/protocol as a context, we
9574 // need it to have a definition.
9575 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) {
9576 auto *FromRecord = cast<RecordDecl>(FromDC);
9577 if (ToRecord->isCompleteDefinition())
9578 return ToDC;
9579
9580 // If FromRecord is not defined we need to force it to be.
9581 // Simply calling CompleteDecl(...) for a RecordDecl will break some cases
9582 // it will start the definition but we never finish it.
9583 // If there are base classes they won't be imported and we will
9584 // be missing anything that we inherit from those bases.
9585 if (FromRecord->getASTContext().getExternalSource() &&
9586 !FromRecord->isCompleteDefinition())
9587 FromRecord->getASTContext().getExternalSource()->CompleteType(FromRecord);
9588
9589 if (FromRecord->isCompleteDefinition())
9590 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9591 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic))
9592 return std::move(Err);
9593 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) {
9594 auto *FromEnum = cast<EnumDecl>(FromDC);
9595 if (ToEnum->isCompleteDefinition()) {
9596 // Do nothing.
9597 } else if (FromEnum->isCompleteDefinition()) {
9598 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9599 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic))
9600 return std::move(Err);
9601 } else {
9602 CompleteDecl(ToEnum);
9603 }
9604 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) {
9605 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC);
9606 if (ToClass->getDefinition()) {
9607 // Do nothing.
9608 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) {
9609 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9610 FromDef, ToClass, ASTNodeImporter::IDK_Basic))
9611 return std::move(Err);
9612 } else {
9613 CompleteDecl(ToClass);
9614 }
9615 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) {
9616 auto *FromProto = cast<ObjCProtocolDecl>(FromDC);
9617 if (ToProto->getDefinition()) {
9618 // Do nothing.
9619 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) {
9620 if (Error Err = ASTNodeImporter(*this).ImportDefinition(
9621 FromDef, ToProto, ASTNodeImporter::IDK_Basic))
9622 return std::move(Err);
9623 } else {
9624 CompleteDecl(ToProto);
9625 }
9626 }
9627
9628 return ToDC;
9629}
9630
9632 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE)))
9633 return cast_or_null<Expr>(*ToSOrErr);
9634 else
9635 return ToSOrErr.takeError();
9636}
9637
9639 if (!FromS)
9640 return nullptr;
9641
9642 // Check whether we've already imported this statement.
9643 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS);
9644 if (Pos != ImportedStmts.end())
9645 return Pos->second;
9646
9647 // Import the statement.
9648 ASTNodeImporter Importer(*this);
9649 ExpectedStmt ToSOrErr = Importer.Visit(FromS);
9650 if (!ToSOrErr)
9651 return ToSOrErr;
9652
9653 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) {
9654 auto *FromE = cast<Expr>(FromS);
9655 // Copy ExprBitfields, which may not be handled in Expr subclasses
9656 // constructors.
9657 ToE->setValueKind(FromE->getValueKind());
9658 ToE->setObjectKind(FromE->getObjectKind());
9659 ToE->setDependence(FromE->getDependence());
9660 }
9661
9662 // Record the imported statement object.
9663 ImportedStmts[FromS] = *ToSOrErr;
9664 return ToSOrErr;
9665}
9666
9669 if (!FromNNS)
9670 return nullptr;
9671
9672 NestedNameSpecifier *Prefix = nullptr;
9673 if (Error Err = importInto(Prefix, FromNNS->getPrefix()))
9674 return std::move(Err);
9675
9676 switch (FromNNS->getKind()) {
9678 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier.");
9679 return NestedNameSpecifier::Create(ToContext, Prefix,
9680 Import(FromNNS->getAsIdentifier()));
9681
9683 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) {
9684 return NestedNameSpecifier::Create(ToContext, Prefix,
9685 cast<NamespaceDecl>(*NSOrErr));
9686 } else
9687 return NSOrErr.takeError();
9688
9690 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias()))
9691 return NestedNameSpecifier::Create(ToContext, Prefix,
9692 cast<NamespaceAliasDecl>(*NSADOrErr));
9693 else
9694 return NSADOrErr.takeError();
9695
9697 return NestedNameSpecifier::GlobalSpecifier(ToContext);
9698
9700 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl()))
9701 return NestedNameSpecifier::SuperSpecifier(ToContext,
9702 cast<CXXRecordDecl>(*RDOrErr));
9703 else
9704 return RDOrErr.takeError();
9705
9708 if (ExpectedTypePtr TyOrErr = Import(FromNNS->getAsType())) {
9709 bool TSTemplate =
9711 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate,
9712 *TyOrErr);
9713 } else {
9714 return TyOrErr.takeError();
9715 }
9716 }
9717
9718 llvm_unreachable("Invalid nested name specifier kind");
9719}
9720
9723 // Copied from NestedNameSpecifier mostly.
9725 NestedNameSpecifierLoc NNS = FromNNS;
9726
9727 // Push each of the nested-name-specifiers's onto a stack for
9728 // serialization in reverse order.
9729 while (NNS) {
9730 NestedNames.push_back(NNS);
9731 NNS = NNS.getPrefix();
9732 }
9733
9735
9736 while (!NestedNames.empty()) {
9737 NNS = NestedNames.pop_back_val();
9738 NestedNameSpecifier *Spec = nullptr;
9739 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier()))
9740 return std::move(Err);
9741
9743
9744 SourceLocation ToLocalBeginLoc, ToLocalEndLoc;
9745 if (Kind != NestedNameSpecifier::Super) {
9746 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc()))
9747 return std::move(Err);
9748
9749 if (Kind != NestedNameSpecifier::Global)
9750 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc()))
9751 return std::move(Err);
9752 }
9753
9754 switch (Kind) {
9756 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc,
9757 ToLocalEndLoc);
9758 break;
9759
9761 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc,
9762 ToLocalEndLoc);
9763 break;
9764
9766 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(),
9767 ToLocalBeginLoc, ToLocalEndLoc);
9768 break;
9769
9772 SourceLocation ToTLoc;
9773 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc()))
9774 return std::move(Err);
9776 QualType(Spec->getAsType(), 0), ToTLoc);
9778 // ToLocalBeginLoc is here the location of the 'template' keyword.
9779 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(),
9780 ToLocalEndLoc);
9781 else
9782 // No location for 'template' keyword here.
9783 Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(),
9784 ToLocalEndLoc);
9785 break;
9786 }
9787
9789 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc);
9790 break;
9791
9793 auto ToSourceRangeOrErr = Import(NNS.getSourceRange());
9794 if (!ToSourceRangeOrErr)
9795 return ToSourceRangeOrErr.takeError();
9796
9797 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(),
9798 ToSourceRangeOrErr->getBegin(),
9799 ToSourceRangeOrErr->getEnd());
9800 }
9801 }
9802 }
9803
9804 return Builder.getWithLocInContext(getToContext());
9805}
9806
9808 switch (From.getKind()) {
9810 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl()))
9811 return TemplateName(cast<TemplateDecl>((*ToTemplateOrErr)->getCanonicalDecl()));
9812 else
9813 return ToTemplateOrErr.takeError();
9814
9817 UnresolvedSet<2> ToTemplates;
9818 for (auto *I : *FromStorage) {
9819 if (auto ToOrErr = Import(I))
9820 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr));
9821 else
9822 return ToOrErr.takeError();
9823 }
9824 return ToContext.getOverloadedTemplateName(ToTemplates.begin(),
9825 ToTemplates.end());
9826 }
9827
9830 auto DeclNameOrErr = Import(FromStorage->getDeclName());
9831 if (!DeclNameOrErr)
9832 return DeclNameOrErr.takeError();
9833 return ToContext.getAssumedTemplateName(*DeclNameOrErr);
9834 }
9835
9838 auto QualifierOrErr = Import(QTN->getQualifier());
9839 if (!QualifierOrErr)
9840 return QualifierOrErr.takeError();
9841 auto TNOrErr = Import(QTN->getUnderlyingTemplate());
9842 if (!TNOrErr)
9843 return TNOrErr.takeError();
9844 return ToContext.getQualifiedTemplateName(
9845 *QualifierOrErr, QTN->hasTemplateKeyword(), *TNOrErr);
9846 }
9847
9850 auto QualifierOrErr = Import(DTN->getQualifier());
9851 if (!QualifierOrErr)
9852 return QualifierOrErr.takeError();
9853
9854 if (DTN->isIdentifier()) {
9855 return ToContext.getDependentTemplateName(*QualifierOrErr,
9856 Import(DTN->getIdentifier()));
9857 }
9858
9859 return ToContext.getDependentTemplateName(*QualifierOrErr,
9860 DTN->getOperator());
9861 }
9862
9866 auto ReplacementOrErr = Import(Subst->getReplacement());
9867 if (!ReplacementOrErr)
9868 return ReplacementOrErr.takeError();
9869
9870 auto AssociatedDeclOrErr = Import(Subst->getAssociatedDecl());
9871 if (!AssociatedDeclOrErr)
9872 return AssociatedDeclOrErr.takeError();
9873
9874 return ToContext.getSubstTemplateTemplateParm(
9875 *ReplacementOrErr, *AssociatedDeclOrErr, Subst->getIndex(),
9876 Subst->getPackIndex());
9877 }
9878
9882 ASTNodeImporter Importer(*this);
9883 auto ArgPackOrErr =
9884 Importer.ImportTemplateArgument(SubstPack->getArgumentPack());
9885 if (!ArgPackOrErr)
9886 return ArgPackOrErr.takeError();
9887
9888 auto AssociatedDeclOrErr = Import(SubstPack->getAssociatedDecl());
9889 if (!AssociatedDeclOrErr)
9890 return AssociatedDeclOrErr.takeError();
9891
9892 return ToContext.getSubstTemplateTemplateParmPack(
9893 *ArgPackOrErr, *AssociatedDeclOrErr, SubstPack->getIndex(),
9894 SubstPack->getFinal());
9895 }
9897 auto UsingOrError = Import(From.getAsUsingShadowDecl());
9898 if (!UsingOrError)
9899 return UsingOrError.takeError();
9900 return TemplateName(cast<UsingShadowDecl>(*UsingOrError));
9901 }
9902 }
9903
9904 llvm_unreachable("Invalid template name kind");
9905}
9906
9908 if (FromLoc.isInvalid())
9909 return SourceLocation{};
9910
9911 SourceManager &FromSM = FromContext.getSourceManager();
9912 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc);
9913
9914 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc);
9915 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin);
9916 if (!ToFileIDOrErr)
9917 return ToFileIDOrErr.takeError();
9918 SourceManager &ToSM = ToContext.getSourceManager();
9919 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second);
9920}
9921
9923 SourceLocation ToBegin, ToEnd;
9924 if (Error Err = importInto(ToBegin, FromRange.getBegin()))
9925 return std::move(Err);
9926 if (Error Err = importInto(ToEnd, FromRange.getEnd()))
9927 return std::move(Err);
9928
9929 return SourceRange(ToBegin, ToEnd);
9930}
9931
9933 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID);
9934 if (Pos != ImportedFileIDs.end())
9935 return Pos->second;
9936
9937 SourceManager &FromSM = FromContext.getSourceManager();
9938 SourceManager &ToSM = ToContext.getSourceManager();
9939 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID);
9940
9941 // Map the FromID to the "to" source manager.
9942 FileID ToID;
9943 if (FromSLoc.isExpansion()) {
9944 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion();
9945 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc());
9946 if (!ToSpLoc)
9947 return ToSpLoc.takeError();
9948 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart());
9949 if (!ToExLocS)
9950 return ToExLocS.takeError();
9951 unsigned ExLength = FromSM.getFileIDSize(FromID);
9952 SourceLocation MLoc;
9953 if (FromEx.isMacroArgExpansion()) {
9954 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, ExLength);
9955 } else {
9956 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd()))
9957 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, ExLength,
9958 FromEx.isExpansionTokenRange());
9959 else
9960 return ToExLocE.takeError();
9961 }
9962 ToID = ToSM.getFileID(MLoc);
9963 } else {
9964 const SrcMgr::ContentCache *Cache = &FromSLoc.getFile().getContentCache();
9965
9966 if (!IsBuiltin && !Cache->BufferOverridden) {
9967 // Include location of this file.
9968 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc());
9969 if (!ToIncludeLoc)
9970 return ToIncludeLoc.takeError();
9971
9972 // Every FileID that is not the main FileID needs to have a valid include
9973 // location so that the include chain points to the main FileID. When
9974 // importing the main FileID (which has no include location), we need to
9975 // create a fake include location in the main file to keep this property
9976 // intact.
9977 SourceLocation ToIncludeLocOrFakeLoc = *ToIncludeLoc;
9978 if (FromID == FromSM.getMainFileID())
9979 ToIncludeLocOrFakeLoc = ToSM.getLocForStartOfFile(ToSM.getMainFileID());
9980
9981 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) {
9982 // FIXME: We probably want to use getVirtualFile(), so we don't hit the
9983 // disk again
9984 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather
9985 // than mmap the files several times.
9986 auto Entry =
9987 ToFileManager.getOptionalFileRef(Cache->OrigEntry->getName());
9988 // FIXME: The filename may be a virtual name that does probably not
9989 // point to a valid file and we get no Entry here. In this case try with
9990 // the memory buffer below.
9991 if (Entry)
9992 ToID = ToSM.createFileID(*Entry, ToIncludeLocOrFakeLoc,
9993 FromSLoc.getFile().getFileCharacteristic());
9994 }
9995 }
9996
9997 if (ToID.isInvalid() || IsBuiltin) {
9998 // FIXME: We want to re-use the existing MemoryBuffer!
9999 std::optional<llvm::MemoryBufferRef> FromBuf =
10000 Cache->getBufferOrNone(FromContext.getDiagnostics(),
10001 FromSM.getFileManager(), SourceLocation{});
10002 if (!FromBuf)
10003 return llvm::make_error<ASTImportError>(ASTImportError::Unknown);
10004
10005 std::unique_ptr<llvm::MemoryBuffer> ToBuf =
10006 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(),
10007 FromBuf->getBufferIdentifier());
10008 ToID = ToSM.createFileID(std::move(ToBuf),
10009 FromSLoc.getFile().getFileCharacteristic());
10010 }
10011 }
10012
10013 assert(ToID.isValid() && "Unexpected invalid fileID was created.");
10014
10015 ImportedFileIDs[FromID] = ToID;
10016 return ToID;
10017}
10018
10020 ExpectedExpr ToExprOrErr = Import(From->getInit());
10021 if (!ToExprOrErr)
10022 return ToExprOrErr.takeError();
10023
10024 auto LParenLocOrErr = Import(From->getLParenLoc());
10025 if (!LParenLocOrErr)
10026 return LParenLocOrErr.takeError();
10027
10028 auto RParenLocOrErr = Import(From->getRParenLoc());
10029 if (!RParenLocOrErr)
10030 return RParenLocOrErr.takeError();
10031
10032 if (From->isBaseInitializer()) {
10033 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
10034 if (!ToTInfoOrErr)
10035 return ToTInfoOrErr.takeError();
10036
10037 SourceLocation EllipsisLoc;
10038 if (From->isPackExpansion())
10039 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc()))
10040 return std::move(Err);
10041
10042 return new (ToContext) CXXCtorInitializer(
10043 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr,
10044 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc);
10045 } else if (From->isMemberInitializer()) {
10046 ExpectedDecl ToFieldOrErr = Import(From->getMember());
10047 if (!ToFieldOrErr)
10048 return ToFieldOrErr.takeError();
10049
10050 auto MemberLocOrErr = Import(From->getMemberLocation());
10051 if (!MemberLocOrErr)
10052 return MemberLocOrErr.takeError();
10053
10054 return new (ToContext) CXXCtorInitializer(
10055 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr,
10056 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10057 } else if (From->isIndirectMemberInitializer()) {
10058 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember());
10059 if (!ToIFieldOrErr)
10060 return ToIFieldOrErr.takeError();
10061
10062 auto MemberLocOrErr = Import(From->getMemberLocation());
10063 if (!MemberLocOrErr)
10064 return MemberLocOrErr.takeError();
10065
10066 return new (ToContext) CXXCtorInitializer(
10067 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr),
10068 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr);
10069 } else if (From->isDelegatingInitializer()) {
10070 auto ToTInfoOrErr = Import(From->getTypeSourceInfo());
10071 if (!ToTInfoOrErr)
10072 return ToTInfoOrErr.takeError();
10073
10074 return new (ToContext)
10075 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr,
10076 *ToExprOrErr, *RParenLocOrErr);
10077 } else {
10078 // FIXME: assert?
10079 return make_error<ASTImportError>();
10080 }
10081}
10082
10085 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec);
10086 if (Pos != ImportedCXXBaseSpecifiers.end())
10087 return Pos->second;
10088
10089 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange());
10090 if (!ToSourceRange)
10091 return ToSourceRange.takeError();
10093 if (!ToTSI)
10094 return ToTSI.takeError();
10095 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc());
10096 if (!ToEllipsisLoc)
10097 return ToEllipsisLoc.takeError();
10098 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier(
10099 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(),
10100 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc);
10101 ImportedCXXBaseSpecifiers[BaseSpec] = Imported;
10102 return Imported;
10103}
10104
10106 ASTNodeImporter Importer(*this);
10107 return Importer.ImportAPValue(FromValue);
10108}
10109
10111 ExpectedDecl ToOrErr = Import(From);
10112 if (!ToOrErr)
10113 return ToOrErr.takeError();
10114 Decl *To = *ToOrErr;
10115
10116 auto *FromDC = cast<DeclContext>(From);
10117 ASTNodeImporter Importer(*this);
10118
10119 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) {
10120 if (!ToRecord->getDefinition()) {
10121 return Importer.ImportDefinition(
10122 cast<RecordDecl>(FromDC), ToRecord,
10124 }
10125 }
10126
10127 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) {
10128 if (!ToEnum->getDefinition()) {
10129 return Importer.ImportDefinition(
10130 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything);
10131 }
10132 }
10133
10134 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) {
10135 if (!ToIFace->getDefinition()) {
10136 return Importer.ImportDefinition(
10137 cast<ObjCInterfaceDecl>(FromDC), ToIFace,
10139 }
10140 }
10141
10142 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) {
10143 if (!ToProto->getDefinition()) {
10144 return Importer.ImportDefinition(
10145 cast<ObjCProtocolDecl>(FromDC), ToProto,
10147 }
10148 }
10149
10150 return Importer.ImportDeclContext(FromDC, true);
10151}
10152
10154 if (!FromName)
10155 return DeclarationName{};
10156
10157 switch (FromName.getNameKind()) {
10159 return DeclarationName(Import(FromName.getAsIdentifierInfo()));
10160
10164 if (auto ToSelOrErr = Import(FromName.getObjCSelector()))
10165 return DeclarationName(*ToSelOrErr);
10166 else
10167 return ToSelOrErr.takeError();
10168
10170 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10171 return ToContext.DeclarationNames.getCXXConstructorName(
10172 ToContext.getCanonicalType(*ToTyOrErr));
10173 else
10174 return ToTyOrErr.takeError();
10175 }
10176
10178 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10179 return ToContext.DeclarationNames.getCXXDestructorName(
10180 ToContext.getCanonicalType(*ToTyOrErr));
10181 else
10182 return ToTyOrErr.takeError();
10183 }
10184
10186 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate()))
10188 cast<TemplateDecl>(*ToTemplateOrErr));
10189 else
10190 return ToTemplateOrErr.takeError();
10191 }
10192
10194 if (auto ToTyOrErr = Import(FromName.getCXXNameType()))
10196 ToContext.getCanonicalType(*ToTyOrErr));
10197 else
10198 return ToTyOrErr.takeError();
10199 }
10200
10202 return ToContext.DeclarationNames.getCXXOperatorName(
10203 FromName.getCXXOverloadedOperator());
10204
10207 Import(FromName.getCXXLiteralIdentifier()));
10208
10210 // FIXME: STATICS!
10212 }
10213
10214 llvm_unreachable("Invalid DeclarationName Kind!");
10215}
10216
10218 if (!FromId)
10219 return nullptr;
10220
10221 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName());
10222
10223 if (!ToId->getBuiltinID() && FromId->getBuiltinID())
10224 ToId->setBuiltinID(FromId->getBuiltinID());
10225
10226 return ToId;
10227}
10228
10230 if (FromSel.isNull())
10231 return Selector{};
10232
10234 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0)));
10235 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I)
10236 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I)));
10237 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data());
10238}
10239
10243 llvm::Error Err = llvm::Error::success();
10244 auto ImportLoop = [&](const APValue *From, APValue *To, unsigned Size) {
10245 for (unsigned Idx = 0; Idx < Size; Idx++) {
10246 APValue Tmp = importChecked(Err, From[Idx]);
10247 To[Idx] = Tmp;
10248 }
10249 };
10250 switch (FromValue.getKind()) {
10251 case APValue::None:
10253 case APValue::Int:
10254 case APValue::Float:
10258 Result = FromValue;
10259 break;
10260 case APValue::Vector: {
10261 Result.MakeVector();
10263 Result.setVectorUninit(FromValue.getVectorLength());
10264 ImportLoop(((const APValue::Vec *)(const char *)&FromValue.Data)->Elts,
10265 Elts.data(), FromValue.getVectorLength());
10266 break;
10267 }
10268 case APValue::Array:
10269 Result.MakeArray(FromValue.getArrayInitializedElts(),
10270 FromValue.getArraySize());
10271 ImportLoop(((const APValue::Arr *)(const char *)&FromValue.Data)->Elts,
10272 ((const APValue::Arr *)(const char *)&Result.Data)->Elts,
10273 FromValue.getArrayInitializedElts());
10274 break;
10275 case APValue::Struct:
10276 Result.MakeStruct(FromValue.getStructNumBases(),
10277 FromValue.getStructNumFields());
10278 ImportLoop(
10279 ((const APValue::StructData *)(const char *)&FromValue.Data)->Elts,
10280 ((const APValue::StructData *)(const char *)&Result.Data)->Elts,
10281 FromValue.getStructNumBases() + FromValue.getStructNumFields());
10282 break;
10283 case APValue::Union: {
10284 Result.MakeUnion();
10285 const Decl *ImpFDecl = importChecked(Err, FromValue.getUnionField());
10286 APValue ImpValue = importChecked(Err, FromValue.getUnionValue());
10287 if (Err)
10288 return std::move(Err);
10289 Result.setUnion(cast<FieldDecl>(ImpFDecl), ImpValue);
10290 break;
10291 }
10293 Result.MakeAddrLabelDiff();
10294 const Expr *ImpLHS = importChecked(Err, FromValue.getAddrLabelDiffLHS());
10295 const Expr *ImpRHS = importChecked(Err, FromValue.getAddrLabelDiffRHS());
10296 if (Err)
10297 return std::move(Err);
10298 Result.setAddrLabelDiff(cast<AddrLabelExpr>(ImpLHS),
10299 cast<AddrLabelExpr>(ImpRHS));
10300 break;
10301 }
10303 const Decl *ImpMemPtrDecl =
10304 importChecked(Err, FromValue.getMemberPointerDecl());
10305 if (Err)
10306 return std::move(Err);
10308 Result.setMemberPointerUninit(
10309 cast<const ValueDecl>(ImpMemPtrDecl),
10311 FromValue.getMemberPointerPath().size());
10313 Result.getMemberPointerPath();
10314 for (unsigned Idx = 0; Idx < FromValue.getMemberPointerPath().size();
10315 Idx++) {
10316 const Decl *ImpDecl = importChecked(Err, FromPath[Idx]);
10317 if (Err)
10318 return std::move(Err);
10319 ToPath[Idx] = cast<const CXXRecordDecl>(ImpDecl->getCanonicalDecl());
10320 }
10321 break;
10322 }
10323 case APValue::LValue:
10325 QualType FromElemTy;
10326 if (FromValue.getLValueBase()) {
10327 assert(!FromValue.getLValueBase().is<DynamicAllocLValue>() &&
10328 "in C++20 dynamic allocation are transient so they shouldn't "
10329 "appear in the AST");
10330 if (!FromValue.getLValueBase().is<TypeInfoLValue>()) {
10331 if (const auto *E =
10332 FromValue.getLValueBase().dyn_cast<const Expr *>()) {
10333 FromElemTy = E->getType();
10334 const Expr *ImpExpr = importChecked(Err, E);
10335 if (Err)
10336 return std::move(Err);
10337 Base = APValue::LValueBase(ImpExpr,
10338 FromValue.getLValueBase().getCallIndex(),
10339 FromValue.getLValueBase().getVersion());
10340 } else {
10341 FromElemTy =
10342 FromValue.getLValueBase().get<const ValueDecl *>()->getType();
10343 const Decl *ImpDecl = importChecked(
10344 Err, FromValue.getLValueBase().get<const ValueDecl *>());
10345 if (Err)
10346 return std::move(Err);
10347 Base = APValue::LValueBase(cast<ValueDecl>(ImpDecl),
10348 FromValue.getLValueBase().getCallIndex(),
10349 FromValue.getLValueBase().getVersion());
10350 }
10351 } else {
10352 FromElemTy = FromValue.getLValueBase().getTypeInfoType();
10353 const Type *ImpTypeInfo = importChecked(
10354 Err, FromValue.getLValueBase().get<TypeInfoLValue>().getType());
10355 QualType ImpType =
10356 importChecked(Err, FromValue.getLValueBase().getTypeInfoType());
10357 if (Err)
10358 return std::move(Err);
10360 ImpType);
10361 }
10362 }
10363 CharUnits Offset = FromValue.getLValueOffset();
10364 unsigned PathLength = FromValue.getLValuePath().size();
10365 Result.MakeLValue();
10366 if (FromValue.hasLValuePath()) {
10367 MutableArrayRef<APValue::LValuePathEntry> ToPath = Result.setLValueUninit(
10368 Base, Offset, PathLength, FromValue.isLValueOnePastTheEnd(),
10369 FromValue.isNullPointer());
10371 FromValue.getLValuePath();
10372 for (unsigned LoopIdx = 0; LoopIdx < PathLength; LoopIdx++) {
10373 if (FromElemTy->isRecordType()) {
10374 const Decl *FromDecl =
10375 FromPath[LoopIdx].getAsBaseOrMember().getPointer();
10376 const Decl *ImpDecl = importChecked(Err, FromDecl);
10377 if (Err)
10378 return std::move(Err);
10379 if (auto *RD = dyn_cast<CXXRecordDecl>(FromDecl))
10380 FromElemTy = Importer.FromContext.getRecordType(RD);
10381 else
10382 FromElemTy = cast<ValueDecl>(FromDecl)->getType();
10384 ImpDecl, FromPath[LoopIdx].getAsBaseOrMember().getInt()));
10385 } else {
10386 FromElemTy =
10387 Importer.FromContext.getAsArrayType(FromElemTy)->getElementType();
10388 ToPath[LoopIdx] = APValue::LValuePathEntry::ArrayIndex(
10389 FromPath[LoopIdx].getAsArrayIndex());
10390 }
10391 }
10392 } else
10393 Result.setLValue(Base, Offset, APValue::NoLValuePath{},
10394 FromValue.isNullPointer());
10395 }
10396 if (Err)
10397 return std::move(Err);
10398 return Result;
10399}
10400
10402 DeclContext *DC,
10403 unsigned IDNS,
10404 NamedDecl **Decls,
10405 unsigned NumDecls) {
10406 if (ODRHandling == ODRHandlingType::Conservative)
10407 // Report error at any name conflict.
10408 return make_error<ASTImportError>(ASTImportError::NameConflict);
10409 else
10410 // Allow to create the new Decl with the same name.
10411 return Name;
10412}
10413
10415 if (LastDiagFromFrom)
10417 FromContext.getDiagnostics());
10418 LastDiagFromFrom = false;
10419 return ToContext.getDiagnostics().Report(Loc, DiagID);
10420}
10421
10423 if (!LastDiagFromFrom)
10425 ToContext.getDiagnostics());
10426 LastDiagFromFrom = true;
10427 return FromContext.getDiagnostics().Report(Loc, DiagID);
10428}
10429
10431 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
10432 if (!ID->getDefinition())
10433 ID->startDefinition();
10434 }
10435 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) {
10436 if (!PD->getDefinition())
10437 PD->startDefinition();
10438 }
10439 else if (auto *TD = dyn_cast<TagDecl>(D)) {
10440 if (!TD->getDefinition() && !TD->isBeingDefined()) {
10441 TD->startDefinition();
10442 TD->setCompleteDefinition(true);
10443 }
10444 }
10445 else {
10446 assert(0 && "CompleteDecl called on a Decl that can't be completed");
10447 }
10448}
10449
10451 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From);
10452 assert((Pos == ImportedDecls.end() || Pos->second == To) &&
10453 "Try to import an already imported Decl");
10454 if (Pos != ImportedDecls.end())
10455 return Pos->second;
10456 ImportedDecls[From] = To;
10457 // This mapping should be maintained only in this function. Therefore do not
10458 // check for additional consistency.
10459 ImportedFromDecls[To] = From;
10460 // In the case of TypedefNameDecl we create the Decl first and only then we
10461 // import and set its DeclContext. So, the DC is still not set when we reach
10462 // here from GetImportedOrCreateDecl.
10463 if (To->getDeclContext())
10464 AddToLookupTable(To);
10465 return To;
10466}
10467
10468std::optional<ASTImportError>
10470 auto Pos = ImportDeclErrors.find(FromD);
10471 if (Pos != ImportDeclErrors.end())
10472 return Pos->second;
10473 else
10474 return std::nullopt;
10475}
10476
10478 auto InsertRes = ImportDeclErrors.insert({From, Error});
10479 (void)InsertRes;
10480 // Either we set the error for the first time, or we already had set one and
10481 // now we want to set the same error.
10482 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error);
10483}
10484
10486 bool Complain) {
10487 llvm::DenseMap<const Type *, const Type *>::iterator Pos =
10488 ImportedTypes.find(From.getTypePtr());
10489 if (Pos != ImportedTypes.end()) {
10490 if (ExpectedType ToFromOrErr = Import(From)) {
10491 if (ToContext.hasSameType(*ToFromOrErr, To))
10492 return true;
10493 } else {
10494 llvm::consumeError(ToFromOrErr.takeError());
10495 }
10496 }
10497
10498 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls,
10499 getStructuralEquivalenceKind(*this), false,
10500 Complain);
10501 return Ctx.IsEquivalent(From, To);
10502}
Defines the clang::ASTContext interface.
ASTImporterLookupTable & LT
static FriendCountAndPosition getFriendCountAndPosition(ASTImporter &Importer, FriendDecl *FD)
static bool IsEquivalentFriend(ASTImporter &Importer, FriendDecl *FD1, FriendDecl *FD2)
static auto getTemplateDefinition(T *D) -> T *
static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D)
static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, ASTImporter &Importer)
static StructuralEquivalenceKind getStructuralEquivalenceKind(const ASTImporter &Importer)
Defines enum values for all the target-independent builtin functions.
const Decl * D
IndirectLocalPath & Path
Expr * E
enum clang::sema::@1651::IndirectLocalPathEntry::EntryKind Kind
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
Defines the ExceptionSpecificationType enumeration and various utility functions.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::FileManager interface and associated types.
int Category
Definition: Format.cpp:2992
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the LambdaCapture class.
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
llvm::SmallVector< std::pair< const MemRegion *, SVal >, 4 > Bindings
SourceLocation Loc
Definition: SemaObjC.cpp:758
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Defines the Objective-C statement AST node classes.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
const NamedDecl * FromDecl
unsigned getVersion() const
Definition: APValue.cpp:113
QualType getTypeInfoType() const
Definition: APValue.cpp:117
static LValueBase getTypeInfo(TypeInfoLValue LV, QualType TypeInfo)
Definition: APValue.cpp:55
unsigned getCallIndex() const
Definition: APValue.cpp:108
A non-discriminated union of a base, field, or array index.
Definition: APValue.h:208
static LValuePathEntry ArrayIndex(uint64_t Index)
Definition: APValue.h:216
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:994
const FieldDecl * getUnionField() const
Definition: APValue.h:563
unsigned getStructNumFields() const
Definition: APValue.h:542
llvm::PointerIntPair< const Decl *, 1, bool > BaseOrMemberType
A FieldDecl or CXXRecordDecl, along with a flag indicating whether we mean a virtual or non-virtual b...
Definition: APValue.h:205
ValueKind getKind() const
Definition: APValue.h:395
bool isLValueOnePastTheEnd() const
Definition: APValue.cpp:979
bool isMemberPointerToDerivedMember() const
Definition: APValue.cpp:1064
unsigned getArrayInitializedElts() const
Definition: APValue.h:529
unsigned getStructNumBases() const
Definition: APValue.h:538
bool hasLValuePath() const
Definition: APValue.cpp:989
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getUnionValue()
Definition: APValue.h:567
const AddrLabelExpr * getAddrLabelDiffRHS() const
Definition: APValue.h:583
CharUnits & getLValueOffset()
Definition: APValue.cpp:984
unsigned getVectorLength() const
Definition: APValue.h:505
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition: APValue.cpp:1071
unsigned getArraySize() const
Definition: APValue.h:533
@ Indeterminate
This object has an indeterminate value (C++ [basic.indet]).
Definition: APValue.h:131
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isNullPointer() const
Definition: APValue.cpp:1010
const AddrLabelExpr * getAddrLabelDiffLHS() const
Definition: APValue.h:579
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
SourceManager & getSourceManager()
Definition: ASTContext.h:720
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1100
QualType getAtomicType(QualType T) const
Return the uniqued reference to the atomic type for the specified type.
QualType getParenType(QualType NamedType) const
QualType getRValueReferenceType(QualType T) const
Return the uniqued reference to the type for an rvalue reference to the specified type.
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType) const
BuiltinTemplateDecl * getMakeIntegerSeqDecl() const
void setInstantiatedFromUsingDecl(NamedDecl *Inst, NamedDecl *Pattern)
Remember that the using decl Inst is an instantiation of the using decl Pattern of a class template.
QualType getAutoType(QualType DeducedType, AutoTypeKeyword Keyword, bool IsDependent, bool IsPack=false, ConceptDecl *TypeConstraintConcept=nullptr, ArrayRef< TemplateArgument > TypeConstraintArgs={}) const
C++11 deduced auto type.
QualType getDependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, ArrayRef< TemplateArgumentLoc > Args) const
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
QualType getMemberPointerType(QualType T, const Type *Cls) const
Return the uniqued reference to the type for a member pointer to the specified type in the specified ...
NamedDecl * getInstantiatedFromUsingDecl(NamedDecl *Inst)
If the given using decl Inst is an instantiation of another (possibly unresolved) using decl,...
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:663
QualType getTemplateSpecializationType(TemplateName T, ArrayRef< TemplateArgument > Args, QualType Canon=QualType()) const
QualType getRecordType(const RecordDecl *Decl) const
QualType getInjectedClassNameType(CXXRecordDecl *Decl, QualType TST) const
getInjectedClassNameType - Return the unique reference to the injected class name type for the specif...
QualType getVariableArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a variable array of the specified element type.
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
QualType getArrayParameterType(QualType Ty) const
Return the uniqued reference to a specified array parameter type from the original array type.
QualType getCountAttributedType(QualType T, Expr *CountExpr, bool CountInBytes, bool OrNull, ArrayRef< TypeCoupledDeclRefInfo > DependentDecls) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2625
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2641
void setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, UsingShadowDecl *Pattern)
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateName Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getReadPipeType(QualType T) const
Return a read_only pipe type for the specified type.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1634
IdentifierTable & Idents
Definition: ASTContext.h:659
TemplateName getSubstTemplateTemplateParm(TemplateName replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
SelectorTable & Selectors
Definition: ASTContext.h:660
QualType getMacroQualifiedType(QualType UnderlyingTy, const IdentifierInfo *MacroII) const
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
void setInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst, UsingEnumDecl *Pattern)
Remember that the using enum decl Inst is an instantiation of the using enum decl Pattern of a class ...
UsingEnumDecl * getInstantiatedFromUsingEnumDecl(UsingEnumDecl *Inst)
If the given using-enum decl Inst is an instantiation of another using-enum decl, return it.
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
QualType getTemplateTypeParmType(unsigned Depth, unsigned Index, bool ParameterPack, TemplateTypeParmDecl *ParmDecl=nullptr) const
Retrieve the template type parameter type for a template parameter or parameter pack with the given d...
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl, unsigned Index, bool Final, const TemplateArgument &ArgPack)
Retrieve a.
CanQualType CharTy
Definition: ASTContext.h:1120
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2207
QualType getElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, QualType NamedType, TagDecl *OwnedTagDecl=nullptr) const
CanQualType SignedCharTy
Definition: ASTContext.h:1127
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
QualType getObjCObjectType(QualType Base, ObjCProtocolDecl *const *Protocols, unsigned NumProtocols) const
Legacy interface: cannot provide type arguments or __kindof.
QualType getDependentSizedArrayType(QualType EltTy, Expr *NumElts, ArraySizeModifier ASM, unsigned IndexTypeQuals, SourceRange Brackets) const
Return a non-unique reference to the type for a dependently-sized array of the specified element type...
UsingShadowDecl * getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst)
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
QualType getWritePipeType(QualType T) const
Return a write_only pipe type for the specified type.
CanQualType VoidTy
Definition: ASTContext.h:1118
CanQualType UnsignedCharTy
Definition: ASTContext.h:1128
TemplateName getDependentTemplateName(NestedNameSpecifier *NNS, const IdentifierInfo *Name) const
Retrieve the template name that represents a dependent template name such as MetaFun::template apply.
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1612
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
QualType getPackIndexingType(QualType Pattern, Expr *IndexExpr, bool FullySubstituted=false, ArrayRef< QualType > Expansions={}, int Index=-1) const
QualType getUnaryTransformType(QualType BaseType, QualType UnderlyingType, UnaryTransformType::UTTKind UKind) const
Unary type transforms.
QualType getComplexType(QualType T) const
Return the uniqued reference to the type for a complex number with the specified element type.
DiagnosticsEngine & getDiagnostics() const
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
TemplateName getSubstTemplateTemplateParmPack(const TemplateArgument &ArgPack, Decl *AssociatedDecl, unsigned Index, bool Final) const
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1224
BuiltinTemplateDecl * getTypePackElementDecl() const
QualType getTypeOfType(QualType QT, TypeOfKind Kind) const
getTypeOfType - Unlike many "get<Type>" functions, we don't unique TypeOfType nodes.
CanQualType WCharTy
Definition: ASTContext.h:1121
QualType getDecltypeType(Expr *e, QualType UnderlyingType) const
C++11 decltype.
QualType getTypedefType(const TypedefNameDecl *Decl, QualType Underlying=QualType()) const
Return the unique reference to the type for the specified typedef-name decl.
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex) const
Retrieve a substitution-result type.
unsigned char getFixedPointScale(QualType Ty) const
QualType getIncompleteArrayType(QualType EltTy, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return a unique reference to the type for an incomplete array of the specified element type.
QualType getDependentSizedExtVectorType(QualType VectorType, Expr *SizeExpr, SourceLocation AttrLoc) const
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
QualType getTypeOfExprType(Expr *E, TypeOfKind Kind) const
C23 feature and GCC extension.
std::error_code convertToErrorCode() const override
void log(llvm::raw_ostream &OS) const override
std::string toString() const
Definition: ASTImporter.cpp:86
@ Unknown
Not supported node or case.
@ UnsupportedConstruct
Naming ambiguity (likely ODR violation).
void update(NamedDecl *ND, DeclContext *OldDC)
void updateForced(NamedDecl *ND, DeclContext *OldDC)
bool hasCycleAtBack() const
Returns true if the last element can be found earlier in the path.
Definition: ASTImporter.h:164
VecTy copyCycleAtBack() const
Returns the copy of the cycle.
Definition: ASTImporter.h:178
Imports selected nodes from one AST context into another context, merging AST nodes where appropriate...
Definition: ASTImporter.h:62
ASTContext & getFromContext() const
Retrieve the context that AST nodes are being imported from.
Definition: ASTImporter.h:523
NonEquivalentDeclSet & getNonEquivalentDecls()
Return the set of declarations that we know are not equivalent.
Definition: ASTImporter.h:538
ASTContext & getToContext() const
Retrieve the context that AST nodes are being imported into.
Definition: ASTImporter.h:520
DiagnosticBuilder ToDiag(SourceLocation Loc, unsigned DiagID)
Report a diagnostic in the "to" context.
Decl * MapImported(Decl *From, Decl *To)
Store and assign the imported declaration to its counterpart.
TranslationUnitDecl * GetFromTU(Decl *ToD)
Return the translation unit from where the declaration was imported.
llvm::Expected< DeclContext * > ImportContext(DeclContext *FromDC)
Import the given declaration context from the "from" AST context into the "to" AST context.
llvm::Error ImportDefinition(Decl *From)
Import the definition of the given declaration, including all of the declarations it contains.
virtual Expected< DeclarationName > HandleNameConflict(DeclarationName Name, DeclContext *DC, unsigned IDNS, NamedDecl **Decls, unsigned NumDecls)
Cope with a name conflict when importing a declaration into the given context.
virtual bool returnWithErrorInTest()
Used only in unittests to verify the behaviour of the error handling.
Definition: ASTImporter.h:270
std::optional< DeclT * > getImportedFromDecl(const DeclT *ToD) const
Return the declaration in the "from" context from which the declaration in the "to" context was impor...
Definition: ASTImporter.h:371
void RegisterImportedDecl(Decl *FromD, Decl *ToD)
std::optional< ASTImportError > getImportDeclErrorIfAny(Decl *FromD) const
Return if import of the given declaration has failed and if yes the kind of the problem.
friend class ASTNodeImporter
Definition: ASTImporter.h:63
static std::optional< unsigned > getFieldIndex(Decl *F)
Determine the index of a field in its parent record.
llvm::Error importInto(ImportT &To, const ImportT &From)
Import the given object, returns the result.
Definition: ASTImporter.h:308
virtual Decl * GetOriginalDecl(Decl *To)
Called by StructuralEquivalenceContext.
Definition: ASTImporter.h:563
virtual void Imported(Decl *From, Decl *To)
Subclasses can override this function to observe all of the From -> To declaration mappings as they a...
Definition: ASTImporter.h:548
DiagnosticBuilder FromDiag(SourceLocation Loc, unsigned DiagID)
Report a diagnostic in the "from" context.
virtual ~ASTImporter()
bool IsStructurallyEquivalent(QualType From, QualType To, bool Complain=true)
Determine whether the given types are structurally equivalent.
virtual Expected< Decl * > ImportImpl(Decl *From)
Can be overwritten by subclasses to implement their own import logic.
bool isMinimalImport() const
Whether the importer will perform a minimal import, creating to-be-completed forward declarations whe...
Definition: ASTImporter.h:298
ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, ASTContext &FromContext, FileManager &FromFileManager, bool MinimalImport, std::shared_ptr< ASTImporterSharedState > SharedState=nullptr)
llvm::Expected< ExprWithCleanups::CleanupObject > Import(ExprWithCleanups::CleanupObject From)
Import cleanup objects owned by ExprWithCleanup.
virtual void CompleteDecl(Decl *D)
Called for ObjCInterfaceDecl, ObjCProtocolDecl, and TagDecl.
Decl * GetAlreadyImportedOrNull(const Decl *FromD) const
Return the copy of the given declaration in the "to" context if it has already been imported from the...
void setImportDeclError(Decl *From, ASTImportError Error)
Mark (newly) imported declaration with error.
ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D)
ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E)
ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E)
ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D)
ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D)
ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E)
ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D)
ExpectedDecl VisitFunctionDecl(FunctionDecl *D)
ExpectedDecl VisitParmVarDecl(ParmVarDecl *D)
ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E)
ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D)
ExpectedDecl VisitUsingDecl(UsingDecl *D)
ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D)
ExpectedStmt VisitStmt(Stmt *S)
ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D)
ExpectedDecl VisitFieldDecl(FieldDecl *D)
Error ImportFieldDeclDefinition(const FieldDecl *From, const FieldDecl *To)
Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD=nullptr)
ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E)
ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E)
ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S)
ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D)
ExpectedStmt VisitShuffleVectorExpr(ShuffleVectorExpr *E)
ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D)
ExpectedDecl VisitRecordDecl(RecordDecl *D)
ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E)
ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D)
Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin)
ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S)
T importChecked(Error &Err, const T &From)
ExpectedStmt VisitVAArgExpr(VAArgExpr *E)
ExpectedStmt VisitDefaultStmt(DefaultStmt *S)
ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D)
ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E)
ExpectedDecl VisitLabelDecl(LabelDecl *D)
ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E)
ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S)
ExpectedStmt VisitUnaryOperator(UnaryOperator *E)
Error ImportTemplateParameterLists(const DeclTy *FromD, DeclTy *ToD)
Error ImportDeclContext(DeclContext *FromDC, bool ForceImport=false)
ExpectedStmt VisitContinueStmt(ContinueStmt *S)
ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E)
ExpectedDecl VisitVarDecl(VarDecl *D)
ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E)
ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D)
Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To)
ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E)
ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E)
ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D)
ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D)
ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E)
ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE)
ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E)
ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D)
ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E)
ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D)
Expected< InheritedConstructor > ImportInheritedConstructor(const InheritedConstructor &From)
ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E)
Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc)
Error ImportDefinition(RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind=IDK_Default)
ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S)
ExpectedStmt VisitConstantExpr(ConstantExpr *E)
ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E)
ExpectedDecl VisitDecl(Decl *D)
bool hasSameVisibilityContextAndLinkage(T *Found, T *From)
ExpectedStmt VisitParenExpr(ParenExpr *E)
ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S)
ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E)
ExpectedStmt VisitInitListExpr(InitListExpr *E)
Expected< FunctionTemplateAndArgsTy > ImportFunctionTemplateWithTemplateArgsFromSpecialization(FunctionDecl *FromFD)
ExpectedStmt VisitReturnStmt(ReturnStmt *S)
ExpectedStmt VisitAtomicExpr(AtomicExpr *E)
ExpectedStmt VisitConditionalOperator(ConditionalOperator *E)
ExpectedStmt VisitChooseExpr(ChooseExpr *E)
ExpectedStmt VisitCompoundStmt(CompoundStmt *S)
Expected< TemplateArgument > ImportTemplateArgument(const TemplateArgument &From)
ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
ExpectedStmt VisitCaseStmt(CaseStmt *S)
ExpectedStmt VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E)
ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E)
ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D)
ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E)
ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E)
ExpectedStmt VisitLambdaExpr(LambdaExpr *LE)
ExpectedStmt VisitBinaryOperator(BinaryOperator *E)
ExpectedStmt VisitCallExpr(CallExpr *E)
ExpectedStmt VisitDeclStmt(DeclStmt *S)
ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E)
ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E)
Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin)
ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D)
ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D)
Expected< CXXCastPath > ImportCastPath(CastExpr *E)
Expected< APValue > ImportAPValue(const APValue &FromValue)
ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D)
ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E)
ExpectedDecl VisitClassTemplateSpecializationDecl(ClassTemplateSpecializationDecl *D)
ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E)
ExpectedDecl VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D)
ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias)
ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D)
ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D)
ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D)
Expected< ObjCTypeParamList * > ImportObjCTypeParamList(ObjCTypeParamList *list)
ExpectedDecl VisitUsingPackDecl(UsingPackDecl *D)
ExpectedStmt VisitWhileStmt(WhileStmt *S)
ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D)
ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E)
ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S)
ExpectedDecl VisitFriendDecl(FriendDecl *D)
Error ImportContainerChecked(const InContainerTy &InContainer, OutContainerTy &OutContainer)
ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E)
ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E)
bool IsStructuralMatch(Decl *From, Decl *To, bool Complain=true, bool IgnoreTemplateParmDepth=false)
ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E)
ExpectedStmt VisitForStmt(ForStmt *S)
ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E)
ExpectedDecl VisitEnumDecl(EnumDecl *D)
ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D)
ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E)
ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E)
ExpectedStmt VisitSwitchStmt(SwitchStmt *S)
ExpectedType VisitType(const Type *T)
ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D)
ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI)
ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E)
ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E)
ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D)
ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E)
ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D)
ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E)
ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E)
ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D)
Error ImportTemplateArguments(ArrayRef< TemplateArgument > FromArgs, SmallVectorImpl< TemplateArgument > &ToArgs)
ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D)
ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E)
ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D)
ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D)
ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E)
ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E)
Error ImportTemplateArgumentListInfo(const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo)
ExpectedStmt VisitDoStmt(DoStmt *S)
ExpectedStmt VisitNullStmt(NullStmt *S)
ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E)
ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D)
Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod)
ExpectedStmt VisitStringLiteral(StringLiteral *E)
Error ImportDeclarationNameLoc(const DeclarationNameInfo &From, DeclarationNameInfo &To)
ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E)
bool hasReturnTypeDeclaredInside(FunctionDecl *D)
This function checks if the given function has a return type that contains a reference (in any way) t...
ASTNodeImporter(ASTImporter &Importer)
std::tuple< FunctionTemplateDecl *, TemplateArgsTy > FunctionTemplateAndArgsTy
ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D)
ExpectedStmt VisitMemberExpr(MemberExpr *E)
ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E)
Error ImportInitializer(VarDecl *From, VarDecl *To)
ImportDefinitionKind
What we should import from the definition.
@ IDK_Everything
Import everything.
@ IDK_Default
Import the default subset of the definition, which might be nothing (if minimal import is set) or mig...
@ IDK_Basic
Import only the bare bones needed to establish a valid DeclContext.
ExpectedDecl VisitTypedefDecl(TypedefDecl *D)
ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D)
ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E)
ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D)
ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E)
ExpectedStmt VisitIfStmt(IfStmt *S)
ExpectedStmt VisitLabelStmt(LabelStmt *S)
ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E)
ExpectedStmt VisitConvertVectorExpr(ConvertVectorExpr *E)
ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D)
ExpectedStmt VisitGotoStmt(GotoStmt *S)
ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E)
ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S)
ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S)
ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D)
ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S)
ExpectedDecl VisitImportDecl(ImportDecl *D)
Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD)
ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E)
ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E)
ExpectedDecl VisitEmptyDecl(EmptyDecl *D)
ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E)
ExpectedStmt VisitExpr(Expr *E)
Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam, ParmVarDecl *ToParam)
ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E)
ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S)
ExpectedStmt VisitAttributedStmt(AttributedStmt *S)
ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S)
ExpectedStmt VisitParenListExpr(ParenListExpr *E)
Expected< FunctionDecl * > FindFunctionTemplateSpecialization(FunctionDecl *FromFD)
ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D)
ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S)
Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD)
ExpectedStmt VisitStmtExpr(StmtExpr *E)
ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E)
bool shouldForceImportDeclContext(ImportDefinitionKind IDK)
ExpectedDecl VisitBindingDecl(BindingDecl *D)
ExpectedStmt VisitBreakStmt(BreakStmt *S)
Represents an access specifier followed by colon ':'.
Definition: DeclCXX.h:86
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4362
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3320
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5746
Represents a loop initializing the elements of an array.
Definition: Expr.h:5693
Represents a constant array type that does not decay to a pointer when used as a function parameter.
Definition: Type.h:3710
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2852
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3540
QualType getElementType() const
Definition: Type.h:3552
A structure for storing the information associated with a name that has been assumed to be a template...
DeclarationName getDeclName() const
Get the name of the template.
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
Definition: Expr.h:6619
Attr - This represents one attribute.
Definition: Attr.h:42
attr::Kind getKind() const
Definition: Attr.h:88
void setPackExpansion(bool PE)
Definition: Attr.h:104
Attr * clone(ASTContext &C) const
void setImplicit(bool I)
Definition: Attr.h:102
void setAttrName(const IdentifierInfo *AttrNameII)
const IdentifierInfo * getAttrName() const
Represents an attribute applied to a statement.
Definition: Stmt.h:2085
static AttributedStmt * Create(const ASTContext &C, SourceLocation Loc, ArrayRef< const Attr * > Attrs, Stmt *SubStmt)
Definition: Stmt.cpp:425
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:5991
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:6368
Represents a C++ declaration that introduces decls from somewhere else.
Definition: DeclCXX.h:3417
void addShadowDecl(UsingShadowDecl *S)
Definition: DeclCXX.cpp:3121
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4265
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition: Expr.cpp:4804
A binding in a decomposition declaration.
Definition: DeclCXX.h:4107
void setBinding(QualType DeclaredType, Expr *Binding)
Set the binding for this BindingDecl, along with its declared type (which should be a possibly-cv-qua...
Definition: DeclCXX.h:4144
void setDecomposedDecl(ValueDecl *Decomposed)
Set the decomposed variable for this BindingDecl.
Definition: DeclCXX.h:4150
A fixed int type of a specified bitwidth.
Definition: Type.h:7626
Pointer to a block type.
Definition: Type.h:3371
BreakStmt - This represents a break.
Definition: Stmt.h:2985
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition: ExprCXX.h:5290
Represents the builtin template declaration which is used to implement __make_integer_seq and other b...
This class is used for builtin types like 'int'.
Definition: Type.h:3000
static CStyleCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R)
Definition: Expr.cpp:2105
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
AccessSpecifier getAccessSpecifierAsWritten() const
Retrieves the access specifier as written in the source code (which may mean that no access specifier...
Definition: DeclCXX.h:242
SourceLocation getEllipsisLoc() const
For a pack expansion, determine the location of the ellipsis.
Definition: DeclCXX.h:221
bool isVirtual() const
Determines whether the base class is a virtual base class (or not).
Definition: DeclCXX.h:203
TypeSourceInfo * getTypeSourceInfo() const
Retrieves the type and source location of the base class.
Definition: DeclCXX.h:254
bool isBaseOfClass() const
Determine whether this base class is a base of a class declared with the 'class' keyword (vs.
Definition: DeclCXX.h:207
SourceRange getSourceRange() const LLVM_READONLY
Retrieves the source range that contains the entire base specifier.
Definition: DeclCXX.h:193
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
static CXXBindTemporaryExpr * Create(const ASTContext &C, CXXTemporary *Temp, Expr *SubExpr)
Definition: ExprCXX.cpp:1095
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
static CXXBoolLiteralExpr * Create(const ASTContext &C, bool Val, QualType Ty, SourceLocation Loc)
Definition: ExprCXX.h:732
CXXCatchStmt - This represents a C++ catch block.
Definition: StmtCXX.h:28
static CXXConstCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, Expr *Op, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:873
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
void setIsImmediateEscalating(bool Set)
Definition: ExprCXX.h:1708
static CXXConstructExpr * Create(const ASTContext &Ctx, QualType Ty, SourceLocation Loc, CXXConstructorDecl *Ctor, bool Elidable, ArrayRef< Expr * > Args, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization, CXXConstructionKind ConstructKind, SourceRange ParenOrBraceRange)
Create a C++ construction expression.
Definition: ExprCXX.cpp:1157
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2535
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2862
Represents a C++ base or member initializer.
Definition: DeclCXX.h:2300
FieldDecl * getMember() const
If this is a member initializer, returns the declaration of the non-static data member being initiali...
Definition: DeclCXX.h:2440
bool isDelegatingInitializer() const
Determine whether this initializer is creating a delegating constructor.
Definition: DeclCXX.h:2400
Expr * getInit() const
Get the initializer.
Definition: DeclCXX.h:2502
SourceLocation getRParenLoc() const
Definition: DeclCXX.h:2499
SourceLocation getEllipsisLoc() const
Definition: DeclCXX.h:2410
SourceLocation getLParenLoc() const
Definition: DeclCXX.h:2498
bool isPackExpansion() const
Determine whether this initializer is a pack expansion.
Definition: DeclCXX.h:2405
TypeSourceInfo * getTypeSourceInfo() const
Returns the declarator information for a base class or delegating initializer.
Definition: DeclCXX.h:2434
bool isMemberInitializer() const
Determine whether this initializer is initializing a non-static data member.
Definition: DeclCXX.h:2378
bool isBaseInitializer() const
Determine whether this initializer is initializing a base class.
Definition: DeclCXX.h:2372
bool isIndirectMemberInitializer() const
Definition: DeclCXX.h:2384
SourceLocation getMemberLocation() const
Definition: DeclCXX.h:2460
IndirectFieldDecl * getIndirectMember() const
Definition: DeclCXX.h:2454
bool isBaseVirtual() const
Returns whether the base is virtual or not.
Definition: DeclCXX.h:2426
Represents a C++ deduction guide declaration.
Definition: DeclCXX.h:1952
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
static CXXDefaultArgExpr * Create(const ASTContext &C, SourceLocation Loc, ParmVarDecl *Param, Expr *RewrittenExpr, DeclContext *UsedContext)
Definition: ExprCXX.cpp:1016
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
static CXXDefaultInitExpr * Create(const ASTContext &Ctx, SourceLocation Loc, FieldDecl *Field, DeclContext *UsedContext, Expr *RewrittenInitExpr)
Field is the non-static data member whose default initializer is used by this expression.
Definition: ExprCXX.cpp:1070
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2497
Represents a C++ member access expression where the actual member referenced could not be resolved be...
Definition: ExprCXX.h:3681
static CXXDependentScopeMemberExpr * Create(const ASTContext &Ctx, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, NamedDecl *FirstQualifierFoundInScope, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:1531
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
void setOperatorDelete(FunctionDecl *OD, Expr *ThisArg)
Definition: DeclCXX.cpp:2872
static CXXDynamicCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:785
Represents a folding of a pack over an operator.
Definition: ExprCXX.h:4838
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
static CXXFunctionalCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, TypeSourceInfo *Written, CastKind Kind, Expr *Op, const CXXCastPath *Path, FPOptionsOverride FPO, SourceLocation LPLoc, SourceLocation RPLoc)
Definition: ExprCXX.cpp:899
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a call to a member function that may be written either with member call syntax (e....
Definition: ExprCXX.h:176
static CXXMemberCallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RP, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0)
Definition: ExprCXX.cpp:673
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2511
overridden_method_range overridden_methods() const
Definition: DeclCXX.cpp:2536
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2156
Abstract class common to all of the C++ "named"/"keyword" casts.
Definition: ExprCXX.h:372
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2240
static CXXNewExpr * Create(const ASTContext &Ctx, bool IsGlobalNew, FunctionDecl *OperatorNew, FunctionDecl *OperatorDelete, bool ShouldPassAlignment, bool UsualArrayDeleteWantsSize, ArrayRef< Expr * > PlacementArgs, SourceRange TypeIdParens, std::optional< Expr * > ArraySize, CXXNewInitializationStyle InitializationStyle, Expr *Initializer, QualType Ty, TypeSourceInfo *AllocatedTypeInfo, SourceRange Range, SourceRange DirectInitRange)
Create a c++ new expression.
Definition: ExprCXX.cpp:292
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4124
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
static CXXOperatorCallExpr * Create(const ASTContext &Ctx, OverloadedOperatorKind OpKind, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation OperatorLoc, FPOptionsOverride FPFeatures, ADLCallKind UsesADL=NotADL)
Definition: ExprCXX.cpp:609
Represents a C++ pseudo-destructor (C++ [expr.pseudo]).
Definition: ExprCXX.h:2616
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXRecordDecl * getMostRecentDecl()
Definition: DeclCXX.h:540
CXXRecordDecl * getInstantiatedFromMemberClass() const
If this record is an instantiation of a member class, retrieves the member class from which it was in...
Definition: DeclCXX.cpp:1879
method_range methods() const
Definition: DeclCXX.h:661
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:564
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
void setInstantiationOfMemberClass(CXXRecordDecl *RD, TemplateSpecializationKind TSK)
Specify that this record is an instantiation of the member class RD.
Definition: DeclCXX.cpp:1891
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1904
void setLambdaNumbering(LambdaNumbering Numbering)
Set the mangling numbers and context declaration for a lambda class.
Definition: DeclCXX.cpp:1694
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1886
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1919
CXXRecordDecl * getPreviousDecl()
Definition: DeclCXX.h:531
static CXXReinterpretCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind Kind, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:850
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2181
static CXXStaticCastExpr * Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K, Expr *Op, const CXXCastPath *Path, TypeSourceInfo *Written, FPOptionsOverride FPO, SourceLocation L, SourceLocation RParenLoc, SourceRange AngleBrackets)
Definition: ExprCXX.cpp:759
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents a C++ functional cast expression that builds a temporary object.
Definition: ExprCXX.h:1885
static CXXTemporaryObjectExpr * Create(const ASTContext &Ctx, CXXConstructorDecl *Cons, QualType Ty, TypeSourceInfo *TSI, ArrayRef< Expr * > Args, SourceRange ParenOrBraceRange, bool HadMultipleCandidates, bool ListInitialization, bool StdInitListInitialization, bool ZeroInitialization)
Definition: ExprCXX.cpp:1123
Represents a C++ temporary.
Definition: ExprCXX.h:1457
static CXXTemporary * Create(const ASTContext &C, const CXXDestructorDecl *Destructor)
Definition: ExprCXX.cpp:1090
Represents the this expression in C++.
Definition: ExprCXX.h:1152
static CXXThisExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType Ty, bool IsImplicit)
Definition: ExprCXX.cpp:1566
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition: StmtCXX.cpp:25
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition: ExprCXX.h:845
Describes an explicit type conversion that uses functional notion but could not be resolved because o...
Definition: ExprCXX.h:3555
static CXXUnresolvedConstructExpr * Create(const ASTContext &Context, QualType T, TypeSourceInfo *TSI, SourceLocation LParenLoc, ArrayRef< Expr * > Args, SourceLocation RParenLoc, bool IsListInit)
Definition: ExprCXX.cpp:1469
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
static CallExpr * Create(const ASTContext &Ctx, Expr *Fn, ArrayRef< Expr * > Args, QualType Ty, ExprValueKind VK, SourceLocation RParenLoc, FPOptionsOverride FPFeatures, unsigned MinNumArgs=0, ADLCallKind UsesADL=NotADL)
Create a call expression.
Definition: Expr.cpp:1494
CaseStmt - Represent a case statement.
Definition: Stmt.h:1806
static CaseStmt * Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs, SourceLocation caseLoc, SourceLocation ellipsisLoc, SourceLocation colonLoc)
Build a case statement.
Definition: Stmt.cpp:1220
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
path_iterator path_begin()
Definition: Expr.h:3568
path_iterator path_end()
Definition: Expr.h:3569
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
How to handle import errors that occur when import of a child declaration of a DeclContext fails.
bool ignoreChildErrorOnParent(Decl *FromChildD) const
Determine if import failure of a child does not cause import failure of its parent.
ChildErrorHandlingStrategy(const Decl *FromD)
void handleChildImportResult(Error &ResultErr, Error &&ChildErr)
Process the import result of a child (of the current declaration).
ChildErrorHandlingStrategy(const DeclContext *FromDC)
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4582
Declaration of a class template.
void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D, void *InsertPos)
Insert the specified partial specialization knowing that it is not already in.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
ClassTemplatePartialSpecializationDecl * findPartialSpecialization(ArrayRef< TemplateArgument > Args, TemplateParameterList *TPL, void *&InsertPos)
Return the partial specialization with the provided arguments if it exists, otherwise return the inse...
void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
QualType getInjectedClassNameSpecialization()
Retrieve the template specialization type of the injected-class-name for this class template.
ClassTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
ClassTemplatePartialSpecializationDecl * getInstantiatedFromMember() const
Retrieve the member class template partial specialization from which this particular class template p...
QualType getInjectedSpecializationType() const
Retrieves the injected specialization type for this partial specialization.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a class template specialization, which refers to a class template with a given set of temp...
void setPointOfInstantiation(SourceLocation Loc)
void setExternKeywordLoc(SourceLocation Loc)
Sets the location of the extern keyword.
void setSpecializationKind(TemplateSpecializationKind TSK)
void setTemplateKeywordLoc(SourceLocation Loc)
Sets the location of the template keyword.
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
bool isExplicitInstantiationOrSpecialization() const
True if this declaration is an explicit specialization, explicit instantiation declaration,...
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
Complex values, per C99 6.2.5p11.
Definition: Type.h:3108
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4112
static CompoundAssignOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures, QualType CompLHSType=QualType(), QualType CompResultType=QualType())
Definition: Expr.cpp:4826
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition: Stmt.cpp:383
A reference to a concept and its template args, as it appears in the code.
Definition: ASTConcept.h:125
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:164
NamedDecl * getFoundDecl() const
Definition: ASTConcept.h:196
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:168
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:200
static ConceptReference * Create(const ASTContext &C, NestedNameSpecifierLoc NNS, SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo, NamedDecl *FoundDecl, ConceptDecl *NamedConcept, const ASTTemplateArgumentListInfo *ArgsAsWritten)
Definition: ASTConcept.cpp:88
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:204
SourceLocation getTemplateKWLoc() const
Definition: ASTConcept.h:174
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4203
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3578
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Definition: Expr.cpp:350
Represents a concrete matrix type with constant number of rows and columns.
Definition: Type.h:4189
Represents a shadow constructor declaration introduced into a class by a C++11 using-declaration that...
Definition: DeclCXX.h:3598
ContinueStmt - This represents a continue.
Definition: Stmt.h:2955
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4523
Represents a sugar type with __counted_by or __sized_by annotations, including their _or_null variant...
Definition: Type.h:3269
Represents a pointer type decayed from an array or function type.
Definition: Type.h:3354
A POD class for pairing a NamedDecl* with an access specifier.
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1358
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1425
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2079
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:2019
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1309
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1828
bool isRecord() const
Definition: DeclBase.h:2159
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1964
void addDeclInternal(Decl *D)
Add the declaration D into this context, but suppress searches for external declarations with the sam...
Definition: DeclBase.cpp:1750
bool containsDeclAndLoad(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1616
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1661
lookup_result noload_lookup(DeclarationName Name)
Find the declarations with the given name that are visible within this context; don't attempt to retr...
Definition: DeclBase.cpp:1893
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1611
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2339
bool isFunctionOrMethod() const
Definition: DeclBase.h:2131
void localUncachedLookup(DeclarationName Name, SmallVectorImpl< NamedDecl * > &Results)
A simplistic name lookup mechanism that performs name lookup into this declaration context without co...
Definition: DeclBase.cpp:1925
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
iterator begin()
Definition: DeclGroup.h:99
iterator end()
Definition: DeclGroup.h:105
bool isNull() const
Definition: DeclGroup.h:79
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition: Expr.cpp:488
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
A simple visitor class that helps create declaration visitors.
Definition: DeclVisitor.h:67
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:441
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1205
bool hasAttrs() const
Definition: DeclBase.h:524
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:523
void addAttr(Attr *A)
Definition: DeclBase.cpp:1014
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:599
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:872
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1196
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1159
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:508
SourceLocation getLocation() const
Definition: DeclBase.h:445
const char * getDeclKindName() const
Definition: DeclBase.cpp:145
IdentifierNamespace
IdentifierNamespace - The different namespaces in which declarations may appear.
Definition: DeclBase.h:115
@ IDNS_NonMemberOperator
This declaration is a C++ operator declared in a non-class context.
Definition: DeclBase.h:168
@ IDNS_TagFriend
This declaration is a friend class.
Definition: DeclBase.h:157
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:144
@ IDNS_ObjCProtocol
Objective C @protocol.
Definition: DeclBase.h:147
@ IDNS_Namespace
Namespaces, declared with 'namespace foo {}'.
Definition: DeclBase.h:140
@ IDNS_OrdinaryFriend
This declaration is a friend function.
Definition: DeclBase.h:152
@ IDNS_Tag
Tags, declared with 'struct foo;' and referenced with 'struct foo'.
Definition: DeclBase.h:125
void setImplicit(bool I=true)
Definition: DeclBase.h:600
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: DeclBase.h:1028
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:614
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:552
DeclContext * getDeclContext()
Definition: DeclBase.h:454
AccessSpecifier getAccess() const
Definition: DeclBase.h:513
bool isInAnonymousNamespace() const
Definition: DeclBase.cpp:415
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:437
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:508
AttrVec & getAttrs()
Definition: DeclBase.h:530
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:897
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:957
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
DeclarationName getCXXLiteralOperatorName(const IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
The name of a declaration.
IdentifierInfo * getAsIdentifierInfo() const
Retrieve the IdentifierInfo * stored in this declaration name, or null if this declaration name isn't...
TemplateDecl * getCXXDeductionGuideTemplate() const
If this name is the name of a C++ deduction guide, return the template associated with that name.
const IdentifierInfo * getCXXLiteralIdentifier() const
If this name is the name of a literal operator, retrieve the identifier associated with it.
static DeclarationName getUsingDirectiveName()
Returns the name for all C++ using-directives.
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
QualType getCXXNameType() const
If this name is one of the C++ names (of a constructor, destructor, or conversion function),...
Selector getObjCSelector() const
Get the Objective-C selector stored in this declaration name.
NameKind getNameKind() const
Determine what kind of name this is.
bool isEmpty() const
Evaluates true when this declaration name is empty.
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1982
Represents the type decltype(expr) (C++11).
Definition: Type.h:5745
A decomposition declaration.
Definition: DeclCXX.h:4166
Represents a C++17 deduced template specialization type.
Definition: Type.h:6416
Represents an extended address space qualifier where the input address space value is dependent.
Definition: Type.h:3881
Represents a qualified type name for which the type name is dependent.
Definition: Type.h:6836
A qualified reference to a name whose declaration cannot yet be resolved.
Definition: ExprCXX.h:3321
static DependentScopeDeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &NameInfo, const TemplateArgumentListInfo *TemplateArgs)
Definition: ExprCXX.cpp:529
Represents an array type in C++ whose size is a value-dependent expression.
Definition: Type.h:3823
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3921
Represents a matrix type where the type and the number of rows and columns is dependent on a template...
Definition: Type.h:4248
Represents a dependent template name that cannot be resolved prior to template instantiation.
Definition: TemplateName.h:491
OverloadedOperatorKind getOperator() const
Return the overloaded operator to which this template name refers.
Definition: TemplateName.h:563
bool isIdentifier() const
Determine whether this template name refers to an identifier.
Definition: TemplateName.h:550
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:547
const IdentifierInfo * getIdentifier() const
Returns the identifier to which this template name refers.
Definition: TemplateName.h:553
Represents a template specialization type whose template cannot be resolved, e.g.
Definition: Type.h:6888
Represents a vector type where either the type or size is dependent.
Definition: Type.h:4043
Represents a single C99 designator.
Definition: Expr.h:5317
static Designator CreateArrayRangeDesignator(unsigned Index, SourceLocation LBracketLoc, SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
Creates a GNU array-range designator.
Definition: Expr.h:5444
static Designator CreateFieldDesignator(const IdentifierInfo *FieldName, SourceLocation DotLoc, SourceLocation FieldLoc)
Creates a field designator.
Definition: Expr.h:5398
static Designator CreateArrayDesignator(unsigned Index, SourceLocation LBracketLoc, SourceLocation RBracketLoc)
Creates an array designator.
Definition: Expr.h:5434
Represents a C99 designated initializer expression.
Definition: Expr.h:5274
static DesignatedInitExpr * Create(const ASTContext &C, llvm::ArrayRef< Designator > Designators, ArrayRef< Expr * > IndexExprs, SourceLocation EqualOrColonLoc, bool GNUSyntax, Expr *Init)
Definition: Expr.cpp:4605
A little helper class used to produce diagnostics.
Definition: Diagnostic.h:1271
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
void notePriorDiagnosticFrom(const DiagnosticsEngine &Other)
Note that the prior diagnostic was emitted by some other DiagnosticsEngine, and we may be attaching a...
Definition: Diagnostic.h:896
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2730
Symbolic representation of a dynamic allocation.
Definition: APValue.h:65
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6755
Represents an empty-declaration.
Definition: Decl.h:4905
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3270
Represents an enum.
Definition: Decl.h:3840
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4099
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition: Decl.h:4037
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:4009
EnumDecl * getMostRecentDecl()
Definition: Decl.h:3936
void completeDefinition(QualType NewType, QualType PromotionType, unsigned NumPositiveBits, unsigned NumNegativeBits)
When created, the EnumDecl corresponds to a forward-declared enum.
Definition: Decl.cpp:4866
EnumDecl * getDefinition() const
Definition: Decl.h:3943
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum.
Definition: Decl.h:4026
QualType getPromotionType() const
Return the integer type that enumerators should promote to.
Definition: Decl.h:3992
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5962
ExplicitCastExpr - An explicit cast written in the source code.
Definition: Expr.h:3750
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1897
ExplicitSpecKind getKind() const
Definition: DeclCXX.h:1905
const Expr * getExpr() const
Definition: DeclCXX.h:1906
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3472
llvm::PointerUnion< BlockDecl *, CompoundLiteralExpr * > CleanupObject
The type of objects that are kept in the cleanup.
Definition: ExprCXX.h:3478
static ExprWithCleanups * Create(const ASTContext &C, EmptyShell empty, unsigned numObjects)
Definition: ExprCXX.cpp:1444
This represents one expression.
Definition: Expr.h:110
void setType(QualType t)
Definition: Expr.h:143
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates).
Definition: Expr.h:239
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
Definition: Expr.h:444
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
ExprDependence getDependence() const
Definition: Expr.h:162
An expression trait intrinsic.
Definition: ExprCXX.h:2923
ExtVectorType - Extended vector type.
Definition: Type.h:4083
virtual void CompleteType(TagDecl *Tag)
Gives the external AST source an opportunity to complete an incomplete type.
Represents difference between two FPOptions values.
Definition: LangOptions.h:919
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4558
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
void setInClassInitializer(Expr *NewInit)
Set the C++11 in-class initializer for this member.
Definition: Decl.cpp:4568
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Definition: Decl.cpp:4663
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
bool isValid() const
bool isInvalid() const
Implements support for file system lookup, file system caching, and directory search management.
Definition: FileManager.h:53
OptionalFileEntryRef getOptionalFileRef(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Get a FileEntryRef if it exists, without doing anything on error.
Definition: FileManager.h:240
static FloatingLiteral * Create(const ASTContext &C, const llvm::APFloat &V, bool isexact, QualType Type, SourceLocation L)
Definition: Expr.cpp:1078
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2786
FriendDecl - Represents the declaration of a friend entity, which can be a function,...
Definition: DeclFriend.h:54
llvm::PointerUnion< NamedDecl *, TypeSourceInfo * > FriendUnion
Definition: DeclFriend.h:58
TypeSourceInfo * getFriendType() const
If this friend declaration names an (untemplated but possibly dependent) type, return the type; other...
Definition: DeclFriend.h:122
static DefaultedOrDeletedFunctionInfo * Create(ASTContext &Context, ArrayRef< DeclAccessPair > Lookups, StringLiteral *DeletedMessage=nullptr)
Definition: Decl.cpp:3084
Represents a function declaration or definition.
Definition: Decl.h:1932
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4035
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4030
void setIsPureVirtual(bool P=true)
Definition: Decl.cpp:3243
void setDefaultedOrDeletedInfo(DefaultedOrDeletedFunctionInfo *Info)
Definition: Decl.cpp:3105
void setFriendConstraintRefersToEnclosingTemplate(bool V=true)
Definition: Decl.h:2574
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4009
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:4160
void setDefaultLoc(SourceLocation NewLoc)
Definition: Decl.h:2327
DependentFunctionTemplateSpecializationInfo * getDependentSpecializationInfo() const
Definition: Decl.cpp:4225
@ TK_MemberSpecialization
Definition: Decl.h:1944
@ TK_DependentNonTemplate
Definition: Decl.h:1953
@ TK_FunctionTemplateSpecialization
Definition: Decl.h:1948
@ TK_DependentFunctionTemplateSpecialization
Definition: Decl.h:1951
void setTrivial(bool IT)
Definition: Decl.h:2303
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3981
void setInstantiatedFromDecl(FunctionDecl *FD)
Specify that this function declaration was instantiated from a FunctionDecl FD.
Definition: Decl.cpp:4048
void setDependentTemplateSpecialization(ASTContext &Context, const UnresolvedSetImpl &Templates, const TemplateArgumentListInfo *TemplateArgs)
Specifies that this function declaration is actually a dependent function template specialization.
Definition: Decl.cpp:4214
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2281
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2150
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4054
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template instantiation this function represents.
Definition: Decl.cpp:4254
void setDefaulted(bool D=true)
Definition: Decl.h:2311
void setBody(Stmt *B)
Definition: Decl.cpp:3236
void setDeletedAsWritten(bool D=true, StringLiteral *Message=nullptr)
Definition: Decl.cpp:3114
void setExplicitlyDefaulted(bool ED=true)
State that this function is explicitly defaulted.
Definition: Decl.h:2319
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4002
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Definition: Type.h:4638
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4973
QualType desugar() const
Definition: Type.h:5517
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5237
ArrayRef< QualType > exceptions() const
Definition: Type.h:5396
ArrayRef< QualType > param_types() const
Definition: Type.h:5382
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getMostRecentDecl()
ExtInfo getExtInfo() const
Definition: Type.h:4612
QualType getReturnType() const
Definition: Type.h:4600
This represents a GCC inline-assembly statement extension.
Definition: Stmt.h:3264
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4657
Represents a C11 generic selection.
Definition: Expr.h:5907
static GenericSelectionExpr * Create(const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr, ArrayRef< TypeSourceInfo * > AssocTypes, ArrayRef< Expr * > AssocExprs, SourceLocation DefaultLoc, SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
Create a non-result-dependent generic selection expression accepting an expression predicate.
Definition: Expr.cpp:4493
GotoStmt - This represents a direct goto.
Definition: Stmt.h:2867
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
void setBuiltinID(unsigned ID)
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2143
static IfStmt * Create(const ASTContext &Ctx, SourceLocation IL, IfStatementKind Kind, Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL, SourceLocation RPL, Stmt *Then, SourceLocation EL=SourceLocation(), Stmt *Else=nullptr)
Create an IfStmt.
Definition: Stmt.cpp:958
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5782
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4779
Represents a C array with an unspecified size.
Definition: Type.h:3725
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3314
IndirectGotoStmt - This represents an indirect goto.
Definition: Stmt.h:2906
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2506
CXXConstructorDecl * getConstructor() const
Definition: DeclCXX.h:2519
ConstructorUsingShadowDecl * getShadowDecl() const
Definition: DeclCXX.h:2518
Describes an C or C++ initializer list.
Definition: Expr.h:5029
void setSyntacticForm(InitListExpr *Init)
Definition: Expr.h:5199
void setArrayFiller(Expr *filler)
Definition: Expr.cpp:2419
void setInitializedFieldInUnion(FieldDecl *FD)
Definition: Expr.h:5154
void sawArrayRangeDesignator(bool ARD=true)
Definition: Expr.h:5209
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6605
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:977
An lvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3446
Represents the declaration of a label.
Definition: Decl.h:499
void setStmt(LabelStmt *T)
Definition: Decl.h:524
LabelStmt - Represents a label, which has a substatement.
Definition: Stmt.h:2036
Describes the capture of a variable or of this, or of a C++1y init-capture.
Definition: LambdaCapture.h:25
bool capturesVariable() const
Determine whether this capture handles a variable.
Definition: LambdaCapture.h:88
bool isPackExpansion() const
Determine whether this capture is a pack expansion, which captures a function parameter pack.
SourceLocation getEllipsisLoc() const
Retrieve the location of the ellipsis for a capture that is a pack expansion.
LambdaCaptureKind getCaptureKind() const
Determine the kind of capture.
Definition: ExprCXX.cpp:1243
ValueDecl * getCapturedVar() const
Retrieve the declaration of the local variable being captured.
bool isImplicit() const
Determine whether this was an implicit capture (not written between the square brackets introducing t...
SourceLocation getLocation() const
Retrieve the source location of the capture.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition: ExprCXX.cpp:1291
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition: DeclCXX.h:3229
Represents a linkage specification.
Definition: DeclCXX.h:2934
void setRBraceLoc(SourceLocation L)
Definition: DeclCXX.h:2976
Represents the results of name lookup.
Definition: Lookup.h:46
iterator end() const
Definition: Lookup.h:359
iterator begin() const
Definition: Lookup.h:358
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5636
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4726
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
static MemberExpr * Create(const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *MemberDecl, DeclAccessPair FoundDecl, DeclarationNameInfo MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR)
Definition: Expr.cpp:1754
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3482
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:660
This represents a decl that may have a name.
Definition: Decl.h:249
Linkage getLinkageInternal() const
Determine what kind of linkage this entity has.
Definition: Decl.cpp:1176
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
Represents a C++ namespace alias.
Definition: DeclCXX.h:3120
Represent a C++ namespace.
Definition: Decl.h:547
NamespaceDecl * getAnonymousNamespace() const
Retrieve the anonymous namespace that inhabits this namespace, if any.
Definition: Decl.h:630
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:649
Class that aids in the construction of nested-name-specifiers along with source-location information ...
A C++ nested-name-specifier augmented with source location information.
SourceLocation getLocalEndLoc() const
Retrieve the location of the end of this component of the nested-name-specifier.
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
SourceLocation getLocalBeginLoc() const
Retrieve the location of the beginning of this component of the nested-name-specifier.
SourceRange getSourceRange() const LLVM_READONLY
Retrieve the source range covering the entirety of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
CXXRecordDecl * getAsRecordDecl() const
Retrieve the record declaration stored in this nested name specifier.
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, const IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
NamespaceAliasDecl * getAsNamespaceAlias() const
Retrieve the namespace alias stored in this nested name specifier.
IdentifierInfo * getAsIdentifier() const
Retrieve the identifier stored in this nested name specifier.
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
SpecifierKind
The kind of specifier that completes this nested name specifier.
@ NamespaceAlias
A namespace alias, stored as a NamespaceAliasDecl*.
@ TypeSpec
A type, stored as a Type*.
@ TypeSpecWithTemplate
A type that was preceded by the 'template' keyword, stored as a Type*.
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
@ Identifier
An identifier, stored as an IdentifierInfo*.
@ Global
The global specifier '::'. There is no stored value.
@ Namespace
A namespace, stored as a NamespaceDecl*.
NamespaceDecl * getAsNamespace() const
Retrieve the namespace stored in this nested name specifier.
static NestedNameSpecifier * SuperSpecifier(const ASTContext &Context, CXXRecordDecl *RD)
Returns the nested name specifier representing the __super scope for the given CXXRecordDecl.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
NullStmt - This is the null statement ";": C99 6.8.3p3.
Definition: Stmt.h:1569
Represents Objective-C's @catch statement.
Definition: StmtObjC.h:77
Represents Objective-C's @finally statement.
Definition: StmtObjC.h:127
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:303
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:358
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:167
static ObjCAtTryStmt * Create(const ASTContext &Context, SourceLocation atTryLoc, Stmt *atTryStmt, Stmt **CatchStmts, unsigned NumCatchStmts, Stmt *atFinallyStmt)
Definition: StmtObjC.cpp:45
Represents Objective-C's @autoreleasepool Statement.
Definition: StmtObjC.h:394
An Objective-C "bridged" cast expression, which casts between Objective-C pointers and C pointers,...
Definition: ExprObjC.h:1636
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
void setTypeParamList(ObjCTypeParamList *TPL)
Set the type parameters of this category.
Definition: DeclObjC.cpp:2167
void setProtocolList(ObjCProtocolDecl *const *List, unsigned Num, const SourceLocation *Locs, ASTContext &C)
setProtocolList - Set the list of protocols that this interface implements.
Definition: DeclObjC.h:2388
void setImplementation(ObjCCategoryImplDecl *ImplD)
Definition: DeclObjC.cpp:2163
ObjCProtocolList::iterator protocol_iterator
Definition: DeclObjC.h:2397
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
Represents Objective-C's collection statement.
Definition: StmtObjC.h:23
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
const ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.h:2732
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
void setProtocolList(ObjCProtocolDecl *const *List, unsigned Num, const SourceLocation *Locs, ASTContext &C)
setProtocolList - Set the list of protocols that this interface implements.
Definition: DeclObjC.h:1484
ObjCCategoryDecl * FindCategoryDeclaration(const IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
Definition: DeclObjC.cpp:1748
protocol_loc_iterator protocol_loc_begin() const
Definition: DeclObjC.h:1391
void setImplementation(ObjCImplementationDecl *ImplD)
Definition: DeclObjC.cpp:1642
known_categories_range known_categories() const
Definition: DeclObjC.h:1686
void setSuperClass(TypeSourceInfo *superClass)
Definition: DeclObjC.h:1587
protocol_iterator protocol_end() const
Definition: DeclObjC.h:1373
SourceLocation getSuperClassLoc() const
Retrieve the starting location of the superclass.
Definition: DeclObjC.cpp:372
void setTypeParamList(ObjCTypeParamList *TPL)
Set the type parameters of this class.
Definition: DeclObjC.cpp:343
ObjCProtocolList::iterator protocol_iterator
Definition: DeclObjC.h:1355
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1629
protocol_iterator protocol_begin() const
Definition: DeclObjC.h:1362
void startDefinition()
Starts the definition of this Objective-C class, taking it from a forward declaration (@class) to a d...
Definition: DeclObjC.cpp:616
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1913
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1541
TypeSourceInfo * getSuperClassTInfo() const
Definition: DeclObjC.h:1572
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:7336
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
void setMethodParams(ASTContext &C, ArrayRef< ParmVarDecl * > Params, ArrayRef< SourceLocation > SelLocs=std::nullopt)
Sets the method's parameters and selector source locations.
Definition: DeclObjC.cpp:944
void createImplicitParams(ASTContext &Context, const ObjCInterfaceDecl *ID)
createImplicitParams - Used to lazily create the self and cmd implicit parameters.
Definition: DeclObjC.cpp:1190
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:350
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7392
Represents a class type in Objective C.
Definition: Type.h:7138
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
void setSetterName(Selector Sel, SourceLocation Loc=SourceLocation())
Definition: DeclObjC.h:895
void setPropertyAttributes(ObjCPropertyAttribute::Kind PRVal)
Definition: DeclObjC.h:818
void setPropertyAttributesAsWritten(ObjCPropertyAttribute::Kind PRVal)
Definition: DeclObjC.h:830
void setPropertyIvarDecl(ObjCIvarDecl *Ivar)
Definition: DeclObjC.h:919
void setSetterMethodDecl(ObjCMethodDecl *gDecl)
Definition: DeclObjC.h:904
void setGetterName(Selector Sel, SourceLocation Loc=SourceLocation())
Definition: DeclObjC.h:887
void setGetterMethodDecl(ObjCMethodDecl *gDecl)
Definition: DeclObjC.h:901
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:2876
SourceLocation getPropertyIvarDeclLoc() const
Definition: DeclObjC.h:2879
Kind getPropertyImplementation() const
Definition: DeclObjC.h:2872
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
void setProtocolList(ObjCProtocolDecl *const *List, unsigned Num, const SourceLocation *Locs, ASTContext &C)
setProtocolList - Set the list of protocols that this interface implements.
Definition: DeclObjC.h:2206
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2247
void startDefinition()
Starts the definition of this Objective-C protocol.
Definition: DeclObjC.cpp:2023
ObjCProtocolList::iterator protocol_iterator
Definition: DeclObjC.h:2155
protocol_iterator protocol_begin() const
Definition: DeclObjC.h:2162
protocol_iterator protocol_end() const
Definition: DeclObjC.h:2169
protocol_loc_iterator protocol_loc_begin() const
Definition: DeclObjC.h:2183
Represents the declaration of an Objective-C type parameter.
Definition: DeclObjC.h:578
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:659
SourceLocation getRAngleLoc() const
Definition: DeclObjC.h:710
static ObjCTypeParamList * create(ASTContext &ctx, SourceLocation lAngleLoc, ArrayRef< ObjCTypeParamDecl * > typeParams, SourceLocation rAngleLoc)
Create a new Objective-C type parameter list.
Definition: DeclObjC.cpp:1520
SourceLocation getLAngleLoc() const
Definition: DeclObjC.h:709
Represents a type parameter type in Objective C.
Definition: Type.h:7064
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2475
static OffsetOfExpr * Create(const ASTContext &C, QualType type, SourceLocation OperatorLoc, TypeSourceInfo *tsi, ArrayRef< OffsetOfNode > comps, ArrayRef< Expr * > exprs, SourceLocation RParenLoc)
Definition: Expr.cpp:1657
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition: Expr.h:2427
FieldDecl * getField() const
For a field offsetof node, returns the field.
Definition: Expr.h:2433
IdentifierInfo * getFieldName() const
For a field or identifier offsetof node, returns the name of the field.
Definition: Expr.cpp:1692
@ Array
An index into an array.
Definition: Expr.h:2374
@ Identifier
A field in a dependent type, known only by its name.
Definition: Expr.h:2378
@ Field
A field.
Definition: Expr.h:2376
@ Base
An implicit indirection through a C++ base class, when the field found is in a base class.
Definition: Expr.h:2381
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.h:2455
Kind getKind() const
Determine what kind of offsetof node this is.
Definition: Expr.h:2423
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Expr.h:2456
CXXBaseSpecifier * getBase() const
For a base class node, returns the base specifier.
Definition: Expr.h:2443
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
A structure for storing the information associated with an overloaded template name.
Definition: TemplateName.h:108
Represents a C++11 pack expansion that produces a sequence of expressions.
Definition: ExprCXX.h:4178
Represents a pack expansion of types.
Definition: Type.h:6953
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
static ParenListExpr * Create(const ASTContext &Ctx, SourceLocation LParenLoc, ArrayRef< Expr * > Exprs, SourceLocation RParenLoc)
Create a paren list.
Definition: Expr.cpp:4746
Sugar for parentheses used when specifying types.
Definition: Type.h:3135
Represents a parameter to a function.
Definition: Decl.h:1722
bool isKNRPromoted() const
True if the value passed to this parameter must undergo K&R-style default argument promotion:
Definition: Decl.h:1803
void setObjCDeclQualifier(ObjCDeclQualifier QTVal)
Definition: Decl.h:1790
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2968
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1818
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1863
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1851
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2993
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1855
void setObjCMethodScopeInfo(unsigned parameterIndex)
Definition: Decl.h:1750
bool hasInheritedDefaultArg() const
Definition: Decl.h:1867
void setKNRPromoted(bool promoted)
Definition: Decl.h:1806
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1814
Expr * getDefaultArg()
Definition: Decl.cpp:2956
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2998
bool hasDefaultArg() const
Determines whether this parameter has a default argument, either parsed or not.
Definition: Decl.cpp:3004
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1871
PipeType - OpenCL20.
Definition: Type.h:7592
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3161
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
static PredefinedExpr * Create(const ASTContext &Ctx, SourceLocation L, QualType FNTy, PredefinedIdentKind IK, bool IsTransparent, StringLiteral *SL)
Create a PredefinedExpr.
Definition: Expr.cpp:638
Stores the type being destroyed by a pseudo-destructor expression.
Definition: ExprCXX.h:2565
A (possibly-)qualified type.
Definition: Type.h:941
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7743
QualType getCanonicalType() const
Definition: Type.h:7795
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:7775
Represents a template name as written in source code.
Definition: TemplateName.h:434
TemplateName getUnderlyingTemplate() const
Return the underlying template name.
Definition: TemplateName.h:469
NestedNameSpecifier * getQualifier() const
Return the nested name specifier that qualifies this name.
Definition: TemplateName.h:462
bool hasTemplateKeyword() const
Whether the template name was prefixed by the "template" keyword.
Definition: TemplateName.h:466
An rvalue reference type, per C++11 [dcl.ref].
Definition: Type.h:3464
Represents a struct/union/class.
Definition: Decl.h:4141
bool isLambda() const
Determine whether this record is a class describing a lambda function object.
Definition: Decl.cpp:5028
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:4197
RecordDecl * getMostRecentDecl()
Definition: Decl.h:4167
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:5069
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4332
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5936
RecordDecl * getDecl() const
Definition: Type.h:5946
Provides common interface for the Decls that can be redeclared.
Definition: Redeclarable.h:84
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4974
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3402
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
static ReturnStmt * Create(const ASTContext &Ctx, SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
Create a return statement.
Definition: Stmt.cpp:1204
Selector getSelector(unsigned NumArgs, const IdentifierInfo **IIV)
Can create any sort of selector.
Smart pointer class that efficiently represents Objective-C method names.
const IdentifierInfo * getIdentifierInfoForSlot(unsigned argIndex) const
Retrieve the identifier at a given position in the selector.
bool isNull() const
Determine whether this is the empty selector.
unsigned getNumArgs() const
static std::enable_if_t< std::is_base_of_v< Attr, AttrInfo >, SourceLocation > getAttrLoc(const AttrInfo &AL)
A helper function to provide Attribute Location for the Attr types AND the ParsedAttr.
Definition: Sema.h:4409
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4455
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4256
static SizeOfPackExpr * Create(ASTContext &Context, SourceLocation OperatorLoc, NamedDecl *Pack, SourceLocation PackLoc, SourceLocation RParenLoc, std::optional< unsigned > Length=std::nullopt, ArrayRef< TemplateArgument > PartialArgs=std::nullopt)
Definition: ExprCXX.cpp:1691
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4751
Encodes a location in the source.
This class handles loading and caching of source files into memory.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
bool isWrittenInBuiltinFile(SourceLocation Loc) const
Returns whether Loc is located in a <built-in> file.
FileID createFileID(FileEntryRef SourceFile, SourceLocation IncludePos, SrcMgr::CharacteristicKind FileCharacter, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Create a new FileID that represents the specified file being #included from the specified IncludePosi...
SourceLocation getComposedLoc(FileID FID, unsigned Offset) const
Form a SourceLocation from a FileID and Offset pair.
FileManager & getFileManager() const
FileID getMainFileID() const
Returns the FileID of the main source file.
unsigned getFileIDSize(FileID FID) const
The size of the SLocEntry that FID represents.
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
SourceLocation getLocForStartOfFile(FileID FID) const
Return the source location corresponding to the first byte of the specified file.
SourceLocation createExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned Length, bool ExpansionIsTokenRange=true, int LoadedID=0, SourceLocation::UIntTy LoadedOffset=0)
Creates an expansion SLocEntry for a macro use.
const SrcMgr::SLocEntry & getSLocEntry(FileID FID, bool *Invalid=nullptr) const
SourceLocation createMacroArgExpansionLoc(SourceLocation SpellingLoc, SourceLocation ExpansionLoc, unsigned Length)
Creates an expansion SLocEntry for the substitution of an argument into a function-like macro's body.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
One instance of this struct is kept for every file loaded or used.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
SourceLocation getSpellingLoc() const
SourceLocation getExpansionLocEnd() const
const ContentCache & getContentCache() const
CharacteristicKind getFileCharacteristic() const
Return whether this is a system header or not.
SourceLocation getIncludeLoc() const
This is a discriminated union of FileInfo and ExpansionInfo.
const FileInfo & getFile() const
const ExpansionInfo & getExpansion() const
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4058
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4407
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Definition: StmtVisitor.h:185
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
child_iterator child_begin()
Definition: Stmt.h:1457
StmtClass getStmtClass() const
Definition: Stmt.h:1358
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:326
child_iterator child_end()
Definition: Stmt.h:1458
const char * getStmtClassName() const
Definition: Stmt.cpp:79
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4482
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
TemplateArgument getArgumentPack() const
Retrieve the template template argument pack with which this parameter was substituted.
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:156
A structure for storing the information associated with a substituted template template parameter.
Definition: TemplateName.h:375
std::optional< unsigned > getPackIndex() const
Definition: TemplateName.h:399
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: TemplateName.h:397
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: TemplateName.h:393
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6276
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6206
void setNextSwitchCase(SwitchCase *SC)
Definition: Stmt.h:1781
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2393
static SwitchStmt * Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a switch statement.
Definition: Stmt.cpp:1081
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3557
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3680
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3660
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3785
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4725
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4716
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4771
void setBraceRange(SourceRange R)
Definition: Decl.h:3637
void setCompleteDefinition(bool V=true)
True if this decl has its body fully specified.
Definition: Decl.h:3663
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
SourceLocation getRAngleLoc() const
Definition: TemplateBase.h:648
void addArgument(const TemplateArgumentLoc &Loc)
Definition: TemplateBase.h:667
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:659
SourceLocation getLAngleLoc() const
Definition: TemplateBase.h:647
A template argument list.
Definition: DeclTemplate.h:244
static TemplateArgumentList * CreateCopy(ASTContext &Context, ArrayRef< TemplateArgument > Args)
Create a new template argument list that copies the given set of template arguments.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
TemplateArgumentLocInfo getLocInfo() const
Definition: TemplateBase.h:576
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
QualType getStructuralValueType() const
Get the type of a StructuralValue.
Definition: TemplateBase.h:399
QualType getParamTypeForDecl() const
Definition: TemplateBase.h:331
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
std::optional< unsigned > getNumTemplateExpansions() const
Retrieve the number of expansions that a template template argument expansion will produce,...
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
QualType getNullPtrType() const
Retrieve the type for null non-type template argument.
Definition: TemplateBase.h:337
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
QualType getIntegralType() const
Retrieve the type of the integral value.
Definition: TemplateBase.h:377
bool getIsDefaulted() const
If returns 'true', this TemplateArgument corresponds to a default template parameter.
Definition: TemplateBase.h:393
ValueDecl * getAsDecl() const
Retrieve the declaration for a declaration non-type template argument.
Definition: TemplateBase.h:326
ArrayRef< TemplateArgument > pack_elements() const
Iterator range referencing all of the elements of a template argument pack.
Definition: TemplateBase.h:432
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ StructuralValue
The template argument is a non-type template argument that can't be represented by the special-case D...
Definition: TemplateBase.h:89
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ TemplateExpansion
The template argument is a pack expansion of a template name that was provided for a template templat...
Definition: TemplateBase.h:97
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Null
Represents an empty template argument, e.g., one that has not been deduced.
Definition: TemplateBase.h:67
@ Integral
The template argument is an integral value stored in an llvm::APSInt that was provided for an integra...
Definition: TemplateBase.h:82
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
TemplateName getAsTemplateOrTemplatePattern() const
Retrieve the template argument as a template name; if the argument is a pack expansion,...
Definition: TemplateBase.h:350
const APValue & getAsStructuralValue() const
Get the value of a StructuralValue.
Definition: TemplateBase.h:396
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
DependentTemplateName * getAsDependentTemplateName() const
Retrieve the underlying dependent template name structure, if any.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
OverloadedTemplateStorage * getAsOverloadedTemplate() const
Retrieve the underlying, overloaded function template declarations that this template name refers to,...
AssumedTemplateStorage * getAsAssumedTemplateName() const
Retrieve information on a name that has been assumed to be a template-name in order to permit a call ...
NameKind getKind() const
@ UsingTemplate
A template name that refers to a template declaration found through a specific using shadow declarati...
Definition: TemplateName.h:248
@ OverloadedTemplate
A set of overloaded template declarations.
Definition: TemplateName.h:223
@ Template
A single template declaration.
Definition: TemplateName.h:220
@ DependentTemplate
A dependent template name that has not been resolved to a template (or set of templates).
Definition: TemplateName.h:235
@ SubstTemplateTemplateParm
A template template parameter that has been substituted for some other template name.
Definition: TemplateName.h:239
@ SubstTemplateTemplateParmPack
A template template parameter pack that has been substituted for a template template argument pack,...
Definition: TemplateName.h:244
@ QualifiedTemplate
A qualified template name, where the qualification is kept to describe the source code as written.
Definition: TemplateName.h:231
@ AssumedTemplate
An unqualified-id that has been assumed to name a function template that will be found by ADL.
Definition: TemplateName.h:227
UsingShadowDecl * getAsUsingShadowDecl() const
Retrieve the using shadow declaration through which the underlying template declaration is introduced...
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
SubstTemplateTemplateParmStorage * getAsSubstTemplateTemplateParm() const
Retrieve the substituted template template parameter, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
Expr * getRequiresClause()
The constraint-expression of the associated requires-clause.
Definition: DeclTemplate.h:180
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:201
SourceLocation getLAngleLoc() const
Definition: DeclTemplate.h:200
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6473
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter, and whether that default argument was inherited...
Declaration of a template type parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
void setDefaultArgument(const ASTContext &C, const TemplateArgumentLoc &DefArg)
Set the default argument for this template parameter.
The top declaration context.
Definition: Decl.h:84
Represents the declaration of a typedef-name via a C++11 alias-declaration.
Definition: Decl.h:3528
TypeAliasTemplateDecl * getDescribedAliasTemplate() const
Definition: Decl.h:3546
Declaration of an alias template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:228
[BoundsSafety] Represents information of declarations referenced by the arguments of the counted_by a...
Definition: Type.h:3189
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3388
const Type * getTypeForDecl() const
Definition: Decl.h:3387
Symbolic representation of typeid(T) for some type T.
Definition: APValue.h:44
const Type * getType() const
Definition: APValue.h:51
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
Definition: Type.h:5668
Represents typeof(type), a C23 feature and GCC extension, or `typeof_unqual(type),...
Definition: Type.h:5718
The type-property cache.
Definition: Type.cpp:4430
A container of type source information.
Definition: Type.h:7714
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7725
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2767
static TypeTraitExpr * Create(const ASTContext &C, QualType T, SourceLocation Loc, TypeTrait Kind, ArrayRef< TypeSourceInfo * > Args, SourceLocation RParenLoc, bool Value)
Create a new type trait expression.
Definition: ExprCXX.cpp:1874
An operation on a type.
Definition: TypeVisitor.h:64
ExpectedType Visit(const Type *T)
Performs the operation associated with this visitor object.
Definition: TypeVisitor.h:68
The base class of the type hierarchy.
Definition: Type.h:1829
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:8473
bool isArrayType() const
Definition: Type.h:8064
bool isPointerType() const
Definition: Type.h:7996
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2672
QualType getCanonicalTypeInternal() const
Definition: Type.h:2955
const char * getTypeClassName() const
Definition: Type.cpp:3270
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8466
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
Definition: Type.h:2342
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8516
bool isRecordType() const
Definition: Type.h:8092
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3507
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
static UnaryOperator * CreateEmpty(const ASTContext &C, bool hasFPFeatures)
Definition: Expr.cpp:4840
A unary type transform, which is a type constructed from another.
Definition: Type.h:5853
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition: ExprCXX.h:3202
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, UnresolvedSetIterator Begin, UnresolvedSetIterator End, bool KnownDependent)
Definition: ExprCXX.cpp:419
Represents a C++ member access expression for which lookup produced a set of overloaded functions.
Definition: ExprCXX.h:3941
static UnresolvedMemberExpr * Create(const ASTContext &Context, bool HasUnresolvedUsing, Expr *Base, QualType BaseType, bool IsArrow, SourceLocation OperatorLoc, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, const DeclarationNameInfo &MemberNameInfo, const TemplateArgumentListInfo *TemplateArgs, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:1633
void addDecl(NamedDecl *D)
Definition: UnresolvedSet.h:92
A set of unresolved declarations.
Represents the dependent type named by a dependently-scoped typename using declaration,...
Definition: Type.h:5538
Represents a dependent using declaration which was marked with typename.
Definition: DeclCXX.h:3959
Represents a dependent using declaration which was not marked with typename.
Definition: DeclCXX.h:3862
Represents a C++ using-declaration.
Definition: DeclCXX.h:3512
Represents C++ using-directive.
Definition: DeclCXX.h:3015
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3713
Represents a pack of using declarations that a single using-declarator pack-expanded into.
Definition: DeclCXX.h:3794
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3320
Represents a call to the builtin function __builtin_va_arg.
Definition: Expr.h:4691
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
void setInstantiationOfStaticDataMember(VarDecl *VD, TemplateSpecializationKind TSK)
Specify that this variable is an instantiation of the static data member VD.
Definition: Decl.cpp:2892
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
EvaluatedStmt * getEvaluatedStmt() const
Definition: Decl.cpp:2535
EvaluatedStmt * ensureEvaluatedStmt() const
Convert the initializer for this declaration to the elaborated EvaluatedStmt form,...
Definition: Decl.cpp:2521
void setInlineSpecified()
Definition: Decl.h:1499
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1121
const Expr * getInit() const
Definition: Decl.h:1316
void setConstexpr(bool IC)
Definition: Decl.h:1513
void setInit(Expr *I)
Definition: Decl.cpp:2442
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2780
void setImplicitlyInline()
Definition: Decl.h:1504
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1306
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2855
Declaration of a variable template.
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos)
Insert the specified specialization knowing that it is not already in.
VarTemplateSpecializationDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
VarTemplateDecl * getMostRecentDecl()
void setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec)
Represents a variable template specialization, which refers to a variable template with a given set o...
void setTemplateArgsAsWritten(const ASTTemplateArgumentListInfo *ArgsWritten)
Set the template argument list as written in the sources.
void setSpecializationKind(TemplateSpecializationKind TSK)
void setPointOfInstantiation(SourceLocation Loc)
VarTemplateSpecializationDecl * getMostRecentDecl()
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3769
Represents a GCC generic vector type.
Definition: Type.h:3991
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2589
static WhileStmt * Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond, Stmt *Body, SourceLocation WL, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a while statement.
Definition: Stmt.cpp:1143
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition: Address.h:328
StructuralEquivalenceKind
Whether to perform a normal or minimal equivalence check.
CanThrowResult
Possible results from evaluation of a noexcept expression.
void updateFlags(const Decl *From, Decl *To)
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Definition: Specifiers.h:146
@ Property
The type of a property.
@ Result
The result type of a method or function.
@ BTK__type_pack_element
This names the __type_pack_element BuiltinTemplateDecl.
Definition: Builtins.h:312
@ BTK__make_integer_seq
This names the __make_integer_seq BuiltinTemplateDecl.
Definition: Builtins.h:309
CastKind
CastKind - The kind of operation required for a conversion.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
Definition: Specifiers.h:129
const FunctionProtoType * T
llvm::SmallVector< Decl *, 2 > getCanonicalForwardRedeclChain(Decl *D)
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1264
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
#define false
Definition: stdbool.h:26
Used as return type of getFriendCountAndPosition.
unsigned int IndexOfDecl
Index of the specific FriendDecl.
unsigned int TotalCount
Number of similar looking friends.
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
static const ASTTemplateArgumentListInfo * Create(const ASTContext &C, const TemplateArgumentListInfo &List)
Information about how a lambda is numbered within its context.
Definition: DeclCXX.h:1798
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
TypeSourceInfo * getNamedTypeInfo() const
getNamedTypeInfo - Returns the source type info associated to the name.
SourceLocation getCXXLiteralOperatorNameLoc() const
getCXXLiteralOperatorNameLoc - Returns the location of the literal operator name (not the operator ke...
Structure used to store a statement, the constant value to which it was evaluated (if any),...
Definition: Decl.h:844
bool HasConstantDestruction
Whether this variable is known to have constant destruction.
Definition: Decl.h:862
bool HasConstantInitialization
Whether this variable is known to have constant initialization.
Definition: Decl.h:855
FunctionDecl * SourceDecl
The function whose exception specification this is, for EST_Unevaluated and EST_Uninstantiated.
Definition: Type.h:5042
FunctionDecl * SourceTemplate
The function template whose exception specification this is instantiated from, for EST_Uninstantiated...
Definition: Type.h:5046
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5032
ArrayRef< QualType > Exceptions
Explicitly-specified list of exception types.
Definition: Type.h:5035
Expr * NoexceptExpr
Noexcept expression, if this is a computed noexcept specification.
Definition: Type.h:5038
Extra information about a function prototype.
Definition: Type.h:5058
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5065
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5059
bool IsEquivalent(Decl *D1, Decl *D2)
Determine whether the two declarations are structurally equivalent.
Location information for a TemplateArgument.
Definition: TemplateBase.h:472
SourceLocation getTemplateEllipsisLoc() const
Definition: TemplateBase.h:517
NestedNameSpecifierLoc getTemplateQualifierLoc() const
Definition: TemplateBase.h:507
TypeSourceInfo * getAsTypeSourceInfo() const
Definition: TemplateBase.h:501
SourceLocation getTemplateNameLoc() const
Definition: TemplateBase.h:513