Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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

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