Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 5640, column 16
Called C++ object pointer is uninitialized

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp

1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTImporter class which imports AST nodes from one
10// context into another context.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTImporter.h"
15#include "clang/AST/ASTImporterSharedState.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTDiagnostic.h"
18#include "clang/AST/ASTStructuralEquivalence.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclAccessPair.h"
22#include "clang/AST/DeclBase.h"
23#include "clang/AST/DeclCXX.h"
24#include "clang/AST/DeclFriend.h"
25#include "clang/AST/DeclGroup.h"
26#include "clang/AST/DeclObjC.h"
27#include "clang/AST/DeclTemplate.h"
28#include "clang/AST/DeclVisitor.h"
29#include "clang/AST/DeclarationName.h"
30#include "clang/AST/Expr.h"
31#include "clang/AST/ExprCXX.h"
32#include "clang/AST/ExprObjC.h"
33#include "clang/AST/ExternalASTSource.h"
34#include "clang/AST/LambdaCapture.h"
35#include "clang/AST/NestedNameSpecifier.h"
36#include "clang/AST/OperationKinds.h"
37#include "clang/AST/Stmt.h"
38#include "clang/AST/StmtCXX.h"
39#include "clang/AST/StmtObjC.h"
40#include "clang/AST/StmtVisitor.h"
41#include "clang/AST/TemplateBase.h"
42#include "clang/AST/TemplateName.h"
43#include "clang/AST/Type.h"
44#include "clang/AST/TypeLoc.h"
45#include "clang/AST/TypeVisitor.h"
46#include "clang/AST/UnresolvedSet.h"
47#include "clang/Basic/Builtins.h"
48#include "clang/Basic/ExceptionSpecificationType.h"
49#include "clang/Basic/FileManager.h"
50#include "clang/Basic/IdentifierTable.h"
51#include "clang/Basic/LLVM.h"
52#include "clang/Basic/LangOptions.h"
53#include "clang/Basic/SourceLocation.h"
54#include "clang/Basic/SourceManager.h"
55#include "clang/Basic/Specifiers.h"
56#include "llvm/ADT/APSInt.h"
57#include "llvm/ADT/ArrayRef.h"
58#include "llvm/ADT/DenseMap.h"
59#include "llvm/ADT/None.h"
60#include "llvm/ADT/Optional.h"
61#include "llvm/ADT/ScopeExit.h"
62#include "llvm/ADT/STLExtras.h"
63#include "llvm/ADT/SmallVector.h"
64#include "llvm/Support/Casting.h"
65#include "llvm/Support/ErrorHandling.h"
66#include "llvm/Support/MemoryBuffer.h"
67#include <algorithm>
68#include <cassert>
69#include <cstddef>
70#include <memory>
71#include <type_traits>
72#include <utility>
73
74namespace clang {
75
76 using llvm::make_error;
77 using llvm::Error;
78 using llvm::Expected;
79 using ExpectedType = llvm::Expected<QualType>;
80 using ExpectedStmt = llvm::Expected<Stmt *>;
81 using ExpectedExpr = llvm::Expected<Expr *>;
82 using ExpectedDecl = llvm::Expected<Decl *>;
83 using ExpectedSLoc = llvm::Expected<SourceLocation>;
84 using ExpectedName = llvm::Expected<DeclarationName>;
85
86 std::string ImportError::toString() const {
87 // FIXME: Improve error texts.
88 switch (Error) {
89 case NameConflict:
90 return "NameConflict";
91 case UnsupportedConstruct:
92 return "UnsupportedConstruct";
93 case Unknown:
94 return "Unknown error";
95 }
96 llvm_unreachable("Invalid error code.")::llvm::llvm_unreachable_internal("Invalid error code.", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 96)
;
97 return "Invalid error code.";
98 }
99
100 void ImportError::log(raw_ostream &OS) const {
101 OS << toString();
102 }
103
104 std::error_code ImportError::convertToErrorCode() const {
105 llvm_unreachable("Function not implemented.")::llvm::llvm_unreachable_internal("Function not implemented."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 105)
;
106 }
107
108 char ImportError::ID;
109
110 template <class T>
111 SmallVector<Decl *, 2>
112 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
113 SmallVector<Decl *, 2> Redecls;
114 for (auto *R : D->getFirstDecl()->redecls()) {
115 if (R != D->getFirstDecl())
116 Redecls.push_back(R);
117 }
118 Redecls.push_back(D->getFirstDecl());
119 std::reverse(Redecls.begin(), Redecls.end());
120 return Redecls;
121 }
122
123 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
124 if (auto *FD = dyn_cast<FunctionDecl>(D))
125 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
126 if (auto *VD = dyn_cast<VarDecl>(D))
127 return getCanonicalForwardRedeclChain<VarDecl>(VD);
128 if (auto *TD = dyn_cast<TagDecl>(D))
129 return getCanonicalForwardRedeclChain<TagDecl>(TD);
130 llvm_unreachable("Bad declaration kind")::llvm::llvm_unreachable_internal("Bad declaration kind", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 130)
;
131 }
132
133 void updateFlags(const Decl *From, Decl *To) {
134 // Check if some flags or attrs are new in 'From' and copy into 'To'.
135 // FIXME: Other flags or attrs?
136 if (From->isUsed(false) && !To->isUsed(false))
137 To->setIsUsed();
138 }
139
140 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
141 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
142 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
143 ASTImporter &Importer;
144
145 // Use this instead of Importer.importInto .
146 template <typename ImportT>
147 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT &To, const ImportT &From) {
148 return Importer.importInto(To, From);
149 }
150
151 // Use this to import pointers of specific type.
152 template <typename ImportT>
153 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT *&To, ImportT *From) {
154 auto ToOrErr = Importer.Import(From);
155 if (ToOrErr)
13
Taking false branch
156 To = cast_or_null<ImportT>(*ToOrErr);
157 return ToOrErr.takeError();
14
Returning without writing to 'To'
158 }
159
160 // Call the import function of ASTImporter for a baseclass of type `T` and
161 // cast the return value to `T`.
162 template <typename T>
163 Expected<T *> import(T *From) {
164 auto ToOrErr = Importer.Import(From);
1
Calling 'ASTImporter::Import'
165 if (!ToOrErr)
166 return ToOrErr.takeError();
167 return cast_or_null<T>(*ToOrErr);
168 }
169
170 template <typename T>
171 Expected<T *> import(const T *From) {
172 return import(const_cast<T *>(From));
173 }
174
175 // Call the import function of ASTImporter for type `T`.
176 template <typename T>
177 Expected<T> import(const T &From) {
178 return Importer.Import(From);
179 }
180
181 // Import an Optional<T> by importing the contained T, if any.
182 template<typename T>
183 Expected<Optional<T>> import(Optional<T> From) {
184 if (!From)
185 return Optional<T>();
186 return import(*From);
187 }
188
189 // Helper for chaining together multiple imports. If an error is detected,
190 // subsequent imports will return default constructed nodes, so that failure
191 // can be detected with a single conditional branch after a sequence of
192 // imports.
193 template <typename T> T importChecked(Error &Err, const T &From) {
194 // Don't attempt to import nodes if we hit an error earlier.
195 if (Err)
196 return T{};
197 Expected<T> MaybeVal = import(From);
198 if (!MaybeVal) {
199 Err = MaybeVal.takeError();
200 return T{};
201 }
202 return *MaybeVal;
203 }
204
205 ExplicitSpecifier importExplicitSpecifier(Error &Err,
206 ExplicitSpecifier ESpec);
207
208 // Wrapper for an overload set.
209 template <typename ToDeclT> struct CallOverloadedCreateFun {
210 template <typename... Args> decltype(auto) operator()(Args &&... args) {
211 return ToDeclT::Create(std::forward<Args>(args)...);
212 }
213 };
214
215 // Always use these functions to create a Decl during import. There are
216 // certain tasks which must be done after the Decl was created, e.g. we
217 // must immediately register that as an imported Decl. The parameter `ToD`
218 // will be set to the newly created Decl or if had been imported before
219 // then to the already imported Decl. Returns a bool value set to true if
220 // the `FromD` had been imported before.
221 template <typename ToDeclT, typename FromDeclT, typename... Args>
222 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
223 Args &&... args) {
224 // There may be several overloads of ToDeclT::Create. We must make sure
225 // to call the one which would be chosen by the arguments, thus we use a
226 // wrapper for the overload set.
227 CallOverloadedCreateFun<ToDeclT> OC;
228 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
229 std::forward<Args>(args)...);
230 }
231 // Use this overload if a special Type is needed to be created. E.g if we
232 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
233 // then:
234 // TypedefNameDecl *ToTypedef;
235 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
236 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
237 typename... Args>
238 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
239 Args &&... args) {
240 CallOverloadedCreateFun<NewDeclT> OC;
241 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
242 std::forward<Args>(args)...);
243 }
244 // Use this version if a special create function must be
245 // used, e.g. CXXRecordDecl::CreateLambda .
246 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
247 typename... Args>
248 LLVM_NODISCARD[[clang::warn_unused_result]] bool
249 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
250 FromDeclT *FromD, Args &&... args) {
251 if (Importer.getImportDeclErrorIfAny(FromD)) {
252 ToD = nullptr;
253 return true; // Already imported but with error.
254 }
255 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
256 if (ToD)
257 return true; // Already imported.
258 ToD = CreateFun(std::forward<Args>(args)...);
259 // Keep track of imported Decls.
260 Importer.RegisterImportedDecl(FromD, ToD);
261 InitializeImportedDecl(FromD, ToD);
262 return false; // A new Decl is created.
263 }
264
265 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
266 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
267 if (FromD->isUsed())
268 ToD->setIsUsed();
269 if (FromD->isImplicit())
270 ToD->setImplicit();
271 }
272
273 // Check if we have found an existing definition. Returns with that
274 // definition if yes, otherwise returns null.
275 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
276 const FunctionDecl *Definition = nullptr;
277 if (D->doesThisDeclarationHaveABody() &&
278 FoundFunction->hasBody(Definition))
279 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
280 return nullptr;
281 }
282
283 void addDeclToContexts(Decl *FromD, Decl *ToD) {
284 if (Importer.isMinimalImport()) {
285 // In minimal import case the decl must be added even if it is not
286 // contained in original context, for LLDB compatibility.
287 // FIXME: Check if a better solution is possible.
288 if (!FromD->getDescribedTemplate() &&
289 FromD->getFriendObjectKind() == Decl::FOK_None)
290 ToD->getLexicalDeclContext()->addDeclInternal(ToD);
291 return;
292 }
293
294 DeclContext *FromDC = FromD->getDeclContext();
295 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext();
296 DeclContext *ToDC = ToD->getDeclContext();
297 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext();
298
299 bool Visible = false;
300 if (FromDC->containsDeclAndLoad(FromD)) {
301 ToDC->addDeclInternal(ToD);
302 Visible = true;
303 }
304 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) {
305 ToLexicalDC->addDeclInternal(ToD);
306 Visible = true;
307 }
308
309 // If the Decl was added to any context, it was made already visible.
310 // Otherwise it is still possible that it should be visible.
311 if (!Visible) {
312 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) {
313 auto *ToNamed = cast<NamedDecl>(ToD);
314 DeclContextLookupResult FromLookup =
315 FromDC->lookup(FromNamed->getDeclName());
316 for (NamedDecl *ND : FromLookup)
317 if (ND == FromNamed) {
318 ToDC->makeDeclVisibleInContext(ToNamed);
319 break;
320 }
321 }
322 }
323 }
324
325 void updateLookupTableForTemplateParameters(TemplateParameterList &Params,
326 DeclContext *OldDC) {
327 ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable();
328 if (!LT)
329 return;
330
331 for (NamedDecl *TP : Params)
332 LT->update(TP, OldDC);
333 }
334
335 void updateLookupTableForTemplateParameters(TemplateParameterList &Params) {
336 updateLookupTableForTemplateParameters(
337 Params, Importer.getToContext().getTranslationUnitDecl());
338 }
339
340 public:
341 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
342
343 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
344 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
345 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
346
347 // Importing types
348 ExpectedType VisitType(const Type *T);
349 ExpectedType VisitAtomicType(const AtomicType *T);
350 ExpectedType VisitBuiltinType(const BuiltinType *T);
351 ExpectedType VisitDecayedType(const DecayedType *T);
352 ExpectedType VisitComplexType(const ComplexType *T);
353 ExpectedType VisitPointerType(const PointerType *T);
354 ExpectedType VisitBlockPointerType(const BlockPointerType *T);
355 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
356 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
357 ExpectedType VisitMemberPointerType(const MemberPointerType *T);
358 ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
359 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
360 ExpectedType VisitVariableArrayType(const VariableArrayType *T);
361 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
362 // FIXME: DependentSizedExtVectorType
363 ExpectedType VisitVectorType(const VectorType *T);
364 ExpectedType VisitExtVectorType(const ExtVectorType *T);
365 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
366 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
367 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
368 ExpectedType VisitParenType(const ParenType *T);
369 ExpectedType VisitTypedefType(const TypedefType *T);
370 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
371 // FIXME: DependentTypeOfExprType
372 ExpectedType VisitTypeOfType(const TypeOfType *T);
373 ExpectedType VisitDecltypeType(const DecltypeType *T);
374 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
375 ExpectedType VisitAutoType(const AutoType *T);
376 ExpectedType VisitDeducedTemplateSpecializationType(
377 const DeducedTemplateSpecializationType *T);
378 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
379 // FIXME: DependentDecltypeType
380 ExpectedType VisitRecordType(const RecordType *T);
381 ExpectedType VisitEnumType(const EnumType *T);
382 ExpectedType VisitAttributedType(const AttributedType *T);
383 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
384 ExpectedType VisitSubstTemplateTypeParmType(
385 const SubstTemplateTypeParmType *T);
386 ExpectedType VisitTemplateSpecializationType(
387 const TemplateSpecializationType *T);
388 ExpectedType VisitElaboratedType(const ElaboratedType *T);
389 ExpectedType VisitDependentNameType(const DependentNameType *T);
390 ExpectedType VisitPackExpansionType(const PackExpansionType *T);
391 ExpectedType VisitDependentTemplateSpecializationType(
392 const DependentTemplateSpecializationType *T);
393 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
394 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
395 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
396
397 // Importing declarations
398 Error ImportDeclParts(NamedDecl *D, DeclarationName &Name, NamedDecl *&ToD,
399 SourceLocation &Loc);
400 Error ImportDeclParts(
401 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
402 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
403 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
404 Error ImportDeclarationNameLoc(
405 const DeclarationNameInfo &From, DeclarationNameInfo &To);
406 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
407 Error ImportDeclContext(
408 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
409 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
410
411 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
412 Expected<APValue> ImportAPValue(const APValue &FromValue);
413
414 using Designator = DesignatedInitExpr::Designator;
415
416 /// What we should import from the definition.
417 enum ImportDefinitionKind {
418 /// Import the default subset of the definition, which might be
419 /// nothing (if minimal import is set) or might be everything (if minimal
420 /// import is not set).
421 IDK_Default,
422 /// Import everything.
423 IDK_Everything,
424 /// Import only the bare bones needed to establish a valid
425 /// DeclContext.
426 IDK_Basic
427 };
428
429 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
430 return IDK == IDK_Everything ||
431 (IDK == IDK_Default && !Importer.isMinimalImport());
432 }
433
434 Error ImportInitializer(VarDecl *From, VarDecl *To);
435 Error ImportDefinition(
436 RecordDecl *From, RecordDecl *To,
437 ImportDefinitionKind Kind = IDK_Default);
438 Error ImportDefinition(
439 EnumDecl *From, EnumDecl *To,
440 ImportDefinitionKind Kind = IDK_Default);
441 Error ImportDefinition(
442 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
443 ImportDefinitionKind Kind = IDK_Default);
444 Error ImportDefinition(
445 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
446 ImportDefinitionKind Kind = IDK_Default);
447 Error ImportTemplateArguments(
448 const TemplateArgument *FromArgs, unsigned NumFromArgs,
449 SmallVectorImpl<TemplateArgument> &ToArgs);
450 Expected<TemplateArgument>
451 ImportTemplateArgument(const TemplateArgument &From);
452
453 template <typename InContainerTy>
454 Error ImportTemplateArgumentListInfo(
455 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
456
457 template<typename InContainerTy>
458 Error ImportTemplateArgumentListInfo(
459 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
460 const InContainerTy &Container, TemplateArgumentListInfo &Result);
461
462 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
463 using FunctionTemplateAndArgsTy =
464 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
465 Expected<FunctionTemplateAndArgsTy>
466 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
467 FunctionDecl *FromFD);
468 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
469 DeclaratorDecl *ToD);
470
471 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
472
473 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
474
475 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam,
476 ParmVarDecl *ToParam);
477
478 template <typename T>
479 bool hasSameVisibilityContextAndLinkage(T *Found, T *From);
480
481 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
482 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
483 bool Complain = true);
484 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
485 bool Complain = true);
486 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
487 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
488 bool IsStructuralMatch(FunctionTemplateDecl *From,
489 FunctionTemplateDecl *To);
490 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
491 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
492 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
493 ExpectedDecl VisitDecl(Decl *D);
494 ExpectedDecl VisitImportDecl(ImportDecl *D);
495 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
496 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
497 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
498 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
499 ExpectedDecl VisitBindingDecl(BindingDecl *D);
500 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
501 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
502 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
503 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
504 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
505 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
506 ExpectedDecl VisitLabelDecl(LabelDecl *D);
507 ExpectedDecl VisitEnumDecl(EnumDecl *D);
508 ExpectedDecl VisitRecordDecl(RecordDecl *D);
509 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
510 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
511 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
512 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
513 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
514 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
515 ExpectedDecl VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D);
516 ExpectedDecl VisitFieldDecl(FieldDecl *D);
517 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
518 ExpectedDecl VisitFriendDecl(FriendDecl *D);
519 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
520 ExpectedDecl VisitVarDecl(VarDecl *D);
521 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
522 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
523 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
524 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
525 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
526 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
527 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
528 ExpectedDecl VisitUsingDecl(UsingDecl *D);
529 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
530 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
531 ExpectedDecl ImportUsingShadowDecls(BaseUsingDecl *D, BaseUsingDecl *ToSI);
532 ExpectedDecl VisitUsingEnumDecl(UsingEnumDecl *D);
533 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
534 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
535 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
536 ExpectedDecl
537 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
538
539 Expected<ObjCTypeParamList *>
540 ImportObjCTypeParamList(ObjCTypeParamList *list);
541
542 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
543 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
544 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
545 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
546 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
547 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
548 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
549 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
550 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
551 ExpectedDecl VisitClassTemplateSpecializationDecl(
552 ClassTemplateSpecializationDecl *D);
553 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
554 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
555 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
556
557 // Importing statements
558 ExpectedStmt VisitStmt(Stmt *S);
559 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
560 ExpectedStmt VisitDeclStmt(DeclStmt *S);
561 ExpectedStmt VisitNullStmt(NullStmt *S);
562 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
563 ExpectedStmt VisitCaseStmt(CaseStmt *S);
564 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
565 ExpectedStmt VisitLabelStmt(LabelStmt *S);
566 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
567 ExpectedStmt VisitIfStmt(IfStmt *S);
568 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
569 ExpectedStmt VisitWhileStmt(WhileStmt *S);
570 ExpectedStmt VisitDoStmt(DoStmt *S);
571 ExpectedStmt VisitForStmt(ForStmt *S);
572 ExpectedStmt VisitGotoStmt(GotoStmt *S);
573 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
574 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
575 ExpectedStmt VisitBreakStmt(BreakStmt *S);
576 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
577 // FIXME: MSAsmStmt
578 // FIXME: SEHExceptStmt
579 // FIXME: SEHFinallyStmt
580 // FIXME: SEHTryStmt
581 // FIXME: SEHLeaveStmt
582 // FIXME: CapturedStmt
583 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
584 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
585 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
586 // FIXME: MSDependentExistsStmt
587 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
588 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
589 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
590 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
591 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
592 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
593 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
594
595 // Importing expressions
596 ExpectedStmt VisitExpr(Expr *E);
597 ExpectedStmt VisitSourceLocExpr(SourceLocExpr *E);
598 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
599 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
600 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
601 ExpectedStmt VisitGenericSelectionExpr(GenericSelectionExpr *E);
602 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
603 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
604 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
605 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
606 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
607 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
608 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
609 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
610 ExpectedStmt VisitFixedPointLiteral(FixedPointLiteral *E);
611 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
612 ExpectedStmt VisitStringLiteral(StringLiteral *E);
613 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
614 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
615 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
616 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
617 ExpectedStmt VisitParenExpr(ParenExpr *E);
618 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
619 ExpectedStmt VisitStmtExpr(StmtExpr *E);
620 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
621 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
622 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
623 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
624 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
625 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
626 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
627 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
628 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
629 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
630 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
631 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
632 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
633 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
634 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
635 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
636 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
637 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
638 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
639 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
640 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
641 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
642 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
643 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
644 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
645 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
646 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
647 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
648 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
649 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
650 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
651 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
652 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
653 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
654 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
655 ExpectedStmt VisitMemberExpr(MemberExpr *E);
656 ExpectedStmt VisitCallExpr(CallExpr *E);
657 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
658 ExpectedStmt VisitInitListExpr(InitListExpr *E);
659 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
660 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
661 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
662 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
663 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
664 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
665 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
666 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
667 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
668 ExpectedStmt VisitCXXFoldExpr(CXXFoldExpr *E);
669
670 template<typename IIter, typename OIter>
671 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
672 using ItemT = std::remove_reference_t<decltype(*Obegin)>;
673 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
674 Expected<ItemT> ToOrErr = import(*Ibegin);
675 if (!ToOrErr)
676 return ToOrErr.takeError();
677 *Obegin = *ToOrErr;
678 }
679 return Error::success();
680 }
681
682 // Import every item from a container structure into an output container.
683 // If error occurs, stops at first error and returns the error.
684 // The output container should have space for all needed elements (it is not
685 // expanded, new items are put into from the beginning).
686 template<typename InContainerTy, typename OutContainerTy>
687 Error ImportContainerChecked(
688 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
689 return ImportArrayChecked(
690 InContainer.begin(), InContainer.end(), OutContainer.begin());
691 }
692
693 template<typename InContainerTy, typename OIter>
694 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
695 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
696 }
697
698 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod,
699 CXXMethodDecl *FromMethod);
700
701 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
702 FunctionDecl *FromFD);
703
704 // Returns true if the given function has a placeholder return type and
705 // that type is declared inside the body of the function.
706 // E.g. auto f() { struct X{}; return X(); }
707 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D);
708 };
709
710template <typename InContainerTy>
711Error ASTNodeImporter::ImportTemplateArgumentListInfo(
712 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
713 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
714 auto ToLAngleLocOrErr = import(FromLAngleLoc);
715 if (!ToLAngleLocOrErr)
716 return ToLAngleLocOrErr.takeError();
717 auto ToRAngleLocOrErr = import(FromRAngleLoc);
718 if (!ToRAngleLocOrErr)
719 return ToRAngleLocOrErr.takeError();
720
721 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
722 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
723 return Err;
724 Result = ToTAInfo;
725 return Error::success();
726}
727
728template <>
729Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
730 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
731 return ImportTemplateArgumentListInfo(
732 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
733}
734
735template <>
736Error ASTNodeImporter::ImportTemplateArgumentListInfo<
737 ASTTemplateArgumentListInfo>(
738 const ASTTemplateArgumentListInfo &From,
739 TemplateArgumentListInfo &Result) {
740 return ImportTemplateArgumentListInfo(
741 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
742}
743
744Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
745ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
746 FunctionDecl *FromFD) {
747 assert(FromFD->getTemplatedKind() ==(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 748, __extension__ __PRETTY_FUNCTION__))
748 FunctionDecl::TK_FunctionTemplateSpecialization)(static_cast <bool> (FromFD->getTemplatedKind() == FunctionDecl
::TK_FunctionTemplateSpecialization) ? void (0) : __assert_fail
("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 748, __extension__ __PRETTY_FUNCTION__))
;
749
750 FunctionTemplateAndArgsTy Result;
751
752 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
753 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
754 return std::move(Err);
755
756 // Import template arguments.
757 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
758 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
759 std::get<1>(Result)))
760 return std::move(Err);
761
762 return Result;
763}
764
765template <>
766Expected<TemplateParameterList *>
767ASTNodeImporter::import(TemplateParameterList *From) {
768 SmallVector<NamedDecl *, 4> To(From->size());
769 if (Error Err = ImportContainerChecked(*From, To))
770 return std::move(Err);
771
772 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
773 if (!ToRequiresClause)
774 return ToRequiresClause.takeError();
775
776 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
777 if (!ToTemplateLocOrErr)
778 return ToTemplateLocOrErr.takeError();
779 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
780 if (!ToLAngleLocOrErr)
781 return ToLAngleLocOrErr.takeError();
782 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
783 if (!ToRAngleLocOrErr)
784 return ToRAngleLocOrErr.takeError();
785
786 return TemplateParameterList::Create(
787 Importer.getToContext(),
788 *ToTemplateLocOrErr,
789 *ToLAngleLocOrErr,
790 To,
791 *ToRAngleLocOrErr,
792 *ToRequiresClause);
793}
794
795template <>
796Expected<TemplateArgument>
797ASTNodeImporter::import(const TemplateArgument &From) {
798 switch (From.getKind()) {
799 case TemplateArgument::Null:
800 return TemplateArgument();
801
802 case TemplateArgument::Type: {
803 ExpectedType ToTypeOrErr = import(From.getAsType());
804 if (!ToTypeOrErr)
805 return ToTypeOrErr.takeError();
806 return TemplateArgument(*ToTypeOrErr);
807 }
808
809 case TemplateArgument::Integral: {
810 ExpectedType ToTypeOrErr = import(From.getIntegralType());
811 if (!ToTypeOrErr)
812 return ToTypeOrErr.takeError();
813 return TemplateArgument(From, *ToTypeOrErr);
814 }
815
816 case TemplateArgument::Declaration: {
817 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
818 if (!ToOrErr)
819 return ToOrErr.takeError();
820 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
821 if (!ToTypeOrErr)
822 return ToTypeOrErr.takeError();
823 return TemplateArgument(*ToOrErr, *ToTypeOrErr);
824 }
825
826 case TemplateArgument::NullPtr: {
827 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
828 if (!ToTypeOrErr)
829 return ToTypeOrErr.takeError();
830 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
831 }
832
833 case TemplateArgument::Template: {
834 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
835 if (!ToTemplateOrErr)
836 return ToTemplateOrErr.takeError();
837
838 return TemplateArgument(*ToTemplateOrErr);
839 }
840
841 case TemplateArgument::TemplateExpansion: {
842 Expected<TemplateName> ToTemplateOrErr =
843 import(From.getAsTemplateOrTemplatePattern());
844 if (!ToTemplateOrErr)
845 return ToTemplateOrErr.takeError();
846
847 return TemplateArgument(
848 *ToTemplateOrErr, From.getNumTemplateExpansions());
849 }
850
851 case TemplateArgument::Expression:
852 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
853 return TemplateArgument(*ToExpr);
854 else
855 return ToExpr.takeError();
856
857 case TemplateArgument::Pack: {
858 SmallVector<TemplateArgument, 2> ToPack;
859 ToPack.reserve(From.pack_size());
860 if (Error Err = ImportTemplateArguments(
861 From.pack_begin(), From.pack_size(), ToPack))
862 return std::move(Err);
863
864 return TemplateArgument(
865 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
866 }
867 }
868
869 llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 869)
;
870}
871
872template <>
873Expected<TemplateArgumentLoc>
874ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
875 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
876 if (!ArgOrErr)
877 return ArgOrErr.takeError();
878 TemplateArgument Arg = *ArgOrErr;
879
880 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
881
882 TemplateArgumentLocInfo ToInfo;
883 if (Arg.getKind() == TemplateArgument::Expression) {
884 ExpectedExpr E = import(FromInfo.getAsExpr());
885 if (!E)
886 return E.takeError();
887 ToInfo = TemplateArgumentLocInfo(*E);
888 } else if (Arg.getKind() == TemplateArgument::Type) {
889 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
890 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
891 else
892 return TSIOrErr.takeError();
893 } else {
894 auto ToTemplateQualifierLocOrErr =
895 import(FromInfo.getTemplateQualifierLoc());
896 if (!ToTemplateQualifierLocOrErr)
897 return ToTemplateQualifierLocOrErr.takeError();
898 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
899 if (!ToTemplateNameLocOrErr)
900 return ToTemplateNameLocOrErr.takeError();
901 auto ToTemplateEllipsisLocOrErr =
902 import(FromInfo.getTemplateEllipsisLoc());
903 if (!ToTemplateEllipsisLocOrErr)
904 return ToTemplateEllipsisLocOrErr.takeError();
905 ToInfo = TemplateArgumentLocInfo(
906 Importer.getToContext(), *ToTemplateQualifierLocOrErr,
907 *ToTemplateNameLocOrErr, *ToTemplateEllipsisLocOrErr);
908 }
909
910 return TemplateArgumentLoc(Arg, ToInfo);
911}
912
913template <>
914Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
915 if (DG.isNull())
916 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
917 size_t NumDecls = DG.end() - DG.begin();
918 SmallVector<Decl *, 1> ToDecls;
919 ToDecls.reserve(NumDecls);
920 for (Decl *FromD : DG) {
921 if (auto ToDOrErr = import(FromD))
922 ToDecls.push_back(*ToDOrErr);
923 else
924 return ToDOrErr.takeError();
925 }
926 return DeclGroupRef::Create(Importer.getToContext(),
927 ToDecls.begin(),
928 NumDecls);
929}
930
931template <>
932Expected<ASTNodeImporter::Designator>
933ASTNodeImporter::import(const Designator &D) {
934 if (D.isFieldDesignator()) {
935 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
936
937 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
938 if (!ToDotLocOrErr)
939 return ToDotLocOrErr.takeError();
940
941 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
942 if (!ToFieldLocOrErr)
943 return ToFieldLocOrErr.takeError();
944
945 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
946 }
947
948 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
949 if (!ToLBracketLocOrErr)
950 return ToLBracketLocOrErr.takeError();
951
952 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
953 if (!ToRBracketLocOrErr)
954 return ToRBracketLocOrErr.takeError();
955
956 if (D.isArrayDesignator())
957 return Designator(D.getFirstExprIndex(),
958 *ToLBracketLocOrErr, *ToRBracketLocOrErr);
959
960 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
961 if (!ToEllipsisLocOrErr)
962 return ToEllipsisLocOrErr.takeError();
963
964 assert(D.isArrayRangeDesignator())(static_cast <bool> (D.isArrayRangeDesignator()) ? void
(0) : __assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 964, __extension__ __PRETTY_FUNCTION__))
;
965 return Designator(
966 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
967 *ToRBracketLocOrErr);
968}
969
970template <>
971Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
972 VarDecl *Var = nullptr;
973 if (From.capturesVariable()) {
974 if (auto VarOrErr = import(From.getCapturedVar()))
975 Var = *VarOrErr;
976 else
977 return VarOrErr.takeError();
978 }
979
980 auto LocationOrErr = import(From.getLocation());
981 if (!LocationOrErr)
982 return LocationOrErr.takeError();
983
984 SourceLocation EllipsisLoc;
985 if (From.isPackExpansion())
986 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
987 return std::move(Err);
988
989 return LambdaCapture(
990 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
991 EllipsisLoc);
992}
993
994template <typename T>
995bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(T *Found, T *From) {
996 if (Found->getLinkageInternal() != From->getLinkageInternal())
997 return false;
998
999 if (From->hasExternalFormalLinkage())
1000 return Found->hasExternalFormalLinkage();
1001 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
1002 return false;
1003 if (From->isInAnonymousNamespace())
1004 return Found->isInAnonymousNamespace();
1005 else
1006 return !Found->isInAnonymousNamespace() &&
1007 !Found->hasExternalFormalLinkage();
1008}
1009
1010template <>
1011bool ASTNodeImporter::hasSameVisibilityContextAndLinkage(TypedefNameDecl *Found,
1012 TypedefNameDecl *From) {
1013 if (Found->getLinkageInternal() != From->getLinkageInternal())
1014 return false;
1015
1016 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace())
1017 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl();
1018 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace();
1019}
1020
1021} // namespace clang
1022
1023//----------------------------------------------------------------------------
1024// Import Types
1025//----------------------------------------------------------------------------
1026
1027using namespace clang;
1028
1029ExpectedType ASTNodeImporter::VisitType(const Type *T) {
1030 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
1031 << T->getTypeClassName();
1032 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1033}
1034
1035ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
1036 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
1037 if (!UnderlyingTypeOrErr)
1038 return UnderlyingTypeOrErr.takeError();
1039
1040 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
1041}
1042
1043ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
1044 switch (T->getKind()) {
1045#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1046 case BuiltinType::Id: \
1047 return Importer.getToContext().SingletonId;
1048#include "clang/Basic/OpenCLImageTypes.def"
1049#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
1050 case BuiltinType::Id: \
1051 return Importer.getToContext().Id##Ty;
1052#include "clang/Basic/OpenCLExtensionTypes.def"
1053#define SVE_TYPE(Name, Id, SingletonId) \
1054 case BuiltinType::Id: \
1055 return Importer.getToContext().SingletonId;
1056#include "clang/Basic/AArch64SVEACLETypes.def"
1057#define PPC_VECTOR_TYPE(Name, Id, Size) \
1058 case BuiltinType::Id: \
1059 return Importer.getToContext().Id##Ty;
1060#include "clang/Basic/PPCTypes.def"
1061#define RVV_TYPE(Name, Id, SingletonId) \
1062 case BuiltinType::Id: \
1063 return Importer.getToContext().SingletonId;
1064#include "clang/Basic/RISCVVTypes.def"
1065#define SHARED_SINGLETON_TYPE(Expansion)
1066#define BUILTIN_TYPE(Id, SingletonId) \
1067 case BuiltinType::Id: return Importer.getToContext().SingletonId;
1068#include "clang/AST/BuiltinTypes.def"
1069
1070 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
1071 // context supports C++.
1072
1073 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
1074 // context supports ObjC.
1075
1076 case BuiltinType::Char_U:
1077 // The context we're importing from has an unsigned 'char'. If we're
1078 // importing into a context with a signed 'char', translate to
1079 // 'unsigned char' instead.
1080 if (Importer.getToContext().getLangOpts().CharIsSigned)
1081 return Importer.getToContext().UnsignedCharTy;
1082
1083 return Importer.getToContext().CharTy;
1084
1085 case BuiltinType::Char_S:
1086 // The context we're importing from has an unsigned 'char'. If we're
1087 // importing into a context with a signed 'char', translate to
1088 // 'unsigned char' instead.
1089 if (!Importer.getToContext().getLangOpts().CharIsSigned)
1090 return Importer.getToContext().SignedCharTy;
1091
1092 return Importer.getToContext().CharTy;
1093
1094 case BuiltinType::WChar_S:
1095 case BuiltinType::WChar_U:
1096 // FIXME: If not in C++, shall we translate to the C equivalent of
1097 // wchar_t?
1098 return Importer.getToContext().WCharTy;
1099 }
1100
1101 llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1101)
;
1102}
1103
1104ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1105 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1106 if (!ToOriginalTypeOrErr)
1107 return ToOriginalTypeOrErr.takeError();
1108
1109 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1110}
1111
1112ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1113 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1114 if (!ToElementTypeOrErr)
1115 return ToElementTypeOrErr.takeError();
1116
1117 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1118}
1119
1120ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1121 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1122 if (!ToPointeeTypeOrErr)
1123 return ToPointeeTypeOrErr.takeError();
1124
1125 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1126}
1127
1128ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1129 // FIXME: Check for blocks support in "to" context.
1130 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1131 if (!ToPointeeTypeOrErr)
1132 return ToPointeeTypeOrErr.takeError();
1133
1134 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1135}
1136
1137ExpectedType
1138ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1139 // FIXME: Check for C++ support in "to" context.
1140 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1141 if (!ToPointeeTypeOrErr)
1142 return ToPointeeTypeOrErr.takeError();
1143
1144 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1145}
1146
1147ExpectedType
1148ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1149 // FIXME: Check for C++0x support in "to" context.
1150 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1151 if (!ToPointeeTypeOrErr)
1152 return ToPointeeTypeOrErr.takeError();
1153
1154 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1155}
1156
1157ExpectedType
1158ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1159 // FIXME: Check for C++ support in "to" context.
1160 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1161 if (!ToPointeeTypeOrErr)
1162 return ToPointeeTypeOrErr.takeError();
1163
1164 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1165 if (!ClassTypeOrErr)
1166 return ClassTypeOrErr.takeError();
1167
1168 return Importer.getToContext().getMemberPointerType(
1169 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1170}
1171
1172ExpectedType
1173ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1174 Error Err = Error::success();
1175 auto ToElementType = importChecked(Err, T->getElementType());
1176 auto ToSizeExpr = importChecked(Err, T->getSizeExpr());
1177 if (Err)
1178 return std::move(Err);
1179
1180 return Importer.getToContext().getConstantArrayType(
1181 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(),
1182 T->getIndexTypeCVRQualifiers());
1183}
1184
1185ExpectedType
1186ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1187 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1188 if (!ToElementTypeOrErr)
1189 return ToElementTypeOrErr.takeError();
1190
1191 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1192 T->getSizeModifier(),
1193 T->getIndexTypeCVRQualifiers());
1194}
1195
1196ExpectedType
1197ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1198 Error Err = Error::success();
1199 QualType ToElementType = importChecked(Err, T->getElementType());
1200 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1201 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1202 if (Err)
1203 return std::move(Err);
1204 return Importer.getToContext().getVariableArrayType(
1205 ToElementType, ToSizeExpr, T->getSizeModifier(),
1206 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1207}
1208
1209ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1210 const DependentSizedArrayType *T) {
1211 Error Err = Error::success();
1212 QualType ToElementType = importChecked(Err, T->getElementType());
1213 Expr *ToSizeExpr = importChecked(Err, T->getSizeExpr());
1214 SourceRange ToBracketsRange = importChecked(Err, T->getBracketsRange());
1215 if (Err)
1216 return std::move(Err);
1217 // SizeExpr may be null if size is not specified directly.
1218 // For example, 'int a[]'.
1219
1220 return Importer.getToContext().getDependentSizedArrayType(
1221 ToElementType, ToSizeExpr, T->getSizeModifier(),
1222 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1223}
1224
1225ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1226 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1227 if (!ToElementTypeOrErr)
1228 return ToElementTypeOrErr.takeError();
1229
1230 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1231 T->getNumElements(),
1232 T->getVectorKind());
1233}
1234
1235ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1236 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1237 if (!ToElementTypeOrErr)
1238 return ToElementTypeOrErr.takeError();
1239
1240 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1241 T->getNumElements());
1242}
1243
1244ExpectedType
1245ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1246 // FIXME: What happens if we're importing a function without a prototype
1247 // into C++? Should we make it variadic?
1248 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1249 if (!ToReturnTypeOrErr)
1250 return ToReturnTypeOrErr.takeError();
1251
1252 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1253 T->getExtInfo());
1254}
1255
1256ExpectedType
1257ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1258 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1259 if (!ToReturnTypeOrErr)
1260 return ToReturnTypeOrErr.takeError();
1261
1262 // Import argument types
1263 SmallVector<QualType, 4> ArgTypes;
1264 for (const auto &A : T->param_types()) {
1265 ExpectedType TyOrErr = import(A);
1266 if (!TyOrErr)
1267 return TyOrErr.takeError();
1268 ArgTypes.push_back(*TyOrErr);
1269 }
1270
1271 // Import exception types
1272 SmallVector<QualType, 4> ExceptionTypes;
1273 for (const auto &E : T->exceptions()) {
1274 ExpectedType TyOrErr = import(E);
1275 if (!TyOrErr)
1276 return TyOrErr.takeError();
1277 ExceptionTypes.push_back(*TyOrErr);
1278 }
1279
1280 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1281 Error Err = Error::success();
1282 FunctionProtoType::ExtProtoInfo ToEPI;
1283 ToEPI.ExtInfo = FromEPI.ExtInfo;
1284 ToEPI.Variadic = FromEPI.Variadic;
1285 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1286 ToEPI.TypeQuals = FromEPI.TypeQuals;
1287 ToEPI.RefQualifier = FromEPI.RefQualifier;
1288 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1289 ToEPI.ExceptionSpec.NoexceptExpr =
1290 importChecked(Err, FromEPI.ExceptionSpec.NoexceptExpr);
1291 ToEPI.ExceptionSpec.SourceDecl =
1292 importChecked(Err, FromEPI.ExceptionSpec.SourceDecl);
1293 ToEPI.ExceptionSpec.SourceTemplate =
1294 importChecked(Err, FromEPI.ExceptionSpec.SourceTemplate);
1295 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1296
1297 if (Err)
1298 return std::move(Err);
1299
1300 return Importer.getToContext().getFunctionType(
1301 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1302}
1303
1304ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1305 const UnresolvedUsingType *T) {
1306 Error Err = Error::success();
1307 auto ToD = importChecked(Err, T->getDecl());
1308 auto ToPrevD = importChecked(Err, T->getDecl()->getPreviousDecl());
1309 if (Err)
1310 return std::move(Err);
1311
1312 return Importer.getToContext().getTypeDeclType(
1313 ToD, cast_or_null<TypeDecl>(ToPrevD));
1314}
1315
1316ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1317 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1318 if (!ToInnerTypeOrErr)
1319 return ToInnerTypeOrErr.takeError();
1320
1321 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1322}
1323
1324ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1325 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1326 if (!ToDeclOrErr)
1327 return ToDeclOrErr.takeError();
1328
1329 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1330}
1331
1332ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1333 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1334 if (!ToExprOrErr)
1335 return ToExprOrErr.takeError();
1336
1337 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1338}
1339
1340ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1341 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1342 if (!ToUnderlyingTypeOrErr)
1343 return ToUnderlyingTypeOrErr.takeError();
1344
1345 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1346}
1347
1348ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1349 // FIXME: Make sure that the "to" context supports C++0x!
1350 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1351 if (!ToExprOrErr)
1352 return ToExprOrErr.takeError();
1353
1354 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1355 if (!ToUnderlyingTypeOrErr)
1356 return ToUnderlyingTypeOrErr.takeError();
1357
1358 return Importer.getToContext().getDecltypeType(
1359 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1360}
1361
1362ExpectedType
1363ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1364 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1365 if (!ToBaseTypeOrErr)
1366 return ToBaseTypeOrErr.takeError();
1367
1368 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1369 if (!ToUnderlyingTypeOrErr)
1370 return ToUnderlyingTypeOrErr.takeError();
1371
1372 return Importer.getToContext().getUnaryTransformType(
1373 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1374}
1375
1376ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1377 // FIXME: Make sure that the "to" context supports C++11!
1378 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1379 if (!ToDeducedTypeOrErr)
1380 return ToDeducedTypeOrErr.takeError();
1381
1382 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept());
1383 if (!ToTypeConstraintConcept)
1384 return ToTypeConstraintConcept.takeError();
1385
1386 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1387 ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments();
1388 if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(),
1389 FromTemplateArgs.size(),
1390 ToTemplateArgs))
1391 return std::move(Err);
1392
1393 return Importer.getToContext().getAutoType(
1394 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false,
1395 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept),
1396 ToTemplateArgs);
1397}
1398
1399ExpectedType ASTNodeImporter::VisitDeducedTemplateSpecializationType(
1400 const DeducedTemplateSpecializationType *T) {
1401 // FIXME: Make sure that the "to" context supports C++17!
1402 Expected<TemplateName> ToTemplateNameOrErr = import(T->getTemplateName());
1403 if (!ToTemplateNameOrErr)
1404 return ToTemplateNameOrErr.takeError();
1405 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1406 if (!ToDeducedTypeOrErr)
1407 return ToDeducedTypeOrErr.takeError();
1408
1409 return Importer.getToContext().getDeducedTemplateSpecializationType(
1410 *ToTemplateNameOrErr, *ToDeducedTypeOrErr, T->isDependentType());
1411}
1412
1413ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1414 const InjectedClassNameType *T) {
1415 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1416 if (!ToDeclOrErr)
1417 return ToDeclOrErr.takeError();
1418
1419 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1420 if (!ToInjTypeOrErr)
1421 return ToInjTypeOrErr.takeError();
1422
1423 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1424 // See comments in InjectedClassNameType definition for details
1425 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1426 enum {
1427 TypeAlignmentInBits = 4,
1428 TypeAlignment = 1 << TypeAlignmentInBits
1429 };
1430
1431 return QualType(new (Importer.getToContext(), TypeAlignment)
1432 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1433}
1434
1435ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1436 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1437 if (!ToDeclOrErr)
1438 return ToDeclOrErr.takeError();
1439
1440 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1441}
1442
1443ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1444 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1445 if (!ToDeclOrErr)
1446 return ToDeclOrErr.takeError();
1447
1448 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1449}
1450
1451ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1452 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1453 if (!ToModifiedTypeOrErr)
1454 return ToModifiedTypeOrErr.takeError();
1455 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1456 if (!ToEquivalentTypeOrErr)
1457 return ToEquivalentTypeOrErr.takeError();
1458
1459 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1460 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1461}
1462
1463ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1464 const TemplateTypeParmType *T) {
1465 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1466 if (!ToDeclOrErr)
1467 return ToDeclOrErr.takeError();
1468
1469 return Importer.getToContext().getTemplateTypeParmType(
1470 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1471}
1472
1473ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1474 const SubstTemplateTypeParmType *T) {
1475 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1476 if (!ReplacedOrErr)
1477 return ReplacedOrErr.takeError();
1478 const TemplateTypeParmType *Replaced =
1479 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1480
1481 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1482 if (!ToReplacementTypeOrErr)
1483 return ToReplacementTypeOrErr.takeError();
1484
1485 return Importer.getToContext().getSubstTemplateTypeParmType(
1486 Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1487}
1488
1489ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1490 const TemplateSpecializationType *T) {
1491 auto ToTemplateOrErr = import(T->getTemplateName());
1492 if (!ToTemplateOrErr)
1493 return ToTemplateOrErr.takeError();
1494
1495 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1496 if (Error Err = ImportTemplateArguments(
1497 T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1498 return std::move(Err);
1499
1500 QualType ToCanonType;
1501 if (!QualType(T, 0).isCanonical()) {
1502 QualType FromCanonType
1503 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1504 if (ExpectedType TyOrErr = import(FromCanonType))
1505 ToCanonType = *TyOrErr;
1506 else
1507 return TyOrErr.takeError();
1508 }
1509 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1510 ToTemplateArgs,
1511 ToCanonType);
1512}
1513
1514ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1515 // Note: the qualifier in an ElaboratedType is optional.
1516 auto ToQualifierOrErr = import(T->getQualifier());
1517 if (!ToQualifierOrErr)
1518 return ToQualifierOrErr.takeError();
1519
1520 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1521 if (!ToNamedTypeOrErr)
1522 return ToNamedTypeOrErr.takeError();
1523
1524 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1525 if (!ToOwnedTagDeclOrErr)
1526 return ToOwnedTagDeclOrErr.takeError();
1527
1528 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1529 *ToQualifierOrErr,
1530 *ToNamedTypeOrErr,
1531 *ToOwnedTagDeclOrErr);
1532}
1533
1534ExpectedType
1535ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1536 ExpectedType ToPatternOrErr = import(T->getPattern());
1537 if (!ToPatternOrErr)
1538 return ToPatternOrErr.takeError();
1539
1540 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1541 T->getNumExpansions(),
1542 /*ExpactPack=*/false);
1543}
1544
1545ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1546 const DependentTemplateSpecializationType *T) {
1547 auto ToQualifierOrErr = import(T->getQualifier());
1548 if (!ToQualifierOrErr)
1549 return ToQualifierOrErr.takeError();
1550
1551 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1552
1553 SmallVector<TemplateArgument, 2> ToPack;
1554 ToPack.reserve(T->getNumArgs());
1555 if (Error Err = ImportTemplateArguments(
1556 T->getArgs(), T->getNumArgs(), ToPack))
1557 return std::move(Err);
1558
1559 return Importer.getToContext().getDependentTemplateSpecializationType(
1560 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1561}
1562
1563ExpectedType
1564ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1565 auto ToQualifierOrErr = import(T->getQualifier());
1566 if (!ToQualifierOrErr)
1567 return ToQualifierOrErr.takeError();
1568
1569 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1570
1571 QualType Canon;
1572 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1573 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1574 Canon = (*TyOrErr).getCanonicalType();
1575 else
1576 return TyOrErr.takeError();
1577 }
1578
1579 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1580 *ToQualifierOrErr,
1581 Name, Canon);
1582}
1583
1584ExpectedType
1585ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1586 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1587 if (!ToDeclOrErr)
1588 return ToDeclOrErr.takeError();
1589
1590 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1591}
1592
1593ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1594 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1595 if (!ToBaseTypeOrErr)
1596 return ToBaseTypeOrErr.takeError();
1597
1598 SmallVector<QualType, 4> TypeArgs;
1599 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1600 if (ExpectedType TyOrErr = import(TypeArg))
1601 TypeArgs.push_back(*TyOrErr);
1602 else
1603 return TyOrErr.takeError();
1604 }
1605
1606 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1607 for (auto *P : T->quals()) {
1608 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1609 Protocols.push_back(*ProtocolOrErr);
1610 else
1611 return ProtocolOrErr.takeError();
1612
1613 }
1614
1615 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1616 Protocols,
1617 T->isKindOfTypeAsWritten());
1618}
1619
1620ExpectedType
1621ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1622 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1623 if (!ToPointeeTypeOrErr)
1624 return ToPointeeTypeOrErr.takeError();
1625
1626 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1627}
1628
1629//----------------------------------------------------------------------------
1630// Import Declarations
1631//----------------------------------------------------------------------------
1632Error ASTNodeImporter::ImportDeclParts(
1633 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1634 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1635 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1636 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1637 // FIXME: We could support these constructs by importing a different type of
1638 // this parameter and by importing the original type of the parameter only
1639 // after the FunctionDecl is created. See
1640 // VisitFunctionDecl::UsedDifferentProtoType.
1641 DeclContext *OrigDC = D->getDeclContext();
1642 FunctionDecl *FunDecl;
1643 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1644 FunDecl->hasBody()) {
1645 auto getLeafPointeeType = [](const Type *T) {
1646 while (T->isPointerType() || T->isArrayType()) {
1647 T = T->getPointeeOrArrayElementType();
1648 }
1649 return T;
1650 };
1651 for (const ParmVarDecl *P : FunDecl->parameters()) {
1652 const Type *LeafT =
1653 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1654 auto *RT = dyn_cast<RecordType>(LeafT);
1655 if (RT && RT->getDecl() == D) {
1656 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1657 << D->getDeclKindName();
1658 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1659 }
1660 }
1661 }
1662
1663 // Import the context of this declaration.
1664 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1665 return Err;
1666
1667 // Import the name of this declaration.
1668 if (Error Err = importInto(Name, D->getDeclName()))
1669 return Err;
1670
1671 // Import the location of this declaration.
1672 if (Error Err = importInto(Loc, D->getLocation()))
1673 return Err;
1674
1675 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1676 if (ToD)
1677 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1678 return Err;
1679
1680 return Error::success();
1681}
1682
1683Error ASTNodeImporter::ImportDeclParts(NamedDecl *D, DeclarationName &Name,
1684 NamedDecl *&ToD, SourceLocation &Loc) {
1685
1686 // Import the name of this declaration.
1687 if (Error Err = importInto(Name, D->getDeclName()))
1688 return Err;
1689
1690 // Import the location of this declaration.
1691 if (Error Err = importInto(Loc, D->getLocation()))
1692 return Err;
1693
1694 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1695 if (ToD)
1696 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1697 return Err;
1698
1699 return Error::success();
1700}
1701
1702Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1703 if (!FromD)
1704 return Error::success();
1705
1706 if (!ToD)
1707 if (Error Err = importInto(ToD, FromD))
1708 return Err;
1709
1710 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1711 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1712 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1713 !ToRecord->getDefinition()) {
1714 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1715 return Err;
1716 }
1717 }
1718 return Error::success();
1719 }
1720
1721 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1722 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1723 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1724 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1725 return Err;
1726 }
1727 }
1728 return Error::success();
1729 }
1730
1731 return Error::success();
1732}
1733
1734Error
1735ASTNodeImporter::ImportDeclarationNameLoc(
1736 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1737 // NOTE: To.Name and To.Loc are already imported.
1738 // We only have to import To.LocInfo.
1739 switch (To.getName().getNameKind()) {
1740 case DeclarationName::Identifier:
1741 case DeclarationName::ObjCZeroArgSelector:
1742 case DeclarationName::ObjCOneArgSelector:
1743 case DeclarationName::ObjCMultiArgSelector:
1744 case DeclarationName::CXXUsingDirective:
1745 case DeclarationName::CXXDeductionGuideName:
1746 return Error::success();
1747
1748 case DeclarationName::CXXOperatorName: {
1749 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1750 To.setCXXOperatorNameRange(*ToRangeOrErr);
1751 else
1752 return ToRangeOrErr.takeError();
1753 return Error::success();
1754 }
1755 case DeclarationName::CXXLiteralOperatorName: {
1756 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1757 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1758 else
1759 return LocOrErr.takeError();
1760 return Error::success();
1761 }
1762 case DeclarationName::CXXConstructorName:
1763 case DeclarationName::CXXDestructorName:
1764 case DeclarationName::CXXConversionFunctionName: {
1765 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1766 To.setNamedTypeInfo(*ToTInfoOrErr);
1767 else
1768 return ToTInfoOrErr.takeError();
1769 return Error::success();
1770 }
1771 }
1772 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1772)
;
1773}
1774
1775Error
1776ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1777 if (Importer.isMinimalImport() && !ForceImport) {
1778 auto ToDCOrErr = Importer.ImportContext(FromDC);
1779 return ToDCOrErr.takeError();
1780 }
1781
1782 // We use strict error handling in case of records and enums, but not
1783 // with e.g. namespaces.
1784 //
1785 // FIXME Clients of the ASTImporter should be able to choose an
1786 // appropriate error handling strategy for their needs. For instance,
1787 // they may not want to mark an entire namespace as erroneous merely
1788 // because there is an ODR error with two typedefs. As another example,
1789 // the client may allow EnumConstantDecls with same names but with
1790 // different values in two distinct translation units.
1791 bool AccumulateChildErrors = isa<TagDecl>(FromDC);
1792
1793 Error ChildErrors = Error::success();
1794 for (auto *From : FromDC->decls()) {
1795 ExpectedDecl ImportedOrErr = import(From);
1796
1797 // If we are in the process of ImportDefinition(...) for a RecordDecl we
1798 // want to make sure that we are also completing each FieldDecl. There
1799 // are currently cases where this does not happen and this is correctness
1800 // fix since operations such as code generation will expect this to be so.
1801 if (ImportedOrErr) {
1802 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From);
1803 Decl *ImportedDecl = *ImportedOrErr;
1804 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl);
1805 if (FieldFrom && FieldTo) {
1806 RecordDecl *FromRecordDecl = nullptr;
1807 RecordDecl *ToRecordDecl = nullptr;
1808 // If we have a field that is an ArrayType we need to check if the array
1809 // element is a RecordDecl and if so we need to import the defintion.
1810 if (FieldFrom->getType()->isArrayType()) {
1811 // getBaseElementTypeUnsafe(...) handles multi-dimensonal arrays for us.
1812 FromRecordDecl = FieldFrom->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1813 ToRecordDecl = FieldTo->getType()->getBaseElementTypeUnsafe()->getAsRecordDecl();
1814 }
1815
1816 if (!FromRecordDecl || !ToRecordDecl) {
1817 const RecordType *RecordFrom =
1818 FieldFrom->getType()->getAs<RecordType>();
1819 const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>();
1820
1821 if (RecordFrom && RecordTo) {
1822 FromRecordDecl = RecordFrom->getDecl();
1823 ToRecordDecl = RecordTo->getDecl();
1824 }
1825 }
1826
1827 if (FromRecordDecl && ToRecordDecl) {
1828 if (FromRecordDecl->isCompleteDefinition() &&
1829 !ToRecordDecl->isCompleteDefinition()) {
1830 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl);
1831
1832 if (Err && AccumulateChildErrors)
1833 ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err));
1834 else
1835 consumeError(std::move(Err));
1836 }
1837 }
1838 }
1839 } else {
1840 if (AccumulateChildErrors)
1841 ChildErrors =
1842 joinErrors(std::move(ChildErrors), ImportedOrErr.takeError());
1843 else
1844 consumeError(ImportedOrErr.takeError());
1845 }
1846 }
1847
1848 // We reorder declarations in RecordDecls because they may have another order
1849 // in the "to" context than they have in the "from" context. This may happen
1850 // e.g when we import a class like this:
1851 // struct declToImport {
1852 // int a = c + b;
1853 // int b = 1;
1854 // int c = 2;
1855 // };
1856 // During the import of `a` we import first the dependencies in sequence,
1857 // thus the order would be `c`, `b`, `a`. We will get the normal order by
1858 // first removing the already imported members and then adding them in the
1859 // order as they apper in the "from" context.
1860 //
1861 // Keeping field order is vital because it determines structure layout.
1862 //
1863 // Here and below, we cannot call field_begin() method and its callers on
1864 // ToDC if it has an external storage. Calling field_begin() will
1865 // automatically load all the fields by calling
1866 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would
1867 // call ASTImporter::Import(). This is because the ExternalASTSource
1868 // interface in LLDB is implemented by the means of the ASTImporter. However,
1869 // calling an import at this point would result in an uncontrolled import, we
1870 // must avoid that.
1871 const auto *FromRD = dyn_cast<RecordDecl>(FromDC);
1872 if (!FromRD)
1873 return ChildErrors;
1874
1875 auto ToDCOrErr = Importer.ImportContext(FromDC);
1876 if (!ToDCOrErr) {
1877 consumeError(std::move(ChildErrors));
1878 return ToDCOrErr.takeError();
1879 }
1880
1881 DeclContext *ToDC = *ToDCOrErr;
1882 // Remove all declarations, which may be in wrong order in the
1883 // lexical DeclContext and then add them in the proper order.
1884 for (auto *D : FromRD->decls()) {
1885 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) {
1886 assert(D && "DC contains a null decl")(static_cast <bool> (D && "DC contains a null decl"
) ? void (0) : __assert_fail ("D && \"DC contains a null decl\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1886, __extension__ __PRETTY_FUNCTION__))
;
1887 Decl *ToD = Importer.GetAlreadyImportedOrNull(D);
1888 // Remove only the decls which we successfully imported.
1889 if (ToD) {
1890 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD))(static_cast <bool> (ToDC == ToD->getLexicalDeclContext
() && ToDC->containsDecl(ToD)) ? void (0) : __assert_fail
("ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1890, __extension__ __PRETTY_FUNCTION__))
;
1891 // Remove the decl from its wrong place in the linked list.
1892 ToDC->removeDecl(ToD);
1893 // Add the decl to the end of the linked list.
1894 // This time it will be at the proper place because the enclosing for
1895 // loop iterates in the original (good) order of the decls.
1896 ToDC->addDeclInternal(ToD);
1897 }
1898 }
1899 }
1900
1901 return ChildErrors;
1902}
1903
1904Error ASTNodeImporter::ImportDeclContext(
1905 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1906 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1907 if (!ToDCOrErr)
1908 return ToDCOrErr.takeError();
1909 ToDC = *ToDCOrErr;
1910
1911 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1912 auto ToLexicalDCOrErr = Importer.ImportContext(
1913 FromD->getLexicalDeclContext());
1914 if (!ToLexicalDCOrErr)
1915 return ToLexicalDCOrErr.takeError();
1916 ToLexicalDC = *ToLexicalDCOrErr;
1917 } else
1918 ToLexicalDC = ToDC;
1919
1920 return Error::success();
1921}
1922
1923Error ASTNodeImporter::ImportImplicitMethods(
1924 const CXXRecordDecl *From, CXXRecordDecl *To) {
1925 assert(From->isCompleteDefinition() && To->getDefinition() == To &&(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1926, __extension__ __PRETTY_FUNCTION__))
1926 "Import implicit methods to or from non-definition")(static_cast <bool> (From->isCompleteDefinition() &&
To->getDefinition() == To && "Import implicit methods to or from non-definition"
) ? void (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 1926, __extension__ __PRETTY_FUNCTION__))
;
1927
1928 for (CXXMethodDecl *FromM : From->methods())
1929 if (FromM->isImplicit()) {
1930 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1931 if (!ToMOrErr)
1932 return ToMOrErr.takeError();
1933 }
1934
1935 return Error::success();
1936}
1937
1938static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1939 ASTImporter &Importer) {
1940 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1941 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1942 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1943 else
1944 return ToTypedefOrErr.takeError();
1945 }
1946 return Error::success();
1947}
1948
1949Error ASTNodeImporter::ImportDefinition(
1950 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
1951 auto DefinitionCompleter = [To]() {
1952 // There are cases in LLDB when we first import a class without its
1953 // members. The class will have DefinitionData, but no members. Then,
1954 // importDefinition is called from LLDB, which tries to get the members, so
1955 // when we get here, the class already has the DefinitionData set, so we
1956 // must unset the CompleteDefinition here to be able to complete again the
1957 // definition.
1958 To->setCompleteDefinition(false);
1959 To->completeDefinition();
1960 };
1961
1962 if (To->getDefinition() || To->isBeingDefined()) {
1963 if (Kind == IDK_Everything ||
1964 // In case of lambdas, the class already has a definition ptr set, but
1965 // the contained decls are not imported yet. Also, isBeingDefined was
1966 // set in CXXRecordDecl::CreateLambda. We must import the contained
1967 // decls here and finish the definition.
1968 (To->isLambda() && shouldForceImportDeclContext(Kind))) {
1969 if (To->isLambda()) {
1970 auto *FromCXXRD = cast<CXXRecordDecl>(From);
1971 SmallVector<LambdaCapture, 8> ToCaptures;
1972 ToCaptures.reserve(FromCXXRD->capture_size());
1973 for (const auto &FromCapture : FromCXXRD->captures()) {
1974 if (auto ToCaptureOrErr = import(FromCapture))
1975 ToCaptures.push_back(*ToCaptureOrErr);
1976 else
1977 return ToCaptureOrErr.takeError();
1978 }
1979 cast<CXXRecordDecl>(To)->setCaptures(Importer.getToContext(),
1980 ToCaptures);
1981 }
1982
1983 Error Result = ImportDeclContext(From, /*ForceImport=*/true);
1984 // Finish the definition of the lambda, set isBeingDefined to false.
1985 if (To->isLambda())
1986 DefinitionCompleter();
1987 return Result;
1988 }
1989
1990 return Error::success();
1991 }
1992
1993 To->startDefinition();
1994 // Complete the definition even if error is returned.
1995 // The RecordDecl may be already part of the AST so it is better to
1996 // have it in complete state even if something is wrong with it.
1997 auto DefinitionCompleterScopeExit =
1998 llvm::make_scope_exit(DefinitionCompleter);
1999
2000 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2001 return Err;
2002
2003 // Add base classes.
2004 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
2005 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
2006 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
2007
2008 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
2009 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
2010
2011 #define FIELD(Name, Width, Merge) \
2012 ToData.Name = FromData.Name;
2013 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
2014
2015 // Copy over the data stored in RecordDeclBits
2016 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
2017
2018 SmallVector<CXXBaseSpecifier *, 4> Bases;
2019 for (const auto &Base1 : FromCXX->bases()) {
2020 ExpectedType TyOrErr = import(Base1.getType());
2021 if (!TyOrErr)
2022 return TyOrErr.takeError();
2023
2024 SourceLocation EllipsisLoc;
2025 if (Base1.isPackExpansion()) {
2026 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
2027 EllipsisLoc = *LocOrErr;
2028 else
2029 return LocOrErr.takeError();
2030 }
2031
2032 // Ensure that we have a definition for the base.
2033 if (Error Err =
2034 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
2035 return Err;
2036
2037 auto RangeOrErr = import(Base1.getSourceRange());
2038 if (!RangeOrErr)
2039 return RangeOrErr.takeError();
2040
2041 auto TSIOrErr = import(Base1.getTypeSourceInfo());
2042 if (!TSIOrErr)
2043 return TSIOrErr.takeError();
2044
2045 Bases.push_back(
2046 new (Importer.getToContext()) CXXBaseSpecifier(
2047 *RangeOrErr,
2048 Base1.isVirtual(),
2049 Base1.isBaseOfClass(),
2050 Base1.getAccessSpecifierAsWritten(),
2051 *TSIOrErr,
2052 EllipsisLoc));
2053 }
2054 if (!Bases.empty())
2055 ToCXX->setBases(Bases.data(), Bases.size());
2056 }
2057
2058 if (shouldForceImportDeclContext(Kind))
2059 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2060 return Err;
2061
2062 return Error::success();
2063}
2064
2065Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
2066 if (To->getAnyInitializer())
2067 return Error::success();
2068
2069 Expr *FromInit = From->getInit();
2070 if (!FromInit)
2071 return Error::success();
2072
2073 ExpectedExpr ToInitOrErr = import(FromInit);
2074 if (!ToInitOrErr)
2075 return ToInitOrErr.takeError();
2076
2077 To->setInit(*ToInitOrErr);
2078 if (EvaluatedStmt *FromEval = From->getEvaluatedStmt()) {
2079 EvaluatedStmt *ToEval = To->ensureEvaluatedStmt();
2080 ToEval->HasConstantInitialization = FromEval->HasConstantInitialization;
2081 ToEval->HasConstantDestruction = FromEval->HasConstantDestruction;
2082 // FIXME: Also import the initializer value.
2083 }
2084
2085 // FIXME: Other bits to merge?
2086 return Error::success();
2087}
2088
2089Error ASTNodeImporter::ImportDefinition(
2090 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
2091 if (To->getDefinition() || To->isBeingDefined()) {
2092 if (Kind == IDK_Everything)
2093 return ImportDeclContext(From, /*ForceImport=*/true);
2094 return Error::success();
2095 }
2096
2097 To->startDefinition();
2098
2099 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
2100 return Err;
2101
2102 ExpectedType ToTypeOrErr =
2103 import(Importer.getFromContext().getTypeDeclType(From));
2104 if (!ToTypeOrErr)
2105 return ToTypeOrErr.takeError();
2106
2107 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
2108 if (!ToPromotionTypeOrErr)
2109 return ToPromotionTypeOrErr.takeError();
2110
2111 if (shouldForceImportDeclContext(Kind))
2112 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
2113 return Err;
2114
2115 // FIXME: we might need to merge the number of positive or negative bits
2116 // if the enumerator lists don't match.
2117 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
2118 From->getNumPositiveBits(),
2119 From->getNumNegativeBits());
2120 return Error::success();
2121}
2122
2123Error ASTNodeImporter::ImportTemplateArguments(
2124 const TemplateArgument *FromArgs, unsigned NumFromArgs,
2125 SmallVectorImpl<TemplateArgument> &ToArgs) {
2126 for (unsigned I = 0; I != NumFromArgs; ++I) {
2127 if (auto ToOrErr = import(FromArgs[I]))
2128 ToArgs.push_back(*ToOrErr);
2129 else
2130 return ToOrErr.takeError();
2131 }
2132
2133 return Error::success();
2134}
2135
2136// FIXME: Do not forget to remove this and use only 'import'.
2137Expected<TemplateArgument>
2138ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
2139 return import(From);
2140}
2141
2142template <typename InContainerTy>
2143Error ASTNodeImporter::ImportTemplateArgumentListInfo(
2144 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
2145 for (const auto &FromLoc : Container) {
2146 if (auto ToLocOrErr = import(FromLoc))
2147 ToTAInfo.addArgument(*ToLocOrErr);
2148 else
2149 return ToLocOrErr.takeError();
2150 }
2151 return Error::success();
2152}
2153
2154static StructuralEquivalenceKind
2155getStructuralEquivalenceKind(const ASTImporter &Importer) {
2156 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
2157 : StructuralEquivalenceKind::Default;
2158}
2159
2160bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
2161 StructuralEquivalenceContext Ctx(
2162 Importer.getFromContext(), Importer.getToContext(),
2163 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2164 false, Complain);
2165 return Ctx.IsEquivalent(From, To);
2166}
2167
2168bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
2169 RecordDecl *ToRecord, bool Complain) {
2170 // Eliminate a potential failure point where we attempt to re-import
2171 // something we're trying to import while completing ToRecord.
2172 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
2173 if (ToOrigin) {
2174 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
2175 if (ToOriginRecord)
2176 ToRecord = ToOriginRecord;
2177 }
2178
2179 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2180 ToRecord->getASTContext(),
2181 Importer.getNonEquivalentDecls(),
2182 getStructuralEquivalenceKind(Importer),
2183 false, Complain);
2184 return Ctx.IsEquivalent(FromRecord, ToRecord);
2185}
2186
2187bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
2188 bool Complain) {
2189 StructuralEquivalenceContext Ctx(
2190 Importer.getFromContext(), Importer.getToContext(),
2191 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2192 false, Complain);
2193 return Ctx.IsEquivalent(FromVar, ToVar);
2194}
2195
2196bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
2197 // Eliminate a potential failure point where we attempt to re-import
2198 // something we're trying to import while completing ToEnum.
2199 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
2200 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
2201 ToEnum = ToOriginEnum;
2202
2203 StructuralEquivalenceContext Ctx(
2204 Importer.getFromContext(), Importer.getToContext(),
2205 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
2206 return Ctx.IsEquivalent(FromEnum, ToEnum);
2207}
2208
2209bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
2210 FunctionTemplateDecl *To) {
2211 StructuralEquivalenceContext Ctx(
2212 Importer.getFromContext(), Importer.getToContext(),
2213 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2214 false, false);
2215 return Ctx.IsEquivalent(From, To);
2216}
2217
2218bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
2219 StructuralEquivalenceContext Ctx(
2220 Importer.getFromContext(), Importer.getToContext(),
2221 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
2222 false, false);
2223 return Ctx.IsEquivalent(From, To);
2224}
2225
2226bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
2227 EnumConstantDecl *ToEC) {
2228 const llvm::APSInt &FromVal = FromEC->getInitVal();
2229 const llvm::APSInt &ToVal = ToEC->getInitVal();
2230
2231 return FromVal.isSigned() == ToVal.isSigned() &&
2232 FromVal.getBitWidth() == ToVal.getBitWidth() &&
2233 FromVal == ToVal;
2234}
2235
2236bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2237 ClassTemplateDecl *To) {
2238 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2239 Importer.getToContext(),
2240 Importer.getNonEquivalentDecls(),
2241 getStructuralEquivalenceKind(Importer));
2242 return Ctx.IsEquivalent(From, To);
2243}
2244
2245bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2246 VarTemplateDecl *To) {
2247 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2248 Importer.getToContext(),
2249 Importer.getNonEquivalentDecls(),
2250 getStructuralEquivalenceKind(Importer));
2251 return Ctx.IsEquivalent(From, To);
2252}
2253
2254ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2255 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2256 << D->getDeclKindName();
2257 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2258}
2259
2260ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2261 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2262 << D->getDeclKindName();
2263 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2264}
2265
2266ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2267 // Import the context of this declaration.
2268 DeclContext *DC, *LexicalDC;
2269 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2270 return std::move(Err);
2271
2272 // Import the location of this declaration.
2273 ExpectedSLoc LocOrErr = import(D->getLocation());
2274 if (!LocOrErr)
2275 return LocOrErr.takeError();
2276
2277 EmptyDecl *ToD;
2278 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2279 return ToD;
2280
2281 ToD->setLexicalDeclContext(LexicalDC);
2282 LexicalDC->addDeclInternal(ToD);
2283 return ToD;
2284}
2285
2286ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2287 TranslationUnitDecl *ToD =
2288 Importer.getToContext().getTranslationUnitDecl();
2289
2290 Importer.MapImported(D, ToD);
2291
2292 return ToD;
2293}
2294
2295ExpectedDecl ASTNodeImporter::VisitBindingDecl(BindingDecl *D) {
2296 DeclContext *DC, *LexicalDC;
2297 DeclarationName Name;
2298 SourceLocation Loc;
2299 NamedDecl *ToND;
2300 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToND, Loc))
2301 return std::move(Err);
2302 if (ToND)
2303 return ToND;
2304
2305 BindingDecl *ToD;
2306 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, Loc,
2307 Name.getAsIdentifierInfo()))
2308 return ToD;
2309
2310 Error Err = Error::success();
2311 QualType ToType = importChecked(Err, D->getType());
2312 Expr *ToBinding = importChecked(Err, D->getBinding());
2313 ValueDecl *ToDecomposedDecl = importChecked(Err, D->getDecomposedDecl());
2314 if (Err)
2315 return std::move(Err);
2316
2317 ToD->setBinding(ToType, ToBinding);
2318 ToD->setDecomposedDecl(ToDecomposedDecl);
2319 addDeclToContexts(D, ToD);
2320
2321 return ToD;
2322}
2323
2324ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2325 ExpectedSLoc LocOrErr = import(D->getLocation());
2326 if (!LocOrErr)
2327 return LocOrErr.takeError();
2328 auto ColonLocOrErr = import(D->getColonLoc());
2329 if (!ColonLocOrErr)
2330 return ColonLocOrErr.takeError();
2331
2332 // Import the context of this declaration.
2333 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2334 if (!DCOrErr)
2335 return DCOrErr.takeError();
2336 DeclContext *DC = *DCOrErr;
2337
2338 AccessSpecDecl *ToD;
2339 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2340 DC, *LocOrErr, *ColonLocOrErr))
2341 return ToD;
2342
2343 // Lexical DeclContext and Semantic DeclContext
2344 // is always the same for the accessSpec.
2345 ToD->setLexicalDeclContext(DC);
2346 DC->addDeclInternal(ToD);
2347
2348 return ToD;
2349}
2350
2351ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2352 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2353 if (!DCOrErr)
2354 return DCOrErr.takeError();
2355 DeclContext *DC = *DCOrErr;
2356 DeclContext *LexicalDC = DC;
2357
2358 Error Err = Error::success();
2359 auto ToLocation = importChecked(Err, D->getLocation());
2360 auto ToRParenLoc = importChecked(Err, D->getRParenLoc());
2361 auto ToAssertExpr = importChecked(Err, D->getAssertExpr());
2362 auto ToMessage = importChecked(Err, D->getMessage());
2363 if (Err)
2364 return std::move(Err);
2365
2366 StaticAssertDecl *ToD;
2367 if (GetImportedOrCreateDecl(
2368 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2369 ToRParenLoc, D->isFailed()))
2370 return ToD;
2371
2372 ToD->setLexicalDeclContext(LexicalDC);
2373 LexicalDC->addDeclInternal(ToD);
2374 return ToD;
2375}
2376
2377ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2378 // Import the major distinguishing characteristics of this namespace.
2379 DeclContext *DC, *LexicalDC;
2380 DeclarationName Name;
2381 SourceLocation Loc;
2382 NamedDecl *ToD;
2383 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2384 return std::move(Err);
2385 if (ToD)
2386 return ToD;
2387
2388 NamespaceDecl *MergeWithNamespace = nullptr;
2389 if (!Name) {
2390 // This is an anonymous namespace. Adopt an existing anonymous
2391 // namespace if we can.
2392 // FIXME: Not testable.
2393 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2394 MergeWithNamespace = TU->getAnonymousNamespace();
2395 else
2396 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2397 } else {
2398 SmallVector<NamedDecl *, 4> ConflictingDecls;
2399 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2400 for (auto *FoundDecl : FoundDecls) {
2401 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2402 continue;
2403
2404 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2405 MergeWithNamespace = FoundNS;
2406 ConflictingDecls.clear();
2407 break;
2408 }
2409
2410 ConflictingDecls.push_back(FoundDecl);
2411 }
2412
2413 if (!ConflictingDecls.empty()) {
2414 ExpectedName NameOrErr = Importer.HandleNameConflict(
2415 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(),
2416 ConflictingDecls.size());
2417 if (NameOrErr)
2418 Name = NameOrErr.get();
2419 else
2420 return NameOrErr.takeError();
2421 }
2422 }
2423
2424 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2425 if (!BeginLocOrErr)
2426 return BeginLocOrErr.takeError();
2427 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
2428 if (!RBraceLocOrErr)
2429 return RBraceLocOrErr.takeError();
2430
2431 // Create the "to" namespace, if needed.
2432 NamespaceDecl *ToNamespace = MergeWithNamespace;
2433 if (!ToNamespace) {
2434 if (GetImportedOrCreateDecl(
2435 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2436 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2437 /*PrevDecl=*/nullptr))
2438 return ToNamespace;
2439 ToNamespace->setRBraceLoc(*RBraceLocOrErr);
2440 ToNamespace->setLexicalDeclContext(LexicalDC);
2441 LexicalDC->addDeclInternal(ToNamespace);
2442
2443 // If this is an anonymous namespace, register it as the anonymous
2444 // namespace within its context.
2445 if (!Name) {
2446 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2447 TU->setAnonymousNamespace(ToNamespace);
2448 else
2449 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2450 }
2451 }
2452 Importer.MapImported(D, ToNamespace);
2453
2454 if (Error Err = ImportDeclContext(D))
2455 return std::move(Err);
2456
2457 return ToNamespace;
2458}
2459
2460ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2461 // Import the major distinguishing characteristics of this namespace.
2462 DeclContext *DC, *LexicalDC;
2463 DeclarationName Name;
2464 SourceLocation Loc;
2465 NamedDecl *LookupD;
2466 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2467 return std::move(Err);
2468 if (LookupD)
2469 return LookupD;
2470
2471 // NOTE: No conflict resolution is done for namespace aliases now.
2472
2473 Error Err = Error::success();
2474 auto ToNamespaceLoc = importChecked(Err, D->getNamespaceLoc());
2475 auto ToAliasLoc = importChecked(Err, D->getAliasLoc());
2476 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2477 auto ToTargetNameLoc = importChecked(Err, D->getTargetNameLoc());
2478 auto ToNamespace = importChecked(Err, D->getNamespace());
2479 if (Err)
2480 return std::move(Err);
2481
2482 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2483
2484 NamespaceAliasDecl *ToD;
2485 if (GetImportedOrCreateDecl(
2486 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2487 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2488 return ToD;
2489
2490 ToD->setLexicalDeclContext(LexicalDC);
2491 LexicalDC->addDeclInternal(ToD);
2492
2493 return ToD;
2494}
2495
2496ExpectedDecl
2497ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2498 // Import the major distinguishing characteristics of this typedef.
2499 DeclarationName Name;
2500 SourceLocation Loc;
2501 NamedDecl *ToD;
2502 // Do not import the DeclContext, we will import it once the TypedefNameDecl
2503 // is created.
2504 if (Error Err = ImportDeclParts(D, Name, ToD, Loc))
2505 return std::move(Err);
2506 if (ToD)
2507 return ToD;
2508
2509 DeclContext *DC = cast_or_null<DeclContext>(
2510 Importer.GetAlreadyImportedOrNull(cast<Decl>(D->getDeclContext())));
2511 DeclContext *LexicalDC =
2512 cast_or_null<DeclContext>(Importer.GetAlreadyImportedOrNull(
2513 cast<Decl>(D->getLexicalDeclContext())));
2514
2515 // If this typedef is not in block scope, determine whether we've
2516 // seen a typedef with the same name (that we can merge with) or any
2517 // other entity by that name (which name lookup could conflict with).
2518 // Note: Repeated typedefs are not valid in C99:
2519 // 'typedef int T; typedef int T;' is invalid
2520 // We do not care about this now.
2521 if (DC && !DC->isFunctionOrMethod()) {
2522 SmallVector<NamedDecl *, 4> ConflictingDecls;
2523 unsigned IDNS = Decl::IDNS_Ordinary;
2524 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2525 for (auto *FoundDecl : FoundDecls) {
2526 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2527 continue;
2528 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2529 if (!hasSameVisibilityContextAndLinkage(FoundTypedef, D))
2530 continue;
2531
2532 QualType FromUT = D->getUnderlyingType();
2533 QualType FoundUT = FoundTypedef->getUnderlyingType();
2534 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2535 // If the "From" context has a complete underlying type but we
2536 // already have a complete underlying type then return with that.
2537 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2538 return Importer.MapImported(D, FoundTypedef);
2539 // FIXME Handle redecl chain. When you do that make consistent changes
2540 // in ASTImporterLookupTable too.
2541 } else {
2542 ConflictingDecls.push_back(FoundDecl);
2543 }
2544 }
2545 }
2546
2547 if (!ConflictingDecls.empty()) {
2548 ExpectedName NameOrErr = Importer.HandleNameConflict(
2549 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2550 if (NameOrErr)
2551 Name = NameOrErr.get();
2552 else
2553 return NameOrErr.takeError();
2554 }
2555 }
2556
2557 Error Err = Error::success();
2558 auto ToUnderlyingType = importChecked(Err, D->getUnderlyingType());
2559 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
2560 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2561 if (Err)
2562 return std::move(Err);
2563
2564 // Create the new typedef node.
2565 // FIXME: ToUnderlyingType is not used.
2566 (void)ToUnderlyingType;
2567 TypedefNameDecl *ToTypedef;
2568 if (IsAlias) {
2569 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2570 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2571 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2572 return ToTypedef;
2573 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2574 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2575 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2576 return ToTypedef;
2577
2578 // Import the DeclContext and set it to the Typedef.
2579 if ((Err = ImportDeclContext(D, DC, LexicalDC)))
2580 return std::move(Err);
2581 ToTypedef->setDeclContext(DC);
2582 ToTypedef->setLexicalDeclContext(LexicalDC);
2583 // Add to the lookupTable because we could not do that in MapImported.
2584 Importer.AddToLookupTable(ToTypedef);
2585
2586 ToTypedef->setAccess(D->getAccess());
2587
2588 // Templated declarations should not appear in DeclContext.
2589 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2590 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2591 LexicalDC->addDeclInternal(ToTypedef);
2592
2593 return ToTypedef;
2594}
2595
2596ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2597 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2598}
2599
2600ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2601 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2602}
2603
2604ExpectedDecl
2605ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2606 // Import the major distinguishing characteristics of this typedef.
2607 DeclContext *DC, *LexicalDC;
2608 DeclarationName Name;
2609 SourceLocation Loc;
2610 NamedDecl *FoundD;
2611 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2612 return std::move(Err);
2613 if (FoundD)
2614 return FoundD;
2615
2616 // If this typedef is not in block scope, determine whether we've
2617 // seen a typedef with the same name (that we can merge with) or any
2618 // other entity by that name (which name lookup could conflict with).
2619 if (!DC->isFunctionOrMethod()) {
2620 SmallVector<NamedDecl *, 4> ConflictingDecls;
2621 unsigned IDNS = Decl::IDNS_Ordinary;
2622 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2623 for (auto *FoundDecl : FoundDecls) {
2624 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2625 continue;
2626 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2627 return Importer.MapImported(D, FoundAlias);
2628 ConflictingDecls.push_back(FoundDecl);
2629 }
2630
2631 if (!ConflictingDecls.empty()) {
2632 ExpectedName NameOrErr = Importer.HandleNameConflict(
2633 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
2634 if (NameOrErr)
2635 Name = NameOrErr.get();
2636 else
2637 return NameOrErr.takeError();
2638 }
2639 }
2640
2641 Error Err = Error::success();
2642 auto ToTemplateParameters = importChecked(Err, D->getTemplateParameters());
2643 auto ToTemplatedDecl = importChecked(Err, D->getTemplatedDecl());
2644 if (Err)
2645 return std::move(Err);
2646
2647 TypeAliasTemplateDecl *ToAlias;
2648 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2649 Name, ToTemplateParameters, ToTemplatedDecl))
2650 return ToAlias;
2651
2652 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2653
2654 ToAlias->setAccess(D->getAccess());
2655 ToAlias->setLexicalDeclContext(LexicalDC);
2656 LexicalDC->addDeclInternal(ToAlias);
2657 if (DC != Importer.getToContext().getTranslationUnitDecl())
2658 updateLookupTableForTemplateParameters(*ToTemplateParameters);
2659 return ToAlias;
2660}
2661
2662ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2663 // Import the major distinguishing characteristics of this label.
2664 DeclContext *DC, *LexicalDC;
2665 DeclarationName Name;
2666 SourceLocation Loc;
2667 NamedDecl *ToD;
2668 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2669 return std::move(Err);
2670 if (ToD)
2671 return ToD;
2672
2673 assert(LexicalDC->isFunctionOrMethod())(static_cast <bool> (LexicalDC->isFunctionOrMethod()
) ? void (0) : __assert_fail ("LexicalDC->isFunctionOrMethod()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 2673, __extension__ __PRETTY_FUNCTION__))
;
2674
2675 LabelDecl *ToLabel;
2676 if (D->isGnuLocal()) {
2677 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2678 if (!BeginLocOrErr)
2679 return BeginLocOrErr.takeError();
2680 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2681 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2682 return ToLabel;
2683
2684 } else {
2685 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2686 Name.getAsIdentifierInfo()))
2687 return ToLabel;
2688
2689 }
2690
2691 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2692 if (!ToStmtOrErr)
2693 return ToStmtOrErr.takeError();
2694
2695 ToLabel->setStmt(*ToStmtOrErr);
2696 ToLabel->setLexicalDeclContext(LexicalDC);
2697 LexicalDC->addDeclInternal(ToLabel);
2698 return ToLabel;
2699}
2700
2701ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2702 // Import the major distinguishing characteristics of this enum.
2703 DeclContext *DC, *LexicalDC;
2704 DeclarationName Name;
2705 SourceLocation Loc;
2706 NamedDecl *ToD;
2707 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2708 return std::move(Err);
2709 if (ToD)
2710 return ToD;
2711
2712 // Figure out what enum name we're looking for.
2713 unsigned IDNS = Decl::IDNS_Tag;
2714 DeclarationName SearchName = Name;
2715 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2716 if (Error Err = importInto(
2717 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2718 return std::move(Err);
2719 IDNS = Decl::IDNS_Ordinary;
2720 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2721 IDNS |= Decl::IDNS_Ordinary;
2722
2723 // We may already have an enum of the same name; try to find and match it.
2724 EnumDecl *PrevDecl = nullptr;
2725 if (!DC->isFunctionOrMethod() && SearchName) {
2726 SmallVector<NamedDecl *, 4> ConflictingDecls;
2727 auto FoundDecls =
2728 Importer.findDeclsInToCtx(DC, SearchName);
2729 for (auto *FoundDecl : FoundDecls) {
2730 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2731 continue;
2732
2733 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2734 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2735 FoundDecl = Tag->getDecl();
2736 }
2737
2738 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2739 if (!hasSameVisibilityContextAndLinkage(FoundEnum, D))
2740 continue;
2741 if (IsStructuralMatch(D, FoundEnum)) {
2742 EnumDecl *FoundDef = FoundEnum->getDefinition();
2743 if (D->isThisDeclarationADefinition() && FoundDef)
2744 return Importer.MapImported(D, FoundDef);
2745 PrevDecl = FoundEnum->getMostRecentDecl();
2746 break;
2747 }
2748 ConflictingDecls.push_back(FoundDecl);
2749 }
2750 }
2751
2752 if (!ConflictingDecls.empty()) {
2753 ExpectedName NameOrErr = Importer.HandleNameConflict(
2754 SearchName, DC, IDNS, ConflictingDecls.data(),
2755 ConflictingDecls.size());
2756 if (NameOrErr)
2757 Name = NameOrErr.get();
2758 else
2759 return NameOrErr.takeError();
2760 }
2761 }
2762
2763 Error Err = Error::success();
2764 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
2765 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
2766 auto ToIntegerType = importChecked(Err, D->getIntegerType());
2767 auto ToBraceRange = importChecked(Err, D->getBraceRange());
2768 if (Err)
2769 return std::move(Err);
2770
2771 // Create the enum declaration.
2772 EnumDecl *D2;
2773 if (GetImportedOrCreateDecl(
2774 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2775 Loc, Name.getAsIdentifierInfo(), PrevDecl, D->isScoped(),
2776 D->isScopedUsingClassTag(), D->isFixed()))
2777 return D2;
2778
2779 D2->setQualifierInfo(ToQualifierLoc);
2780 D2->setIntegerType(ToIntegerType);
2781 D2->setBraceRange(ToBraceRange);
2782 D2->setAccess(D->getAccess());
2783 D2->setLexicalDeclContext(LexicalDC);
2784 addDeclToContexts(D, D2);
2785
2786 if (MemberSpecializationInfo *MemberInfo = D->getMemberSpecializationInfo()) {
2787 TemplateSpecializationKind SK = MemberInfo->getTemplateSpecializationKind();
2788 EnumDecl *FromInst = D->getInstantiatedFromMemberEnum();
2789 if (Expected<EnumDecl *> ToInstOrErr = import(FromInst))
2790 D2->setInstantiationOfMemberEnum(*ToInstOrErr, SK);
2791 else
2792 return ToInstOrErr.takeError();
2793 if (ExpectedSLoc POIOrErr = import(MemberInfo->getPointOfInstantiation()))
2794 D2->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
2795 else
2796 return POIOrErr.takeError();
2797 }
2798
2799 // Import the definition
2800 if (D->isCompleteDefinition())
2801 if (Error Err = ImportDefinition(D, D2))
2802 return std::move(Err);
2803
2804 return D2;
2805}
2806
2807ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2808 bool IsFriendTemplate = false;
2809 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2810 IsFriendTemplate =
2811 DCXX->getDescribedClassTemplate() &&
2812 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2813 Decl::FOK_None;
2814 }
2815
2816 // Import the major distinguishing characteristics of this record.
2817 DeclContext *DC = nullptr, *LexicalDC = nullptr;
2818 DeclarationName Name;
2819 SourceLocation Loc;
2820 NamedDecl *ToD = nullptr;
2821 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2822 return std::move(Err);
2823 if (ToD)
2824 return ToD;
2825
2826 // Figure out what structure name we're looking for.
2827 unsigned IDNS = Decl::IDNS_Tag;
2828 DeclarationName SearchName = Name;
2829 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2830 if (Error Err = importInto(
2831 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2832 return std::move(Err);
2833 IDNS = Decl::IDNS_Ordinary;
2834 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2835 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2836
2837 // We may already have a record of the same name; try to find and match it.
2838 RecordDecl *PrevDecl = nullptr;
2839 if (!DC->isFunctionOrMethod() && !D->isLambda()) {
2840 SmallVector<NamedDecl *, 4> ConflictingDecls;
2841 auto FoundDecls =
2842 Importer.findDeclsInToCtx(DC, SearchName);
2843 if (!FoundDecls.empty()) {
2844 // We're going to have to compare D against potentially conflicting Decls,
2845 // so complete it.
2846 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2847 D->getASTContext().getExternalSource()->CompleteType(D);
2848 }
2849
2850 for (auto *FoundDecl : FoundDecls) {
2851 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2852 continue;
2853
2854 Decl *Found = FoundDecl;
2855 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2856 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2857 Found = Tag->getDecl();
2858 }
2859
2860 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2861 // Do not emit false positive diagnostic in case of unnamed
2862 // struct/union and in case of anonymous structs. Would be false
2863 // because there may be several anonymous/unnamed structs in a class.
2864 // E.g. these are both valid:
2865 // struct A { // unnamed structs
2866 // struct { struct A *next; } entry0;
2867 // struct { struct A *next; } entry1;
2868 // };
2869 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2870 if (!SearchName)
2871 if (!IsStructuralMatch(D, FoundRecord, false))
2872 continue;
2873
2874 if (!hasSameVisibilityContextAndLinkage(FoundRecord, D))
2875 continue;
2876
2877 if (IsStructuralMatch(D, FoundRecord)) {
2878 RecordDecl *FoundDef = FoundRecord->getDefinition();
2879 if (D->isThisDeclarationADefinition() && FoundDef) {
2880 // FIXME: Structural equivalence check should check for same
2881 // user-defined methods.
2882 Importer.MapImported(D, FoundDef);
2883 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2884 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2885 assert(FoundCXX && "Record type mismatch")(static_cast <bool> (FoundCXX && "Record type mismatch"
) ? void (0) : __assert_fail ("FoundCXX && \"Record type mismatch\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 2885, __extension__ __PRETTY_FUNCTION__))
;
2886
2887 if (!Importer.isMinimalImport())
2888 // FoundDef may not have every implicit method that D has
2889 // because implicit methods are created only if they are used.
2890 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2891 return std::move(Err);
2892 }
2893 }
2894 PrevDecl = FoundRecord->getMostRecentDecl();
2895 break;
2896 }
2897 ConflictingDecls.push_back(FoundDecl);
2898 } // kind is RecordDecl
2899 } // for
2900
2901 if (!ConflictingDecls.empty() && SearchName) {
2902 ExpectedName NameOrErr = Importer.HandleNameConflict(
2903 SearchName, DC, IDNS, ConflictingDecls.data(),
2904 ConflictingDecls.size());
2905 if (NameOrErr)
2906 Name = NameOrErr.get();
2907 else
2908 return NameOrErr.takeError();
2909 }
2910 }
2911
2912 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2913 if (!BeginLocOrErr)
2914 return BeginLocOrErr.takeError();
2915
2916 // Create the record declaration.
2917 RecordDecl *D2 = nullptr;
2918 CXXRecordDecl *D2CXX = nullptr;
2919 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2920 if (DCXX->isLambda()) {
2921 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2922 if (!TInfoOrErr)
2923 return TInfoOrErr.takeError();
2924 if (GetImportedOrCreateSpecialDecl(
2925 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2926 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2927 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2928 return D2CXX;
2929 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2930 if (!CDeclOrErr)
2931 return CDeclOrErr.takeError();
2932 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr,
2933 DCXX->hasKnownLambdaInternalLinkage());
2934 D2CXX->setDeviceLambdaManglingNumber(
2935 DCXX->getDeviceLambdaManglingNumber());
2936 } else if (DCXX->isInjectedClassName()) {
2937 // We have to be careful to do a similar dance to the one in
2938 // Sema::ActOnStartCXXMemberDeclarations
2939 const bool DelayTypeCreation = true;
2940 if (GetImportedOrCreateDecl(
2941 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2942 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2943 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2944 return D2CXX;
2945 Importer.getToContext().getTypeDeclType(
2946 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2947 } else {
2948 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2949 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2950 Name.getAsIdentifierInfo(),
2951 cast_or_null<CXXRecordDecl>(PrevDecl)))
2952 return D2CXX;
2953 }
2954
2955 D2 = D2CXX;
2956 D2->setAccess(D->getAccess());
2957 D2->setLexicalDeclContext(LexicalDC);
2958 addDeclToContexts(D, D2);
2959
2960 if (ClassTemplateDecl *FromDescribed =
2961 DCXX->getDescribedClassTemplate()) {
2962 ClassTemplateDecl *ToDescribed;
2963 if (Error Err = importInto(ToDescribed, FromDescribed))
2964 return std::move(Err);
2965 D2CXX->setDescribedClassTemplate(ToDescribed);
2966 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2967 // In a record describing a template the type should be an
2968 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2969 // previously set type to the correct value here (ToDescribed is not
2970 // available at record create).
2971 // FIXME: The previous type is cleared but not removed from
2972 // ASTContext's internal storage.
2973 CXXRecordDecl *Injected = nullptr;
2974 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2975 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2976 if (Record && Record->isInjectedClassName()) {
2977 Injected = Record;
2978 break;
2979 }
2980 }
2981 // Create an injected type for the whole redecl chain.
2982 SmallVector<Decl *, 2> Redecls =
2983 getCanonicalForwardRedeclChain(D2CXX);
2984 for (auto *R : Redecls) {
2985 auto *RI = cast<CXXRecordDecl>(R);
2986 RI->setTypeForDecl(nullptr);
2987 // Below we create a new injected type and assign that to the
2988 // canonical decl, subsequent declarations in the chain will reuse
2989 // that type.
2990 Importer.getToContext().getInjectedClassNameType(
2991 RI, ToDescribed->getInjectedClassNameSpecialization());
2992 }
2993 // Set the new type for the previous injected decl too.
2994 if (Injected) {
2995 Injected->setTypeForDecl(nullptr);
2996 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2997 }
2998 }
2999 } else if (MemberSpecializationInfo *MemberInfo =
3000 DCXX->getMemberSpecializationInfo()) {
3001 TemplateSpecializationKind SK =
3002 MemberInfo->getTemplateSpecializationKind();
3003 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
3004
3005 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
3006 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
3007 else
3008 return ToInstOrErr.takeError();
3009
3010 if (ExpectedSLoc POIOrErr =
3011 import(MemberInfo->getPointOfInstantiation()))
3012 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
3013 *POIOrErr);
3014 else
3015 return POIOrErr.takeError();
3016 }
3017
3018 } else {
3019 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
3020 D->getTagKind(), DC, *BeginLocOrErr, Loc,
3021 Name.getAsIdentifierInfo(), PrevDecl))
3022 return D2;
3023 D2->setLexicalDeclContext(LexicalDC);
3024 addDeclToContexts(D, D2);
3025 }
3026
3027 if (auto BraceRangeOrErr = import(D->getBraceRange()))
3028 D2->setBraceRange(*BraceRangeOrErr);
3029 else
3030 return BraceRangeOrErr.takeError();
3031 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
3032 D2->setQualifierInfo(*QualifierLocOrErr);
3033 else
3034 return QualifierLocOrErr.takeError();
3035
3036 if (D->isAnonymousStructOrUnion())
3037 D2->setAnonymousStructOrUnion(true);
3038
3039 if (D->isCompleteDefinition())
3040 if (Error Err = ImportDefinition(D, D2, IDK_Default))
3041 return std::move(Err);
3042
3043 return D2;
3044}
3045
3046ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
3047 // Import the major distinguishing characteristics of this enumerator.
3048 DeclContext *DC, *LexicalDC;
3049 DeclarationName Name;
3050 SourceLocation Loc;
3051 NamedDecl *ToD;
3052 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3053 return std::move(Err);
3054 if (ToD)
3055 return ToD;
3056
3057 // Determine whether there are any other declarations with the same name and
3058 // in the same context.
3059 if (!LexicalDC->isFunctionOrMethod()) {
3060 SmallVector<NamedDecl *, 4> ConflictingDecls;
3061 unsigned IDNS = Decl::IDNS_Ordinary;
3062 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3063 for (auto *FoundDecl : FoundDecls) {
3064 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3065 continue;
3066
3067 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
3068 if (IsStructuralMatch(D, FoundEnumConstant))
3069 return Importer.MapImported(D, FoundEnumConstant);
3070 ConflictingDecls.push_back(FoundDecl);
3071 }
3072 }
3073
3074 if (!ConflictingDecls.empty()) {
3075 ExpectedName NameOrErr = Importer.HandleNameConflict(
3076 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3077 if (NameOrErr)
3078 Name = NameOrErr.get();
3079 else
3080 return NameOrErr.takeError();
3081 }
3082 }
3083
3084 ExpectedType TypeOrErr = import(D->getType());
3085 if (!TypeOrErr)
3086 return TypeOrErr.takeError();
3087
3088 ExpectedExpr InitOrErr = import(D->getInitExpr());
3089 if (!InitOrErr)
3090 return InitOrErr.takeError();
3091
3092 EnumConstantDecl *ToEnumerator;
3093 if (GetImportedOrCreateDecl(
3094 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
3095 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
3096 return ToEnumerator;
3097
3098 ToEnumerator->setAccess(D->getAccess());
3099 ToEnumerator->setLexicalDeclContext(LexicalDC);
3100 LexicalDC->addDeclInternal(ToEnumerator);
3101 return ToEnumerator;
3102}
3103
3104Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
3105 DeclaratorDecl *ToD) {
3106 unsigned int Num = FromD->getNumTemplateParameterLists();
3107 if (Num == 0)
3108 return Error::success();
3109 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
3110 for (unsigned int I = 0; I < Num; ++I)
3111 if (Expected<TemplateParameterList *> ToTPListOrErr =
3112 import(FromD->getTemplateParameterList(I)))
3113 ToTPLists[I] = *ToTPListOrErr;
3114 else
3115 return ToTPListOrErr.takeError();
3116 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
3117 return Error::success();
3118}
3119
3120Error ASTNodeImporter::ImportTemplateInformation(
3121 FunctionDecl *FromFD, FunctionDecl *ToFD) {
3122 switch (FromFD->getTemplatedKind()) {
3123 case FunctionDecl::TK_NonTemplate:
3124 case FunctionDecl::TK_FunctionTemplate:
3125 return Error::success();
3126
3127 case FunctionDecl::TK_MemberSpecialization: {
3128 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
3129
3130 if (Expected<FunctionDecl *> InstFDOrErr =
3131 import(FromFD->getInstantiatedFromMemberFunction()))
3132 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
3133 else
3134 return InstFDOrErr.takeError();
3135
3136 if (ExpectedSLoc POIOrErr = import(
3137 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
3138 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
3139 else
3140 return POIOrErr.takeError();
3141
3142 return Error::success();
3143 }
3144
3145 case FunctionDecl::TK_FunctionTemplateSpecialization: {
3146 auto FunctionAndArgsOrErr =
3147 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3148 if (!FunctionAndArgsOrErr)
3149 return FunctionAndArgsOrErr.takeError();
3150
3151 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
3152 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
3153
3154 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
3155 TemplateArgumentListInfo ToTAInfo;
3156 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
3157 if (FromTAArgsAsWritten)
3158 if (Error Err = ImportTemplateArgumentListInfo(
3159 *FromTAArgsAsWritten, ToTAInfo))
3160 return Err;
3161
3162 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
3163 if (!POIOrErr)
3164 return POIOrErr.takeError();
3165
3166 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
3167 return Err;
3168
3169 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
3170 ToFD->setFunctionTemplateSpecialization(
3171 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
3172 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
3173 return Error::success();
3174 }
3175
3176 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
3177 auto *FromInfo = FromFD->getDependentSpecializationInfo();
3178 UnresolvedSet<8> TemplDecls;
3179 unsigned NumTemplates = FromInfo->getNumTemplates();
3180 for (unsigned I = 0; I < NumTemplates; I++) {
3181 if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
3182 import(FromInfo->getTemplate(I)))
3183 TemplDecls.addDecl(*ToFTDOrErr);
3184 else
3185 return ToFTDOrErr.takeError();
3186 }
3187
3188 // Import TemplateArgumentListInfo.
3189 TemplateArgumentListInfo ToTAInfo;
3190 if (Error Err = ImportTemplateArgumentListInfo(
3191 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
3192 llvm::makeArrayRef(
3193 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
3194 ToTAInfo))
3195 return Err;
3196
3197 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
3198 TemplDecls, ToTAInfo);
3199 return Error::success();
3200 }
3201 }
3202 llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3202)
;
3203}
3204
3205Expected<FunctionDecl *>
3206ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
3207 auto FunctionAndArgsOrErr =
3208 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
3209 if (!FunctionAndArgsOrErr)
3210 return FunctionAndArgsOrErr.takeError();
3211
3212 FunctionTemplateDecl *Template;
3213 TemplateArgsTy ToTemplArgs;
3214 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
3215 void *InsertPos = nullptr;
3216 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
3217 return FoundSpec;
3218}
3219
3220Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
3221 FunctionDecl *ToFD) {
3222 if (Stmt *FromBody = FromFD->getBody()) {
3223 if (ExpectedStmt ToBodyOrErr = import(FromBody))
3224 ToFD->setBody(*ToBodyOrErr);
3225 else
3226 return ToBodyOrErr.takeError();
3227 }
3228 return Error::success();
3229}
3230
3231// Returns true if the given D has a DeclContext up to the TranslationUnitDecl
3232// which is equal to the given DC.
3233static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) {
3234 const DeclContext *DCi = D->getDeclContext();
3235 while (DCi != D->getTranslationUnitDecl()) {
3236 if (DCi == DC)
3237 return true;
3238 DCi = DCi->getParent();
3239 }
3240 return false;
3241}
3242
3243bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) {
3244 QualType FromTy = D->getType();
3245 const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>();
3246 assert(FromFPT && "Must be called on FunctionProtoType")(static_cast <bool> (FromFPT && "Must be called on FunctionProtoType"
) ? void (0) : __assert_fail ("FromFPT && \"Must be called on FunctionProtoType\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3246, __extension__ __PRETTY_FUNCTION__))
;
3247 if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) {
3248 QualType DeducedT = AutoT->getDeducedType();
3249 if (const RecordType *RecordT =
3250 DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) {
3251 RecordDecl *RD = RecordT->getDecl();
3252 assert(RD)(static_cast <bool> (RD) ? void (0) : __assert_fail ("RD"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3252, __extension__ __PRETTY_FUNCTION__))
;
3253 if (isAncestorDeclContextOf(D, RD)) {
3254 assert(RD->getLexicalDeclContext() == RD->getDeclContext())(static_cast <bool> (RD->getLexicalDeclContext() == RD
->getDeclContext()) ? void (0) : __assert_fail ("RD->getLexicalDeclContext() == RD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3254, __extension__ __PRETTY_FUNCTION__))
;
3255 return true;
3256 }
3257 }
3258 }
3259 if (const TypedefType *TypedefT =
3260 dyn_cast<TypedefType>(FromFPT->getReturnType())) {
3261 TypedefNameDecl *TD = TypedefT->getDecl();
3262 assert(TD)(static_cast <bool> (TD) ? void (0) : __assert_fail ("TD"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3262, __extension__ __PRETTY_FUNCTION__))
;
3263 if (isAncestorDeclContextOf(D, TD)) {
3264 assert(TD->getLexicalDeclContext() == TD->getDeclContext())(static_cast <bool> (TD->getLexicalDeclContext() == TD
->getDeclContext()) ? void (0) : __assert_fail ("TD->getLexicalDeclContext() == TD->getDeclContext()"
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3264, __extension__ __PRETTY_FUNCTION__))
;
3265 return true;
3266 }
3267 }
3268 return false;
3269}
3270
3271ExplicitSpecifier
3272ASTNodeImporter::importExplicitSpecifier(Error &Err, ExplicitSpecifier ESpec) {
3273 Expr *ExplicitExpr = ESpec.getExpr();
3274 if (ExplicitExpr)
3275 ExplicitExpr = importChecked(Err, ESpec.getExpr());
3276 return ExplicitSpecifier(ExplicitExpr, ESpec.getKind());
3277}
3278
3279ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
3280
3281 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
3282 auto RedeclIt = Redecls.begin();
3283 // Import the first part of the decl chain. I.e. import all previous
3284 // declarations starting from the canonical decl.
3285 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3286 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3287 if (!ToRedeclOrErr)
3288 return ToRedeclOrErr.takeError();
3289 }
3290 assert(*RedeclIt == D)(static_cast <bool> (*RedeclIt == D) ? void (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3290, __extension__ __PRETTY_FUNCTION__))
;
3291
3292 // Import the major distinguishing characteristics of this function.
3293 DeclContext *DC, *LexicalDC;
3294 DeclarationName Name;
3295 SourceLocation Loc;
3296 NamedDecl *ToD;
3297 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3298 return std::move(Err);
3299 if (ToD)
3300 return ToD;
3301
3302 FunctionDecl *FoundByLookup = nullptr;
3303 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
3304
3305 // If this is a function template specialization, then try to find the same
3306 // existing specialization in the "to" context. The lookup below will not
3307 // find any specialization, but would find the primary template; thus, we
3308 // have to skip normal lookup in case of specializations.
3309 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
3310 if (D->getTemplatedKind() ==
3311 FunctionDecl::TK_FunctionTemplateSpecialization) {
3312 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
3313 if (!FoundFunctionOrErr)
3314 return FoundFunctionOrErr.takeError();
3315 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
3316 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3317 return Def;
3318 FoundByLookup = FoundFunction;
3319 }
3320 }
3321 // Try to find a function in our own ("to") context with the same name, same
3322 // type, and in the same context as the function we're importing.
3323 else if (!LexicalDC->isFunctionOrMethod()) {
3324 SmallVector<NamedDecl *, 4> ConflictingDecls;
3325 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
3326 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3327 for (auto *FoundDecl : FoundDecls) {
3328 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3329 continue;
3330
3331 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
3332 if (!hasSameVisibilityContextAndLinkage(FoundFunction, D))
3333 continue;
3334
3335 if (IsStructuralMatch(D, FoundFunction)) {
3336 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
3337 return Def;
3338 FoundByLookup = FoundFunction;
3339 break;
3340 }
3341 // FIXME: Check for overloading more carefully, e.g., by boosting
3342 // Sema::IsOverload out to the AST library.
3343
3344 // Function overloading is okay in C++.
3345 if (Importer.getToContext().getLangOpts().CPlusPlus)
3346 continue;
3347
3348 // Complain about inconsistent function types.
3349 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
3350 << Name << D->getType() << FoundFunction->getType();
3351 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3352 << FoundFunction->getType();
3353 ConflictingDecls.push_back(FoundDecl);
3354 }
3355 }
3356
3357 if (!ConflictingDecls.empty()) {
3358 ExpectedName NameOrErr = Importer.HandleNameConflict(
3359 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
3360 if (NameOrErr)
3361 Name = NameOrErr.get();
3362 else
3363 return NameOrErr.takeError();
3364 }
3365 }
3366
3367 // We do not allow more than one in-class declaration of a function. This is
3368 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3369 // assumes there is only one in-class declaration. Building a redecl
3370 // chain would result in more than one in-class declaration for
3371 // overrides (even if they are part of the same redecl chain inside the
3372 // derived class.)
3373 if (FoundByLookup) {
3374 if (isa<CXXMethodDecl>(FoundByLookup)) {
3375 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3376 if (!D->doesThisDeclarationHaveABody()) {
3377 if (FunctionTemplateDecl *DescribedD =
3378 D->getDescribedFunctionTemplate()) {
3379 // Handle a "templated" function together with its described
3380 // template. This avoids need for a similar check at import of the
3381 // described template.
3382 assert(FoundByLookup->getDescribedFunctionTemplate() &&(static_cast <bool> (FoundByLookup->getDescribedFunctionTemplate
() && "Templated function mapped to non-templated?") ?
void (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3383, __extension__ __PRETTY_FUNCTION__))
3383 "Templated function mapped to non-templated?")(static_cast <bool> (FoundByLookup->getDescribedFunctionTemplate
() && "Templated function mapped to non-templated?") ?
void (0) : __assert_fail ("FoundByLookup->getDescribedFunctionTemplate() && \"Templated function mapped to non-templated?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3383, __extension__ __PRETTY_FUNCTION__))
;
3384 Importer.MapImported(DescribedD,
3385 FoundByLookup->getDescribedFunctionTemplate());
3386 }
3387 return Importer.MapImported(D, FoundByLookup);
3388 } else {
3389 // Let's continue and build up the redecl chain in this case.
3390 // FIXME Merge the functions into one decl.
3391 }
3392 }
3393 }
3394 }
3395
3396 DeclarationNameInfo NameInfo(Name, Loc);
3397 // Import additional name location/type info.
3398 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3399 return std::move(Err);
3400
3401 QualType FromTy = D->getType();
3402 // Set to true if we do not import the type of the function as is. There are
3403 // cases when the original type would result in an infinite recursion during
3404 // the import. To avoid an infinite recursion when importing, we create the
3405 // FunctionDecl with a simplified function type and update it only after the
3406 // relevant AST nodes are already imported.
3407 bool UsedDifferentProtoType = false;
3408 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) {
3409 QualType FromReturnTy = FromFPT->getReturnType();
3410 // Functions with auto return type may define a struct inside their body
3411 // and the return type could refer to that struct.
3412 // E.g.: auto foo() { struct X{}; return X(); }
3413 // To avoid an infinite recursion when importing, create the FunctionDecl
3414 // with a simplified return type.
3415 if (hasAutoReturnTypeDeclaredInside(D)) {
3416 FromReturnTy = Importer.getFromContext().VoidTy;
3417 UsedDifferentProtoType = true;
3418 }
3419 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3420 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3421 // FunctionDecl that we are importing the FunctionProtoType for.
3422 // To avoid an infinite recursion when importing, create the FunctionDecl
3423 // with a simplified function type.
3424 if (FromEPI.ExceptionSpec.SourceDecl ||
3425 FromEPI.ExceptionSpec.SourceTemplate ||
3426 FromEPI.ExceptionSpec.NoexceptExpr) {
3427 FunctionProtoType::ExtProtoInfo DefaultEPI;
3428 FromEPI = DefaultEPI;
3429 UsedDifferentProtoType = true;
3430 }
3431 FromTy = Importer.getFromContext().getFunctionType(
3432 FromReturnTy, FromFPT->getParamTypes(), FromEPI);
3433 }
3434
3435 Error Err = Error::success();
3436 auto T = importChecked(Err, FromTy);
3437 auto TInfo = importChecked(Err, D->getTypeSourceInfo());
3438 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3439 auto ToEndLoc = importChecked(Err, D->getEndLoc());
3440 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
3441 auto TrailingRequiresClause =
3442 importChecked(Err, D->getTrailingRequiresClause());
3443 if (Err)
3444 return std::move(Err);
3445
3446 // Import the function parameters.
3447 SmallVector<ParmVarDecl *, 8> Parameters;
3448 for (auto P : D->parameters()) {
3449 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3450 Parameters.push_back(*ToPOrErr);
3451 else
3452 return ToPOrErr.takeError();
3453 }
3454
3455 // Create the imported function.
3456 FunctionDecl *ToFunction = nullptr;
3457 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3458 ExplicitSpecifier ESpec =
3459 importExplicitSpecifier(Err, FromConstructor->getExplicitSpecifier());
3460 if (Err)
3461 return std::move(Err);
3462 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3463 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3464 ToInnerLocStart, NameInfo, T, TInfo, ESpec, D->UsesFPIntrin(),
3465 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3466 InheritedConstructor(), // FIXME: Properly import inherited
3467 // constructor info
3468 TrailingRequiresClause))
3469 return ToFunction;
3470 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3471
3472 Error Err = Error::success();
3473 auto ToOperatorDelete = importChecked(
3474 Err, const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()));
3475 auto ToThisArg = importChecked(Err, FromDtor->getOperatorDeleteThisArg());
3476 if (Err)
3477 return std::move(Err);
3478
3479 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3480 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3481 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3482 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(),
3483 TrailingRequiresClause))
3484 return ToFunction;
3485
3486 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3487
3488 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3489 } else if (CXXConversionDecl *FromConversion =
3490 dyn_cast<CXXConversionDecl>(D)) {
3491 ExplicitSpecifier ESpec =
3492 importExplicitSpecifier(Err, FromConversion->getExplicitSpecifier());
3493 if (Err)
3494 return std::move(Err);
3495 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3496 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3497 ToInnerLocStart, NameInfo, T, TInfo, D->UsesFPIntrin(),
3498 D->isInlineSpecified(), ESpec, D->getConstexprKind(),
3499 SourceLocation(), TrailingRequiresClause))
3500 return ToFunction;
3501 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3502 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3503 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3504 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3505 Method->UsesFPIntrin(), Method->isInlineSpecified(),
3506 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause))
3507 return ToFunction;
3508 } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(D)) {
3509 ExplicitSpecifier ESpec =
3510 importExplicitSpecifier(Err, Guide->getExplicitSpecifier());
3511 CXXConstructorDecl *Ctor =
3512 importChecked(Err, Guide->getCorrespondingConstructor());
3513 if (Err)
3514 return std::move(Err);
3515 if (GetImportedOrCreateDecl<CXXDeductionGuideDecl>(
3516 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, ESpec,
3517 NameInfo, T, TInfo, ToEndLoc, Ctor))
3518 return ToFunction;
3519 cast<CXXDeductionGuideDecl>(ToFunction)
3520 ->setIsCopyDeductionCandidate(Guide->isCopyDeductionCandidate());
3521 } else {
3522 if (GetImportedOrCreateDecl(
3523 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart,
3524 NameInfo, T, TInfo, D->getStorageClass(), D->UsesFPIntrin(),
3525 D->isInlineSpecified(), D->hasWrittenPrototype(),
3526 D->getConstexprKind(), TrailingRequiresClause))
3527 return ToFunction;
3528 }
3529
3530 // Connect the redecl chain.
3531 if (FoundByLookup) {
3532 auto *Recent = const_cast<FunctionDecl *>(
3533 FoundByLookup->getMostRecentDecl());
3534 ToFunction->setPreviousDecl(Recent);
3535 // FIXME Probably we should merge exception specifications. E.g. In the
3536 // "To" context the existing function may have exception specification with
3537 // noexcept-unevaluated, while the newly imported function may have an
3538 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3539 // decl and its redeclarations may be required.
3540 }
3541
3542 ToFunction->setQualifierInfo(ToQualifierLoc);
3543 ToFunction->setAccess(D->getAccess());
3544 ToFunction->setLexicalDeclContext(LexicalDC);
3545 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3546 ToFunction->setTrivial(D->isTrivial());
3547 ToFunction->setPure(D->isPure());
3548 ToFunction->setDefaulted(D->isDefaulted());
3549 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted());
3550 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten());
3551 ToFunction->setRangeEnd(ToEndLoc);
3552
3553 // Set the parameters.
3554 for (auto *Param : Parameters) {
3555 Param->setOwningFunction(ToFunction);
3556 ToFunction->addDeclInternal(Param);
3557 if (ASTImporterLookupTable *LT = Importer.SharedState->getLookupTable())
3558 LT->update(Param, Importer.getToContext().getTranslationUnitDecl());
3559 }
3560 ToFunction->setParams(Parameters);
3561
3562 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3563 // params it refers to.
3564 if (TInfo) {
3565 if (auto ProtoLoc =
3566 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3567 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3568 ProtoLoc.setParam(I, Parameters[I]);
3569 }
3570 }
3571
3572 // Import the describing template function, if any.
3573 if (FromFT) {
3574 auto ToFTOrErr = import(FromFT);
3575 if (!ToFTOrErr)
3576 return ToFTOrErr.takeError();
3577 }
3578
3579 // Import Ctor initializers.
3580 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3581 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3582 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3583 // Import first, then allocate memory and copy if there was no error.
3584 if (Error Err = ImportContainerChecked(
3585 FromConstructor->inits(), CtorInitializers))
3586 return std::move(Err);
3587 auto **Memory =
3588 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3589 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3590 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3591 ToCtor->setCtorInitializers(Memory);
3592 ToCtor->setNumCtorInitializers(NumInitializers);
3593 }
3594 }
3595
3596 if (D->doesThisDeclarationHaveABody()) {
3597 Error Err = ImportFunctionDeclBody(D, ToFunction);
3598
3599 if (Err)
3600 return std::move(Err);
3601 }
3602
3603 // Import and set the original type in case we used another type.
3604 if (UsedDifferentProtoType) {
3605 if (ExpectedType TyOrErr = import(D->getType()))
3606 ToFunction->setType(*TyOrErr);
3607 else
3608 return TyOrErr.takeError();
3609 }
3610
3611 // FIXME: Other bits to merge?
3612
3613 // If it is a template, import all related things.
3614 if (Error Err = ImportTemplateInformation(D, ToFunction))
3615 return std::move(Err);
3616
3617 addDeclToContexts(D, ToFunction);
3618
3619 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3620 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction),
3621 FromCXXMethod))
3622 return std::move(Err);
3623
3624 // Import the rest of the chain. I.e. import all subsequent declarations.
3625 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3626 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3627 if (!ToRedeclOrErr)
3628 return ToRedeclOrErr.takeError();
3629 }
3630
3631 return ToFunction;
3632}
3633
3634ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3635 return VisitFunctionDecl(D);
3636}
3637
3638ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3639 return VisitCXXMethodDecl(D);
3640}
3641
3642ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3643 return VisitCXXMethodDecl(D);
3644}
3645
3646ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3647 return VisitCXXMethodDecl(D);
3648}
3649
3650ExpectedDecl
3651ASTNodeImporter::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3652 return VisitFunctionDecl(D);
3653}
3654
3655ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3656 // Import the major distinguishing characteristics of a variable.
3657 DeclContext *DC, *LexicalDC;
3658 DeclarationName Name;
3659 SourceLocation Loc;
3660 NamedDecl *ToD;
3661 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3662 return std::move(Err);
3663 if (ToD)
3664 return ToD;
3665
3666 // Determine whether we've already imported this field.
3667 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3668 for (auto *FoundDecl : FoundDecls) {
3669 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3670 // For anonymous fields, match up by index.
3671 if (!Name &&
3672 ASTImporter::getFieldIndex(D) !=
3673 ASTImporter::getFieldIndex(FoundField))
3674 continue;
3675
3676 if (Importer.IsStructurallyEquivalent(D->getType(),
3677 FoundField->getType())) {
3678 Importer.MapImported(D, FoundField);
3679 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3680 // initializer of a FieldDecl might not had been instantiated in the
3681 // "To" context. However, the "From" context might instantiated that,
3682 // thus we have to merge that.
3683 if (Expr *FromInitializer = D->getInClassInitializer()) {
3684 // We don't have yet the initializer set.
3685 if (FoundField->hasInClassInitializer() &&
3686 !FoundField->getInClassInitializer()) {
3687 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3688 FoundField->setInClassInitializer(*ToInitializerOrErr);
3689 else {
3690 // We can't return error here,
3691 // since we already mapped D as imported.
3692 // FIXME: warning message?
3693 consumeError(ToInitializerOrErr.takeError());
3694 return FoundField;
3695 }
3696 }
3697 }
3698 return FoundField;
3699 }
3700
3701 // FIXME: Why is this case not handled with calling HandleNameConflict?
3702 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3703 << Name << D->getType() << FoundField->getType();
3704 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3705 << FoundField->getType();
3706
3707 return make_error<ImportError>(ImportError::NameConflict);
3708 }
3709 }
3710
3711 Error Err = Error::success();
3712 auto ToType = importChecked(Err, D->getType());
3713 auto ToTInfo = importChecked(Err, D->getTypeSourceInfo());
3714 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3715 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3716 auto ToInitializer = importChecked(Err, D->getInClassInitializer());
3717 if (Err)
3718 return std::move(Err);
3719 const Type *ToCapturedVLAType = nullptr;
3720 if (Error Err = Importer.importInto(
3721 ToCapturedVLAType, cast_or_null<Type>(D->getCapturedVLAType())))
3722 return std::move(Err);
3723
3724 FieldDecl *ToField;
3725 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3726 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3727 ToType, ToTInfo, ToBitWidth, D->isMutable(),
3728 D->getInClassInitStyle()))
3729 return ToField;
3730
3731 ToField->setAccess(D->getAccess());
3732 ToField->setLexicalDeclContext(LexicalDC);
3733 if (ToInitializer)
3734 ToField->setInClassInitializer(ToInitializer);
3735 ToField->setImplicit(D->isImplicit());
3736 if (ToCapturedVLAType)
3737 ToField->setCapturedVLAType(cast<VariableArrayType>(ToCapturedVLAType));
3738 LexicalDC->addDeclInternal(ToField);
3739 return ToField;
3740}
3741
3742ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3743 // Import the major distinguishing characteristics of a variable.
3744 DeclContext *DC, *LexicalDC;
3745 DeclarationName Name;
3746 SourceLocation Loc;
3747 NamedDecl *ToD;
3748 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3749 return std::move(Err);
3750 if (ToD)
3751 return ToD;
3752
3753 // Determine whether we've already imported this field.
3754 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3755 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3756 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3757 // For anonymous indirect fields, match up by index.
3758 if (!Name &&
3759 ASTImporter::getFieldIndex(D) !=
3760 ASTImporter::getFieldIndex(FoundField))
3761 continue;
3762
3763 if (Importer.IsStructurallyEquivalent(D->getType(),
3764 FoundField->getType(),
3765 !Name.isEmpty())) {
3766 Importer.MapImported(D, FoundField);
3767 return FoundField;
3768 }
3769
3770 // If there are more anonymous fields to check, continue.
3771 if (!Name && I < N-1)
3772 continue;
3773
3774 // FIXME: Why is this case not handled with calling HandleNameConflict?
3775 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3776 << Name << D->getType() << FoundField->getType();
3777 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3778 << FoundField->getType();
3779
3780 return make_error<ImportError>(ImportError::NameConflict);
3781 }
3782 }
3783
3784 // Import the type.
3785 auto TypeOrErr = import(D->getType());
3786 if (!TypeOrErr)
3787 return TypeOrErr.takeError();
3788
3789 auto **NamedChain =
3790 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3791
3792 unsigned i = 0;
3793 for (auto *PI : D->chain())
3794 if (Expected<NamedDecl *> ToD = import(PI))
3795 NamedChain[i++] = *ToD;
3796 else
3797 return ToD.takeError();
3798
3799 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3800 IndirectFieldDecl *ToIndirectField;
3801 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3802 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3803 // FIXME here we leak `NamedChain` which is allocated before
3804 return ToIndirectField;
3805
3806 ToIndirectField->setAccess(D->getAccess());
3807 ToIndirectField->setLexicalDeclContext(LexicalDC);
3808 LexicalDC->addDeclInternal(ToIndirectField);
3809 return ToIndirectField;
3810}
3811
3812/// Used as return type of getFriendCountAndPosition.
3813struct FriendCountAndPosition {
3814 /// Number of similar looking friends.
3815 unsigned int TotalCount;
3816 /// Index of the specific FriendDecl.
3817 unsigned int IndexOfDecl;
3818};
3819
3820template <class T>
3821static FriendCountAndPosition getFriendCountAndPosition(
3822 const FriendDecl *FD,
3823 llvm::function_ref<T(const FriendDecl *)> GetCanTypeOrDecl) {
3824 unsigned int FriendCount = 0;
3825 llvm::Optional<unsigned int> FriendPosition;
3826 const auto *RD = cast<CXXRecordDecl>(FD->getLexicalDeclContext());
3827
3828 T TypeOrDecl = GetCanTypeOrDecl(FD);
3829
3830 for (const FriendDecl *FoundFriend : RD->friends()) {
3831 if (FoundFriend == FD) {
3832 FriendPosition = FriendCount;
3833 ++FriendCount;
3834 } else if (!FoundFriend->getFriendDecl() == !FD->getFriendDecl() &&
3835 GetCanTypeOrDecl(FoundFriend) == TypeOrDecl) {
3836 ++FriendCount;
3837 }
3838 }
3839
3840 assert(FriendPosition && "Friend decl not found in own parent.")(static_cast <bool> (FriendPosition && "Friend decl not found in own parent."
) ? void (0) : __assert_fail ("FriendPosition && \"Friend decl not found in own parent.\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3840, __extension__ __PRETTY_FUNCTION__))
;
3841
3842 return {FriendCount, *FriendPosition};
3843}
3844
3845static FriendCountAndPosition getFriendCountAndPosition(const FriendDecl *FD) {
3846 if (FD->getFriendType())
3847 return getFriendCountAndPosition<QualType>(FD, [](const FriendDecl *F) {
3848 if (TypeSourceInfo *TSI = F->getFriendType())
3849 return TSI->getType().getCanonicalType();
3850 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3850)
;
3851 });
3852 else
3853 return getFriendCountAndPosition<Decl *>(FD, [](const FriendDecl *F) {
3854 if (Decl *D = F->getFriendDecl())
3855 return D->getCanonicalDecl();
3856 llvm_unreachable("Wrong friend object type.")::llvm::llvm_unreachable_internal("Wrong friend object type."
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3856)
;
3857 });
3858}
3859
3860ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3861 // Import the major distinguishing characteristics of a declaration.
3862 DeclContext *DC, *LexicalDC;
3863 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3864 return std::move(Err);
3865
3866 // Determine whether we've already imported this decl.
3867 // FriendDecl is not a NamedDecl so we cannot use lookup.
3868 // We try to maintain order and count of redundant friend declarations.
3869 const auto *RD = cast<CXXRecordDecl>(DC);
3870 FriendDecl *ImportedFriend = RD->getFirstFriend();
3871 SmallVector<FriendDecl *, 2> ImportedEquivalentFriends;
3872
3873 while (ImportedFriend) {
3874 bool Match = false;
3875 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3876 Match =
3877 IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3878 /*Complain=*/false);
3879 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3880 Match = Importer.IsStructurallyEquivalent(
3881 D->getFriendType()->getType(),
3882 ImportedFriend->getFriendType()->getType(), /*Complain=*/false);
3883 }
3884 if (Match)
3885 ImportedEquivalentFriends.push_back(ImportedFriend);
3886
3887 ImportedFriend = ImportedFriend->getNextFriend();
3888 }
3889 FriendCountAndPosition CountAndPosition = getFriendCountAndPosition(D);
3890
3891 assert(ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount &&(static_cast <bool> (ImportedEquivalentFriends.size() <=
CountAndPosition.TotalCount && "Class with non-matching friends is imported, ODR check wrong?"
) ? void (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3892, __extension__ __PRETTY_FUNCTION__))
3892 "Class with non-matching friends is imported, ODR check wrong?")(static_cast <bool> (ImportedEquivalentFriends.size() <=
CountAndPosition.TotalCount && "Class with non-matching friends is imported, ODR check wrong?"
) ? void (0) : __assert_fail ("ImportedEquivalentFriends.size() <= CountAndPosition.TotalCount && \"Class with non-matching friends is imported, ODR check wrong?\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 3892, __extension__ __PRETTY_FUNCTION__))
;
3893 if (ImportedEquivalentFriends.size() == CountAndPosition.TotalCount)
3894 return Importer.MapImported(
3895 D, ImportedEquivalentFriends[CountAndPosition.IndexOfDecl]);
3896
3897 // Not found. Create it.
3898 // The declarations will be put into order later by ImportDeclContext.
3899 FriendDecl::FriendUnion ToFU;
3900 if (NamedDecl *FriendD = D->getFriendDecl()) {
3901 NamedDecl *ToFriendD;
3902 if (Error Err = importInto(ToFriendD, FriendD))
3903 return std::move(Err);
3904
3905 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3906 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3907 ToFriendD->setObjectOfFriendDecl(false);
3908
3909 ToFU = ToFriendD;
3910 } else { // The friend is a type, not a decl.
3911 if (auto TSIOrErr = import(D->getFriendType()))
3912 ToFU = *TSIOrErr;
3913 else
3914 return TSIOrErr.takeError();
3915 }
3916
3917 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3918 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3919 for (unsigned I = 0; I < D->NumTPLists; I++) {
3920 if (auto ListOrErr = import(FromTPLists[I]))
3921 ToTPLists[I] = *ListOrErr;
3922 else
3923 return ListOrErr.takeError();
3924 }
3925
3926 auto LocationOrErr = import(D->getLocation());
3927 if (!LocationOrErr)
3928 return LocationOrErr.takeError();
3929 auto FriendLocOrErr = import(D->getFriendLoc());
3930 if (!FriendLocOrErr)
3931 return FriendLocOrErr.takeError();
3932
3933 FriendDecl *FrD;
3934 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3935 *LocationOrErr, ToFU,
3936 *FriendLocOrErr, ToTPLists))
3937 return FrD;
3938
3939 FrD->setAccess(D->getAccess());
3940 FrD->setLexicalDeclContext(LexicalDC);
3941 LexicalDC->addDeclInternal(FrD);
3942 return FrD;
3943}
3944
3945ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3946 // Import the major distinguishing characteristics of an ivar.
3947 DeclContext *DC, *LexicalDC;
3948 DeclarationName Name;
3949 SourceLocation Loc;
3950 NamedDecl *ToD;
3951 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3952 return std::move(Err);
3953 if (ToD)
3954 return ToD;
3955
3956 // Determine whether we've already imported this ivar
3957 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3958 for (auto *FoundDecl : FoundDecls) {
3959 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3960 if (Importer.IsStructurallyEquivalent(D->getType(),
3961 FoundIvar->getType())) {
3962 Importer.MapImported(D, FoundIvar);
3963 return FoundIvar;
3964 }
3965
3966 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3967 << Name << D->getType() << FoundIvar->getType();
3968 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3969 << FoundIvar->getType();
3970
3971 return make_error<ImportError>(ImportError::NameConflict);
3972 }
3973 }
3974
3975 Error Err = Error::success();
3976 auto ToType = importChecked(Err, D->getType());
3977 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
3978 auto ToBitWidth = importChecked(Err, D->getBitWidth());
3979 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
3980 if (Err)
3981 return std::move(Err);
3982
3983 ObjCIvarDecl *ToIvar;
3984 if (GetImportedOrCreateDecl(
3985 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3986 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3987 ToType, ToTypeSourceInfo,
3988 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3989 return ToIvar;
3990
3991 ToIvar->setLexicalDeclContext(LexicalDC);
3992 LexicalDC->addDeclInternal(ToIvar);
3993 return ToIvar;
3994}
3995
3996ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3997
3998 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
3999 auto RedeclIt = Redecls.begin();
4000 // Import the first part of the decl chain. I.e. import all previous
4001 // declarations starting from the canonical decl.
4002 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
4003 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4004 if (!RedeclOrErr)
4005 return RedeclOrErr.takeError();
4006 }
4007 assert(*RedeclIt == D)(static_cast <bool> (*RedeclIt == D) ? void (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 4007, __extension__ __PRETTY_FUNCTION__))
;
4008
4009 // Import the major distinguishing characteristics of a variable.
4010 DeclContext *DC, *LexicalDC;
4011 DeclarationName Name;
4012 SourceLocation Loc;
4013 NamedDecl *ToD;
4014 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4015 return std::move(Err);
4016 if (ToD)
4017 return ToD;
4018
4019 // Try to find a variable in our own ("to") context with the same name and
4020 // in the same context as the variable we're importing.
4021 VarDecl *FoundByLookup = nullptr;
4022 if (D->isFileVarDecl()) {
4023 SmallVector<NamedDecl *, 4> ConflictingDecls;
4024 unsigned IDNS = Decl::IDNS_Ordinary;
4025 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4026 for (auto *FoundDecl : FoundDecls) {
4027 if (!FoundDecl->isInIdentifierNamespace(IDNS))
4028 continue;
4029
4030 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
4031 if (!hasSameVisibilityContextAndLinkage(FoundVar, D))
4032 continue;
4033 if (Importer.IsStructurallyEquivalent(D->getType(),
4034 FoundVar->getType())) {
4035
4036 // The VarDecl in the "From" context has a definition, but in the
4037 // "To" context we already have a definition.
4038 VarDecl *FoundDef = FoundVar->getDefinition();
4039 if (D->isThisDeclarationADefinition() && FoundDef)
4040 // FIXME Check for ODR error if the two definitions have
4041 // different initializers?
4042 return Importer.MapImported(D, FoundDef);
4043
4044 // The VarDecl in the "From" context has an initializer, but in the
4045 // "To" context we already have an initializer.
4046 const VarDecl *FoundDInit = nullptr;
4047 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
4048 // FIXME Diagnose ODR error if the two initializers are different?
4049 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
4050
4051 FoundByLookup = FoundVar;
4052 break;
4053 }
4054
4055 const ArrayType *FoundArray
4056 = Importer.getToContext().getAsArrayType(FoundVar->getType());
4057 const ArrayType *TArray
4058 = Importer.getToContext().getAsArrayType(D->getType());
4059 if (FoundArray && TArray) {
4060 if (isa<IncompleteArrayType>(FoundArray) &&
4061 isa<ConstantArrayType>(TArray)) {
4062 // Import the type.
4063 if (auto TyOrErr = import(D->getType()))
4064 FoundVar->setType(*TyOrErr);
4065 else
4066 return TyOrErr.takeError();
4067
4068 FoundByLookup = FoundVar;
4069 break;
4070 } else if (isa<IncompleteArrayType>(TArray) &&
4071 isa<ConstantArrayType>(FoundArray)) {
4072 FoundByLookup = FoundVar;
4073 break;
4074 }
4075 }
4076
4077 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
4078 << Name << D->getType() << FoundVar->getType();
4079 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
4080 << FoundVar->getType();
4081 ConflictingDecls.push_back(FoundDecl);
4082 }
4083 }
4084
4085 if (!ConflictingDecls.empty()) {
4086 ExpectedName NameOrErr = Importer.HandleNameConflict(
4087 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size());
4088 if (NameOrErr)
4089 Name = NameOrErr.get();
4090 else
4091 return NameOrErr.takeError();
4092 }
4093 }
4094
4095 Error Err = Error::success();
4096 auto ToType = importChecked(Err, D->getType());
4097 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4098 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4099 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4100 if (Err)
4101 return std::move(Err);
4102
4103 VarDecl *ToVar;
4104 if (auto *FromDecomp = dyn_cast<DecompositionDecl>(D)) {
4105 SmallVector<BindingDecl *> Bindings(FromDecomp->bindings().size());
4106 if (Error Err =
4107 ImportArrayChecked(FromDecomp->bindings(), Bindings.begin()))
4108 return std::move(Err);
4109 DecompositionDecl *ToDecomp;
4110 if (GetImportedOrCreateDecl(
4111 ToDecomp, FromDecomp, Importer.getToContext(), DC, ToInnerLocStart,
4112 Loc, ToType, ToTypeSourceInfo, D->getStorageClass(), Bindings))
4113 return ToDecomp;
4114 ToVar = ToDecomp;
4115 } else {
4116 // Create the imported variable.
4117 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
4118 ToInnerLocStart, Loc,
4119 Name.getAsIdentifierInfo(), ToType,
4120 ToTypeSourceInfo, D->getStorageClass()))
4121 return ToVar;
4122 }
4123
4124 ToVar->setTSCSpec(D->getTSCSpec());
4125 ToVar->setQualifierInfo(ToQualifierLoc);
4126 ToVar->setAccess(D->getAccess());
4127 ToVar->setLexicalDeclContext(LexicalDC);
4128
4129 if (FoundByLookup) {
4130 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
4131 ToVar->setPreviousDecl(Recent);
4132 }
4133
4134 // Import the described template, if any.
4135 if (D->getDescribedVarTemplate()) {
4136 auto ToVTOrErr = import(D->getDescribedVarTemplate());
4137 if (!ToVTOrErr)
4138 return ToVTOrErr.takeError();
4139 }
4140
4141 if (Error Err = ImportInitializer(D, ToVar))
4142 return std::move(Err);
4143
4144 if (D->isConstexpr())
4145 ToVar->setConstexpr(true);
4146
4147 addDeclToContexts(D, ToVar);
4148
4149 // Import the rest of the chain. I.e. import all subsequent declarations.
4150 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
4151 ExpectedDecl RedeclOrErr = import(*RedeclIt);
4152 if (!RedeclOrErr)
4153 return RedeclOrErr.takeError();
4154 }
4155
4156 return ToVar;
4157}
4158
4159ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
4160 // Parameters are created in the translation unit's context, then moved
4161 // into the function declaration's context afterward.
4162 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4163
4164 Error Err = Error::success();
4165 auto ToDeclName = importChecked(Err, D->getDeclName());
4166 auto ToLocation = importChecked(Err, D->getLocation());
4167 auto ToType = importChecked(Err, D->getType());
4168 if (Err)
4169 return std::move(Err);
4170
4171 // Create the imported parameter.
4172 ImplicitParamDecl *ToParm = nullptr;
4173 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4174 ToLocation, ToDeclName.getAsIdentifierInfo(),
4175 ToType, D->getParameterKind()))
4176 return ToParm;
4177 return ToParm;
4178}
4179
4180Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl(
4181 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) {
4182 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg());
4183 ToParam->setKNRPromoted(FromParam->isKNRPromoted());
4184
4185 if (FromParam->hasUninstantiatedDefaultArg()) {
4186 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg()))
4187 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr);
4188 else
4189 return ToDefArgOrErr.takeError();
4190 } else if (FromParam->hasUnparsedDefaultArg()) {
4191 ToParam->setUnparsedDefaultArg();
4192 } else if (FromParam->hasDefaultArg()) {
4193 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg()))
4194 ToParam->setDefaultArg(*ToDefArgOrErr);
4195 else
4196 return ToDefArgOrErr.takeError();
4197 }
4198
4199 return Error::success();
4200}
4201
4202ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
4203 // Parameters are created in the translation unit's context, then moved
4204 // into the function declaration's context afterward.
4205 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
4206
4207 Error Err = Error::success();
4208 auto ToDeclName = importChecked(Err, D->getDeclName());
4209 auto ToLocation = importChecked(Err, D->getLocation());
4210 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
4211 auto ToType = importChecked(Err, D->getType());
4212 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4213 if (Err)
4214 return std::move(Err);
4215
4216 ParmVarDecl *ToParm;
4217 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
4218 ToInnerLocStart, ToLocation,
4219 ToDeclName.getAsIdentifierInfo(), ToType,
4220 ToTypeSourceInfo, D->getStorageClass(),
4221 /*DefaultArg*/ nullptr))
4222 return ToParm;
4223
4224 // Set the default argument. It should be no problem if it was already done.
4225 // Do not import the default expression before GetImportedOrCreateDecl call
4226 // to avoid possible infinite import loop because circular dependency.
4227 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm))
4228 return std::move(Err);
4229
4230 if (D->isObjCMethodParameter()) {
4231 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
4232 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
4233 } else {
4234 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
4235 D->getFunctionScopeIndex());
4236 }
4237
4238 return ToParm;
4239}
4240
4241ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
4242 // Import the major distinguishing characteristics of a method.
4243 DeclContext *DC, *LexicalDC;
4244 DeclarationName Name;
4245 SourceLocation Loc;
4246 NamedDecl *ToD;
4247 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4248 return std::move(Err);
4249 if (ToD)
4250 return ToD;
4251
4252 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4253 for (auto *FoundDecl : FoundDecls) {
4254 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
4255 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
4256 continue;
4257
4258 // Check return types.
4259 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
4260 FoundMethod->getReturnType())) {
4261 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
4262 << D->isInstanceMethod() << Name << D->getReturnType()
4263 << FoundMethod->getReturnType();
4264 Importer.ToDiag(FoundMethod->getLocation(),
4265 diag::note_odr_objc_method_here)
4266 << D->isInstanceMethod() << Name;
4267
4268 return make_error<ImportError>(ImportError::NameConflict);
4269 }
4270
4271 // Check the number of parameters.
4272 if (D->param_size() != FoundMethod->param_size()) {
4273 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
4274 << D->isInstanceMethod() << Name
4275 << D->param_size() << FoundMethod->param_size();
4276 Importer.ToDiag(FoundMethod->getLocation(),
4277 diag::note_odr_objc_method_here)
4278 << D->isInstanceMethod() << Name;
4279
4280 return make_error<ImportError>(ImportError::NameConflict);
4281 }
4282
4283 // Check parameter types.
4284 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
4285 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
4286 P != PEnd; ++P, ++FoundP) {
4287 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
4288 (*FoundP)->getType())) {
4289 Importer.FromDiag((*P)->getLocation(),
4290 diag::warn_odr_objc_method_param_type_inconsistent)
4291 << D->isInstanceMethod() << Name
4292 << (*P)->getType() << (*FoundP)->getType();
4293 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
4294 << (*FoundP)->getType();
4295
4296 return make_error<ImportError>(ImportError::NameConflict);
4297 }
4298 }
4299
4300 // Check variadic/non-variadic.
4301 // Check the number of parameters.
4302 if (D->isVariadic() != FoundMethod->isVariadic()) {
4303 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
4304 << D->isInstanceMethod() << Name;
4305 Importer.ToDiag(FoundMethod->getLocation(),
4306 diag::note_odr_objc_method_here)
4307 << D->isInstanceMethod() << Name;
4308
4309 return make_error<ImportError>(ImportError::NameConflict);
4310 }
4311
4312 // FIXME: Any other bits we need to merge?
4313 return Importer.MapImported(D, FoundMethod);
4314 }
4315 }
4316
4317 Error Err = Error::success();
4318 auto ToEndLoc = importChecked(Err, D->getEndLoc());
4319 auto ToReturnType = importChecked(Err, D->getReturnType());
4320 auto ToReturnTypeSourceInfo =
4321 importChecked(Err, D->getReturnTypeSourceInfo());
4322 if (Err)
4323 return std::move(Err);
4324
4325 ObjCMethodDecl *ToMethod;
4326 if (GetImportedOrCreateDecl(
4327 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc,
4328 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC,
4329 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(),
4330 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(),
4331 D->getImplementationControl(), D->hasRelatedResultType()))
4332 return ToMethod;
4333
4334 // FIXME: When we decide to merge method definitions, we'll need to
4335 // deal with implicit parameters.
4336
4337 // Import the parameters
4338 SmallVector<ParmVarDecl *, 5> ToParams;
4339 for (auto *FromP : D->parameters()) {
4340 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
4341 ToParams.push_back(*ToPOrErr);
4342 else
4343 return ToPOrErr.takeError();
4344 }
4345
4346 // Set the parameters.
4347 for (auto *ToParam : ToParams) {
4348 ToParam->setOwningFunction(ToMethod);
4349 ToMethod->addDeclInternal(ToParam);
4350 }
4351
4352 SmallVector<SourceLocation, 12> FromSelLocs;
4353 D->getSelectorLocs(FromSelLocs);
4354 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
4355 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
4356 return std::move(Err);
4357
4358 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
4359
4360 ToMethod->setLexicalDeclContext(LexicalDC);
4361 LexicalDC->addDeclInternal(ToMethod);
4362
4363 // Implicit params are declared when Sema encounters the definition but this
4364 // never happens when the method is imported. Manually declare the implicit
4365 // params now that the MethodDecl knows its class interface.
4366 if (D->getSelfDecl())
4367 ToMethod->createImplicitParams(Importer.getToContext(),
4368 ToMethod->getClassInterface());
4369
4370 return ToMethod;
4371}
4372
4373ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
4374 // Import the major distinguishing characteristics of a category.
4375 DeclContext *DC, *LexicalDC;
4376 DeclarationName Name;
4377 SourceLocation Loc;
4378 NamedDecl *ToD;
4379 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4380 return std::move(Err);
4381 if (ToD)
4382 return ToD;
4383
4384 Error Err = Error::success();
4385 auto ToVarianceLoc = importChecked(Err, D->getVarianceLoc());
4386 auto ToLocation = importChecked(Err, D->getLocation());
4387 auto ToColonLoc = importChecked(Err, D->getColonLoc());
4388 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
4389 if (Err)
4390 return std::move(Err);
4391
4392 ObjCTypeParamDecl *Result;
4393 if (GetImportedOrCreateDecl(
4394 Result, D, Importer.getToContext(), DC, D->getVariance(),
4395 ToVarianceLoc, D->getIndex(),
4396 ToLocation, Name.getAsIdentifierInfo(),
4397 ToColonLoc, ToTypeSourceInfo))
4398 return Result;
4399
4400 Result->setLexicalDeclContext(LexicalDC);
4401 return Result;
4402}
4403
4404ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
4405 // Import the major distinguishing characteristics of a category.
4406 DeclContext *DC, *LexicalDC;
4407 DeclarationName Name;
4408 SourceLocation Loc;
4409 NamedDecl *ToD;
4410 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4411 return std::move(Err);
4412 if (ToD)
4413 return ToD;
4414
4415 ObjCInterfaceDecl *ToInterface;
4416 if (Error Err = importInto(ToInterface, D->getClassInterface()))
4417 return std::move(Err);
4418
4419 // Determine if we've already encountered this category.
4420 ObjCCategoryDecl *MergeWithCategory
4421 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
4422 ObjCCategoryDecl *ToCategory = MergeWithCategory;
4423 if (!ToCategory) {
4424
4425 Error Err = Error::success();
4426 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
4427 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
4428 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
4429 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
4430 if (Err)
4431 return std::move(Err);
4432
4433 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
4434 ToAtStartLoc, Loc,
4435 ToCategoryNameLoc,
4436 Name.getAsIdentifierInfo(), ToInterface,
4437 /*TypeParamList=*/nullptr,
4438 ToIvarLBraceLoc,
4439 ToIvarRBraceLoc))
4440 return ToCategory;
4441
4442 ToCategory->setLexicalDeclContext(LexicalDC);
4443 LexicalDC->addDeclInternal(ToCategory);
4444 // Import the type parameter list after MapImported, to avoid
4445 // loops when bringing in their DeclContext.
4446 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
4447 ToCategory->setTypeParamList(*PListOrErr);
4448 else
4449 return PListOrErr.takeError();
4450
4451 // Import protocols
4452 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4453 SmallVector<SourceLocation, 4> ProtocolLocs;
4454 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
4455 = D->protocol_loc_begin();
4456 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
4457 FromProtoEnd = D->protocol_end();
4458 FromProto != FromProtoEnd;
4459 ++FromProto, ++FromProtoLoc) {
4460 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4461 Protocols.push_back(*ToProtoOrErr);
4462 else
4463 return ToProtoOrErr.takeError();
4464
4465 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4466 ProtocolLocs.push_back(*ToProtoLocOrErr);
4467 else
4468 return ToProtoLocOrErr.takeError();
4469 }
4470
4471 // FIXME: If we're merging, make sure that the protocol list is the same.
4472 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4473 ProtocolLocs.data(), Importer.getToContext());
4474
4475 } else {
4476 Importer.MapImported(D, ToCategory);
4477 }
4478
4479 // Import all of the members of this category.
4480 if (Error Err = ImportDeclContext(D))
4481 return std::move(Err);
4482
4483 // If we have an implementation, import it as well.
4484 if (D->getImplementation()) {
4485 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4486 import(D->getImplementation()))
4487 ToCategory->setImplementation(*ToImplOrErr);
4488 else
4489 return ToImplOrErr.takeError();
4490 }
4491
4492 return ToCategory;
4493}
4494
4495Error ASTNodeImporter::ImportDefinition(
4496 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4497 if (To->getDefinition()) {
4498 if (shouldForceImportDeclContext(Kind))
4499 if (Error Err = ImportDeclContext(From))
4500 return Err;
4501 return Error::success();
4502 }
4503
4504 // Start the protocol definition
4505 To->startDefinition();
4506
4507 // Import protocols
4508 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4509 SmallVector<SourceLocation, 4> ProtocolLocs;
4510 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4511 From->protocol_loc_begin();
4512 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4513 FromProtoEnd = From->protocol_end();
4514 FromProto != FromProtoEnd;
4515 ++FromProto, ++FromProtoLoc) {
4516 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4517 Protocols.push_back(*ToProtoOrErr);
4518 else
4519 return ToProtoOrErr.takeError();
4520
4521 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4522 ProtocolLocs.push_back(*ToProtoLocOrErr);
4523 else
4524 return ToProtoLocOrErr.takeError();
4525
4526 }
4527
4528 // FIXME: If we're merging, make sure that the protocol list is the same.
4529 To->setProtocolList(Protocols.data(), Protocols.size(),
4530 ProtocolLocs.data(), Importer.getToContext());
4531
4532 if (shouldForceImportDeclContext(Kind)) {
4533 // Import all of the members of this protocol.
4534 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4535 return Err;
4536 }
4537 return Error::success();
4538}
4539
4540ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4541 // If this protocol has a definition in the translation unit we're coming
4542 // from, but this particular declaration is not that definition, import the
4543 // definition and map to that.
4544 ObjCProtocolDecl *Definition = D->getDefinition();
4545 if (Definition && Definition != D) {
4546 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4547 return Importer.MapImported(D, *ImportedDefOrErr);
4548 else
4549 return ImportedDefOrErr.takeError();
4550 }
4551
4552 // Import the major distinguishing characteristics of a protocol.
4553 DeclContext *DC, *LexicalDC;
4554 DeclarationName Name;
4555 SourceLocation Loc;
4556 NamedDecl *ToD;
4557 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4558 return std::move(Err);
4559 if (ToD)
4560 return ToD;
4561
4562 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4563 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4564 for (auto *FoundDecl : FoundDecls) {
4565 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4566 continue;
4567
4568 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4569 break;
4570 }
4571
4572 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4573 if (!ToProto) {
4574 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4575 if (!ToAtBeginLocOrErr)
4576 return ToAtBeginLocOrErr.takeError();
4577
4578 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4579 Name.getAsIdentifierInfo(), Loc,
4580 *ToAtBeginLocOrErr,
4581 /*PrevDecl=*/nullptr))
4582 return ToProto;
4583 ToProto->setLexicalDeclContext(LexicalDC);
4584 LexicalDC->addDeclInternal(ToProto);
4585 }
4586
4587 Importer.MapImported(D, ToProto);
4588
4589 if (D->isThisDeclarationADefinition())
4590 if (Error Err = ImportDefinition(D, ToProto))
4591 return std::move(Err);
4592
4593 return ToProto;
4594}
4595
4596ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4597 DeclContext *DC, *LexicalDC;
4598 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4599 return std::move(Err);
4600
4601 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4602 if (!ExternLocOrErr)
4603 return ExternLocOrErr.takeError();
4604
4605 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4606 if (!LangLocOrErr)
4607 return LangLocOrErr.takeError();
4608
4609 bool HasBraces = D->hasBraces();
4610
4611 LinkageSpecDecl *ToLinkageSpec;
4612 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4613 *ExternLocOrErr, *LangLocOrErr,
4614 D->getLanguage(), HasBraces))
4615 return ToLinkageSpec;
4616
4617 if (HasBraces) {
4618 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4619 if (!RBraceLocOrErr)
4620 return RBraceLocOrErr.takeError();
4621 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4622 }
4623
4624 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4625 LexicalDC->addDeclInternal(ToLinkageSpec);
4626
4627 return ToLinkageSpec;
4628}
4629
4630ExpectedDecl ASTNodeImporter::ImportUsingShadowDecls(BaseUsingDecl *D,
4631 BaseUsingDecl *ToSI) {
4632 for (UsingShadowDecl *FromShadow : D->shadows()) {
4633 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4634 ToSI->addShadowDecl(*ToShadowOrErr);
4635 else
4636 // FIXME: We return error here but the definition is already created
4637 // and available with lookups. How to fix this?..
4638 return ToShadowOrErr.takeError();
4639 }
4640 return ToSI;
4641}
4642
4643ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
4644 DeclContext *DC, *LexicalDC;
4645 DeclarationName Name;
4646 SourceLocation Loc;
4647 NamedDecl *ToD = nullptr;
4648 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4649 return std::move(Err);
4650 if (ToD)
4651 return ToD;
4652
4653 Error Err = Error::success();
4654 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4655 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4656 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4657 if (Err)
4658 return std::move(Err);
4659
4660 DeclarationNameInfo NameInfo(Name, ToLoc);
4661 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4662 return std::move(Err);
4663
4664 UsingDecl *ToUsing;
4665 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4666 ToUsingLoc, ToQualifierLoc, NameInfo,
4667 D->hasTypename()))
4668 return ToUsing;
4669
4670 ToUsing->setLexicalDeclContext(LexicalDC);
4671 LexicalDC->addDeclInternal(ToUsing);
4672
4673 if (NamedDecl *FromPattern =
4674 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4675 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4676 Importer.getToContext().setInstantiatedFromUsingDecl(
4677 ToUsing, *ToPatternOrErr);
4678 else
4679 return ToPatternOrErr.takeError();
4680 }
4681
4682 return ImportUsingShadowDecls(D, ToUsing);
4683}
4684
4685ExpectedDecl ASTNodeImporter::VisitUsingEnumDecl(UsingEnumDecl *D) {
4686 DeclContext *DC, *LexicalDC;
4687 DeclarationName Name;
4688 SourceLocation Loc;
4689 NamedDecl *ToD = nullptr;
4690 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4691 return std::move(Err);
4692 if (ToD)
4693 return ToD;
4694
4695 Error Err = Error::success();
4696 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4697 auto ToEnumLoc = importChecked(Err, D->getEnumLoc());
4698 auto ToEnumDecl = importChecked(Err, D->getEnumDecl());
4699 if (Err)
4700 return std::move(Err);
4701
4702 UsingEnumDecl *ToUsingEnum;
4703 if (GetImportedOrCreateDecl(ToUsingEnum, D, Importer.getToContext(), DC,
4704 ToUsingLoc, ToEnumLoc, Loc, ToEnumDecl))
4705 return ToUsingEnum;
4706
4707 ToUsingEnum->setLexicalDeclContext(LexicalDC);
4708 LexicalDC->addDeclInternal(ToUsingEnum);
4709
4710 if (UsingEnumDecl *FromPattern =
4711 Importer.getFromContext().getInstantiatedFromUsingEnumDecl(D)) {
4712 if (Expected<UsingEnumDecl *> ToPatternOrErr = import(FromPattern))
4713 Importer.getToContext().setInstantiatedFromUsingEnumDecl(ToUsingEnum,
4714 *ToPatternOrErr);
4715 else
4716 return ToPatternOrErr.takeError();
4717 }
4718
4719 return ImportUsingShadowDecls(D, ToUsingEnum);
4720}
4721
4722ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
4723 DeclContext *DC, *LexicalDC;
4724 DeclarationName Name;
4725 SourceLocation Loc;
4726 NamedDecl *ToD = nullptr;
4727 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4728 return std::move(Err);
4729 if (ToD)
4730 return ToD;
4731
4732 Expected<BaseUsingDecl *> ToIntroducerOrErr = import(D->getIntroducer());
4733 if (!ToIntroducerOrErr)
4734 return ToIntroducerOrErr.takeError();
4735
4736 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4737 if (!ToTargetOrErr)
4738 return ToTargetOrErr.takeError();
4739
4740 UsingShadowDecl *ToShadow;
4741 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4742 Name, *ToIntroducerOrErr, *ToTargetOrErr))
4743 return ToShadow;
4744
4745 ToShadow->setLexicalDeclContext(LexicalDC);
4746 ToShadow->setAccess(D->getAccess());
4747
4748 if (UsingShadowDecl *FromPattern =
4749 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4750 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4751 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4752 ToShadow, *ToPatternOrErr);
4753 else
4754 // FIXME: We return error here but the definition is already created
4755 // and available with lookups. How to fix this?..
4756 return ToPatternOrErr.takeError();
4757 }
4758
4759 LexicalDC->addDeclInternal(ToShadow);
4760
4761 return ToShadow;
4762}
4763
4764ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4765 DeclContext *DC, *LexicalDC;
4766 DeclarationName Name;
4767 SourceLocation Loc;
4768 NamedDecl *ToD = nullptr;
4769 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4770 return std::move(Err);
4771 if (ToD)
4772 return ToD;
4773
4774 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4775 if (!ToComAncestorOrErr)
4776 return ToComAncestorOrErr.takeError();
4777
4778 Error Err = Error::success();
4779 auto ToNominatedNamespace = importChecked(Err, D->getNominatedNamespace());
4780 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4781 auto ToNamespaceKeyLocation =
4782 importChecked(Err, D->getNamespaceKeyLocation());
4783 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4784 auto ToIdentLocation = importChecked(Err, D->getIdentLocation());
4785 if (Err)
4786 return std::move(Err);
4787
4788 UsingDirectiveDecl *ToUsingDir;
4789 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4790 ToUsingLoc,
4791 ToNamespaceKeyLocation,
4792 ToQualifierLoc,
4793 ToIdentLocation,
4794 ToNominatedNamespace, *ToComAncestorOrErr))
4795 return ToUsingDir;
4796
4797 ToUsingDir->setLexicalDeclContext(LexicalDC);
4798 LexicalDC->addDeclInternal(ToUsingDir);
4799
4800 return ToUsingDir;
4801}
4802
4803ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
4804 UnresolvedUsingValueDecl *D) {
4805 DeclContext *DC, *LexicalDC;
4806 DeclarationName Name;
4807 SourceLocation Loc;
4808 NamedDecl *ToD = nullptr;
4809 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4810 return std::move(Err);
4811 if (ToD)
4812 return ToD;
4813
4814 Error Err = Error::success();
4815 auto ToLoc = importChecked(Err, D->getNameInfo().getLoc());
4816 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4817 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4818 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4819 if (Err)
4820 return std::move(Err);
4821
4822 DeclarationNameInfo NameInfo(Name, ToLoc);
4823 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4824 return std::move(Err);
4825
4826 UnresolvedUsingValueDecl *ToUsingValue;
4827 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4828 ToUsingLoc, ToQualifierLoc, NameInfo,
4829 ToEllipsisLoc))
4830 return ToUsingValue;
4831
4832 ToUsingValue->setAccess(D->getAccess());
4833 ToUsingValue->setLexicalDeclContext(LexicalDC);
4834 LexicalDC->addDeclInternal(ToUsingValue);
4835
4836 return ToUsingValue;
4837}
4838
4839ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
4840 UnresolvedUsingTypenameDecl *D) {
4841 DeclContext *DC, *LexicalDC;
4842 DeclarationName Name;
4843 SourceLocation Loc;
4844 NamedDecl *ToD = nullptr;
4845 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4846 return std::move(Err);
4847 if (ToD)
4848 return ToD;
4849
4850 Error Err = Error::success();
4851 auto ToUsingLoc = importChecked(Err, D->getUsingLoc());
4852 auto ToTypenameLoc = importChecked(Err, D->getTypenameLoc());
4853 auto ToQualifierLoc = importChecked(Err, D->getQualifierLoc());
4854 auto ToEllipsisLoc = importChecked(Err, D->getEllipsisLoc());
4855 if (Err)
4856 return std::move(Err);
4857
4858 UnresolvedUsingTypenameDecl *ToUsing;
4859 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4860 ToUsingLoc, ToTypenameLoc,
4861 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4862 return ToUsing;
4863
4864 ToUsing->setAccess(D->getAccess());
4865 ToUsing->setLexicalDeclContext(LexicalDC);
4866 LexicalDC->addDeclInternal(ToUsing);
4867
4868 return ToUsing;
4869}
4870
4871ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
4872 Decl* ToD = nullptr;
4873 switch (D->getBuiltinTemplateKind()) {
4874 case BuiltinTemplateKind::BTK__make_integer_seq:
4875 ToD = Importer.getToContext().getMakeIntegerSeqDecl();
4876 break;
4877 case BuiltinTemplateKind::BTK__type_pack_element:
4878 ToD = Importer.getToContext().getTypePackElementDecl();
4879 break;
4880 }
4881 assert(ToD && "BuiltinTemplateDecl of unsupported kind!")(static_cast <bool> (ToD && "BuiltinTemplateDecl of unsupported kind!"
) ? void (0) : __assert_fail ("ToD && \"BuiltinTemplateDecl of unsupported kind!\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 4881, __extension__ __PRETTY_FUNCTION__))
;
4882 Importer.MapImported(D, ToD);
4883 return ToD;
4884}
4885
4886Error ASTNodeImporter::ImportDefinition(
4887 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
4888 if (To->getDefinition()) {
4889 // Check consistency of superclass.
4890 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4891 if (FromSuper) {
4892 if (auto FromSuperOrErr = import(FromSuper))
4893 FromSuper = *FromSuperOrErr;
4894 else
4895 return FromSuperOrErr.takeError();
4896 }
4897
4898 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4899 if ((bool)FromSuper != (bool)ToSuper ||
4900 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4901 Importer.ToDiag(To->getLocation(),
4902 diag::warn_odr_objc_superclass_inconsistent)
4903 << To->getDeclName();
4904 if (ToSuper)
4905 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4906 << To->getSuperClass()->getDeclName();
4907 else
4908 Importer.ToDiag(To->getLocation(),
4909 diag::note_odr_objc_missing_superclass);
4910 if (From->getSuperClass())
4911 Importer.FromDiag(From->getSuperClassLoc(),
4912 diag::note_odr_objc_superclass)
4913 << From->getSuperClass()->getDeclName();
4914 else
4915 Importer.FromDiag(From->getLocation(),
4916 diag::note_odr_objc_missing_superclass);
4917 }
4918
4919 if (shouldForceImportDeclContext(Kind))
4920 if (Error Err = ImportDeclContext(From))
4921 return Err;
4922 return Error::success();
4923 }
4924
4925 // Start the definition.
4926 To->startDefinition();
4927
4928 // If this class has a superclass, import it.
4929 if (From->getSuperClass()) {
4930 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4931 To->setSuperClass(*SuperTInfoOrErr);
4932 else
4933 return SuperTInfoOrErr.takeError();
4934 }
4935
4936 // Import protocols
4937 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4938 SmallVector<SourceLocation, 4> ProtocolLocs;
4939 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
4940 From->protocol_loc_begin();
4941
4942 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4943 FromProtoEnd = From->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
4958 // FIXME: If we're merging, make sure that the protocol list is the same.
4959 To->setProtocolList(Protocols.data(), Protocols.size(),
4960 ProtocolLocs.data(), Importer.getToContext());
4961
4962 // Import categories. When the categories themselves are imported, they'll
4963 // hook themselves into this interface.
4964 for (auto *Cat : From->known_categories()) {
4965 auto ToCatOrErr = import(Cat);
4966 if (!ToCatOrErr)
4967 return ToCatOrErr.takeError();
4968 }
4969
4970 // If we have an @implementation, import it as well.
4971 if (From->getImplementation()) {
4972 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4973 import(From->getImplementation()))
4974 To->setImplementation(*ToImplOrErr);
4975 else
4976 return ToImplOrErr.takeError();
4977 }
4978
4979 // Import all of the members of this class.
4980 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4981 return Err;
4982
4983 return Error::success();
4984}
4985
4986Expected<ObjCTypeParamList *>
4987ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4988 if (!list)
4989 return nullptr;
4990
4991 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4992 for (auto *fromTypeParam : *list) {
4993 if (auto toTypeParamOrErr = import(fromTypeParam))
4994 toTypeParams.push_back(*toTypeParamOrErr);
4995 else
4996 return toTypeParamOrErr.takeError();
4997 }
4998
4999 auto LAngleLocOrErr = import(list->getLAngleLoc());
5000 if (!LAngleLocOrErr)
5001 return LAngleLocOrErr.takeError();
5002
5003 auto RAngleLocOrErr = import(list->getRAngleLoc());
5004 if (!RAngleLocOrErr)
5005 return RAngleLocOrErr.takeError();
5006
5007 return ObjCTypeParamList::create(Importer.getToContext(),
5008 *LAngleLocOrErr,
5009 toTypeParams,
5010 *RAngleLocOrErr);
5011}
5012
5013ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
5014 // If this class has a definition in the translation unit we're coming from,
5015 // but this particular declaration is not that definition, import the
5016 // definition and map to that.
5017 ObjCInterfaceDecl *Definition = D->getDefinition();
5018 if (Definition && Definition != D) {
5019 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5020 return Importer.MapImported(D, *ImportedDefOrErr);
5021 else
5022 return ImportedDefOrErr.takeError();
5023 }
5024
5025 // Import the major distinguishing characteristics of an @interface.
5026 DeclContext *DC, *LexicalDC;
5027 DeclarationName Name;
5028 SourceLocation Loc;
5029 NamedDecl *ToD;
5030 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5031 return std::move(Err);
5032 if (ToD)
5033 return ToD;
5034
5035 // Look for an existing interface with the same name.
5036 ObjCInterfaceDecl *MergeWithIface = nullptr;
5037 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5038 for (auto *FoundDecl : FoundDecls) {
5039 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5040 continue;
5041
5042 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
5043 break;
5044 }
5045
5046 // Create an interface declaration, if one does not already exist.
5047 ObjCInterfaceDecl *ToIface = MergeWithIface;
5048 if (!ToIface) {
5049 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
5050 if (!AtBeginLocOrErr)
5051 return AtBeginLocOrErr.takeError();
5052
5053 if (GetImportedOrCreateDecl(
5054 ToIface, D, Importer.getToContext(), DC,
5055 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
5056 /*TypeParamList=*/nullptr,
5057 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
5058 return ToIface;
5059 ToIface->setLexicalDeclContext(LexicalDC);
5060 LexicalDC->addDeclInternal(ToIface);
5061 }
5062 Importer.MapImported(D, ToIface);
5063 // Import the type parameter list after MapImported, to avoid
5064 // loops when bringing in their DeclContext.
5065 if (auto ToPListOrErr =
5066 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
5067 ToIface->setTypeParamList(*ToPListOrErr);
5068 else
5069 return ToPListOrErr.takeError();
5070
5071 if (D->isThisDeclarationADefinition())
5072 if (Error Err = ImportDefinition(D, ToIface))
5073 return std::move(Err);
5074
5075 return ToIface;
5076}
5077
5078ExpectedDecl
5079ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
5080 ObjCCategoryDecl *Category;
5081 if (Error Err = importInto(Category, D->getCategoryDecl()))
5082 return std::move(Err);
5083
5084 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
5085 if (!ToImpl) {
5086 DeclContext *DC, *LexicalDC;
5087 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5088 return std::move(Err);
5089
5090 Error Err = Error::success();
5091 auto ToLocation = importChecked(Err, D->getLocation());
5092 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5093 auto ToCategoryNameLoc = importChecked(Err, D->getCategoryNameLoc());
5094 if (Err)
5095 return std::move(Err);
5096
5097 if (GetImportedOrCreateDecl(
5098 ToImpl, D, Importer.getToContext(), DC,
5099 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
5100 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
5101 return ToImpl;
5102
5103 ToImpl->setLexicalDeclContext(LexicalDC);
5104 LexicalDC->addDeclInternal(ToImpl);
5105 Category->setImplementation(ToImpl);
5106 }
5107
5108 Importer.MapImported(D, ToImpl);
5109 if (Error Err = ImportDeclContext(D))
5110 return std::move(Err);
5111
5112 return ToImpl;
5113}
5114
5115ExpectedDecl
5116ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
5117 // Find the corresponding interface.
5118 ObjCInterfaceDecl *Iface;
5119 if (Error Err = importInto(Iface, D->getClassInterface()))
5120 return std::move(Err);
5121
5122 // Import the superclass, if any.
5123 ObjCInterfaceDecl *Super;
5124 if (Error Err = importInto(Super, D->getSuperClass()))
5125 return std::move(Err);
5126
5127 ObjCImplementationDecl *Impl = Iface->getImplementation();
5128 if (!Impl) {
5129 // We haven't imported an implementation yet. Create a new @implementation
5130 // now.
5131 DeclContext *DC, *LexicalDC;
5132 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5133 return std::move(Err);
5134
5135 Error Err = Error::success();
5136 auto ToLocation = importChecked(Err, D->getLocation());
5137 auto ToAtStartLoc = importChecked(Err, D->getAtStartLoc());
5138 auto ToSuperClassLoc = importChecked(Err, D->getSuperClassLoc());
5139 auto ToIvarLBraceLoc = importChecked(Err, D->getIvarLBraceLoc());
5140 auto ToIvarRBraceLoc = importChecked(Err, D->getIvarRBraceLoc());
5141 if (Err)
5142 return std::move(Err);
5143
5144 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
5145 DC, Iface, Super,
5146 ToLocation,
5147 ToAtStartLoc,
5148 ToSuperClassLoc,
5149 ToIvarLBraceLoc,
5150 ToIvarRBraceLoc))
5151 return Impl;
5152
5153 Impl->setLexicalDeclContext(LexicalDC);
5154
5155 // Associate the implementation with the class it implements.
5156 Iface->setImplementation(Impl);
5157 Importer.MapImported(D, Iface->getImplementation());
5158 } else {
5159 Importer.MapImported(D, Iface->getImplementation());
5160
5161 // Verify that the existing @implementation has the same superclass.
5162 if ((Super && !Impl->getSuperClass()) ||
5163 (!Super && Impl->getSuperClass()) ||
5164 (Super && Impl->getSuperClass() &&
5165 !declaresSameEntity(Super->getCanonicalDecl(),
5166 Impl->getSuperClass()))) {
5167 Importer.ToDiag(Impl->getLocation(),
5168 diag::warn_odr_objc_superclass_inconsistent)
5169 << Iface->getDeclName();
5170 // FIXME: It would be nice to have the location of the superclass
5171 // below.
5172 if (Impl->getSuperClass())
5173 Importer.ToDiag(Impl->getLocation(),
5174 diag::note_odr_objc_superclass)
5175 << Impl->getSuperClass()->getDeclName();
5176 else
5177 Importer.ToDiag(Impl->getLocation(),
5178 diag::note_odr_objc_missing_superclass);
5179 if (D->getSuperClass())
5180 Importer.FromDiag(D->getLocation(),
5181 diag::note_odr_objc_superclass)
5182 << D->getSuperClass()->getDeclName();
5183 else
5184 Importer.FromDiag(D->getLocation(),
5185 diag::note_odr_objc_missing_superclass);
5186
5187 return make_error<ImportError>(ImportError::NameConflict);
5188 }
5189 }
5190
5191 // Import all of the members of this @implementation.
5192 if (Error Err = ImportDeclContext(D))
5193 return std::move(Err);
5194
5195 return Impl;
5196}
5197
5198ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
5199 // Import the major distinguishing characteristics of an @property.
5200 DeclContext *DC, *LexicalDC;
5201 DeclarationName Name;
5202 SourceLocation Loc;
5203 NamedDecl *ToD;
5204 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5205 return std::move(Err);
5206 if (ToD)
5207 return ToD;
5208
5209 // Check whether we have already imported this property.
5210 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5211 for (auto *FoundDecl : FoundDecls) {
5212 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
5213 // Instance and class properties can share the same name but are different
5214 // declarations.
5215 if (FoundProp->isInstanceProperty() != D->isInstanceProperty())
5216 continue;
5217
5218 // Check property types.
5219 if (!Importer.IsStructurallyEquivalent(D->getType(),
5220 FoundProp->getType())) {
5221 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
5222 << Name << D->getType() << FoundProp->getType();
5223 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
5224 << FoundProp->getType();
5225
5226 return make_error<ImportError>(ImportError::NameConflict);
5227 }
5228
5229 // FIXME: Check property attributes, getters, setters, etc.?
5230
5231 // Consider these properties to be equivalent.
5232 Importer.MapImported(D, FoundProp);
5233 return FoundProp;
5234 }
5235 }
5236
5237 Error Err = Error::success();
5238 auto ToType = importChecked(Err, D->getType());
5239 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5240 auto ToAtLoc = importChecked(Err, D->getAtLoc());
5241 auto ToLParenLoc = importChecked(Err, D->getLParenLoc());
5242 if (Err)
5243 return std::move(Err);
5244
5245 // Create the new property.
5246 ObjCPropertyDecl *ToProperty;
5247 if (GetImportedOrCreateDecl(
5248 ToProperty, D, Importer.getToContext(), DC, Loc,
5249 Name.getAsIdentifierInfo(), ToAtLoc,
5250 ToLParenLoc, ToType,
5251 ToTypeSourceInfo, D->getPropertyImplementation()))
5252 return ToProperty;
5253
5254 auto ToGetterName = importChecked(Err, D->getGetterName());
5255 auto ToSetterName = importChecked(Err, D->getSetterName());
5256 auto ToGetterNameLoc = importChecked(Err, D->getGetterNameLoc());
5257 auto ToSetterNameLoc = importChecked(Err, D->getSetterNameLoc());
5258 auto ToGetterMethodDecl = importChecked(Err, D->getGetterMethodDecl());
5259 auto ToSetterMethodDecl = importChecked(Err, D->getSetterMethodDecl());
5260 auto ToPropertyIvarDecl = importChecked(Err, D->getPropertyIvarDecl());
5261 if (Err)
5262 return std::move(Err);
5263
5264 ToProperty->setLexicalDeclContext(LexicalDC);
5265 LexicalDC->addDeclInternal(ToProperty);
5266
5267 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
5268 ToProperty->setPropertyAttributesAsWritten(
5269 D->getPropertyAttributesAsWritten());
5270 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
5271 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
5272 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
5273 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
5274 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
5275 return ToProperty;
5276}
5277
5278ExpectedDecl
5279ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
5280 ObjCPropertyDecl *Property;
5281 if (Error Err = importInto(Property, D->getPropertyDecl()))
5282 return std::move(Err);
5283
5284 DeclContext *DC, *LexicalDC;
5285 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5286 return std::move(Err);
5287
5288 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
5289
5290 // Import the ivar (for an @synthesize).
5291 ObjCIvarDecl *Ivar = nullptr;
5292 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
5293 return std::move(Err);
5294
5295 ObjCPropertyImplDecl *ToImpl
5296 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
5297 Property->getQueryKind());
5298 if (!ToImpl) {
5299
5300 Error Err = Error::success();
5301 auto ToBeginLoc = importChecked(Err, D->getBeginLoc());
5302 auto ToLocation = importChecked(Err, D->getLocation());
5303 auto ToPropertyIvarDeclLoc =
5304 importChecked(Err, D->getPropertyIvarDeclLoc());
5305 if (Err)
5306 return std::move(Err);
5307
5308 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
5309 ToBeginLoc,
5310 ToLocation, Property,
5311 D->getPropertyImplementation(), Ivar,
5312 ToPropertyIvarDeclLoc))
5313 return ToImpl;
5314
5315 ToImpl->setLexicalDeclContext(LexicalDC);
5316 LexicalDC->addDeclInternal(ToImpl);
5317 } else {
5318 // Check that we have the same kind of property implementation (@synthesize
5319 // vs. @dynamic).
5320 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
5321 Importer.ToDiag(ToImpl->getLocation(),
5322 diag::warn_odr_objc_property_impl_kind_inconsistent)
5323 << Property->getDeclName()
5324 << (ToImpl->getPropertyImplementation()
5325 == ObjCPropertyImplDecl::Dynamic);
5326 Importer.FromDiag(D->getLocation(),
5327 diag::note_odr_objc_property_impl_kind)
5328 << D->getPropertyDecl()->getDeclName()
5329 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
5330
5331 return make_error<ImportError>(ImportError::NameConflict);
5332 }
5333
5334 // For @synthesize, check that we have the same
5335 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
5336 Ivar != ToImpl->getPropertyIvarDecl()) {
5337 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
5338 diag::warn_odr_objc_synthesize_ivar_inconsistent)
5339 << Property->getDeclName()
5340 << ToImpl->getPropertyIvarDecl()->getDeclName()
5341 << Ivar->getDeclName();
5342 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
5343 diag::note_odr_objc_synthesize_ivar_here)
5344 << D->getPropertyIvarDecl()->getDeclName();
5345
5346 return make_error<ImportError>(ImportError::NameConflict);
5347 }
5348
5349 // Merge the existing implementation with the new implementation.
5350 Importer.MapImported(D, ToImpl);
5351 }
5352
5353 return ToImpl;
5354}
5355
5356ExpectedDecl
5357ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
5358 // For template arguments, we adopt the translation unit as our declaration
5359 // context. This context will be fixed when the actual template declaration
5360 // is created.
5361
5362 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5363 if (!BeginLocOrErr)
5364 return BeginLocOrErr.takeError();
5365
5366 ExpectedSLoc LocationOrErr = import(D->getLocation());
5367 if (!LocationOrErr)
5368 return LocationOrErr.takeError();
5369
5370 TemplateTypeParmDecl *ToD = nullptr;
5371 if (GetImportedOrCreateDecl(
5372 ToD, D, Importer.getToContext(),
5373 Importer.getToContext().getTranslationUnitDecl(),
5374 *BeginLocOrErr, *LocationOrErr,
5375 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
5376 D->wasDeclaredWithTypename(), D->isParameterPack(),
5377 D->hasTypeConstraint()))
5378 return ToD;
5379
5380 // Import the type-constraint
5381 if (const TypeConstraint *TC = D->getTypeConstraint()) {
5382
5383 Error Err = Error::success();
5384 auto ToNNS = importChecked(Err, TC->getNestedNameSpecifierLoc());
5385 auto ToName = importChecked(Err, TC->getConceptNameInfo().getName());
5386 auto ToNameLoc = importChecked(Err, TC->getConceptNameInfo().getLoc());
5387 auto ToFoundDecl = importChecked(Err, TC->getFoundDecl());
5388 auto ToNamedConcept = importChecked(Err, TC->getNamedConcept());
5389 auto ToIDC = importChecked(Err, TC->getImmediatelyDeclaredConstraint());
5390 if (Err)
5391 return std::move(Err);
5392
5393 TemplateArgumentListInfo ToTAInfo;
5394 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten();
5395 if (ASTTemplateArgs)
5396 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs,
5397 ToTAInfo))
5398 return std::move(Err);
5399
5400 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc),
5401 ToFoundDecl, ToNamedConcept,
5402 ASTTemplateArgs ?
5403 ASTTemplateArgumentListInfo::Create(Importer.getToContext(),
5404 ToTAInfo) : nullptr,
5405 ToIDC);
5406 }
5407
5408 if (D->hasDefaultArgument()) {
5409 Expected<TypeSourceInfo *> ToDefaultArgOrErr =
5410 import(D->getDefaultArgumentInfo());
5411 if (!ToDefaultArgOrErr)
5412 return ToDefaultArgOrErr.takeError();
5413 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5414 }
5415
5416 return ToD;
5417}
5418
5419ExpectedDecl
5420ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
5421
5422 Error Err = Error::success();
5423 auto ToDeclName = importChecked(Err, D->getDeclName());
5424 auto ToLocation = importChecked(Err, D->getLocation());
5425 auto ToType = importChecked(Err, D->getType());
5426 auto ToTypeSourceInfo = importChecked(Err, D->getTypeSourceInfo());
5427 auto ToInnerLocStart = importChecked(Err, D->getInnerLocStart());
5428 if (Err)
5429 return std::move(Err);
5430
5431 NonTypeTemplateParmDecl *ToD = nullptr;
5432 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(),
5433 Importer.getToContext().getTranslationUnitDecl(),
5434 ToInnerLocStart, ToLocation, D->getDepth(),
5435 D->getPosition(),
5436 ToDeclName.getAsIdentifierInfo(), ToType,
5437 D->isParameterPack(), ToTypeSourceInfo))
5438 return ToD;
5439
5440 if (D->hasDefaultArgument()) {
5441 ExpectedExpr ToDefaultArgOrErr = import(D->getDefaultArgument());
5442 if (!ToDefaultArgOrErr)
5443 return ToDefaultArgOrErr.takeError();
5444 ToD->setDefaultArgument(*ToDefaultArgOrErr);
5445 }
5446
5447 return ToD;
5448}
5449
5450ExpectedDecl
5451ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
5452 // Import the name of this declaration.
5453 auto NameOrErr = import(D->getDeclName());
5454 if (!NameOrErr)
5455 return NameOrErr.takeError();
5456
5457 // Import the location of this declaration.
5458 ExpectedSLoc LocationOrErr = import(D->getLocation());
5459 if (!LocationOrErr)
5460 return LocationOrErr.takeError();
5461
5462 // Import template parameters.
5463 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5464 if (!TemplateParamsOrErr)
5465 return TemplateParamsOrErr.takeError();
5466
5467 TemplateTemplateParmDecl *ToD = nullptr;
5468 if (GetImportedOrCreateDecl(
5469 ToD, D, Importer.getToContext(),
5470 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
5471 D->getDepth(), D->getPosition(), D->isParameterPack(),
5472 (*NameOrErr).getAsIdentifierInfo(), *TemplateParamsOrErr))
5473 return ToD;
5474
5475 if (D->hasDefaultArgument()) {
5476 Expected<TemplateArgumentLoc> ToDefaultArgOrErr =
5477 import(D->getDefaultArgument());
5478 if (!ToDefaultArgOrErr)
5479 return ToDefaultArgOrErr.takeError();
5480 ToD->setDefaultArgument(Importer.getToContext(), *ToDefaultArgOrErr);
5481 }
5482
5483 return ToD;
5484}
5485
5486// Returns the definition for a (forward) declaration of a TemplateDecl, if
5487// it has any definition in the redecl chain.
5488template <typename T> static auto getTemplateDefinition(T *D) -> T * {
5489 assert(D->getTemplatedDecl() && "Should be called on templates only")(static_cast <bool> (D->getTemplatedDecl() &&
"Should be called on templates only") ? void (0) : __assert_fail
("D->getTemplatedDecl() && \"Should be called on templates only\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 5489, __extension__ __PRETTY_FUNCTION__))
;
5490 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
5491 if (!ToTemplatedDef)
5492 return nullptr;
5493 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
5494 return cast_or_null<T>(TemplateWithDef);
5495}
5496
5497ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
5498
5499 // Import the major distinguishing characteristics of this class template.
5500 DeclContext *DC, *LexicalDC;
5501 DeclarationName Name;
5502 SourceLocation Loc;
5503 NamedDecl *ToD;
5504 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5505 return std::move(Err);
5506 if (ToD)
5507 return ToD;
5508
5509 ClassTemplateDecl *FoundByLookup = nullptr;
5510
5511 // We may already have a template of the same name; try to find and match it.
5512 if (!DC->isFunctionOrMethod()) {
5513 SmallVector<NamedDecl *, 4> ConflictingDecls;
5514 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5515 for (auto *FoundDecl : FoundDecls) {
5516 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
5517 Decl::IDNS_TagFriend))
5518 continue;
5519
5520 Decl *Found = FoundDecl;
5521 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
5522 if (FoundTemplate) {
5523 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
5524 continue;
5525
5526 if (IsStructuralMatch(D, FoundTemplate)) {
5527 ClassTemplateDecl *TemplateWithDef =
5528 getTemplateDefinition(FoundTemplate);
5529 if (D->isThisDeclarationADefinition() && TemplateWithDef)
5530 return Importer.MapImported(D, TemplateWithDef);
5531 if (!FoundByLookup)
5532 FoundByLookup = FoundTemplate;
5533 // Search in all matches because there may be multiple decl chains,
5534 // see ASTTests test ImportExistingFriendClassTemplateDef.
5535 continue;
5536 }
5537 ConflictingDecls.push_back(FoundDecl);
5538 }
5539 }
5540
5541 if (!ConflictingDecls.empty()) {
5542 ExpectedName NameOrErr = Importer.HandleNameConflict(
5543 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5544 ConflictingDecls.size());
5545 if (NameOrErr)
5546 Name = NameOrErr.get();
5547 else
5548 return NameOrErr.takeError();
5549 }
5550 }
5551
5552 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
5553
5554 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5555 if (!TemplateParamsOrErr)
5556 return TemplateParamsOrErr.takeError();
5557
5558 // Create the declaration that is being templated.
5559 CXXRecordDecl *ToTemplated;
5560 if (Error Err = importInto(ToTemplated, FromTemplated))
5561 return std::move(Err);
5562
5563 // Create the class template declaration itself.
5564 ClassTemplateDecl *D2;
5565 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5566 *TemplateParamsOrErr, ToTemplated))
5567 return D2;
5568
5569 ToTemplated->setDescribedClassTemplate(D2);
5570
5571 D2->setAccess(D->getAccess());
5572 D2->setLexicalDeclContext(LexicalDC);
5573
5574 addDeclToContexts(D, D2);
5575 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
5576
5577 if (FoundByLookup) {
5578 auto *Recent =
5579 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5580
5581 // It is possible that during the import of the class template definition
5582 // we start the import of a fwd friend decl of the very same class template
5583 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5584 // had been created earlier and by that time the lookup could not find
5585 // anything existing, so it has no previous decl. Later, (still during the
5586 // import of the fwd friend decl) we start to import the definition again
5587 // and this time the lookup finds the previous fwd friend class template.
5588 // In this case we must set up the previous decl for the templated decl.
5589 if (!ToTemplated->getPreviousDecl()) {
5590 assert(FoundByLookup->getTemplatedDecl() &&(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 5591, __extension__ __PRETTY_FUNCTION__))
5591 "Found decl must have its templated decl set")(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 5591, __extension__ __PRETTY_FUNCTION__))
;
5592 CXXRecordDecl *PrevTemplated =
5593 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5594 if (ToTemplated != PrevTemplated)
5595 ToTemplated->setPreviousDecl(PrevTemplated);
5596 }
5597
5598 D2->setPreviousDecl(Recent);
5599 }
5600
5601 if (FromTemplated->isCompleteDefinition() &&
5602 !ToTemplated->isCompleteDefinition()) {
5603 // FIXME: Import definition!
5604 }
5605
5606 return D2;
5607}
5608
5609ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
5610 ClassTemplateSpecializationDecl *D) {
5611 ClassTemplateDecl *ClassTemplate;
11
'ClassTemplate' declared without an initial value
5612 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
12
Calling 'ASTNodeImporter::importInto'
15
Returning from 'ASTNodeImporter::importInto'
16
Assuming the condition is false
17
Taking false branch
5613 return std::move(Err);
5614
5615 // Import the context of this declaration.
5616 DeclContext *DC, *LexicalDC;
5617 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
18
Assuming the condition is false
19
Taking false branch
5618 return std::move(Err);
5619
5620 // Import template arguments.
5621 SmallVector<TemplateArgument, 2> TemplateArgs;
5622 if (Error Err = ImportTemplateArguments(
20
Assuming the condition is false
21
Taking false branch
5623 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5624 return std::move(Err);
5625 // Try to find an existing specialization with these template arguments and
5626 // template parameter list.
5627 void *InsertPos = nullptr;
5628 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5629 ClassTemplatePartialSpecializationDecl *PartialSpec =
5630 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
22
Assuming 'D' is a 'ClassTemplatePartialSpecializationDecl'
5631
5632 // Import template parameters.
5633 TemplateParameterList *ToTPList = nullptr;
5634
5635 if (PartialSpec
22.1
'PartialSpec' is non-null
22.1
'PartialSpec' is non-null
22.1
'PartialSpec' is non-null
22.1
'PartialSpec' is non-null
) {
23
Taking true branch
5636 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5637 if (!ToTPListOrErr)
24
Calling 'Expected::operator bool'
27
Returning from 'Expected::operator bool'
28
Taking false branch
5638 return ToTPListOrErr.takeError();
5639 ToTPList = *ToTPListOrErr;
5640 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs,
29
Called C++ object pointer is uninitialized
5641 *ToTPListOrErr,
5642 InsertPos);
5643 } else
5644 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5645
5646 if (PrevDecl) {
5647 if (IsStructuralMatch(D, PrevDecl)) {
5648 CXXRecordDecl *PrevDefinition = PrevDecl->getDefinition();
5649 if (D->isThisDeclarationADefinition() && PrevDefinition) {
5650 Importer.MapImported(D, PrevDefinition);
5651 // Import those default field initializers which have been
5652 // instantiated in the "From" context, but not in the "To" context.
5653 for (auto *FromField : D->fields()) {
5654 auto ToOrErr = import(FromField);
5655 if (!ToOrErr)
5656 return ToOrErr.takeError();
5657 }
5658
5659 // Import those methods which have been instantiated in the
5660 // "From" context, but not in the "To" context.
5661 for (CXXMethodDecl *FromM : D->methods()) {
5662 auto ToOrErr = import(FromM);
5663 if (!ToOrErr)
5664 return ToOrErr.takeError();
5665 }
5666
5667 // TODO Import instantiated default arguments.
5668 // TODO Import instantiated exception specifications.
5669 //
5670 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5671 // what else could be fused during an AST merge.
5672 return PrevDefinition;
5673 }
5674 } else { // ODR violation.
5675 // FIXME HandleNameConflict
5676 return make_error<ImportError>(ImportError::NameConflict);
5677 }
5678 }
5679
5680 // Import the location of this declaration.
5681 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5682 if (!BeginLocOrErr)
5683 return BeginLocOrErr.takeError();
5684 ExpectedSLoc IdLocOrErr = import(D->getLocation());
5685 if (!IdLocOrErr)
5686 return IdLocOrErr.takeError();
5687
5688 // Create the specialization.
5689 ClassTemplateSpecializationDecl *D2 = nullptr;
5690 if (PartialSpec) {
5691 // Import TemplateArgumentListInfo.
5692 TemplateArgumentListInfo ToTAInfo;
5693 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5694 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5695 return std::move(Err);
5696
5697 QualType CanonInjType;
5698 if (Error Err = importInto(
5699 CanonInjType, PartialSpec->getInjectedSpecializationType()))
5700 return std::move(Err);
5701 CanonInjType = CanonInjType.getCanonicalType();
5702
5703 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5704 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5705 *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate,
5706 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5707 ToTAInfo, CanonInjType,
5708 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5709 return D2;
5710
5711 // Update InsertPos, because preceding import calls may have invalidated
5712 // it by adding new specializations.
5713 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2);
5714 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList,
5715 InsertPos))
5716 // Add this partial specialization to the class template.
5717 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos);
5718
5719 updateLookupTableForTemplateParameters(*ToTPList);
5720 } else { // Not a partial specialization.
5721 if (GetImportedOrCreateDecl(
5722 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5723 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5724 PrevDecl))
5725 return D2;
5726
5727 // Update InsertPos, because preceding import calls may have invalidated
5728 // it by adding new specializations.
5729 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5730 // Add this specialization to the class template.
5731 ClassTemplate->AddSpecialization(D2, InsertPos);
5732 }
5733
5734 D2->setSpecializationKind(D->getSpecializationKind());
5735
5736 // Set the context of this specialization/instantiation.
5737 D2->setLexicalDeclContext(LexicalDC);
5738
5739 // Add to the DC only if it was an explicit specialization/instantiation.
5740 if (D2->isExplicitInstantiationOrSpecialization()) {
5741 LexicalDC->addDeclInternal(D2);
5742 }
5743
5744 if (auto BraceRangeOrErr = import(D->getBraceRange()))
5745 D2->setBraceRange(*BraceRangeOrErr);
5746 else
5747 return BraceRangeOrErr.takeError();
5748
5749 // Import the qualifier, if any.
5750 if (auto LocOrErr = import(D->getQualifierLoc()))
5751 D2->setQualifierInfo(*LocOrErr);
5752 else
5753 return LocOrErr.takeError();
5754
5755 if (auto *TSI = D->getTypeAsWritten()) {
5756 if (auto TInfoOrErr = import(TSI))
5757 D2->setTypeAsWritten(*TInfoOrErr);
5758 else
5759 return TInfoOrErr.takeError();
5760
5761 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5762 D2->setTemplateKeywordLoc(*LocOrErr);
5763 else
5764 return LocOrErr.takeError();
5765
5766 if (auto LocOrErr = import(D->getExternLoc()))
5767 D2->setExternLoc(*LocOrErr);
5768 else
5769 return LocOrErr.takeError();
5770 }
5771
5772 if (D->getPointOfInstantiation().isValid()) {
5773 if (auto POIOrErr = import(D->getPointOfInstantiation()))
5774 D2->setPointOfInstantiation(*POIOrErr);
5775 else
5776 return POIOrErr.takeError();
5777 }
5778
5779 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
5780
5781 if (D->isCompleteDefinition())
5782 if (Error Err = ImportDefinition(D, D2))
5783 return std::move(Err);
5784
5785 return D2;
5786}
5787
5788ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
5789 // Import the major distinguishing characteristics of this variable template.
5790 DeclContext *DC, *LexicalDC;
5791 DeclarationName Name;
5792 SourceLocation Loc;
5793 NamedDecl *ToD;
5794 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5795 return std::move(Err);
5796 if (ToD)
5797 return ToD;
5798
5799 // We may already have a template of the same name; try to find and match it.
5800 assert(!DC->isFunctionOrMethod() &&(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 5801, __extension__ __PRETTY_FUNCTION__))
5801 "Variable templates cannot be declared at function scope")(static_cast <bool> (!DC->isFunctionOrMethod() &&
"Variable templates cannot be declared at function scope") ?
void (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 5801, __extension__ __PRETTY_FUNCTION__))
;
5802
5803 SmallVector<NamedDecl *, 4> ConflictingDecls;
5804 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5805 VarTemplateDecl *FoundByLookup = nullptr;
5806 for (auto *FoundDecl : FoundDecls) {
5807 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5808 continue;
5809
5810 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(FoundDecl)) {
5811 // Use the templated decl, some linkage flags are set only there.
5812 if (!hasSameVisibilityContextAndLinkage(FoundTemplate->getTemplatedDecl(),
5813 D->getTemplatedDecl()))
5814 continue;
5815 if (IsStructuralMatch(D, FoundTemplate)) {
5816 // The Decl in the "From" context has a definition, but in the
5817 // "To" context we already have a definition.
5818 VarTemplateDecl *FoundDef = getTemplateDefinition(FoundTemplate);
5819 if (D->isThisDeclarationADefinition() && FoundDef)
5820 // FIXME Check for ODR error if the two definitions have
5821 // different initializers?
5822 return Importer.MapImported(D, FoundDef);
5823
5824 FoundByLookup = FoundTemplate;
5825 break;
5826 }
5827 ConflictingDecls.push_back(FoundDecl);
5828 }
5829 }
5830
5831 if (!ConflictingDecls.empty()) {
5832 ExpectedName NameOrErr = Importer.HandleNameConflict(
5833 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(),
5834 ConflictingDecls.size());
5835 if (NameOrErr)
5836 Name = NameOrErr.get();
5837 else
5838 return NameOrErr.takeError();
5839 }
5840
5841 VarDecl *DTemplated = D->getTemplatedDecl();
5842
5843 // Import the type.
5844 // FIXME: Value not used?
5845 ExpectedType TypeOrErr = import(DTemplated->getType());
5846 if (!TypeOrErr)
5847 return TypeOrErr.takeError();
5848
5849 // Create the declaration that is being templated.
5850 VarDecl *ToTemplated;
5851 if (Error Err = importInto(ToTemplated, DTemplated))
5852 return std::move(Err);
5853
5854 // Create the variable template declaration itself.
5855 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5856 if (!TemplateParamsOrErr)
5857 return TemplateParamsOrErr.takeError();
5858
5859 VarTemplateDecl *ToVarTD;
5860 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5861 Name, *TemplateParamsOrErr, ToTemplated))
5862 return ToVarTD;
5863
5864 ToTemplated->setDescribedVarTemplate(ToVarTD);
5865
5866 ToVarTD->setAccess(D->getAccess());
5867 ToVarTD->setLexicalDeclContext(LexicalDC);
5868 LexicalDC->addDeclInternal(ToVarTD);
5869 if (DC != Importer.getToContext().getTranslationUnitDecl())
5870 updateLookupTableForTemplateParameters(**TemplateParamsOrErr);
5871
5872 if (FoundByLookup) {
5873 auto *Recent =
5874 const_cast<VarTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5875 if (!ToTemplated->getPreviousDecl()) {
5876 auto *PrevTemplated =
5877 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5878 if (ToTemplated != PrevTemplated)
5879 ToTemplated->setPreviousDecl(PrevTemplated);
5880 }
5881 ToVarTD->setPreviousDecl(Recent);
5882 }
5883
5884 if (DTemplated->isThisDeclarationADefinition() &&
5885 !ToTemplated->isThisDeclarationADefinition()) {
5886 // FIXME: Import definition!
5887 }
5888
5889 return ToVarTD;
5890}
5891
5892ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
5893 VarTemplateSpecializationDecl *D) {
5894 // If this record has a definition in the translation unit we're coming from,
5895 // but this particular declaration is not that definition, import the
5896 // definition and map to that.
5897 VarDecl *Definition = D->getDefinition();
5898 if (Definition && Definition != D) {
5899 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5900 return Importer.MapImported(D, *ImportedDefOrErr);
5901 else
5902 return ImportedDefOrErr.takeError();
5903 }
5904
5905 VarTemplateDecl *VarTemplate = nullptr;
5906 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5907 return std::move(Err);
5908
5909 // Import the context of this declaration.
5910 DeclContext *DC, *LexicalDC;
5911 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5912 return std::move(Err);
5913
5914 // Import the location of this declaration.
5915 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5916 if (!BeginLocOrErr)
5917 return BeginLocOrErr.takeError();
5918
5919 auto IdLocOrErr = import(D->getLocation());
5920 if (!IdLocOrErr)
5921 return IdLocOrErr.takeError();
5922
5923 // Import template arguments.
5924 SmallVector<TemplateArgument, 2> TemplateArgs;
5925 if (Error Err = ImportTemplateArguments(
5926 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5927 return std::move(Err);
5928
5929 // Try to find an existing specialization with these template arguments.
5930 void *InsertPos = nullptr;
5931 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
5932 TemplateArgs, InsertPos);
5933 if (D2) {
5934 // We already have a variable template specialization with these template
5935 // arguments.
5936
5937 // FIXME: Check for specialization vs. instantiation errors.
5938
5939 if (VarDecl *FoundDef = D2->getDefinition()) {
5940 if (!D->isThisDeclarationADefinition() ||
5941 IsStructuralMatch(D, FoundDef)) {
5942 // The record types structurally match, or the "from" translation
5943 // unit only had a forward declaration anyway; call it the same
5944 // variable.
5945 return Importer.MapImported(D, FoundDef);
5946 }
5947 }
5948 } else {
5949 // Import the type.
5950 QualType T;
5951 if (Error Err = importInto(T, D->getType()))
5952 return std::move(Err);
5953
5954 auto TInfoOrErr = import(D->getTypeSourceInfo());
5955 if (!TInfoOrErr)
5956 return TInfoOrErr.takeError();
5957
5958 TemplateArgumentListInfo ToTAInfo;
5959 if (Error Err = ImportTemplateArgumentListInfo(
5960 D->getTemplateArgsInfo(), ToTAInfo))
5961 return std::move(Err);
5962
5963 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5964 // Create a new specialization.
5965 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5966 // Import TemplateArgumentListInfo
5967 TemplateArgumentListInfo ArgInfos;
5968 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5969 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5970 if (Error Err = ImportTemplateArgumentListInfo(
5971 *FromTAArgsAsWritten, ArgInfos))
5972 return std::move(Err);
5973
5974 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5975 if (!ToTPListOrErr)
5976 return ToTPListOrErr.takeError();
5977
5978 PartVarSpecDecl *ToPartial;
5979 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5980 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5981 VarTemplate, T, *TInfoOrErr,
5982 D->getStorageClass(), TemplateArgs, ArgInfos))
5983 return ToPartial;
5984
5985 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5986 FromPartial->getInstantiatedFromMember()))
5987 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5988 else
5989 return ToInstOrErr.takeError();
5990
5991 if (FromPartial->isMemberSpecialization())
5992 ToPartial->setMemberSpecialization();
5993
5994 D2 = ToPartial;
5995
5996 // FIXME: Use this update if VarTemplatePartialSpecializationDecl is fixed
5997 // to adopt template parameters.
5998 // updateLookupTableForTemplateParameters(**ToTPListOrErr);
5999 } else { // Full specialization
6000 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
6001 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
6002 T, *TInfoOrErr,
6003 D->getStorageClass(), TemplateArgs))
6004 return D2;
6005 }
6006
6007 if (D->getPointOfInstantiation().isValid()) {
6008 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
6009 D2->setPointOfInstantiation(*POIOrErr);
6010 else
6011 return POIOrErr.takeError();
6012 }
6013
6014 D2->setSpecializationKind(D->getSpecializationKind());
6015 D2->setTemplateArgsInfo(ToTAInfo);
6016
6017 // Add this specialization to the class template.
6018 VarTemplate->AddSpecialization(D2, InsertPos);
6019
6020 // Import the qualifier, if any.
6021 if (auto LocOrErr = import(D->getQualifierLoc()))
6022 D2->setQualifierInfo(*LocOrErr);
6023 else
6024 return LocOrErr.takeError();
6025
6026 if (D->isConstexpr())
6027 D2->setConstexpr(true);
6028
6029 // Add the specialization to this context.
6030 D2->setLexicalDeclContext(LexicalDC);
6031 LexicalDC->addDeclInternal(D2);
6032
6033 D2->setAccess(D->getAccess());
6034 }
6035
6036 if (Error Err = ImportInitializer(D, D2))
6037 return std::move(Err);
6038
6039 return D2;
6040}
6041
6042ExpectedDecl
6043ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
6044 DeclContext *DC, *LexicalDC;
6045 DeclarationName Name;
6046 SourceLocation Loc;
6047 NamedDecl *ToD;
6048
6049 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
6050 return std::move(Err);
6051
6052 if (ToD)
6053 return ToD;
6054
6055 const FunctionTemplateDecl *FoundByLookup = nullptr;
6056
6057 // Try to find a function in our own ("to") context with the same name, same
6058 // type, and in the same context as the function we're importing.
6059 // FIXME Split this into a separate function.
6060 if (!LexicalDC->isFunctionOrMethod()) {
6061 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
6062 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
6063 for (auto *FoundDecl : FoundDecls) {
6064 if (!FoundDecl->isInIdentifierNamespace(IDNS))
6065 continue;
6066
6067 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
6068 if (!hasSameVisibilityContextAndLinkage(FoundTemplate, D))
6069 continue;
6070 if (IsStructuralMatch(D, FoundTemplate)) {
6071 FunctionTemplateDecl *TemplateWithDef =
6072 getTemplateDefinition(FoundTemplate);
6073 if (D->isThisDeclarationADefinition() && TemplateWithDef)
6074 return Importer.MapImported(D, TemplateWithDef);
6075
6076 FoundByLookup = FoundTemplate;
6077 break;
6078 // TODO: handle conflicting names
6079 }
6080 }
6081 }
6082 }
6083
6084 auto ParamsOrErr = import(D->getTemplateParameters());
6085 if (!ParamsOrErr)
6086 return ParamsOrErr.takeError();
6087 TemplateParameterList *Params = *ParamsOrErr;
6088
6089 FunctionDecl *TemplatedFD;
6090 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
6091 return std::move(Err);
6092
6093 // Template parameters of the ClassTemplateDecl and FunctionTemplateDecl are
6094 // shared, if the FunctionTemplateDecl is a deduction guide for the class.
6095 // At import the ClassTemplateDecl object is always created first (FIXME: is
6096 // this really true?) because the dependency, then the FunctionTemplateDecl.
6097 // The DeclContext of the template parameters is changed when the
6098 // FunctionTemplateDecl is created, but was set already when the class
6099 // template was created. So here it is not the TU (default value) any more.
6100 // FIXME: The DeclContext of the parameters is now set finally to the
6101 // CXXDeductionGuideDecl object that was imported later. This may not be the
6102 // same that is in the original AST, specially if there are multiple deduction
6103 // guides.
6104 DeclContext *OldParamDC = nullptr;
6105 if (Params->size() > 0)
6106 OldParamDC = Params->getParam(0)->getDeclContext();
6107
6108 FunctionTemplateDecl *ToFunc;
6109 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
6110 Params, TemplatedFD))
6111 return ToFunc;
6112
6113 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
6114
6115 ToFunc->setAccess(D->getAccess());
6116 ToFunc->setLexicalDeclContext(LexicalDC);
6117 LexicalDC->addDeclInternal(ToFunc);
6118 updateLookupTableForTemplateParameters(*Params, OldParamDC);
6119
6120 if (FoundByLookup) {
6121 auto *Recent =
6122 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
6123 if (!TemplatedFD->getPreviousDecl()) {
6124 assert(FoundByLookup->getTemplatedDecl() &&(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 6125, __extension__ __PRETTY_FUNCTION__))
6125 "Found decl must have its templated decl set")(static_cast <bool> (FoundByLookup->getTemplatedDecl
() && "Found decl must have its templated decl set") ?
void (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/AST/ASTImporter.cpp"
, 6125, __extension__ __PRETTY_FUNCTION__))
;
6126 auto *PrevTemplated =
6127 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
6128 if (TemplatedFD != PrevTemplated)
6129 TemplatedFD->setPreviousDecl(PrevTemplated);
6130 }
6131 ToFunc->setPreviousDecl(Recent);
6132 }
6133
6134 return ToFunc;
6135}
6136
6137//----------------------------------------------------------------------------
6138// Import Statements
6139//----------------------------------------------------------------------------
6140
6141ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
6142 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
6143 << S->getStmtClassName();
6144 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6145}
6146
6147
6148ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
6149 if (Importer.returnWithErrorInTest())
6150 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6151 SmallVector<IdentifierInfo *, 4> Names;