Bug Summary

File:tools/clang/include/clang/AST/DeclTemplate.h
Warning:line 1821, column 31
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')

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-eagerly-assume -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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Serialization -I /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn337204/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn337204/build-llvm/tools/clang/lib/Serialization -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-07-17-043059-5239-1 -x c++ /build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Serialization/ASTReaderDecl.cpp

/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/lib/Serialization/ASTReaderDecl.cpp

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

/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h

1//===- DeclTemplate.h - Classes for representing C++ templates --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10/// \file
11/// Defines the C++ template declaration subclasses.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_AST_DECLTEMPLATE_H
16#define LLVM_CLANG_AST_DECLTEMPLATE_H
17
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclBase.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclarationName.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/TemplateBase.h"
24#include "clang/AST/Type.h"
25#include "clang/Basic/LLVM.h"
26#include "clang/Basic/SourceLocation.h"
27#include "clang/Basic/Specifiers.h"
28#include "llvm/ADT/ArrayRef.h"
29#include "llvm/ADT/FoldingSet.h"
30#include "llvm/ADT/PointerIntPair.h"
31#include "llvm/ADT/PointerUnion.h"
32#include "llvm/ADT/iterator.h"
33#include "llvm/ADT/iterator_range.h"
34#include "llvm/Support/Casting.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/TrailingObjects.h"
37#include <cassert>
38#include <cstddef>
39#include <cstdint>
40#include <iterator>
41#include <utility>
42
43namespace clang {
44
45enum BuiltinTemplateKind : int;
46class ClassTemplateDecl;
47class ClassTemplatePartialSpecializationDecl;
48class Expr;
49class FunctionTemplateDecl;
50class IdentifierInfo;
51class NonTypeTemplateParmDecl;
52class TemplateDecl;
53class TemplateTemplateParmDecl;
54class TemplateTypeParmDecl;
55class UnresolvedSetImpl;
56class VarTemplateDecl;
57class VarTemplatePartialSpecializationDecl;
58
59/// Stores a template parameter of any kind.
60using TemplateParameter =
61 llvm::PointerUnion3<TemplateTypeParmDecl *, NonTypeTemplateParmDecl *,
62 TemplateTemplateParmDecl *>;
63
64NamedDecl *getAsNamedDecl(TemplateParameter P);
65
66/// Stores a list of template parameters for a TemplateDecl and its
67/// derived classes.
68class TemplateParameterList final
69 : private llvm::TrailingObjects<TemplateParameterList, NamedDecl *,
70 Expr *> {
71 /// The location of the 'template' keyword.
72 SourceLocation TemplateLoc;
73
74 /// The locations of the '<' and '>' angle brackets.
75 SourceLocation LAngleLoc, RAngleLoc;
76
77 /// The number of template parameters in this template
78 /// parameter list.
79 unsigned NumParams : 30;
80
81 /// Whether this template parameter list contains an unexpanded parameter
82 /// pack.
83 unsigned ContainsUnexpandedParameterPack : 1;
84
85 /// Whether this template parameter list has an associated requires-clause
86 unsigned HasRequiresClause : 1;
87
88protected:
89 TemplateParameterList(SourceLocation TemplateLoc, SourceLocation LAngleLoc,
90 ArrayRef<NamedDecl *> Params, SourceLocation RAngleLoc,
91 Expr *RequiresClause);
92
93 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
94 return NumParams;
95 }
96
97 size_t numTrailingObjects(OverloadToken<Expr *>) const {
98 return HasRequiresClause;
99 }
100
101public:
102 template <size_t N, bool HasRequiresClause>
103 friend class FixedSizeTemplateParameterListStorage;
104 friend TrailingObjects;
105
106 static TemplateParameterList *Create(const ASTContext &C,
107 SourceLocation TemplateLoc,
108 SourceLocation LAngleLoc,
109 ArrayRef<NamedDecl *> Params,
110 SourceLocation RAngleLoc,
111 Expr *RequiresClause);
112
113 /// Iterates through the template parameters in this list.
114 using iterator = NamedDecl **;
115
116 /// Iterates through the template parameters in this list.
117 using const_iterator = NamedDecl * const *;
118
119 iterator begin() { return getTrailingObjects<NamedDecl *>(); }
120 const_iterator begin() const { return getTrailingObjects<NamedDecl *>(); }
121 iterator end() { return begin() + NumParams; }
122 const_iterator end() const { return begin() + NumParams; }
123
124 unsigned size() const { return NumParams; }
125
126 ArrayRef<NamedDecl*> asArray() {
127 return llvm::makeArrayRef(begin(), end());
128 }
129 ArrayRef<const NamedDecl*> asArray() const {
130 return llvm::makeArrayRef(begin(), size());
131 }
132
133 NamedDecl* getParam(unsigned Idx) {
134 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 134, __extension__ __PRETTY_FUNCTION__))
;
135 return begin()[Idx];
136 }
137 const NamedDecl* getParam(unsigned Idx) const {
138 assert(Idx < size() && "Template parameter index out-of-range")(static_cast <bool> (Idx < size() && "Template parameter index out-of-range"
) ? void (0) : __assert_fail ("Idx < size() && \"Template parameter index out-of-range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 138, __extension__ __PRETTY_FUNCTION__))
;
139 return begin()[Idx];
140 }
141
142 /// Returns the minimum number of arguments needed to form a
143 /// template specialization.
144 ///
145 /// This may be fewer than the number of template parameters, if some of
146 /// the parameters have default arguments or if there is a parameter pack.
147 unsigned getMinRequiredArguments() const;
148
149 /// Get the depth of this template parameter list in the set of
150 /// template parameter lists.
151 ///
152 /// The first template parameter list in a declaration will have depth 0,
153 /// the second template parameter list will have depth 1, etc.
154 unsigned getDepth() const;
155
156 /// Determine whether this template parameter list contains an
157 /// unexpanded parameter pack.
158 bool containsUnexpandedParameterPack() const {
159 return ContainsUnexpandedParameterPack;
160 }
161
162 /// The constraint-expression of the associated requires-clause.
163 Expr *getRequiresClause() {
164 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
165 }
166
167 /// The constraint-expression of the associated requires-clause.
168 const Expr *getRequiresClause() const {
169 return HasRequiresClause ? *getTrailingObjects<Expr *>() : nullptr;
170 }
171
172 SourceLocation getTemplateLoc() const { return TemplateLoc; }
173 SourceLocation getLAngleLoc() const { return LAngleLoc; }
174 SourceLocation getRAngleLoc() const { return RAngleLoc; }
175
176 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
177 return SourceRange(TemplateLoc, RAngleLoc);
178 }
179
180public:
181 // FIXME: workaround for MSVC 2013; remove when no longer needed
182 using FixedSizeStorageOwner = TrailingObjects::FixedSizeStorageOwner;
183};
184
185/// Stores a list of template parameters and the associated
186/// requires-clause (if any) for a TemplateDecl and its derived classes.
187/// Suitable for creating on the stack.
188template <size_t N, bool HasRequiresClause>
189class FixedSizeTemplateParameterListStorage
190 : public TemplateParameterList::FixedSizeStorageOwner {
191 typename TemplateParameterList::FixedSizeStorage<
192 NamedDecl *, Expr *>::with_counts<
193 N, HasRequiresClause ? 1u : 0u
194 >::type storage;
195
196public:
197 FixedSizeTemplateParameterListStorage(SourceLocation TemplateLoc,
198 SourceLocation LAngleLoc,
199 ArrayRef<NamedDecl *> Params,
200 SourceLocation RAngleLoc,
201 Expr *RequiresClause)
202 : FixedSizeStorageOwner(
203 (assert(N == Params.size())(static_cast <bool> (N == Params.size()) ? void (0) : __assert_fail
("N == Params.size()", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 203, __extension__ __PRETTY_FUNCTION__))
,
204 assert(HasRequiresClause == static_cast<bool>(RequiresClause))(static_cast <bool> (HasRequiresClause == static_cast<
bool>(RequiresClause)) ? void (0) : __assert_fail ("HasRequiresClause == static_cast<bool>(RequiresClause)"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 204, __extension__ __PRETTY_FUNCTION__))
,
205 new (static_cast<void *>(&storage)) TemplateParameterList(
206 TemplateLoc, LAngleLoc, Params, RAngleLoc, RequiresClause))) {}
207};
208
209/// A template argument list.
210class TemplateArgumentList final
211 : private llvm::TrailingObjects<TemplateArgumentList, TemplateArgument> {
212 /// The template argument list.
213 const TemplateArgument *Arguments;
214
215 /// The number of template arguments in this template
216 /// argument list.
217 unsigned NumArguments;
218
219 // Constructs an instance with an internal Argument list, containing
220 // a copy of the Args array. (Called by CreateCopy)
221 TemplateArgumentList(ArrayRef<TemplateArgument> Args);
222
223public:
224 friend TrailingObjects;
225
226 TemplateArgumentList(const TemplateArgumentList &) = delete;
227 TemplateArgumentList &operator=(const TemplateArgumentList &) = delete;
228
229 /// Type used to indicate that the template argument list itself is a
230 /// stack object. It does not own its template arguments.
231 enum OnStackType { OnStack };
232
233 /// Create a new template argument list that copies the given set of
234 /// template arguments.
235 static TemplateArgumentList *CreateCopy(ASTContext &Context,
236 ArrayRef<TemplateArgument> Args);
237
238 /// Construct a new, temporary template argument list on the stack.
239 ///
240 /// The template argument list does not own the template arguments
241 /// provided.
242 explicit TemplateArgumentList(OnStackType, ArrayRef<TemplateArgument> Args)
243 : Arguments(Args.data()), NumArguments(Args.size()) {}
244
245 /// Produces a shallow copy of the given template argument list.
246 ///
247 /// This operation assumes that the input argument list outlives it.
248 /// This takes the list as a pointer to avoid looking like a copy
249 /// constructor, since this really really isn't safe to use that
250 /// way.
251 explicit TemplateArgumentList(const TemplateArgumentList *Other)
252 : Arguments(Other->data()), NumArguments(Other->size()) {}
253
254 /// Retrieve the template argument at a given index.
255 const TemplateArgument &get(unsigned Idx) const {
256 assert(Idx < NumArguments && "Invalid template argument index")(static_cast <bool> (Idx < NumArguments && "Invalid template argument index"
) ? void (0) : __assert_fail ("Idx < NumArguments && \"Invalid template argument index\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 256, __extension__ __PRETTY_FUNCTION__))
;
257 return data()[Idx];
258 }
259
260 /// Retrieve the template argument at a given index.
261 const TemplateArgument &operator[](unsigned Idx) const { return get(Idx); }
262
263 /// Produce this as an array ref.
264 ArrayRef<TemplateArgument> asArray() const {
265 return llvm::makeArrayRef(data(), size());
266 }
267
268 /// Retrieve the number of template arguments in this
269 /// template argument list.
270 unsigned size() const { return NumArguments; }
271
272 /// Retrieve a pointer to the template argument list.
273 const TemplateArgument *data() const { return Arguments; }
274};
275
276void *allocateDefaultArgStorageChain(const ASTContext &C);
277
278/// Storage for a default argument. This is conceptually either empty, or an
279/// argument value, or a pointer to a previous declaration that had a default
280/// argument.
281///
282/// However, this is complicated by modules: while we require all the default
283/// arguments for a template to be equivalent, there may be more than one, and
284/// we need to track all the originating parameters to determine if the default
285/// argument is visible.
286template<typename ParmDecl, typename ArgType>
287class DefaultArgStorage {
288 /// Storage for both the value *and* another parameter from which we inherit
289 /// the default argument. This is used when multiple default arguments for a
290 /// parameter are merged together from different modules.
291 struct Chain {
292 ParmDecl *PrevDeclWithDefaultArg;
293 ArgType Value;
294 };
295 static_assert(sizeof(Chain) == sizeof(void *) * 2,
296 "non-pointer argument type?");
297
298 llvm::PointerUnion3<ArgType, ParmDecl*, Chain*> ValueOrInherited;
299
300 static ParmDecl *getParmOwningDefaultArg(ParmDecl *Parm) {
301 const DefaultArgStorage &Storage = Parm->getDefaultArgStorage();
302 if (auto *Prev = Storage.ValueOrInherited.template dyn_cast<ParmDecl *>())
303 Parm = Prev;
304 assert(!Parm->getDefaultArgStorage()(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
305 .ValueOrInherited.template is<ParmDecl *>() &&(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
306 "should only be one level of indirection")(static_cast <bool> (!Parm->getDefaultArgStorage() .
ValueOrInherited.template is<ParmDecl *>() && "should only be one level of indirection"
) ? void (0) : __assert_fail ("!Parm->getDefaultArgStorage() .ValueOrInherited.template is<ParmDecl *>() && \"should only be one level of indirection\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 306, __extension__ __PRETTY_FUNCTION__))
;
307 return Parm;
308 }
309
310public:
311 DefaultArgStorage() : ValueOrInherited(ArgType()) {}
312
313 /// Determine whether there is a default argument for this parameter.
314 bool isSet() const { return !ValueOrInherited.isNull(); }
315
316 /// Determine whether the default argument for this parameter was inherited
317 /// from a previous declaration of the same entity.
318 bool isInherited() const { return ValueOrInherited.template is<ParmDecl*>(); }
319
320 /// Get the default argument's value. This does not consider whether the
321 /// default argument is visible.
322 ArgType get() const {
323 const DefaultArgStorage *Storage = this;
324 if (const auto *Prev = ValueOrInherited.template dyn_cast<ParmDecl *>())
325 Storage = &Prev->getDefaultArgStorage();
326 if (const auto *C = Storage->ValueOrInherited.template dyn_cast<Chain *>())
327 return C->Value;
328 return Storage->ValueOrInherited.template get<ArgType>();
329 }
330
331 /// Get the parameter from which we inherit the default argument, if any.
332 /// This is the parameter on which the default argument was actually written.
333 const ParmDecl *getInheritedFrom() const {
334 if (const auto *D = ValueOrInherited.template dyn_cast<ParmDecl *>())
335 return D;
336 if (const auto *C = ValueOrInherited.template dyn_cast<Chain *>())
337 return C->PrevDeclWithDefaultArg;
338 return nullptr;
339 }
340
341 /// Set the default argument.
342 void set(ArgType Arg) {
343 assert(!isSet() && "default argument already set")(static_cast <bool> (!isSet() && "default argument already set"
) ? void (0) : __assert_fail ("!isSet() && \"default argument already set\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 343, __extension__ __PRETTY_FUNCTION__))
;
344 ValueOrInherited = Arg;
345 }
346
347 /// Set that the default argument was inherited from another parameter.
348 void setInherited(const ASTContext &C, ParmDecl *InheritedFrom) {
349 assert(!isInherited() && "default argument already inherited")(static_cast <bool> (!isInherited() && "default argument already inherited"
) ? void (0) : __assert_fail ("!isInherited() && \"default argument already inherited\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 349, __extension__ __PRETTY_FUNCTION__))
;
350 InheritedFrom = getParmOwningDefaultArg(InheritedFrom);
351 if (!isSet())
352 ValueOrInherited = InheritedFrom;
353 else
354 ValueOrInherited = new (allocateDefaultArgStorageChain(C))
355 Chain{InheritedFrom, ValueOrInherited.template get<ArgType>()};
356 }
357
358 /// Remove the default argument, even if it was inherited.
359 void clear() {
360 ValueOrInherited = ArgType();
361 }
362};
363
364//===----------------------------------------------------------------------===//
365// Kinds of Templates
366//===----------------------------------------------------------------------===//
367
368/// Stores the template parameter list and associated constraints for
369/// \c TemplateDecl objects that track associated constraints.
370class ConstrainedTemplateDeclInfo {
371 friend TemplateDecl;
372
373public:
374 ConstrainedTemplateDeclInfo() = default;
375
376 TemplateParameterList *getTemplateParameters() const {
377 return TemplateParams;
378 }
379
380 Expr *getAssociatedConstraints() const { return AssociatedConstraints; }
381
382protected:
383 void setTemplateParameters(TemplateParameterList *TParams) {
384 TemplateParams = TParams;
385 }
386
387 void setAssociatedConstraints(Expr *AC) { AssociatedConstraints = AC; }
388
389 TemplateParameterList *TemplateParams = nullptr;
390 Expr *AssociatedConstraints = nullptr;
391};
392
393
394/// The base class of all kinds of template declarations (e.g.,
395/// class, function, etc.).
396///
397/// The TemplateDecl class stores the list of template parameters and a
398/// reference to the templated scoped declaration: the underlying AST node.
399class TemplateDecl : public NamedDecl {
400 void anchor() override;
401
402protected:
403 // Construct a template decl with the given name and parameters.
404 // Used when there is no templated element (e.g., for tt-params).
405 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
406 SourceLocation L, DeclarationName Name,
407 TemplateParameterList *Params)
408 : NamedDecl(DK, DC, L, Name), TemplatedDecl(nullptr),
409 TemplateParams(CTDI) {
410 this->setTemplateParameters(Params);
411 }
412
413 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
414 TemplateParameterList *Params)
415 : TemplateDecl(nullptr, DK, DC, L, Name, Params) {}
416
417 // Construct a template decl with name, parameters, and templated element.
418 TemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK, DeclContext *DC,
419 SourceLocation L, DeclarationName Name,
420 TemplateParameterList *Params, NamedDecl *Decl)
421 : NamedDecl(DK, DC, L, Name), TemplatedDecl(Decl),
422 TemplateParams(CTDI) {
423 this->setTemplateParameters(Params);
424 }
425
426 TemplateDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name,
427 TemplateParameterList *Params, NamedDecl *Decl)
428 : TemplateDecl(nullptr, DK, DC, L, Name, Params, Decl) {}
429
430public:
431 /// Get the list of template parameters
432 TemplateParameterList *getTemplateParameters() const {
433 const auto *const CTDI =
434 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
435 return CTDI ? CTDI->getTemplateParameters()
436 : TemplateParams.get<TemplateParameterList *>();
437 }
438
439 /// Get the constraint-expression from the associated requires-clause (if any)
440 const Expr *getRequiresClause() const {
441 const TemplateParameterList *const TP = getTemplateParameters();
442 return TP ? TP->getRequiresClause() : nullptr;
443 }
444
445 Expr *getAssociatedConstraints() const {
446 const auto *const C = cast<TemplateDecl>(getCanonicalDecl());
447 const auto *const CTDI =
448 C->TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>();
449 return CTDI ? CTDI->getAssociatedConstraints() : nullptr;
450 }
451
452 /// Get the underlying, templated declaration.
453 NamedDecl *getTemplatedDecl() const { return TemplatedDecl; }
454
455 // Implement isa/cast/dyncast/etc.
456 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
457
458 static bool classofKind(Kind K) {
459 return K >= firstTemplate && K <= lastTemplate;
460 }
461
462 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
463 return SourceRange(getTemplateParameters()->getTemplateLoc(),
464 TemplatedDecl->getSourceRange().getEnd());
465 }
466
467protected:
468 NamedDecl *TemplatedDecl;
469
470 /// The template parameter list and optional requires-clause
471 /// associated with this declaration; alternatively, a
472 /// \c ConstrainedTemplateDeclInfo if the associated constraints of the
473 /// template are being tracked by this particular declaration.
474 llvm::PointerUnion<TemplateParameterList *,
475 ConstrainedTemplateDeclInfo *>
476 TemplateParams;
477
478 void setTemplateParameters(TemplateParameterList *TParams) {
479 if (auto *const CTDI =
480 TemplateParams.dyn_cast<ConstrainedTemplateDeclInfo *>()) {
481 CTDI->setTemplateParameters(TParams);
482 } else {
483 TemplateParams = TParams;
484 }
485 }
486
487 void setAssociatedConstraints(Expr *AC) {
488 assert(isCanonicalDecl() &&(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 489, __extension__ __PRETTY_FUNCTION__))
489 "Attaching associated constraints to non-canonical Decl")(static_cast <bool> (isCanonicalDecl() && "Attaching associated constraints to non-canonical Decl"
) ? void (0) : __assert_fail ("isCanonicalDecl() && \"Attaching associated constraints to non-canonical Decl\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 489, __extension__ __PRETTY_FUNCTION__))
;
490 TemplateParams.get<ConstrainedTemplateDeclInfo *>()
491 ->setAssociatedConstraints(AC);
492 }
493
494public:
495 /// Initialize the underlying templated declaration and
496 /// template parameters.
497 void init(NamedDecl *templatedDecl, TemplateParameterList* templateParams) {
498 assert(!TemplatedDecl && "TemplatedDecl already set!")(static_cast <bool> (!TemplatedDecl && "TemplatedDecl already set!"
) ? void (0) : __assert_fail ("!TemplatedDecl && \"TemplatedDecl already set!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 498, __extension__ __PRETTY_FUNCTION__))
;
499 assert(!TemplateParams && "TemplateParams already set!")(static_cast <bool> (!TemplateParams && "TemplateParams already set!"
) ? void (0) : __assert_fail ("!TemplateParams && \"TemplateParams already set!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 499, __extension__ __PRETTY_FUNCTION__))
;
500 TemplatedDecl = templatedDecl;
501 TemplateParams = templateParams;
502 }
503};
504
505/// Provides information about a function template specialization,
506/// which is a FunctionDecl that has been explicitly specialization or
507/// instantiated from a function template.
508class FunctionTemplateSpecializationInfo : public llvm::FoldingSetNode {
509 FunctionTemplateSpecializationInfo(FunctionDecl *FD,
510 FunctionTemplateDecl *Template,
511 TemplateSpecializationKind TSK,
512 const TemplateArgumentList *TemplateArgs,
513 const ASTTemplateArgumentListInfo *TemplateArgsAsWritten,
514 SourceLocation POI)
515 : Function(FD), Template(Template, TSK - 1),
516 TemplateArguments(TemplateArgs),
517 TemplateArgumentsAsWritten(TemplateArgsAsWritten),
518 PointOfInstantiation(POI) {}
519
520public:
521 static FunctionTemplateSpecializationInfo *
522 Create(ASTContext &C, FunctionDecl *FD, FunctionTemplateDecl *Template,
523 TemplateSpecializationKind TSK,
524 const TemplateArgumentList *TemplateArgs,
525 const TemplateArgumentListInfo *TemplateArgsAsWritten,
526 SourceLocation POI);
527
528 /// The function template specialization that this structure
529 /// describes.
530 FunctionDecl *Function;
531
532 /// The function template from which this function template
533 /// specialization was generated.
534 ///
535 /// The two bits contain the top 4 values of TemplateSpecializationKind.
536 llvm::PointerIntPair<FunctionTemplateDecl *, 2> Template;
537
538 /// The template arguments used to produce the function template
539 /// specialization from the function template.
540 const TemplateArgumentList *TemplateArguments;
541
542 /// The template arguments as written in the sources, if provided.
543 const ASTTemplateArgumentListInfo *TemplateArgumentsAsWritten;
544
545 /// The point at which this function template specialization was
546 /// first instantiated.
547 SourceLocation PointOfInstantiation;
548
549 /// Retrieve the template from which this function was specialized.
550 FunctionTemplateDecl *getTemplate() const { return Template.getPointer(); }
551
552 /// Determine what kind of template specialization this is.
553 TemplateSpecializationKind getTemplateSpecializationKind() const {
554 return (TemplateSpecializationKind)(Template.getInt() + 1);
555 }
556
557 bool isExplicitSpecialization() const {
558 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
559 }
560
561 /// True if this declaration is an explicit specialization,
562 /// explicit instantiation declaration, or explicit instantiation
563 /// definition.
564 bool isExplicitInstantiationOrSpecialization() const {
565 return isTemplateExplicitInstantiationOrSpecialization(
566 getTemplateSpecializationKind());
567 }
568
569 /// Set the template specialization kind.
570 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
571 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 572, __extension__ __PRETTY_FUNCTION__))
572 "Cannot encode TSK_Undeclared for a function template specialization")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode TSK_Undeclared for a function template specialization"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode TSK_Undeclared for a function template specialization\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 572, __extension__ __PRETTY_FUNCTION__))
;
573 Template.setInt(TSK - 1);
574 }
575
576 /// Retrieve the first point of instantiation of this function
577 /// template specialization.
578 ///
579 /// The point of instantiation may be an invalid source location if this
580 /// function has yet to be instantiated.
581 SourceLocation getPointOfInstantiation() const {
582 return PointOfInstantiation;
583 }
584
585 /// Set the (first) point of instantiation of this function template
586 /// specialization.
587 void setPointOfInstantiation(SourceLocation POI) {
588 PointOfInstantiation = POI;
589 }
590
591 void Profile(llvm::FoldingSetNodeID &ID) {
592 Profile(ID, TemplateArguments->asArray(),
593 Function->getASTContext());
594 }
595
596 static void
597 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
598 ASTContext &Context) {
599 ID.AddInteger(TemplateArgs.size());
600 for (const TemplateArgument &TemplateArg : TemplateArgs)
601 TemplateArg.Profile(ID, Context);
602 }
603};
604
605/// Provides information a specialization of a member of a class
606/// template, which may be a member function, static data member,
607/// member class or member enumeration.
608class MemberSpecializationInfo {
609 // The member declaration from which this member was instantiated, and the
610 // manner in which the instantiation occurred (in the lower two bits).
611 llvm::PointerIntPair<NamedDecl *, 2> MemberAndTSK;
612
613 // The point at which this member was first instantiated.
614 SourceLocation PointOfInstantiation;
615
616public:
617 explicit
618 MemberSpecializationInfo(NamedDecl *IF, TemplateSpecializationKind TSK,
619 SourceLocation POI = SourceLocation())
620 : MemberAndTSK(IF, TSK - 1), PointOfInstantiation(POI) {
621 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 622, __extension__ __PRETTY_FUNCTION__))
622 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 622, __extension__ __PRETTY_FUNCTION__))
;
623 }
624
625 /// Retrieve the member declaration from which this member was
626 /// instantiated.
627 NamedDecl *getInstantiatedFrom() const { return MemberAndTSK.getPointer(); }
628
629 /// Determine what kind of template specialization this is.
630 TemplateSpecializationKind getTemplateSpecializationKind() const {
631 return (TemplateSpecializationKind)(MemberAndTSK.getInt() + 1);
632 }
633
634 bool isExplicitSpecialization() const {
635 return getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
636 }
637
638 /// Set the template specialization kind.
639 void setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
640 assert(TSK != TSK_Undeclared &&(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 641, __extension__ __PRETTY_FUNCTION__))
641 "Cannot encode undeclared template specializations for members")(static_cast <bool> (TSK != TSK_Undeclared && "Cannot encode undeclared template specializations for members"
) ? void (0) : __assert_fail ("TSK != TSK_Undeclared && \"Cannot encode undeclared template specializations for members\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 641, __extension__ __PRETTY_FUNCTION__))
;
642 MemberAndTSK.setInt(TSK - 1);
643 }
644
645 /// Retrieve the first point of instantiation of this member.
646 /// If the point of instantiation is an invalid location, then this member
647 /// has not yet been instantiated.
648 SourceLocation getPointOfInstantiation() const {
649 return PointOfInstantiation;
650 }
651
652 /// Set the first point of instantiation.
653 void setPointOfInstantiation(SourceLocation POI) {
654 PointOfInstantiation = POI;
655 }
656};
657
658/// Provides information about a dependent function-template
659/// specialization declaration.
660///
661/// Since explicit function template specialization and instantiation
662/// declarations can only appear in namespace scope, and you can only
663/// specialize a member of a fully-specialized class, the only way to
664/// get one of these is in a friend declaration like the following:
665///
666/// \code
667/// template \<class T> void foo(T);
668/// template \<class T> class A {
669/// friend void foo<>(T);
670/// };
671/// \endcode
672class DependentFunctionTemplateSpecializationInfo final
673 : private llvm::TrailingObjects<DependentFunctionTemplateSpecializationInfo,
674 TemplateArgumentLoc,
675 FunctionTemplateDecl *> {
676 /// The number of potential template candidates.
677 unsigned NumTemplates;
678
679 /// The number of template arguments.
680 unsigned NumArgs;
681
682 /// The locations of the left and right angle brackets.
683 SourceRange AngleLocs;
684
685 size_t numTrailingObjects(OverloadToken<TemplateArgumentLoc>) const {
686 return NumArgs;
687 }
688 size_t numTrailingObjects(OverloadToken<FunctionTemplateDecl *>) const {
689 return NumTemplates;
690 }
691
692 DependentFunctionTemplateSpecializationInfo(
693 const UnresolvedSetImpl &Templates,
694 const TemplateArgumentListInfo &TemplateArgs);
695
696public:
697 friend TrailingObjects;
698
699 static DependentFunctionTemplateSpecializationInfo *
700 Create(ASTContext &Context, const UnresolvedSetImpl &Templates,
701 const TemplateArgumentListInfo &TemplateArgs);
702
703 /// Returns the number of function templates that this might
704 /// be a specialization of.
705 unsigned getNumTemplates() const { return NumTemplates; }
706
707 /// Returns the i'th template candidate.
708 FunctionTemplateDecl *getTemplate(unsigned I) const {
709 assert(I < getNumTemplates() && "template index out of range")(static_cast <bool> (I < getNumTemplates() &&
"template index out of range") ? void (0) : __assert_fail ("I < getNumTemplates() && \"template index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 709, __extension__ __PRETTY_FUNCTION__))
;
710 return getTrailingObjects<FunctionTemplateDecl *>()[I];
711 }
712
713 /// Returns the explicit template arguments that were given.
714 const TemplateArgumentLoc *getTemplateArgs() const {
715 return getTrailingObjects<TemplateArgumentLoc>();
716 }
717
718 /// Returns the number of explicit template arguments that were given.
719 unsigned getNumTemplateArgs() const { return NumArgs; }
720
721 /// Returns the nth template argument.
722 const TemplateArgumentLoc &getTemplateArg(unsigned I) const {
723 assert(I < getNumTemplateArgs() && "template arg index out of range")(static_cast <bool> (I < getNumTemplateArgs() &&
"template arg index out of range") ? void (0) : __assert_fail
("I < getNumTemplateArgs() && \"template arg index out of range\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 723, __extension__ __PRETTY_FUNCTION__))
;
724 return getTemplateArgs()[I];
725 }
726
727 SourceLocation getLAngleLoc() const {
728 return AngleLocs.getBegin();
729 }
730
731 SourceLocation getRAngleLoc() const {
732 return AngleLocs.getEnd();
733 }
734};
735
736/// Declaration of a redeclarable template.
737class RedeclarableTemplateDecl : public TemplateDecl,
738 public Redeclarable<RedeclarableTemplateDecl>
739{
740 using redeclarable_base = Redeclarable<RedeclarableTemplateDecl>;
741
742 RedeclarableTemplateDecl *getNextRedeclarationImpl() override {
743 return getNextRedeclaration();
744 }
745
746 RedeclarableTemplateDecl *getPreviousDeclImpl() override {
747 return getPreviousDecl();
748 }
749
750 RedeclarableTemplateDecl *getMostRecentDeclImpl() override {
751 return getMostRecentDecl();
752 }
753
754protected:
755 template <typename EntryType> struct SpecEntryTraits {
756 using DeclType = EntryType;
757
758 static DeclType *getDecl(EntryType *D) {
759 return D;
760 }
761
762 static ArrayRef<TemplateArgument> getTemplateArgs(EntryType *D) {
763 return D->getTemplateArgs().asArray();
764 }
765 };
766
767 template <typename EntryType, typename SETraits = SpecEntryTraits<EntryType>,
768 typename DeclType = typename SETraits::DeclType>
769 struct SpecIterator
770 : llvm::iterator_adaptor_base<
771 SpecIterator<EntryType, SETraits, DeclType>,
772 typename llvm::FoldingSetVector<EntryType>::iterator,
773 typename std::iterator_traits<typename llvm::FoldingSetVector<
774 EntryType>::iterator>::iterator_category,
775 DeclType *, ptrdiff_t, DeclType *, DeclType *> {
776 SpecIterator() = default;
777 explicit SpecIterator(
778 typename llvm::FoldingSetVector<EntryType>::iterator SetIter)
779 : SpecIterator::iterator_adaptor_base(std::move(SetIter)) {}
780
781 DeclType *operator*() const {
782 return SETraits::getDecl(&*this->I)->getMostRecentDecl();
783 }
784
785 DeclType *operator->() const { return **this; }
786 };
787
788 template <typename EntryType>
789 static SpecIterator<EntryType>
790 makeSpecIterator(llvm::FoldingSetVector<EntryType> &Specs, bool isEnd) {
791 return SpecIterator<EntryType>(isEnd ? Specs.end() : Specs.begin());
792 }
793
794 void loadLazySpecializationsImpl() const;
795
796 template <class EntryType> typename SpecEntryTraits<EntryType>::DeclType*
797 findSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
798 ArrayRef<TemplateArgument> Args, void *&InsertPos);
799
800 template <class Derived, class EntryType>
801 void addSpecializationImpl(llvm::FoldingSetVector<EntryType> &Specs,
802 EntryType *Entry, void *InsertPos);
803
804 struct CommonBase {
805 CommonBase() : InstantiatedFromMember(nullptr, false) {}
806
807 /// The template from which this was most
808 /// directly instantiated (or null).
809 ///
810 /// The boolean value indicates whether this template
811 /// was explicitly specialized.
812 llvm::PointerIntPair<RedeclarableTemplateDecl*, 1, bool>
813 InstantiatedFromMember;
814
815 /// If non-null, points to an array of specializations (including
816 /// partial specializations) known only by their external declaration IDs.
817 ///
818 /// The first value in the array is the number of specializations/partial
819 /// specializations that follow.
820 uint32_t *LazySpecializations = nullptr;
821 };
822
823 /// Pointer to the common data shared by all declarations of this
824 /// template.
825 mutable CommonBase *Common = nullptr;
826
827 /// Retrieves the "common" pointer shared by all (re-)declarations of
828 /// the same template. Calling this routine may implicitly allocate memory
829 /// for the common pointer.
830 CommonBase *getCommonPtr() const;
831
832 virtual CommonBase *newCommon(ASTContext &C) const = 0;
833
834 // Construct a template decl with name, parameters, and templated element.
835 RedeclarableTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, Kind DK,
836 ASTContext &C, DeclContext *DC, SourceLocation L,
837 DeclarationName Name, TemplateParameterList *Params,
838 NamedDecl *Decl)
839 : TemplateDecl(CTDI, DK, DC, L, Name, Params, Decl), redeclarable_base(C)
840 {}
841
842 RedeclarableTemplateDecl(Kind DK, ASTContext &C, DeclContext *DC,
843 SourceLocation L, DeclarationName Name,
844 TemplateParameterList *Params, NamedDecl *Decl)
845 : RedeclarableTemplateDecl(nullptr, DK, C, DC, L, Name, Params, Decl) {}
846
847public:
848 friend class ASTDeclReader;
849 friend class ASTDeclWriter;
850 friend class ASTReader;
851 template <class decl_type> friend class RedeclarableTemplate;
852
853 /// Retrieves the canonical declaration of this template.
854 RedeclarableTemplateDecl *getCanonicalDecl() override {
855 return getFirstDecl();
856 }
857 const RedeclarableTemplateDecl *getCanonicalDecl() const {
858 return getFirstDecl();
859 }
860
861 /// Determines whether this template was a specialization of a
862 /// member template.
863 ///
864 /// In the following example, the function template \c X<int>::f and the
865 /// member template \c X<int>::Inner are member specializations.
866 ///
867 /// \code
868 /// template<typename T>
869 /// struct X {
870 /// template<typename U> void f(T, U);
871 /// template<typename U> struct Inner;
872 /// };
873 ///
874 /// template<> template<typename T>
875 /// void X<int>::f(int, T);
876 /// template<> template<typename T>
877 /// struct X<int>::Inner { /* ... */ };
878 /// \endcode
879 bool isMemberSpecialization() const {
880 return getCommonPtr()->InstantiatedFromMember.getInt();
881 }
882
883 /// Note that this member template is a specialization.
884 void setMemberSpecialization() {
885 assert(getCommonPtr()->InstantiatedFromMember.getPointer() &&(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 886, __extension__ __PRETTY_FUNCTION__))
886 "Only member templates can be member template specializations")(static_cast <bool> (getCommonPtr()->InstantiatedFromMember
.getPointer() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("getCommonPtr()->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 886, __extension__ __PRETTY_FUNCTION__))
;
887 getCommonPtr()->InstantiatedFromMember.setInt(true);
888 }
889
890 /// Retrieve the member template from which this template was
891 /// instantiated, or nullptr if this template was not instantiated from a
892 /// member template.
893 ///
894 /// A template is instantiated from a member template when the member
895 /// template itself is part of a class template (or member thereof). For
896 /// example, given
897 ///
898 /// \code
899 /// template<typename T>
900 /// struct X {
901 /// template<typename U> void f(T, U);
902 /// };
903 ///
904 /// void test(X<int> x) {
905 /// x.f(1, 'a');
906 /// };
907 /// \endcode
908 ///
909 /// \c X<int>::f is a FunctionTemplateDecl that describes the function
910 /// template
911 ///
912 /// \code
913 /// template<typename U> void X<int>::f(int, U);
914 /// \endcode
915 ///
916 /// which was itself created during the instantiation of \c X<int>. Calling
917 /// getInstantiatedFromMemberTemplate() on this FunctionTemplateDecl will
918 /// retrieve the FunctionTemplateDecl for the original template \c f within
919 /// the class template \c X<T>, i.e.,
920 ///
921 /// \code
922 /// template<typename T>
923 /// template<typename U>
924 /// void X<T>::f(T, U);
925 /// \endcode
926 RedeclarableTemplateDecl *getInstantiatedFromMemberTemplate() const {
927 return getCommonPtr()->InstantiatedFromMember.getPointer();
928 }
929
930 void setInstantiatedFromMemberTemplate(RedeclarableTemplateDecl *TD) {
931 assert(!getCommonPtr()->InstantiatedFromMember.getPointer())(static_cast <bool> (!getCommonPtr()->InstantiatedFromMember
.getPointer()) ? void (0) : __assert_fail ("!getCommonPtr()->InstantiatedFromMember.getPointer()"
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 931, __extension__ __PRETTY_FUNCTION__))
;
932 getCommonPtr()->InstantiatedFromMember.setPointer(TD);
933 }
934
935 using redecl_range = redeclarable_base::redecl_range;
936 using redecl_iterator = redeclarable_base::redecl_iterator;
937
938 using redeclarable_base::redecls_begin;
939 using redeclarable_base::redecls_end;
940 using redeclarable_base::redecls;
941 using redeclarable_base::getPreviousDecl;
942 using redeclarable_base::getMostRecentDecl;
943 using redeclarable_base::isFirstDecl;
944
945 // Implement isa/cast/dyncast/etc.
946 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
947
948 static bool classofKind(Kind K) {
949 return K >= firstRedeclarableTemplate && K <= lastRedeclarableTemplate;
950 }
951};
952
953template <> struct RedeclarableTemplateDecl::
954SpecEntryTraits<FunctionTemplateSpecializationInfo> {
955 using DeclType = FunctionDecl;
956
957 static DeclType *getDecl(FunctionTemplateSpecializationInfo *I) {
958 return I->Function;
959 }
960
961 static ArrayRef<TemplateArgument>
962 getTemplateArgs(FunctionTemplateSpecializationInfo *I) {
963 return I->TemplateArguments->asArray();
964 }
965};
966
967/// Declaration of a template function.
968class FunctionTemplateDecl : public RedeclarableTemplateDecl {
969protected:
970 friend class FunctionDecl;
971
972 /// Data that is common to all of the declarations of a given
973 /// function template.
974 struct Common : CommonBase {
975 /// The function template specializations for this function
976 /// template, including explicit specializations and instantiations.
977 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> Specializations;
978
979 /// The set of "injected" template arguments used within this
980 /// function template.
981 ///
982 /// This pointer refers to the template arguments (there are as
983 /// many template arguments as template parameaters) for the function
984 /// template, and is allocated lazily, since most function templates do not
985 /// require the use of this information.
986 TemplateArgument *InjectedArgs = nullptr;
987
988 Common() = default;
989 };
990
991 FunctionTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
992 DeclarationName Name, TemplateParameterList *Params,
993 NamedDecl *Decl)
994 : RedeclarableTemplateDecl(FunctionTemplate, C, DC, L, Name, Params,
995 Decl) {}
996
997 CommonBase *newCommon(ASTContext &C) const override;
998
999 Common *getCommonPtr() const {
1000 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
1001 }
1002
1003 /// Retrieve the set of function template specializations of this
1004 /// function template.
1005 llvm::FoldingSetVector<FunctionTemplateSpecializationInfo> &
1006 getSpecializations() const;
1007
1008 /// Add a specialization of this function template.
1009 ///
1010 /// \param InsertPos Insert position in the FoldingSetVector, must have been
1011 /// retrieved by an earlier call to findSpecialization().
1012 void addSpecialization(FunctionTemplateSpecializationInfo* Info,
1013 void *InsertPos);
1014
1015public:
1016 friend class ASTDeclReader;
1017 friend class ASTDeclWriter;
1018
1019 /// Load any lazily-loaded specializations from the external source.
1020 void LoadLazySpecializations() const;
1021
1022 /// Get the underlying function declaration of the template.
1023 FunctionDecl *getTemplatedDecl() const {
1024 return static_cast<FunctionDecl *>(TemplatedDecl);
1025 }
1026
1027 /// Returns whether this template declaration defines the primary
1028 /// pattern.
1029 bool isThisDeclarationADefinition() const {
1030 return getTemplatedDecl()->isThisDeclarationADefinition();
1031 }
1032
1033 /// Return the specialization with the provided arguments if it exists,
1034 /// otherwise return the insertion point.
1035 FunctionDecl *findSpecialization(ArrayRef<TemplateArgument> Args,
1036 void *&InsertPos);
1037
1038 FunctionTemplateDecl *getCanonicalDecl() override {
1039 return cast<FunctionTemplateDecl>(
1040 RedeclarableTemplateDecl::getCanonicalDecl());
1041 }
1042 const FunctionTemplateDecl *getCanonicalDecl() const {
1043 return cast<FunctionTemplateDecl>(
1044 RedeclarableTemplateDecl::getCanonicalDecl());
1045 }
1046
1047 /// Retrieve the previous declaration of this function template, or
1048 /// nullptr if no such declaration exists.
1049 FunctionTemplateDecl *getPreviousDecl() {
1050 return cast_or_null<FunctionTemplateDecl>(
1051 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1052 }
1053 const FunctionTemplateDecl *getPreviousDecl() const {
1054 return cast_or_null<FunctionTemplateDecl>(
1055 static_cast<const RedeclarableTemplateDecl *>(this)->getPreviousDecl());
1056 }
1057
1058 FunctionTemplateDecl *getMostRecentDecl() {
1059 return cast<FunctionTemplateDecl>(
1060 static_cast<RedeclarableTemplateDecl *>(this)
1061 ->getMostRecentDecl());
1062 }
1063 const FunctionTemplateDecl *getMostRecentDecl() const {
1064 return const_cast<FunctionTemplateDecl*>(this)->getMostRecentDecl();
1065 }
1066
1067 FunctionTemplateDecl *getInstantiatedFromMemberTemplate() const {
1068 return cast_or_null<FunctionTemplateDecl>(
1069 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
1070 }
1071
1072 using spec_iterator = SpecIterator<FunctionTemplateSpecializationInfo>;
1073 using spec_range = llvm::iterator_range<spec_iterator>;
1074
1075 spec_range specializations() const {
1076 return spec_range(spec_begin(), spec_end());
1077 }
1078
1079 spec_iterator spec_begin() const {
1080 return makeSpecIterator(getSpecializations(), false);
1081 }
1082
1083 spec_iterator spec_end() const {
1084 return makeSpecIterator(getSpecializations(), true);
1085 }
1086
1087 /// Retrieve the "injected" template arguments that correspond to the
1088 /// template parameters of this function template.
1089 ///
1090 /// Although the C++ standard has no notion of the "injected" template
1091 /// arguments for a function template, the notion is convenient when
1092 /// we need to perform substitutions inside the definition of a function
1093 /// template.
1094 ArrayRef<TemplateArgument> getInjectedTemplateArgs();
1095
1096 /// Create a function template node.
1097 static FunctionTemplateDecl *Create(ASTContext &C, DeclContext *DC,
1098 SourceLocation L,
1099 DeclarationName Name,
1100 TemplateParameterList *Params,
1101 NamedDecl *Decl);
1102
1103 /// Create an empty function template node.
1104 static FunctionTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1105
1106 // Implement isa/cast/dyncast support
1107 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1108 static bool classofKind(Kind K) { return K == FunctionTemplate; }
1109};
1110
1111//===----------------------------------------------------------------------===//
1112// Kinds of Template Parameters
1113//===----------------------------------------------------------------------===//
1114
1115/// Defines the position of a template parameter within a template
1116/// parameter list.
1117///
1118/// Because template parameter can be listed
1119/// sequentially for out-of-line template members, each template parameter is
1120/// given a Depth - the nesting of template parameter scopes - and a Position -
1121/// the occurrence within the parameter list.
1122/// This class is inheritedly privately by different kinds of template
1123/// parameters and is not part of the Decl hierarchy. Just a facility.
1124class TemplateParmPosition {
1125protected:
1126 // FIXME: These probably don't need to be ints. int:5 for depth, int:8 for
1127 // position? Maybe?
1128 unsigned Depth;
1129 unsigned Position;
1130
1131 TemplateParmPosition(unsigned D, unsigned P) : Depth(D), Position(P) {}
1132
1133public:
1134 TemplateParmPosition() = delete;
1135
1136 /// Get the nesting depth of the template parameter.
1137 unsigned getDepth() const { return Depth; }
1138 void setDepth(unsigned D) { Depth = D; }
1139
1140 /// Get the position of the template parameter within its parameter list.
1141 unsigned getPosition() const { return Position; }
1142 void setPosition(unsigned P) { Position = P; }
1143
1144 /// Get the index of the template parameter within its parameter list.
1145 unsigned getIndex() const { return Position; }
1146};
1147
1148/// Declaration of a template type parameter.
1149///
1150/// For example, "T" in
1151/// \code
1152/// template<typename T> class vector;
1153/// \endcode
1154class TemplateTypeParmDecl : public TypeDecl {
1155 /// Sema creates these on the stack during auto type deduction.
1156 friend class Sema;
1157
1158 /// Whether this template type parameter was declaration with
1159 /// the 'typename' keyword.
1160 ///
1161 /// If false, it was declared with the 'class' keyword.
1162 bool Typename : 1;
1163
1164 /// The default template argument, if any.
1165 using DefArgStorage =
1166 DefaultArgStorage<TemplateTypeParmDecl, TypeSourceInfo *>;
1167 DefArgStorage DefaultArgument;
1168
1169 TemplateTypeParmDecl(DeclContext *DC, SourceLocation KeyLoc,
1170 SourceLocation IdLoc, IdentifierInfo *Id,
1171 bool Typename)
1172 : TypeDecl(TemplateTypeParm, DC, IdLoc, Id, KeyLoc), Typename(Typename) {}
1173
1174public:
1175 static TemplateTypeParmDecl *Create(const ASTContext &C, DeclContext *DC,
1176 SourceLocation KeyLoc,
1177 SourceLocation NameLoc,
1178 unsigned D, unsigned P,
1179 IdentifierInfo *Id, bool Typename,
1180 bool ParameterPack);
1181 static TemplateTypeParmDecl *CreateDeserialized(const ASTContext &C,
1182 unsigned ID);
1183
1184 /// Whether this template type parameter was declared with
1185 /// the 'typename' keyword.
1186 ///
1187 /// If not, it was declared with the 'class' keyword.
1188 bool wasDeclaredWithTypename() const { return Typename; }
1189
1190 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1191
1192 /// Determine whether this template parameter has a default
1193 /// argument.
1194 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1195
1196 /// Retrieve the default argument, if any.
1197 QualType getDefaultArgument() const {
1198 return DefaultArgument.get()->getType();
1199 }
1200
1201 /// Retrieves the default argument's source information, if any.
1202 TypeSourceInfo *getDefaultArgumentInfo() const {
1203 return DefaultArgument.get();
1204 }
1205
1206 /// Retrieves the location of the default argument declaration.
1207 SourceLocation getDefaultArgumentLoc() const;
1208
1209 /// Determines whether the default argument was inherited
1210 /// from a previous declaration of this template.
1211 bool defaultArgumentWasInherited() const {
1212 return DefaultArgument.isInherited();
1213 }
1214
1215 /// Set the default argument for this template parameter.
1216 void setDefaultArgument(TypeSourceInfo *DefArg) {
1217 DefaultArgument.set(DefArg);
1218 }
1219
1220 /// Set that this default argument was inherited from another
1221 /// parameter.
1222 void setInheritedDefaultArgument(const ASTContext &C,
1223 TemplateTypeParmDecl *Prev) {
1224 DefaultArgument.setInherited(C, Prev);
1225 }
1226
1227 /// Removes the default argument of this template parameter.
1228 void removeDefaultArgument() {
1229 DefaultArgument.clear();
1230 }
1231
1232 /// Set whether this template type parameter was declared with
1233 /// the 'typename' or 'class' keyword.
1234 void setDeclaredWithTypename(bool withTypename) { Typename = withTypename; }
1235
1236 /// Retrieve the depth of the template parameter.
1237 unsigned getDepth() const;
1238
1239 /// Retrieve the index of the template parameter.
1240 unsigned getIndex() const;
1241
1242 /// Returns whether this is a parameter pack.
1243 bool isParameterPack() const;
1244
1245 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1246
1247 // Implement isa/cast/dyncast/etc.
1248 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1249 static bool classofKind(Kind K) { return K == TemplateTypeParm; }
1250};
1251
1252/// NonTypeTemplateParmDecl - Declares a non-type template parameter,
1253/// e.g., "Size" in
1254/// @code
1255/// template<int Size> class array { };
1256/// @endcode
1257class NonTypeTemplateParmDecl final
1258 : public DeclaratorDecl,
1259 protected TemplateParmPosition,
1260 private llvm::TrailingObjects<NonTypeTemplateParmDecl,
1261 std::pair<QualType, TypeSourceInfo *>> {
1262 friend class ASTDeclReader;
1263 friend TrailingObjects;
1264
1265 /// The default template argument, if any, and whether or not
1266 /// it was inherited.
1267 using DefArgStorage = DefaultArgStorage<NonTypeTemplateParmDecl, Expr *>;
1268 DefArgStorage DefaultArgument;
1269
1270 // FIXME: Collapse this into TemplateParamPosition; or, just move depth/index
1271 // down here to save memory.
1272
1273 /// Whether this non-type template parameter is a parameter pack.
1274 bool ParameterPack;
1275
1276 /// Whether this non-type template parameter is an "expanded"
1277 /// parameter pack, meaning that its type is a pack expansion and we
1278 /// already know the set of types that expansion expands to.
1279 bool ExpandedParameterPack = false;
1280
1281 /// The number of types in an expanded parameter pack.
1282 unsigned NumExpandedTypes = 0;
1283
1284 size_t numTrailingObjects(
1285 OverloadToken<std::pair<QualType, TypeSourceInfo *>>) const {
1286 return NumExpandedTypes;
1287 }
1288
1289 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1290 SourceLocation IdLoc, unsigned D, unsigned P,
1291 IdentifierInfo *Id, QualType T,
1292 bool ParameterPack, TypeSourceInfo *TInfo)
1293 : DeclaratorDecl(NonTypeTemplateParm, DC, IdLoc, Id, T, TInfo, StartLoc),
1294 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1295
1296 NonTypeTemplateParmDecl(DeclContext *DC, SourceLocation StartLoc,
1297 SourceLocation IdLoc, unsigned D, unsigned P,
1298 IdentifierInfo *Id, QualType T,
1299 TypeSourceInfo *TInfo,
1300 ArrayRef<QualType> ExpandedTypes,
1301 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1302
1303public:
1304 static NonTypeTemplateParmDecl *
1305 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1306 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1307 QualType T, bool ParameterPack, TypeSourceInfo *TInfo);
1308
1309 static NonTypeTemplateParmDecl *
1310 Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
1311 SourceLocation IdLoc, unsigned D, unsigned P, IdentifierInfo *Id,
1312 QualType T, TypeSourceInfo *TInfo, ArrayRef<QualType> ExpandedTypes,
1313 ArrayRef<TypeSourceInfo *> ExpandedTInfos);
1314
1315 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1316 unsigned ID);
1317 static NonTypeTemplateParmDecl *CreateDeserialized(ASTContext &C,
1318 unsigned ID,
1319 unsigned NumExpandedTypes);
1320
1321 using TemplateParmPosition::getDepth;
1322 using TemplateParmPosition::setDepth;
1323 using TemplateParmPosition::getPosition;
1324 using TemplateParmPosition::setPosition;
1325 using TemplateParmPosition::getIndex;
1326
1327 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1328
1329 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1330
1331 /// Determine whether this template parameter has a default
1332 /// argument.
1333 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1334
1335 /// Retrieve the default argument, if any.
1336 Expr *getDefaultArgument() const { return DefaultArgument.get(); }
1337
1338 /// Retrieve the location of the default argument, if any.
1339 SourceLocation getDefaultArgumentLoc() const;
1340
1341 /// Determines whether the default argument was inherited
1342 /// from a previous declaration of this template.
1343 bool defaultArgumentWasInherited() const {
1344 return DefaultArgument.isInherited();
1345 }
1346
1347 /// Set the default argument for this template parameter, and
1348 /// whether that default argument was inherited from another
1349 /// declaration.
1350 void setDefaultArgument(Expr *DefArg) { DefaultArgument.set(DefArg); }
1351 void setInheritedDefaultArgument(const ASTContext &C,
1352 NonTypeTemplateParmDecl *Parm) {
1353 DefaultArgument.setInherited(C, Parm);
1354 }
1355
1356 /// Removes the default argument of this template parameter.
1357 void removeDefaultArgument() { DefaultArgument.clear(); }
1358
1359 /// Whether this parameter is a non-type template parameter pack.
1360 ///
1361 /// If the parameter is a parameter pack, the type may be a
1362 /// \c PackExpansionType. In the following example, the \c Dims parameter
1363 /// is a parameter pack (whose type is 'unsigned').
1364 ///
1365 /// \code
1366 /// template<typename T, unsigned ...Dims> struct multi_array;
1367 /// \endcode
1368 bool isParameterPack() const { return ParameterPack; }
1369
1370 /// Whether this parameter pack is a pack expansion.
1371 ///
1372 /// A non-type template parameter pack is a pack expansion if its type
1373 /// contains an unexpanded parameter pack. In this case, we will have
1374 /// built a PackExpansionType wrapping the type.
1375 bool isPackExpansion() const {
1376 return ParameterPack && getType()->getAs<PackExpansionType>();
1377 }
1378
1379 /// Whether this parameter is a non-type template parameter pack
1380 /// that has a known list of different types at different positions.
1381 ///
1382 /// A parameter pack is an expanded parameter pack when the original
1383 /// parameter pack's type was itself a pack expansion, and that expansion
1384 /// has already been expanded. For example, given:
1385 ///
1386 /// \code
1387 /// template<typename ...Types>
1388 /// struct X {
1389 /// template<Types ...Values>
1390 /// struct Y { /* ... */ };
1391 /// };
1392 /// \endcode
1393 ///
1394 /// The parameter pack \c Values has a \c PackExpansionType as its type,
1395 /// which expands \c Types. When \c Types is supplied with template arguments
1396 /// by instantiating \c X, the instantiation of \c Values becomes an
1397 /// expanded parameter pack. For example, instantiating
1398 /// \c X<int, unsigned int> results in \c Values being an expanded parameter
1399 /// pack with expansion types \c int and \c unsigned int.
1400 ///
1401 /// The \c getExpansionType() and \c getExpansionTypeSourceInfo() functions
1402 /// return the expansion types.
1403 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1404
1405 /// Retrieves the number of expansion types in an expanded parameter
1406 /// pack.
1407 unsigned getNumExpansionTypes() const {
1408 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1408, __extension__ __PRETTY_FUNCTION__))
;
1409 return NumExpandedTypes;
1410 }
1411
1412 /// Retrieve a particular expansion type within an expanded parameter
1413 /// pack.
1414 QualType getExpansionType(unsigned I) const {
1415 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1415, __extension__ __PRETTY_FUNCTION__))
;
1416 auto TypesAndInfos =
1417 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1418 return TypesAndInfos[I].first;
1419 }
1420
1421 /// Retrieve a particular expansion type source info within an
1422 /// expanded parameter pack.
1423 TypeSourceInfo *getExpansionTypeSourceInfo(unsigned I) const {
1424 assert(I < NumExpandedTypes && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedTypes &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedTypes && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1424, __extension__ __PRETTY_FUNCTION__))
;
1425 auto TypesAndInfos =
1426 getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
1427 return TypesAndInfos[I].second;
1428 }
1429
1430 // Implement isa/cast/dyncast/etc.
1431 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1432 static bool classofKind(Kind K) { return K == NonTypeTemplateParm; }
1433};
1434
1435/// TemplateTemplateParmDecl - Declares a template template parameter,
1436/// e.g., "T" in
1437/// @code
1438/// template <template <typename> class T> class container { };
1439/// @endcode
1440/// A template template parameter is a TemplateDecl because it defines the
1441/// name of a template and the template parameters allowable for substitution.
1442class TemplateTemplateParmDecl final
1443 : public TemplateDecl,
1444 protected TemplateParmPosition,
1445 private llvm::TrailingObjects<TemplateTemplateParmDecl,
1446 TemplateParameterList *> {
1447 /// The default template argument, if any.
1448 using DefArgStorage =
1449 DefaultArgStorage<TemplateTemplateParmDecl, TemplateArgumentLoc *>;
1450 DefArgStorage DefaultArgument;
1451
1452 /// Whether this parameter is a parameter pack.
1453 bool ParameterPack;
1454
1455 /// Whether this template template parameter is an "expanded"
1456 /// parameter pack, meaning that it is a pack expansion and we
1457 /// already know the set of template parameters that expansion expands to.
1458 bool ExpandedParameterPack = false;
1459
1460 /// The number of parameters in an expanded parameter pack.
1461 unsigned NumExpandedParams = 0;
1462
1463 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1464 unsigned D, unsigned P, bool ParameterPack,
1465 IdentifierInfo *Id, TemplateParameterList *Params)
1466 : TemplateDecl(TemplateTemplateParm, DC, L, Id, Params),
1467 TemplateParmPosition(D, P), ParameterPack(ParameterPack) {}
1468
1469 TemplateTemplateParmDecl(DeclContext *DC, SourceLocation L,
1470 unsigned D, unsigned P,
1471 IdentifierInfo *Id, TemplateParameterList *Params,
1472 ArrayRef<TemplateParameterList *> Expansions);
1473
1474 void anchor() override;
1475
1476public:
1477 friend class ASTDeclReader;
1478 friend class ASTDeclWriter;
1479 friend TrailingObjects;
1480
1481 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1482 SourceLocation L, unsigned D,
1483 unsigned P, bool ParameterPack,
1484 IdentifierInfo *Id,
1485 TemplateParameterList *Params);
1486 static TemplateTemplateParmDecl *Create(const ASTContext &C, DeclContext *DC,
1487 SourceLocation L, unsigned D,
1488 unsigned P,
1489 IdentifierInfo *Id,
1490 TemplateParameterList *Params,
1491 ArrayRef<TemplateParameterList *> Expansions);
1492
1493 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1494 unsigned ID);
1495 static TemplateTemplateParmDecl *CreateDeserialized(ASTContext &C,
1496 unsigned ID,
1497 unsigned NumExpansions);
1498
1499 using TemplateParmPosition::getDepth;
1500 using TemplateParmPosition::setDepth;
1501 using TemplateParmPosition::getPosition;
1502 using TemplateParmPosition::setPosition;
1503 using TemplateParmPosition::getIndex;
1504
1505 /// Whether this template template parameter is a template
1506 /// parameter pack.
1507 ///
1508 /// \code
1509 /// template<template <class T> ...MetaFunctions> struct Apply;
1510 /// \endcode
1511 bool isParameterPack() const { return ParameterPack; }
1512
1513 /// Whether this parameter pack is a pack expansion.
1514 ///
1515 /// A template template parameter pack is a pack expansion if its template
1516 /// parameter list contains an unexpanded parameter pack.
1517 bool isPackExpansion() const {
1518 return ParameterPack &&
1519 getTemplateParameters()->containsUnexpandedParameterPack();
1520 }
1521
1522 /// Whether this parameter is a template template parameter pack that
1523 /// has a known list of different template parameter lists at different
1524 /// positions.
1525 ///
1526 /// A parameter pack is an expanded parameter pack when the original parameter
1527 /// pack's template parameter list was itself a pack expansion, and that
1528 /// expansion has already been expanded. For exampe, given:
1529 ///
1530 /// \code
1531 /// template<typename...Types> struct Outer {
1532 /// template<template<Types> class...Templates> struct Inner;
1533 /// };
1534 /// \endcode
1535 ///
1536 /// The parameter pack \c Templates is a pack expansion, which expands the
1537 /// pack \c Types. When \c Types is supplied with template arguments by
1538 /// instantiating \c Outer, the instantiation of \c Templates is an expanded
1539 /// parameter pack.
1540 bool isExpandedParameterPack() const { return ExpandedParameterPack; }
1541
1542 /// Retrieves the number of expansion template parameters in
1543 /// an expanded parameter pack.
1544 unsigned getNumExpansionTemplateParameters() const {
1545 assert(ExpandedParameterPack && "Not an expansion parameter pack")(static_cast <bool> (ExpandedParameterPack && "Not an expansion parameter pack"
) ? void (0) : __assert_fail ("ExpandedParameterPack && \"Not an expansion parameter pack\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1545, __extension__ __PRETTY_FUNCTION__))
;
1546 return NumExpandedParams;
1547 }
1548
1549 /// Retrieve a particular expansion type within an expanded parameter
1550 /// pack.
1551 TemplateParameterList *getExpansionTemplateParameters(unsigned I) const {
1552 assert(I < NumExpandedParams && "Out-of-range expansion type index")(static_cast <bool> (I < NumExpandedParams &&
"Out-of-range expansion type index") ? void (0) : __assert_fail
("I < NumExpandedParams && \"Out-of-range expansion type index\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1552, __extension__ __PRETTY_FUNCTION__))
;
1553 return getTrailingObjects<TemplateParameterList *>()[I];
1554 }
1555
1556 const DefArgStorage &getDefaultArgStorage() const { return DefaultArgument; }
1557
1558 /// Determine whether this template parameter has a default
1559 /// argument.
1560 bool hasDefaultArgument() const { return DefaultArgument.isSet(); }
1561
1562 /// Retrieve the default argument, if any.
1563 const TemplateArgumentLoc &getDefaultArgument() const {
1564 static const TemplateArgumentLoc None;
1565 return DefaultArgument.isSet() ? *DefaultArgument.get() : None;
1566 }
1567
1568 /// Retrieve the location of the default argument, if any.
1569 SourceLocation getDefaultArgumentLoc() const;
1570
1571 /// Determines whether the default argument was inherited
1572 /// from a previous declaration of this template.
1573 bool defaultArgumentWasInherited() const {
1574 return DefaultArgument.isInherited();
1575 }
1576
1577 /// Set the default argument for this template parameter, and
1578 /// whether that default argument was inherited from another
1579 /// declaration.
1580 void setDefaultArgument(const ASTContext &C,
1581 const TemplateArgumentLoc &DefArg);
1582 void setInheritedDefaultArgument(const ASTContext &C,
1583 TemplateTemplateParmDecl *Prev) {
1584 DefaultArgument.setInherited(C, Prev);
1585 }
1586
1587 /// Removes the default argument of this template parameter.
1588 void removeDefaultArgument() { DefaultArgument.clear(); }
1589
1590 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1591 SourceLocation End = getLocation();
1592 if (hasDefaultArgument() && !defaultArgumentWasInherited())
1593 End = getDefaultArgument().getSourceRange().getEnd();
1594 return SourceRange(getTemplateParameters()->getTemplateLoc(), End);
1595 }
1596
1597 // Implement isa/cast/dyncast/etc.
1598 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1599 static bool classofKind(Kind K) { return K == TemplateTemplateParm; }
1600};
1601
1602/// Represents the builtin template declaration which is used to
1603/// implement __make_integer_seq and other builtin templates. It serves
1604/// no real purpose beyond existing as a place to hold template parameters.
1605class BuiltinTemplateDecl : public TemplateDecl {
1606 BuiltinTemplateKind BTK;
1607
1608 BuiltinTemplateDecl(const ASTContext &C, DeclContext *DC,
1609 DeclarationName Name, BuiltinTemplateKind BTK);
1610
1611 void anchor() override;
1612
1613public:
1614 // Implement isa/cast/dyncast support
1615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1616 static bool classofKind(Kind K) { return K == BuiltinTemplate; }
1617
1618 static BuiltinTemplateDecl *Create(const ASTContext &C, DeclContext *DC,
1619 DeclarationName Name,
1620 BuiltinTemplateKind BTK) {
1621 return new (C, DC) BuiltinTemplateDecl(C, DC, Name, BTK);
1622 }
1623
1624 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
1625 return {};
1626 }
1627
1628 BuiltinTemplateKind getBuiltinTemplateKind() const { return BTK; }
1629};
1630
1631/// Represents a class template specialization, which refers to
1632/// a class template with a given set of template arguments.
1633///
1634/// Class template specializations represent both explicit
1635/// specialization of class templates, as in the example below, and
1636/// implicit instantiations of class templates.
1637///
1638/// \code
1639/// template<typename T> class array;
1640///
1641/// template<>
1642/// class array<bool> { }; // class template specialization array<bool>
1643/// \endcode
1644class ClassTemplateSpecializationDecl
1645 : public CXXRecordDecl, public llvm::FoldingSetNode {
1646 /// Structure that stores information about a class template
1647 /// specialization that was instantiated from a class template partial
1648 /// specialization.
1649 struct SpecializedPartialSpecialization {
1650 /// The class template partial specialization from which this
1651 /// class template specialization was instantiated.
1652 ClassTemplatePartialSpecializationDecl *PartialSpecialization;
1653
1654 /// The template argument list deduced for the class template
1655 /// partial specialization itself.
1656 const TemplateArgumentList *TemplateArgs;
1657 };
1658
1659 /// The template that this specialization specializes
1660 llvm::PointerUnion<ClassTemplateDecl *, SpecializedPartialSpecialization *>
1661 SpecializedTemplate;
1662
1663 /// Further info for explicit template specialization/instantiation.
1664 struct ExplicitSpecializationInfo {
1665 /// The type-as-written.
1666 TypeSourceInfo *TypeAsWritten = nullptr;
1667
1668 /// The location of the extern keyword.
1669 SourceLocation ExternLoc;
1670
1671 /// The location of the template keyword.
1672 SourceLocation TemplateKeywordLoc;
1673
1674 ExplicitSpecializationInfo() = default;
1675 };
1676
1677 /// Further info for explicit template specialization/instantiation.
1678 /// Does not apply to implicit specializations.
1679 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
1680
1681 /// The template arguments used to describe this specialization.
1682 const TemplateArgumentList *TemplateArgs;
1683
1684 /// The point where this template was instantiated (if any)
1685 SourceLocation PointOfInstantiation;
1686
1687 /// The kind of specialization this declaration refers to.
1688 /// Really a value of type TemplateSpecializationKind.
1689 unsigned SpecializationKind : 3;
1690
1691protected:
1692 ClassTemplateSpecializationDecl(ASTContext &Context, Kind DK, TagKind TK,
1693 DeclContext *DC, SourceLocation StartLoc,
1694 SourceLocation IdLoc,
1695 ClassTemplateDecl *SpecializedTemplate,
1696 ArrayRef<TemplateArgument> Args,
1697 ClassTemplateSpecializationDecl *PrevDecl);
1698
1699 explicit ClassTemplateSpecializationDecl(ASTContext &C, Kind DK);
1700
1701public:
1702 friend class ASTDeclReader;
1703 friend class ASTDeclWriter;
1704
1705 static ClassTemplateSpecializationDecl *
1706 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1707 SourceLocation StartLoc, SourceLocation IdLoc,
1708 ClassTemplateDecl *SpecializedTemplate,
1709 ArrayRef<TemplateArgument> Args,
1710 ClassTemplateSpecializationDecl *PrevDecl);
1711 static ClassTemplateSpecializationDecl *
1712 CreateDeserialized(ASTContext &C, unsigned ID);
1713
1714 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
1715 bool Qualified) const override;
1716
1717 // FIXME: This is broken. CXXRecordDecl::getMostRecentDecl() returns a
1718 // different "most recent" declaration from this function for the same
1719 // declaration, because we don't override getMostRecentDeclImpl(). But
1720 // it's not clear that we should override that, because the most recent
1721 // declaration as a CXXRecordDecl sometimes is the injected-class-name.
1722 ClassTemplateSpecializationDecl *getMostRecentDecl() {
1723 return cast<ClassTemplateSpecializationDecl>(
1724 getMostRecentNonInjectedDecl());
1725 }
1726
1727 /// Retrieve the template that this specialization specializes.
1728 ClassTemplateDecl *getSpecializedTemplate() const;
1729
1730 /// Retrieve the template arguments of the class template
1731 /// specialization.
1732 const TemplateArgumentList &getTemplateArgs() const {
1733 return *TemplateArgs;
1734 }
1735
1736 /// Determine the kind of specialization that this
1737 /// declaration represents.
1738 TemplateSpecializationKind getSpecializationKind() const {
1739 return static_cast<TemplateSpecializationKind>(SpecializationKind);
1740 }
1741
1742 bool isExplicitSpecialization() const {
1743 return getSpecializationKind() == TSK_ExplicitSpecialization;
1744 }
1745
1746 /// True if this declaration is an explicit specialization,
1747 /// explicit instantiation declaration, or explicit instantiation
1748 /// definition.
1749 bool isExplicitInstantiationOrSpecialization() const {
1750 return isTemplateExplicitInstantiationOrSpecialization(
1751 getTemplateSpecializationKind());
1752 }
1753
1754 void setSpecializationKind(TemplateSpecializationKind TSK) {
1755 SpecializationKind = TSK;
1756 }
1757
1758 /// Get the point of instantiation (if any), or null if none.
1759 SourceLocation getPointOfInstantiation() const {
1760 return PointOfInstantiation;
1761 }
1762
1763 void setPointOfInstantiation(SourceLocation Loc) {
1764 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1764, __extension__ __PRETTY_FUNCTION__))
;
1765 PointOfInstantiation = Loc;
1766 }
1767
1768 /// If this class template specialization is an instantiation of
1769 /// a template (rather than an explicit specialization), return the
1770 /// class template or class template partial specialization from which it
1771 /// was instantiated.
1772 llvm::PointerUnion<ClassTemplateDecl *,
1773 ClassTemplatePartialSpecializationDecl *>
1774 getInstantiatedFrom() const {
1775 if (!isTemplateInstantiation(getSpecializationKind()))
1776 return llvm::PointerUnion<ClassTemplateDecl *,
1777 ClassTemplatePartialSpecializationDecl *>();
1778
1779 return getSpecializedTemplateOrPartial();
1780 }
1781
1782 /// Retrieve the class template or class template partial
1783 /// specialization which was specialized by this.
1784 llvm::PointerUnion<ClassTemplateDecl *,
1785 ClassTemplatePartialSpecializationDecl *>
1786 getSpecializedTemplateOrPartial() const {
1787 if (const auto *PartialSpec =
1788 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1789 return PartialSpec->PartialSpecialization;
1790
1791 return SpecializedTemplate.get<ClassTemplateDecl*>();
1792 }
1793
1794 /// Retrieve the set of template arguments that should be used
1795 /// to instantiate members of the class template or class template partial
1796 /// specialization from which this class template specialization was
1797 /// instantiated.
1798 ///
1799 /// \returns For a class template specialization instantiated from the primary
1800 /// template, this function will return the same template arguments as
1801 /// getTemplateArgs(). For a class template specialization instantiated from
1802 /// a class template partial specialization, this function will return the
1803 /// deduced template arguments for the class template partial specialization
1804 /// itself.
1805 const TemplateArgumentList &getTemplateInstantiationArgs() const {
1806 if (const auto *PartialSpec =
1807 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
1808 return *PartialSpec->TemplateArgs;
1809
1810 return getTemplateArgs();
1811 }
1812
1813 /// Note that this class template specialization is actually an
1814 /// instantiation of the given class template partial specialization whose
1815 /// template arguments have been deduced.
1816 void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec,
1817 const TemplateArgumentList *TemplateArgs) {
1818 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1819, __extension__ __PRETTY_FUNCTION__))
1819 "Already set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Already set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1819, __extension__ __PRETTY_FUNCTION__))
;
1820 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
16
'PS' initialized to a null pointer value
1821 PS->PartialSpecialization = PartialSpec;
17
Access to field 'PartialSpecialization' results in a dereference of a null pointer (loaded from variable 'PS')
1822 PS->TemplateArgs = TemplateArgs;
1823 SpecializedTemplate = PS;
1824 }
1825
1826 /// Note that this class template specialization is an instantiation
1827 /// of the given class template.
1828 void setInstantiationOf(ClassTemplateDecl *TemplDecl) {
1829 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization*>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1830, __extension__ __PRETTY_FUNCTION__))
1830 "Previously set to a class template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a class template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization*>() && \"Previously set to a class template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 1830, __extension__ __PRETTY_FUNCTION__))
;
1831 SpecializedTemplate = TemplDecl;
1832 }
1833
1834 /// Sets the type of this specialization as it was written by
1835 /// the user. This will be a class template specialization type.
1836 void setTypeAsWritten(TypeSourceInfo *T) {
1837 if (!ExplicitInfo)
1838 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1839 ExplicitInfo->TypeAsWritten = T;
1840 }
1841
1842 /// Gets the type of this specialization as it was written by
1843 /// the user, if it was so written.
1844 TypeSourceInfo *getTypeAsWritten() const {
1845 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
1846 }
1847
1848 /// Gets the location of the extern keyword, if present.
1849 SourceLocation getExternLoc() const {
1850 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
1851 }
1852
1853 /// Sets the location of the extern keyword.
1854 void setExternLoc(SourceLocation Loc) {
1855 if (!ExplicitInfo)
1856 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1857 ExplicitInfo->ExternLoc = Loc;
1858 }
1859
1860 /// Sets the location of the template keyword.
1861 void setTemplateKeywordLoc(SourceLocation Loc) {
1862 if (!ExplicitInfo)
1863 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
1864 ExplicitInfo->TemplateKeywordLoc = Loc;
1865 }
1866
1867 /// Gets the location of the template keyword, if present.
1868 SourceLocation getTemplateKeywordLoc() const {
1869 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
1870 }
1871
1872 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1873
1874 void Profile(llvm::FoldingSetNodeID &ID) const {
1875 Profile(ID, TemplateArgs->asArray(), getASTContext());
1876 }
1877
1878 static void
1879 Profile(llvm::FoldingSetNodeID &ID, ArrayRef<TemplateArgument> TemplateArgs,
1880 ASTContext &Context) {
1881 ID.AddInteger(TemplateArgs.size());
1882 for (const TemplateArgument &TemplateArg : TemplateArgs)
1883 TemplateArg.Profile(ID, Context);
1884 }
1885
1886 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
1887
1888 static bool classofKind(Kind K) {
1889 return K >= firstClassTemplateSpecialization &&
1890 K <= lastClassTemplateSpecialization;
1891 }
1892};
1893
1894class ClassTemplatePartialSpecializationDecl
1895 : public ClassTemplateSpecializationDecl {
1896 /// The list of template parameters
1897 TemplateParameterList* TemplateParams = nullptr;
1898
1899 /// The source info for the template arguments as written.
1900 /// FIXME: redundant with TypeAsWritten?
1901 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
1902
1903 /// The class template partial specialization from which this
1904 /// class template partial specialization was instantiated.
1905 ///
1906 /// The boolean value will be true to indicate that this class template
1907 /// partial specialization was specialized at this level.
1908 llvm::PointerIntPair<ClassTemplatePartialSpecializationDecl *, 1, bool>
1909 InstantiatedFromMember;
1910
1911 ClassTemplatePartialSpecializationDecl(ASTContext &Context, TagKind TK,
1912 DeclContext *DC,
1913 SourceLocation StartLoc,
1914 SourceLocation IdLoc,
1915 TemplateParameterList *Params,
1916 ClassTemplateDecl *SpecializedTemplate,
1917 ArrayRef<TemplateArgument> Args,
1918 const ASTTemplateArgumentListInfo *ArgsAsWritten,
1919 ClassTemplatePartialSpecializationDecl *PrevDecl);
1920
1921 ClassTemplatePartialSpecializationDecl(ASTContext &C)
1922 : ClassTemplateSpecializationDecl(C, ClassTemplatePartialSpecialization),
1923 InstantiatedFromMember(nullptr, false) {}
1924
1925 void anchor() override;
1926
1927public:
1928 friend class ASTDeclReader;
1929 friend class ASTDeclWriter;
1930
1931 static ClassTemplatePartialSpecializationDecl *
1932 Create(ASTContext &Context, TagKind TK, DeclContext *DC,
1933 SourceLocation StartLoc, SourceLocation IdLoc,
1934 TemplateParameterList *Params,
1935 ClassTemplateDecl *SpecializedTemplate,
1936 ArrayRef<TemplateArgument> Args,
1937 const TemplateArgumentListInfo &ArgInfos,
1938 QualType CanonInjectedType,
1939 ClassTemplatePartialSpecializationDecl *PrevDecl);
1940
1941 static ClassTemplatePartialSpecializationDecl *
1942 CreateDeserialized(ASTContext &C, unsigned ID);
1943
1944 ClassTemplatePartialSpecializationDecl *getMostRecentDecl() {
1945 return cast<ClassTemplatePartialSpecializationDecl>(
1946 static_cast<ClassTemplateSpecializationDecl *>(
1947 this)->getMostRecentDecl());
1948 }
1949
1950 /// Get the list of template parameters
1951 TemplateParameterList *getTemplateParameters() const {
1952 return TemplateParams;
1953 }
1954
1955 /// Get the template arguments as written.
1956 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
1957 return ArgsAsWritten;
1958 }
1959
1960 /// Retrieve the member class template partial specialization from
1961 /// which this particular class template partial specialization was
1962 /// instantiated.
1963 ///
1964 /// \code
1965 /// template<typename T>
1966 /// struct Outer {
1967 /// template<typename U> struct Inner;
1968 /// template<typename U> struct Inner<U*> { }; // #1
1969 /// };
1970 ///
1971 /// Outer<float>::Inner<int*> ii;
1972 /// \endcode
1973 ///
1974 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
1975 /// end up instantiating the partial specialization
1976 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the class
1977 /// template partial specialization \c Outer<T>::Inner<U*>. Given
1978 /// \c Outer<float>::Inner<U*>, this function would return
1979 /// \c Outer<T>::Inner<U*>.
1980 ClassTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
1981 const auto *First =
1982 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1983 return First->InstantiatedFromMember.getPointer();
1984 }
1985 ClassTemplatePartialSpecializationDecl *
1986 getInstantiatedFromMemberTemplate() const {
1987 return getInstantiatedFromMember();
1988 }
1989
1990 void setInstantiatedFromMember(
1991 ClassTemplatePartialSpecializationDecl *PartialSpec) {
1992 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
1993 First->InstantiatedFromMember.setPointer(PartialSpec);
1994 }
1995
1996 /// Determines whether this class template partial specialization
1997 /// template was a specialization of a member partial specialization.
1998 ///
1999 /// In the following example, the member template partial specialization
2000 /// \c X<int>::Inner<T*> is a member specialization.
2001 ///
2002 /// \code
2003 /// template<typename T>
2004 /// struct X {
2005 /// template<typename U> struct Inner;
2006 /// template<typename U> struct Inner<U*>;
2007 /// };
2008 ///
2009 /// template<> template<typename T>
2010 /// struct X<int>::Inner<T*> { /* ... */ };
2011 /// \endcode
2012 bool isMemberSpecialization() {
2013 const auto *First =
2014 cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2015 return First->InstantiatedFromMember.getInt();
2016 }
2017
2018 /// Note that this member template is a specialization.
2019 void setMemberSpecialization() {
2020 auto *First = cast<ClassTemplatePartialSpecializationDecl>(getFirstDecl());
2021 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2022, __extension__ __PRETTY_FUNCTION__))
2022 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2022, __extension__ __PRETTY_FUNCTION__))
;
2023 return First->InstantiatedFromMember.setInt(true);
2024 }
2025
2026 /// Retrieves the injected specialization type for this partial
2027 /// specialization. This is not the same as the type-decl-type for
2028 /// this partial specialization, which is an InjectedClassNameType.
2029 QualType getInjectedSpecializationType() const {
2030 assert(getTypeForDecl() && "partial specialization has no type set!")(static_cast <bool> (getTypeForDecl() && "partial specialization has no type set!"
) ? void (0) : __assert_fail ("getTypeForDecl() && \"partial specialization has no type set!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2030, __extension__ __PRETTY_FUNCTION__))
;
2031 return cast<InjectedClassNameType>(getTypeForDecl())
2032 ->getInjectedSpecializationType();
2033 }
2034
2035 // FIXME: Add Profile support!
2036
2037 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2038
2039 static bool classofKind(Kind K) {
2040 return K == ClassTemplatePartialSpecialization;
2041 }
2042};
2043
2044/// Declaration of a class template.
2045class ClassTemplateDecl : public RedeclarableTemplateDecl {
2046protected:
2047 /// Data that is common to all of the declarations of a given
2048 /// class template.
2049 struct Common : CommonBase {
2050 /// The class template specializations for this class
2051 /// template, including explicit specializations and instantiations.
2052 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> Specializations;
2053
2054 /// The class template partial specializations for this class
2055 /// template.
2056 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl>
2057 PartialSpecializations;
2058
2059 /// The injected-class-name type for this class template.
2060 QualType InjectedClassNameType;
2061
2062 Common() = default;
2063 };
2064
2065 /// Retrieve the set of specializations of this class template.
2066 llvm::FoldingSetVector<ClassTemplateSpecializationDecl> &
2067 getSpecializations() const;
2068
2069 /// Retrieve the set of partial specializations of this class
2070 /// template.
2071 llvm::FoldingSetVector<ClassTemplatePartialSpecializationDecl> &
2072 getPartialSpecializations();
2073
2074 ClassTemplateDecl(ConstrainedTemplateDeclInfo *CTDI, ASTContext &C,
2075 DeclContext *DC, SourceLocation L, DeclarationName Name,
2076 TemplateParameterList *Params, NamedDecl *Decl)
2077 : RedeclarableTemplateDecl(CTDI, ClassTemplate, C, DC, L, Name, Params,
2078 Decl) {}
2079
2080 ClassTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2081 DeclarationName Name, TemplateParameterList *Params,
2082 NamedDecl *Decl)
2083 : ClassTemplateDecl(nullptr, C, DC, L, Name, Params, Decl) {}
2084
2085 CommonBase *newCommon(ASTContext &C) const override;
2086
2087 Common *getCommonPtr() const {
2088 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2089 }
2090
2091public:
2092 friend class ASTDeclReader;
2093 friend class ASTDeclWriter;
2094
2095 /// Load any lazily-loaded specializations from the external source.
2096 void LoadLazySpecializations() const;
2097
2098 /// Get the underlying class declarations of the template.
2099 CXXRecordDecl *getTemplatedDecl() const {
2100 return static_cast<CXXRecordDecl *>(TemplatedDecl);
2101 }
2102
2103 /// Returns whether this template declaration defines the primary
2104 /// class pattern.
2105 bool isThisDeclarationADefinition() const {
2106 return getTemplatedDecl()->isThisDeclarationADefinition();
2107 }
2108
2109 // FIXME: remove default argument for AssociatedConstraints
2110 /// Create a class template node.
2111 static ClassTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2112 SourceLocation L,
2113 DeclarationName Name,
2114 TemplateParameterList *Params,
2115 NamedDecl *Decl,
2116 Expr *AssociatedConstraints = nullptr);
2117
2118 /// Create an empty class template node.
2119 static ClassTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2120
2121 /// Return the specialization with the provided arguments if it exists,
2122 /// otherwise return the insertion point.
2123 ClassTemplateSpecializationDecl *
2124 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2125
2126 /// Insert the specified specialization knowing that it is not already
2127 /// in. InsertPos must be obtained from findSpecialization.
2128 void AddSpecialization(ClassTemplateSpecializationDecl *D, void *InsertPos);
2129
2130 ClassTemplateDecl *getCanonicalDecl() override {
2131 return cast<ClassTemplateDecl>(
2132 RedeclarableTemplateDecl::getCanonicalDecl());
2133 }
2134 const ClassTemplateDecl *getCanonicalDecl() const {
2135 return cast<ClassTemplateDecl>(
2136 RedeclarableTemplateDecl::getCanonicalDecl());
2137 }
2138
2139 /// Retrieve the previous declaration of this class template, or
2140 /// nullptr if no such declaration exists.
2141 ClassTemplateDecl *getPreviousDecl() {
2142 return cast_or_null<ClassTemplateDecl>(
2143 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2144 }
2145 const ClassTemplateDecl *getPreviousDecl() const {
2146 return cast_or_null<ClassTemplateDecl>(
2147 static_cast<const RedeclarableTemplateDecl *>(
2148 this)->getPreviousDecl());
2149 }
2150
2151 ClassTemplateDecl *getMostRecentDecl() {
2152 return cast<ClassTemplateDecl>(
2153 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2154 }
2155 const ClassTemplateDecl *getMostRecentDecl() const {
2156 return const_cast<ClassTemplateDecl*>(this)->getMostRecentDecl();
2157 }
2158
2159 ClassTemplateDecl *getInstantiatedFromMemberTemplate() const {
2160 return cast_or_null<ClassTemplateDecl>(
2161 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2162 }
2163
2164 /// Return the partial specialization with the provided arguments if it
2165 /// exists, otherwise return the insertion point.
2166 ClassTemplatePartialSpecializationDecl *
2167 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2168
2169 /// Insert the specified partial specialization knowing that it is not
2170 /// already in. InsertPos must be obtained from findPartialSpecialization.
2171 void AddPartialSpecialization(ClassTemplatePartialSpecializationDecl *D,
2172 void *InsertPos);
2173
2174 /// Retrieve the partial specializations as an ordered list.
2175 void getPartialSpecializations(
2176 SmallVectorImpl<ClassTemplatePartialSpecializationDecl *> &PS);
2177
2178 /// Find a class template partial specialization with the given
2179 /// type T.
2180 ///
2181 /// \param T a dependent type that names a specialization of this class
2182 /// template.
2183 ///
2184 /// \returns the class template partial specialization that exactly matches
2185 /// the type \p T, or nullptr if no such partial specialization exists.
2186 ClassTemplatePartialSpecializationDecl *findPartialSpecialization(QualType T);
2187
2188 /// Find a class template partial specialization which was instantiated
2189 /// from the given member partial specialization.
2190 ///
2191 /// \param D a member class template partial specialization.
2192 ///
2193 /// \returns the class template partial specialization which was instantiated
2194 /// from the given member partial specialization, or nullptr if no such
2195 /// partial specialization exists.
2196 ClassTemplatePartialSpecializationDecl *
2197 findPartialSpecInstantiatedFromMember(
2198 ClassTemplatePartialSpecializationDecl *D);
2199
2200 /// Retrieve the template specialization type of the
2201 /// injected-class-name for this class template.
2202 ///
2203 /// The injected-class-name for a class template \c X is \c
2204 /// X<template-args>, where \c template-args is formed from the
2205 /// template arguments that correspond to the template parameters of
2206 /// \c X. For example:
2207 ///
2208 /// \code
2209 /// template<typename T, int N>
2210 /// struct array {
2211 /// typedef array this_type; // "array" is equivalent to "array<T, N>"
2212 /// };
2213 /// \endcode
2214 QualType getInjectedClassNameSpecialization();
2215
2216 using spec_iterator = SpecIterator<ClassTemplateSpecializationDecl>;
2217 using spec_range = llvm::iterator_range<spec_iterator>;
2218
2219 spec_range specializations() const {
2220 return spec_range(spec_begin(), spec_end());
2221 }
2222
2223 spec_iterator spec_begin() const {
2224 return makeSpecIterator(getSpecializations(), false);
2225 }
2226
2227 spec_iterator spec_end() const {
2228 return makeSpecIterator(getSpecializations(), true);
2229 }
2230
2231 // Implement isa/cast/dyncast support
2232 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2233 static bool classofKind(Kind K) { return K == ClassTemplate; }
2234};
2235
2236/// Declaration of a friend template.
2237///
2238/// For example:
2239/// \code
2240/// template \<typename T> class A {
2241/// friend class MyVector<T>; // not a friend template
2242/// template \<typename U> friend class B; // not a friend template
2243/// template \<typename U> friend class Foo<T>::Nested; // friend template
2244/// };
2245/// \endcode
2246///
2247/// \note This class is not currently in use. All of the above
2248/// will yield a FriendDecl, not a FriendTemplateDecl.
2249class FriendTemplateDecl : public Decl {
2250 virtual void anchor();
2251
2252public:
2253 using FriendUnion = llvm::PointerUnion<NamedDecl *,TypeSourceInfo *>;
2254
2255private:
2256 // The number of template parameters; always non-zero.
2257 unsigned NumParams = 0;
2258
2259 // The parameter list.
2260 TemplateParameterList **Params = nullptr;
2261
2262 // The declaration that's a friend of this class.
2263 FriendUnion Friend;
2264
2265 // Location of the 'friend' specifier.
2266 SourceLocation FriendLoc;
2267
2268 FriendTemplateDecl(DeclContext *DC, SourceLocation Loc,
2269 MutableArrayRef<TemplateParameterList *> Params,
2270 FriendUnion Friend, SourceLocation FriendLoc)
2271 : Decl(Decl::FriendTemplate, DC, Loc), NumParams(Params.size()),
2272 Params(Params.data()), Friend(Friend), FriendLoc(FriendLoc) {}
2273
2274 FriendTemplateDecl(EmptyShell Empty) : Decl(Decl::FriendTemplate, Empty) {}
2275
2276public:
2277 friend class ASTDeclReader;
2278
2279 static FriendTemplateDecl *
2280 Create(ASTContext &Context, DeclContext *DC, SourceLocation Loc,
2281 MutableArrayRef<TemplateParameterList *> Params, FriendUnion Friend,
2282 SourceLocation FriendLoc);
2283
2284 static FriendTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2285
2286 /// If this friend declaration names a templated type (or
2287 /// a dependent member type of a templated type), return that
2288 /// type; otherwise return null.
2289 TypeSourceInfo *getFriendType() const {
2290 return Friend.dyn_cast<TypeSourceInfo*>();
2291 }
2292
2293 /// If this friend declaration names a templated function (or
2294 /// a member function of a templated type), return that type;
2295 /// otherwise return null.
2296 NamedDecl *getFriendDecl() const {
2297 return Friend.dyn_cast<NamedDecl*>();
2298 }
2299
2300 /// Retrieves the location of the 'friend' keyword.
2301 SourceLocation getFriendLoc() const {
2302 return FriendLoc;
2303 }
2304
2305 TemplateParameterList *getTemplateParameterList(unsigned i) const {
2306 assert(i <= NumParams)(static_cast <bool> (i <= NumParams) ? void (0) : __assert_fail
("i <= NumParams", "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2306, __extension__ __PRETTY_FUNCTION__))
;
2307 return Params[i];
2308 }
2309
2310 unsigned getNumTemplateParameters() const {
2311 return NumParams;
2312 }
2313
2314 // Implement isa/cast/dyncast/etc.
2315 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2316 static bool classofKind(Kind K) { return K == Decl::FriendTemplate; }
2317};
2318
2319/// Declaration of an alias template.
2320///
2321/// For example:
2322/// \code
2323/// template \<typename T> using V = std::map<T*, int, MyCompare<T>>;
2324/// \endcode
2325class TypeAliasTemplateDecl : public RedeclarableTemplateDecl {
2326protected:
2327 using Common = CommonBase;
2328
2329 TypeAliasTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2330 DeclarationName Name, TemplateParameterList *Params,
2331 NamedDecl *Decl)
2332 : RedeclarableTemplateDecl(TypeAliasTemplate, C, DC, L, Name, Params,
2333 Decl) {}
2334
2335 CommonBase *newCommon(ASTContext &C) const override;
2336
2337 Common *getCommonPtr() {
2338 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2339 }
2340
2341public:
2342 friend class ASTDeclReader;
2343 friend class ASTDeclWriter;
2344
2345 /// Get the underlying function declaration of the template.
2346 TypeAliasDecl *getTemplatedDecl() const {
2347 return static_cast<TypeAliasDecl *>(TemplatedDecl);
2348 }
2349
2350
2351 TypeAliasTemplateDecl *getCanonicalDecl() override {
2352 return cast<TypeAliasTemplateDecl>(
2353 RedeclarableTemplateDecl::getCanonicalDecl());
2354 }
2355 const TypeAliasTemplateDecl *getCanonicalDecl() const {
2356 return cast<TypeAliasTemplateDecl>(
2357 RedeclarableTemplateDecl::getCanonicalDecl());
2358 }
2359
2360 /// Retrieve the previous declaration of this function template, or
2361 /// nullptr if no such declaration exists.
2362 TypeAliasTemplateDecl *getPreviousDecl() {
2363 return cast_or_null<TypeAliasTemplateDecl>(
2364 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2365 }
2366 const TypeAliasTemplateDecl *getPreviousDecl() const {
2367 return cast_or_null<TypeAliasTemplateDecl>(
2368 static_cast<const RedeclarableTemplateDecl *>(
2369 this)->getPreviousDecl());
2370 }
2371
2372 TypeAliasTemplateDecl *getInstantiatedFromMemberTemplate() const {
2373 return cast_or_null<TypeAliasTemplateDecl>(
2374 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2375 }
2376
2377 /// Create a function template node.
2378 static TypeAliasTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2379 SourceLocation L,
2380 DeclarationName Name,
2381 TemplateParameterList *Params,
2382 NamedDecl *Decl);
2383
2384 /// Create an empty alias template node.
2385 static TypeAliasTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2386
2387 // Implement isa/cast/dyncast support
2388 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2389 static bool classofKind(Kind K) { return K == TypeAliasTemplate; }
2390};
2391
2392/// Declaration of a function specialization at template class scope.
2393///
2394/// This is a non-standard extension needed to support MSVC.
2395///
2396/// For example:
2397/// \code
2398/// template <class T>
2399/// class A {
2400/// template <class U> void foo(U a) { }
2401/// template<> void foo(int a) { }
2402/// }
2403/// \endcode
2404///
2405/// "template<> foo(int a)" will be saved in Specialization as a normal
2406/// CXXMethodDecl. Then during an instantiation of class A, it will be
2407/// transformed into an actual function specialization.
2408class ClassScopeFunctionSpecializationDecl : public Decl {
2409 CXXMethodDecl *Specialization;
2410 bool HasExplicitTemplateArgs;
2411 TemplateArgumentListInfo TemplateArgs;
2412
2413 ClassScopeFunctionSpecializationDecl(DeclContext *DC, SourceLocation Loc,
2414 CXXMethodDecl *FD, bool Args,
2415 TemplateArgumentListInfo TemplArgs)
2416 : Decl(Decl::ClassScopeFunctionSpecialization, DC, Loc),
2417 Specialization(FD), HasExplicitTemplateArgs(Args),
2418 TemplateArgs(std::move(TemplArgs)) {}
2419
2420 ClassScopeFunctionSpecializationDecl(EmptyShell Empty)
2421 : Decl(Decl::ClassScopeFunctionSpecialization, Empty) {}
2422
2423 virtual void anchor();
2424
2425public:
2426 friend class ASTDeclReader;
2427 friend class ASTDeclWriter;
2428
2429 CXXMethodDecl *getSpecialization() const { return Specialization; }
2430 bool hasExplicitTemplateArgs() const { return HasExplicitTemplateArgs; }
2431 const TemplateArgumentListInfo& templateArgs() const { return TemplateArgs; }
2432
2433 static ClassScopeFunctionSpecializationDecl *Create(ASTContext &C,
2434 DeclContext *DC,
2435 SourceLocation Loc,
2436 CXXMethodDecl *FD,
2437 bool HasExplicitTemplateArgs,
2438 TemplateArgumentListInfo TemplateArgs) {
2439 return new (C, DC) ClassScopeFunctionSpecializationDecl(
2440 DC, Loc, FD, HasExplicitTemplateArgs, std::move(TemplateArgs));
2441 }
2442
2443 static ClassScopeFunctionSpecializationDecl *
2444 CreateDeserialized(ASTContext &Context, unsigned ID);
2445
2446 // Implement isa/cast/dyncast/etc.
2447 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2448
2449 static bool classofKind(Kind K) {
2450 return K == Decl::ClassScopeFunctionSpecialization;
2451 }
2452};
2453
2454/// Implementation of inline functions that require the template declarations
2455inline AnyFunctionDecl::AnyFunctionDecl(FunctionTemplateDecl *FTD)
2456 : Function(FTD) {}
2457
2458/// Represents a variable template specialization, which refers to
2459/// a variable template with a given set of template arguments.
2460///
2461/// Variable template specializations represent both explicit
2462/// specializations of variable templates, as in the example below, and
2463/// implicit instantiations of variable templates.
2464///
2465/// \code
2466/// template<typename T> constexpr T pi = T(3.1415926535897932385);
2467///
2468/// template<>
2469/// constexpr float pi<float>; // variable template specialization pi<float>
2470/// \endcode
2471class VarTemplateSpecializationDecl : public VarDecl,
2472 public llvm::FoldingSetNode {
2473
2474 /// Structure that stores information about a variable template
2475 /// specialization that was instantiated from a variable template partial
2476 /// specialization.
2477 struct SpecializedPartialSpecialization {
2478 /// The variable template partial specialization from which this
2479 /// variable template specialization was instantiated.
2480 VarTemplatePartialSpecializationDecl *PartialSpecialization;
2481
2482 /// The template argument list deduced for the variable template
2483 /// partial specialization itself.
2484 const TemplateArgumentList *TemplateArgs;
2485 };
2486
2487 /// The template that this specialization specializes.
2488 llvm::PointerUnion<VarTemplateDecl *, SpecializedPartialSpecialization *>
2489 SpecializedTemplate;
2490
2491 /// Further info for explicit template specialization/instantiation.
2492 struct ExplicitSpecializationInfo {
2493 /// The type-as-written.
2494 TypeSourceInfo *TypeAsWritten = nullptr;
2495
2496 /// The location of the extern keyword.
2497 SourceLocation ExternLoc;
2498
2499 /// The location of the template keyword.
2500 SourceLocation TemplateKeywordLoc;
2501
2502 ExplicitSpecializationInfo() = default;
2503 };
2504
2505 /// Further info for explicit template specialization/instantiation.
2506 /// Does not apply to implicit specializations.
2507 ExplicitSpecializationInfo *ExplicitInfo = nullptr;
2508
2509 /// The template arguments used to describe this specialization.
2510 const TemplateArgumentList *TemplateArgs;
2511 TemplateArgumentListInfo TemplateArgsInfo;
2512
2513 /// The point where this template was instantiated (if any).
2514 SourceLocation PointOfInstantiation;
2515
2516 /// The kind of specialization this declaration refers to.
2517 /// Really a value of type TemplateSpecializationKind.
2518 unsigned SpecializationKind : 3;
2519
2520 /// Whether this declaration is a complete definition of the
2521 /// variable template specialization. We can't otherwise tell apart
2522 /// an instantiated declaration from an instantiated definition with
2523 /// no initializer.
2524 unsigned IsCompleteDefinition : 1;
2525
2526protected:
2527 VarTemplateSpecializationDecl(Kind DK, ASTContext &Context, DeclContext *DC,
2528 SourceLocation StartLoc, SourceLocation IdLoc,
2529 VarTemplateDecl *SpecializedTemplate,
2530 QualType T, TypeSourceInfo *TInfo,
2531 StorageClass S,
2532 ArrayRef<TemplateArgument> Args);
2533
2534 explicit VarTemplateSpecializationDecl(Kind DK, ASTContext &Context);
2535
2536public:
2537 friend class ASTDeclReader;
2538 friend class ASTDeclWriter;
2539 friend class VarDecl;
2540
2541 static VarTemplateSpecializationDecl *
2542 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2543 SourceLocation IdLoc, VarTemplateDecl *SpecializedTemplate, QualType T,
2544 TypeSourceInfo *TInfo, StorageClass S,
2545 ArrayRef<TemplateArgument> Args);
2546 static VarTemplateSpecializationDecl *CreateDeserialized(ASTContext &C,
2547 unsigned ID);
2548
2549 void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy,
2550 bool Qualified) const override;
2551
2552 VarTemplateSpecializationDecl *getMostRecentDecl() {
2553 VarDecl *Recent = static_cast<VarDecl *>(this)->getMostRecentDecl();
2554 return cast<VarTemplateSpecializationDecl>(Recent);
2555 }
2556
2557 /// Retrieve the template that this specialization specializes.
2558 VarTemplateDecl *getSpecializedTemplate() const;
2559
2560 /// Retrieve the template arguments of the variable template
2561 /// specialization.
2562 const TemplateArgumentList &getTemplateArgs() const { return *TemplateArgs; }
2563
2564 // TODO: Always set this when creating the new specialization?
2565 void setTemplateArgsInfo(const TemplateArgumentListInfo &ArgsInfo);
2566
2567 const TemplateArgumentListInfo &getTemplateArgsInfo() const {
2568 return TemplateArgsInfo;
2569 }
2570
2571 /// Determine the kind of specialization that this
2572 /// declaration represents.
2573 TemplateSpecializationKind getSpecializationKind() const {
2574 return static_cast<TemplateSpecializationKind>(SpecializationKind);
2575 }
2576
2577 bool isExplicitSpecialization() const {
2578 return getSpecializationKind() == TSK_ExplicitSpecialization;
2579 }
2580
2581 /// True if this declaration is an explicit specialization,
2582 /// explicit instantiation declaration, or explicit instantiation
2583 /// definition.
2584 bool isExplicitInstantiationOrSpecialization() const {
2585 return isTemplateExplicitInstantiationOrSpecialization(
2586 getTemplateSpecializationKind());
2587 }
2588
2589 void setSpecializationKind(TemplateSpecializationKind TSK) {
2590 SpecializationKind = TSK;
2591 }
2592
2593 /// Get the point of instantiation (if any), or null if none.
2594 SourceLocation getPointOfInstantiation() const {
2595 return PointOfInstantiation;
2596 }
2597
2598 void setPointOfInstantiation(SourceLocation Loc) {
2599 assert(Loc.isValid() && "point of instantiation must be valid!")(static_cast <bool> (Loc.isValid() && "point of instantiation must be valid!"
) ? void (0) : __assert_fail ("Loc.isValid() && \"point of instantiation must be valid!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2599, __extension__ __PRETTY_FUNCTION__))
;
2600 PointOfInstantiation = Loc;
2601 }
2602
2603 void setCompleteDefinition() { IsCompleteDefinition = true; }
2604
2605 /// If this variable template specialization is an instantiation of
2606 /// a template (rather than an explicit specialization), return the
2607 /// variable template or variable template partial specialization from which
2608 /// it was instantiated.
2609 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2610 getInstantiatedFrom() const {
2611 if (!isTemplateInstantiation(getSpecializationKind()))
2612 return llvm::PointerUnion<VarTemplateDecl *,
2613 VarTemplatePartialSpecializationDecl *>();
2614
2615 return getSpecializedTemplateOrPartial();
2616 }
2617
2618 /// Retrieve the variable template or variable template partial
2619 /// specialization which was specialized by this.
2620 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
2621 getSpecializedTemplateOrPartial() const {
2622 if (const auto *PartialSpec =
2623 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2624 return PartialSpec->PartialSpecialization;
2625
2626 return SpecializedTemplate.get<VarTemplateDecl *>();
2627 }
2628
2629 /// Retrieve the set of template arguments that should be used
2630 /// to instantiate the initializer of the variable template or variable
2631 /// template partial specialization from which this variable template
2632 /// specialization was instantiated.
2633 ///
2634 /// \returns For a variable template specialization instantiated from the
2635 /// primary template, this function will return the same template arguments
2636 /// as getTemplateArgs(). For a variable template specialization instantiated
2637 /// from a variable template partial specialization, this function will the
2638 /// return deduced template arguments for the variable template partial
2639 /// specialization itself.
2640 const TemplateArgumentList &getTemplateInstantiationArgs() const {
2641 if (const auto *PartialSpec =
2642 SpecializedTemplate.dyn_cast<SpecializedPartialSpecialization *>())
2643 return *PartialSpec->TemplateArgs;
2644
2645 return getTemplateArgs();
2646 }
2647
2648 /// Note that this variable template specialization is actually an
2649 /// instantiation of the given variable template partial specialization whose
2650 /// template arguments have been deduced.
2651 void setInstantiationOf(VarTemplatePartialSpecializationDecl *PartialSpec,
2652 const TemplateArgumentList *TemplateArgs) {
2653 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2654, __extension__ __PRETTY_FUNCTION__))
2654 "Already set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Already set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Already set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2654, __extension__ __PRETTY_FUNCTION__))
;
2655 auto *PS = new (getASTContext()) SpecializedPartialSpecialization();
2656 PS->PartialSpecialization = PartialSpec;
2657 PS->TemplateArgs = TemplateArgs;
2658 SpecializedTemplate = PS;
2659 }
2660
2661 /// Note that this variable template specialization is an instantiation
2662 /// of the given variable template.
2663 void setInstantiationOf(VarTemplateDecl *TemplDecl) {
2664 assert(!SpecializedTemplate.is<SpecializedPartialSpecialization *>() &&(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2665, __extension__ __PRETTY_FUNCTION__))
2665 "Previously set to a variable template partial specialization!")(static_cast <bool> (!SpecializedTemplate.is<SpecializedPartialSpecialization
*>() && "Previously set to a variable template partial specialization!"
) ? void (0) : __assert_fail ("!SpecializedTemplate.is<SpecializedPartialSpecialization *>() && \"Previously set to a variable template partial specialization!\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2665, __extension__ __PRETTY_FUNCTION__))
;
2666 SpecializedTemplate = TemplDecl;
2667 }
2668
2669 /// Sets the type of this specialization as it was written by
2670 /// the user.
2671 void setTypeAsWritten(TypeSourceInfo *T) {
2672 if (!ExplicitInfo)
2673 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2674 ExplicitInfo->TypeAsWritten = T;
2675 }
2676
2677 /// Gets the type of this specialization as it was written by
2678 /// the user, if it was so written.
2679 TypeSourceInfo *getTypeAsWritten() const {
2680 return ExplicitInfo ? ExplicitInfo->TypeAsWritten : nullptr;
2681 }
2682
2683 /// Gets the location of the extern keyword, if present.
2684 SourceLocation getExternLoc() const {
2685 return ExplicitInfo ? ExplicitInfo->ExternLoc : SourceLocation();
2686 }
2687
2688 /// Sets the location of the extern keyword.
2689 void setExternLoc(SourceLocation Loc) {
2690 if (!ExplicitInfo)
2691 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2692 ExplicitInfo->ExternLoc = Loc;
2693 }
2694
2695 /// Sets the location of the template keyword.
2696 void setTemplateKeywordLoc(SourceLocation Loc) {
2697 if (!ExplicitInfo)
2698 ExplicitInfo = new (getASTContext()) ExplicitSpecializationInfo;
2699 ExplicitInfo->TemplateKeywordLoc = Loc;
2700 }
2701
2702 /// Gets the location of the template keyword, if present.
2703 SourceLocation getTemplateKeywordLoc() const {
2704 return ExplicitInfo ? ExplicitInfo->TemplateKeywordLoc : SourceLocation();
2705 }
2706
2707 void Profile(llvm::FoldingSetNodeID &ID) const {
2708 Profile(ID, TemplateArgs->asArray(), getASTContext());
2709 }
2710
2711 static void Profile(llvm::FoldingSetNodeID &ID,
2712 ArrayRef<TemplateArgument> TemplateArgs,
2713 ASTContext &Context) {
2714 ID.AddInteger(TemplateArgs.size());
2715 for (const TemplateArgument &TemplateArg : TemplateArgs)
2716 TemplateArg.Profile(ID, Context);
2717 }
2718
2719 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2720
2721 static bool classofKind(Kind K) {
2722 return K >= firstVarTemplateSpecialization &&
2723 K <= lastVarTemplateSpecialization;
2724 }
2725};
2726
2727class VarTemplatePartialSpecializationDecl
2728 : public VarTemplateSpecializationDecl {
2729 /// The list of template parameters
2730 TemplateParameterList *TemplateParams = nullptr;
2731
2732 /// The source info for the template arguments as written.
2733 /// FIXME: redundant with TypeAsWritten?
2734 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2735
2736 /// The variable template partial specialization from which this
2737 /// variable template partial specialization was instantiated.
2738 ///
2739 /// The boolean value will be true to indicate that this variable template
2740 /// partial specialization was specialized at this level.
2741 llvm::PointerIntPair<VarTemplatePartialSpecializationDecl *, 1, bool>
2742 InstantiatedFromMember;
2743
2744 VarTemplatePartialSpecializationDecl(
2745 ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2746 SourceLocation IdLoc, TemplateParameterList *Params,
2747 VarTemplateDecl *SpecializedTemplate, QualType T, TypeSourceInfo *TInfo,
2748 StorageClass S, ArrayRef<TemplateArgument> Args,
2749 const ASTTemplateArgumentListInfo *ArgInfos);
2750
2751 VarTemplatePartialSpecializationDecl(ASTContext &Context)
2752 : VarTemplateSpecializationDecl(VarTemplatePartialSpecialization,
2753 Context),
2754 InstantiatedFromMember(nullptr, false) {}
2755
2756 void anchor() override;
2757
2758public:
2759 friend class ASTDeclReader;
2760 friend class ASTDeclWriter;
2761
2762 static VarTemplatePartialSpecializationDecl *
2763 Create(ASTContext &Context, DeclContext *DC, SourceLocation StartLoc,
2764 SourceLocation IdLoc, TemplateParameterList *Params,
2765 VarTemplateDecl *SpecializedTemplate, QualType T,
2766 TypeSourceInfo *TInfo, StorageClass S, ArrayRef<TemplateArgument> Args,
2767 const TemplateArgumentListInfo &ArgInfos);
2768
2769 static VarTemplatePartialSpecializationDecl *CreateDeserialized(ASTContext &C,
2770 unsigned ID);
2771
2772 VarTemplatePartialSpecializationDecl *getMostRecentDecl() {
2773 return cast<VarTemplatePartialSpecializationDecl>(
2774 static_cast<VarTemplateSpecializationDecl *>(
2775 this)->getMostRecentDecl());
2776 }
2777
2778 /// Get the list of template parameters
2779 TemplateParameterList *getTemplateParameters() const {
2780 return TemplateParams;
2781 }
2782
2783 /// Get the template arguments as written.
2784 const ASTTemplateArgumentListInfo *getTemplateArgsAsWritten() const {
2785 return ArgsAsWritten;
2786 }
2787
2788 /// Retrieve the member variable template partial specialization from
2789 /// which this particular variable template partial specialization was
2790 /// instantiated.
2791 ///
2792 /// \code
2793 /// template<typename T>
2794 /// struct Outer {
2795 /// template<typename U> U Inner;
2796 /// template<typename U> U* Inner<U*> = (U*)(0); // #1
2797 /// };
2798 ///
2799 /// template int* Outer<float>::Inner<int*>;
2800 /// \endcode
2801 ///
2802 /// In this example, the instantiation of \c Outer<float>::Inner<int*> will
2803 /// end up instantiating the partial specialization
2804 /// \c Outer<float>::Inner<U*>, which itself was instantiated from the
2805 /// variable template partial specialization \c Outer<T>::Inner<U*>. Given
2806 /// \c Outer<float>::Inner<U*>, this function would return
2807 /// \c Outer<T>::Inner<U*>.
2808 VarTemplatePartialSpecializationDecl *getInstantiatedFromMember() const {
2809 const auto *First =
2810 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2811 return First->InstantiatedFromMember.getPointer();
2812 }
2813
2814 void
2815 setInstantiatedFromMember(VarTemplatePartialSpecializationDecl *PartialSpec) {
2816 auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2817 First->InstantiatedFromMember.setPointer(PartialSpec);
2818 }
2819
2820 /// Determines whether this variable template partial specialization
2821 /// was a specialization of a member partial specialization.
2822 ///
2823 /// In the following example, the member template partial specialization
2824 /// \c X<int>::Inner<T*> is a member specialization.
2825 ///
2826 /// \code
2827 /// template<typename T>
2828 /// struct X {
2829 /// template<typename U> U Inner;
2830 /// template<typename U> U* Inner<U*> = (U*)(0);
2831 /// };
2832 ///
2833 /// template<> template<typename T>
2834 /// U* X<int>::Inner<T*> = (T*)(0) + 1;
2835 /// \endcode
2836 bool isMemberSpecialization() {
2837 const auto *First =
2838 cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2839 return First->InstantiatedFromMember.getInt();
2840 }
2841
2842 /// Note that this member template is a specialization.
2843 void setMemberSpecialization() {
2844 auto *First = cast<VarTemplatePartialSpecializationDecl>(getFirstDecl());
2845 assert(First->InstantiatedFromMember.getPointer() &&(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2846, __extension__ __PRETTY_FUNCTION__))
2846 "Only member templates can be member template specializations")(static_cast <bool> (First->InstantiatedFromMember.getPointer
() && "Only member templates can be member template specializations"
) ? void (0) : __assert_fail ("First->InstantiatedFromMember.getPointer() && \"Only member templates can be member template specializations\""
, "/build/llvm-toolchain-snapshot-7~svn337204/tools/clang/include/clang/AST/DeclTemplate.h"
, 2846, __extension__ __PRETTY_FUNCTION__))
;
2847 return First->InstantiatedFromMember.setInt(true);
2848 }
2849
2850 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
2851
2852 static bool classofKind(Kind K) {
2853 return K == VarTemplatePartialSpecialization;
2854 }
2855};
2856
2857/// Declaration of a variable template.
2858class VarTemplateDecl : public RedeclarableTemplateDecl {
2859protected:
2860 /// Data that is common to all of the declarations of a given
2861 /// variable template.
2862 struct Common : CommonBase {
2863 /// The variable template specializations for this variable
2864 /// template, including explicit specializations and instantiations.
2865 llvm::FoldingSetVector<VarTemplateSpecializationDecl> Specializations;
2866
2867 /// The variable template partial specializations for this variable
2868 /// template.
2869 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl>
2870 PartialSpecializations;
2871
2872 Common() = default;
2873 };
2874
2875 /// Retrieve the set of specializations of this variable template.
2876 llvm::FoldingSetVector<VarTemplateSpecializationDecl> &
2877 getSpecializations() const;
2878
2879 /// Retrieve the set of partial specializations of this class
2880 /// template.
2881 llvm::FoldingSetVector<VarTemplatePartialSpecializationDecl> &
2882 getPartialSpecializations();
2883
2884 VarTemplateDecl(ASTContext &C, DeclContext *DC, SourceLocation L,
2885 DeclarationName Name, TemplateParameterList *Params,
2886 NamedDecl *Decl)
2887 : RedeclarableTemplateDecl(VarTemplate, C, DC, L, Name, Params, Decl) {}
2888
2889 CommonBase *newCommon(ASTContext &C) const override;
2890
2891 Common *getCommonPtr() const {
2892 return static_cast<Common *>(RedeclarableTemplateDecl::getCommonPtr());
2893 }
2894
2895public:
2896 friend class ASTDeclReader;
2897 friend class ASTDeclWriter;
2898
2899 /// Load any lazily-loaded specializations from the external source.
2900 void LoadLazySpecializations() const;
2901
2902 /// Get the underlying variable declarations of the template.
2903 VarDecl *getTemplatedDecl() const {
2904 return static_cast<VarDecl *>(TemplatedDecl);
2905 }
2906
2907 /// Returns whether this template declaration defines the primary
2908 /// variable pattern.
2909 bool isThisDeclarationADefinition() const {
2910 return getTemplatedDecl()->isThisDeclarationADefinition();
2911 }
2912
2913 VarTemplateDecl *getDefinition();
2914
2915 /// Create a variable template node.
2916 static VarTemplateDecl *Create(ASTContext &C, DeclContext *DC,
2917 SourceLocation L, DeclarationName Name,
2918 TemplateParameterList *Params,
2919 VarDecl *Decl);
2920
2921 /// Create an empty variable template node.
2922 static VarTemplateDecl *CreateDeserialized(ASTContext &C, unsigned ID);
2923
2924 /// Return the specialization with the provided arguments if it exists,
2925 /// otherwise return the insertion point.
2926 VarTemplateSpecializationDecl *
2927 findSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2928
2929 /// Insert the specified specialization knowing that it is not already
2930 /// in. InsertPos must be obtained from findSpecialization.
2931 void AddSpecialization(VarTemplateSpecializationDecl *D, void *InsertPos);
2932
2933 VarTemplateDecl *getCanonicalDecl() override {
2934 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2935 }
2936 const VarTemplateDecl *getCanonicalDecl() const {
2937 return cast<VarTemplateDecl>(RedeclarableTemplateDecl::getCanonicalDecl());
2938 }
2939
2940 /// Retrieve the previous declaration of this variable template, or
2941 /// nullptr if no such declaration exists.
2942 VarTemplateDecl *getPreviousDecl() {
2943 return cast_or_null<VarTemplateDecl>(
2944 static_cast<RedeclarableTemplateDecl *>(this)->getPreviousDecl());
2945 }
2946 const VarTemplateDecl *getPreviousDecl() const {
2947 return cast_or_null<VarTemplateDecl>(
2948 static_cast<const RedeclarableTemplateDecl *>(
2949 this)->getPreviousDecl());
2950 }
2951
2952 VarTemplateDecl *getMostRecentDecl() {
2953 return cast<VarTemplateDecl>(
2954 static_cast<RedeclarableTemplateDecl *>(this)->getMostRecentDecl());
2955 }
2956 const VarTemplateDecl *getMostRecentDecl() const {
2957 return const_cast<VarTemplateDecl *>(this)->getMostRecentDecl();
2958 }
2959
2960 VarTemplateDecl *getInstantiatedFromMemberTemplate() const {
2961 return cast_or_null<VarTemplateDecl>(
2962 RedeclarableTemplateDecl::getInstantiatedFromMemberTemplate());
2963 }
2964
2965 /// Return the partial specialization with the provided arguments if it
2966 /// exists, otherwise return the insertion point.
2967 VarTemplatePartialSpecializationDecl *
2968 findPartialSpecialization(ArrayRef<TemplateArgument> Args, void *&InsertPos);
2969
2970 /// Insert the specified partial specialization knowing that it is not
2971 /// already in. InsertPos must be obtained from findPartialSpecialization.
2972 void AddPartialSpecialization(VarTemplatePartialSpecializationDecl *D,
2973 void *InsertPos);
2974
2975 /// Retrieve the partial specializations as an ordered list.
2976 void getPartialSpecializations(
2977 SmallVectorImpl<VarTemplatePartialSpecializationDecl *> &PS);
2978
2979 /// Find a variable template partial specialization which was
2980 /// instantiated
2981 /// from the given member partial specialization.
2982 ///
2983 /// \param D a member variable template partial specialization.
2984 ///
2985 /// \returns the variable template partial specialization which was
2986 /// instantiated
2987 /// from the given member partial specialization, or nullptr if no such
2988 /// partial specialization exists.
2989 VarTemplatePartialSpecializationDecl *findPartialSpecInstantiatedFromMember(
2990 VarTemplatePartialSpecializationDecl *D);
2991
2992 using spec_iterator = SpecIterator<VarTemplateSpecializationDecl>;
2993 using spec_range = llvm::iterator_range<spec_iterator>;
2994
2995 spec_range specializations() const {
2996 return spec_range(spec_begin(), spec_end());
2997 }
2998
2999 spec_iterator spec_begin() const {
3000 return makeSpecIterator(getSpecializations(), false);
3001 }
3002
3003 spec_iterator spec_end() const {
3004 return makeSpecIterator(getSpecializations(), true);
3005 }
3006
3007 // Implement isa/cast/dyncast support
3008 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
3009 static bool classofKind(Kind K) { return K == VarTemplate; }
3010};
3011
3012inline NamedDecl *getAsNamedDecl(TemplateParameter P) {
3013 if (auto *PD = P.dyn_cast<TemplateTypeParmDecl *>())
3014 return PD;
3015 if (auto *PD = P.dyn_cast<NonTypeTemplateParmDecl *>())
3016 return PD;
3017 return P.get<TemplateTemplateParmDecl *>();
3018}
3019
3020inline TemplateDecl *getAsTypeTemplateDecl(Decl *D) {
3021 auto *TD = dyn_cast<TemplateDecl>(D);
3022 return TD && (isa<ClassTemplateDecl>(TD) ||
3023 isa<ClassTemplatePartialSpecializationDecl>(TD) ||
3024 isa<TypeAliasTemplateDecl>(TD) ||
3025 isa<TemplateTemplateParmDecl>(TD))
3026 ? TD
3027 : nullptr;
3028}
3029
3030} // namespace clang
3031
3032#endif // LLVM_CLANG_AST_DECLTEMPLATE_H