Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/AST/ASTImporter.cpp
Warning:line 2577, column 5
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

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

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/AST/ASTImporter.cpp

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