Bug Summary

File:clang/lib/Serialization/ASTReaderDecl.cpp
Warning:line 2552, column 16
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name ASTReaderDecl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-01-26-233846-219801-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220126101029+f487a76430a0/clang/lib/Serialization/ASTReaderDecl.cpp
1//===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
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 implements the ASTReader::readDeclRecord method, which is the
10// entrypoint for loading a decl.
11//
12//===----------------------------------------------------------------------===//
13
14#include "ASTCommon.h"
15#include "ASTReaderInternals.h"
16#include "clang/AST/ASTContext.h"
17#include "clang/AST/Attr.h"
18#include "clang/AST/AttrIterator.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclBase.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclFriend.h"
23#include "clang/AST/DeclObjC.h"
24#include "clang/AST/DeclOpenMP.h"
25#include "clang/AST/DeclTemplate.h"
26#include "clang/AST/DeclVisitor.h"
27#include "clang/AST/DeclarationName.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/ExternalASTSource.h"
30#include "clang/AST/LambdaCapture.h"
31#include "clang/AST/NestedNameSpecifier.h"
32#include "clang/AST/OpenMPClause.h"
33#include "clang/AST/Redeclarable.h"
34#include "clang/AST/Stmt.h"
35#include "clang/AST/TemplateBase.h"
36#include "clang/AST/Type.h"
37#include "clang/AST/UnresolvedSet.h"
38#include "clang/Basic/AttrKinds.h"
39#include "clang/Basic/ExceptionSpecificationType.h"
40#include "clang/Basic/IdentifierTable.h"
41#include "clang/Basic/LLVM.h"
42#include "clang/Basic/Lambda.h"
43#include "clang/Basic/LangOptions.h"
44#include "clang/Basic/Linkage.h"
45#include "clang/Basic/Module.h"
46#include "clang/Basic/PragmaKinds.h"
47#include "clang/Basic/SourceLocation.h"
48#include "clang/Basic/Specifiers.h"
49#include "clang/Sema/IdentifierResolver.h"
50#include "clang/Serialization/ASTBitCodes.h"
51#include "clang/Serialization/ASTRecordReader.h"
52#include "clang/Serialization/ContinuousRangeMap.h"
53#include "clang/Serialization/ModuleFile.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/FoldingSet.h"
56#include "llvm/ADT/STLExtras.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/iterator_range.h"
60#include "llvm/Bitstream/BitstreamReader.h"
61#include "llvm/Support/Casting.h"
62#include "llvm/Support/ErrorHandling.h"
63#include "llvm/Support/SaveAndRestore.h"
64#include <algorithm>
65#include <cassert>
66#include <cstdint>
67#include <cstring>
68#include <string>
69#include <utility>
70
71using namespace clang;
72using namespace serialization;
73
74//===----------------------------------------------------------------------===//
75// Declaration deserialization
76//===----------------------------------------------------------------------===//
77
78namespace clang {
79
80 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
81 ASTReader &Reader;
82 ASTRecordReader &Record;
83 ASTReader::RecordLocation Loc;
84 const DeclID ThisDeclID;
85 const SourceLocation ThisDeclLoc;
86
87 using RecordData = ASTReader::RecordData;
88
89 TypeID DeferredTypeID = 0;
90 unsigned AnonymousDeclNumber;
91 GlobalDeclID NamedDeclForTagDecl = 0;
92 IdentifierInfo *TypedefNameForLinkage = nullptr;
93
94 bool HasPendingBody = false;
95
96 ///A flag to carry the information for a decl from the entity is
97 /// used. We use it to delay the marking of the canonical decl as used until
98 /// the entire declaration is deserialized and merged.
99 bool IsDeclMarkedUsed = false;
100
101 uint64_t GetCurrentCursorOffset();
102
103 uint64_t ReadLocalOffset() {
104 uint64_t LocalOffset = Record.readInt();
105 assert(LocalOffset < Loc.Offset && "offset point after current record")(static_cast <bool> (LocalOffset < Loc.Offset &&
"offset point after current record") ? void (0) : __assert_fail
("LocalOffset < Loc.Offset && \"offset point after current record\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 105, __extension__
__PRETTY_FUNCTION__))
;
106 return LocalOffset ? Loc.Offset - LocalOffset : 0;
107 }
108
109 uint64_t ReadGlobalOffset() {
110 uint64_t Local = ReadLocalOffset();
111 return Local ? Record.getGlobalBitOffset(Local) : 0;
112 }
113
114 SourceLocation readSourceLocation() {
115 return Record.readSourceLocation();
116 }
117
118 SourceRange readSourceRange() {
119 return Record.readSourceRange();
120 }
121
122 TypeSourceInfo *readTypeSourceInfo() {
123 return Record.readTypeSourceInfo();
124 }
125
126 serialization::DeclID readDeclID() {
127 return Record.readDeclID();
128 }
129
130 std::string readString() {
131 return Record.readString();
132 }
133
134 void readDeclIDList(SmallVectorImpl<DeclID> &IDs) {
135 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
136 IDs.push_back(readDeclID());
137 }
138
139 Decl *readDecl() {
140 return Record.readDecl();
141 }
142
143 template<typename T>
144 T *readDeclAs() {
145 return Record.readDeclAs<T>();
146 }
147
148 serialization::SubmoduleID readSubmoduleID() {
149 if (Record.getIdx() == Record.size())
150 return 0;
151
152 return Record.getGlobalSubmoduleID(Record.readInt());
153 }
154
155 Module *readModule() {
156 return Record.getSubmodule(readSubmoduleID());
157 }
158
159 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
160 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
161 const CXXRecordDecl *D);
162 void MergeDefinitionData(CXXRecordDecl *D,
163 struct CXXRecordDecl::DefinitionData &&NewDD);
164 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
165 void MergeDefinitionData(ObjCInterfaceDecl *D,
166 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
167 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
168 void MergeDefinitionData(ObjCProtocolDecl *D,
169 struct ObjCProtocolDecl::DefinitionData &&NewDD);
170
171 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
172
173 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
174 DeclContext *DC,
175 unsigned Index);
176 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
177 unsigned Index, NamedDecl *D);
178
179 /// Results from loading a RedeclarableDecl.
180 class RedeclarableResult {
181 Decl *MergeWith;
182 GlobalDeclID FirstID;
183 bool IsKeyDecl;
184
185 public:
186 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
187 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
188
189 /// Retrieve the first ID.
190 GlobalDeclID getFirstID() const { return FirstID; }
191
192 /// Is this declaration a key declaration?
193 bool isKeyDecl() const { return IsKeyDecl; }
194
195 /// Get a known declaration that this should be merged with, if
196 /// any.
197 Decl *getKnownMergeTarget() const { return MergeWith; }
198 };
199
200 /// Class used to capture the result of searching for an existing
201 /// declaration of a specific kind and name, along with the ability
202 /// to update the place where this result was found (the declaration
203 /// chain hanging off an identifier or the DeclContext we searched in)
204 /// if requested.
205 class FindExistingResult {
206 ASTReader &Reader;
207 NamedDecl *New = nullptr;
208 NamedDecl *Existing = nullptr;
209 bool AddResult = false;
210 unsigned AnonymousDeclNumber = 0;
211 IdentifierInfo *TypedefNameForLinkage = nullptr;
212
213 public:
214 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
215
216 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
217 unsigned AnonymousDeclNumber,
218 IdentifierInfo *TypedefNameForLinkage)
219 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
220 AnonymousDeclNumber(AnonymousDeclNumber),
221 TypedefNameForLinkage(TypedefNameForLinkage) {}
222
223 FindExistingResult(FindExistingResult &&Other)
224 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
225 AddResult(Other.AddResult),
226 AnonymousDeclNumber(Other.AnonymousDeclNumber),
227 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
228 Other.AddResult = false;
229 }
230
231 FindExistingResult &operator=(FindExistingResult &&) = delete;
232 ~FindExistingResult();
233
234 /// Suppress the addition of this result into the known set of
235 /// names.
236 void suppress() { AddResult = false; }
237
238 operator NamedDecl*() const { return Existing; }
239
240 template<typename T>
241 operator T*() const { return dyn_cast_or_null<T>(Existing); }
242 };
243
244 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
245 DeclContext *DC);
246 FindExistingResult findExisting(NamedDecl *D);
247
248 public:
249 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
250 ASTReader::RecordLocation Loc,
251 DeclID thisDeclID, SourceLocation ThisDeclLoc)
252 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
253 ThisDeclLoc(ThisDeclLoc) {}
254
255 template <typename T> static
256 void AddLazySpecializations(T *D,
257 SmallVectorImpl<serialization::DeclID>& IDs) {
258 if (IDs.empty())
259 return;
260
261 // FIXME: We should avoid this pattern of getting the ASTContext.
262 ASTContext &C = D->getASTContext();
263
264 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
265
266 if (auto &Old = LazySpecializations) {
267 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
268 llvm::sort(IDs);
269 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
270 }
271
272 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
273 *Result = IDs.size();
274 std::copy(IDs.begin(), IDs.end(), Result + 1);
275
276 LazySpecializations = Result;
277 }
278
279 template <typename DeclT>
280 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
281 static Decl *getMostRecentDeclImpl(...);
282 static Decl *getMostRecentDecl(Decl *D);
283
284 static void mergeInheritableAttributes(ASTReader &Reader, Decl *D,
285 Decl *Previous);
286
287 template <typename DeclT>
288 static void attachPreviousDeclImpl(ASTReader &Reader,
289 Redeclarable<DeclT> *D, Decl *Previous,
290 Decl *Canon);
291 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
292 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
293 Decl *Canon);
294
295 template <typename DeclT>
296 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
297 static void attachLatestDeclImpl(...);
298 static void attachLatestDecl(Decl *D, Decl *latest);
299
300 template <typename DeclT>
301 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
302 static void markIncompleteDeclChainImpl(...);
303
304 /// Determine whether this declaration has a pending body.
305 bool hasPendingBody() const { return HasPendingBody; }
306
307 void ReadFunctionDefinition(FunctionDecl *FD);
308 void Visit(Decl *D);
309
310 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
311
312 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
313 ObjCCategoryDecl *Next) {
314 Cat->NextClassCategory = Next;
315 }
316
317 void VisitDecl(Decl *D);
318 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
319 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
320 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
321 void VisitNamedDecl(NamedDecl *ND);
322 void VisitLabelDecl(LabelDecl *LD);
323 void VisitNamespaceDecl(NamespaceDecl *D);
324 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
325 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
326 void VisitTypeDecl(TypeDecl *TD);
327 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
328 void VisitTypedefDecl(TypedefDecl *TD);
329 void VisitTypeAliasDecl(TypeAliasDecl *TD);
330 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
331 void VisitUnresolvedUsingIfExistsDecl(UnresolvedUsingIfExistsDecl *D);
332 RedeclarableResult VisitTagDecl(TagDecl *TD);
333 void VisitEnumDecl(EnumDecl *ED);
334 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
335 void VisitRecordDecl(RecordDecl *RD);
336 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
337 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
338 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
339 ClassTemplateSpecializationDecl *D);
340
341 void VisitClassTemplateSpecializationDecl(
342 ClassTemplateSpecializationDecl *D) {
343 VisitClassTemplateSpecializationDeclImpl(D);
344 }
345
346 void VisitClassTemplatePartialSpecializationDecl(
347 ClassTemplatePartialSpecializationDecl *D);
348 void VisitClassScopeFunctionSpecializationDecl(
349 ClassScopeFunctionSpecializationDecl *D);
350 RedeclarableResult
351 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
352
353 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
354 VisitVarTemplateSpecializationDeclImpl(D);
355 }
356
357 void VisitVarTemplatePartialSpecializationDecl(
358 VarTemplatePartialSpecializationDecl *D);
359 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
360 void VisitValueDecl(ValueDecl *VD);
361 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
362 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
363 void VisitDeclaratorDecl(DeclaratorDecl *DD);
364 void VisitFunctionDecl(FunctionDecl *FD);
365 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
366 void VisitCXXMethodDecl(CXXMethodDecl *D);
367 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
368 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
369 void VisitCXXConversionDecl(CXXConversionDecl *D);
370 void VisitFieldDecl(FieldDecl *FD);
371 void VisitMSPropertyDecl(MSPropertyDecl *FD);
372 void VisitMSGuidDecl(MSGuidDecl *D);
373 void VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D);
374 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
375 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
376 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
377 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
378 void VisitParmVarDecl(ParmVarDecl *PD);
379 void VisitDecompositionDecl(DecompositionDecl *DD);
380 void VisitBindingDecl(BindingDecl *BD);
381 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
382 DeclID VisitTemplateDecl(TemplateDecl *D);
383 void VisitConceptDecl(ConceptDecl *D);
384 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
385 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
386 void VisitClassTemplateDecl(ClassTemplateDecl *D);
387 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
388 void VisitVarTemplateDecl(VarTemplateDecl *D);
389 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
390 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
391 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
392 void VisitUsingDecl(UsingDecl *D);
393 void VisitUsingEnumDecl(UsingEnumDecl *D);
394 void VisitUsingPackDecl(UsingPackDecl *D);
395 void VisitUsingShadowDecl(UsingShadowDecl *D);
396 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
397 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
398 void VisitExportDecl(ExportDecl *D);
399 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
400 void VisitImportDecl(ImportDecl *D);
401 void VisitAccessSpecDecl(AccessSpecDecl *D);
402 void VisitFriendDecl(FriendDecl *D);
403 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
404 void VisitStaticAssertDecl(StaticAssertDecl *D);
405 void VisitBlockDecl(BlockDecl *BD);
406 void VisitCapturedDecl(CapturedDecl *CD);
407 void VisitEmptyDecl(EmptyDecl *D);
408 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
409
410 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
411
412 template<typename T>
413 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
414
415 template<typename T>
416 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
417 DeclID TemplatePatternID = 0);
418
419 template<typename T>
420 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
421 RedeclarableResult &Redecl,
422 DeclID TemplatePatternID = 0);
423
424 template<typename T>
425 void mergeMergeable(Mergeable<T> *D);
426
427 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
428
429 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
430 RedeclarableTemplateDecl *Existing,
431 DeclID DsID, bool IsKeyDecl);
432
433 ObjCTypeParamList *ReadObjCTypeParamList();
434
435 // FIXME: Reorder according to DeclNodes.td?
436 void VisitObjCMethodDecl(ObjCMethodDecl *D);
437 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
438 void VisitObjCContainerDecl(ObjCContainerDecl *D);
439 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
440 void VisitObjCIvarDecl(ObjCIvarDecl *D);
441 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
442 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
443 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
444 void VisitObjCImplDecl(ObjCImplDecl *D);
445 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
446 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
447 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
448 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
449 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
450 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
451 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
452 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
453 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
454 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
455 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
456 };
457
458} // namespace clang
459
460namespace {
461
462/// Iterator over the redeclarations of a declaration that have already
463/// been merged into the same redeclaration chain.
464template<typename DeclT>
465class MergedRedeclIterator {
466 DeclT *Start;
467 DeclT *Canonical = nullptr;
468 DeclT *Current = nullptr;
469
470public:
471 MergedRedeclIterator() = default;
472 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
473
474 DeclT *operator*() { return Current; }
475
476 MergedRedeclIterator &operator++() {
477 if (Current->isFirstDecl()) {
478 Canonical = Current;
479 Current = Current->getMostRecentDecl();
480 } else
481 Current = Current->getPreviousDecl();
482
483 // If we started in the merged portion, we'll reach our start position
484 // eventually. Otherwise, we'll never reach it, but the second declaration
485 // we reached was the canonical declaration, so stop when we see that one
486 // again.
487 if (Current == Start || Current == Canonical)
488 Current = nullptr;
489 return *this;
490 }
491
492 friend bool operator!=(const MergedRedeclIterator &A,
493 const MergedRedeclIterator &B) {
494 return A.Current != B.Current;
495 }
496};
497
498} // namespace
499
500template <typename DeclT>
501static llvm::iterator_range<MergedRedeclIterator<DeclT>>
502merged_redecls(DeclT *D) {
503 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
504 MergedRedeclIterator<DeclT>());
505}
506
507uint64_t ASTDeclReader::GetCurrentCursorOffset() {
508 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
509}
510
511void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
512 if (Record.readInt()) {
513 Reader.DefinitionSource[FD] =
514 Loc.F->Kind == ModuleKind::MK_MainFile ||
515 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
516 }
517 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
518 CD->setNumCtorInitializers(Record.readInt());
519 if (CD->getNumCtorInitializers())
520 CD->CtorInitializers = ReadGlobalOffset();
521 }
522 // Store the offset of the body so we can lazily load it later.
523 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
524 HasPendingBody = true;
525}
526
527void ASTDeclReader::Visit(Decl *D) {
528 DeclVisitor<ASTDeclReader, void>::Visit(D);
529
530 // At this point we have deserialized and merged the decl and it is safe to
531 // update its canonical decl to signal that the entire entity is used.
532 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
533 IsDeclMarkedUsed = false;
534
535 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
536 if (auto *TInfo = DD->getTypeSourceInfo())
537 Record.readTypeLoc(TInfo->getTypeLoc());
538 }
539
540 if (auto *TD = dyn_cast<TypeDecl>(D)) {
541 // We have a fully initialized TypeDecl. Read its type now.
542 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
543
544 // If this is a tag declaration with a typedef name for linkage, it's safe
545 // to load that typedef now.
546 if (NamedDeclForTagDecl)
547 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
548 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
549 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
550 // if we have a fully initialized TypeDecl, we can safely read its type now.
551 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
552 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
553 // FunctionDecl's body was written last after all other Stmts/Exprs.
554 // We only read it if FD doesn't already have a body (e.g., from another
555 // module).
556 // FIXME: Can we diagnose ODR violations somehow?
557 if (Record.readInt())
558 ReadFunctionDefinition(FD);
559 }
560}
561
562void ASTDeclReader::VisitDecl(Decl *D) {
563 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
564 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
565 // We don't want to deserialize the DeclContext of a template
566 // parameter or of a parameter of a function template immediately. These
567 // entities might be used in the formulation of its DeclContext (for
568 // example, a function parameter can be used in decltype() in trailing
569 // return type of the function). Use the translation unit DeclContext as a
570 // placeholder.
571 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
572 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
573 if (!LexicalDCIDForTemplateParmDecl)
574 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
575 Reader.addPendingDeclContextInfo(D,
576 SemaDCIDForTemplateParmDecl,
577 LexicalDCIDForTemplateParmDecl);
578 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
579 } else {
580 auto *SemaDC = readDeclAs<DeclContext>();
581 auto *LexicalDC = readDeclAs<DeclContext>();
582 if (!LexicalDC)
583 LexicalDC = SemaDC;
584 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
585 // Avoid calling setLexicalDeclContext() directly because it uses
586 // Decl::getASTContext() internally which is unsafe during derialization.
587 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
588 Reader.getContext());
589 }
590 D->setLocation(ThisDeclLoc);
591 D->InvalidDecl = Record.readInt();
592 if (Record.readInt()) { // hasAttrs
593 AttrVec Attrs;
594 Record.readAttributes(Attrs);
595 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
596 // internally which is unsafe during derialization.
597 D->setAttrsImpl(Attrs, Reader.getContext());
598 }
599 D->setImplicit(Record.readInt());
600 D->Used = Record.readInt();
601 IsDeclMarkedUsed |= D->Used;
602 D->setReferenced(Record.readInt());
603 D->setTopLevelDeclInObjCContainer(Record.readInt());
604 D->setAccess((AccessSpecifier)Record.readInt());
605 D->FromASTFile = true;
606 bool ModulePrivate = Record.readInt();
607
608 // Determine whether this declaration is part of a (sub)module. If so, it
609 // may not yet be visible.
610 if (unsigned SubmoduleID = readSubmoduleID()) {
611 // Store the owning submodule ID in the declaration.
612 D->setModuleOwnershipKind(
613 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
614 : Decl::ModuleOwnershipKind::VisibleWhenImported);
615 D->setOwningModuleID(SubmoduleID);
616
617 if (ModulePrivate) {
618 // Module-private declarations are never visible, so there is no work to
619 // do.
620 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
621 // If local visibility is being tracked, this declaration will become
622 // hidden and visible as the owning module does.
623 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
624 // Mark the declaration as visible when its owning module becomes visible.
625 if (Owner->NameVisibility == Module::AllVisible)
626 D->setVisibleDespiteOwningModule();
627 else
628 Reader.HiddenNamesMap[Owner].push_back(D);
629 }
630 } else if (ModulePrivate) {
631 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
632 }
633}
634
635void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
636 VisitDecl(D);
637 D->setLocation(readSourceLocation());
638 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
639 std::string Arg = readString();
640 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
641 D->getTrailingObjects<char>()[Arg.size()] = '\0';
642}
643
644void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
645 VisitDecl(D);
646 D->setLocation(readSourceLocation());
647 std::string Name = readString();
648 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
649 D->getTrailingObjects<char>()[Name.size()] = '\0';
650
651 D->ValueStart = Name.size() + 1;
652 std::string Value = readString();
653 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
654 Value.size());
655 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
656}
657
658void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
659 llvm_unreachable("Translation units are not serialized")::llvm::llvm_unreachable_internal("Translation units are not serialized"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 659)
;
660}
661
662void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
663 VisitDecl(ND);
664 ND->setDeclName(Record.readDeclarationName());
665 AnonymousDeclNumber = Record.readInt();
666}
667
668void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
669 VisitNamedDecl(TD);
670 TD->setLocStart(readSourceLocation());
671 // Delay type reading until after we have fully initialized the decl.
672 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
673}
674
675ASTDeclReader::RedeclarableResult
676ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
677 RedeclarableResult Redecl = VisitRedeclarable(TD);
678 VisitTypeDecl(TD);
679 TypeSourceInfo *TInfo = readTypeSourceInfo();
680 if (Record.readInt()) { // isModed
681 QualType modedT = Record.readType();
682 TD->setModedTypeSourceInfo(TInfo, modedT);
683 } else
684 TD->setTypeSourceInfo(TInfo);
685 // Read and discard the declaration for which this is a typedef name for
686 // linkage, if it exists. We cannot rely on our type to pull in this decl,
687 // because it might have been merged with a type from another module and
688 // thus might not refer to our version of the declaration.
689 readDecl();
690 return Redecl;
691}
692
693void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
694 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
695 mergeRedeclarable(TD, Redecl);
696}
697
698void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
699 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
700 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
701 // Merged when we merge the template.
702 TD->setDescribedAliasTemplate(Template);
703 else
704 mergeRedeclarable(TD, Redecl);
705}
706
707ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
708 RedeclarableResult Redecl = VisitRedeclarable(TD);
709 VisitTypeDecl(TD);
710
711 TD->IdentifierNamespace = Record.readInt();
712 TD->setTagKind((TagDecl::TagKind)Record.readInt());
713 if (!isa<CXXRecordDecl>(TD))
714 TD->setCompleteDefinition(Record.readInt());
715 TD->setEmbeddedInDeclarator(Record.readInt());
716 TD->setFreeStanding(Record.readInt());
717 TD->setCompleteDefinitionRequired(Record.readInt());
718 TD->setBraceRange(readSourceRange());
719
720 switch (Record.readInt()) {
721 case 0:
722 break;
723 case 1: { // ExtInfo
724 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
725 Record.readQualifierInfo(*Info);
726 TD->TypedefNameDeclOrQualifier = Info;
727 break;
728 }
729 case 2: // TypedefNameForAnonDecl
730 NamedDeclForTagDecl = readDeclID();
731 TypedefNameForLinkage = Record.readIdentifier();
732 break;
733 default:
734 llvm_unreachable("unexpected tag info kind")::llvm::llvm_unreachable_internal("unexpected tag info kind",
"clang/lib/Serialization/ASTReaderDecl.cpp", 734)
;
735 }
736
737 if (!isa<CXXRecordDecl>(TD))
738 mergeRedeclarable(TD, Redecl);
739 return Redecl;
740}
741
742void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
743 VisitTagDecl(ED);
744 if (TypeSourceInfo *TI = readTypeSourceInfo())
745 ED->setIntegerTypeSourceInfo(TI);
746 else
747 ED->setIntegerType(Record.readType());
748 ED->setPromotionType(Record.readType());
749 ED->setNumPositiveBits(Record.readInt());
750 ED->setNumNegativeBits(Record.readInt());
751 ED->setScoped(Record.readInt());
752 ED->setScopedUsingClassTag(Record.readInt());
753 ED->setFixed(Record.readInt());
754
755 ED->setHasODRHash(true);
756 ED->ODRHash = Record.readInt();
757
758 // If this is a definition subject to the ODR, and we already have a
759 // definition, merge this one into it.
760 if (ED->isCompleteDefinition() &&
761 Reader.getContext().getLangOpts().Modules &&
762 Reader.getContext().getLangOpts().CPlusPlus) {
763 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
764 if (!OldDef) {
765 // This is the first time we've seen an imported definition. Look for a
766 // local definition before deciding that we are the first definition.
767 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
768 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
769 OldDef = D;
770 break;
771 }
772 }
773 }
774 if (OldDef) {
775 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
776 ED->setCompleteDefinition(false);
777 Reader.mergeDefinitionVisibility(OldDef, ED);
778 if (OldDef->getODRHash() != ED->getODRHash())
779 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
780 } else {
781 OldDef = ED;
782 }
783 }
784
785 if (auto *InstED = readDeclAs<EnumDecl>()) {
786 auto TSK = (TemplateSpecializationKind)Record.readInt();
787 SourceLocation POI = readSourceLocation();
788 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
789 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
790 }
791}
792
793ASTDeclReader::RedeclarableResult
794ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
795 RedeclarableResult Redecl = VisitTagDecl(RD);
796 RD->setHasFlexibleArrayMember(Record.readInt());
797 RD->setAnonymousStructOrUnion(Record.readInt());
798 RD->setHasObjectMember(Record.readInt());
799 RD->setHasVolatileMember(Record.readInt());
800 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
801 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
802 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
803 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
804 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
805 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
806 RD->setParamDestroyedInCallee(Record.readInt());
807 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
808 return Redecl;
809}
810
811void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
812 VisitRecordDeclImpl(RD);
813
814 // Maintain the invariant of a redeclaration chain containing only
815 // a single definition.
816 if (RD->isCompleteDefinition()) {
817 RecordDecl *Canon = static_cast<RecordDecl *>(RD->getCanonicalDecl());
818 RecordDecl *&OldDef = Reader.RecordDefinitions[Canon];
819 if (!OldDef) {
820 // This is the first time we've seen an imported definition. Look for a
821 // local definition before deciding that we are the first definition.
822 for (auto *D : merged_redecls(Canon)) {
823 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
824 OldDef = D;
825 break;
826 }
827 }
828 }
829 if (OldDef) {
830 Reader.MergedDeclContexts.insert(std::make_pair(RD, OldDef));
831 RD->setCompleteDefinition(false);
832 Reader.mergeDefinitionVisibility(OldDef, RD);
833 } else {
834 OldDef = RD;
835 }
836 }
837}
838
839void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
840 VisitNamedDecl(VD);
841 // For function declarations, defer reading the type in case the function has
842 // a deduced return type that references an entity declared within the
843 // function.
844 if (isa<FunctionDecl>(VD))
845 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
846 else
847 VD->setType(Record.readType());
848}
849
850void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
851 VisitValueDecl(ECD);
852 if (Record.readInt())
853 ECD->setInitExpr(Record.readExpr());
854 ECD->setInitVal(Record.readAPSInt());
855 mergeMergeable(ECD);
856}
857
858void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
859 VisitValueDecl(DD);
860 DD->setInnerLocStart(readSourceLocation());
861 if (Record.readInt()) { // hasExtInfo
862 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
863 Record.readQualifierInfo(*Info);
864 Info->TrailingRequiresClause = Record.readExpr();
865 DD->DeclInfo = Info;
866 }
867 QualType TSIType = Record.readType();
868 DD->setTypeSourceInfo(
869 TSIType.isNull() ? nullptr
870 : Reader.getContext().CreateTypeSourceInfo(TSIType));
871}
872
873void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
874 RedeclarableResult Redecl = VisitRedeclarable(FD);
875 VisitDeclaratorDecl(FD);
876
877 // Attach a type to this function. Use the real type if possible, but fall
878 // back to the type as written if it involves a deduced return type.
879 if (FD->getTypeSourceInfo() &&
880 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
881 ->getReturnType()->getContainedAutoType()) {
882 // We'll set up the real type in Visit, once we've finished loading the
883 // function.
884 FD->setType(FD->getTypeSourceInfo()->getType());
885 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
886 } else {
887 FD->setType(Reader.GetType(DeferredTypeID));
888 }
889 DeferredTypeID = 0;
890
891 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
892 FD->IdentifierNamespace = Record.readInt();
893
894 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
895 // after everything else is read.
896
897 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
898 FD->setInlineSpecified(Record.readInt());
899 FD->setImplicitlyInline(Record.readInt());
900 FD->setVirtualAsWritten(Record.readInt());
901 // We defer calling `FunctionDecl::setPure()` here as for methods of
902 // `CXXTemplateSpecializationDecl`s, we may not have connected up the
903 // definition (which is required for `setPure`).
904 const bool Pure = Record.readInt();
905 FD->setHasInheritedPrototype(Record.readInt());
906 FD->setHasWrittenPrototype(Record.readInt());
907 FD->setDeletedAsWritten(Record.readInt());
908 FD->setTrivial(Record.readInt());
909 FD->setTrivialForCall(Record.readInt());
910 FD->setDefaulted(Record.readInt());
911 FD->setExplicitlyDefaulted(Record.readInt());
912 FD->setHasImplicitReturnZero(Record.readInt());
913 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
914 FD->setUsesSEHTry(Record.readInt());
915 FD->setHasSkippedBody(Record.readInt());
916 FD->setIsMultiVersion(Record.readInt());
917 FD->setLateTemplateParsed(Record.readInt());
918
919 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
920 FD->EndRangeLoc = readSourceLocation();
921
922 FD->ODRHash = Record.readInt();
923 FD->setHasODRHash(true);
924
925 if (FD->isDefaulted()) {
926 if (unsigned NumLookups = Record.readInt()) {
927 SmallVector<DeclAccessPair, 8> Lookups;
928 for (unsigned I = 0; I != NumLookups; ++I) {
929 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
930 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
931 Lookups.push_back(DeclAccessPair::make(ND, AS));
932 }
933 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
934 Reader.getContext(), Lookups));
935 }
936 }
937
938 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
939 case FunctionDecl::TK_NonTemplate:
940 mergeRedeclarable(FD, Redecl);
941 break;
942 case FunctionDecl::TK_FunctionTemplate:
943 // Merged when we merge the template.
944 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
945 break;
946 case FunctionDecl::TK_MemberSpecialization: {
947 auto *InstFD = readDeclAs<FunctionDecl>();
948 auto TSK = (TemplateSpecializationKind)Record.readInt();
949 SourceLocation POI = readSourceLocation();
950 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
951 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
952 mergeRedeclarable(FD, Redecl);
953 break;
954 }
955 case FunctionDecl::TK_FunctionTemplateSpecialization: {
956 auto *Template = readDeclAs<FunctionTemplateDecl>();
957 auto TSK = (TemplateSpecializationKind)Record.readInt();
958
959 // Template arguments.
960 SmallVector<TemplateArgument, 8> TemplArgs;
961 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
962
963 // Template args as written.
964 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
965 SourceLocation LAngleLoc, RAngleLoc;
966 bool HasTemplateArgumentsAsWritten = Record.readInt();
967 if (HasTemplateArgumentsAsWritten) {
968 unsigned NumTemplateArgLocs = Record.readInt();
969 TemplArgLocs.reserve(NumTemplateArgLocs);
970 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
971 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
972
973 LAngleLoc = readSourceLocation();
974 RAngleLoc = readSourceLocation();
975 }
976
977 SourceLocation POI = readSourceLocation();
978
979 ASTContext &C = Reader.getContext();
980 TemplateArgumentList *TemplArgList
981 = TemplateArgumentList::CreateCopy(C, TemplArgs);
982 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
983 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
984 TemplArgsInfo.addArgument(TemplArgLocs[i]);
985
986 MemberSpecializationInfo *MSInfo = nullptr;
987 if (Record.readInt()) {
988 auto *FD = readDeclAs<FunctionDecl>();
989 auto TSK = (TemplateSpecializationKind)Record.readInt();
990 SourceLocation POI = readSourceLocation();
991
992 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
993 MSInfo->setPointOfInstantiation(POI);
994 }
995
996 FunctionTemplateSpecializationInfo *FTInfo =
997 FunctionTemplateSpecializationInfo::Create(
998 C, FD, Template, TSK, TemplArgList,
999 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
1000 MSInfo);
1001 FD->TemplateOrSpecialization = FTInfo;
1002
1003 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
1004 // The template that contains the specializations set. It's not safe to
1005 // use getCanonicalDecl on Template since it may still be initializing.
1006 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
1007 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
1008 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
1009 // FunctionTemplateSpecializationInfo's Profile().
1010 // We avoid getASTContext because a decl in the parent hierarchy may
1011 // be initializing.
1012 llvm::FoldingSetNodeID ID;
1013 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
1014 void *InsertPos = nullptr;
1015 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
1016 FunctionTemplateSpecializationInfo *ExistingInfo =
1017 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
1018 if (InsertPos)
1019 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
1020 else {
1021 assert(Reader.getContext().getLangOpts().Modules &&(static_cast <bool> (Reader.getContext().getLangOpts().
Modules && "already deserialized this template specialization"
) ? void (0) : __assert_fail ("Reader.getContext().getLangOpts().Modules && \"already deserialized this template specialization\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1022, __extension__
__PRETTY_FUNCTION__))
1022 "already deserialized this template specialization")(static_cast <bool> (Reader.getContext().getLangOpts().
Modules && "already deserialized this template specialization"
) ? void (0) : __assert_fail ("Reader.getContext().getLangOpts().Modules && \"already deserialized this template specialization\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1022, __extension__
__PRETTY_FUNCTION__))
;
1023 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
1024 }
1025 }
1026 break;
1027 }
1028 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
1029 // Templates.
1030 UnresolvedSet<8> TemplDecls;
1031 unsigned NumTemplates = Record.readInt();
1032 while (NumTemplates--)
1033 TemplDecls.addDecl(readDeclAs<NamedDecl>());
1034
1035 // Templates args.
1036 TemplateArgumentListInfo TemplArgs;
1037 unsigned NumArgs = Record.readInt();
1038 while (NumArgs--)
1039 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1040 TemplArgs.setLAngleLoc(readSourceLocation());
1041 TemplArgs.setRAngleLoc(readSourceLocation());
1042
1043 FD->setDependentTemplateSpecialization(Reader.getContext(),
1044 TemplDecls, TemplArgs);
1045 // These are not merged; we don't need to merge redeclarations of dependent
1046 // template friends.
1047 break;
1048 }
1049 }
1050
1051 // Defer calling `setPure` until merging above has guaranteed we've set
1052 // `DefinitionData` (as this will need to access it).
1053 FD->setPure(Pure);
1054
1055 // Read in the parameters.
1056 unsigned NumParams = Record.readInt();
1057 SmallVector<ParmVarDecl *, 16> Params;
1058 Params.reserve(NumParams);
1059 for (unsigned I = 0; I != NumParams; ++I)
1060 Params.push_back(readDeclAs<ParmVarDecl>());
1061 FD->setParams(Reader.getContext(), Params);
1062}
1063
1064void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1065 VisitNamedDecl(MD);
1066 if (Record.readInt()) {
1067 // Load the body on-demand. Most clients won't care, because method
1068 // definitions rarely show up in headers.
1069 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1070 HasPendingBody = true;
1071 }
1072 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1073 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1074 MD->setInstanceMethod(Record.readInt());
1075 MD->setVariadic(Record.readInt());
1076 MD->setPropertyAccessor(Record.readInt());
1077 MD->setSynthesizedAccessorStub(Record.readInt());
1078 MD->setDefined(Record.readInt());
1079 MD->setOverriding(Record.readInt());
1080 MD->setHasSkippedBody(Record.readInt());
1081
1082 MD->setIsRedeclaration(Record.readInt());
1083 MD->setHasRedeclaration(Record.readInt());
1084 if (MD->hasRedeclaration())
1085 Reader.getContext().setObjCMethodRedeclaration(MD,
1086 readDeclAs<ObjCMethodDecl>());
1087
1088 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1089 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1090 MD->setRelatedResultType(Record.readInt());
1091 MD->setReturnType(Record.readType());
1092 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1093 MD->DeclEndLoc = readSourceLocation();
1094 unsigned NumParams = Record.readInt();
1095 SmallVector<ParmVarDecl *, 16> Params;
1096 Params.reserve(NumParams);
1097 for (unsigned I = 0; I != NumParams; ++I)
1098 Params.push_back(readDeclAs<ParmVarDecl>());
1099
1100 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1101 unsigned NumStoredSelLocs = Record.readInt();
1102 SmallVector<SourceLocation, 16> SelLocs;
1103 SelLocs.reserve(NumStoredSelLocs);
1104 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1105 SelLocs.push_back(readSourceLocation());
1106
1107 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1108}
1109
1110void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1111 VisitTypedefNameDecl(D);
1112
1113 D->Variance = Record.readInt();
1114 D->Index = Record.readInt();
1115 D->VarianceLoc = readSourceLocation();
1116 D->ColonLoc = readSourceLocation();
1117}
1118
1119void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1120 VisitNamedDecl(CD);
1121 CD->setAtStartLoc(readSourceLocation());
1122 CD->setAtEndRange(readSourceRange());
1123}
1124
1125ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1126 unsigned numParams = Record.readInt();
1127 if (numParams == 0)
1128 return nullptr;
1129
1130 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1131 typeParams.reserve(numParams);
1132 for (unsigned i = 0; i != numParams; ++i) {
1133 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1134 if (!typeParam)
1135 return nullptr;
1136
1137 typeParams.push_back(typeParam);
1138 }
1139
1140 SourceLocation lAngleLoc = readSourceLocation();
1141 SourceLocation rAngleLoc = readSourceLocation();
1142
1143 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1144 typeParams, rAngleLoc);
1145}
1146
1147void ASTDeclReader::ReadObjCDefinitionData(
1148 struct ObjCInterfaceDecl::DefinitionData &Data) {
1149 // Read the superclass.
1150 Data.SuperClassTInfo = readTypeSourceInfo();
1151
1152 Data.EndLoc = readSourceLocation();
1153 Data.HasDesignatedInitializers = Record.readInt();
1154
1155 // Read the directly referenced protocols and their SourceLocations.
1156 unsigned NumProtocols = Record.readInt();
1157 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1158 Protocols.reserve(NumProtocols);
1159 for (unsigned I = 0; I != NumProtocols; ++I)
1160 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1161 SmallVector<SourceLocation, 16> ProtoLocs;
1162 ProtoLocs.reserve(NumProtocols);
1163 for (unsigned I = 0; I != NumProtocols; ++I)
1164 ProtoLocs.push_back(readSourceLocation());
1165 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1166 Reader.getContext());
1167
1168 // Read the transitive closure of protocols referenced by this class.
1169 NumProtocols = Record.readInt();
1170 Protocols.clear();
1171 Protocols.reserve(NumProtocols);
1172 for (unsigned I = 0; I != NumProtocols; ++I)
1173 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1174 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1175 Reader.getContext());
1176}
1177
1178void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1179 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1180 struct ObjCInterfaceDecl::DefinitionData &DD = D->data();
1181 if (DD.Definition != NewDD.Definition) {
1182 Reader.MergedDeclContexts.insert(
1183 std::make_pair(NewDD.Definition, DD.Definition));
1184 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1185 }
1186
1187 // FIXME: odr checking?
1188}
1189
1190void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1191 RedeclarableResult Redecl = VisitRedeclarable(ID);
1192 VisitObjCContainerDecl(ID);
1193 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1194 mergeRedeclarable(ID, Redecl);
1195
1196 ID->TypeParamList = ReadObjCTypeParamList();
1197 if (Record.readInt()) {
1198 // Read the definition.
1199 ID->allocateDefinitionData();
1200
1201 ReadObjCDefinitionData(ID->data());
1202 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1203 if (Canon->Data.getPointer()) {
1204 // If we already have a definition, keep the definition invariant and
1205 // merge the data.
1206 MergeDefinitionData(Canon, std::move(ID->data()));
1207 ID->Data = Canon->Data;
1208 } else {
1209 // Set the definition data of the canonical declaration, so other
1210 // redeclarations will see it.
1211 ID->getCanonicalDecl()->Data = ID->Data;
1212
1213 // We will rebuild this list lazily.
1214 ID->setIvarList(nullptr);
1215 }
1216
1217 // Note that we have deserialized a definition.
1218 Reader.PendingDefinitions.insert(ID);
1219
1220 // Note that we've loaded this Objective-C class.
1221 Reader.ObjCClassesLoaded.push_back(ID);
1222 } else {
1223 ID->Data = ID->getCanonicalDecl()->Data;
1224 }
1225}
1226
1227void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1228 VisitFieldDecl(IVD);
1229 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1230 // This field will be built lazily.
1231 IVD->setNextIvar(nullptr);
1232 bool synth = Record.readInt();
1233 IVD->setSynthesize(synth);
1234}
1235
1236void ASTDeclReader::ReadObjCDefinitionData(
1237 struct ObjCProtocolDecl::DefinitionData &Data) {
1238 unsigned NumProtoRefs = Record.readInt();
1239 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1240 ProtoRefs.reserve(NumProtoRefs);
1241 for (unsigned I = 0; I != NumProtoRefs; ++I)
1242 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1243 SmallVector<SourceLocation, 16> ProtoLocs;
1244 ProtoLocs.reserve(NumProtoRefs);
1245 for (unsigned I = 0; I != NumProtoRefs; ++I)
1246 ProtoLocs.push_back(readSourceLocation());
1247 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1248 ProtoLocs.data(), Reader.getContext());
1249}
1250
1251void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1252 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1253 struct ObjCProtocolDecl::DefinitionData &DD = D->data();
1254 if (DD.Definition != NewDD.Definition) {
1255 Reader.MergedDeclContexts.insert(
1256 std::make_pair(NewDD.Definition, DD.Definition));
1257 Reader.mergeDefinitionVisibility(DD.Definition, NewDD.Definition);
1258 }
1259
1260 // FIXME: odr checking?
1261}
1262
1263void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1264 RedeclarableResult Redecl = VisitRedeclarable(PD);
1265 VisitObjCContainerDecl(PD);
1266 mergeRedeclarable(PD, Redecl);
1267
1268 if (Record.readInt()) {
1269 // Read the definition.
1270 PD->allocateDefinitionData();
1271
1272 ReadObjCDefinitionData(PD->data());
1273
1274 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1275 if (Canon->Data.getPointer()) {
1276 // If we already have a definition, keep the definition invariant and
1277 // merge the data.
1278 MergeDefinitionData(Canon, std::move(PD->data()));
1279 PD->Data = Canon->Data;
1280 } else {
1281 // Set the definition data of the canonical declaration, so other
1282 // redeclarations will see it.
1283 PD->getCanonicalDecl()->Data = PD->Data;
1284 }
1285 // Note that we have deserialized a definition.
1286 Reader.PendingDefinitions.insert(PD);
1287 } else {
1288 PD->Data = PD->getCanonicalDecl()->Data;
1289 }
1290}
1291
1292void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1293 VisitFieldDecl(FD);
1294}
1295
1296void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1297 VisitObjCContainerDecl(CD);
1298 CD->setCategoryNameLoc(readSourceLocation());
1299 CD->setIvarLBraceLoc(readSourceLocation());
1300 CD->setIvarRBraceLoc(readSourceLocation());
1301
1302 // Note that this category has been deserialized. We do this before
1303 // deserializing the interface declaration, so that it will consider this
1304 /// category.
1305 Reader.CategoriesDeserialized.insert(CD);
1306
1307 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1308 CD->TypeParamList = ReadObjCTypeParamList();
1309 unsigned NumProtoRefs = Record.readInt();
1310 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1311 ProtoRefs.reserve(NumProtoRefs);
1312 for (unsigned I = 0; I != NumProtoRefs; ++I)
1313 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1314 SmallVector<SourceLocation, 16> ProtoLocs;
1315 ProtoLocs.reserve(NumProtoRefs);
1316 for (unsigned I = 0; I != NumProtoRefs; ++I)
1317 ProtoLocs.push_back(readSourceLocation());
1318 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1319 Reader.getContext());
1320
1321 // Protocols in the class extension belong to the class.
1322 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1323 CD->ClassInterface->mergeClassExtensionProtocolList(
1324 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1325 Reader.getContext());
1326}
1327
1328void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1329 VisitNamedDecl(CAD);
1330 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1331}
1332
1333void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1334 VisitNamedDecl(D);
1335 D->setAtLoc(readSourceLocation());
1336 D->setLParenLoc(readSourceLocation());
1337 QualType T = Record.readType();
1338 TypeSourceInfo *TSI = readTypeSourceInfo();
1339 D->setType(T, TSI);
1340 D->setPropertyAttributes((ObjCPropertyAttribute::Kind)Record.readInt());
1341 D->setPropertyAttributesAsWritten(
1342 (ObjCPropertyAttribute::Kind)Record.readInt());
1343 D->setPropertyImplementation(
1344 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1345 DeclarationName GetterName = Record.readDeclarationName();
1346 SourceLocation GetterLoc = readSourceLocation();
1347 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1348 DeclarationName SetterName = Record.readDeclarationName();
1349 SourceLocation SetterLoc = readSourceLocation();
1350 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1351 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1352 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1353 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1354}
1355
1356void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1357 VisitObjCContainerDecl(D);
1358 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1359}
1360
1361void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1362 VisitObjCImplDecl(D);
1363 D->CategoryNameLoc = readSourceLocation();
1364}
1365
1366void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1367 VisitObjCImplDecl(D);
1368 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1369 D->SuperLoc = readSourceLocation();
1370 D->setIvarLBraceLoc(readSourceLocation());
1371 D->setIvarRBraceLoc(readSourceLocation());
1372 D->setHasNonZeroConstructors(Record.readInt());
1373 D->setHasDestructors(Record.readInt());
1374 D->NumIvarInitializers = Record.readInt();
1375 if (D->NumIvarInitializers)
1376 D->IvarInitializers = ReadGlobalOffset();
1377}
1378
1379void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1380 VisitDecl(D);
1381 D->setAtLoc(readSourceLocation());
1382 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1383 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1384 D->IvarLoc = readSourceLocation();
1385 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1386 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1387 D->setGetterCXXConstructor(Record.readExpr());
1388 D->setSetterCXXAssignment(Record.readExpr());
1389}
1390
1391void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1392 VisitDeclaratorDecl(FD);
1393 FD->Mutable = Record.readInt();
1394
1395 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1396 FD->InitStorage.setInt(ISK);
1397 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1398 ? Record.readType().getAsOpaquePtr()
1399 : Record.readExpr());
1400 }
1401
1402 if (auto *BW = Record.readExpr())
1403 FD->setBitWidth(BW);
1404
1405 if (!FD->getDeclName()) {
1406 if (auto *Tmpl = readDeclAs<FieldDecl>())
1407 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1408 }
1409 mergeMergeable(FD);
1410}
1411
1412void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1413 VisitDeclaratorDecl(PD);
1414 PD->GetterId = Record.readIdentifier();
1415 PD->SetterId = Record.readIdentifier();
1416}
1417
1418void ASTDeclReader::VisitMSGuidDecl(MSGuidDecl *D) {
1419 VisitValueDecl(D);
1420 D->PartVal.Part1 = Record.readInt();
1421 D->PartVal.Part2 = Record.readInt();
1422 D->PartVal.Part3 = Record.readInt();
1423 for (auto &C : D->PartVal.Part4And5)
1424 C = Record.readInt();
1425
1426 // Add this GUID to the AST context's lookup structure, and merge if needed.
1427 if (MSGuidDecl *Existing = Reader.getContext().MSGuidDecls.GetOrInsertNode(D))
1428 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1429}
1430
1431void ASTDeclReader::VisitTemplateParamObjectDecl(TemplateParamObjectDecl *D) {
1432 VisitValueDecl(D);
1433 D->Value = Record.readAPValue();
1434
1435 // Add this template parameter object to the AST context's lookup structure,
1436 // and merge if needed.
1437 if (TemplateParamObjectDecl *Existing =
1438 Reader.getContext().TemplateParamObjectDecls.GetOrInsertNode(D))
1439 Reader.getContext().setPrimaryMergedDecl(D, Existing->getCanonicalDecl());
1440}
1441
1442void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1443 VisitValueDecl(FD);
1444
1445 FD->ChainingSize = Record.readInt();
1446 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2")(static_cast <bool> (FD->ChainingSize >= 2 &&
"Anonymous chaining must be >= 2") ? void (0) : __assert_fail
("FD->ChainingSize >= 2 && \"Anonymous chaining must be >= 2\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1446, __extension__
__PRETTY_FUNCTION__))
;
1447 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1448
1449 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1450 FD->Chaining[I] = readDeclAs<NamedDecl>();
1451
1452 mergeMergeable(FD);
1453}
1454
1455ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1456 RedeclarableResult Redecl = VisitRedeclarable(VD);
1457 VisitDeclaratorDecl(VD);
1458
1459 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1460 VD->VarDeclBits.TSCSpec = Record.readInt();
1461 VD->VarDeclBits.InitStyle = Record.readInt();
1462 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1463 if (!isa<ParmVarDecl>(VD)) {
1464 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1465 Record.readInt();
1466 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1467 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1468 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1469 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1470 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1471 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1472 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1473 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1474 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1475 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1476 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1477 }
1478 auto VarLinkage = Linkage(Record.readInt());
1479 VD->setCachedLinkage(VarLinkage);
1480
1481 // Reconstruct the one piece of the IdentifierNamespace that we need.
1482 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1483 VD->getLexicalDeclContext()->isFunctionOrMethod())
1484 VD->setLocalExternDecl();
1485
1486 if (uint64_t Val = Record.readInt()) {
1487 VD->setInit(Record.readExpr());
1488 if (Val != 1) {
1489 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1490 Eval->HasConstantInitialization = (Val & 2) != 0;
1491 Eval->HasConstantDestruction = (Val & 4) != 0;
1492 }
1493 }
1494
1495 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1496 Expr *CopyExpr = Record.readExpr();
1497 if (CopyExpr)
1498 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1499 }
1500
1501 if (VD->getStorageDuration() == SD_Static && Record.readInt()) {
1502 Reader.DefinitionSource[VD] =
1503 Loc.F->Kind == ModuleKind::MK_MainFile ||
1504 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1505 }
1506
1507 enum VarKind {
1508 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1509 };
1510 switch ((VarKind)Record.readInt()) {
1511 case VarNotTemplate:
1512 // Only true variables (not parameters or implicit parameters) can be
1513 // merged; the other kinds are not really redeclarable at all.
1514 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1515 !isa<VarTemplateSpecializationDecl>(VD))
1516 mergeRedeclarable(VD, Redecl);
1517 break;
1518 case VarTemplate:
1519 // Merged when we merge the template.
1520 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1521 break;
1522 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1523 auto *Tmpl = readDeclAs<VarDecl>();
1524 auto TSK = (TemplateSpecializationKind)Record.readInt();
1525 SourceLocation POI = readSourceLocation();
1526 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1527 mergeRedeclarable(VD, Redecl);
1528 break;
1529 }
1530 }
1531
1532 return Redecl;
1533}
1534
1535void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1536 VisitVarDecl(PD);
1537}
1538
1539void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1540 VisitVarDecl(PD);
1541 unsigned isObjCMethodParam = Record.readInt();
1542 unsigned scopeDepth = Record.readInt();
1543 unsigned scopeIndex = Record.readInt();
1544 unsigned declQualifier = Record.readInt();
1545 if (isObjCMethodParam) {
1546 assert(scopeDepth == 0)(static_cast <bool> (scopeDepth == 0) ? void (0) : __assert_fail
("scopeDepth == 0", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 1546, __extension__ __PRETTY_FUNCTION__))
;
1547 PD->setObjCMethodScopeInfo(scopeIndex);
1548 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1549 } else {
1550 PD->setScopeInfo(scopeDepth, scopeIndex);
1551 }
1552 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1553 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1554 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1555 PD->setUninstantiatedDefaultArg(Record.readExpr());
1556
1557 // FIXME: If this is a redeclaration of a function from another module, handle
1558 // inheritance of default arguments.
1559}
1560
1561void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1562 VisitVarDecl(DD);
1563 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1564 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1565 BDs[I] = readDeclAs<BindingDecl>();
1566 BDs[I]->setDecomposedDecl(DD);
1567 }
1568}
1569
1570void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1571 VisitValueDecl(BD);
1572 BD->Binding = Record.readExpr();
1573}
1574
1575void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1576 VisitDecl(AD);
1577 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1578 AD->setRParenLoc(readSourceLocation());
1579}
1580
1581void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1582 VisitDecl(BD);
1583 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1584 BD->setSignatureAsWritten(readTypeSourceInfo());
1585 unsigned NumParams = Record.readInt();
1586 SmallVector<ParmVarDecl *, 16> Params;
1587 Params.reserve(NumParams);
1588 for (unsigned I = 0; I != NumParams; ++I)
1589 Params.push_back(readDeclAs<ParmVarDecl>());
1590 BD->setParams(Params);
1591
1592 BD->setIsVariadic(Record.readInt());
1593 BD->setBlockMissingReturnType(Record.readInt());
1594 BD->setIsConversionFromLambda(Record.readInt());
1595 BD->setDoesNotEscape(Record.readInt());
1596 BD->setCanAvoidCopyToHeap(Record.readInt());
1597
1598 bool capturesCXXThis = Record.readInt();
1599 unsigned numCaptures = Record.readInt();
1600 SmallVector<BlockDecl::Capture, 16> captures;
1601 captures.reserve(numCaptures);
1602 for (unsigned i = 0; i != numCaptures; ++i) {
1603 auto *decl = readDeclAs<VarDecl>();
1604 unsigned flags = Record.readInt();
1605 bool byRef = (flags & 1);
1606 bool nested = (flags & 2);
1607 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1608
1609 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1610 }
1611 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1612}
1613
1614void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1615 VisitDecl(CD);
1616 unsigned ContextParamPos = Record.readInt();
1617 CD->setNothrow(Record.readInt() != 0);
1618 // Body is set by VisitCapturedStmt.
1619 for (unsigned I = 0; I < CD->NumParams; ++I) {
1620 if (I != ContextParamPos)
1621 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1622 else
1623 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1624 }
1625}
1626
1627void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1628 VisitDecl(D);
1629 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1630 D->setExternLoc(readSourceLocation());
1631 D->setRBraceLoc(readSourceLocation());
1632}
1633
1634void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1635 VisitDecl(D);
1636 D->RBraceLoc = readSourceLocation();
1637}
1638
1639void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1640 VisitNamedDecl(D);
1641 D->setLocStart(readSourceLocation());
1642}
1643
1644void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1645 RedeclarableResult Redecl = VisitRedeclarable(D);
1646 VisitNamedDecl(D);
1647 D->setInline(Record.readInt());
1648 D->LocStart = readSourceLocation();
1649 D->RBraceLoc = readSourceLocation();
1650
1651 // Defer loading the anonymous namespace until we've finished merging
1652 // this namespace; loading it might load a later declaration of the
1653 // same namespace, and we have an invariant that older declarations
1654 // get merged before newer ones try to merge.
1655 GlobalDeclID AnonNamespace = 0;
1656 if (Redecl.getFirstID() == ThisDeclID) {
1657 AnonNamespace = readDeclID();
1658 } else {
1659 // Link this namespace back to the first declaration, which has already
1660 // been deserialized.
1661 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1662 }
1663
1664 mergeRedeclarable(D, Redecl);
1665
1666 if (AnonNamespace) {
1667 // Each module has its own anonymous namespace, which is disjoint from
1668 // any other module's anonymous namespaces, so don't attach the anonymous
1669 // namespace at all.
1670 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1671 if (!Record.isModule())
1672 D->setAnonymousNamespace(Anon);
1673 }
1674}
1675
1676void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1677 RedeclarableResult Redecl = VisitRedeclarable(D);
1678 VisitNamedDecl(D);
1679 D->NamespaceLoc = readSourceLocation();
1680 D->IdentLoc = readSourceLocation();
1681 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1682 D->Namespace = readDeclAs<NamedDecl>();
1683 mergeRedeclarable(D, Redecl);
1684}
1685
1686void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1687 VisitNamedDecl(D);
1688 D->setUsingLoc(readSourceLocation());
1689 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1690 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1691 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1692 D->setTypename(Record.readInt());
1693 if (auto *Pattern = readDeclAs<NamedDecl>())
1694 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1695 mergeMergeable(D);
1696}
1697
1698void ASTDeclReader::VisitUsingEnumDecl(UsingEnumDecl *D) {
1699 VisitNamedDecl(D);
1700 D->setUsingLoc(readSourceLocation());
1701 D->setEnumLoc(readSourceLocation());
1702 D->Enum = readDeclAs<EnumDecl>();
1703 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1704 if (auto *Pattern = readDeclAs<UsingEnumDecl>())
1705 Reader.getContext().setInstantiatedFromUsingEnumDecl(D, Pattern);
1706 mergeMergeable(D);
1707}
1708
1709void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1710 VisitNamedDecl(D);
1711 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1712 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1713 for (unsigned I = 0; I != D->NumExpansions; ++I)
1714 Expansions[I] = readDeclAs<NamedDecl>();
1715 mergeMergeable(D);
1716}
1717
1718void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1719 RedeclarableResult Redecl = VisitRedeclarable(D);
1720 VisitNamedDecl(D);
1721 D->Underlying = readDeclAs<NamedDecl>();
1722 D->IdentifierNamespace = Record.readInt();
1723 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1724 auto *Pattern = readDeclAs<UsingShadowDecl>();
1725 if (Pattern)
1726 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1727 mergeRedeclarable(D, Redecl);
1728}
1729
1730void ASTDeclReader::VisitConstructorUsingShadowDecl(
1731 ConstructorUsingShadowDecl *D) {
1732 VisitUsingShadowDecl(D);
1733 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1734 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1735 D->IsVirtual = Record.readInt();
1736}
1737
1738void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1739 VisitNamedDecl(D);
1740 D->UsingLoc = readSourceLocation();
1741 D->NamespaceLoc = readSourceLocation();
1742 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1743 D->NominatedNamespace = readDeclAs<NamedDecl>();
1744 D->CommonAncestor = readDeclAs<DeclContext>();
1745}
1746
1747void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1748 VisitValueDecl(D);
1749 D->setUsingLoc(readSourceLocation());
1750 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1751 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1752 D->EllipsisLoc = readSourceLocation();
1753 mergeMergeable(D);
1754}
1755
1756void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1757 UnresolvedUsingTypenameDecl *D) {
1758 VisitTypeDecl(D);
1759 D->TypenameLocation = readSourceLocation();
1760 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1761 D->EllipsisLoc = readSourceLocation();
1762 mergeMergeable(D);
1763}
1764
1765void ASTDeclReader::VisitUnresolvedUsingIfExistsDecl(
1766 UnresolvedUsingIfExistsDecl *D) {
1767 VisitNamedDecl(D);
1768}
1769
1770void ASTDeclReader::ReadCXXDefinitionData(
1771 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1772 #define FIELD(Name, Width, Merge) \
1773 Data.Name = Record.readInt();
1774 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1775
1776 // Note: the caller has deserialized the IsLambda bit already.
1777 Data.ODRHash = Record.readInt();
1778 Data.HasODRHash = true;
1779
1780 if (Record.readInt()) {
1781 Reader.DefinitionSource[D] =
1782 Loc.F->Kind == ModuleKind::MK_MainFile ||
1783 Reader.getContext().getLangOpts().BuildingPCHWithObjectFile;
1784 }
1785
1786 Data.NumBases = Record.readInt();
1787 if (Data.NumBases)
1788 Data.Bases = ReadGlobalOffset();
1789 Data.NumVBases = Record.readInt();
1790 if (Data.NumVBases)
1791 Data.VBases = ReadGlobalOffset();
1792
1793 Record.readUnresolvedSet(Data.Conversions);
1794 Data.ComputedVisibleConversions = Record.readInt();
1795 if (Data.ComputedVisibleConversions)
1796 Record.readUnresolvedSet(Data.VisibleConversions);
1797 assert(Data.Definition && "Data.Definition should be already set!")(static_cast <bool> (Data.Definition && "Data.Definition should be already set!"
) ? void (0) : __assert_fail ("Data.Definition && \"Data.Definition should be already set!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1797, __extension__
__PRETTY_FUNCTION__))
;
1798 Data.FirstFriend = readDeclID();
1799
1800 if (Data.IsLambda) {
1801 using Capture = LambdaCapture;
1802
1803 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1804 Lambda.Dependent = Record.readInt();
1805 Lambda.IsGenericLambda = Record.readInt();
1806 Lambda.CaptureDefault = Record.readInt();
1807 Lambda.NumCaptures = Record.readInt();
1808 Lambda.NumExplicitCaptures = Record.readInt();
1809 Lambda.HasKnownInternalLinkage = Record.readInt();
1810 Lambda.ManglingNumber = Record.readInt();
1811 D->setDeviceLambdaManglingNumber(Record.readInt());
1812 Lambda.ContextDecl = readDeclID();
1813 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1814 sizeof(Capture) * Lambda.NumCaptures);
1815 Capture *ToCapture = Lambda.Captures;
1816 Lambda.MethodTyInfo = readTypeSourceInfo();
1817 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1818 SourceLocation Loc = readSourceLocation();
1819 bool IsImplicit = Record.readInt();
1820 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1821 switch (Kind) {
1822 case LCK_StarThis:
1823 case LCK_This:
1824 case LCK_VLAType:
1825 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1826 break;
1827 case LCK_ByCopy:
1828 case LCK_ByRef:
1829 auto *Var = readDeclAs<VarDecl>();
1830 SourceLocation EllipsisLoc = readSourceLocation();
1831 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1832 break;
1833 }
1834 }
1835 }
1836}
1837
1838void ASTDeclReader::MergeDefinitionData(
1839 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1840 assert(D->DefinitionData &&(static_cast <bool> (D->DefinitionData && "merging class definition into non-definition"
) ? void (0) : __assert_fail ("D->DefinitionData && \"merging class definition into non-definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1841, __extension__
__PRETTY_FUNCTION__))
1841 "merging class definition into non-definition")(static_cast <bool> (D->DefinitionData && "merging class definition into non-definition"
) ? void (0) : __assert_fail ("D->DefinitionData && \"merging class definition into non-definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1841, __extension__
__PRETTY_FUNCTION__))
;
1842 auto &DD = *D->DefinitionData;
1843
1844 if (DD.Definition != MergeDD.Definition) {
1845 // Track that we merged the definitions.
1846 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1847 DD.Definition));
1848 Reader.PendingDefinitions.erase(MergeDD.Definition);
1849 MergeDD.Definition->setCompleteDefinition(false);
1850 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1851 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&(static_cast <bool> (Reader.Lookups.find(MergeDD.Definition
) == Reader.Lookups.end() && "already loaded pending lookups for merged definition"
) ? void (0) : __assert_fail ("Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() && \"already loaded pending lookups for merged definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1852, __extension__
__PRETTY_FUNCTION__))
1852 "already loaded pending lookups for merged definition")(static_cast <bool> (Reader.Lookups.find(MergeDD.Definition
) == Reader.Lookups.end() && "already loaded pending lookups for merged definition"
) ? void (0) : __assert_fail ("Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() && \"already loaded pending lookups for merged definition\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1852, __extension__
__PRETTY_FUNCTION__))
;
1853 }
1854
1855 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1856 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1857 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1858 // We faked up this definition data because we found a class for which we'd
1859 // not yet loaded the definition. Replace it with the real thing now.
1860 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?")(static_cast <bool> (!DD.IsLambda && !MergeDD.IsLambda
&& "faked up lambda definition?") ? void (0) : __assert_fail
("!DD.IsLambda && !MergeDD.IsLambda && \"faked up lambda definition?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 1860, __extension__
__PRETTY_FUNCTION__))
;
1861 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1862
1863 // Don't change which declaration is the definition; that is required
1864 // to be invariant once we select it.
1865 auto *Def = DD.Definition;
1866 DD = std::move(MergeDD);
1867 DD.Definition = Def;
1868 return;
1869 }
1870
1871 bool DetectedOdrViolation = false;
1872
1873 #define FIELD(Name, Width, Merge) Merge(Name)
1874 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1875 #define NO_MERGE(Field) \
1876 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1877 MERGE_OR(Field)
1878 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1879 NO_MERGE(IsLambda)
1880 #undef NO_MERGE
1881 #undef MERGE_OR
1882
1883 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1884 DetectedOdrViolation = true;
1885 // FIXME: Issue a diagnostic if the base classes don't match when we come
1886 // to lazily load them.
1887
1888 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1889 // match when we come to lazily load them.
1890 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1891 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1892 DD.ComputedVisibleConversions = true;
1893 }
1894
1895 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1896 // lazily load it.
1897
1898 if (DD.IsLambda) {
1899 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1900 // when they occur within the body of a function template specialization).
1901 }
1902
1903 if (D->getODRHash() != MergeDD.ODRHash) {
1904 DetectedOdrViolation = true;
1905 }
1906
1907 if (DetectedOdrViolation)
1908 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1909 {MergeDD.Definition, &MergeDD});
1910}
1911
1912void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1913 struct CXXRecordDecl::DefinitionData *DD;
1914 ASTContext &C = Reader.getContext();
1915
1916 // Determine whether this is a lambda closure type, so that we can
1917 // allocate the appropriate DefinitionData structure.
1918 bool IsLambda = Record.readInt();
1919 if (IsLambda)
1920 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1921 LCD_None);
1922 else
1923 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1924
1925 CXXRecordDecl *Canon = D->getCanonicalDecl();
1926 // Set decl definition data before reading it, so that during deserialization
1927 // when we read CXXRecordDecl, it already has definition data and we don't
1928 // set fake one.
1929 if (!Canon->DefinitionData)
1930 Canon->DefinitionData = DD;
1931 D->DefinitionData = Canon->DefinitionData;
1932 ReadCXXDefinitionData(*DD, D);
1933
1934 // We might already have a different definition for this record. This can
1935 // happen either because we're reading an update record, or because we've
1936 // already done some merging. Either way, just merge into it.
1937 if (Canon->DefinitionData != DD) {
1938 MergeDefinitionData(Canon, std::move(*DD));
1939 return;
1940 }
1941
1942 // Mark this declaration as being a definition.
1943 D->setCompleteDefinition(true);
1944
1945 // If this is not the first declaration or is an update record, we can have
1946 // other redeclarations already. Make a note that we need to propagate the
1947 // DefinitionData pointer onto them.
1948 if (Update || Canon != D)
1949 Reader.PendingDefinitions.insert(D);
1950}
1951
1952ASTDeclReader::RedeclarableResult
1953ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1954 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1955
1956 ASTContext &C = Reader.getContext();
1957
1958 enum CXXRecKind {
1959 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1960 };
1961 switch ((CXXRecKind)Record.readInt()) {
1962 case CXXRecNotTemplate:
1963 // Merged when we merge the folding set entry in the primary template.
1964 if (!isa<ClassTemplateSpecializationDecl>(D))
1965 mergeRedeclarable(D, Redecl);
1966 break;
1967 case CXXRecTemplate: {
1968 // Merged when we merge the template.
1969 auto *Template = readDeclAs<ClassTemplateDecl>();
1970 D->TemplateOrInstantiation = Template;
1971 if (!Template->getTemplatedDecl()) {
1972 // We've not actually loaded the ClassTemplateDecl yet, because we're
1973 // currently being loaded as its pattern. Rely on it to set up our
1974 // TypeForDecl (see VisitClassTemplateDecl).
1975 //
1976 // Beware: we do not yet know our canonical declaration, and may still
1977 // get merged once the surrounding class template has got off the ground.
1978 DeferredTypeID = 0;
1979 }
1980 break;
1981 }
1982 case CXXRecMemberSpecialization: {
1983 auto *RD = readDeclAs<CXXRecordDecl>();
1984 auto TSK = (TemplateSpecializationKind)Record.readInt();
1985 SourceLocation POI = readSourceLocation();
1986 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1987 MSI->setPointOfInstantiation(POI);
1988 D->TemplateOrInstantiation = MSI;
1989 mergeRedeclarable(D, Redecl);
1990 break;
1991 }
1992 }
1993
1994 bool WasDefinition = Record.readInt();
1995 if (WasDefinition)
1996 ReadCXXRecordDefinition(D, /*Update*/false);
1997 else
1998 // Propagate DefinitionData pointer from the canonical declaration.
1999 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
2000
2001 // Lazily load the key function to avoid deserializing every method so we can
2002 // compute it.
2003 if (WasDefinition) {
2004 DeclID KeyFn = readDeclID();
2005 if (KeyFn && D->isCompleteDefinition())
2006 // FIXME: This is wrong for the ARM ABI, where some other module may have
2007 // made this function no longer be a key function. We need an update
2008 // record or similar for that case.
2009 C.KeyFunctions[D] = KeyFn;
2010 }
2011
2012 return Redecl;
2013}
2014
2015void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
2016 D->setExplicitSpecifier(Record.readExplicitSpec());
2017 D->Ctor = readDeclAs<CXXConstructorDecl>();
2018 VisitFunctionDecl(D);
2019 D->setIsCopyDeductionCandidate(Record.readInt());
2020}
2021
2022void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
2023 VisitFunctionDecl(D);
2024
2025 unsigned NumOverridenMethods = Record.readInt();
2026 if (D->isCanonicalDecl()) {
2027 while (NumOverridenMethods--) {
2028 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
2029 // MD may be initializing.
2030 if (auto *MD = readDeclAs<CXXMethodDecl>())
2031 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
2032 }
2033 } else {
2034 // We don't care about which declarations this used to override; we get
2035 // the relevant information from the canonical declaration.
2036 Record.skipInts(NumOverridenMethods);
2037 }
2038}
2039
2040void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2041 // We need the inherited constructor information to merge the declaration,
2042 // so we have to read it before we call VisitCXXMethodDecl.
2043 D->setExplicitSpecifier(Record.readExplicitSpec());
2044 if (D->isInheritingConstructor()) {
2045 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
2046 auto *Ctor = readDeclAs<CXXConstructorDecl>();
2047 *D->getTrailingObjects<InheritedConstructor>() =
2048 InheritedConstructor(Shadow, Ctor);
2049 }
2050
2051 VisitCXXMethodDecl(D);
2052}
2053
2054void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2055 VisitCXXMethodDecl(D);
2056
2057 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
2058 CXXDestructorDecl *Canon = D->getCanonicalDecl();
2059 auto *ThisArg = Record.readExpr();
2060 // FIXME: Check consistency if we have an old and new operator delete.
2061 if (!Canon->OperatorDelete) {
2062 Canon->OperatorDelete = OperatorDelete;
2063 Canon->OperatorDeleteThisArg = ThisArg;
2064 }
2065 }
2066}
2067
2068void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
2069 D->setExplicitSpecifier(Record.readExplicitSpec());
2070 VisitCXXMethodDecl(D);
2071}
2072
2073void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
2074 VisitDecl(D);
2075 D->ImportedModule = readModule();
2076 D->setImportComplete(Record.readInt());
2077 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
2078 for (unsigned I = 0, N = Record.back(); I != N; ++I)
2079 StoredLocs[I] = readSourceLocation();
2080 Record.skipInts(1); // The number of stored source locations.
2081}
2082
2083void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
2084 VisitDecl(D);
2085 D->setColonLoc(readSourceLocation());
2086}
2087
2088void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
2089 VisitDecl(D);
2090 if (Record.readInt()) // hasFriendDecl
2091 D->Friend = readDeclAs<NamedDecl>();
2092 else
2093 D->Friend = readTypeSourceInfo();
2094 for (unsigned i = 0; i != D->NumTPLists; ++i)
2095 D->getTrailingObjects<TemplateParameterList *>()[i] =
2096 Record.readTemplateParameterList();
2097 D->NextFriend = readDeclID();
2098 D->UnsupportedFriend = (Record.readInt() != 0);
2099 D->FriendLoc = readSourceLocation();
2100}
2101
2102void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2103 VisitDecl(D);
2104 unsigned NumParams = Record.readInt();
2105 D->NumParams = NumParams;
2106 D->Params = new TemplateParameterList*[NumParams];
2107 for (unsigned i = 0; i != NumParams; ++i)
2108 D->Params[i] = Record.readTemplateParameterList();
2109 if (Record.readInt()) // HasFriendDecl
2110 D->Friend = readDeclAs<NamedDecl>();
2111 else
2112 D->Friend = readTypeSourceInfo();
2113 D->FriendLoc = readSourceLocation();
2114}
2115
2116DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2117 VisitNamedDecl(D);
2118
2119 DeclID PatternID = readDeclID();
2120 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2121 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2122 D->init(TemplatedDecl, TemplateParams);
2123
2124 return PatternID;
2125}
2126
2127void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2128 VisitTemplateDecl(D);
2129 D->ConstraintExpr = Record.readExpr();
2130 mergeMergeable(D);
2131}
2132
2133void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2134}
2135
2136ASTDeclReader::RedeclarableResult
2137ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2138 RedeclarableResult Redecl = VisitRedeclarable(D);
2139
2140 // Make sure we've allocated the Common pointer first. We do this before
2141 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2142 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2143 if (!CanonD->Common) {
2144 CanonD->Common = CanonD->newCommon(Reader.getContext());
2145 Reader.PendingDefinitions.insert(CanonD);
2146 }
2147 D->Common = CanonD->Common;
2148
2149 // If this is the first declaration of the template, fill in the information
2150 // for the 'common' pointer.
2151 if (ThisDeclID == Redecl.getFirstID()) {
2152 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2153 assert(RTD->getKind() == D->getKind() &&(static_cast <bool> (RTD->getKind() == D->getKind
() && "InstantiatedFromMemberTemplate kind mismatch")
? void (0) : __assert_fail ("RTD->getKind() == D->getKind() && \"InstantiatedFromMemberTemplate kind mismatch\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2154, __extension__
__PRETTY_FUNCTION__))
2154 "InstantiatedFromMemberTemplate kind mismatch")(static_cast <bool> (RTD->getKind() == D->getKind
() && "InstantiatedFromMemberTemplate kind mismatch")
? void (0) : __assert_fail ("RTD->getKind() == D->getKind() && \"InstantiatedFromMemberTemplate kind mismatch\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2154, __extension__
__PRETTY_FUNCTION__))
;
2155 D->setInstantiatedFromMemberTemplate(RTD);
2156 if (Record.readInt())
2157 D->setMemberSpecialization();
2158 }
2159 }
2160
2161 DeclID PatternID = VisitTemplateDecl(D);
2162 D->IdentifierNamespace = Record.readInt();
2163
2164 mergeRedeclarable(D, Redecl, PatternID);
2165
2166 // If we merged the template with a prior declaration chain, merge the common
2167 // pointer.
2168 // FIXME: Actually merge here, don't just overwrite.
2169 D->Common = D->getCanonicalDecl()->Common;
2170
2171 return Redecl;
2172}
2173
2174void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2175 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2176
2177 if (ThisDeclID == Redecl.getFirstID()) {
2178 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2179 // the specializations.
2180 SmallVector<serialization::DeclID, 32> SpecIDs;
2181 readDeclIDList(SpecIDs);
2182 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2183 }
2184
2185 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2186 // We were loaded before our templated declaration was. We've not set up
2187 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2188 // it now.
2189 Reader.getContext().getInjectedClassNameType(
2190 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2191 }
2192}
2193
2194void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2195 llvm_unreachable("BuiltinTemplates are not serialized")::llvm::llvm_unreachable_internal("BuiltinTemplates are not serialized"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2195)
;
2196}
2197
2198/// TODO: Unify with ClassTemplateDecl version?
2199/// May require unifying ClassTemplateDecl and
2200/// VarTemplateDecl beyond TemplateDecl...
2201void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2202 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2203
2204 if (ThisDeclID == Redecl.getFirstID()) {
2205 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2206 // the specializations.
2207 SmallVector<serialization::DeclID, 32> SpecIDs;
2208 readDeclIDList(SpecIDs);
2209 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2210 }
2211}
2212
2213ASTDeclReader::RedeclarableResult
2214ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2215 ClassTemplateSpecializationDecl *D) {
2216 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2217
2218 ASTContext &C = Reader.getContext();
2219 if (Decl *InstD = readDecl()) {
2220 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2221 D->SpecializedTemplate = CTD;
2222 } else {
2223 SmallVector<TemplateArgument, 8> TemplArgs;
2224 Record.readTemplateArgumentList(TemplArgs);
2225 TemplateArgumentList *ArgList
2226 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2227 auto *PS =
2228 new (C) ClassTemplateSpecializationDecl::
2229 SpecializedPartialSpecialization();
2230 PS->PartialSpecialization
2231 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2232 PS->TemplateArgs = ArgList;
2233 D->SpecializedTemplate = PS;
2234 }
2235 }
2236
2237 SmallVector<TemplateArgument, 8> TemplArgs;
2238 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2239 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2240 D->PointOfInstantiation = readSourceLocation();
2241 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2242
2243 bool writtenAsCanonicalDecl = Record.readInt();
2244 if (writtenAsCanonicalDecl) {
2245 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2246 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2247 // Set this as, or find, the canonical declaration for this specialization
2248 ClassTemplateSpecializationDecl *CanonSpec;
2249 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2250 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2251 .GetOrInsertNode(Partial);
2252 } else {
2253 CanonSpec =
2254 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2255 }
2256 // If there was already a canonical specialization, merge into it.
2257 if (CanonSpec != D) {
2258 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2259
2260 // This declaration might be a definition. Merge with any existing
2261 // definition.
2262 if (auto *DDD = D->DefinitionData) {
2263 if (CanonSpec->DefinitionData)
2264 MergeDefinitionData(CanonSpec, std::move(*DDD));
2265 else
2266 CanonSpec->DefinitionData = D->DefinitionData;
2267 }
2268 D->DefinitionData = CanonSpec->DefinitionData;
2269 }
2270 }
2271 }
2272
2273 // Explicit info.
2274 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2275 auto *ExplicitInfo =
2276 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2277 ExplicitInfo->TypeAsWritten = TyInfo;
2278 ExplicitInfo->ExternLoc = readSourceLocation();
2279 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2280 D->ExplicitInfo = ExplicitInfo;
2281 }
2282
2283 return Redecl;
2284}
2285
2286void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2287 ClassTemplatePartialSpecializationDecl *D) {
2288 // We need to read the template params first because redeclarable is going to
2289 // need them for profiling
2290 TemplateParameterList *Params = Record.readTemplateParameterList();
2291 D->TemplateParams = Params;
2292 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2293
2294 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2295
2296 // These are read/set from/to the first declaration.
2297 if (ThisDeclID == Redecl.getFirstID()) {
2298 D->InstantiatedFromMember.setPointer(
2299 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2300 D->InstantiatedFromMember.setInt(Record.readInt());
2301 }
2302}
2303
2304void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2305 ClassScopeFunctionSpecializationDecl *D) {
2306 VisitDecl(D);
2307 D->Specialization = readDeclAs<CXXMethodDecl>();
2308 if (Record.readInt())
2309 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2310}
2311
2312void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2313 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2314
2315 if (ThisDeclID == Redecl.getFirstID()) {
2316 // This FunctionTemplateDecl owns a CommonPtr; read it.
2317 SmallVector<serialization::DeclID, 32> SpecIDs;
2318 readDeclIDList(SpecIDs);
2319 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2320 }
2321}
2322
2323/// TODO: Unify with ClassTemplateSpecializationDecl version?
2324/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2325/// VarTemplate(Partial)SpecializationDecl with a new data
2326/// structure Template(Partial)SpecializationDecl, and
2327/// using Template(Partial)SpecializationDecl as input type.
2328ASTDeclReader::RedeclarableResult
2329ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2330 VarTemplateSpecializationDecl *D) {
2331 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2332
2333 ASTContext &C = Reader.getContext();
2334 if (Decl *InstD = readDecl()) {
2335 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2336 D->SpecializedTemplate = VTD;
2337 } else {
2338 SmallVector<TemplateArgument, 8> TemplArgs;
2339 Record.readTemplateArgumentList(TemplArgs);
2340 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2341 C, TemplArgs);
2342 auto *PS =
2343 new (C)
2344 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2345 PS->PartialSpecialization =
2346 cast<VarTemplatePartialSpecializationDecl>(InstD);
2347 PS->TemplateArgs = ArgList;
2348 D->SpecializedTemplate = PS;
2349 }
2350 }
2351
2352 // Explicit info.
2353 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2354 auto *ExplicitInfo =
2355 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2356 ExplicitInfo->TypeAsWritten = TyInfo;
2357 ExplicitInfo->ExternLoc = readSourceLocation();
2358 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2359 D->ExplicitInfo = ExplicitInfo;
2360 }
2361
2362 SmallVector<TemplateArgument, 8> TemplArgs;
2363 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2364 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2365 D->PointOfInstantiation = readSourceLocation();
2366 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2367 D->IsCompleteDefinition = Record.readInt();
2368
2369 bool writtenAsCanonicalDecl = Record.readInt();
2370 if (writtenAsCanonicalDecl) {
2371 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2372 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2373 // FIXME: If it's already present, merge it.
2374 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2375 CanonPattern->getCommonPtr()->PartialSpecializations
2376 .GetOrInsertNode(Partial);
2377 } else {
2378 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2379 }
2380 }
2381 }
2382
2383 return Redecl;
2384}
2385
2386/// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2387/// May require unifying ClassTemplate(Partial)SpecializationDecl and
2388/// VarTemplate(Partial)SpecializationDecl with a new data
2389/// structure Template(Partial)SpecializationDecl, and
2390/// using Template(Partial)SpecializationDecl as input type.
2391void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2392 VarTemplatePartialSpecializationDecl *D) {
2393 TemplateParameterList *Params = Record.readTemplateParameterList();
2394 D->TemplateParams = Params;
2395 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2396
2397 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2398
2399 // These are read/set from/to the first declaration.
2400 if (ThisDeclID == Redecl.getFirstID()) {
2401 D->InstantiatedFromMember.setPointer(
2402 readDeclAs<VarTemplatePartialSpecializationDecl>());
2403 D->InstantiatedFromMember.setInt(Record.readInt());
2404 }
2405}
2406
2407void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2408 VisitTypeDecl(D);
2409
2410 D->setDeclaredWithTypename(Record.readInt());
2411
2412 if (Record.readBool()) {
2413 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2414 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2415 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2416 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2417 if (Record.readBool())
2418 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2419 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2420 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2421 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2422 if ((D->ExpandedParameterPack = Record.readInt()))
2423 D->NumExpanded = Record.readInt();
2424 }
2425
2426 if (Record.readInt())
2427 D->setDefaultArgument(readTypeSourceInfo());
2428}
2429
2430void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2431 VisitDeclaratorDecl(D);
2432 // TemplateParmPosition.
2433 D->setDepth(Record.readInt());
2434 D->setPosition(Record.readInt());
2435 if (D->hasPlaceholderTypeConstraint())
2436 D->setPlaceholderTypeConstraint(Record.readExpr());
2437 if (D->isExpandedParameterPack()) {
2438 auto TypesAndInfos =
2439 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2440 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2441 new (&TypesAndInfos[I].first) QualType(Record.readType());
2442 TypesAndInfos[I].second = readTypeSourceInfo();
2443 }
2444 } else {
2445 // Rest of NonTypeTemplateParmDecl.
2446 D->ParameterPack = Record.readInt();
2447 if (Record.readInt())
2448 D->setDefaultArgument(Record.readExpr());
2449 }
2450}
2451
2452void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2453 VisitTemplateDecl(D);
2454 // TemplateParmPosition.
2455 D->setDepth(Record.readInt());
2456 D->setPosition(Record.readInt());
2457 if (D->isExpandedParameterPack()) {
2458 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2459 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2460 I != N; ++I)
2461 Data[I] = Record.readTemplateParameterList();
2462 } else {
2463 // Rest of TemplateTemplateParmDecl.
2464 D->ParameterPack = Record.readInt();
2465 if (Record.readInt())
2466 D->setDefaultArgument(Reader.getContext(),
2467 Record.readTemplateArgumentLoc());
2468 }
2469}
2470
2471void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2472 VisitRedeclarableTemplateDecl(D);
2473}
2474
2475void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2476 VisitDecl(D);
2477 D->AssertExprAndFailed.setPointer(Record.readExpr());
2478 D->AssertExprAndFailed.setInt(Record.readInt());
2479 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2480 D->RParenLoc = readSourceLocation();
2481}
2482
2483void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2484 VisitDecl(D);
2485}
2486
2487void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2488 LifetimeExtendedTemporaryDecl *D) {
2489 VisitDecl(D);
2490 D->ExtendingDecl = readDeclAs<ValueDecl>();
2491 D->ExprWithTemporary = Record.readStmt();
2492 if (Record.readInt()) {
2493 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2494 D->getASTContext().addDestruction(D->Value);
2495 }
2496 D->ManglingNumber = Record.readInt();
2497 mergeMergeable(D);
2498}
2499
2500std::pair<uint64_t, uint64_t>
2501ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2502 uint64_t LexicalOffset = ReadLocalOffset();
2503 uint64_t VisibleOffset = ReadLocalOffset();
2504 return std::make_pair(LexicalOffset, VisibleOffset);
2505}
2506
2507template <typename T>
2508ASTDeclReader::RedeclarableResult
2509ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2510 DeclID FirstDeclID = readDeclID();
2511 Decl *MergeWith = nullptr;
2512
2513 bool IsKeyDecl = ThisDeclID == FirstDeclID;
1
Assuming 'FirstDeclID' is not equal to field 'ThisDeclID'
2514 bool IsFirstLocalDecl = false;
2515
2516 uint64_t RedeclOffset = 0;
2517
2518 // 0 indicates that this declaration was the only declaration of its entity,
2519 // and is used for space optimization.
2520 if (FirstDeclID == 0) {
2
Assuming 'FirstDeclID' is equal to 0
3
Taking true branch
2521 FirstDeclID = ThisDeclID;
2522 IsKeyDecl = true;
2523 IsFirstLocalDecl = true;
2524 } else if (unsigned N = Record.readInt()) {
2525 // This declaration was the first local declaration, but may have imported
2526 // other declarations.
2527 IsKeyDecl = N == 1;
2528 IsFirstLocalDecl = true;
2529
2530 // We have some declarations that must be before us in our redeclaration
2531 // chain. Read them now, and remember that we ought to merge with one of
2532 // them.
2533 // FIXME: Provide a known merge target to the second and subsequent such
2534 // declaration.
2535 for (unsigned I = 0; I != N - 1; ++I)
2536 MergeWith = readDecl();
2537
2538 RedeclOffset = ReadLocalOffset();
2539 } else {
2540 // This declaration was not the first local declaration. Read the first
2541 // local declaration now, to trigger the import of other redeclarations.
2542 (void)readDecl();
2543 }
2544
2545 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
4
Assuming null pointer is passed into cast
5
'FirstDecl' initialized to a null pointer value
2546 if (FirstDecl != D) {
6
Assuming 'FirstDecl' is not equal to 'D'
7
Taking true branch
2547 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2548 // We temporarily set the first (canonical) declaration as the previous one
2549 // which is the one that matters and mark the real previous DeclID to be
2550 // loaded & attached later on.
2551 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2552 D->First = FirstDecl->getCanonicalDecl();
8
Called C++ object pointer is null
2553 }
2554
2555 auto *DAsT = static_cast<T *>(D);
2556
2557 // Note that we need to load local redeclarations of this decl and build a
2558 // decl chain for them. This must happen *after* we perform the preloading
2559 // above; this ensures that the redeclaration chain is built in the correct
2560 // order.
2561 if (IsFirstLocalDecl)
2562 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2563
2564 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2565}
2566
2567/// Attempts to merge the given declaration (D) with another declaration
2568/// of the same entity.
2569template<typename T>
2570void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2571 RedeclarableResult &Redecl,
2572 DeclID TemplatePatternID) {
2573 // If modules are not available, there is no reason to perform this merge.
2574 if (!Reader.getContext().getLangOpts().Modules)
2575 return;
2576
2577 // If we're not the canonical declaration, we don't need to merge.
2578 if (!DBase->isFirstDecl())
2579 return;
2580
2581 auto *D = static_cast<T *>(DBase);
2582
2583 if (auto *Existing = Redecl.getKnownMergeTarget())
2584 // We already know of an existing declaration we should merge with.
2585 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2586 else if (FindExistingResult ExistingRes = findExisting(D))
2587 if (T *Existing = ExistingRes)
2588 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2589}
2590
2591/// "Cast" to type T, asserting if we don't have an implicit conversion.
2592/// We use this to put code in a template that will only be valid for certain
2593/// instantiations.
2594template<typename T> static T assert_cast(T t) { return t; }
2595template<typename T> static T assert_cast(...) {
2596 llvm_unreachable("bad assert_cast")::llvm::llvm_unreachable_internal("bad assert_cast", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 2596)
;
2597}
2598
2599/// Merge together the pattern declarations from two template
2600/// declarations.
2601void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2602 RedeclarableTemplateDecl *Existing,
2603 DeclID DsID, bool IsKeyDecl) {
2604 auto *DPattern = D->getTemplatedDecl();
2605 auto *ExistingPattern = Existing->getTemplatedDecl();
2606 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2607 DPattern->getCanonicalDecl()->getGlobalID(),
2608 IsKeyDecl);
2609
2610 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2611 // Merge with any existing definition.
2612 // FIXME: This is duplicated in several places. Refactor.
2613 auto *ExistingClass =
2614 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2615 if (auto *DDD = DClass->DefinitionData) {
2616 if (ExistingClass->DefinitionData) {
2617 MergeDefinitionData(ExistingClass, std::move(*DDD));
2618 } else {
2619 ExistingClass->DefinitionData = DClass->DefinitionData;
2620 // We may have skipped this before because we thought that DClass
2621 // was the canonical declaration.
2622 Reader.PendingDefinitions.insert(DClass);
2623 }
2624 }
2625 DClass->DefinitionData = ExistingClass->DefinitionData;
2626
2627 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2628 Result);
2629 }
2630 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2631 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2632 Result);
2633 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2634 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2635 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2636 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2637 Result);
2638 llvm_unreachable("merged an unknown kind of redeclarable template")::llvm::llvm_unreachable_internal("merged an unknown kind of redeclarable template"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2638)
;
2639}
2640
2641/// Attempts to merge the given declaration (D) with another declaration
2642/// of the same entity.
2643template<typename T>
2644void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2645 RedeclarableResult &Redecl,
2646 DeclID TemplatePatternID) {
2647 auto *D = static_cast<T *>(DBase);
2648 T *ExistingCanon = Existing->getCanonicalDecl();
2649 T *DCanon = D->getCanonicalDecl();
2650 if (ExistingCanon != DCanon) {
2651 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&(static_cast <bool> (DCanon->getGlobalID() == Redecl
.getFirstID() && "already merged this declaration") ?
void (0) : __assert_fail ("DCanon->getGlobalID() == Redecl.getFirstID() && \"already merged this declaration\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2652, __extension__
__PRETTY_FUNCTION__))
2652 "already merged this declaration")(static_cast <bool> (DCanon->getGlobalID() == Redecl
.getFirstID() && "already merged this declaration") ?
void (0) : __assert_fail ("DCanon->getGlobalID() == Redecl.getFirstID() && \"already merged this declaration\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2652, __extension__
__PRETTY_FUNCTION__))
;
2653
2654 // Have our redeclaration link point back at the canonical declaration
2655 // of the existing declaration, so that this declaration has the
2656 // appropriate canonical declaration.
2657 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2658 D->First = ExistingCanon;
2659 ExistingCanon->Used |= D->Used;
2660 D->Used = false;
2661
2662 // When we merge a namespace, update its pointer to the first namespace.
2663 // We cannot have loaded any redeclarations of this declaration yet, so
2664 // there's nothing else that needs to be updated.
2665 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2666 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2667 assert_cast<NamespaceDecl*>(ExistingCanon));
2668
2669 // When we merge a template, merge its pattern.
2670 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2671 mergeTemplatePattern(
2672 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2673 TemplatePatternID, Redecl.isKeyDecl());
2674
2675 // If this declaration is a key declaration, make a note of that.
2676 if (Redecl.isKeyDecl())
2677 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2678 }
2679}
2680
2681/// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2682/// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2683/// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2684/// that some types are mergeable during deserialization, otherwise name
2685/// lookup fails. This is the case for EnumConstantDecl.
2686static bool allowODRLikeMergeInC(NamedDecl *ND) {
2687 if (!ND)
2688 return false;
2689 // TODO: implement merge for other necessary decls.
2690 if (isa<EnumConstantDecl, FieldDecl, IndirectFieldDecl>(ND))
2691 return true;
2692 return false;
2693}
2694
2695/// Attempts to merge LifetimeExtendedTemporaryDecl with
2696/// identical class definitions from two different modules.
2697void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2698 // If modules are not available, there is no reason to perform this merge.
2699 if (!Reader.getContext().getLangOpts().Modules)
2700 return;
2701
2702 LifetimeExtendedTemporaryDecl *LETDecl = D;
2703
2704 LifetimeExtendedTemporaryDecl *&LookupResult =
2705 Reader.LETemporaryForMerging[std::make_pair(
2706 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2707 if (LookupResult)
2708 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2709 LookupResult->getCanonicalDecl());
2710 else
2711 LookupResult = LETDecl;
2712}
2713
2714/// Attempts to merge the given declaration (D) with another declaration
2715/// of the same entity, for the case where the entity is not actually
2716/// redeclarable. This happens, for instance, when merging the fields of
2717/// identical class definitions from two different modules.
2718template<typename T>
2719void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2720 // If modules are not available, there is no reason to perform this merge.
2721 if (!Reader.getContext().getLangOpts().Modules)
2722 return;
2723
2724 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2725 // Note that C identically-named things in different translation units are
2726 // not redeclarations, but may still have compatible types, where ODR-like
2727 // semantics may apply.
2728 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2729 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2730 return;
2731
2732 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2733 if (T *Existing = ExistingRes)
2734 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2735 Existing->getCanonicalDecl());
2736}
2737
2738void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2739 Record.readOMPChildren(D->Data);
2740 VisitDecl(D);
2741}
2742
2743void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2744 Record.readOMPChildren(D->Data);
2745 VisitDecl(D);
2746}
2747
2748void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2749 Record.readOMPChildren(D->Data);
2750 VisitDecl(D);
2751}
2752
2753void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2754 VisitValueDecl(D);
2755 D->setLocation(readSourceLocation());
2756 Expr *In = Record.readExpr();
2757 Expr *Out = Record.readExpr();
2758 D->setCombinerData(In, Out);
2759 Expr *Combiner = Record.readExpr();
2760 D->setCombiner(Combiner);
2761 Expr *Orig = Record.readExpr();
2762 Expr *Priv = Record.readExpr();
2763 D->setInitializerData(Orig, Priv);
2764 Expr *Init = Record.readExpr();
2765 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2766 D->setInitializer(Init, IK);
2767 D->PrevDeclInScope = readDeclID();
2768}
2769
2770void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2771 Record.readOMPChildren(D->Data);
2772 VisitValueDecl(D);
2773 D->VarName = Record.readDeclarationName();
2774 D->PrevDeclInScope = readDeclID();
2775}
2776
2777void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2778 VisitVarDecl(D);
2779}
2780
2781//===----------------------------------------------------------------------===//
2782// Attribute Reading
2783//===----------------------------------------------------------------------===//
2784
2785namespace {
2786class AttrReader {
2787 ASTRecordReader &Reader;
2788
2789public:
2790 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2791
2792 uint64_t readInt() {
2793 return Reader.readInt();
2794 }
2795
2796 SourceRange readSourceRange() {
2797 return Reader.readSourceRange();
2798 }
2799
2800 SourceLocation readSourceLocation() {
2801 return Reader.readSourceLocation();
2802 }
2803
2804 Expr *readExpr() { return Reader.readExpr(); }
2805
2806 std::string readString() {
2807 return Reader.readString();
2808 }
2809
2810 TypeSourceInfo *readTypeSourceInfo() {
2811 return Reader.readTypeSourceInfo();
2812 }
2813
2814 IdentifierInfo *readIdentifier() {
2815 return Reader.readIdentifier();
2816 }
2817
2818 VersionTuple readVersionTuple() {
2819 return Reader.readVersionTuple();
2820 }
2821
2822 OMPTraitInfo *readOMPTraitInfo() { return Reader.readOMPTraitInfo(); }
2823
2824 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2825 return Reader.GetLocalDeclAs<T>(LocalID);
2826 }
2827};
2828}
2829
2830Attr *ASTRecordReader::readAttr() {
2831 AttrReader Record(*this);
2832 auto V = Record.readInt();
2833 if (!V)
2834 return nullptr;
2835
2836 Attr *New = nullptr;
2837 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2838 // Attr pointer.
2839 auto Kind = static_cast<attr::Kind>(V - 1);
2840 ASTContext &Context = getContext();
2841
2842 IdentifierInfo *AttrName = Record.readIdentifier();
2843 IdentifierInfo *ScopeName = Record.readIdentifier();
2844 SourceRange AttrRange = Record.readSourceRange();
2845 SourceLocation ScopeLoc = Record.readSourceLocation();
2846 unsigned ParsedKind = Record.readInt();
2847 unsigned Syntax = Record.readInt();
2848 unsigned SpellingIndex = Record.readInt();
2849
2850 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2851 AttributeCommonInfo::Kind(ParsedKind),
2852 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2853
2854#include "clang/Serialization/AttrPCHRead.inc"
2855
2856 assert(New && "Unable to decode attribute?")(static_cast <bool> (New && "Unable to decode attribute?"
) ? void (0) : __assert_fail ("New && \"Unable to decode attribute?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2856, __extension__
__PRETTY_FUNCTION__))
;
2857 return New;
2858}
2859
2860/// Reads attributes from the current stream position.
2861void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2862 for (unsigned I = 0, E = readInt(); I != E; ++I)
2863 Attrs.push_back(readAttr());
2864}
2865
2866//===----------------------------------------------------------------------===//
2867// ASTReader Implementation
2868//===----------------------------------------------------------------------===//
2869
2870/// Note that we have loaded the declaration with the given
2871/// Index.
2872///
2873/// This routine notes that this declaration has already been loaded,
2874/// so that future GetDecl calls will return this declaration rather
2875/// than trying to load a new declaration.
2876inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2877 assert(!DeclsLoaded[Index] && "Decl loaded twice?")(static_cast <bool> (!DeclsLoaded[Index] && "Decl loaded twice?"
) ? void (0) : __assert_fail ("!DeclsLoaded[Index] && \"Decl loaded twice?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2877, __extension__
__PRETTY_FUNCTION__))
;
2878 DeclsLoaded[Index] = D;
2879}
2880
2881/// Determine whether the consumer will be interested in seeing
2882/// this declaration (via HandleTopLevelDecl).
2883///
2884/// This routine should return true for anything that might affect
2885/// code generation, e.g., inline function definitions, Objective-C
2886/// declarations with metadata, etc.
2887static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2888 // An ObjCMethodDecl is never considered as "interesting" because its
2889 // implementation container always is.
2890
2891 // An ImportDecl or VarDecl imported from a module map module will get
2892 // emitted when we import the relevant module.
2893 if (isPartOfPerModuleInitializer(D)) {
2894 auto *M = D->getImportedOwningModule();
2895 if (M && M->Kind == Module::ModuleMapModule &&
2896 Ctx.DeclMustBeEmitted(D))
2897 return false;
2898 }
2899
2900 if (isa<FileScopeAsmDecl>(D) ||
2901 isa<ObjCProtocolDecl>(D) ||
2902 isa<ObjCImplDecl>(D) ||
2903 isa<ImportDecl>(D) ||
2904 isa<PragmaCommentDecl>(D) ||
2905 isa<PragmaDetectMismatchDecl>(D))
2906 return true;
2907 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2908 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D) ||
2909 isa<OMPRequiresDecl>(D))
2910 return !D->getDeclContext()->isFunctionOrMethod();
2911 if (const auto *Var = dyn_cast<VarDecl>(D))
2912 return Var->isFileVarDecl() &&
2913 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2914 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2915 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2916 return Func->doesThisDeclarationHaveABody() || HasBody;
2917
2918 if (auto *ES = D->getASTContext().getExternalSource())
2919 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2920 return true;
2921
2922 return false;
2923}
2924
2925/// Get the correct cursor and offset for loading a declaration.
2926ASTReader::RecordLocation
2927ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2928 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2929 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map")(static_cast <bool> (I != GlobalDeclMap.end() &&
"Corrupted global declaration map") ? void (0) : __assert_fail
("I != GlobalDeclMap.end() && \"Corrupted global declaration map\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2929, __extension__
__PRETTY_FUNCTION__))
;
2930 ModuleFile *M = I->second;
2931 const DeclOffset &DOffs =
2932 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2933 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2934 return RecordLocation(M, DOffs.getBitOffset(M->DeclsBlockStartOffset));
2935}
2936
2937ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2938 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2939
2940 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map")(static_cast <bool> (I != GlobalBitOffsetsMap.end() &&
"Corrupted global bit offsets map") ? void (0) : __assert_fail
("I != GlobalBitOffsetsMap.end() && \"Corrupted global bit offsets map\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 2940, __extension__
__PRETTY_FUNCTION__))
;
2941 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2942}
2943
2944uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint64_t LocalOffset) {
2945 return LocalOffset + M.GlobalBitOffset;
2946}
2947
2948static bool isSameTemplateParameterList(const ASTContext &C,
2949 const TemplateParameterList *X,
2950 const TemplateParameterList *Y);
2951static bool isSameEntity(NamedDecl *X, NamedDecl *Y);
2952
2953/// Determine whether two template parameters are similar enough
2954/// that they may be used in declarations of the same template.
2955static bool isSameTemplateParameter(const NamedDecl *X,
2956 const NamedDecl *Y) {
2957 if (X->getKind() != Y->getKind())
2958 return false;
2959
2960 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2961 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2962 if (TX->isParameterPack() != TY->isParameterPack())
2963 return false;
2964 if (TX->hasTypeConstraint() != TY->hasTypeConstraint())
2965 return false;
2966 const TypeConstraint *TXTC = TX->getTypeConstraint();
2967 const TypeConstraint *TYTC = TY->getTypeConstraint();
2968 if (!TXTC != !TYTC)
2969 return false;
2970 if (TXTC && TYTC) {
2971 auto *NCX = TXTC->getNamedConcept();
2972 auto *NCY = TYTC->getNamedConcept();
2973 if (!NCX || !NCY || !isSameEntity(NCX, NCY))
2974 return false;
2975 if (TXTC->hasExplicitTemplateArgs() != TYTC->hasExplicitTemplateArgs())
2976 return false;
2977 if (TXTC->hasExplicitTemplateArgs()) {
2978 const auto *TXTCArgs = TXTC->getTemplateArgsAsWritten();
2979 const auto *TYTCArgs = TYTC->getTemplateArgsAsWritten();
2980 if (TXTCArgs->NumTemplateArgs != TYTCArgs->NumTemplateArgs)
2981 return false;
2982 llvm::FoldingSetNodeID XID, YID;
2983 for (const auto &ArgLoc : TXTCArgs->arguments())
2984 ArgLoc.getArgument().Profile(XID, X->getASTContext());
2985 for (const auto &ArgLoc : TYTCArgs->arguments())
2986 ArgLoc.getArgument().Profile(YID, Y->getASTContext());
2987 if (XID != YID)
2988 return false;
2989 }
2990 }
2991 return true;
2992 }
2993
2994 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2995 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2996 return TX->isParameterPack() == TY->isParameterPack() &&
2997 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2998 }
2999
3000 const auto *TX = cast<TemplateTemplateParmDecl>(X);
3001 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
3002 return TX->isParameterPack() == TY->isParameterPack() &&
3003 isSameTemplateParameterList(TX->getASTContext(),
3004 TX->getTemplateParameters(),
3005 TY->getTemplateParameters());
3006}
3007
3008static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
3009 if (auto *NS = X->getAsNamespace())
3010 return NS;
3011 if (auto *NAS = X->getAsNamespaceAlias())
3012 return NAS->getNamespace();
3013 return nullptr;
3014}
3015
3016static bool isSameQualifier(const NestedNameSpecifier *X,
3017 const NestedNameSpecifier *Y) {
3018 if (auto *NSX = getNamespace(X)) {
3019 auto *NSY = getNamespace(Y);
3020 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
3021 return false;
3022 } else if (X->getKind() != Y->getKind())
3023 return false;
3024
3025 // FIXME: For namespaces and types, we're permitted to check that the entity
3026 // is named via the same tokens. We should probably do so.
3027 switch (X->getKind()) {
3028 case NestedNameSpecifier::Identifier:
3029 if (X->getAsIdentifier() != Y->getAsIdentifier())
3030 return false;
3031 break;
3032 case NestedNameSpecifier::Namespace:
3033 case NestedNameSpecifier::NamespaceAlias:
3034 // We've already checked that we named the same namespace.
3035 break;
3036 case NestedNameSpecifier::TypeSpec:
3037 case NestedNameSpecifier::TypeSpecWithTemplate:
3038 if (X->getAsType()->getCanonicalTypeInternal() !=
3039 Y->getAsType()->getCanonicalTypeInternal())
3040 return false;
3041 break;
3042 case NestedNameSpecifier::Global:
3043 case NestedNameSpecifier::Super:
3044 return true;
3045 }
3046
3047 // Recurse into earlier portion of NNS, if any.
3048 auto *PX = X->getPrefix();
3049 auto *PY = Y->getPrefix();
3050 if (PX && PY)
3051 return isSameQualifier(PX, PY);
3052 return !PX && !PY;
3053}
3054
3055/// Determine whether two template parameter lists are similar enough
3056/// that they may be used in declarations of the same template.
3057static bool isSameTemplateParameterList(const ASTContext &C,
3058 const TemplateParameterList *X,
3059 const TemplateParameterList *Y) {
3060 if (X->size() != Y->size())
3061 return false;
3062
3063 for (unsigned I = 0, N = X->size(); I != N; ++I)
3064 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
3065 return false;
3066
3067 const Expr *XRC = X->getRequiresClause();
3068 const Expr *YRC = Y->getRequiresClause();
3069 if (!XRC != !YRC)
3070 return false;
3071 if (XRC) {
3072 llvm::FoldingSetNodeID XRCID, YRCID;
3073 XRC->Profile(XRCID, C, /*Canonical=*/true);
3074 YRC->Profile(YRCID, C, /*Canonical=*/true);
3075 if (XRCID != YRCID)
3076 return false;
3077 }
3078
3079 return true;
3080}
3081
3082/// Determine whether the attributes we can overload on are identical for A and
3083/// B. Will ignore any overloadable attrs represented in the type of A and B.
3084static bool hasSameOverloadableAttrs(const FunctionDecl *A,
3085 const FunctionDecl *B) {
3086 // Note that pass_object_size attributes are represented in the function's
3087 // ExtParameterInfo, so we don't need to check them here.
3088
3089 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
3090 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
3091 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
3092
3093 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
3094 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
3095 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
3096
3097 // Return false if the number of enable_if attributes is different.
3098 if (!Cand1A || !Cand2A)
3099 return false;
3100
3101 Cand1ID.clear();
3102 Cand2ID.clear();
3103
3104 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
3105 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
3106
3107 // Return false if any of the enable_if expressions of A and B are
3108 // different.
3109 if (Cand1ID != Cand2ID)
3110 return false;
3111 }
3112 return true;
3113}
3114
3115/// Determine whether the two declarations refer to the same entity.
3116static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
3117 if (X == Y)
3118 return true;
3119
3120 if (X->getDeclName() != Y->getDeclName())
3121 return false;
3122
3123 // Must be in the same context.
3124 //
3125 // Note that we can't use DeclContext::Equals here, because the DeclContexts
3126 // could be two different declarations of the same function. (We will fix the
3127 // semantic DC to refer to the primary definition after merging.)
3128 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3129 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3130 return false;
3131
3132 // Two typedefs refer to the same entity if they have the same underlying
3133 // type.
3134 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3135 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3136 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3137 TypedefY->getUnderlyingType());
3138
3139 // Must have the same kind.
3140 if (X->getKind() != Y->getKind())
3141 return false;
3142
3143 // Objective-C classes and protocols with the same name always match.
3144 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3145 return true;
3146
3147 if (isa<ClassTemplateSpecializationDecl>(X)) {
3148 // No need to handle these here: we merge them when adding them to the
3149 // template.
3150 return false;
3151 }
3152
3153 // Compatible tags match.
3154 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3155 const auto *TagY = cast<TagDecl>(Y);
3156 return (TagX->getTagKind() == TagY->getTagKind()) ||
3157 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3158 TagX->getTagKind() == TTK_Interface) &&
3159 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3160 TagY->getTagKind() == TTK_Interface));
3161 }
3162
3163 // Functions with the same type and linkage match.
3164 // FIXME: This needs to cope with merging of prototyped/non-prototyped
3165 // functions, etc.
3166 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3167 const auto *FuncY = cast<FunctionDecl>(Y);
3168 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3169 const auto *CtorY = cast<CXXConstructorDecl>(Y);
3170 if (CtorX->getInheritedConstructor() &&
3171 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3172 CtorY->getInheritedConstructor().getConstructor()))
3173 return false;
3174 }
3175
3176 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3177 return false;
3178
3179 // Multiversioned functions with different feature strings are represented
3180 // as separate declarations.
3181 if (FuncX->isMultiVersion()) {
3182 const auto *TAX = FuncX->getAttr<TargetAttr>();
3183 const auto *TAY = FuncY->getAttr<TargetAttr>();
3184 assert(TAX && TAY && "Multiversion Function without target attribute")(static_cast <bool> (TAX && TAY && "Multiversion Function without target attribute"
) ? void (0) : __assert_fail ("TAX && TAY && \"Multiversion Function without target attribute\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3184, __extension__
__PRETTY_FUNCTION__))
;
3185
3186 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3187 return false;
3188 }
3189
3190 ASTContext &C = FuncX->getASTContext();
3191
3192 const Expr *XRC = FuncX->getTrailingRequiresClause();
3193 const Expr *YRC = FuncY->getTrailingRequiresClause();
3194 if (!XRC != !YRC)
3195 return false;
3196 if (XRC) {
3197 llvm::FoldingSetNodeID XRCID, YRCID;
3198 XRC->Profile(XRCID, C, /*Canonical=*/true);
3199 YRC->Profile(YRCID, C, /*Canonical=*/true);
3200 if (XRCID != YRCID)
3201 return false;
3202 }
3203
3204 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3205 // Map to the first declaration that we've already merged into this one.
3206 // The TSI of redeclarations might not match (due to calling conventions
3207 // being inherited onto the type but not the TSI), but the TSI type of
3208 // the first declaration of the function should match across modules.
3209 FD = FD->getCanonicalDecl();
3210 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3211 : FD->getType();
3212 };
3213 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3214 if (!C.hasSameType(XT, YT)) {
3215 // We can get functions with different types on the redecl chain in C++17
3216 // if they have differing exception specifications and at least one of
3217 // the excpetion specs is unresolved.
3218 auto *XFPT = XT->getAs<FunctionProtoType>();
3219 auto *YFPT = YT->getAs<FunctionProtoType>();
3220 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3221 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3222 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3223 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3224 return true;
3225 return false;
3226 }
3227
3228 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3229 hasSameOverloadableAttrs(FuncX, FuncY);
3230 }
3231
3232 // Variables with the same type and linkage match.
3233 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3234 const auto *VarY = cast<VarDecl>(Y);
3235 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3236 ASTContext &C = VarX->getASTContext();
3237 if (C.hasSameType(VarX->getType(), VarY->getType()))
3238 return true;
3239
3240 // We can get decls with different types on the redecl chain. Eg.
3241 // template <typename T> struct S { static T Var[]; }; // #1
3242 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3243 // Only? happens when completing an incomplete array type. In this case
3244 // when comparing #1 and #2 we should go through their element type.
3245 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3246 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3247 if (!VarXTy || !VarYTy)
3248 return false;
3249 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3250 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3251 }
3252 return false;
3253 }
3254
3255 // Namespaces with the same name and inlinedness match.
3256 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3257 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3258 return NamespaceX->isInline() == NamespaceY->isInline();
3259 }
3260
3261 // Identical template names and kinds match if their template parameter lists
3262 // and patterns match.
3263 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3264 const auto *TemplateY = cast<TemplateDecl>(Y);
3265 return isSameEntity(TemplateX->getTemplatedDecl(),
3266 TemplateY->getTemplatedDecl()) &&
3267 isSameTemplateParameterList(TemplateX->getASTContext(),
3268 TemplateX->getTemplateParameters(),
3269 TemplateY->getTemplateParameters());
3270 }
3271
3272 // Fields with the same name and the same type match.
3273 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3274 const auto *FDY = cast<FieldDecl>(Y);
3275 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3276 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3277 }
3278
3279 // Indirect fields with the same target field match.
3280 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3281 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3282 return IFDX->getAnonField()->getCanonicalDecl() ==
3283 IFDY->getAnonField()->getCanonicalDecl();
3284 }
3285
3286 // Enumerators with the same name match.
3287 if (isa<EnumConstantDecl>(X))
3288 // FIXME: Also check the value is odr-equivalent.
3289 return true;
3290
3291 // Using shadow declarations with the same target match.
3292 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3293 const auto *USY = cast<UsingShadowDecl>(Y);
3294 return USX->getTargetDecl() == USY->getTargetDecl();
3295 }
3296
3297 // Using declarations with the same qualifier match. (We already know that
3298 // the name matches.)
3299 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3300 const auto *UY = cast<UsingDecl>(Y);
3301 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3302 UX->hasTypename() == UY->hasTypename() &&
3303 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3304 }
3305 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3306 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3307 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3308 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3309 }
3310 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X)) {
3311 return isSameQualifier(
3312 UX->getQualifier(),
3313 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3314 }
3315
3316 // Using-pack declarations are only created by instantiation, and match if
3317 // they're instantiated from matching UnresolvedUsing...Decls.
3318 if (const auto *UX = dyn_cast<UsingPackDecl>(X)) {
3319 return declaresSameEntity(
3320 UX->getInstantiatedFromUsingDecl(),
3321 cast<UsingPackDecl>(Y)->getInstantiatedFromUsingDecl());
3322 }
3323
3324 // Namespace alias definitions with the same target match.
3325 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3326 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3327 return NAX->getNamespace()->Equals(NAY->getNamespace());
3328 }
3329
3330 return false;
3331}
3332
3333/// Find the context in which we should search for previous declarations when
3334/// looking for declarations to merge.
3335DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3336 DeclContext *DC) {
3337 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3338 return ND->getOriginalNamespace();
3339
3340 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3341 // Try to dig out the definition.
3342 auto *DD = RD->DefinitionData;
3343 if (!DD)
3344 DD = RD->getCanonicalDecl()->DefinitionData;
3345
3346 // If there's no definition yet, then DC's definition is added by an update
3347 // record, but we've not yet loaded that update record. In this case, we
3348 // commit to DC being the canonical definition now, and will fix this when
3349 // we load the update record.
3350 if (!DD) {
3351 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3352 RD->setCompleteDefinition(true);
3353 RD->DefinitionData = DD;
3354 RD->getCanonicalDecl()->DefinitionData = DD;
3355
3356 // Track that we did this horrible thing so that we can fix it later.
3357 Reader.PendingFakeDefinitionData.insert(
3358 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3359 }
3360
3361 return DD->Definition;
3362 }
3363
3364 if (auto *RD = dyn_cast<RecordDecl>(DC))
3365 return RD->getDefinition();
3366
3367 if (auto *ED = dyn_cast<EnumDecl>(DC))
3368 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3369 : nullptr;
3370
3371 if (auto *OID = dyn_cast<ObjCInterfaceDecl>(DC))
3372 return OID->getDefinition();
3373
3374 // We can see the TU here only if we have no Sema object. In that case,
3375 // there's no TU scope to look in, so using the DC alone is sufficient.
3376 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3377 return TU;
3378
3379 return nullptr;
3380}
3381
3382ASTDeclReader::FindExistingResult::~FindExistingResult() {
3383 // Record that we had a typedef name for linkage whether or not we merge
3384 // with that declaration.
3385 if (TypedefNameForLinkage) {
3386 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3387 Reader.ImportedTypedefNamesForLinkage.insert(
3388 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3389 return;
3390 }
3391
3392 if (!AddResult || Existing)
3393 return;
3394
3395 DeclarationName Name = New->getDeclName();
3396 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3397 if (needsAnonymousDeclarationNumber(New)) {
3398 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3399 AnonymousDeclNumber, New);
3400 } else if (DC->isTranslationUnit() &&
3401 !Reader.getContext().getLangOpts().CPlusPlus) {
3402 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3403 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3404 .push_back(New);
3405 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3406 // Add the declaration to its redeclaration context so later merging
3407 // lookups will find it.
3408 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3409 }
3410}
3411
3412/// Find the declaration that should be merged into, given the declaration found
3413/// by name lookup. If we're merging an anonymous declaration within a typedef,
3414/// we need a matching typedef, and we merge with the type inside it.
3415static NamedDecl *getDeclForMerging(NamedDecl *Found,
3416 bool IsTypedefNameForLinkage) {
3417 if (!IsTypedefNameForLinkage)
3418 return Found;
3419
3420 // If we found a typedef declaration that gives a name to some other
3421 // declaration, then we want that inner declaration. Declarations from
3422 // AST files are handled via ImportedTypedefNamesForLinkage.
3423 if (Found->isFromASTFile())
3424 return nullptr;
3425
3426 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3427 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3428
3429 return nullptr;
3430}
3431
3432/// Find the declaration to use to populate the anonymous declaration table
3433/// for the given lexical DeclContext. We only care about finding local
3434/// definitions of the context; we'll merge imported ones as we go.
3435DeclContext *
3436ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3437 // For classes, we track the definition as we merge.
3438 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3439 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3440 return DD ? DD->Definition : nullptr;
3441 }
3442
3443 // For anything else, walk its merged redeclarations looking for a definition.
3444 // Note that we can't just call getDefinition here because the redeclaration
3445 // chain isn't wired up.
3446 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3447 if (auto *FD = dyn_cast<FunctionDecl>(D))
3448 if (FD->isThisDeclarationADefinition())
3449 return FD;
3450 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3451 if (MD->isThisDeclarationADefinition())
3452 return MD;
3453 if (auto *RD = dyn_cast<RecordDecl>(D))
3454 if (RD->isThisDeclarationADefinition())
3455 return RD;
3456 }
3457
3458 // No merged definition yet.
3459 return nullptr;
3460}
3461
3462NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3463 DeclContext *DC,
3464 unsigned Index) {
3465 // If the lexical context has been merged, look into the now-canonical
3466 // definition.
3467 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3468
3469 // If we've seen this before, return the canonical declaration.
3470 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3471 if (Index < Previous.size() && Previous[Index])
3472 return Previous[Index];
3473
3474 // If this is the first time, but we have parsed a declaration of the context,
3475 // build the anonymous declaration list from the parsed declaration.
3476 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3477 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3478 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3479 if (Previous.size() == Number)
3480 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3481 else
3482 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3483 });
3484 }
3485
3486 return Index < Previous.size() ? Previous[Index] : nullptr;
3487}
3488
3489void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3490 DeclContext *DC, unsigned Index,
3491 NamedDecl *D) {
3492 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3493
3494 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3495 if (Index >= Previous.size())
3496 Previous.resize(Index + 1);
3497 if (!Previous[Index])
3498 Previous[Index] = D;
3499}
3500
3501ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3502 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3503 : D->getDeclName();
3504
3505 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3506 // Don't bother trying to find unnamed declarations that are in
3507 // unmergeable contexts.
3508 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3509 AnonymousDeclNumber, TypedefNameForLinkage);
3510 Result.suppress();
3511 return Result;
3512 }
3513
3514 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3515 if (TypedefNameForLinkage) {
3516 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3517 std::make_pair(DC, TypedefNameForLinkage));
3518 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3519 if (isSameEntity(It->second, D))
3520 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3521 TypedefNameForLinkage);
3522 // Go on to check in other places in case an existing typedef name
3523 // was not imported.
3524 }
3525
3526 if (needsAnonymousDeclarationNumber(D)) {
3527 // This is an anonymous declaration that we may need to merge. Look it up
3528 // in its context by number.
3529 if (auto *Existing = getAnonymousDeclForMerging(
3530 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3531 if (isSameEntity(Existing, D))
3532 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3533 TypedefNameForLinkage);
3534 } else if (DC->isTranslationUnit() &&
3535 !Reader.getContext().getLangOpts().CPlusPlus) {
3536 IdentifierResolver &IdResolver = Reader.getIdResolver();
3537
3538 // Temporarily consider the identifier to be up-to-date. We don't want to
3539 // cause additional lookups here.
3540 class UpToDateIdentifierRAII {
3541 IdentifierInfo *II;
3542 bool WasOutToDate = false;
3543
3544 public:
3545 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3546 if (II) {
3547 WasOutToDate = II->isOutOfDate();
3548 if (WasOutToDate)
3549 II->setOutOfDate(false);
3550 }
3551 }
3552
3553 ~UpToDateIdentifierRAII() {
3554 if (WasOutToDate)
3555 II->setOutOfDate(true);
3556 }
3557 } UpToDate(Name.getAsIdentifierInfo());
3558
3559 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3560 IEnd = IdResolver.end();
3561 I != IEnd; ++I) {
3562 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3563 if (isSameEntity(Existing, D))
3564 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3565 TypedefNameForLinkage);
3566 }
3567 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3568 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3569 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3570 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3571 if (isSameEntity(Existing, D))
3572 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3573 TypedefNameForLinkage);
3574 }
3575 } else {
3576 // Not in a mergeable context.
3577 return FindExistingResult(Reader);
3578 }
3579
3580 // If this declaration is from a merged context, make a note that we need to
3581 // check that the canonical definition of that context contains the decl.
3582 //
3583 // FIXME: We should do something similar if we merge two definitions of the
3584 // same template specialization into the same CXXRecordDecl.
3585 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3586 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3587 MergedDCIt->second == D->getDeclContext())
3588 Reader.PendingOdrMergeChecks.push_back(D);
3589
3590 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3591 AnonymousDeclNumber, TypedefNameForLinkage);
3592}
3593
3594template<typename DeclT>
3595Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3596 return D->RedeclLink.getLatestNotUpdated();
3597}
3598
3599Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3600 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("getMostRecentDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3600)
;
3601}
3602
3603Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3604 assert(D)(static_cast <bool> (D) ? void (0) : __assert_fail ("D"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3604, __extension__
__PRETTY_FUNCTION__))
;
3605
3606 switch (D->getKind()) {
3607#define ABSTRACT_DECL(TYPE)
3608#define DECL(TYPE, BASE) \
3609 case Decl::TYPE: \
3610 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3611#include "clang/AST/DeclNodes.inc"
3612 }
3613 llvm_unreachable("unknown decl kind")::llvm::llvm_unreachable_internal("unknown decl kind", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3613)
;
3614}
3615
3616Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3617 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3618}
3619
3620void ASTDeclReader::mergeInheritableAttributes(ASTReader &Reader, Decl *D,
3621 Decl *Previous) {
3622 InheritableAttr *NewAttr = nullptr;
3623 ASTContext &Context = Reader.getContext();
3624 const auto *IA = Previous->getAttr<MSInheritanceAttr>();
3625
3626 if (IA && !D->hasAttr<MSInheritanceAttr>()) {
3627 NewAttr = cast<InheritableAttr>(IA->clone(Context));
3628 NewAttr->setInherited(true);
3629 D->addAttr(NewAttr);
3630 }
3631}
3632
3633template<typename DeclT>
3634void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3635 Redeclarable<DeclT> *D,
3636 Decl *Previous, Decl *Canon) {
3637 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3638 D->First = cast<DeclT>(Previous)->First;
3639}
3640
3641namespace clang {
3642
3643template<>
3644void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3645 Redeclarable<VarDecl> *D,
3646 Decl *Previous, Decl *Canon) {
3647 auto *VD = static_cast<VarDecl *>(D);
3648 auto *PrevVD = cast<VarDecl>(Previous);
3649 D->RedeclLink.setPrevious(PrevVD);
3650 D->First = PrevVD->First;
3651
3652 // We should keep at most one definition on the chain.
3653 // FIXME: Cache the definition once we've found it. Building a chain with
3654 // N definitions currently takes O(N^2) time here.
3655 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3656 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3657 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3658 Reader.mergeDefinitionVisibility(CurD, VD);
3659 VD->demoteThisDefinitionToDeclaration();
3660 break;
3661 }
3662 }
3663 }
3664}
3665
3666static bool isUndeducedReturnType(QualType T) {
3667 auto *DT = T->getContainedDeducedType();
3668 return DT && !DT->isDeduced();
3669}
3670
3671template<>
3672void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3673 Redeclarable<FunctionDecl> *D,
3674 Decl *Previous, Decl *Canon) {
3675 auto *FD = static_cast<FunctionDecl *>(D);
3676 auto *PrevFD = cast<FunctionDecl>(Previous);
3677
3678 FD->RedeclLink.setPrevious(PrevFD);
3679 FD->First = PrevFD->First;
3680
3681 // If the previous declaration is an inline function declaration, then this
3682 // declaration is too.
3683 if (PrevFD->isInlined() != FD->isInlined()) {
3684 // FIXME: [dcl.fct.spec]p4:
3685 // If a function with external linkage is declared inline in one
3686 // translation unit, it shall be declared inline in all translation
3687 // units in which it appears.
3688 //
3689 // Be careful of this case:
3690 //
3691 // module A:
3692 // template<typename T> struct X { void f(); };
3693 // template<typename T> inline void X<T>::f() {}
3694 //
3695 // module B instantiates the declaration of X<int>::f
3696 // module C instantiates the definition of X<int>::f
3697 //
3698 // If module B and C are merged, we do not have a violation of this rule.
3699 FD->setImplicitlyInline(true);
3700 }
3701
3702 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3703 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3704 if (FPT && PrevFPT) {
3705 // If we need to propagate an exception specification along the redecl
3706 // chain, make a note of that so that we can do so later.
3707 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3708 bool WasUnresolved =
3709 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3710 if (IsUnresolved != WasUnresolved)
3711 Reader.PendingExceptionSpecUpdates.insert(
3712 {Canon, IsUnresolved ? PrevFD : FD});
3713
3714 // If we need to propagate a deduced return type along the redecl chain,
3715 // make a note of that so that we can do it later.
3716 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3717 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3718 if (IsUndeduced != WasUndeduced)
3719 Reader.PendingDeducedTypeUpdates.insert(
3720 {cast<FunctionDecl>(Canon),
3721 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3722 }
3723}
3724
3725} // namespace clang
3726
3727void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3728 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("attachPreviousDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3728)
;
3729}
3730
3731/// Inherit the default template argument from \p From to \p To. Returns
3732/// \c false if there is no default template for \p From.
3733template <typename ParmDecl>
3734static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3735 Decl *ToD) {
3736 auto *To = cast<ParmDecl>(ToD);
3737 if (!From->hasDefaultArgument())
3738 return false;
3739 To->setInheritedDefaultArgument(Context, From);
3740 return true;
3741}
3742
3743static void inheritDefaultTemplateArguments(ASTContext &Context,
3744 TemplateDecl *From,
3745 TemplateDecl *To) {
3746 auto *FromTP = From->getTemplateParameters();
3747 auto *ToTP = To->getTemplateParameters();
3748 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?")(static_cast <bool> (FromTP->size() == ToTP->size
() && "merged mismatched templates?") ? void (0) : __assert_fail
("FromTP->size() == ToTP->size() && \"merged mismatched templates?\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3748, __extension__
__PRETTY_FUNCTION__))
;
3749
3750 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3751 NamedDecl *FromParam = FromTP->getParam(I);
3752 NamedDecl *ToParam = ToTP->getParam(I);
3753
3754 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3755 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3756 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3757 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3758 else
3759 inheritDefaultTemplateArgument(
3760 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3761 }
3762}
3763
3764void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3765 Decl *Previous, Decl *Canon) {
3766 assert(D && Previous)(static_cast <bool> (D && Previous) ? void (0) :
__assert_fail ("D && Previous", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3766, __extension__ __PRETTY_FUNCTION__))
;
3767
3768 switch (D->getKind()) {
3769#define ABSTRACT_DECL(TYPE)
3770#define DECL(TYPE, BASE) \
3771 case Decl::TYPE: \
3772 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3773 break;
3774#include "clang/AST/DeclNodes.inc"
3775 }
3776
3777 // If the declaration was visible in one module, a redeclaration of it in
3778 // another module remains visible even if it wouldn't be visible by itself.
3779 //
3780 // FIXME: In this case, the declaration should only be visible if a module
3781 // that makes it visible has been imported.
3782 D->IdentifierNamespace |=
3783 Previous->IdentifierNamespace &
3784 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3785
3786 // If the declaration declares a template, it may inherit default arguments
3787 // from the previous declaration.
3788 if (auto *TD = dyn_cast<TemplateDecl>(D))
3789 inheritDefaultTemplateArguments(Reader.getContext(),
3790 cast<TemplateDecl>(Previous), TD);
3791
3792 // If any of the declaration in the chain contains an Inheritable attribute,
3793 // it needs to be added to all the declarations in the redeclarable chain.
3794 // FIXME: Only the logic of merging MSInheritableAttr is present, it should
3795 // be extended for all inheritable attributes.
3796 mergeInheritableAttributes(Reader, D, Previous);
3797}
3798
3799template<typename DeclT>
3800void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3801 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3802}
3803
3804void ASTDeclReader::attachLatestDeclImpl(...) {
3805 llvm_unreachable("attachLatestDecl on non-redeclarable declaration")::llvm::llvm_unreachable_internal("attachLatestDecl on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3805)
;
3806}
3807
3808void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3809 assert(D && Latest)(static_cast <bool> (D && Latest) ? void (0) : __assert_fail
("D && Latest", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 3809, __extension__ __PRETTY_FUNCTION__))
;
3810
3811 switch (D->getKind()) {
3812#define ABSTRACT_DECL(TYPE)
3813#define DECL(TYPE, BASE) \
3814 case Decl::TYPE: \
3815 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3816 break;
3817#include "clang/AST/DeclNodes.inc"
3818 }
3819}
3820
3821template<typename DeclT>
3822void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3823 D->RedeclLink.markIncomplete();
3824}
3825
3826void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3827 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration")::llvm::llvm_unreachable_internal("markIncompleteDeclChain on non-redeclarable declaration"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3827)
;
3828}
3829
3830void ASTReader::markIncompleteDeclChain(Decl *D) {
3831 switch (D->getKind()) {
3832#define ABSTRACT_DECL(TYPE)
3833#define DECL(TYPE, BASE) \
3834 case Decl::TYPE: \
3835 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3836 break;
3837#include "clang/AST/DeclNodes.inc"
3838 }
3839}
3840
3841/// Read the declaration at the given offset from the AST file.
3842Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3843 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3844 SourceLocation DeclLoc;
3845 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3846 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3847 // Keep track of where we are in the stream, then jump back there
3848 // after reading this declaration.
3849 SavedStreamPosition SavedPosition(DeclsCursor);
3850
3851 ReadingKindTracker ReadingKind(Read_Decl, *this);
3852
3853 // Note that we are loading a declaration record.
3854 Deserializing ADecl(this);
3855
3856 auto Fail = [](const char *what, llvm::Error &&Err) {
3857 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3858 ": " + toString(std::move(Err)));
3859 };
3860
3861 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3862 Fail("jumping", std::move(JumpFailed));
3863 ASTRecordReader Record(*this, *Loc.F);
3864 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3865 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3866 if (!MaybeCode)
3867 Fail("reading code", MaybeCode.takeError());
3868 unsigned Code = MaybeCode.get();
3869
3870 ASTContext &Context = getContext();
3871 Decl *D = nullptr;
3872 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3873 if (!MaybeDeclCode)
3874 llvm::report_fatal_error(
3875 Twine("ASTReader::readDeclRecord failed reading decl code: ") +
3876 toString(MaybeDeclCode.takeError()));
3877 switch ((DeclCode)MaybeDeclCode.get()) {
3878 case DECL_CONTEXT_LEXICAL:
3879 case DECL_CONTEXT_VISIBLE:
3880 llvm_unreachable("Record cannot be de-serialized with readDeclRecord")::llvm::llvm_unreachable_internal("Record cannot be de-serialized with readDeclRecord"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 3880)
;
3881 case DECL_TYPEDEF:
3882 D = TypedefDecl::CreateDeserialized(Context, ID);
3883 break;
3884 case DECL_TYPEALIAS:
3885 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3886 break;
3887 case DECL_ENUM:
3888 D = EnumDecl::CreateDeserialized(Context, ID);
3889 break;
3890 case DECL_RECORD:
3891 D = RecordDecl::CreateDeserialized(Context, ID);
3892 break;
3893 case DECL_ENUM_CONSTANT:
3894 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3895 break;
3896 case DECL_FUNCTION:
3897 D = FunctionDecl::CreateDeserialized(Context, ID);
3898 break;
3899 case DECL_LINKAGE_SPEC:
3900 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3901 break;
3902 case DECL_EXPORT:
3903 D = ExportDecl::CreateDeserialized(Context, ID);
3904 break;
3905 case DECL_LABEL:
3906 D = LabelDecl::CreateDeserialized(Context, ID);
3907 break;
3908 case DECL_NAMESPACE:
3909 D = NamespaceDecl::CreateDeserialized(Context, ID);
3910 break;
3911 case DECL_NAMESPACE_ALIAS:
3912 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3913 break;
3914 case DECL_USING:
3915 D = UsingDecl::CreateDeserialized(Context, ID);
3916 break;
3917 case DECL_USING_PACK:
3918 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3919 break;
3920 case DECL_USING_SHADOW:
3921 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3922 break;
3923 case DECL_USING_ENUM:
3924 D = UsingEnumDecl::CreateDeserialized(Context, ID);
3925 break;
3926 case DECL_CONSTRUCTOR_USING_SHADOW:
3927 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3928 break;
3929 case DECL_USING_DIRECTIVE:
3930 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3931 break;
3932 case DECL_UNRESOLVED_USING_VALUE:
3933 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3934 break;
3935 case DECL_UNRESOLVED_USING_TYPENAME:
3936 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3937 break;
3938 case DECL_UNRESOLVED_USING_IF_EXISTS:
3939 D = UnresolvedUsingIfExistsDecl::CreateDeserialized(Context, ID);
3940 break;
3941 case DECL_CXX_RECORD:
3942 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3943 break;
3944 case DECL_CXX_DEDUCTION_GUIDE:
3945 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3946 break;
3947 case DECL_CXX_METHOD:
3948 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3949 break;
3950 case DECL_CXX_CONSTRUCTOR:
3951 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3952 break;
3953 case DECL_CXX_DESTRUCTOR:
3954 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3955 break;
3956 case DECL_CXX_CONVERSION:
3957 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3958 break;
3959 case DECL_ACCESS_SPEC:
3960 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3961 break;
3962 case DECL_FRIEND:
3963 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3964 break;
3965 case DECL_FRIEND_TEMPLATE:
3966 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3967 break;
3968 case DECL_CLASS_TEMPLATE:
3969 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3970 break;
3971 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3972 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3973 break;
3974 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3975 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3976 break;
3977 case DECL_VAR_TEMPLATE:
3978 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3979 break;
3980 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3981 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3982 break;
3983 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3984 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3985 break;
3986 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3987 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3988 break;
3989 case DECL_FUNCTION_TEMPLATE:
3990 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3991 break;
3992 case DECL_TEMPLATE_TYPE_PARM: {
3993 bool HasTypeConstraint = Record.readInt();
3994 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3995 HasTypeConstraint);
3996 break;
3997 }
3998 case DECL_NON_TYPE_TEMPLATE_PARM: {
3999 bool HasTypeConstraint = Record.readInt();
4000 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
4001 HasTypeConstraint);
4002 break;
4003 }
4004 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
4005 bool HasTypeConstraint = Record.readInt();
4006 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
4007 Record.readInt(),
4008 HasTypeConstraint);
4009 break;
4010 }
4011 case DECL_TEMPLATE_TEMPLATE_PARM:
4012 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
4013 break;
4014 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
4015 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
4016 Record.readInt());
4017 break;
4018 case DECL_TYPE_ALIAS_TEMPLATE:
4019 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
4020 break;
4021 case DECL_CONCEPT:
4022 D = ConceptDecl::CreateDeserialized(Context, ID);
4023 break;
4024 case DECL_REQUIRES_EXPR_BODY:
4025 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
4026 break;
4027 case DECL_STATIC_ASSERT:
4028 D = StaticAssertDecl::CreateDeserialized(Context, ID);
4029 break;
4030 case DECL_OBJC_METHOD:
4031 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
4032 break;
4033 case DECL_OBJC_INTERFACE:
4034 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
4035 break;
4036 case DECL_OBJC_IVAR:
4037 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
4038 break;
4039 case DECL_OBJC_PROTOCOL:
4040 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
4041 break;
4042 case DECL_OBJC_AT_DEFS_FIELD:
4043 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
4044 break;
4045 case DECL_OBJC_CATEGORY:
4046 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
4047 break;
4048 case DECL_OBJC_CATEGORY_IMPL:
4049 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
4050 break;
4051 case DECL_OBJC_IMPLEMENTATION:
4052 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
4053 break;
4054 case DECL_OBJC_COMPATIBLE_ALIAS:
4055 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
4056 break;
4057 case DECL_OBJC_PROPERTY:
4058 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
4059 break;
4060 case DECL_OBJC_PROPERTY_IMPL:
4061 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
4062 break;
4063 case DECL_FIELD:
4064 D = FieldDecl::CreateDeserialized(Context, ID);
4065 break;
4066 case DECL_INDIRECTFIELD:
4067 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
4068 break;
4069 case DECL_VAR:
4070 D = VarDecl::CreateDeserialized(Context, ID);
4071 break;
4072 case DECL_IMPLICIT_PARAM:
4073 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
4074 break;
4075 case DECL_PARM_VAR:
4076 D = ParmVarDecl::CreateDeserialized(Context, ID);
4077 break;
4078 case DECL_DECOMPOSITION:
4079 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
4080 break;
4081 case DECL_BINDING:
4082 D = BindingDecl::CreateDeserialized(Context, ID);
4083 break;
4084 case DECL_FILE_SCOPE_ASM:
4085 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
4086 break;
4087 case DECL_BLOCK:
4088 D = BlockDecl::CreateDeserialized(Context, ID);
4089 break;
4090 case DECL_MS_PROPERTY:
4091 D = MSPropertyDecl::CreateDeserialized(Context, ID);
4092 break;
4093 case DECL_MS_GUID:
4094 D = MSGuidDecl::CreateDeserialized(Context, ID);
4095 break;
4096 case DECL_TEMPLATE_PARAM_OBJECT:
4097 D = TemplateParamObjectDecl::CreateDeserialized(Context, ID);
4098 break;
4099 case DECL_CAPTURED:
4100 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
4101 break;
4102 case DECL_CXX_BASE_SPECIFIERS:
4103 Error("attempt to read a C++ base-specifier record as a declaration");
4104 return nullptr;
4105 case DECL_CXX_CTOR_INITIALIZERS:
4106 Error("attempt to read a C++ ctor initializer record as a declaration");
4107 return nullptr;
4108 case DECL_IMPORT:
4109 // Note: last entry of the ImportDecl record is the number of stored source
4110 // locations.
4111 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
4112 break;
4113 case DECL_OMP_THREADPRIVATE: {
4114 Record.skipInts(1);
4115 unsigned NumChildren = Record.readInt();
4116 Record.skipInts(1);
4117 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, NumChildren);
4118 break;
4119 }
4120 case DECL_OMP_ALLOCATE: {
4121 unsigned NumClauses = Record.readInt();
4122 unsigned NumVars = Record.readInt();
4123 Record.skipInts(1);
4124 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
4125 break;
4126 }
4127 case DECL_OMP_REQUIRES: {
4128 unsigned NumClauses = Record.readInt();
4129 Record.skipInts(2);
4130 D = OMPRequiresDecl::CreateDeserialized(Context, ID, NumClauses);
4131 break;
4132 }
4133 case DECL_OMP_DECLARE_REDUCTION:
4134 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
4135 break;
4136 case DECL_OMP_DECLARE_MAPPER: {
4137 unsigned NumClauses = Record.readInt();
4138 Record.skipInts(2);
4139 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, NumClauses);
4140 break;
4141 }
4142 case DECL_OMP_CAPTUREDEXPR:
4143 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
4144 break;
4145 case DECL_PRAGMA_COMMENT:
4146 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
4147 break;
4148 case DECL_PRAGMA_DETECT_MISMATCH:
4149 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
4150 Record.readInt());
4151 break;
4152 case DECL_EMPTY:
4153 D = EmptyDecl::CreateDeserialized(Context, ID);
4154 break;
4155 case DECL_LIFETIME_EXTENDED_TEMPORARY:
4156 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
4157 break;
4158 case DECL_OBJC_TYPE_PARAM:
4159 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
4160 break;
4161 }
4162
4163 assert(D && "Unknown declaration reading AST file")(static_cast <bool> (D && "Unknown declaration reading AST file"
) ? void (0) : __assert_fail ("D && \"Unknown declaration reading AST file\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4163, __extension__
__PRETTY_FUNCTION__))
;
4164 LoadedDecl(Index, D);
4165 // Set the DeclContext before doing any deserialization, to make sure internal
4166 // calls to Decl::getASTContext() by Decl's methods will find the
4167 // TranslationUnitDecl without crashing.
4168 D->setDeclContext(Context.getTranslationUnitDecl());
4169 Reader.Visit(D);
4170
4171 // If this declaration is also a declaration context, get the
4172 // offsets for its tables of lexical and visible declarations.
4173 if (auto *DC = dyn_cast<DeclContext>(D)) {
4174 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
4175 if (Offsets.first &&
4176 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
4177 return nullptr;
4178 if (Offsets.second &&
4179 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
4180 return nullptr;
4181 }
4182 assert(Record.getIdx() == Record.size())(static_cast <bool> (Record.getIdx() == Record.size()) ?
void (0) : __assert_fail ("Record.getIdx() == Record.size()"
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4182, __extension__
__PRETTY_FUNCTION__))
;
4183
4184 // Load any relevant update records.
4185 PendingUpdateRecords.push_back(
4186 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
4187
4188 // Load the categories after recursive loading is finished.
4189 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
4190 // If we already have a definition when deserializing the ObjCInterfaceDecl,
4191 // we put the Decl in PendingDefinitions so we can pull the categories here.
4192 if (Class->isThisDeclarationADefinition() ||
4193 PendingDefinitions.count(Class))
4194 loadObjCCategories(ID, Class);
4195
4196 // If we have deserialized a declaration that has a definition the
4197 // AST consumer might need to know about, queue it.
4198 // We don't pass it to the consumer immediately because we may be in recursive
4199 // loading, and some declarations may still be initializing.
4200 PotentiallyInterestingDecls.push_back(
4201 InterestingDecl(D, Reader.hasPendingBody()));
4202
4203 return D;
4204}
4205
4206void ASTReader::PassInterestingDeclsToConsumer() {
4207 assert(Consumer)(static_cast <bool> (Consumer) ? void (0) : __assert_fail
("Consumer", "clang/lib/Serialization/ASTReaderDecl.cpp", 4207
, __extension__ __PRETTY_FUNCTION__))
;
4208
4209 if (PassingDeclsToConsumer)
4210 return;
4211
4212 // Guard variable to avoid recursively redoing the process of passing
4213 // decls to consumer.
4214 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4215 true);
4216
4217 // Ensure that we've loaded all potentially-interesting declarations
4218 // that need to be eagerly loaded.
4219 for (auto ID : EagerlyDeserializedDecls)
4220 GetDecl(ID);
4221 EagerlyDeserializedDecls.clear();
4222
4223 while (!PotentiallyInterestingDecls.empty()) {
4224 InterestingDecl D = PotentiallyInterestingDecls.front();
4225 PotentiallyInterestingDecls.pop_front();
4226 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4227 PassInterestingDeclToConsumer(D.getDecl());
4228 }
4229}
4230
4231void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4232 // The declaration may have been modified by files later in the chain.
4233 // If this is the case, read the record containing the updates from each file
4234 // and pass it to ASTDeclReader to make the modifications.
4235 serialization::GlobalDeclID ID = Record.ID;
4236 Decl *D = Record.D;
4237 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4238 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4239
4240 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4241
4242 if (UpdI != DeclUpdateOffsets.end()) {
4243 auto UpdateOffsets = std::move(UpdI->second);
4244 DeclUpdateOffsets.erase(UpdI);
4245
4246 // Check if this decl was interesting to the consumer. If we just loaded
4247 // the declaration, then we know it was interesting and we skip the call
4248 // to isConsumerInterestedIn because it is unsafe to call in the
4249 // current ASTReader state.
4250 bool WasInteresting =
4251 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4252 for (auto &FileAndOffset : UpdateOffsets) {
4253 ModuleFile *F = FileAndOffset.first;
4254 uint64_t Offset = FileAndOffset.second;
4255 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4256 SavedStreamPosition SavedPosition(Cursor);
4257 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4258 // FIXME don't do a fatal error.
4259 llvm::report_fatal_error(
4260 Twine("ASTReader::loadDeclUpdateRecords failed jumping: ") +
4261 toString(std::move(JumpFailed)));
4262 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4263 if (!MaybeCode)
4264 llvm::report_fatal_error(
4265 Twine("ASTReader::loadDeclUpdateRecords failed reading code: ") +
4266 toString(MaybeCode.takeError()));
4267 unsigned Code = MaybeCode.get();
4268 ASTRecordReader Record(*this, *F);
4269 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4270 assert(MaybeRecCode.get() == DECL_UPDATES &&(static_cast <bool> (MaybeRecCode.get() == DECL_UPDATES
&& "Expected DECL_UPDATES record!") ? void (0) : __assert_fail
("MaybeRecCode.get() == DECL_UPDATES && \"Expected DECL_UPDATES record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4271, __extension__
__PRETTY_FUNCTION__))
4271 "Expected DECL_UPDATES record!")(static_cast <bool> (MaybeRecCode.get() == DECL_UPDATES
&& "Expected DECL_UPDATES record!") ? void (0) : __assert_fail
("MaybeRecCode.get() == DECL_UPDATES && \"Expected DECL_UPDATES record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4271, __extension__
__PRETTY_FUNCTION__))
;
4272 else
4273 llvm::report_fatal_error(
4274 Twine("ASTReader::loadDeclUpdateRecords failed reading rec code: ") +
4275 toString(MaybeCode.takeError()));
4276
4277 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4278 SourceLocation());
4279 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4280
4281 // We might have made this declaration interesting. If so, remember that
4282 // we need to hand it off to the consumer.
4283 if (!WasInteresting &&
4284 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4285 PotentiallyInterestingDecls.push_back(
4286 InterestingDecl(D, Reader.hasPendingBody()));
4287 WasInteresting = true;
4288 }
4289 }
4290 }
4291 // Add the lazy specializations to the template.
4292 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4294, __extension__
__PRETTY_FUNCTION__))
4293 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4294, __extension__
__PRETTY_FUNCTION__))
4294 "Must not have pending specializations")(static_cast <bool> ((PendingLazySpecializationIDs.empty
() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl
>(D) || isa<VarTemplateDecl>(D)) && "Must not have pending specializations"
) ? void (0) : __assert_fail ("(PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) || isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) && \"Must not have pending specializations\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4294, __extension__
__PRETTY_FUNCTION__))
;
4295 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4296 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4297 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4298 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4299 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4300 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4301 PendingLazySpecializationIDs.clear();
4302
4303 // Load the pending visible updates for this decl context, if it has any.
4304 auto I = PendingVisibleUpdates.find(ID);
4305 if (I != PendingVisibleUpdates.end()) {
4306 auto VisibleUpdates = std::move(I->second);
4307 PendingVisibleUpdates.erase(I);
4308
4309 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4310 for (const auto &Update : VisibleUpdates)
4311 Lookups[DC].Table.add(
4312 Update.Mod, Update.Data,
4313 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4314 DC->setHasExternalVisibleStorage(true);
4315 }
4316}
4317
4318void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4319 // Attach FirstLocal to the end of the decl chain.
4320 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4321 if (FirstLocal != CanonDecl) {
4322 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4323 ASTDeclReader::attachPreviousDecl(
4324 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4325 CanonDecl);
4326 }
4327
4328 if (!LocalOffset) {
4329 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4330 return;
4331 }
4332
4333 // Load the list of other redeclarations from this module file.
4334 ModuleFile *M = getOwningModuleFile(FirstLocal);
4335 assert(M && "imported decl from no module file")(static_cast <bool> (M && "imported decl from no module file"
) ? void (0) : __assert_fail ("M && \"imported decl from no module file\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4335, __extension__
__PRETTY_FUNCTION__))
;
4336
4337 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4338 SavedStreamPosition SavedPosition(Cursor);
4339 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4340 llvm::report_fatal_error(
4341 Twine("ASTReader::loadPendingDeclChain failed jumping: ") +
4342 toString(std::move(JumpFailed)));
4343
4344 RecordData Record;
4345 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4346 if (!MaybeCode)
4347 llvm::report_fatal_error(
4348 Twine("ASTReader::loadPendingDeclChain failed reading code: ") +
4349 toString(MaybeCode.takeError()));
4350 unsigned Code = MaybeCode.get();
4351 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4352 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&(static_cast <bool> (MaybeRecCode.get() == LOCAL_REDECLARATIONS
&& "expected LOCAL_REDECLARATIONS record!") ? void (
0) : __assert_fail ("MaybeRecCode.get() == LOCAL_REDECLARATIONS && \"expected LOCAL_REDECLARATIONS record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4353, __extension__
__PRETTY_FUNCTION__))
4353 "expected LOCAL_REDECLARATIONS record!")(static_cast <bool> (MaybeRecCode.get() == LOCAL_REDECLARATIONS
&& "expected LOCAL_REDECLARATIONS record!") ? void (
0) : __assert_fail ("MaybeRecCode.get() == LOCAL_REDECLARATIONS && \"expected LOCAL_REDECLARATIONS record!\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4353, __extension__
__PRETTY_FUNCTION__))
;
4354 else
4355 llvm::report_fatal_error(
4356 Twine("ASTReader::loadPendingDeclChain failed reading rec code: ") +
4357 toString(MaybeCode.takeError()));
4358
4359 // FIXME: We have several different dispatches on decl kind here; maybe
4360 // we should instead generate one loop per kind and dispatch up-front?
4361 Decl *MostRecent = FirstLocal;
4362 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4363 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4364 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4365 MostRecent = D;
4366 }
4367 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4368}
4369
4370namespace {
4371
4372 /// Given an ObjC interface, goes through the modules and links to the
4373 /// interface all the categories for it.
4374 class ObjCCategoriesVisitor {
4375 ASTReader &Reader;
4376 ObjCInterfaceDecl *Interface;
4377 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4378 ObjCCategoryDecl *Tail = nullptr;
4379 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4380 serialization::GlobalDeclID InterfaceID;
4381 unsigned PreviousGeneration;
4382
4383 void add(ObjCCategoryDecl *Cat) {
4384 // Only process each category once.
4385 if (!Deserialized.erase(Cat))
4386 return;
4387
4388 // Check for duplicate categories.
4389 if (Cat->getDeclName()) {
4390 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4391 if (Existing &&
4392 Reader.getOwningModuleFile(Existing)
4393 != Reader.getOwningModuleFile(Cat)) {
4394 // FIXME: We should not warn for duplicates in diamond:
4395 //
4396 // MT //
4397 // / \ //
4398 // ML MR //
4399 // \ / //
4400 // MB //
4401 //
4402 // If there are duplicates in ML/MR, there will be warning when
4403 // creating MB *and* when importing MB. We should not warn when
4404 // importing.
4405 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4406 << Interface->getDeclName() << Cat->getDeclName();
4407 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4408 } else if (!Existing) {
4409 // Record this category.
4410 Existing = Cat;
4411 }
4412 }
4413
4414 // Add this category to the end of the chain.
4415 if (Tail)
4416 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4417 else
4418 Interface->setCategoryListRaw(Cat);
4419 Tail = Cat;
4420 }
4421
4422 public:
4423 ObjCCategoriesVisitor(ASTReader &Reader,
4424 ObjCInterfaceDecl *Interface,
4425 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4426 serialization::GlobalDeclID InterfaceID,
4427 unsigned PreviousGeneration)
4428 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4429 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4430 // Populate the name -> category map with the set of known categories.
4431 for (auto *Cat : Interface->known_categories()) {
4432 if (Cat->getDeclName())
4433 NameCategoryMap[Cat->getDeclName()] = Cat;
4434
4435 // Keep track of the tail of the category list.
4436 Tail = Cat;
4437 }
4438 }
4439
4440 bool operator()(ModuleFile &M) {
4441 // If we've loaded all of the category information we care about from
4442 // this module file, we're done.
4443 if (M.Generation <= PreviousGeneration)
4444 return true;
4445
4446 // Map global ID of the definition down to the local ID used in this
4447 // module file. If there is no such mapping, we'll find nothing here
4448 // (or in any module it imports).
4449 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4450 if (!LocalID)
4451 return true;
4452
4453 // Perform a binary search to find the local redeclarations for this
4454 // declaration (if any).
4455 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4456 const ObjCCategoriesInfo *Result
4457 = std::lower_bound(M.ObjCCategoriesMap,
4458 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4459 Compare);
4460 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4461 Result->DefinitionID != LocalID) {
4462 // We didn't find anything. If the class definition is in this module
4463 // file, then the module files it depends on cannot have any categories,
4464 // so suppress further lookup.
4465 return Reader.isDeclIDFromModule(InterfaceID, M);
4466 }
4467
4468 // We found something. Dig out all of the categories.
4469 unsigned Offset = Result->Offset;
4470 unsigned N = M.ObjCCategories[Offset];
4471 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4472 for (unsigned I = 0; I != N; ++I)
4473 add(cast_or_null<ObjCCategoryDecl>(
4474 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4475 return true;
4476 }
4477 };
4478
4479} // namespace
4480
4481void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4482 ObjCInterfaceDecl *D,
4483 unsigned PreviousGeneration) {
4484 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4485 PreviousGeneration);
4486 ModuleMgr.visit(Visitor);
4487}
4488
4489template<typename DeclT, typename Fn>
4490static void forAllLaterRedecls(DeclT *D, Fn F) {
4491 F(D);
4492
4493 // Check whether we've already merged D into its redeclaration chain.
4494 // MostRecent may or may not be nullptr if D has not been merged. If
4495 // not, walk the merged redecl chain and see if it's there.
4496 auto *MostRecent = D->getMostRecentDecl();
4497 bool Found = false;
4498 for (auto *Redecl = MostRecent; Redecl && !Found;
4499 Redecl = Redecl->getPreviousDecl())
4500 Found = (Redecl == D);
4501
4502 // If this declaration is merged, apply the functor to all later decls.
4503 if (Found) {
4504 for (auto *Redecl = MostRecent; Redecl != D;
4505 Redecl = Redecl->getPreviousDecl())
4506 F(Redecl);
4507 }
4508}
4509
4510void ASTDeclReader::UpdateDecl(Decl *D,
4511 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4512 while (Record.getIdx() < Record.size()) {
4513 switch ((DeclUpdateKind)Record.readInt()) {
4514 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4515 auto *RD = cast<CXXRecordDecl>(D);
4516 // FIXME: If we also have an update record for instantiating the
4517 // definition of D, we need that to happen before we get here.
4518 Decl *MD = Record.readDecl();
4519 assert(MD && "couldn't read decl from update record")(static_cast <bool> (MD && "couldn't read decl from update record"
) ? void (0) : __assert_fail ("MD && \"couldn't read decl from update record\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4519, __extension__
__PRETTY_FUNCTION__))
;
4520 // FIXME: We should call addHiddenDecl instead, to add the member
4521 // to its DeclContext.
4522 RD->addedMember(MD);
4523 break;
4524 }
4525
4526 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4527 // It will be added to the template's lazy specialization set.
4528 PendingLazySpecializationIDs.push_back(readDeclID());
4529 break;
4530
4531 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4532 auto *Anon = readDeclAs<NamespaceDecl>();
4533
4534 // Each module has its own anonymous namespace, which is disjoint from
4535 // any other module's anonymous namespaces, so don't attach the anonymous
4536 // namespace at all.
4537 if (!Record.isModule()) {
4538 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4539 TU->setAnonymousNamespace(Anon);
4540 else
4541 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4542 }
4543 break;
4544 }
4545
4546 case UPD_CXX_ADDED_VAR_DEFINITION: {
4547 auto *VD = cast<VarDecl>(D);
4548 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4549 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4550 uint64_t Val = Record.readInt();
4551 if (Val && !VD->getInit()) {
4552 VD->setInit(Record.readExpr());
4553 if (Val != 1) {
4554 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4555 Eval->HasConstantInitialization = (Val & 2) != 0;
4556 Eval->HasConstantDestruction = (Val & 4) != 0;
4557 }
4558 }
4559 break;
4560 }
4561
4562 case UPD_CXX_POINT_OF_INSTANTIATION: {
4563 SourceLocation POI = Record.readSourceLocation();
4564 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4565 VTSD->setPointOfInstantiation(POI);
4566 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4567 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4568 } else {
4569 auto *FD = cast<FunctionDecl>(D);
4570 if (auto *FTSInfo = FD->TemplateOrSpecialization
4571 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4572 FTSInfo->setPointOfInstantiation(POI);
4573 else
4574 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4575 ->setPointOfInstantiation(POI);
4576 }
4577 break;
4578 }
4579
4580 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4581 auto *Param = cast<ParmVarDecl>(D);
4582
4583 // We have to read the default argument regardless of whether we use it
4584 // so that hypothetical further update records aren't messed up.
4585 // TODO: Add a function to skip over the next expr record.
4586 auto *DefaultArg = Record.readExpr();
4587
4588 // Only apply the update if the parameter still has an uninstantiated
4589 // default argument.
4590 if (Param->hasUninstantiatedDefaultArg())
4591 Param->setDefaultArg(DefaultArg);
4592 break;
4593 }
4594
4595 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4596 auto *FD = cast<FieldDecl>(D);
4597 auto *DefaultInit = Record.readExpr();
4598
4599 // Only apply the update if the field still has an uninstantiated
4600 // default member initializer.
4601 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4602 if (DefaultInit)
4603 FD->setInClassInitializer(DefaultInit);
4604 else
4605 // Instantiation failed. We can get here if we serialized an AST for
4606 // an invalid program.
4607 FD->removeInClassInitializer();
4608 }
4609 break;
4610 }
4611
4612 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4613 auto *FD = cast<FunctionDecl>(D);
4614 if (Reader.PendingBodies[FD]) {
4615 // FIXME: Maybe check for ODR violations.
4616 // It's safe to stop now because this update record is always last.
4617 return;
4618 }
4619
4620 if (Record.readInt()) {
4621 // Maintain AST consistency: any later redeclarations of this function
4622 // are inline if this one is. (We might have merged another declaration
4623 // into this one.)
4624 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4625 FD->setImplicitlyInline();
4626 });
4627 }
4628 FD->setInnerLocStart(readSourceLocation());
4629 ReadFunctionDefinition(FD);
4630 assert(Record.getIdx() == Record.size() && "lazy body must be last")(static_cast <bool> (Record.getIdx() == Record.size() &&
"lazy body must be last") ? void (0) : __assert_fail ("Record.getIdx() == Record.size() && \"lazy body must be last\""
, "clang/lib/Serialization/ASTReaderDecl.cpp", 4630, __extension__
__PRETTY_FUNCTION__))
;
4631 break;
4632 }
4633
4634 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4635 auto *RD = cast<CXXRecordDecl>(D);
4636 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4637 bool HadRealDefinition =
4638 OldDD && (OldDD->Definition != RD ||
4639 !Reader.PendingFakeDefinitionData.count(OldDD));
4640 RD->setParamDestroyedInCallee(Record.readInt());
4641 RD->setArgPassingRestrictions(
4642 (RecordDecl::ArgPassingKind)Record.readInt());
4643 ReadCXXRecordDefinition(RD, /*Update*/true);
4644
4645 // Visible update is handled separately.
4646 uint64_t LexicalOffset = ReadLocalOffset();
4647 if (!HadRealDefinition && LexicalOffset) {
4648 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4649 Reader.PendingFakeDefinitionData.erase(OldDD);
4650 }
4651
4652 auto TSK = (TemplateSpecializationKind)Record.readInt();
4653 SourceLocation POI = readSourceLocation();
4654 if (MemberSpecializationInfo *MSInfo =
4655 RD->getMemberSpecializationInfo()) {
4656 MSInfo->setTemplateSpecializationKind(TSK);
4657 MSInfo->setPointOfInstantiation(POI);
4658 } else {
4659 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4660 Spec->setTemplateSpecializationKind(TSK);
4661 Spec->setPointOfInstantiation(POI);
4662
4663 if (Record.readInt()) {
4664 auto *PartialSpec =
4665 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4666 SmallVector<TemplateArgument, 8> TemplArgs;
4667 Record.readTemplateArgumentList(TemplArgs);
4668 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4669 Reader.getContext(), TemplArgs);
4670
4671 // FIXME: If we already have a partial specialization set,
4672 // check that it matches.
4673 if (!Spec->getSpecializedTemplateOrPartial()
4674 .is<ClassTemplatePartialSpecializationDecl *>())
4675 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4676 }
4677 }
4678
4679 RD->setTagKind((TagTypeKind)Record.readInt());
4680 RD->setLocation(readSourceLocation());
4681 RD->setLocStart(readSourceLocation());
4682 RD->setBraceRange(readSourceRange());
4683
4684 if (Record.readInt()) {
4685 AttrVec Attrs;
4686 Record.readAttributes(Attrs);
4687 // If the declaration already has attributes, we assume that some other
4688 // AST file already loaded them.
4689 if (!D->hasAttrs())
4690 D->setAttrsImpl(Attrs, Reader.getContext());
4691 }
4692 break;
4693 }
4694
4695 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4696 // Set the 'operator delete' directly to avoid emitting another update
4697 // record.
4698 auto *Del = readDeclAs<FunctionDecl>();
4699 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4700 auto *ThisArg = Record.readExpr();
4701 // FIXME: Check consistency if we have an old and new operator delete.
4702 if (!First->OperatorDelete) {
4703 First->OperatorDelete = Del;
4704 First->OperatorDeleteThisArg = ThisArg;
4705 }
4706 break;
4707 }
4708
4709 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4710 SmallVector<QualType, 8> ExceptionStorage;
4711 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4712
4713 // Update this declaration's exception specification, if needed.
4714 auto *FD = cast<FunctionDecl>(D);
4715 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4716 // FIXME: If the exception specification is already present, check that it
4717 // matches.
4718 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4719 FD->setType(Reader.getContext().getFunctionType(
4720 FPT->getReturnType(), FPT->getParamTypes(),
4721 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4722
4723 // When we get to the end of deserializing, see if there are other decls
4724 // that we need to propagate this exception specification onto.
4725 Reader.PendingExceptionSpecUpdates.insert(
4726 std::make_pair(FD->getCanonicalDecl(), FD));
4727 }
4728 break;
4729 }
4730
4731 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4732 auto *FD = cast<FunctionDecl>(D);
4733 QualType DeducedResultType = Record.readType();
4734 Reader.PendingDeducedTypeUpdates.insert(
4735 {FD->getCanonicalDecl(), DeducedResultType});
4736 break;
4737 }
4738
4739 case UPD_DECL_MARKED_USED:
4740 // Maintain AST consistency: any later redeclarations are used too.
4741 D->markUsed(Reader.getContext());
4742 break;
4743
4744 case UPD_MANGLING_NUMBER:
4745 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4746 Record.readInt());
4747 break;
4748
4749 case UPD_STATIC_LOCAL_NUMBER:
4750 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4751 Record.readInt());
4752 break;
4753
4754 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4755 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4756 Reader.getContext(), readSourceRange(),
4757 AttributeCommonInfo::AS_Pragma));
4758 break;
4759
4760 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4761 auto AllocatorKind =
4762 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4763 Expr *Allocator = Record.readExpr();
4764 Expr *Alignment = Record.readExpr();
4765 SourceRange SR = readSourceRange();
4766 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4767 Reader.getContext(), AllocatorKind, Allocator, Alignment, SR,
4768 AttributeCommonInfo::AS_Pragma));
4769 break;
4770 }
4771
4772 case UPD_DECL_EXPORTED: {
4773 unsigned SubmoduleID = readSubmoduleID();
4774 auto *Exported = cast<NamedDecl>(D);
4775 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4776 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4777 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4778 break;
4779 }
4780
4781 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4782 auto MapType = Record.readEnum<OMPDeclareTargetDeclAttr::MapTypeTy>();
4783 auto DevType = Record.readEnum<OMPDeclareTargetDeclAttr::DevTypeTy>();
4784 Expr *IndirectE = Record.readExpr();
4785 bool Indirect = Record.readBool();
4786 unsigned Level = Record.readInt();
4787 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4788 Reader.getContext(), MapType, DevType, IndirectE, Indirect, Level,
4789 readSourceRange(), AttributeCommonInfo::AS_Pragma));
4790 break;
4791 }
4792
4793 case UPD_ADDED_ATTR_TO_RECORD:
4794 AttrVec Attrs;
4795 Record.readAttributes(Attrs);
4796 assert(Attrs.size() == 1)(static_cast <bool> (Attrs.size() == 1) ? void (0) : __assert_fail
("Attrs.size() == 1", "clang/lib/Serialization/ASTReaderDecl.cpp"
, 4796, __extension__ __PRETTY_FUNCTION__))
;
4797 D->addAttr(Attrs[0]);
4798 break;
4799 }
4800 }
4801}