Bug Summary

File:build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ASTImporter.cpp
Warning:line 2576, 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-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -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-15~++20220420111733+e13d2efed663/build-llvm -resource-dir /usr/lib/llvm-15/lib/clang/15.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-15~++20220420111733+e13d2efed663/clang/lib/AST -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/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-15/lib/clang/15.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-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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 -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/= -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-04-20-140412-16051-1 -x c++ /build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ASTImporter.cpp

/build/llvm-toolchain-snapshot-15~++20220420111733+e13d2efed663/clang/lib/AST/ASTImporter.cpp

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