Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 195, column 16
6th function call argument is an uninitialized value

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~++20210926122410+d23fd8ae8906/build-llvm -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 tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/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-command-line-argument -Wno-unknown-warning-option -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~++20210926122410+d23fd8ae8906/build-llvm -ferror-limit 19 -fvisibility-inlines-hidden -fgnuc-version=4.2.1 -fcolor-diagnostics -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-09-26-234817-15343-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210926122410+d23fd8ae8906/clang/lib/AST/ASTImporter.cpp

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