Bug Summary

File:build/source/clang/lib/AST/ASTImporter.cpp
Warning:line 235, column 16
6th function call argument is an uninitialized value

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