Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 5606, column 39
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/build-llvm/include -I /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/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-11/lib/clang/11.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-11~++20200309111110+2c36c23f347/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-03-09-184146-41876-1 -x c++ /build/llvm-toolchain-snapshot-11~++20200309111110+2c36c23f347/clang/lib/AST/ASTImporter.cpp

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