Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 3409, column 53
1st function call argument is an uninitialized value

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/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-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5=. -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 -o /tmp/scan-build-2021-01-16-002530-32805-1 -x c++ /build/llvm-toolchain-snapshot-12~++20210115100614+a14c36fe27f5/clang/lib/AST/ASTImporter.cpp

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