Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

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