Bug Summary

File:build/source/clang/include/clang/AST/Expr.h
Warning:line 4238, column 5
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/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -I tools/clang/lib/AST -I /build/source/clang/lib/AST -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -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-17/lib/clang/17/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/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -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/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -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-2023-05-10-133810-16478-1 -x c++ /build/source/clang/lib/AST/ASTImporter.cpp

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