Bug Summary

File:clang/lib/AST/ASTImporter.cpp
Warning:line 5607, column 39
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -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 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -target-cpu x86-64 -dwarf-column-info -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/include -I /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-01-13-084841-49055-1 -x c++ /build/llvm-toolchain-snapshot-10~++20200112100611+7fa5290d5bd/clang/lib/AST/ASTImporter.cpp

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