Bug Summary

File:build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ASTImporter.cpp
Warning:line 9270, column 47
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTImporter.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-10-03-140002-15933-1 -x c++ /build/llvm-toolchain-snapshot-16~++20221003111214+1fa2019828ca/clang/lib/AST/ASTImporter.cpp

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