Bug Summary

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

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 -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/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-10/lib/clang/10.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-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -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-2019-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/AST/ASTImporter.cpp

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