Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/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~++20200927111121+5811d723998/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998=. -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-2020-09-28-092409-31635-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200927111121+5811d723998/clang/lib/AST/ASTImporter.cpp

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