Bug Summary

File:build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplateVariadic.cpp
Warning:line 704, column 11
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateVariadic.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -resource-dir /usr/lib/llvm-16/lib/clang/16.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-16/lib/clang/16.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2022-09-04-125545-48738-1 -x c++ /build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplateVariadic.cpp

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/lib/Sema/SemaTemplateVariadic.cpp

1//===------- SemaTemplateVariadic.cpp - C++ Variadic Templates ------------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements semantic analysis for C++0x variadic templates.
9//===----------------------------------------------------------------------===/
10
11#include "clang/Sema/Sema.h"
12#include "TypeLocBuilder.h"
13#include "clang/AST/Expr.h"
14#include "clang/AST/RecursiveASTVisitor.h"
15#include "clang/AST/TypeLoc.h"
16#include "clang/Sema/Lookup.h"
17#include "clang/Sema/ParsedTemplate.h"
18#include "clang/Sema/ScopeInfo.h"
19#include "clang/Sema/SemaInternal.h"
20#include "clang/Sema/Template.h"
21
22using namespace clang;
23
24//----------------------------------------------------------------------------
25// Visitor that collects unexpanded parameter packs
26//----------------------------------------------------------------------------
27
28namespace {
29 /// A class that collects unexpanded parameter packs.
30 class CollectUnexpandedParameterPacksVisitor :
31 public RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
32 {
33 typedef RecursiveASTVisitor<CollectUnexpandedParameterPacksVisitor>
34 inherited;
35
36 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded;
37
38 bool InLambda = false;
39 unsigned DepthLimit = (unsigned)-1;
40
41 void addUnexpanded(NamedDecl *ND, SourceLocation Loc = SourceLocation()) {
42 if (auto *VD = dyn_cast<VarDecl>(ND)) {
43 // For now, the only problematic case is a generic lambda's templated
44 // call operator, so we don't need to look for all the other ways we
45 // could have reached a dependent parameter pack.
46 auto *FD = dyn_cast<FunctionDecl>(VD->getDeclContext());
47 auto *FTD = FD ? FD->getDescribedFunctionTemplate() : nullptr;
48 if (FTD && FTD->getTemplateParameters()->getDepth() >= DepthLimit)
49 return;
50 } else if (getDepthAndIndex(ND).first >= DepthLimit)
51 return;
52
53 Unexpanded.push_back({ND, Loc});
54 }
55 void addUnexpanded(const TemplateTypeParmType *T,
56 SourceLocation Loc = SourceLocation()) {
57 if (T->getDepth() < DepthLimit)
58 Unexpanded.push_back({T, Loc});
59 }
60
61 public:
62 explicit CollectUnexpandedParameterPacksVisitor(
63 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded)
64 : Unexpanded(Unexpanded) {}
65
66 bool shouldWalkTypesOfTypeLocs() const { return false; }
67
68 //------------------------------------------------------------------------
69 // Recording occurrences of (unexpanded) parameter packs.
70 //------------------------------------------------------------------------
71
72 /// Record occurrences of template type parameter packs.
73 bool VisitTemplateTypeParmTypeLoc(TemplateTypeParmTypeLoc TL) {
74 if (TL.getTypePtr()->isParameterPack())
75 addUnexpanded(TL.getTypePtr(), TL.getNameLoc());
76 return true;
77 }
78
79 /// Record occurrences of template type parameter packs
80 /// when we don't have proper source-location information for
81 /// them.
82 ///
83 /// Ideally, this routine would never be used.
84 bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {
85 if (T->isParameterPack())
86 addUnexpanded(T);
87
88 return true;
89 }
90
91 bool
92 VisitSubstTemplateTypeParmPackTypeLoc(SubstTemplateTypeParmPackTypeLoc TL) {
93 Unexpanded.push_back({TL.getTypePtr(), TL.getNameLoc()});
94 return true;
95 }
96
97 bool VisitSubstTemplateTypeParmPackType(SubstTemplateTypeParmPackType *T) {
98 Unexpanded.push_back({T, SourceLocation()});
99 return true;
100 }
101
102 bool
103 VisitSubstNonTypeTemplateParmPackExpr(SubstNonTypeTemplateParmPackExpr *E) {
104 Unexpanded.push_back({E, E->getParameterPackLocation()});
105 return true;
106 }
107
108 /// Record occurrences of function and non-type template
109 /// parameter packs in an expression.
110 bool VisitDeclRefExpr(DeclRefExpr *E) {
111 if (E->getDecl()->isParameterPack())
112 addUnexpanded(E->getDecl(), E->getLocation());
113
114 return true;
115 }
116
117 /// Record occurrences of template template parameter packs.
118 bool TraverseTemplateName(TemplateName Template) {
119 if (auto *TTP = dyn_cast_or_null<TemplateTemplateParmDecl>(
120 Template.getAsTemplateDecl())) {
121 if (TTP->isParameterPack())
122 addUnexpanded(TTP);
123 }
124
125 return inherited::TraverseTemplateName(Template);
126 }
127
128 /// Suppress traversal into Objective-C container literal
129 /// elements that are pack expansions.
130 bool TraverseObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
131 if (!E->containsUnexpandedParameterPack())
132 return true;
133
134 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
135 ObjCDictionaryElement Element = E->getKeyValueElement(I);
136 if (Element.isPackExpansion())
137 continue;
138
139 TraverseStmt(Element.Key);
140 TraverseStmt(Element.Value);
141 }
142 return true;
143 }
144 //------------------------------------------------------------------------
145 // Pruning the search for unexpanded parameter packs.
146 //------------------------------------------------------------------------
147
148 /// Suppress traversal into statements and expressions that
149 /// do not contain unexpanded parameter packs.
150 bool TraverseStmt(Stmt *S) {
151 Expr *E = dyn_cast_or_null<Expr>(S);
152 if ((E && E->containsUnexpandedParameterPack()) || InLambda)
153 return inherited::TraverseStmt(S);
154
155 return true;
156 }
157
158 /// Suppress traversal into types that do not contain
159 /// unexpanded parameter packs.
160 bool TraverseType(QualType T) {
161 if ((!T.isNull() && T->containsUnexpandedParameterPack()) || InLambda)
162 return inherited::TraverseType(T);
163
164 return true;
165 }
166
167 /// Suppress traversal into types with location information
168 /// that do not contain unexpanded parameter packs.
169 bool TraverseTypeLoc(TypeLoc TL) {
170 if ((!TL.getType().isNull() &&
171 TL.getType()->containsUnexpandedParameterPack()) ||
172 InLambda)
173 return inherited::TraverseTypeLoc(TL);
174
175 return true;
176 }
177
178 /// Suppress traversal of parameter packs.
179 bool TraverseDecl(Decl *D) {
180 // A function parameter pack is a pack expansion, so cannot contain
181 // an unexpanded parameter pack. Likewise for a template parameter
182 // pack that contains any references to other packs.
183 if (D && D->isParameterPack())
184 return true;
185
186 return inherited::TraverseDecl(D);
187 }
188
189 /// Suppress traversal of pack-expanded attributes.
190 bool TraverseAttr(Attr *A) {
191 if (A->isPackExpansion())
192 return true;
193
194 return inherited::TraverseAttr(A);
195 }
196
197 /// Suppress traversal of pack expansion expressions and types.
198 ///@{
199 bool TraversePackExpansionType(PackExpansionType *T) { return true; }
200 bool TraversePackExpansionTypeLoc(PackExpansionTypeLoc TL) { return true; }
201 bool TraversePackExpansionExpr(PackExpansionExpr *E) { return true; }
202 bool TraverseCXXFoldExpr(CXXFoldExpr *E) { return true; }
203
204 ///@}
205
206 /// Suppress traversal of using-declaration pack expansion.
207 bool TraverseUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
208 if (D->isPackExpansion())
209 return true;
210
211 return inherited::TraverseUnresolvedUsingValueDecl(D);
212 }
213
214 /// Suppress traversal of using-declaration pack expansion.
215 bool TraverseUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D) {
216 if (D->isPackExpansion())
217 return true;
218
219 return inherited::TraverseUnresolvedUsingTypenameDecl(D);
220 }
221
222 /// Suppress traversal of template argument pack expansions.
223 bool TraverseTemplateArgument(const TemplateArgument &Arg) {
224 if (Arg.isPackExpansion())
225 return true;
226
227 return inherited::TraverseTemplateArgument(Arg);
228 }
229
230 /// Suppress traversal of template argument pack expansions.
231 bool TraverseTemplateArgumentLoc(const TemplateArgumentLoc &ArgLoc) {
232 if (ArgLoc.getArgument().isPackExpansion())
233 return true;
234
235 return inherited::TraverseTemplateArgumentLoc(ArgLoc);
236 }
237
238 /// Suppress traversal of base specifier pack expansions.
239 bool TraverseCXXBaseSpecifier(const CXXBaseSpecifier &Base) {
240 if (Base.isPackExpansion())
241 return true;
242
243 return inherited::TraverseCXXBaseSpecifier(Base);
244 }
245
246 /// Suppress traversal of mem-initializer pack expansions.
247 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
248 if (Init->isPackExpansion())
249 return true;
250
251 return inherited::TraverseConstructorInitializer(Init);
252 }
253
254 /// Note whether we're traversing a lambda containing an unexpanded
255 /// parameter pack. In this case, the unexpanded pack can occur anywhere,
256 /// including all the places where we normally wouldn't look. Within a
257 /// lambda, we don't propagate the 'contains unexpanded parameter pack' bit
258 /// outside an expression.
259 bool TraverseLambdaExpr(LambdaExpr *Lambda) {
260 // The ContainsUnexpandedParameterPack bit on a lambda is always correct,
261 // even if it's contained within another lambda.
262 if (!Lambda->containsUnexpandedParameterPack())
263 return true;
264
265 bool WasInLambda = InLambda;
266 unsigned OldDepthLimit = DepthLimit;
267
268 InLambda = true;
269 if (auto *TPL = Lambda->getTemplateParameterList())
270 DepthLimit = TPL->getDepth();
271
272 inherited::TraverseLambdaExpr(Lambda);
273
274 InLambda = WasInLambda;
275 DepthLimit = OldDepthLimit;
276 return true;
277 }
278
279 /// Suppress traversal within pack expansions in lambda captures.
280 bool TraverseLambdaCapture(LambdaExpr *Lambda, const LambdaCapture *C,
281 Expr *Init) {
282 if (C->isPackExpansion())
283 return true;
284
285 return inherited::TraverseLambdaCapture(Lambda, C, Init);
286 }
287 };
288}
289
290/// Determine whether it's possible for an unexpanded parameter pack to
291/// be valid in this location. This only happens when we're in a declaration
292/// that is nested within an expression that could be expanded, such as a
293/// lambda-expression within a function call.
294///
295/// This is conservatively correct, but may claim that some unexpanded packs are
296/// permitted when they are not.
297bool Sema::isUnexpandedParameterPackPermitted() {
298 for (auto *SI : FunctionScopes)
299 if (isa<sema::LambdaScopeInfo>(SI))
300 return true;
301 return false;
302}
303
304/// Diagnose all of the unexpanded parameter packs in the given
305/// vector.
306bool
307Sema::DiagnoseUnexpandedParameterPacks(SourceLocation Loc,
308 UnexpandedParameterPackContext UPPC,
309 ArrayRef<UnexpandedParameterPack> Unexpanded) {
310 if (Unexpanded.empty())
311 return false;
312
313 // If we are within a lambda expression and referencing a pack that is not
314 // declared within the lambda itself, that lambda contains an unexpanded
315 // parameter pack, and we are done.
316 // FIXME: Store 'Unexpanded' on the lambda so we don't need to recompute it
317 // later.
318 SmallVector<UnexpandedParameterPack, 4> LambdaParamPackReferences;
319 if (auto *LSI = getEnclosingLambda()) {
320 for (auto &Pack : Unexpanded) {
321 auto DeclaresThisPack = [&](NamedDecl *LocalPack) {
322 if (auto *TTPT = Pack.first.dyn_cast<const TemplateTypeParmType *>()) {
323 auto *TTPD = dyn_cast<TemplateTypeParmDecl>(LocalPack);
324 return TTPD && TTPD->getTypeForDecl() == TTPT;
325 }
326 return declaresSameEntity(Pack.first.get<const NamedDecl *>(),
327 LocalPack);
328 };
329 if (llvm::any_of(LSI->LocalPacks, DeclaresThisPack))
330 LambdaParamPackReferences.push_back(Pack);
331 }
332
333 if (LambdaParamPackReferences.empty()) {
334 // Construct in lambda only references packs declared outside the lambda.
335 // That's OK for now, but the lambda itself is considered to contain an
336 // unexpanded pack in this case, which will require expansion outside the
337 // lambda.
338
339 // We do not permit pack expansion that would duplicate a statement
340 // expression, not even within a lambda.
341 // FIXME: We could probably support this for statement expressions that
342 // do not contain labels.
343 // FIXME: This is insufficient to detect this problem; consider
344 // f( ({ bad: 0; }) + pack ... );
345 bool EnclosingStmtExpr = false;
346 for (unsigned N = FunctionScopes.size(); N; --N) {
347 sema::FunctionScopeInfo *Func = FunctionScopes[N-1];
348 if (llvm::any_of(
349 Func->CompoundScopes,
350 [](sema::CompoundScopeInfo &CSI) { return CSI.IsStmtExpr; })) {
351 EnclosingStmtExpr = true;
352 break;
353 }
354 // Coumpound-statements outside the lambda are OK for now; we'll check
355 // for those when we finish handling the lambda.
356 if (Func == LSI)
357 break;
358 }
359
360 if (!EnclosingStmtExpr) {
361 LSI->ContainsUnexpandedParameterPack = true;
362 return false;
363 }
364 } else {
365 Unexpanded = LambdaParamPackReferences;
366 }
367 }
368
369 SmallVector<SourceLocation, 4> Locations;
370 SmallVector<IdentifierInfo *, 4> Names;
371 llvm::SmallPtrSet<IdentifierInfo *, 4> NamesKnown;
372
373 for (unsigned I = 0, N = Unexpanded.size(); I != N; ++I) {
374 IdentifierInfo *Name = nullptr;
375 if (const TemplateTypeParmType *TTP
376 = Unexpanded[I].first.dyn_cast<const TemplateTypeParmType *>())
377 Name = TTP->getIdentifier();
378 else
379 Name = Unexpanded[I].first.get<const NamedDecl *>()->getIdentifier();
380
381 if (Name && NamesKnown.insert(Name).second)
382 Names.push_back(Name);
383
384 if (Unexpanded[I].second.isValid())
385 Locations.push_back(Unexpanded[I].second);
386 }
387
388 auto DB = Diag(Loc, diag::err_unexpanded_parameter_pack)
389 << (int)UPPC << (int)Names.size();
390 for (size_t I = 0, E = std::min(Names.size(), (size_t)2); I != E; ++I)
391 DB << Names[I];
392
393 for (unsigned I = 0, N = Locations.size(); I != N; ++I)
394 DB << SourceRange(Locations[I]);
395 return true;
396}
397
398bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
399 TypeSourceInfo *T,
400 UnexpandedParameterPackContext UPPC) {
401 // C++0x [temp.variadic]p5:
402 // An appearance of a name of a parameter pack that is not expanded is
403 // ill-formed.
404 if (!T->getType()->containsUnexpandedParameterPack())
405 return false;
406
407 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
408 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(
409 T->getTypeLoc());
410 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 410, __extension__
__PRETTY_FUNCTION__))
;
411 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
412}
413
414bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
415 UnexpandedParameterPackContext UPPC) {
416 // C++0x [temp.variadic]p5:
417 // An appearance of a name of a parameter pack that is not expanded is
418 // ill-formed.
419 if (!E->containsUnexpandedParameterPack())
420 return false;
421
422 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
423 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
424 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 424, __extension__
__PRETTY_FUNCTION__))
;
425 return DiagnoseUnexpandedParameterPacks(E->getBeginLoc(), UPPC, Unexpanded);
426}
427
428bool Sema::DiagnoseUnexpandedParameterPackInRequiresExpr(RequiresExpr *RE) {
429 if (!RE->containsUnexpandedParameterPack())
430 return false;
431
432 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
433 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(RE);
434 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 434, __extension__
__PRETTY_FUNCTION__))
;
435
436 // We only care about unexpanded references to the RequiresExpr's own
437 // parameter packs.
438 auto Parms = RE->getLocalParameters();
439 llvm::SmallPtrSet<NamedDecl*, 8> ParmSet(Parms.begin(), Parms.end());
440 SmallVector<UnexpandedParameterPack, 2> UnexpandedParms;
441 for (auto Parm : Unexpanded)
442 if (ParmSet.contains(Parm.first.dyn_cast<const NamedDecl *>()))
443 UnexpandedParms.push_back(Parm);
444 if (UnexpandedParms.empty())
445 return false;
446
447 return DiagnoseUnexpandedParameterPacks(RE->getBeginLoc(), UPPC_Requirement,
448 UnexpandedParms);
449}
450
451bool Sema::DiagnoseUnexpandedParameterPack(const CXXScopeSpec &SS,
452 UnexpandedParameterPackContext UPPC) {
453 // C++0x [temp.variadic]p5:
454 // An appearance of a name of a parameter pack that is not expanded is
455 // ill-formed.
456 if (!SS.getScopeRep() ||
457 !SS.getScopeRep()->containsUnexpandedParameterPack())
458 return false;
459
460 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
461 CollectUnexpandedParameterPacksVisitor(Unexpanded)
462 .TraverseNestedNameSpecifier(SS.getScopeRep());
463 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 463, __extension__
__PRETTY_FUNCTION__))
;
464 return DiagnoseUnexpandedParameterPacks(SS.getRange().getBegin(),
465 UPPC, Unexpanded);
466}
467
468bool Sema::DiagnoseUnexpandedParameterPack(const DeclarationNameInfo &NameInfo,
469 UnexpandedParameterPackContext UPPC) {
470 // C++0x [temp.variadic]p5:
471 // An appearance of a name of a parameter pack that is not expanded is
472 // ill-formed.
473 switch (NameInfo.getName().getNameKind()) {
474 case DeclarationName::Identifier:
475 case DeclarationName::ObjCZeroArgSelector:
476 case DeclarationName::ObjCOneArgSelector:
477 case DeclarationName::ObjCMultiArgSelector:
478 case DeclarationName::CXXOperatorName:
479 case DeclarationName::CXXLiteralOperatorName:
480 case DeclarationName::CXXUsingDirective:
481 case DeclarationName::CXXDeductionGuideName:
482 return false;
483
484 case DeclarationName::CXXConstructorName:
485 case DeclarationName::CXXDestructorName:
486 case DeclarationName::CXXConversionFunctionName:
487 // FIXME: We shouldn't need this null check!
488 if (TypeSourceInfo *TSInfo = NameInfo.getNamedTypeInfo())
489 return DiagnoseUnexpandedParameterPack(NameInfo.getLoc(), TSInfo, UPPC);
490
491 if (!NameInfo.getName().getCXXNameType()->containsUnexpandedParameterPack())
492 return false;
493
494 break;
495 }
496
497 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
498 CollectUnexpandedParameterPacksVisitor(Unexpanded)
499 .TraverseType(NameInfo.getName().getCXXNameType());
500 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 500, __extension__
__PRETTY_FUNCTION__))
;
501 return DiagnoseUnexpandedParameterPacks(NameInfo.getLoc(), UPPC, Unexpanded);
502}
503
504bool Sema::DiagnoseUnexpandedParameterPack(SourceLocation Loc,
505 TemplateName Template,
506 UnexpandedParameterPackContext UPPC) {
507
508 if (Template.isNull() || !Template.containsUnexpandedParameterPack())
509 return false;
510
511 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
512 CollectUnexpandedParameterPacksVisitor(Unexpanded)
513 .TraverseTemplateName(Template);
514 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 514, __extension__
__PRETTY_FUNCTION__))
;
515 return DiagnoseUnexpandedParameterPacks(Loc, UPPC, Unexpanded);
516}
517
518bool Sema::DiagnoseUnexpandedParameterPack(TemplateArgumentLoc Arg,
519 UnexpandedParameterPackContext UPPC) {
520 if (Arg.getArgument().isNull() ||
521 !Arg.getArgument().containsUnexpandedParameterPack())
522 return false;
523
524 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
525 CollectUnexpandedParameterPacksVisitor(Unexpanded)
526 .TraverseTemplateArgumentLoc(Arg);
527 assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs")(static_cast <bool> (!Unexpanded.empty() && "Unable to find unexpanded parameter packs"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Unable to find unexpanded parameter packs\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 527, __extension__
__PRETTY_FUNCTION__))
;
528 return DiagnoseUnexpandedParameterPacks(Arg.getLocation(), UPPC, Unexpanded);
529}
530
531void Sema::collectUnexpandedParameterPacks(TemplateArgument Arg,
532 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
533 CollectUnexpandedParameterPacksVisitor(Unexpanded)
534 .TraverseTemplateArgument(Arg);
535}
536
537void Sema::collectUnexpandedParameterPacks(TemplateArgumentLoc Arg,
538 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
539 CollectUnexpandedParameterPacksVisitor(Unexpanded)
540 .TraverseTemplateArgumentLoc(Arg);
541}
542
543void Sema::collectUnexpandedParameterPacks(QualType T,
544 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
545 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(T);
546}
547
548void Sema::collectUnexpandedParameterPacks(TypeLoc TL,
549 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
550 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseTypeLoc(TL);
551}
552
553void Sema::collectUnexpandedParameterPacks(
554 NestedNameSpecifierLoc NNS,
555 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
556 CollectUnexpandedParameterPacksVisitor(Unexpanded)
557 .TraverseNestedNameSpecifierLoc(NNS);
558}
559
560void Sema::collectUnexpandedParameterPacks(
561 const DeclarationNameInfo &NameInfo,
562 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
563 CollectUnexpandedParameterPacksVisitor(Unexpanded)
564 .TraverseDeclarationNameInfo(NameInfo);
565}
566
567
568ParsedTemplateArgument
569Sema::ActOnPackExpansion(const ParsedTemplateArgument &Arg,
570 SourceLocation EllipsisLoc) {
571 if (Arg.isInvalid())
572 return Arg;
573
574 switch (Arg.getKind()) {
575 case ParsedTemplateArgument::Type: {
576 TypeResult Result = ActOnPackExpansion(Arg.getAsType(), EllipsisLoc);
577 if (Result.isInvalid())
578 return ParsedTemplateArgument();
579
580 return ParsedTemplateArgument(Arg.getKind(), Result.get().getAsOpaquePtr(),
581 Arg.getLocation());
582 }
583
584 case ParsedTemplateArgument::NonType: {
585 ExprResult Result = ActOnPackExpansion(Arg.getAsExpr(), EllipsisLoc);
586 if (Result.isInvalid())
587 return ParsedTemplateArgument();
588
589 return ParsedTemplateArgument(Arg.getKind(), Result.get(),
590 Arg.getLocation());
591 }
592
593 case ParsedTemplateArgument::Template:
594 if (!Arg.getAsTemplate().get().containsUnexpandedParameterPack()) {
595 SourceRange R(Arg.getLocation());
596 if (Arg.getScopeSpec().isValid())
597 R.setBegin(Arg.getScopeSpec().getBeginLoc());
598 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
599 << R;
600 return ParsedTemplateArgument();
601 }
602
603 return Arg.getTemplatePackExpansion(EllipsisLoc);
604 }
605 llvm_unreachable("Unhandled template argument kind?")::llvm::llvm_unreachable_internal("Unhandled template argument kind?"
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 605)
;
606}
607
608TypeResult Sema::ActOnPackExpansion(ParsedType Type,
609 SourceLocation EllipsisLoc) {
610 TypeSourceInfo *TSInfo;
611 GetTypeFromParser(Type, &TSInfo);
612 if (!TSInfo)
613 return true;
614
615 TypeSourceInfo *TSResult = CheckPackExpansion(TSInfo, EllipsisLoc, None);
616 if (!TSResult)
617 return true;
618
619 return CreateParsedType(TSResult->getType(), TSResult);
620}
621
622TypeSourceInfo *
623Sema::CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc,
624 Optional<unsigned> NumExpansions) {
625 // Create the pack expansion type and source-location information.
626 QualType Result = CheckPackExpansion(Pattern->getType(),
627 Pattern->getTypeLoc().getSourceRange(),
628 EllipsisLoc, NumExpansions);
629 if (Result.isNull())
630 return nullptr;
631
632 TypeLocBuilder TLB;
633 TLB.pushFullCopy(Pattern->getTypeLoc());
634 PackExpansionTypeLoc TL = TLB.push<PackExpansionTypeLoc>(Result);
635 TL.setEllipsisLoc(EllipsisLoc);
636
637 return TLB.getTypeSourceInfo(Context, Result);
638}
639
640QualType Sema::CheckPackExpansion(QualType Pattern, SourceRange PatternRange,
641 SourceLocation EllipsisLoc,
642 Optional<unsigned> NumExpansions) {
643 // C++11 [temp.variadic]p5:
644 // The pattern of a pack expansion shall name one or more
645 // parameter packs that are not expanded by a nested pack
646 // expansion.
647 //
648 // A pattern containing a deduced type can't occur "naturally" but arises in
649 // the desugaring of an init-capture pack.
650 if (!Pattern->containsUnexpandedParameterPack() &&
651 !Pattern->getContainedDeducedType()) {
652 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
653 << PatternRange;
654 return QualType();
655 }
656
657 return Context.getPackExpansionType(Pattern, NumExpansions,
658 /*ExpectPackInType=*/false);
659}
660
661ExprResult Sema::ActOnPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc) {
662 return CheckPackExpansion(Pattern, EllipsisLoc, None);
663}
664
665ExprResult Sema::CheckPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
666 Optional<unsigned> NumExpansions) {
667 if (!Pattern)
668 return ExprError();
669
670 // C++0x [temp.variadic]p5:
671 // The pattern of a pack expansion shall name one or more
672 // parameter packs that are not expanded by a nested pack
673 // expansion.
674 if (!Pattern->containsUnexpandedParameterPack()) {
675 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
676 << Pattern->getSourceRange();
677 CorrectDelayedTyposInExpr(Pattern);
678 return ExprError();
679 }
680
681 // Create the pack expansion expression and source-location information.
682 return new (Context)
683 PackExpansionExpr(Context.DependentTy, Pattern, EllipsisLoc, NumExpansions);
684}
685
686bool Sema::CheckParameterPacksForExpansion(
687 SourceLocation EllipsisLoc, SourceRange PatternRange,
688 ArrayRef<UnexpandedParameterPack> Unexpanded,
689 const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand,
690 bool &RetainExpansion, Optional<unsigned> &NumExpansions) {
691 ShouldExpand = true;
692 RetainExpansion = false;
693 std::pair<const IdentifierInfo *, SourceLocation> FirstPack;
694 Optional<std::pair<unsigned, SourceLocation>> PartialExpansion;
695 Optional<unsigned> CurNumExpansions;
696
697 for (auto [P, Loc] : Unexpanded) {
1
Assuming '__begin1' is not equal to '__end1'
698 // Compute the depth and index for this parameter pack.
699 Optional<std::pair<unsigned, unsigned>> Pos;
700 unsigned NewPackSize;
701 const auto *ND = P.dyn_cast<const NamedDecl *>();
2
Calling 'PointerUnion::dyn_cast'
17
Returning from 'PointerUnion::dyn_cast'
52
Calling 'PointerUnion::dyn_cast'
71
Returning from 'PointerUnion::dyn_cast'
702 if (ND
17.1
'ND' is null
17.1
'ND' is null
17.1
'ND' is null
17.1
'ND' is null
&& isa<VarDecl>(ND)) {
72
Assuming 'ND' is non-null
73
Assuming 'ND' is a 'class clang::VarDecl &'
74
Taking true branch
703 const auto *DAP =
704 CurrentInstantiationScope->findInstantiationOf(ND)
75
Called C++ object pointer is null
705 ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>();
706 if (!DAP) {
707 // We can't expand this function parameter pack, so we can't expand
708 // the pack expansion.
709 ShouldExpand = false;
710 continue;
711 }
712 NewPackSize = DAP->size();
713 } else if (ND
17.2
'ND' is null
17.2
'ND' is null
17.2
'ND' is null
17.2
'ND' is null
) {
18
Taking false branch
714 Pos = getDepthAndIndex(ND);
715 } else if (const auto *TTP = P.dyn_cast<const TemplateTypeParmType *>()) {
19
Calling 'PointerUnion::dyn_cast'
38
Returning from 'PointerUnion::dyn_cast'
39
Assuming 'TTP' is non-null
40
Taking true branch
716 Pos = {TTP->getDepth(), TTP->getIndex()};
717 ND = TTP->getDecl();
41
Calling 'TemplateTypeParmType::getDecl'
44
Returning from 'TemplateTypeParmType::getDecl'
718 // FIXME: We either should have some fallback for canonical TTP, or
719 // never have canonical TTP here.
720 } else if (const auto *STP =
721 P.dyn_cast<const SubstTemplateTypeParmPackType *>()) {
722 NewPackSize = STP->getNumArgs();
723 ND = STP->getReplacedParameter()->getDecl();
724 } else {
725 const auto *SEP = P.get<const SubstNonTypeTemplateParmPackExpr *>();
726 NewPackSize = SEP->getArgumentPack().pack_size();
727 ND = SEP->getParameterPack();
728 }
729
730 if (Pos) {
731 // If we don't have a template argument at this depth/index, then we
732 // cannot expand the pack expansion. Make a note of this, but we still
733 // want to check any parameter packs we *do* have arguments for.
734 if (Pos->first >= TemplateArgs.getNumLevels() ||
45
Assuming the condition is false
47
Taking false branch
735 !TemplateArgs.hasTemplateArgument(Pos->first, Pos->second)) {
46
Assuming the condition is false
736 ShouldExpand = false;
737 continue;
738 }
739 // Determine the size of the argument pack.
740 NewPackSize = TemplateArgs(Pos->first, Pos->second).pack_size();
741 // C++0x [temp.arg.explicit]p9:
742 // Template argument deduction can extend the sequence of template
743 // arguments corresponding to a template parameter pack, even when the
744 // sequence contains explicitly specified template arguments.
745 if (CurrentInstantiationScope)
48
Assuming field 'CurrentInstantiationScope' is null
746 if (const NamedDecl *PartialPack =
747 CurrentInstantiationScope->getPartiallySubstitutedPack();
748 PartialPack && getDepthAndIndex(PartialPack) == *Pos) {
749 RetainExpansion = true;
750 // We don't actually know the new pack size yet.
751 PartialExpansion = {NewPackSize, Loc};
752 continue;
753 }
754 }
755
756 // FIXME: Workaround for Canonical TTP.
757 const IdentifierInfo *Name = ND
49.1
'ND' is null
49.1
'ND' is null
49.1
'ND' is null
49.1
'ND' is null
? ND->getIdentifier() : nullptr;
49
Taking false branch
50
'?' condition is false
758 if (!CurNumExpansions) {
51
Taking true branch
759 // The is the first pack we've seen for which we have an argument.
760 // Record it.
761 CurNumExpansions = NewPackSize;
762 FirstPack = {Name, Loc};
763 } else if (NewPackSize != *CurNumExpansions) {
764 // C++0x [temp.variadic]p5:
765 // All of the parameter packs expanded by a pack expansion shall have
766 // the same number of arguments specified.
767 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict)
768 << FirstPack.first << Name << *CurNumExpansions << NewPackSize
769 << SourceRange(FirstPack.second) << SourceRange(Loc);
770 return true;
771 }
772 }
773
774 if (NumExpansions && CurNumExpansions &&
775 *NumExpansions != *CurNumExpansions) {
776 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_multilevel)
777 << FirstPack.first << *CurNumExpansions << *NumExpansions
778 << SourceRange(FirstPack.second);
779 return true;
780 }
781
782 // If we're performing a partial expansion but we also have a full expansion,
783 // expand to the number of common arguments. For example, given:
784 //
785 // template<typename ...T> struct A {
786 // template<typename ...U> void f(pair<T, U>...);
787 // };
788 //
789 // ... a call to 'A<int, int>().f<int>' should expand the pack once and
790 // retain an expansion.
791 if (PartialExpansion) {
792 if (CurNumExpansions && *CurNumExpansions < PartialExpansion->first) {
793 NamedDecl *PartialPack =
794 CurrentInstantiationScope->getPartiallySubstitutedPack();
795 Diag(EllipsisLoc, diag::err_pack_expansion_length_conflict_partial)
796 << PartialPack << PartialExpansion->first << *CurNumExpansions
797 << SourceRange(PartialExpansion->second);
798 return true;
799 }
800 NumExpansions = PartialExpansion->first;
801 } else {
802 NumExpansions = CurNumExpansions;
803 }
804
805 return false;
806}
807
808Optional<unsigned> Sema::getNumArgumentsInExpansion(QualType T,
809 const MultiLevelTemplateArgumentList &TemplateArgs) {
810 QualType Pattern = cast<PackExpansionType>(T)->getPattern();
811 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
812 CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseType(Pattern);
813
814 Optional<unsigned> Result;
815 auto setResultSz = [&Result](unsigned Size) {
816 assert((!Result || *Result == Size) && "inconsistent pack sizes")(static_cast <bool> ((!Result || *Result == Size) &&
"inconsistent pack sizes") ? void (0) : __assert_fail ("(!Result || *Result == Size) && \"inconsistent pack sizes\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 816, __extension__
__PRETTY_FUNCTION__))
;
817 Result = Size;
818 };
819 auto setResultPos = [&](const std::pair<unsigned, unsigned> &Pos) -> bool {
820 unsigned Depth = Pos.first, Index = Pos.second;
821 if (Depth >= TemplateArgs.getNumLevels() ||
822 !TemplateArgs.hasTemplateArgument(Depth, Index))
823 // The pattern refers to an unknown template argument. We're not ready to
824 // expand this pack yet.
825 return true;
826 // Determine the size of the argument pack.
827 setResultSz(TemplateArgs(Depth, Index).pack_size());
828 return false;
829 };
830
831 for (auto [I, _] : Unexpanded) {
832 if (const auto *TTP = I.dyn_cast<const TemplateTypeParmType *>()) {
833 if (setResultPos({TTP->getDepth(), TTP->getIndex()}))
834 return None;
835 } else if (const auto *STP =
836 I.dyn_cast<const SubstTemplateTypeParmPackType *>()) {
837 setResultSz(STP->getNumArgs());
838 } else if (const auto *SEP =
839 I.dyn_cast<const SubstNonTypeTemplateParmPackExpr *>()) {
840 setResultSz(SEP->getArgumentPack().pack_size());
841 } else {
842 const auto *ND = I.get<const NamedDecl *>();
843 // Function parameter pack or init-capture pack.
844 if (isa<VarDecl>(ND)) {
845 const auto *DAP =
846 CurrentInstantiationScope->findInstantiationOf(ND)
847 ->dyn_cast<LocalInstantiationScope::DeclArgumentPack *>();
848 if (!DAP)
849 // The pattern refers to an unexpanded pack. We're not ready to expand
850 // this pack yet.
851 return None;
852 setResultSz(DAP->size());
853 } else if (setResultPos(getDepthAndIndex(ND))) {
854 return None;
855 }
856 }
857 }
858
859 return Result;
860}
861
862bool Sema::containsUnexpandedParameterPacks(Declarator &D) {
863 const DeclSpec &DS = D.getDeclSpec();
864 switch (DS.getTypeSpecType()) {
865 case TST_typename:
866 case TST_typeofType:
867#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case TST_##Trait:
868#include "clang/Basic/TransformTypeTraits.def"
869 case TST_atomic: {
870 QualType T = DS.getRepAsType().get();
871 if (!T.isNull() && T->containsUnexpandedParameterPack())
872 return true;
873 break;
874 }
875
876 case TST_typeofExpr:
877 case TST_decltype:
878 case TST_bitint:
879 if (DS.getRepAsExpr() &&
880 DS.getRepAsExpr()->containsUnexpandedParameterPack())
881 return true;
882 break;
883
884 case TST_unspecified:
885 case TST_void:
886 case TST_char:
887 case TST_wchar:
888 case TST_char8:
889 case TST_char16:
890 case TST_char32:
891 case TST_int:
892 case TST_int128:
893 case TST_half:
894 case TST_float:
895 case TST_double:
896 case TST_Accum:
897 case TST_Fract:
898 case TST_Float16:
899 case TST_float128:
900 case TST_ibm128:
901 case TST_bool:
902 case TST_decimal32:
903 case TST_decimal64:
904 case TST_decimal128:
905 case TST_enum:
906 case TST_union:
907 case TST_struct:
908 case TST_interface:
909 case TST_class:
910 case TST_auto:
911 case TST_auto_type:
912 case TST_decltype_auto:
913 case TST_BFloat16:
914#define GENERIC_IMAGE_TYPE(ImgType, Id) case TST_##ImgType##_t:
915#include "clang/Basic/OpenCLImageTypes.def"
916 case TST_unknown_anytype:
917 case TST_error:
918 break;
919 }
920
921 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
922 const DeclaratorChunk &Chunk = D.getTypeObject(I);
923 switch (Chunk.Kind) {
924 case DeclaratorChunk::Pointer:
925 case DeclaratorChunk::Reference:
926 case DeclaratorChunk::Paren:
927 case DeclaratorChunk::Pipe:
928 case DeclaratorChunk::BlockPointer:
929 // These declarator chunks cannot contain any parameter packs.
930 break;
931
932 case DeclaratorChunk::Array:
933 if (Chunk.Arr.NumElts &&
934 Chunk.Arr.NumElts->containsUnexpandedParameterPack())
935 return true;
936 break;
937 case DeclaratorChunk::Function:
938 for (unsigned i = 0, e = Chunk.Fun.NumParams; i != e; ++i) {
939 ParmVarDecl *Param = cast<ParmVarDecl>(Chunk.Fun.Params[i].Param);
940 QualType ParamTy = Param->getType();
941 assert(!ParamTy.isNull() && "Couldn't parse type?")(static_cast <bool> (!ParamTy.isNull() && "Couldn't parse type?"
) ? void (0) : __assert_fail ("!ParamTy.isNull() && \"Couldn't parse type?\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 941, __extension__
__PRETTY_FUNCTION__))
;
942 if (ParamTy->containsUnexpandedParameterPack()) return true;
943 }
944
945 if (Chunk.Fun.getExceptionSpecType() == EST_Dynamic) {
946 for (unsigned i = 0; i != Chunk.Fun.getNumExceptions(); ++i) {
947 if (Chunk.Fun.Exceptions[i]
948 .Ty.get()
949 ->containsUnexpandedParameterPack())
950 return true;
951 }
952 } else if (isComputedNoexcept(Chunk.Fun.getExceptionSpecType()) &&
953 Chunk.Fun.NoexceptExpr->containsUnexpandedParameterPack())
954 return true;
955
956 if (Chunk.Fun.hasTrailingReturnType()) {
957 QualType T = Chunk.Fun.getTrailingReturnType().get();
958 if (!T.isNull() && T->containsUnexpandedParameterPack())
959 return true;
960 }
961 break;
962
963 case DeclaratorChunk::MemberPointer:
964 if (Chunk.Mem.Scope().getScopeRep() &&
965 Chunk.Mem.Scope().getScopeRep()->containsUnexpandedParameterPack())
966 return true;
967 break;
968 }
969 }
970
971 if (Expr *TRC = D.getTrailingRequiresClause())
972 if (TRC->containsUnexpandedParameterPack())
973 return true;
974
975 return false;
976}
977
978namespace {
979
980// Callback to only accept typo corrections that refer to parameter packs.
981class ParameterPackValidatorCCC final : public CorrectionCandidateCallback {
982 public:
983 bool ValidateCandidate(const TypoCorrection &candidate) override {
984 NamedDecl *ND = candidate.getCorrectionDecl();
985 return ND && ND->isParameterPack();
986 }
987
988 std::unique_ptr<CorrectionCandidateCallback> clone() override {
989 return std::make_unique<ParameterPackValidatorCCC>(*this);
990 }
991};
992
993}
994
995/// Called when an expression computing the size of a parameter pack
996/// is parsed.
997///
998/// \code
999/// template<typename ...Types> struct count {
1000/// static const unsigned value = sizeof...(Types);
1001/// };
1002/// \endcode
1003///
1004//
1005/// \param OpLoc The location of the "sizeof" keyword.
1006/// \param Name The name of the parameter pack whose size will be determined.
1007/// \param NameLoc The source location of the name of the parameter pack.
1008/// \param RParenLoc The location of the closing parentheses.
1009ExprResult Sema::ActOnSizeofParameterPackExpr(Scope *S,
1010 SourceLocation OpLoc,
1011 IdentifierInfo &Name,
1012 SourceLocation NameLoc,
1013 SourceLocation RParenLoc) {
1014 // C++0x [expr.sizeof]p5:
1015 // The identifier in a sizeof... expression shall name a parameter pack.
1016 LookupResult R(*this, &Name, NameLoc, LookupOrdinaryName);
1017 LookupName(R, S);
1018
1019 NamedDecl *ParameterPack = nullptr;
1020 switch (R.getResultKind()) {
1021 case LookupResult::Found:
1022 ParameterPack = R.getFoundDecl();
1023 break;
1024
1025 case LookupResult::NotFound:
1026 case LookupResult::NotFoundInCurrentInstantiation: {
1027 ParameterPackValidatorCCC CCC{};
1028 if (TypoCorrection Corrected =
1029 CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, nullptr,
1030 CCC, CTK_ErrorRecovery)) {
1031 diagnoseTypo(Corrected,
1032 PDiag(diag::err_sizeof_pack_no_pack_name_suggest) << &Name,
1033 PDiag(diag::note_parameter_pack_here));
1034 ParameterPack = Corrected.getCorrectionDecl();
1035 }
1036 break;
1037 }
1038 case LookupResult::FoundOverloaded:
1039 case LookupResult::FoundUnresolvedValue:
1040 break;
1041
1042 case LookupResult::Ambiguous:
1043 DiagnoseAmbiguousLookup(R);
1044 return ExprError();
1045 }
1046
1047 if (!ParameterPack || !ParameterPack->isParameterPack()) {
1048 Diag(NameLoc, diag::err_sizeof_pack_no_pack_name)
1049 << &Name;
1050 return ExprError();
1051 }
1052
1053 MarkAnyDeclReferenced(OpLoc, ParameterPack, true);
1054
1055 return SizeOfPackExpr::Create(Context, OpLoc, ParameterPack, NameLoc,
1056 RParenLoc);
1057}
1058
1059TemplateArgumentLoc
1060Sema::getTemplateArgumentPackExpansionPattern(
1061 TemplateArgumentLoc OrigLoc,
1062 SourceLocation &Ellipsis, Optional<unsigned> &NumExpansions) const {
1063 const TemplateArgument &Argument = OrigLoc.getArgument();
1064 assert(Argument.isPackExpansion())(static_cast <bool> (Argument.isPackExpansion()) ? void
(0) : __assert_fail ("Argument.isPackExpansion()", "clang/lib/Sema/SemaTemplateVariadic.cpp"
, 1064, __extension__ __PRETTY_FUNCTION__))
;
1065 switch (Argument.getKind()) {
1066 case TemplateArgument::Type: {
1067 // FIXME: We shouldn't ever have to worry about missing
1068 // type-source info!
1069 TypeSourceInfo *ExpansionTSInfo = OrigLoc.getTypeSourceInfo();
1070 if (!ExpansionTSInfo)
1071 ExpansionTSInfo = Context.getTrivialTypeSourceInfo(Argument.getAsType(),
1072 Ellipsis);
1073 PackExpansionTypeLoc Expansion =
1074 ExpansionTSInfo->getTypeLoc().castAs<PackExpansionTypeLoc>();
1075 Ellipsis = Expansion.getEllipsisLoc();
1076
1077 TypeLoc Pattern = Expansion.getPatternLoc();
1078 NumExpansions = Expansion.getTypePtr()->getNumExpansions();
1079
1080 // We need to copy the TypeLoc because TemplateArgumentLocs store a
1081 // TypeSourceInfo.
1082 // FIXME: Find some way to avoid the copy?
1083 TypeLocBuilder TLB;
1084 TLB.pushFullCopy(Pattern);
1085 TypeSourceInfo *PatternTSInfo =
1086 TLB.getTypeSourceInfo(Context, Pattern.getType());
1087 return TemplateArgumentLoc(TemplateArgument(Pattern.getType()),
1088 PatternTSInfo);
1089 }
1090
1091 case TemplateArgument::Expression: {
1092 PackExpansionExpr *Expansion
1093 = cast<PackExpansionExpr>(Argument.getAsExpr());
1094 Expr *Pattern = Expansion->getPattern();
1095 Ellipsis = Expansion->getEllipsisLoc();
1096 NumExpansions = Expansion->getNumExpansions();
1097 return TemplateArgumentLoc(Pattern, Pattern);
1098 }
1099
1100 case TemplateArgument::TemplateExpansion:
1101 Ellipsis = OrigLoc.getTemplateEllipsisLoc();
1102 NumExpansions = Argument.getNumTemplateExpansions();
1103 return TemplateArgumentLoc(Context, Argument.getPackExpansionPattern(),
1104 OrigLoc.getTemplateQualifierLoc(),
1105 OrigLoc.getTemplateNameLoc());
1106
1107 case TemplateArgument::Declaration:
1108 case TemplateArgument::NullPtr:
1109 case TemplateArgument::Template:
1110 case TemplateArgument::Integral:
1111 case TemplateArgument::Pack:
1112 case TemplateArgument::Null:
1113 return TemplateArgumentLoc();
1114 }
1115
1116 llvm_unreachable("Invalid TemplateArgument Kind!")::llvm::llvm_unreachable_internal("Invalid TemplateArgument Kind!"
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 1116)
;
1117}
1118
1119Optional<unsigned> Sema::getFullyPackExpandedSize(TemplateArgument Arg) {
1120 assert(Arg.containsUnexpandedParameterPack())(static_cast <bool> (Arg.containsUnexpandedParameterPack
()) ? void (0) : __assert_fail ("Arg.containsUnexpandedParameterPack()"
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 1120, __extension__
__PRETTY_FUNCTION__))
;
1121
1122 // If this is a substituted pack, grab that pack. If not, we don't know
1123 // the size yet.
1124 // FIXME: We could find a size in more cases by looking for a substituted
1125 // pack anywhere within this argument, but that's not necessary in the common
1126 // case for 'sizeof...(A)' handling.
1127 TemplateArgument Pack;
1128 switch (Arg.getKind()) {
1129 case TemplateArgument::Type:
1130 if (auto *Subst = Arg.getAsType()->getAs<SubstTemplateTypeParmPackType>())
1131 Pack = Subst->getArgumentPack();
1132 else
1133 return None;
1134 break;
1135
1136 case TemplateArgument::Expression:
1137 if (auto *Subst =
1138 dyn_cast<SubstNonTypeTemplateParmPackExpr>(Arg.getAsExpr()))
1139 Pack = Subst->getArgumentPack();
1140 else if (auto *Subst = dyn_cast<FunctionParmPackExpr>(Arg.getAsExpr())) {
1141 for (VarDecl *PD : *Subst)
1142 if (PD->isParameterPack())
1143 return None;
1144 return Subst->getNumExpansions();
1145 } else
1146 return None;
1147 break;
1148
1149 case TemplateArgument::Template:
1150 if (SubstTemplateTemplateParmPackStorage *Subst =
1151 Arg.getAsTemplate().getAsSubstTemplateTemplateParmPack())
1152 Pack = Subst->getArgumentPack();
1153 else
1154 return None;
1155 break;
1156
1157 case TemplateArgument::Declaration:
1158 case TemplateArgument::NullPtr:
1159 case TemplateArgument::TemplateExpansion:
1160 case TemplateArgument::Integral:
1161 case TemplateArgument::Pack:
1162 case TemplateArgument::Null:
1163 return None;
1164 }
1165
1166 // Check that no argument in the pack is itself a pack expansion.
1167 for (TemplateArgument Elem : Pack.pack_elements()) {
1168 // There's no point recursing in this case; we would have already
1169 // expanded this pack expansion into the enclosing pack if we could.
1170 if (Elem.isPackExpansion())
1171 return None;
1172 }
1173 return Pack.pack_size();
1174}
1175
1176static void CheckFoldOperand(Sema &S, Expr *E) {
1177 if (!E)
1178 return;
1179
1180 E = E->IgnoreImpCasts();
1181 auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
1182 if ((OCE && OCE->isInfixBinaryOp()) || isa<BinaryOperator>(E) ||
1183 isa<AbstractConditionalOperator>(E)) {
1184 S.Diag(E->getExprLoc(), diag::err_fold_expression_bad_operand)
1185 << E->getSourceRange()
1186 << FixItHint::CreateInsertion(E->getBeginLoc(), "(")
1187 << FixItHint::CreateInsertion(E->getEndLoc(), ")");
1188 }
1189}
1190
1191ExprResult Sema::ActOnCXXFoldExpr(Scope *S, SourceLocation LParenLoc, Expr *LHS,
1192 tok::TokenKind Operator,
1193 SourceLocation EllipsisLoc, Expr *RHS,
1194 SourceLocation RParenLoc) {
1195 // LHS and RHS must be cast-expressions. We allow an arbitrary expression
1196 // in the parser and reduce down to just cast-expressions here.
1197 CheckFoldOperand(*this, LHS);
1198 CheckFoldOperand(*this, RHS);
1199
1200 auto DiscardOperands = [&] {
1201 CorrectDelayedTyposInExpr(LHS);
1202 CorrectDelayedTyposInExpr(RHS);
1203 };
1204
1205 // [expr.prim.fold]p3:
1206 // In a binary fold, op1 and op2 shall be the same fold-operator, and
1207 // either e1 shall contain an unexpanded parameter pack or e2 shall contain
1208 // an unexpanded parameter pack, but not both.
1209 if (LHS && RHS &&
1210 LHS->containsUnexpandedParameterPack() ==
1211 RHS->containsUnexpandedParameterPack()) {
1212 DiscardOperands();
1213 return Diag(EllipsisLoc,
1214 LHS->containsUnexpandedParameterPack()
1215 ? diag::err_fold_expression_packs_both_sides
1216 : diag::err_pack_expansion_without_parameter_packs)
1217 << LHS->getSourceRange() << RHS->getSourceRange();
1218 }
1219
1220 // [expr.prim.fold]p2:
1221 // In a unary fold, the cast-expression shall contain an unexpanded
1222 // parameter pack.
1223 if (!LHS || !RHS) {
1224 Expr *Pack = LHS ? LHS : RHS;
1225 assert(Pack && "fold expression with neither LHS nor RHS")(static_cast <bool> (Pack && "fold expression with neither LHS nor RHS"
) ? void (0) : __assert_fail ("Pack && \"fold expression with neither LHS nor RHS\""
, "clang/lib/Sema/SemaTemplateVariadic.cpp", 1225, __extension__
__PRETTY_FUNCTION__))
;
1226 DiscardOperands();
1227 if (!Pack->containsUnexpandedParameterPack())
1228 return Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1229 << Pack->getSourceRange();
1230 }
1231
1232 BinaryOperatorKind Opc = ConvertTokenKindToBinaryOpcode(Operator);
1233
1234 // Perform first-phase name lookup now.
1235 UnresolvedLookupExpr *ULE = nullptr;
1236 {
1237 UnresolvedSet<16> Functions;
1238 LookupBinOp(S, EllipsisLoc, Opc, Functions);
1239 if (!Functions.empty()) {
1240 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(
1241 BinaryOperator::getOverloadedOperator(Opc));
1242 ExprResult Callee = CreateUnresolvedLookupExpr(
1243 /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
1244 DeclarationNameInfo(OpName, EllipsisLoc), Functions);
1245 if (Callee.isInvalid())
1246 return ExprError();
1247 ULE = cast<UnresolvedLookupExpr>(Callee.get());
1248 }
1249 }
1250
1251 return BuildCXXFoldExpr(ULE, LParenLoc, LHS, Opc, EllipsisLoc, RHS, RParenLoc,
1252 None);
1253}
1254
1255ExprResult Sema::BuildCXXFoldExpr(UnresolvedLookupExpr *Callee,
1256 SourceLocation LParenLoc, Expr *LHS,
1257 BinaryOperatorKind Operator,
1258 SourceLocation EllipsisLoc, Expr *RHS,
1259 SourceLocation RParenLoc,
1260 Optional<unsigned> NumExpansions) {
1261 return new (Context)
1262 CXXFoldExpr(Context.DependentTy, Callee, LParenLoc, LHS, Operator,
1263 EllipsisLoc, RHS, RParenLoc, NumExpansions);
1264}
1265
1266ExprResult Sema::BuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
1267 BinaryOperatorKind Operator) {
1268 // [temp.variadic]p9:
1269 // If N is zero for a unary fold-expression, the value of the expression is
1270 // && -> true
1271 // || -> false
1272 // , -> void()
1273 // if the operator is not listed [above], the instantiation is ill-formed.
1274 //
1275 // Note that we need to use something like int() here, not merely 0, to
1276 // prevent the result from being a null pointer constant.
1277 QualType ScalarType;
1278 switch (Operator) {
1279 case BO_LOr:
1280 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_false);
1281 case BO_LAnd:
1282 return ActOnCXXBoolLiteral(EllipsisLoc, tok::kw_true);
1283 case BO_Comma:
1284 ScalarType = Context.VoidTy;
1285 break;
1286
1287 default:
1288 return Diag(EllipsisLoc, diag::err_fold_expression_empty)
1289 << BinaryOperator::getOpcodeStr(Operator);
1290 }
1291
1292 return new (Context) CXXScalarValueInitExpr(
1293 ScalarType, Context.getTrivialTypeSourceInfo(ScalarType, EllipsisLoc),
1294 EllipsisLoc);
1295}

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/ADT/PointerUnion.h

1//===- llvm/ADT/PointerUnion.h - Discriminated Union of 2 Ptrs --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file defines the PointerUnion class, which is a discriminated union of
11/// pointer types.
12///
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_POINTERUNION_H
16#define LLVM_ADT_POINTERUNION_H
17
18#include "llvm/ADT/DenseMapInfo.h"
19#include "llvm/ADT/PointerIntPair.h"
20#include "llvm/ADT/STLExtras.h"
21#include "llvm/Support/Casting.h"
22#include "llvm/Support/PointerLikeTypeTraits.h"
23#include <algorithm>
24#include <cassert>
25#include <cstddef>
26#include <cstdint>
27
28namespace llvm {
29
30namespace pointer_union_detail {
31 /// Determine the number of bits required to store integers with values < n.
32 /// This is ceil(log2(n)).
33 constexpr int bitsRequired(unsigned n) {
34 return n > 1 ? 1 + bitsRequired((n + 1) / 2) : 0;
35 }
36
37 template <typename... Ts> constexpr int lowBitsAvailable() {
38 return std::min<int>({PointerLikeTypeTraits<Ts>::NumLowBitsAvailable...});
39 }
40
41 /// Find the first type in a list of types.
42 template <typename T, typename...> struct GetFirstType {
43 using type = T;
44 };
45
46 /// Provide PointerLikeTypeTraits for void* that is used by PointerUnion
47 /// for the template arguments.
48 template <typename ...PTs> class PointerUnionUIntTraits {
49 public:
50 static inline void *getAsVoidPointer(void *P) { return P; }
51 static inline void *getFromVoidPointer(void *P) { return P; }
52 static constexpr int NumLowBitsAvailable = lowBitsAvailable<PTs...>();
53 };
54
55 template <typename Derived, typename ValTy, int I, typename ...Types>
56 class PointerUnionMembers;
57
58 template <typename Derived, typename ValTy, int I>
59 class PointerUnionMembers<Derived, ValTy, I> {
60 protected:
61 ValTy Val;
62 PointerUnionMembers() = default;
63 PointerUnionMembers(ValTy Val) : Val(Val) {}
64
65 friend struct PointerLikeTypeTraits<Derived>;
66 };
67
68 template <typename Derived, typename ValTy, int I, typename Type,
69 typename ...Types>
70 class PointerUnionMembers<Derived, ValTy, I, Type, Types...>
71 : public PointerUnionMembers<Derived, ValTy, I + 1, Types...> {
72 using Base = PointerUnionMembers<Derived, ValTy, I + 1, Types...>;
73 public:
74 using Base::Base;
75 PointerUnionMembers() = default;
76 PointerUnionMembers(Type V)
77 : Base(ValTy(const_cast<void *>(
78 PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
79 I)) {}
80
81 using Base::operator=;
82 Derived &operator=(Type V) {
83 this->Val = ValTy(
84 const_cast<void *>(PointerLikeTypeTraits<Type>::getAsVoidPointer(V)),
85 I);
86 return static_cast<Derived &>(*this);
87 };
88 };
89}
90
91// This is a forward declaration of CastInfoPointerUnionImpl
92// Refer to its definition below for further details
93template <typename... PTs> struct CastInfoPointerUnionImpl;
94/// A discriminated union of two or more pointer types, with the discriminator
95/// in the low bit of the pointer.
96///
97/// This implementation is extremely efficient in space due to leveraging the
98/// low bits of the pointer, while exposing a natural and type-safe API.
99///
100/// Common use patterns would be something like this:
101/// PointerUnion<int*, float*> P;
102/// P = (int*)0;
103/// printf("%d %d", P.is<int*>(), P.is<float*>()); // prints "1 0"
104/// X = P.get<int*>(); // ok.
105/// Y = P.get<float*>(); // runtime assertion failure.
106/// Z = P.get<double*>(); // compile time failure.
107/// P = (float*)0;
108/// Y = P.get<float*>(); // ok.
109/// X = P.get<int*>(); // runtime assertion failure.
110/// PointerUnion<int*, int*> Q; // compile time failure.
111template <typename... PTs>
112class PointerUnion
113 : public pointer_union_detail::PointerUnionMembers<
114 PointerUnion<PTs...>,
115 PointerIntPair<
116 void *, pointer_union_detail::bitsRequired(sizeof...(PTs)), int,
117 pointer_union_detail::PointerUnionUIntTraits<PTs...>>,
118 0, PTs...> {
119 static_assert(TypesAreDistinct<PTs...>::value,
120 "PointerUnion alternative types cannot be repeated");
121 // The first type is special because we want to directly cast a pointer to a
122 // default-initialized union to a pointer to the first type. But we don't
123 // want PointerUnion to be a 'template <typename First, typename ...Rest>'
124 // because it's much more convenient to have a name for the whole pack. So
125 // split off the first type here.
126 using First = TypeAtIndex<0, PTs...>;
127 using Base = typename PointerUnion::PointerUnionMembers;
128
129 /// This is needed to give the CastInfo implementation below access
130 /// to protected members.
131 /// Refer to its definition for further details.
132 friend struct CastInfoPointerUnionImpl<PTs...>;
133
134public:
135 PointerUnion() = default;
136
137 PointerUnion(std::nullptr_t) : PointerUnion() {}
138 using Base::Base;
139
140 /// Test if the pointer held in the union is null, regardless of
141 /// which type it is.
142 bool isNull() const { return !this->Val.getPointer(); }
143
144 explicit operator bool() const { return !isNull(); }
145
146 // FIXME: Replace the uses of is(), get() and dyn_cast() with
147 // isa<T>, cast<T> and the llvm::dyn_cast<T>
148
149 /// Test if the Union currently holds the type matching T.
150 template <typename T> inline bool is() const { return isa<T>(*this); }
151
152 /// Returns the value of the specified pointer type.
153 ///
154 /// If the specified pointer type is incorrect, assert.
155 template <typename T> inline T get() const {
156 assert(isa<T>(*this) && "Invalid accessor called")(static_cast <bool> (isa<T>(*this) && "Invalid accessor called"
) ? void (0) : __assert_fail ("isa<T>(*this) && \"Invalid accessor called\""
, "llvm/include/llvm/ADT/PointerUnion.h", 156, __extension__ __PRETTY_FUNCTION__
))
;
157 return cast<T>(*this);
158 }
159
160 /// Returns the current pointer if it is of the specified pointer type,
161 /// otherwise returns null.
162 template <typename T> inline T dyn_cast() const {
163 return llvm::dyn_cast<T>(*this);
3
Calling 'dyn_cast<const clang::NamedDecl *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
15
Returning from 'dyn_cast<const clang::NamedDecl *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
16
Returning null pointer, which participates in a condition later
20
Calling 'dyn_cast<const clang::TemplateTypeParmType *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
36
Returning from 'dyn_cast<const clang::TemplateTypeParmType *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
37
Returning pointer, which participates in a condition later
53
Calling 'dyn_cast<const clang::NamedDecl *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
69
Returning from 'dyn_cast<const clang::NamedDecl *, llvm::PointerUnion<const clang::TemplateTypeParmType *, const clang::SubstTemplateTypeParmPackType *, const clang::SubstNonTypeTemplateParmPackExpr *, const clang::NamedDecl *>>'
70
Returning pointer, which participates in a condition later
164 }
165
166 /// If the union is set to the first pointer type get an address pointing to
167 /// it.
168 First const *getAddrOfPtr1() const {
169 return const_cast<PointerUnion *>(this)->getAddrOfPtr1();
170 }
171
172 /// If the union is set to the first pointer type get an address pointing to
173 /// it.
174 First *getAddrOfPtr1() {
175 assert(is<First>() && "Val is not the first pointer")(static_cast <bool> (is<First>() && "Val is not the first pointer"
) ? void (0) : __assert_fail ("is<First>() && \"Val is not the first pointer\""
, "llvm/include/llvm/ADT/PointerUnion.h", 175, __extension__ __PRETTY_FUNCTION__
))
;
176 assert((static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 179, __extension__ __PRETTY_FUNCTION__
))
177 PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) ==(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 179, __extension__ __PRETTY_FUNCTION__
))
178 this->Val.getPointer() &&(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 179, __extension__ __PRETTY_FUNCTION__
))
179 "Can't get the address because PointerLikeTypeTraits changes the ptr")(static_cast <bool> (PointerLikeTypeTraits<First>
::getAsVoidPointer(get<First>()) == this->Val.getPointer
() && "Can't get the address because PointerLikeTypeTraits changes the ptr"
) ? void (0) : __assert_fail ("PointerLikeTypeTraits<First>::getAsVoidPointer(get<First>()) == this->Val.getPointer() && \"Can't get the address because PointerLikeTypeTraits changes the ptr\""
, "llvm/include/llvm/ADT/PointerUnion.h", 179, __extension__ __PRETTY_FUNCTION__
))
;
180 return const_cast<First *>(
181 reinterpret_cast<const First *>(this->Val.getAddrOfPointer()));
182 }
183
184 /// Assignment from nullptr which just clears the union.
185 const PointerUnion &operator=(std::nullptr_t) {
186 this->Val.initWithPointer(nullptr);
187 return *this;
188 }
189
190 /// Assignment from elements of the union.
191 using Base::operator=;
192
193 void *getOpaqueValue() const { return this->Val.getOpaqueValue(); }
194 static inline PointerUnion getFromOpaqueValue(void *VP) {
195 PointerUnion V;
196 V.Val = decltype(V.Val)::getFromOpaqueValue(VP);
197 return V;
198 }
199};
200
201template <typename ...PTs>
202bool operator==(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
203 return lhs.getOpaqueValue() == rhs.getOpaqueValue();
204}
205
206template <typename ...PTs>
207bool operator!=(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
208 return lhs.getOpaqueValue() != rhs.getOpaqueValue();
209}
210
211template <typename ...PTs>
212bool operator<(PointerUnion<PTs...> lhs, PointerUnion<PTs...> rhs) {
213 return lhs.getOpaqueValue() < rhs.getOpaqueValue();
214}
215
216/// We can't (at least, at this moment with C++14) declare CastInfo
217/// as a friend of PointerUnion like this:
218/// ```
219/// template<typename To>
220/// friend struct CastInfo<To, PointerUnion<PTs...>>;
221/// ```
222/// The compiler complains 'Partial specialization cannot be declared as a
223/// friend'.
224/// So we define this struct to be a bridge between CastInfo and
225/// PointerUnion.
226template <typename... PTs> struct CastInfoPointerUnionImpl {
227 using From = PointerUnion<PTs...>;
228
229 template <typename To> static inline bool isPossible(From &F) {
230 return F.Val.getInt() == FirstIndexOfType<To, PTs...>::value;
231 }
232
233 template <typename To> static To doCast(From &F) {
234 assert(isPossible<To>(F) && "cast to an incompatible type !")(static_cast <bool> (isPossible<To>(F) &&
"cast to an incompatible type !") ? void (0) : __assert_fail
("isPossible<To>(F) && \"cast to an incompatible type !\""
, "llvm/include/llvm/ADT/PointerUnion.h", 234, __extension__ __PRETTY_FUNCTION__
))
;
26
'?' condition is true
59
'?' condition is true
235 return PointerLikeTypeTraits<To>::getFromVoidPointer(F.Val.getPointer());
27
Returning pointer, which participates in a condition later
60
Returning pointer, which participates in a condition later
236 }
237};
238
239// Specialization of CastInfo for PointerUnion
240template <typename To, typename... PTs>
241struct CastInfo<To, PointerUnion<PTs...>>
242 : public DefaultDoCastIfPossible<To, PointerUnion<PTs...>,
243 CastInfo<To, PointerUnion<PTs...>>> {
244 using From = PointerUnion<PTs...>;
245 using Impl = CastInfoPointerUnionImpl<PTs...>;
246
247 static inline bool isPossible(From &f) {
248 return Impl::template isPossible<To>(f);
249 }
250
251 static To doCast(From &f) { return Impl::template doCast<To>(f); }
25
Calling 'CastInfoPointerUnionImpl::doCast'
28
Returning from 'CastInfoPointerUnionImpl::doCast'
29
Returning pointer, which participates in a condition later
58
Calling 'CastInfoPointerUnionImpl::doCast'
61
Returning from 'CastInfoPointerUnionImpl::doCast'
62
Returning pointer, which participates in a condition later
252
253 static inline To castFailed() { return To(); }
8
Returning null pointer, which participates in a condition later
254};
255
256template <typename To, typename... PTs>
257struct CastInfo<To, const PointerUnion<PTs...>>
258 : public ConstStrippingForwardingCast<To, const PointerUnion<PTs...>,
259 CastInfo<To, PointerUnion<PTs...>>> {
260};
261
262// Teach SmallPtrSet that PointerUnion is "basically a pointer", that has
263// # low bits available = min(PT1bits,PT2bits)-1.
264template <typename ...PTs>
265struct PointerLikeTypeTraits<PointerUnion<PTs...>> {
266 static inline void *getAsVoidPointer(const PointerUnion<PTs...> &P) {
267 return P.getOpaqueValue();
268 }
269
270 static inline PointerUnion<PTs...> getFromVoidPointer(void *P) {
271 return PointerUnion<PTs...>::getFromOpaqueValue(P);
272 }
273
274 // The number of bits available are the min of the pointer types minus the
275 // bits needed for the discriminator.
276 static constexpr int NumLowBitsAvailable = PointerLikeTypeTraits<decltype(
277 PointerUnion<PTs...>::Val)>::NumLowBitsAvailable;
278};
279
280// Teach DenseMap how to use PointerUnions as keys.
281template <typename ...PTs> struct DenseMapInfo<PointerUnion<PTs...>> {
282 using Union = PointerUnion<PTs...>;
283 using FirstInfo =
284 DenseMapInfo<typename pointer_union_detail::GetFirstType<PTs...>::type>;
285
286 static inline Union getEmptyKey() { return Union(FirstInfo::getEmptyKey()); }
287
288 static inline Union getTombstoneKey() {
289 return Union(FirstInfo::getTombstoneKey());
290 }
291
292 static unsigned getHashValue(const Union &UnionVal) {
293 intptr_t key = (intptr_t)UnionVal.getOpaqueValue();
294 return DenseMapInfo<intptr_t>::getHashValue(key);
295 }
296
297 static bool isEqual(const Union &LHS, const Union &RHS) {
298 return LHS == RHS;
299 }
300};
301
302} // end namespace llvm
303
304#endif // LLVM_ADT_POINTERUNION_H

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/llvm/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the isa<X>(), cast<X>(), dyn_cast<X>(),
10// cast_if_present<X>(), and dyn_cast_if_present<X>() templates.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_SUPPORT_CASTING_H
15#define LLVM_SUPPORT_CASTING_H
16
17#include "llvm/ADT/Optional.h"
18#include "llvm/Support/Compiler.h"
19#include "llvm/Support/type_traits.h"
20#include <cassert>
21#include <memory>
22#include <type_traits>
23
24namespace llvm {
25
26//===----------------------------------------------------------------------===//
27// simplify_type
28//===----------------------------------------------------------------------===//
29
30/// Define a template that can be specialized by smart pointers to reflect the
31/// fact that they are automatically dereferenced, and are not involved with the
32/// template selection process... the default implementation is a noop.
33// TODO: rename this and/or replace it with other cast traits.
34template <typename From> struct simplify_type {
35 using SimpleType = From; // The real type this represents...
36
37 // An accessor to get the real value...
38 static SimpleType &getSimplifiedValue(From &Val) { return Val; }
39};
40
41template <typename From> struct simplify_type<const From> {
42 using NonConstSimpleType = typename simplify_type<From>::SimpleType;
43 using SimpleType = typename add_const_past_pointer<NonConstSimpleType>::type;
44 using RetType =
45 typename add_lvalue_reference_if_not_pointer<SimpleType>::type;
46
47 static RetType getSimplifiedValue(const From &Val) {
48 return simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val));
49 }
50};
51
52// TODO: add this namespace once everyone is switched to using the new
53// interface.
54// namespace detail {
55
56//===----------------------------------------------------------------------===//
57// isa_impl
58//===----------------------------------------------------------------------===//
59
60// The core of the implementation of isa<X> is here; To and From should be
61// the names of classes. This template can be specialized to customize the
62// implementation of isa<> without rewriting it from scratch.
63template <typename To, typename From, typename Enabler = void> struct isa_impl {
64 static inline bool doit(const From &Val) { return To::classof(&Val); }
65};
66
67// Always allow upcasts, and perform no dynamic check for them.
68template <typename To, typename From>
69struct isa_impl<To, From, std::enable_if_t<std::is_base_of<To, From>::value>> {
70 static inline bool doit(const From &) { return true; }
71};
72
73template <typename To, typename From> struct isa_impl_cl {
74 static inline bool doit(const From &Val) {
75 return isa_impl<To, From>::doit(Val);
76 }
77};
78
79template <typename To, typename From> struct isa_impl_cl<To, const From> {
80 static inline bool doit(const From &Val) {
81 return isa_impl<To, From>::doit(Val);
82 }
83};
84
85template <typename To, typename From>
86struct isa_impl_cl<To, const std::unique_ptr<From>> {
87 static inline bool doit(const std::unique_ptr<From> &Val) {
88 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 88, __extension__ __PRETTY_FUNCTION__
))
;
89 return isa_impl_cl<To, From>::doit(*Val);
90 }
91};
92
93template <typename To, typename From> struct isa_impl_cl<To, From *> {
94 static inline bool doit(const From *Val) {
95 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 95, __extension__ __PRETTY_FUNCTION__
))
;
96 return isa_impl<To, From>::doit(*Val);
97 }
98};
99
100template <typename To, typename From> struct isa_impl_cl<To, From *const> {
101 static inline bool doit(const From *Val) {
102 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 102, __extension__ __PRETTY_FUNCTION__
))
;
103 return isa_impl<To, From>::doit(*Val);
104 }
105};
106
107template <typename To, typename From> struct isa_impl_cl<To, const From *> {
108 static inline bool doit(const From *Val) {
109 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 109, __extension__ __PRETTY_FUNCTION__
))
;
110 return isa_impl<To, From>::doit(*Val);
111 }
112};
113
114template <typename To, typename From>
115struct isa_impl_cl<To, const From *const> {
116 static inline bool doit(const From *Val) {
117 assert(Val && "isa<> used on a null pointer")(static_cast <bool> (Val && "isa<> used on a null pointer"
) ? void (0) : __assert_fail ("Val && \"isa<> used on a null pointer\""
, "llvm/include/llvm/Support/Casting.h", 117, __extension__ __PRETTY_FUNCTION__
))
;
118 return isa_impl<To, From>::doit(*Val);
119 }
120};
121
122template <typename To, typename From, typename SimpleFrom>
123struct isa_impl_wrap {
124 // When From != SimplifiedType, we can simplify the type some more by using
125 // the simplify_type template.
126 static bool doit(const From &Val) {
127 return isa_impl_wrap<To, SimpleFrom,
128 typename simplify_type<SimpleFrom>::SimpleType>::
129 doit(simplify_type<const From>::getSimplifiedValue(Val));
130 }
131};
132
133template <typename To, typename FromTy>
134struct isa_impl_wrap<To, FromTy, FromTy> {
135 // When From == SimpleType, we are as simple as we are going to get.
136 static bool doit(const FromTy &Val) {
137 return isa_impl_cl<To, FromTy>::doit(Val);
138 }
139};
140
141//===----------------------------------------------------------------------===//
142// cast_retty + cast_retty_impl
143//===----------------------------------------------------------------------===//
144
145template <class To, class From> struct cast_retty;
146
147// Calculate what type the 'cast' function should return, based on a requested
148// type of To and a source type of From.
149template <class To, class From> struct cast_retty_impl {
150 using ret_type = To &; // Normal case, return Ty&
151};
152template <class To, class From> struct cast_retty_impl<To, const From> {
153 using ret_type = const To &; // Normal case, return Ty&
154};
155
156template <class To, class From> struct cast_retty_impl<To, From *> {
157 using ret_type = To *; // Pointer arg case, return Ty*
158};
159
160template <class To, class From> struct cast_retty_impl<To, const From *> {
161 using ret_type = const To *; // Constant pointer arg case, return const Ty*
162};
163
164template <class To, class From> struct cast_retty_impl<To, const From *const> {
165 using ret_type = const To *; // Constant pointer arg case, return const Ty*
166};
167
168template <class To, class From>
169struct cast_retty_impl<To, std::unique_ptr<From>> {
170private:
171 using PointerType = typename cast_retty_impl<To, From *>::ret_type;
172 using ResultType = std::remove_pointer_t<PointerType>;
173
174public:
175 using ret_type = std::unique_ptr<ResultType>;
176};
177
178template <class To, class From, class SimpleFrom> struct cast_retty_wrap {
179 // When the simplified type and the from type are not the same, use the type
180 // simplifier to reduce the type, then reuse cast_retty_impl to get the
181 // resultant type.
182 using ret_type = typename cast_retty<To, SimpleFrom>::ret_type;
183};
184
185template <class To, class FromTy> struct cast_retty_wrap<To, FromTy, FromTy> {
186 // When the simplified type is equal to the from type, use it directly.
187 using ret_type = typename cast_retty_impl<To, FromTy>::ret_type;
188};
189
190template <class To, class From> struct cast_retty {
191 using ret_type = typename cast_retty_wrap<
192 To, From, typename simplify_type<From>::SimpleType>::ret_type;
193};
194
195//===----------------------------------------------------------------------===//
196// cast_convert_val
197//===----------------------------------------------------------------------===//
198
199// Ensure the non-simple values are converted using the simplify_type template
200// that may be specialized by smart pointers...
201//
202template <class To, class From, class SimpleFrom> struct cast_convert_val {
203 // This is not a simple type, use the template to simplify it...
204 static typename cast_retty<To, From>::ret_type doit(const From &Val) {
205 return cast_convert_val<To, SimpleFrom,
206 typename simplify_type<SimpleFrom>::SimpleType>::
207 doit(simplify_type<From>::getSimplifiedValue(const_cast<From &>(Val)));
208 }
209};
210
211template <class To, class FromTy> struct cast_convert_val<To, FromTy, FromTy> {
212 // If it's a reference, switch to a pointer to do the cast and then deref it.
213 static typename cast_retty<To, FromTy>::ret_type doit(const FromTy &Val) {
214 return *(std::remove_reference_t<typename cast_retty<To, FromTy>::ret_type>
215 *)&const_cast<FromTy &>(Val);
216 }
217};
218
219template <class To, class FromTy>
220struct cast_convert_val<To, FromTy *, FromTy *> {
221 // If it's a pointer, we can use c-style casting directly.
222 static typename cast_retty<To, FromTy *>::ret_type doit(const FromTy *Val) {
223 return (typename cast_retty<To, FromTy *>::ret_type) const_cast<FromTy *>(
224 Val);
225 }
226};
227
228//===----------------------------------------------------------------------===//
229// is_simple_type
230//===----------------------------------------------------------------------===//
231
232template <class X> struct is_simple_type {
233 static const bool value =
234 std::is_same<X, typename simplify_type<X>::SimpleType>::value;
235};
236
237// } // namespace detail
238
239//===----------------------------------------------------------------------===//
240// CastIsPossible
241//===----------------------------------------------------------------------===//
242
243/// This struct provides a way to check if a given cast is possible. It provides
244/// a static function called isPossible that is used to check if a cast can be
245/// performed. It should be overridden like this:
246///
247/// template<> struct CastIsPossible<foo, bar> {
248/// static inline bool isPossible(const bar &b) {
249/// return bar.isFoo();
250/// }
251/// };
252template <typename To, typename From, typename Enable = void>
253struct CastIsPossible {
254 static inline bool isPossible(const From &f) {
255 return isa_impl_wrap<
256 To, const From,
257 typename simplify_type<const From>::SimpleType>::doit(f);
258 }
259};
260
261// Needed for optional unwrapping. This could be implemented with isa_impl, but
262// we want to implement things in the new method and move old implementations
263// over. In fact, some of the isa_impl templates should be moved over to
264// CastIsPossible.
265template <typename To, typename From>
266struct CastIsPossible<To, Optional<From>> {
267 static inline bool isPossible(const Optional<From> &f) {
268 assert(f && "CastIsPossible::isPossible called on a nullopt!")(static_cast <bool> (f && "CastIsPossible::isPossible called on a nullopt!"
) ? void (0) : __assert_fail ("f && \"CastIsPossible::isPossible called on a nullopt!\""
, "llvm/include/llvm/Support/Casting.h", 268, __extension__ __PRETTY_FUNCTION__
))
;
269 return isa_impl_wrap<
270 To, const From,
271 typename simplify_type<const From>::SimpleType>::doit(*f);
272 }
273};
274
275/// Upcasting (from derived to base) and casting from a type to itself should
276/// always be possible.
277template <typename To, typename From>
278struct CastIsPossible<To, From,
279 std::enable_if_t<std::is_base_of<To, From>::value>> {
280 static inline bool isPossible(const From &f) { return true; }
281};
282
283//===----------------------------------------------------------------------===//
284// Cast traits
285//===----------------------------------------------------------------------===//
286
287/// All of these cast traits are meant to be implementations for useful casts
288/// that users may want to use that are outside the standard behavior. An
289/// example of how to use a special cast called `CastTrait` is:
290///
291/// template<> struct CastInfo<foo, bar> : public CastTrait<foo, bar> {};
292///
293/// Essentially, if your use case falls directly into one of the use cases
294/// supported by a given cast trait, simply inherit your special CastInfo
295/// directly from one of these to avoid having to reimplement the boilerplate
296/// `isPossible/castFailed/doCast/doCastIfPossible`. A cast trait can also
297/// provide a subset of those functions.
298
299/// This cast trait just provides castFailed for the specified `To` type to make
300/// CastInfo specializations more declarative. In order to use this, the target
301/// result type must be `To` and `To` must be constructible from `nullptr`.
302template <typename To> struct NullableValueCastFailed {
303 static To castFailed() { return To(nullptr); }
304};
305
306/// This cast trait just provides the default implementation of doCastIfPossible
307/// to make CastInfo specializations more declarative. The `Derived` template
308/// parameter *must* be provided for forwarding castFailed and doCast.
309template <typename To, typename From, typename Derived>
310struct DefaultDoCastIfPossible {
311 static To doCastIfPossible(From f) {
312 if (!Derived::isPossible(f))
6
Taking true branch
23
Taking false branch
56
Taking false branch
313 return Derived::castFailed();
7
Calling 'CastInfo::castFailed'
9
Returning from 'CastInfo::castFailed'
10
Returning null pointer, which participates in a condition later
314 return Derived::doCast(f);
24
Calling 'CastInfo::doCast'
30
Returning from 'CastInfo::doCast'
31
Returning pointer, which participates in a condition later
57
Calling 'CastInfo::doCast'
63
Returning from 'CastInfo::doCast'
64
Returning pointer, which participates in a condition later
315 }
316};
317
318namespace detail {
319/// A helper to derive the type to use with `Self` for cast traits, when the
320/// provided CRTP derived type is allowed to be void.
321template <typename OptionalDerived, typename Default>
322using SelfType = std::conditional_t<std::is_same<OptionalDerived, void>::value,
323 Default, OptionalDerived>;
324} // namespace detail
325
326/// This cast trait provides casting for the specific case of casting to a
327/// value-typed object from a pointer-typed object. Note that `To` must be
328/// nullable/constructible from a pointer to `From` to use this cast.
329template <typename To, typename From, typename Derived = void>
330struct ValueFromPointerCast
331 : public CastIsPossible<To, From *>,
332 public NullableValueCastFailed<To>,
333 public DefaultDoCastIfPossible<
334 To, From *,
335 detail::SelfType<Derived, ValueFromPointerCast<To, From>>> {
336 static inline To doCast(From *f) { return To(f); }
337};
338
339/// This cast trait provides std::unique_ptr casting. It has the semantics of
340/// moving the contents of the input unique_ptr into the output unique_ptr
341/// during the cast. It's also a good example of how to implement a move-only
342/// cast.
343template <typename To, typename From, typename Derived = void>
344struct UniquePtrCast : public CastIsPossible<To, From *> {
345 using Self = detail::SelfType<Derived, UniquePtrCast<To, From>>;
346 using CastResultType = std::unique_ptr<
347 std::remove_reference_t<typename cast_retty<To, From>::ret_type>>;
348
349 static inline CastResultType doCast(std::unique_ptr<From> &&f) {
350 return CastResultType((typename CastResultType::element_type *)f.release());
351 }
352
353 static inline CastResultType castFailed() { return CastResultType(nullptr); }
354
355 static inline CastResultType doCastIfPossible(std::unique_ptr<From> &&f) {
356 if (!Self::isPossible(f))
357 return castFailed();
358 return doCast(f);
359 }
360};
361
362/// This cast trait provides Optional<T> casting. This means that if you have a
363/// value type, you can cast it to another value type and have dyn_cast return
364/// an Optional<T>.
365template <typename To, typename From, typename Derived = void>
366struct OptionalValueCast
367 : public CastIsPossible<To, From>,
368 public DefaultDoCastIfPossible<
369 Optional<To>, From,
370 detail::SelfType<Derived, OptionalValueCast<To, From>>> {
371 static inline Optional<To> castFailed() { return Optional<To>{}; }
372
373 static inline Optional<To> doCast(const From &f) { return To(f); }
374};
375
376/// Provides a cast trait that strips `const` from types to make it easier to
377/// implement a const-version of a non-const cast. It just removes boilerplate
378/// and reduces the amount of code you as the user need to implement. You can
379/// use it like this:
380///
381/// template<> struct CastInfo<foo, bar> {
382/// ...verbose implementation...
383/// };
384///
385/// template<> struct CastInfo<foo, const bar> : public
386/// ConstStrippingForwardingCast<foo, const bar, CastInfo<foo, bar>> {};
387///
388template <typename To, typename From, typename ForwardTo>
389struct ConstStrippingForwardingCast {
390 // Remove the pointer if it exists, then we can get rid of consts/volatiles.
391 using DecayedFrom = std::remove_cv_t<std::remove_pointer_t<From>>;
392 // Now if it's a pointer, add it back. Otherwise, we want a ref.
393 using NonConstFrom = std::conditional_t<std::is_pointer<From>::value,
394 DecayedFrom *, DecayedFrom &>;
395
396 static inline bool isPossible(const From &f) {
397 return ForwardTo::isPossible(const_cast<NonConstFrom>(f));
398 }
399
400 static inline decltype(auto) castFailed() { return ForwardTo::castFailed(); }
401
402 static inline decltype(auto) doCast(const From &f) {
403 return ForwardTo::doCast(const_cast<NonConstFrom>(f));
404 }
405
406 static inline decltype(auto) doCastIfPossible(const From &f) {
407 return ForwardTo::doCastIfPossible(const_cast<NonConstFrom>(f));
5
Calling 'DefaultDoCastIfPossible::doCastIfPossible'
11
Returning from 'DefaultDoCastIfPossible::doCastIfPossible'
12
Returning null pointer, which participates in a condition later
22
Calling 'DefaultDoCastIfPossible::doCastIfPossible'
32
Returning from 'DefaultDoCastIfPossible::doCastIfPossible'
33
Returning pointer, which participates in a condition later
55
Calling 'DefaultDoCastIfPossible::doCastIfPossible'
65
Returning from 'DefaultDoCastIfPossible::doCastIfPossible'
66
Returning pointer, which participates in a condition later
408 }
409};
410
411/// Provides a cast trait that uses a defined pointer to pointer cast as a base
412/// for reference-to-reference casts. Note that it does not provide castFailed
413/// and doCastIfPossible because a pointer-to-pointer cast would likely just
414/// return `nullptr` which could cause nullptr dereference. You can use it like
415/// this:
416///
417/// template <> struct CastInfo<foo, bar *> { ... verbose implementation... };
418///
419/// template <>
420/// struct CastInfo<foo, bar>
421/// : public ForwardToPointerCast<foo, bar, CastInfo<foo, bar *>> {};
422///
423template <typename To, typename From, typename ForwardTo>
424struct ForwardToPointerCast {
425 static inline bool isPossible(const From &f) {
426 return ForwardTo::isPossible(&f);
427 }
428
429 static inline decltype(auto) doCast(const From &f) {
430 return *ForwardTo::doCast(&f);
431 }
432};
433
434//===----------------------------------------------------------------------===//
435// CastInfo
436//===----------------------------------------------------------------------===//
437
438/// This struct provides a method for customizing the way a cast is performed.
439/// It inherits from CastIsPossible, to support the case of declaring many
440/// CastIsPossible specializations without having to specialize the full
441/// CastInfo.
442///
443/// In order to specialize different behaviors, specify different functions in
444/// your CastInfo specialization.
445/// For isa<> customization, provide:
446///
447/// `static bool isPossible(const From &f)`
448///
449/// For cast<> customization, provide:
450///
451/// `static To doCast(const From &f)`
452///
453/// For dyn_cast<> and the *_if_present<> variants' customization, provide:
454///
455/// `static To castFailed()` and `static To doCastIfPossible(const From &f)`
456///
457/// Your specialization might look something like this:
458///
459/// template<> struct CastInfo<foo, bar> : public CastIsPossible<foo, bar> {
460/// static inline foo doCast(const bar &b) {
461/// return foo(const_cast<bar &>(b));
462/// }
463/// static inline foo castFailed() { return foo(); }
464/// static inline foo doCastIfPossible(const bar &b) {
465/// if (!CastInfo<foo, bar>::isPossible(b))
466/// return castFailed();
467/// return doCast(b);
468/// }
469/// };
470
471// The default implementations of CastInfo don't use cast traits for now because
472// we need to specify types all over the place due to the current expected
473// casting behavior and the way cast_retty works. New use cases can and should
474// take advantage of the cast traits whenever possible!
475
476template <typename To, typename From, typename Enable = void>
477struct CastInfo : public CastIsPossible<To, From> {
478 using Self = CastInfo<To, From, Enable>;
479
480 using CastReturnType = typename cast_retty<To, From>::ret_type;
481
482 static inline CastReturnType doCast(const From &f) {
483 return cast_convert_val<
484 To, From,
485 typename simplify_type<From>::SimpleType>::doit(const_cast<From &>(f));
486 }
487
488 // This assumes that you can construct the cast return type from `nullptr`.
489 // This is largely to support legacy use cases - if you don't want this
490 // behavior you should specialize CastInfo for your use case.
491 static inline CastReturnType castFailed() { return CastReturnType(nullptr); }
492
493 static inline CastReturnType doCastIfPossible(const From &f) {
494 if (!Self::isPossible(f))
495 return castFailed();
496 return doCast(f);
497 }
498};
499
500/// This struct provides an overload for CastInfo where From has simplify_type
501/// defined. This simply forwards to the appropriate CastInfo with the
502/// simplified type/value, so you don't have to implement both.
503template <typename To, typename From>
504struct CastInfo<To, From, std::enable_if_t<!is_simple_type<From>::value>> {
505 using Self = CastInfo<To, From>;
506 using SimpleFrom = typename simplify_type<From>::SimpleType;
507 using SimplifiedSelf = CastInfo<To, SimpleFrom>;
508
509 static inline bool isPossible(From &f) {
510 return SimplifiedSelf::isPossible(
511 simplify_type<From>::getSimplifiedValue(f));
512 }
513
514 static inline decltype(auto) doCast(From &f) {
515 return SimplifiedSelf::doCast(simplify_type<From>::getSimplifiedValue(f));
516 }
517
518 static inline decltype(auto) castFailed() {
519 return SimplifiedSelf::castFailed();
520 }
521
522 static inline decltype(auto) doCastIfPossible(From &f) {
523 return SimplifiedSelf::doCastIfPossible(
524 simplify_type<From>::getSimplifiedValue(f));
525 }
526};
527
528//===----------------------------------------------------------------------===//
529// Pre-specialized CastInfo
530//===----------------------------------------------------------------------===//
531
532/// Provide a CastInfo specialized for std::unique_ptr.
533template <typename To, typename From>
534struct CastInfo<To, std::unique_ptr<From>> : public UniquePtrCast<To, From> {};
535
536/// Provide a CastInfo specialized for Optional<From>. It's assumed that if the
537/// input is Optional<From> that the output can be Optional<To>. If that's not
538/// the case, specialize CastInfo for your use case.
539template <typename To, typename From>
540struct CastInfo<To, Optional<From>> : public OptionalValueCast<To, From> {};
541
542/// isa<X> - Return true if the parameter to the template is an instance of one
543/// of the template type arguments. Used like this:
544///
545/// if (isa<Type>(myVal)) { ... }
546/// if (isa<Type0, Type1, Type2>(myVal)) { ... }
547template <typename To, typename From>
548[[nodiscard]] inline bool isa(const From &Val) {
549 return CastInfo<To, const From>::isPossible(Val);
550}
551
552template <typename First, typename Second, typename... Rest, typename From>
553[[nodiscard]] inline bool isa(const From &Val) {
554 return isa<First>(Val) || isa<Second, Rest...>(Val);
555}
556
557/// cast<X> - Return the argument parameter cast to the specified type. This
558/// casting operator asserts that the type is correct, so it does not return
559/// null on failure. It does not allow a null argument (use cast_if_present for
560/// that). It is typically used like this:
561///
562/// cast<Instruction>(myVal)->getParent()
563
564template <typename To, typename From>
565[[nodiscard]] inline decltype(auto) cast(const From &Val) {
566 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 566, __extension__ __PRETTY_FUNCTION__
))
;
567 return CastInfo<To, const From>::doCast(Val);
568}
569
570template <typename To, typename From>
571[[nodiscard]] inline decltype(auto) cast(From &Val) {
572 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 572, __extension__ __PRETTY_FUNCTION__
))
;
573 return CastInfo<To, From>::doCast(Val);
574}
575
576template <typename To, typename From>
577[[nodiscard]] inline decltype(auto) cast(From *Val) {
578 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 578, __extension__ __PRETTY_FUNCTION__
))
;
579 return CastInfo<To, From *>::doCast(Val);
580}
581
582template <typename To, typename From>
583[[nodiscard]] inline decltype(auto) cast(std::unique_ptr<From> &&Val) {
584 assert(isa<To>(Val) && "cast<Ty>() argument of incompatible type!")(static_cast <bool> (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<To>(Val) && \"cast<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 584, __extension__ __PRETTY_FUNCTION__
))
;
585 return CastInfo<To, std::unique_ptr<From>>::doCast(std::move(Val));
586}
587
588/// dyn_cast<X> - Return the argument parameter cast to the specified type. This
589/// casting operator returns null if the argument is of the wrong type, so it
590/// can be used to test for a type as well as cast if successful. The value
591/// passed in must be present, if not, use dyn_cast_if_present. This should be
592/// used in the context of an if statement like this:
593///
594/// if (const Instruction *I = dyn_cast<Instruction>(myVal)) { ... }
595
596template <typename To, typename From>
597[[nodiscard]] inline decltype(auto) dyn_cast(const From &Val) {
598 return CastInfo<To, const From>::doCastIfPossible(Val);
4
Calling 'ConstStrippingForwardingCast::doCastIfPossible'
13
Returning from 'ConstStrippingForwardingCast::doCastIfPossible'
14
Returning null pointer, which participates in a condition later
21
Calling 'ConstStrippingForwardingCast::doCastIfPossible'
34
Returning from 'ConstStrippingForwardingCast::doCastIfPossible'
35
Returning pointer, which participates in a condition later
54
Calling 'ConstStrippingForwardingCast::doCastIfPossible'
67
Returning from 'ConstStrippingForwardingCast::doCastIfPossible'
68
Returning pointer, which participates in a condition later
599}
600
601template <typename To, typename From>
602[[nodiscard]] inline decltype(auto) dyn_cast(From &Val) {
603 return CastInfo<To, From>::doCastIfPossible(Val);
604}
605
606template <typename To, typename From>
607[[nodiscard]] inline decltype(auto) dyn_cast(From *Val) {
608 return CastInfo<To, From *>::doCastIfPossible(Val);
609}
610
611template <typename To, typename From>
612[[nodiscard]] inline decltype(auto) dyn_cast(std::unique_ptr<From> &&Val) {
613 return CastInfo<To, std::unique_ptr<From>>::doCastIfPossible(std::move(Val));
614}
615
616//===----------------------------------------------------------------------===//
617// ValueIsPresent
618//===----------------------------------------------------------------------===//
619
620template <typename T>
621constexpr bool IsNullable = std::is_pointer<T>::value ||
622 std::is_constructible<T, std::nullptr_t>::value;
623
624/// ValueIsPresent provides a way to check if a value is, well, present. For
625/// pointers, this is the equivalent of checking against nullptr, for
626/// Optionals this is the equivalent of checking hasValue(). It also
627/// provides a method for unwrapping a value (think dereferencing a
628/// pointer).
629
630// Generic values can't *not* be present.
631template <typename T, typename Enable = void> struct ValueIsPresent {
632 using UnwrappedType = T;
633 static inline bool isPresent(const T &t) { return true; }
634 static inline decltype(auto) unwrapValue(T &t) { return t; }
635};
636
637// Optional provides its own way to check if something is present.
638template <typename T> struct ValueIsPresent<Optional<T>> {
639 using UnwrappedType = T;
640 static inline bool isPresent(const Optional<T> &t) { return t.has_value(); }
641 static inline decltype(auto) unwrapValue(Optional<T> &t) { return t.value(); }
642};
643
644// If something is "nullable" then we just compare it to nullptr to see if it
645// exists.
646template <typename T>
647struct ValueIsPresent<T, std::enable_if_t<IsNullable<T>>> {
648 using UnwrappedType = T;
649 static inline bool isPresent(const T &t) { return t != nullptr; }
650 static inline decltype(auto) unwrapValue(T &t) { return t; }
651};
652
653namespace detail {
654// Convenience function we can use to check if a value is present. Because of
655// simplify_type, we have to call it on the simplified type for now.
656template <typename T> inline bool isPresent(const T &t) {
657 return ValueIsPresent<typename simplify_type<T>::SimpleType>::isPresent(
658 simplify_type<T>::getSimplifiedValue(const_cast<T &>(t)));
659}
660
661// Convenience function we can use to unwrap a value.
662template <typename T> inline decltype(auto) unwrapValue(T &t) {
663 return ValueIsPresent<T>::unwrapValue(t);
664}
665} // namespace detail
666
667/// isa_and_present<X> - Functionally identical to isa, except that a null value
668/// is accepted.
669template <typename... X, class Y>
670[[nodiscard]] inline bool isa_and_present(const Y &Val) {
671 if (!detail::isPresent(Val))
672 return false;
673 return isa<X...>(Val);
674}
675
676template <typename... X, class Y>
677[[nodiscard]] inline bool isa_and_nonnull(const Y &Val) {
678 return isa_and_present<X...>(Val);
679}
680
681/// cast_if_present<X> - Functionally identical to cast, except that a null
682/// value is accepted.
683template <class X, class Y>
684[[nodiscard]] inline auto cast_if_present(const Y &Val) {
685 if (!detail::isPresent(Val))
686 return CastInfo<X, const Y>::castFailed();
687 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 687, __extension__ __PRETTY_FUNCTION__
))
;
688 return cast<X>(detail::unwrapValue(Val));
689}
690
691template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y &Val) {
692 if (!detail::isPresent(Val))
693 return CastInfo<X, Y>::castFailed();
694 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 694, __extension__ __PRETTY_FUNCTION__
))
;
695 return cast<X>(detail::unwrapValue(Val));
696}
697
698template <class X, class Y> [[nodiscard]] inline auto cast_if_present(Y *Val) {
699 if (!detail::isPresent(Val))
700 return CastInfo<X, Y *>::castFailed();
701 assert(isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!")(static_cast <bool> (isa<X>(Val) && "cast_if_present<Ty>() argument of incompatible type!"
) ? void (0) : __assert_fail ("isa<X>(Val) && \"cast_if_present<Ty>() argument of incompatible type!\""
, "llvm/include/llvm/Support/Casting.h", 701, __extension__ __PRETTY_FUNCTION__
))
;
702 return cast<X>(detail::unwrapValue(Val));
703}
704
705template <class X, class Y>
706[[nodiscard]] inline auto cast_if_present(std::unique_ptr<Y> &&Val) {
707 if (!detail::isPresent(Val))
708 return UniquePtrCast<X, Y>::castFailed();
709 return UniquePtrCast<X, Y>::doCast(std::move(Val));
710}
711
712// Provide a forwarding from cast_or_null to cast_if_present for current
713// users. This is deprecated and will be removed in a future patch, use
714// cast_if_present instead.
715template <class X, class Y> auto cast_or_null(const Y &Val) {
716 return cast_if_present<X>(Val);
717}
718
719template <class X, class Y> auto cast_or_null(Y &Val) {
720 return cast_if_present<X>(Val);
721}
722
723template <class X, class Y> auto cast_or_null(Y *Val) {
724 return cast_if_present<X>(Val);
725}
726
727template <class X, class Y> auto cast_or_null(std::unique_ptr<Y> &&Val) {
728 return cast_if_present<X>(std::move(Val));
729}
730
731/// dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a
732/// null (or none in the case of optionals) value is accepted.
733template <class X, class Y> auto dyn_cast_if_present(const Y &Val) {
734 if (!detail::isPresent(Val))
735 return CastInfo<X, const Y>::castFailed();
736 return CastInfo<X, const Y>::doCastIfPossible(detail::unwrapValue(Val));
737}
738
739template <class X, class Y> auto dyn_cast_if_present(Y &Val) {
740 if (!detail::isPresent(Val))
741 return CastInfo<X, Y>::castFailed();
742 return CastInfo<X, Y>::doCastIfPossible(detail::unwrapValue(Val));
743}
744
745template <class X, class Y> auto dyn_cast_if_present(Y *Val) {
746 if (!detail::isPresent(Val))
747 return CastInfo<X, Y *>::castFailed();
748 return CastInfo<X, Y *>::doCastIfPossible(detail::unwrapValue(Val));
749}
750
751// Forwards to dyn_cast_if_present to avoid breaking current users. This is
752// deprecated and will be removed in a future patch, use
753// cast_if_present instead.
754template <class X, class Y> auto dyn_cast_or_null(const Y &Val) {
755 return dyn_cast_if_present<X>(Val);
756}
757
758template <class X, class Y> auto dyn_cast_or_null(Y &Val) {
759 return dyn_cast_if_present<X>(Val);
760}
761
762template <class X, class Y> auto dyn_cast_or_null(Y *Val) {
763 return dyn_cast_if_present<X>(Val);
764}
765
766/// unique_dyn_cast<X> - Given a unique_ptr<Y>, try to return a unique_ptr<X>,
767/// taking ownership of the input pointer iff isa<X>(Val) is true. If the
768/// cast is successful, From refers to nullptr on exit and the casted value
769/// is returned. If the cast is unsuccessful, the function returns nullptr
770/// and From is unchanged.
771template <class X, class Y>
772[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
773unique_dyn_cast(std::unique_ptr<Y> &Val) {
774 if (!isa<X>(Val))
775 return nullptr;
776 return cast<X>(std::move(Val));
777}
778
779template <class X, class Y>
780[[nodiscard]] inline auto unique_dyn_cast(std::unique_ptr<Y> &&Val) {
781 return unique_dyn_cast<X, Y>(Val);
782}
783
784// unique_dyn_cast_or_null<X> - Functionally identical to unique_dyn_cast,
785// except that a null value is accepted.
786template <class X, class Y>
787[[nodiscard]] inline typename CastInfo<X, std::unique_ptr<Y>>::CastResultType
788unique_dyn_cast_or_null(std::unique_ptr<Y> &Val) {
789 if (!Val)
790 return nullptr;
791 return unique_dyn_cast<X, Y>(Val);
792}
793
794template <class X, class Y>
795[[nodiscard]] inline auto unique_dyn_cast_or_null(std::unique_ptr<Y> &&Val) {
796 return unique_dyn_cast_or_null<X, Y>(Val);
797}
798
799} // end namespace llvm
800
801#endif // LLVM_SUPPORT_CASTING_H

/build/llvm-toolchain-snapshot-16~++20220904122748+c444af1c20b3/clang/include/clang/AST/Type.h

1//===- Type.h - C Language Family Type Representation -----------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// C Language Family Type Representation
11///
12/// This file defines the clang::Type interface and subclasses, used to
13/// represent types for languages in the C family.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_CLANG_AST_TYPE_H
18#define LLVM_CLANG_AST_TYPE_H
19
20#include "clang/AST/DependenceFlags.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/TemplateName.h"
23#include "clang/Basic/AddressSpaces.h"
24#include "clang/Basic/AttrKinds.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/ExceptionSpecificationType.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/PartialDiagnostic.h"
30#include "clang/Basic/SourceLocation.h"
31#include "clang/Basic/Specifiers.h"
32#include "clang/Basic/Visibility.h"
33#include "llvm/ADT/APInt.h"
34#include "llvm/ADT/APSInt.h"
35#include "llvm/ADT/ArrayRef.h"
36#include "llvm/ADT/FoldingSet.h"
37#include "llvm/ADT/None.h"
38#include "llvm/ADT/Optional.h"
39#include "llvm/ADT/PointerIntPair.h"
40#include "llvm/ADT/PointerUnion.h"
41#include "llvm/ADT/StringRef.h"
42#include "llvm/ADT/Twine.h"
43#include "llvm/ADT/iterator_range.h"
44#include "llvm/Support/Casting.h"
45#include "llvm/Support/Compiler.h"
46#include "llvm/Support/ErrorHandling.h"
47#include "llvm/Support/PointerLikeTypeTraits.h"
48#include "llvm/Support/TrailingObjects.h"
49#include "llvm/Support/type_traits.h"
50#include <cassert>
51#include <cstddef>
52#include <cstdint>
53#include <cstring>
54#include <string>
55#include <type_traits>
56#include <utility>
57
58namespace clang {
59
60class BTFTypeTagAttr;
61class ExtQuals;
62class QualType;
63class ConceptDecl;
64class TagDecl;
65class TemplateParameterList;
66class Type;
67
68enum {
69 TypeAlignmentInBits = 4,
70 TypeAlignment = 1 << TypeAlignmentInBits
71};
72
73namespace serialization {
74 template <class T> class AbstractTypeReader;
75 template <class T> class AbstractTypeWriter;
76}
77
78} // namespace clang
79
80namespace llvm {
81
82 template <typename T>
83 struct PointerLikeTypeTraits;
84 template<>
85 struct PointerLikeTypeTraits< ::clang::Type*> {
86 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
87
88 static inline ::clang::Type *getFromVoidPointer(void *P) {
89 return static_cast< ::clang::Type*>(P);
90 }
91
92 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
93 };
94
95 template<>
96 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
97 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
98
99 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
100 return static_cast< ::clang::ExtQuals*>(P);
101 }
102
103 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
104 };
105
106} // namespace llvm
107
108namespace clang {
109
110class ASTContext;
111template <typename> class CanQual;
112class CXXRecordDecl;
113class DeclContext;
114class EnumDecl;
115class Expr;
116class ExtQualsTypeCommonBase;
117class FunctionDecl;
118class IdentifierInfo;
119class NamedDecl;
120class ObjCInterfaceDecl;
121class ObjCProtocolDecl;
122class ObjCTypeParamDecl;
123struct PrintingPolicy;
124class RecordDecl;
125class Stmt;
126class TagDecl;
127class TemplateArgument;
128class TemplateArgumentListInfo;
129class TemplateArgumentLoc;
130class TemplateTypeParmDecl;
131class TypedefNameDecl;
132class UnresolvedUsingTypenameDecl;
133class UsingShadowDecl;
134
135using CanQualType = CanQual<Type>;
136
137// Provide forward declarations for all of the *Type classes.
138#define TYPE(Class, Base) class Class##Type;
139#include "clang/AST/TypeNodes.inc"
140
141/// The collection of all-type qualifiers we support.
142/// Clang supports five independent qualifiers:
143/// * C99: const, volatile, and restrict
144/// * MS: __unaligned
145/// * Embedded C (TR18037): address spaces
146/// * Objective C: the GC attributes (none, weak, or strong)
147class Qualifiers {
148public:
149 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
150 Const = 0x1,
151 Restrict = 0x2,
152 Volatile = 0x4,
153 CVRMask = Const | Volatile | Restrict
154 };
155
156 enum GC {
157 GCNone = 0,
158 Weak,
159 Strong
160 };
161
162 enum ObjCLifetime {
163 /// There is no lifetime qualification on this type.
164 OCL_None,
165
166 /// This object can be modified without requiring retains or
167 /// releases.
168 OCL_ExplicitNone,
169
170 /// Assigning into this object requires the old value to be
171 /// released and the new value to be retained. The timing of the
172 /// release of the old value is inexact: it may be moved to
173 /// immediately after the last known point where the value is
174 /// live.
175 OCL_Strong,
176
177 /// Reading or writing from this object requires a barrier call.
178 OCL_Weak,
179
180 /// Assigning into this object requires a lifetime extension.
181 OCL_Autoreleasing
182 };
183
184 enum {
185 /// The maximum supported address space number.
186 /// 23 bits should be enough for anyone.
187 MaxAddressSpace = 0x7fffffu,
188
189 /// The width of the "fast" qualifier mask.
190 FastWidth = 3,
191
192 /// The fast qualifier mask.
193 FastMask = (1 << FastWidth) - 1
194 };
195
196 /// Returns the common set of qualifiers while removing them from
197 /// the given sets.
198 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
199 // If both are only CVR-qualified, bit operations are sufficient.
200 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
201 Qualifiers Q;
202 Q.Mask = L.Mask & R.Mask;
203 L.Mask &= ~Q.Mask;
204 R.Mask &= ~Q.Mask;
205 return Q;
206 }
207
208 Qualifiers Q;
209 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
210 Q.addCVRQualifiers(CommonCRV);
211 L.removeCVRQualifiers(CommonCRV);
212 R.removeCVRQualifiers(CommonCRV);
213
214 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
215 Q.setObjCGCAttr(L.getObjCGCAttr());
216 L.removeObjCGCAttr();
217 R.removeObjCGCAttr();
218 }
219
220 if (L.getObjCLifetime() == R.getObjCLifetime()) {
221 Q.setObjCLifetime(L.getObjCLifetime());
222 L.removeObjCLifetime();
223 R.removeObjCLifetime();
224 }
225
226 if (L.getAddressSpace() == R.getAddressSpace()) {
227 Q.setAddressSpace(L.getAddressSpace());
228 L.removeAddressSpace();
229 R.removeAddressSpace();
230 }
231 return Q;
232 }
233
234 static Qualifiers fromFastMask(unsigned Mask) {
235 Qualifiers Qs;
236 Qs.addFastQualifiers(Mask);
237 return Qs;
238 }
239
240 static Qualifiers fromCVRMask(unsigned CVR) {
241 Qualifiers Qs;
242 Qs.addCVRQualifiers(CVR);
243 return Qs;
244 }
245
246 static Qualifiers fromCVRUMask(unsigned CVRU) {
247 Qualifiers Qs;
248 Qs.addCVRUQualifiers(CVRU);
249 return Qs;
250 }
251
252 // Deserialize qualifiers from an opaque representation.
253 static Qualifiers fromOpaqueValue(unsigned opaque) {
254 Qualifiers Qs;
255 Qs.Mask = opaque;
256 return Qs;
257 }
258
259 // Serialize these qualifiers into an opaque representation.
260 unsigned getAsOpaqueValue() const {
261 return Mask;
262 }
263
264 bool hasConst() const { return Mask & Const; }
265 bool hasOnlyConst() const { return Mask == Const; }
266 void removeConst() { Mask &= ~Const; }
267 void addConst() { Mask |= Const; }
268 Qualifiers withConst() const {
269 Qualifiers Qs = *this;
270 Qs.addConst();
271 return Qs;
272 }
273
274 bool hasVolatile() const { return Mask & Volatile; }
275 bool hasOnlyVolatile() const { return Mask == Volatile; }
276 void removeVolatile() { Mask &= ~Volatile; }
277 void addVolatile() { Mask |= Volatile; }
278 Qualifiers withVolatile() const {
279 Qualifiers Qs = *this;
280 Qs.addVolatile();
281 return Qs;
282 }
283
284 bool hasRestrict() const { return Mask & Restrict; }
285 bool hasOnlyRestrict() const { return Mask == Restrict; }
286 void removeRestrict() { Mask &= ~Restrict; }
287 void addRestrict() { Mask |= Restrict; }
288 Qualifiers withRestrict() const {
289 Qualifiers Qs = *this;
290 Qs.addRestrict();
291 return Qs;
292 }
293
294 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
295 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
296 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
297
298 void setCVRQualifiers(unsigned mask) {
299 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 299, __extension__ __PRETTY_FUNCTION__
))
;
300 Mask = (Mask & ~CVRMask) | mask;
301 }
302 void removeCVRQualifiers(unsigned mask) {
303 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 303, __extension__ __PRETTY_FUNCTION__
))
;
304 Mask &= ~mask;
305 }
306 void removeCVRQualifiers() {
307 removeCVRQualifiers(CVRMask);
308 }
309 void addCVRQualifiers(unsigned mask) {
310 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")(static_cast <bool> (!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? void (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "clang/include/clang/AST/Type.h", 310, __extension__ __PRETTY_FUNCTION__
))
;
311 Mask |= mask;
312 }
313 void addCVRUQualifiers(unsigned mask) {
314 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")(static_cast <bool> (!(mask & ~CVRMask & ~UMask
) && "bitmask contains non-CVRU bits") ? void (0) : __assert_fail
("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "clang/include/clang/AST/Type.h", 314, __extension__ __PRETTY_FUNCTION__
))
;
315 Mask |= mask;
316 }
317
318 bool hasUnaligned() const { return Mask & UMask; }
319 void setUnaligned(bool flag) {
320 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
321 }
322 void removeUnaligned() { Mask &= ~UMask; }
323 void addUnaligned() { Mask |= UMask; }
324
325 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
326 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
327 void setObjCGCAttr(GC type) {
328 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
329 }
330 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
331 void addObjCGCAttr(GC type) {
332 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 332, __extension__ __PRETTY_FUNCTION__
))
;
333 setObjCGCAttr(type);
334 }
335 Qualifiers withoutObjCGCAttr() const {
336 Qualifiers qs = *this;
337 qs.removeObjCGCAttr();
338 return qs;
339 }
340 Qualifiers withoutObjCLifetime() const {
341 Qualifiers qs = *this;
342 qs.removeObjCLifetime();
343 return qs;
344 }
345 Qualifiers withoutAddressSpace() const {
346 Qualifiers qs = *this;
347 qs.removeAddressSpace();
348 return qs;
349 }
350
351 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
352 ObjCLifetime getObjCLifetime() const {
353 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
354 }
355 void setObjCLifetime(ObjCLifetime type) {
356 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
357 }
358 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
359 void addObjCLifetime(ObjCLifetime type) {
360 assert(type)(static_cast <bool> (type) ? void (0) : __assert_fail (
"type", "clang/include/clang/AST/Type.h", 360, __extension__ __PRETTY_FUNCTION__
))
;
361 assert(!hasObjCLifetime())(static_cast <bool> (!hasObjCLifetime()) ? void (0) : __assert_fail
("!hasObjCLifetime()", "clang/include/clang/AST/Type.h", 361
, __extension__ __PRETTY_FUNCTION__))
;
362 Mask |= (type << LifetimeShift);
363 }
364
365 /// True if the lifetime is neither None or ExplicitNone.
366 bool hasNonTrivialObjCLifetime() const {
367 ObjCLifetime lifetime = getObjCLifetime();
368 return (lifetime > OCL_ExplicitNone);
369 }
370
371 /// True if the lifetime is either strong or weak.
372 bool hasStrongOrWeakObjCLifetime() const {
373 ObjCLifetime lifetime = getObjCLifetime();
374 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
375 }
376
377 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
378 LangAS getAddressSpace() const {
379 return static_cast<LangAS>(Mask >> AddressSpaceShift);
380 }
381 bool hasTargetSpecificAddressSpace() const {
382 return isTargetAddressSpace(getAddressSpace());
383 }
384 /// Get the address space attribute value to be printed by diagnostics.
385 unsigned getAddressSpaceAttributePrintValue() const {
386 auto Addr = getAddressSpace();
387 // This function is not supposed to be used with language specific
388 // address spaces. If that happens, the diagnostic message should consider
389 // printing the QualType instead of the address space value.
390 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())(static_cast <bool> (Addr == LangAS::Default || hasTargetSpecificAddressSpace
()) ? void (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "clang/include/clang/AST/Type.h", 390, __extension__ __PRETTY_FUNCTION__
))
;
391 if (Addr != LangAS::Default)
392 return toTargetAddressSpace(Addr);
393 // TODO: The diagnostic messages where Addr may be 0 should be fixed
394 // since it cannot differentiate the situation where 0 denotes the default
395 // address space or user specified __attribute__((address_space(0))).
396 return 0;
397 }
398 void setAddressSpace(LangAS space) {
399 assert((unsigned)space <= MaxAddressSpace)(static_cast <bool> ((unsigned)space <= MaxAddressSpace
) ? void (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "clang/include/clang/AST/Type.h", 399, __extension__ __PRETTY_FUNCTION__
))
;
400 Mask = (Mask & ~AddressSpaceMask)
401 | (((uint32_t) space) << AddressSpaceShift);
402 }
403 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
404 void addAddressSpace(LangAS space) {
405 assert(space != LangAS::Default)(static_cast <bool> (space != LangAS::Default) ? void (
0) : __assert_fail ("space != LangAS::Default", "clang/include/clang/AST/Type.h"
, 405, __extension__ __PRETTY_FUNCTION__))
;
406 setAddressSpace(space);
407 }
408
409 // Fast qualifiers are those that can be allocated directly
410 // on a QualType object.
411 bool hasFastQualifiers() const { return getFastQualifiers(); }
412 unsigned getFastQualifiers() const { return Mask & FastMask; }
413 void setFastQualifiers(unsigned mask) {
414 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 414, __extension__ __PRETTY_FUNCTION__
))
;
415 Mask = (Mask & ~FastMask) | mask;
416 }
417 void removeFastQualifiers(unsigned mask) {
418 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 418, __extension__ __PRETTY_FUNCTION__
))
;
419 Mask &= ~mask;
420 }
421 void removeFastQualifiers() {
422 removeFastQualifiers(FastMask);
423 }
424 void addFastQualifiers(unsigned mask) {
425 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")(static_cast <bool> (!(mask & ~FastMask) &&
"bitmask contains non-fast qualifier bits") ? void (0) : __assert_fail
("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "clang/include/clang/AST/Type.h", 425, __extension__ __PRETTY_FUNCTION__
))
;
426 Mask |= mask;
427 }
428
429 /// Return true if the set contains any qualifiers which require an ExtQuals
430 /// node to be allocated.
431 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
432 Qualifiers getNonFastQualifiers() const {
433 Qualifiers Quals = *this;
434 Quals.setFastQualifiers(0);
435 return Quals;
436 }
437
438 /// Return true if the set contains any qualifiers.
439 bool hasQualifiers() const { return Mask; }
440 bool empty() const { return !Mask; }
441
442 /// Add the qualifiers from the given set to this set.
443 void addQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-or it in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask |= Q.Mask;
448 else {
449 Mask |= (Q.Mask & CVRMask);
450 if (Q.hasAddressSpace())
451 addAddressSpace(Q.getAddressSpace());
452 if (Q.hasObjCGCAttr())
453 addObjCGCAttr(Q.getObjCGCAttr());
454 if (Q.hasObjCLifetime())
455 addObjCLifetime(Q.getObjCLifetime());
456 }
457 }
458
459 /// Remove the qualifiers from the given set from this set.
460 void removeQualifiers(Qualifiers Q) {
461 // If the other set doesn't have any non-boolean qualifiers, just
462 // bit-and the inverse in.
463 if (!(Q.Mask & ~CVRMask))
464 Mask &= ~Q.Mask;
465 else {
466 Mask &= ~(Q.Mask & CVRMask);
467 if (getObjCGCAttr() == Q.getObjCGCAttr())
468 removeObjCGCAttr();
469 if (getObjCLifetime() == Q.getObjCLifetime())
470 removeObjCLifetime();
471 if (getAddressSpace() == Q.getAddressSpace())
472 removeAddressSpace();
473 }
474 }
475
476 /// Add the qualifiers from the given set to this set, given that
477 /// they don't conflict.
478 void addConsistentQualifiers(Qualifiers qs) {
479 assert(getAddressSpace() == qs.getAddressSpace() ||(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 480, __extension__ __PRETTY_FUNCTION__
))
480 !hasAddressSpace() || !qs.hasAddressSpace())(static_cast <bool> (getAddressSpace() == qs.getAddressSpace
() || !hasAddressSpace() || !qs.hasAddressSpace()) ? void (0)
: __assert_fail ("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "clang/include/clang/AST/Type.h", 480, __extension__ __PRETTY_FUNCTION__
))
;
481 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 482, __extension__ __PRETTY_FUNCTION__
))
482 !hasObjCGCAttr() || !qs.hasObjCGCAttr())(static_cast <bool> (getObjCGCAttr() == qs.getObjCGCAttr
() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()) ? void (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "clang/include/clang/AST/Type.h", 482, __extension__ __PRETTY_FUNCTION__
))
;
483 assert(getObjCLifetime() == qs.getObjCLifetime() ||(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 484, __extension__ __PRETTY_FUNCTION__
))
484 !hasObjCLifetime() || !qs.hasObjCLifetime())(static_cast <bool> (getObjCLifetime() == qs.getObjCLifetime
() || !hasObjCLifetime() || !qs.hasObjCLifetime()) ? void (0)
: __assert_fail ("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "clang/include/clang/AST/Type.h", 484, __extension__ __PRETTY_FUNCTION__
))
;
485 Mask |= qs.Mask;
486 }
487
488 /// Returns true if address space A is equal to or a superset of B.
489 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
490 /// overlapping address spaces.
491 /// CL1.1 or CL1.2:
492 /// every address space is a superset of itself.
493 /// CL2.0 adds:
494 /// __generic is a superset of any address space except for __constant.
495 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
496 // Address spaces must match exactly.
497 return A == B ||
498 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
499 // for __constant can be used as __generic.
500 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
501 // We also define global_device and global_host address spaces,
502 // to distinguish global pointers allocated on host from pointers
503 // allocated on device, which are a subset of __global.
504 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
505 B == LangAS::opencl_global_host)) ||
506 (A == LangAS::sycl_global && (B == LangAS::sycl_global_device ||
507 B == LangAS::sycl_global_host)) ||
508 // Consider pointer size address spaces to be equivalent to default.
509 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
510 (isPtrSizeAddressSpace(B) || B == LangAS::Default)) ||
511 // Default is a superset of SYCL address spaces.
512 (A == LangAS::Default &&
513 (B == LangAS::sycl_private || B == LangAS::sycl_local ||
514 B == LangAS::sycl_global || B == LangAS::sycl_global_device ||
515 B == LangAS::sycl_global_host)) ||
516 // In HIP device compilation, any cuda address space is allowed
517 // to implicitly cast into the default address space.
518 (A == LangAS::Default &&
519 (B == LangAS::cuda_constant || B == LangAS::cuda_device ||
520 B == LangAS::cuda_shared));
521 }
522
523 /// Returns true if the address space in these qualifiers is equal to or
524 /// a superset of the address space in the argument qualifiers.
525 bool isAddressSpaceSupersetOf(Qualifiers other) const {
526 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
527 }
528
529 /// Determines if these qualifiers compatibly include another set.
530 /// Generally this answers the question of whether an object with the other
531 /// qualifiers can be safely used as an object with these qualifiers.
532 bool compatiblyIncludes(Qualifiers other) const {
533 return isAddressSpaceSupersetOf(other) &&
534 // ObjC GC qualifiers can match, be added, or be removed, but can't
535 // be changed.
536 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
537 !other.hasObjCGCAttr()) &&
538 // ObjC lifetime qualifiers must match exactly.
539 getObjCLifetime() == other.getObjCLifetime() &&
540 // CVR qualifiers may subset.
541 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
542 // U qualifier may superset.
543 (!other.hasUnaligned() || hasUnaligned());
544 }
545
546 /// Determines if these qualifiers compatibly include another set of
547 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
548 ///
549 /// One set of Objective-C lifetime qualifiers compatibly includes the other
550 /// if the lifetime qualifiers match, or if both are non-__weak and the
551 /// including set also contains the 'const' qualifier, or both are non-__weak
552 /// and one is None (which can only happen in non-ARC modes).
553 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
554 if (getObjCLifetime() == other.getObjCLifetime())
555 return true;
556
557 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
558 return false;
559
560 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
561 return true;
562
563 return hasConst();
564 }
565
566 /// Determine whether this set of qualifiers is a strict superset of
567 /// another set of qualifiers, not considering qualifier compatibility.
568 bool isStrictSupersetOf(Qualifiers Other) const;
569
570 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
571 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
572
573 explicit operator bool() const { return hasQualifiers(); }
574
575 Qualifiers &operator+=(Qualifiers R) {
576 addQualifiers(R);
577 return *this;
578 }
579
580 // Union two qualifier sets. If an enumerated qualifier appears
581 // in both sets, use the one from the right.
582 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
583 L += R;
584 return L;
585 }
586
587 Qualifiers &operator-=(Qualifiers R) {
588 removeQualifiers(R);
589 return *this;
590 }
591
592 /// Compute the difference between two qualifier sets.
593 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
594 L -= R;
595 return L;
596 }
597
598 std::string getAsString() const;
599 std::string getAsString(const PrintingPolicy &Policy) const;
600
601 static std::string getAddrSpaceAsString(LangAS AS);
602
603 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
604 void print(raw_ostream &OS, const PrintingPolicy &Policy,
605 bool appendSpaceIfNonEmpty = false) const;
606
607 void Profile(llvm::FoldingSetNodeID &ID) const {
608 ID.AddInteger(Mask);
609 }
610
611private:
612 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
613 // |C R V|U|GCAttr|Lifetime|AddressSpace|
614 uint32_t Mask = 0;
615
616 static const uint32_t UMask = 0x8;
617 static const uint32_t UShift = 3;
618 static const uint32_t GCAttrMask = 0x30;
619 static const uint32_t GCAttrShift = 4;
620 static const uint32_t LifetimeMask = 0x1C0;
621 static const uint32_t LifetimeShift = 6;
622 static const uint32_t AddressSpaceMask =
623 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
624 static const uint32_t AddressSpaceShift = 9;
625};
626
627class QualifiersAndAtomic {
628 Qualifiers Quals;
629 bool HasAtomic;
630
631public:
632 QualifiersAndAtomic() : HasAtomic(false) {}
633 QualifiersAndAtomic(Qualifiers Quals, bool HasAtomic)
634 : Quals(Quals), HasAtomic(HasAtomic) {}
635
636 operator Qualifiers() const { return Quals; }
637
638 bool hasVolatile() const { return Quals.hasVolatile(); }
639 bool hasConst() const { return Quals.hasConst(); }
640 bool hasRestrict() const { return Quals.hasRestrict(); }
641 bool hasAtomic() const { return HasAtomic; }
642
643 void addVolatile() { Quals.addVolatile(); }
644 void addConst() { Quals.addConst(); }
645 void addRestrict() { Quals.addRestrict(); }
646 void addAtomic() { HasAtomic = true; }
647
648 void removeVolatile() { Quals.removeVolatile(); }
649 void removeConst() { Quals.removeConst(); }
650 void removeRestrict() { Quals.removeRestrict(); }
651 void removeAtomic() { HasAtomic = false; }
652
653 QualifiersAndAtomic withVolatile() {
654 return {Quals.withVolatile(), HasAtomic};
655 }
656 QualifiersAndAtomic withConst() { return {Quals.withConst(), HasAtomic}; }
657 QualifiersAndAtomic withRestrict() {
658 return {Quals.withRestrict(), HasAtomic};
659 }
660 QualifiersAndAtomic withAtomic() { return {Quals, true}; }
661
662 QualifiersAndAtomic &operator+=(Qualifiers RHS) {
663 Quals += RHS;
664 return *this;
665 }
666};
667
668/// A std::pair-like structure for storing a qualified type split
669/// into its local qualifiers and its locally-unqualified type.
670struct SplitQualType {
671 /// The locally-unqualified type.
672 const Type *Ty = nullptr;
673
674 /// The local qualifiers.
675 Qualifiers Quals;
676
677 SplitQualType() = default;
678 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
679
680 SplitQualType getSingleStepDesugaredType() const; // end of this file
681
682 // Make std::tie work.
683 std::pair<const Type *,Qualifiers> asPair() const {
684 return std::pair<const Type *, Qualifiers>(Ty, Quals);
685 }
686
687 friend bool operator==(SplitQualType a, SplitQualType b) {
688 return a.Ty == b.Ty && a.Quals == b.Quals;
689 }
690 friend bool operator!=(SplitQualType a, SplitQualType b) {
691 return a.Ty != b.Ty || a.Quals != b.Quals;
692 }
693};
694
695/// The kind of type we are substituting Objective-C type arguments into.
696///
697/// The kind of substitution affects the replacement of type parameters when
698/// no concrete type information is provided, e.g., when dealing with an
699/// unspecialized type.
700enum class ObjCSubstitutionContext {
701 /// An ordinary type.
702 Ordinary,
703
704 /// The result type of a method or function.
705 Result,
706
707 /// The parameter type of a method or function.
708 Parameter,
709
710 /// The type of a property.
711 Property,
712
713 /// The superclass of a type.
714 Superclass,
715};
716
717/// A (possibly-)qualified type.
718///
719/// For efficiency, we don't store CV-qualified types as nodes on their
720/// own: instead each reference to a type stores the qualifiers. This
721/// greatly reduces the number of nodes we need to allocate for types (for
722/// example we only need one for 'int', 'const int', 'volatile int',
723/// 'const volatile int', etc).
724///
725/// As an added efficiency bonus, instead of making this a pair, we
726/// just store the two bits we care about in the low bits of the
727/// pointer. To handle the packing/unpacking, we make QualType be a
728/// simple wrapper class that acts like a smart pointer. A third bit
729/// indicates whether there are extended qualifiers present, in which
730/// case the pointer points to a special structure.
731class QualType {
732 friend class QualifierCollector;
733
734 // Thankfully, these are efficiently composable.
735 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
736 Qualifiers::FastWidth> Value;
737
738 const ExtQuals *getExtQualsUnsafe() const {
739 return Value.getPointer().get<const ExtQuals*>();
740 }
741
742 const Type *getTypePtrUnsafe() const {
743 return Value.getPointer().get<const Type*>();
744 }
745
746 const ExtQualsTypeCommonBase *getCommonPtr() const {
747 assert(!isNull() && "Cannot retrieve a NULL type pointer")(static_cast <bool> (!isNull() && "Cannot retrieve a NULL type pointer"
) ? void (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "clang/include/clang/AST/Type.h", 747, __extension__ __PRETTY_FUNCTION__
))
;
748 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
749 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
750 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
751 }
752
753public:
754 QualType() = default;
755 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
756 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
757
758 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
759 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
760
761 /// Retrieves a pointer to the underlying (unqualified) type.
762 ///
763 /// This function requires that the type not be NULL. If the type might be
764 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
765 const Type *getTypePtr() const;
766
767 const Type *getTypePtrOrNull() const;
768
769 /// Retrieves a pointer to the name of the base type.
770 const IdentifierInfo *getBaseTypeIdentifier() const;
771
772 /// Divides a QualType into its unqualified type and a set of local
773 /// qualifiers.
774 SplitQualType split() const;
775
776 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
777
778 static QualType getFromOpaquePtr(const void *Ptr) {
779 QualType T;
780 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
781 return T;
782 }
783
784 const Type &operator*() const {
785 return *getTypePtr();
786 }
787
788 const Type *operator->() const {
789 return getTypePtr();
790 }
791
792 bool isCanonical() const;
793 bool isCanonicalAsParam() const;
794
795 /// Return true if this QualType doesn't point to a type yet.
796 bool isNull() const {
797 return Value.getPointer().isNull();
798 }
799
800 // Determines if a type can form `T&`.
801 bool isReferenceable() const;
802
803 /// Determine whether this particular QualType instance has the
804 /// "const" qualifier set, without looking through typedefs that may have
805 /// added "const" at a different level.
806 bool isLocalConstQualified() const {
807 return (getLocalFastQualifiers() & Qualifiers::Const);
808 }
809
810 /// Determine whether this type is const-qualified.
811 bool isConstQualified() const;
812
813 /// Determine whether this particular QualType instance has the
814 /// "restrict" qualifier set, without looking through typedefs that may have
815 /// added "restrict" at a different level.
816 bool isLocalRestrictQualified() const {
817 return (getLocalFastQualifiers() & Qualifiers::Restrict);
818 }
819
820 /// Determine whether this type is restrict-qualified.
821 bool isRestrictQualified() const;
822
823 /// Determine whether this particular QualType instance has the
824 /// "volatile" qualifier set, without looking through typedefs that may have
825 /// added "volatile" at a different level.
826 bool isLocalVolatileQualified() const {
827 return (getLocalFastQualifiers() & Qualifiers::Volatile);
828 }
829
830 /// Determine whether this type is volatile-qualified.
831 bool isVolatileQualified() const;
832
833 /// Determine whether this particular QualType instance has any
834 /// qualifiers, without looking through any typedefs that might add
835 /// qualifiers at a different level.
836 bool hasLocalQualifiers() const {
837 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
838 }
839
840 /// Determine whether this type has any qualifiers.
841 bool hasQualifiers() const;
842
843 /// Determine whether this particular QualType instance has any
844 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
845 /// instance.
846 bool hasLocalNonFastQualifiers() const {
847 return Value.getPointer().is<const ExtQuals*>();
848 }
849
850 /// Retrieve the set of qualifiers local to this particular QualType
851 /// instance, not including any qualifiers acquired through typedefs or
852 /// other sugar.
853 Qualifiers getLocalQualifiers() const;
854
855 /// Retrieve the set of qualifiers applied to this type.
856 Qualifiers getQualifiers() const;
857
858 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
859 /// local to this particular QualType instance, not including any qualifiers
860 /// acquired through typedefs or other sugar.
861 unsigned getLocalCVRQualifiers() const {
862 return getLocalFastQualifiers();
863 }
864
865 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
866 /// applied to this type.
867 unsigned getCVRQualifiers() const;
868
869 bool isConstant(const ASTContext& Ctx) const {
870 return QualType::isConstant(*this, Ctx);
871 }
872
873 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
874 bool isPODType(const ASTContext &Context) const;
875
876 /// Return true if this is a POD type according to the rules of the C++98
877 /// standard, regardless of the current compilation's language.
878 bool isCXX98PODType(const ASTContext &Context) const;
879
880 /// Return true if this is a POD type according to the more relaxed rules
881 /// of the C++11 standard, regardless of the current compilation's language.
882 /// (C++0x [basic.types]p9). Note that, unlike
883 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
884 bool isCXX11PODType(const ASTContext &Context) const;
885
886 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
887 bool isTrivialType(const ASTContext &Context) const;
888
889 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
890 bool isTriviallyCopyableType(const ASTContext &Context) const;
891
892 /// Return true if this is a trivially relocatable type.
893 bool isTriviallyRelocatableType(const ASTContext &Context) const;
894
895 /// Returns true if it is a class and it might be dynamic.
896 bool mayBeDynamicClass() const;
897
898 /// Returns true if it is not a class or if the class might not be dynamic.
899 bool mayBeNotDynamicClass() const;
900
901 // Don't promise in the API that anything besides 'const' can be
902 // easily added.
903
904 /// Add the `const` type qualifier to this QualType.
905 void addConst() {
906 addFastQualifiers(Qualifiers::Const);
907 }
908 QualType withConst() const {
909 return withFastQualifiers(Qualifiers::Const);
910 }
911
912 /// Add the `volatile` type qualifier to this QualType.
913 void addVolatile() {
914 addFastQualifiers(Qualifiers::Volatile);
915 }
916 QualType withVolatile() const {
917 return withFastQualifiers(Qualifiers::Volatile);
918 }
919
920 /// Add the `restrict` qualifier to this QualType.
921 void addRestrict() {
922 addFastQualifiers(Qualifiers::Restrict);
923 }
924 QualType withRestrict() const {
925 return withFastQualifiers(Qualifiers::Restrict);
926 }
927
928 QualType withCVRQualifiers(unsigned CVR) const {
929 return withFastQualifiers(CVR);
930 }
931
932 void addFastQualifiers(unsigned TQs) {
933 assert(!(TQs & ~Qualifiers::FastMask)(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 934, __extension__ __PRETTY_FUNCTION__
))
934 && "non-fast qualifier bits set in mask!")(static_cast <bool> (!(TQs & ~Qualifiers::FastMask)
&& "non-fast qualifier bits set in mask!") ? void (0
) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "clang/include/clang/AST/Type.h", 934, __extension__ __PRETTY_FUNCTION__
))
;
935 Value.setInt(Value.getInt() | TQs);
936 }
937
938 void removeLocalConst();
939 void removeLocalVolatile();
940 void removeLocalRestrict();
941 void removeLocalCVRQualifiers(unsigned Mask);
942
943 void removeLocalFastQualifiers() { Value.setInt(0); }
944 void removeLocalFastQualifiers(unsigned Mask) {
945 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")(static_cast <bool> (!(Mask & ~Qualifiers::FastMask
) && "mask has non-fast qualifiers") ? void (0) : __assert_fail
("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "clang/include/clang/AST/Type.h", 945, __extension__ __PRETTY_FUNCTION__
))
;
946 Value.setInt(Value.getInt() & ~Mask);
947 }
948
949 // Creates a type with the given qualifiers in addition to any
950 // qualifiers already on this type.
951 QualType withFastQualifiers(unsigned TQs) const {
952 QualType T = *this;
953 T.addFastQualifiers(TQs);
954 return T;
955 }
956
957 // Creates a type with exactly the given fast qualifiers, removing
958 // any existing fast qualifiers.
959 QualType withExactLocalFastQualifiers(unsigned TQs) const {
960 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
961 }
962
963 // Removes fast qualifiers, but leaves any extended qualifiers in place.
964 QualType withoutLocalFastQualifiers() const {
965 QualType T = *this;
966 T.removeLocalFastQualifiers();
967 return T;
968 }
969
970 QualType getCanonicalType() const;
971
972 /// Return this type with all of the instance-specific qualifiers
973 /// removed, but without removing any qualifiers that may have been applied
974 /// through typedefs.
975 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
976
977 /// Retrieve the unqualified variant of the given type,
978 /// removing as little sugar as possible.
979 ///
980 /// This routine looks through various kinds of sugar to find the
981 /// least-desugared type that is unqualified. For example, given:
982 ///
983 /// \code
984 /// typedef int Integer;
985 /// typedef const Integer CInteger;
986 /// typedef CInteger DifferenceType;
987 /// \endcode
988 ///
989 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
990 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
991 ///
992 /// The resulting type might still be qualified if it's sugar for an array
993 /// type. To strip qualifiers even from within a sugared array type, use
994 /// ASTContext::getUnqualifiedArrayType.
995 ///
996 /// Note: In C, the _Atomic qualifier is special (see C2x 6.2.5p29 for
997 /// details), and it is not stripped by this function. Use
998 /// getAtomicUnqualifiedType() to strip qualifiers including _Atomic.
999 inline QualType getUnqualifiedType() const;
1000
1001 /// Retrieve the unqualified variant of the given type, removing as little
1002 /// sugar as possible.
1003 ///
1004 /// Like getUnqualifiedType(), but also returns the set of
1005 /// qualifiers that were built up.
1006 ///
1007 /// The resulting type might still be qualified if it's sugar for an array
1008 /// type. To strip qualifiers even from within a sugared array type, use
1009 /// ASTContext::getUnqualifiedArrayType.
1010 inline SplitQualType getSplitUnqualifiedType() const;
1011
1012 /// Determine whether this type is more qualified than the other
1013 /// given type, requiring exact equality for non-CVR qualifiers.
1014 bool isMoreQualifiedThan(QualType Other) const;
1015
1016 /// Determine whether this type is at least as qualified as the other
1017 /// given type, requiring exact equality for non-CVR qualifiers.
1018 bool isAtLeastAsQualifiedAs(QualType Other) const;
1019
1020 QualType getNonReferenceType() const;
1021
1022 /// Determine the type of a (typically non-lvalue) expression with the
1023 /// specified result type.
1024 ///
1025 /// This routine should be used for expressions for which the return type is
1026 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
1027 /// an lvalue. It removes a top-level reference (since there are no
1028 /// expressions of reference type) and deletes top-level cvr-qualifiers
1029 /// from non-class types (in C++) or all types (in C).
1030 QualType getNonLValueExprType(const ASTContext &Context) const;
1031
1032 /// Remove an outer pack expansion type (if any) from this type. Used as part
1033 /// of converting the type of a declaration to the type of an expression that
1034 /// references that expression. It's meaningless for an expression to have a
1035 /// pack expansion type.
1036 QualType getNonPackExpansionType() const;
1037
1038 /// Return the specified type with any "sugar" removed from
1039 /// the type. This takes off typedefs, typeof's etc. If the outer level of
1040 /// the type is already concrete, it returns it unmodified. This is similar
1041 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
1042 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
1043 /// concrete.
1044 ///
1045 /// Qualifiers are left in place.
1046 QualType getDesugaredType(const ASTContext &Context) const {
1047 return getDesugaredType(*this, Context);
1048 }
1049
1050 SplitQualType getSplitDesugaredType() const {
1051 return getSplitDesugaredType(*this);
1052 }
1053
1054 /// Return the specified type with one level of "sugar" removed from
1055 /// the type.
1056 ///
1057 /// This routine takes off the first typedef, typeof, etc. If the outer level
1058 /// of the type is already concrete, it returns it unmodified.
1059 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
1060 return getSingleStepDesugaredTypeImpl(*this, Context);
1061 }
1062
1063 /// Returns the specified type after dropping any
1064 /// outer-level parentheses.
1065 QualType IgnoreParens() const {
1066 if (isa<ParenType>(*this))
1067 return QualType::IgnoreParens(*this);
1068 return *this;
1069 }
1070
1071 /// Indicate whether the specified types and qualifiers are identical.
1072 friend bool operator==(const QualType &LHS, const QualType &RHS) {
1073 return LHS.Value == RHS.Value;
1074 }
1075 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
1076 return LHS.Value != RHS.Value;
1077 }
1078 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1079 return LHS.Value < RHS.Value;
1080 }
1081
1082 static std::string getAsString(SplitQualType split,
1083 const PrintingPolicy &Policy) {
1084 return getAsString(split.Ty, split.Quals, Policy);
1085 }
1086 static std::string getAsString(const Type *ty, Qualifiers qs,
1087 const PrintingPolicy &Policy);
1088
1089 std::string getAsString() const;
1090 std::string getAsString(const PrintingPolicy &Policy) const;
1091
1092 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1093 const Twine &PlaceHolder = Twine(),
1094 unsigned Indentation = 0) const;
1095
1096 static void print(SplitQualType split, raw_ostream &OS,
1097 const PrintingPolicy &policy, const Twine &PlaceHolder,
1098 unsigned Indentation = 0) {
1099 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1100 }
1101
1102 static void print(const Type *ty, Qualifiers qs,
1103 raw_ostream &OS, const PrintingPolicy &policy,
1104 const Twine &PlaceHolder,
1105 unsigned Indentation = 0);
1106
1107 void getAsStringInternal(std::string &Str,
1108 const PrintingPolicy &Policy) const;
1109
1110 static void getAsStringInternal(SplitQualType split, std::string &out,
1111 const PrintingPolicy &policy) {
1112 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1113 }
1114
1115 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1116 std::string &out,
1117 const PrintingPolicy &policy);
1118
1119 class StreamedQualTypeHelper {
1120 const QualType &T;
1121 const PrintingPolicy &Policy;
1122 const Twine &PlaceHolder;
1123 unsigned Indentation;
1124
1125 public:
1126 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1127 const Twine &PlaceHolder, unsigned Indentation)
1128 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1129 Indentation(Indentation) {}
1130
1131 friend raw_ostream &operator<<(raw_ostream &OS,
1132 const StreamedQualTypeHelper &SQT) {
1133 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1134 return OS;
1135 }
1136 };
1137
1138 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1139 const Twine &PlaceHolder = Twine(),
1140 unsigned Indentation = 0) const {
1141 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1142 }
1143
1144 void dump(const char *s) const;
1145 void dump() const;
1146 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1147
1148 void Profile(llvm::FoldingSetNodeID &ID) const {
1149 ID.AddPointer(getAsOpaquePtr());
1150 }
1151
1152 /// Check if this type has any address space qualifier.
1153 inline bool hasAddressSpace() const;
1154
1155 /// Return the address space of this type.
1156 inline LangAS getAddressSpace() const;
1157
1158 /// Returns true if address space qualifiers overlap with T address space
1159 /// qualifiers.
1160 /// OpenCL C defines conversion rules for pointers to different address spaces
1161 /// and notion of overlapping address spaces.
1162 /// CL1.1 or CL1.2:
1163 /// address spaces overlap iff they are they same.
1164 /// OpenCL C v2.0 s6.5.5 adds:
1165 /// __generic overlaps with any address space except for __constant.
1166 bool isAddressSpaceOverlapping(QualType T) const {
1167 Qualifiers Q = getQualifiers();
1168 Qualifiers TQ = T.getQualifiers();
1169 // Address spaces overlap if at least one of them is a superset of another
1170 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1171 }
1172
1173 /// Returns gc attribute of this type.
1174 inline Qualifiers::GC getObjCGCAttr() const;
1175
1176 /// true when Type is objc's weak.
1177 bool isObjCGCWeak() const {
1178 return getObjCGCAttr() == Qualifiers::Weak;
1179 }
1180
1181 /// true when Type is objc's strong.
1182 bool isObjCGCStrong() const {
1183 return getObjCGCAttr() == Qualifiers::Strong;
1184 }
1185
1186 /// Returns lifetime attribute of this type.
1187 Qualifiers::ObjCLifetime getObjCLifetime() const {
1188 return getQualifiers().getObjCLifetime();
1189 }
1190
1191 bool hasNonTrivialObjCLifetime() const {
1192 return getQualifiers().hasNonTrivialObjCLifetime();
1193 }
1194
1195 bool hasStrongOrWeakObjCLifetime() const {
1196 return getQualifiers().hasStrongOrWeakObjCLifetime();
1197 }
1198
1199 // true when Type is objc's weak and weak is enabled but ARC isn't.
1200 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1201
1202 enum PrimitiveDefaultInitializeKind {
1203 /// The type does not fall into any of the following categories. Note that
1204 /// this case is zero-valued so that values of this enum can be used as a
1205 /// boolean condition for non-triviality.
1206 PDIK_Trivial,
1207
1208 /// The type is an Objective-C retainable pointer type that is qualified
1209 /// with the ARC __strong qualifier.
1210 PDIK_ARCStrong,
1211
1212 /// The type is an Objective-C retainable pointer type that is qualified
1213 /// with the ARC __weak qualifier.
1214 PDIK_ARCWeak,
1215
1216 /// The type is a struct containing a field whose type is not PCK_Trivial.
1217 PDIK_Struct
1218 };
1219
1220 /// Functions to query basic properties of non-trivial C struct types.
1221
1222 /// Check if this is a non-trivial type that would cause a C struct
1223 /// transitively containing this type to be non-trivial to default initialize
1224 /// and return the kind.
1225 PrimitiveDefaultInitializeKind
1226 isNonTrivialToPrimitiveDefaultInitialize() const;
1227
1228 enum PrimitiveCopyKind {
1229 /// The type does not fall into any of the following categories. Note that
1230 /// this case is zero-valued so that values of this enum can be used as a
1231 /// boolean condition for non-triviality.
1232 PCK_Trivial,
1233
1234 /// The type would be trivial except that it is volatile-qualified. Types
1235 /// that fall into one of the other non-trivial cases may additionally be
1236 /// volatile-qualified.
1237 PCK_VolatileTrivial,
1238
1239 /// The type is an Objective-C retainable pointer type that is qualified
1240 /// with the ARC __strong qualifier.
1241 PCK_ARCStrong,
1242
1243 /// The type is an Objective-C retainable pointer type that is qualified
1244 /// with the ARC __weak qualifier.
1245 PCK_ARCWeak,
1246
1247 /// The type is a struct containing a field whose type is neither
1248 /// PCK_Trivial nor PCK_VolatileTrivial.
1249 /// Note that a C++ struct type does not necessarily match this; C++ copying
1250 /// semantics are too complex to express here, in part because they depend
1251 /// on the exact constructor or assignment operator that is chosen by
1252 /// overload resolution to do the copy.
1253 PCK_Struct
1254 };
1255
1256 /// Check if this is a non-trivial type that would cause a C struct
1257 /// transitively containing this type to be non-trivial to copy and return the
1258 /// kind.
1259 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1260
1261 /// Check if this is a non-trivial type that would cause a C struct
1262 /// transitively containing this type to be non-trivial to destructively
1263 /// move and return the kind. Destructive move in this context is a C++-style
1264 /// move in which the source object is placed in a valid but unspecified state
1265 /// after it is moved, as opposed to a truly destructive move in which the
1266 /// source object is placed in an uninitialized state.
1267 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1268
1269 enum DestructionKind {
1270 DK_none,
1271 DK_cxx_destructor,
1272 DK_objc_strong_lifetime,
1273 DK_objc_weak_lifetime,
1274 DK_nontrivial_c_struct
1275 };
1276
1277 /// Returns a nonzero value if objects of this type require
1278 /// non-trivial work to clean up after. Non-zero because it's
1279 /// conceivable that qualifiers (objc_gc(weak)?) could make
1280 /// something require destruction.
1281 DestructionKind isDestructedType() const {
1282 return isDestructedTypeImpl(*this);
1283 }
1284
1285 /// Check if this is or contains a C union that is non-trivial to
1286 /// default-initialize, which is a union that has a member that is non-trivial
1287 /// to default-initialize. If this returns true,
1288 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1289 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1290
1291 /// Check if this is or contains a C union that is non-trivial to destruct,
1292 /// which is a union that has a member that is non-trivial to destruct. If
1293 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1294 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1295
1296 /// Check if this is or contains a C union that is non-trivial to copy, which
1297 /// is a union that has a member that is non-trivial to copy. If this returns
1298 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1299 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1300
1301 /// Determine whether expressions of the given type are forbidden
1302 /// from being lvalues in C.
1303 ///
1304 /// The expression types that are forbidden to be lvalues are:
1305 /// - 'void', but not qualified void
1306 /// - function types
1307 ///
1308 /// The exact rule here is C99 6.3.2.1:
1309 /// An lvalue is an expression with an object type or an incomplete
1310 /// type other than void.
1311 bool isCForbiddenLValueType() const;
1312
1313 /// Substitute type arguments for the Objective-C type parameters used in the
1314 /// subject type.
1315 ///
1316 /// \param ctx ASTContext in which the type exists.
1317 ///
1318 /// \param typeArgs The type arguments that will be substituted for the
1319 /// Objective-C type parameters in the subject type, which are generally
1320 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1321 /// parameters will be replaced with their bounds or id/Class, as appropriate
1322 /// for the context.
1323 ///
1324 /// \param context The context in which the subject type was written.
1325 ///
1326 /// \returns the resulting type.
1327 QualType substObjCTypeArgs(ASTContext &ctx,
1328 ArrayRef<QualType> typeArgs,
1329 ObjCSubstitutionContext context) const;
1330
1331 /// Substitute type arguments from an object type for the Objective-C type
1332 /// parameters used in the subject type.
1333 ///
1334 /// This operation combines the computation of type arguments for
1335 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1336 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1337 /// callers that need to perform a single substitution in isolation.
1338 ///
1339 /// \param objectType The type of the object whose member type we're
1340 /// substituting into. For example, this might be the receiver of a message
1341 /// or the base of a property access.
1342 ///
1343 /// \param dc The declaration context from which the subject type was
1344 /// retrieved, which indicates (for example) which type parameters should
1345 /// be substituted.
1346 ///
1347 /// \param context The context in which the subject type was written.
1348 ///
1349 /// \returns the subject type after replacing all of the Objective-C type
1350 /// parameters with their corresponding arguments.
1351 QualType substObjCMemberType(QualType objectType,
1352 const DeclContext *dc,
1353 ObjCSubstitutionContext context) const;
1354
1355 /// Strip Objective-C "__kindof" types from the given type.
1356 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1357
1358 /// Remove all qualifiers including _Atomic.
1359 QualType getAtomicUnqualifiedType() const;
1360
1361private:
1362 // These methods are implemented in a separate translation unit;
1363 // "static"-ize them to avoid creating temporary QualTypes in the
1364 // caller.
1365 static bool isConstant(QualType T, const ASTContext& Ctx);
1366 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1367 static SplitQualType getSplitDesugaredType(QualType T);
1368 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1369 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1370 const ASTContext &C);
1371 static QualType IgnoreParens(QualType T);
1372 static DestructionKind isDestructedTypeImpl(QualType type);
1373
1374 /// Check if \param RD is or contains a non-trivial C union.
1375 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1376 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1377 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1378};
1379
1380raw_ostream &operator<<(raw_ostream &OS, QualType QT);
1381
1382} // namespace clang
1383
1384namespace llvm {
1385
1386/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1387/// to a specific Type class.
1388template<> struct simplify_type< ::clang::QualType> {
1389 using SimpleType = const ::clang::Type *;
1390
1391 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1392 return Val.getTypePtr();
1393 }
1394};
1395
1396// Teach SmallPtrSet that QualType is "basically a pointer".
1397template<>
1398struct PointerLikeTypeTraits<clang::QualType> {
1399 static inline void *getAsVoidPointer(clang::QualType P) {
1400 return P.getAsOpaquePtr();
1401 }
1402
1403 static inline clang::QualType getFromVoidPointer(void *P) {
1404 return clang::QualType::getFromOpaquePtr(P);
1405 }
1406
1407 // Various qualifiers go in low bits.
1408 static constexpr int NumLowBitsAvailable = 0;
1409};
1410
1411} // namespace llvm
1412
1413namespace clang {
1414
1415/// Base class that is common to both the \c ExtQuals and \c Type
1416/// classes, which allows \c QualType to access the common fields between the
1417/// two.
1418class ExtQualsTypeCommonBase {
1419 friend class ExtQuals;
1420 friend class QualType;
1421 friend class Type;
1422
1423 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1424 /// a self-referential pointer (for \c Type).
1425 ///
1426 /// This pointer allows an efficient mapping from a QualType to its
1427 /// underlying type pointer.
1428 const Type *const BaseType;
1429
1430 /// The canonical type of this type. A QualType.
1431 QualType CanonicalType;
1432
1433 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1434 : BaseType(baseType), CanonicalType(canon) {}
1435};
1436
1437/// We can encode up to four bits in the low bits of a
1438/// type pointer, but there are many more type qualifiers that we want
1439/// to be able to apply to an arbitrary type. Therefore we have this
1440/// struct, intended to be heap-allocated and used by QualType to
1441/// store qualifiers.
1442///
1443/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1444/// in three low bits on the QualType pointer; a fourth bit records whether
1445/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1446/// Objective-C GC attributes) are much more rare.
1447class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1448 // NOTE: changing the fast qualifiers should be straightforward as
1449 // long as you don't make 'const' non-fast.
1450 // 1. Qualifiers:
1451 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1452 // Fast qualifiers must occupy the low-order bits.
1453 // b) Update Qualifiers::FastWidth and FastMask.
1454 // 2. QualType:
1455 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1456 // b) Update remove{Volatile,Restrict}, defined near the end of
1457 // this header.
1458 // 3. ASTContext:
1459 // a) Update get{Volatile,Restrict}Type.
1460
1461 /// The immutable set of qualifiers applied by this node. Always contains
1462 /// extended qualifiers.
1463 Qualifiers Quals;
1464
1465 ExtQuals *this_() { return this; }
1466
1467public:
1468 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1469 : ExtQualsTypeCommonBase(baseType,
1470 canon.isNull() ? QualType(this_(), 0) : canon),
1471 Quals(quals) {
1472 assert(Quals.hasNonFastQualifiers()(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1473, __extension__ __PRETTY_FUNCTION__
))
1473 && "ExtQuals created with no fast qualifiers")(static_cast <bool> (Quals.hasNonFastQualifiers() &&
"ExtQuals created with no fast qualifiers") ? void (0) : __assert_fail
("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1473, __extension__ __PRETTY_FUNCTION__
))
;
1474 assert(!Quals.hasFastQualifiers()(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1475, __extension__ __PRETTY_FUNCTION__
))
1475 && "ExtQuals created with fast qualifiers")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"ExtQuals created with fast qualifiers") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "clang/include/clang/AST/Type.h", 1475, __extension__ __PRETTY_FUNCTION__
))
;
1476 }
1477
1478 Qualifiers getQualifiers() const { return Quals; }
1479
1480 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1481 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1482
1483 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1484 Qualifiers::ObjCLifetime getObjCLifetime() const {
1485 return Quals.getObjCLifetime();
1486 }
1487
1488 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1489 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1490
1491 const Type *getBaseType() const { return BaseType; }
1492
1493public:
1494 void Profile(llvm::FoldingSetNodeID &ID) const {
1495 Profile(ID, getBaseType(), Quals);
1496 }
1497
1498 static void Profile(llvm::FoldingSetNodeID &ID,
1499 const Type *BaseType,
1500 Qualifiers Quals) {
1501 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")(static_cast <bool> (!Quals.hasFastQualifiers() &&
"fast qualifiers in ExtQuals hash!") ? void (0) : __assert_fail
("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "clang/include/clang/AST/Type.h", 1501, __extension__ __PRETTY_FUNCTION__
))
;
1502 ID.AddPointer(BaseType);
1503 Quals.Profile(ID);
1504 }
1505};
1506
1507/// The kind of C++11 ref-qualifier associated with a function type.
1508/// This determines whether a member function's "this" object can be an
1509/// lvalue, rvalue, or neither.
1510enum RefQualifierKind {
1511 /// No ref-qualifier was provided.
1512 RQ_None = 0,
1513
1514 /// An lvalue ref-qualifier was provided (\c &).
1515 RQ_LValue,
1516
1517 /// An rvalue ref-qualifier was provided (\c &&).
1518 RQ_RValue
1519};
1520
1521/// Which keyword(s) were used to create an AutoType.
1522enum class AutoTypeKeyword {
1523 /// auto
1524 Auto,
1525
1526 /// decltype(auto)
1527 DecltypeAuto,
1528
1529 /// __auto_type (GNU extension)
1530 GNUAutoType
1531};
1532
1533/// The base class of the type hierarchy.
1534///
1535/// A central concept with types is that each type always has a canonical
1536/// type. A canonical type is the type with any typedef names stripped out
1537/// of it or the types it references. For example, consider:
1538///
1539/// typedef int foo;
1540/// typedef foo* bar;
1541/// 'int *' 'foo *' 'bar'
1542///
1543/// There will be a Type object created for 'int'. Since int is canonical, its
1544/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1545/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1546/// there is a PointerType that represents 'int*', which, like 'int', is
1547/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1548/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1549/// is also 'int*'.
1550///
1551/// Non-canonical types are useful for emitting diagnostics, without losing
1552/// information about typedefs being used. Canonical types are useful for type
1553/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1554/// about whether something has a particular form (e.g. is a function type),
1555/// because they implicitly, recursively, strip all typedefs out of a type.
1556///
1557/// Types, once created, are immutable.
1558///
1559class alignas(8) Type : public ExtQualsTypeCommonBase {
1560public:
1561 enum TypeClass {
1562#define TYPE(Class, Base) Class,
1563#define LAST_TYPE(Class) TypeLast = Class
1564#define ABSTRACT_TYPE(Class, Base)
1565#include "clang/AST/TypeNodes.inc"
1566 };
1567
1568private:
1569 /// Bitfields required by the Type class.
1570 class TypeBitfields {
1571 friend class Type;
1572 template <class T> friend class TypePropertyCache;
1573
1574 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1575 unsigned TC : 8;
1576
1577 /// Store information on the type dependency.
1578 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1579
1580 /// True if the cache (i.e. the bitfields here starting with
1581 /// 'Cache') is valid.
1582 mutable unsigned CacheValid : 1;
1583
1584 /// Linkage of this type.
1585 mutable unsigned CachedLinkage : 3;
1586
1587 /// Whether this type involves and local or unnamed types.
1588 mutable unsigned CachedLocalOrUnnamed : 1;
1589
1590 /// Whether this type comes from an AST file.
1591 mutable unsigned FromAST : 1;
1592
1593 bool isCacheValid() const {
1594 return CacheValid;
1595 }
1596
1597 Linkage getLinkage() const {
1598 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1598, __extension__ __PRETTY_FUNCTION__
))
;
1599 return static_cast<Linkage>(CachedLinkage);
1600 }
1601
1602 bool hasLocalOrUnnamedType() const {
1603 assert(isCacheValid() && "getting linkage from invalid cache")(static_cast <bool> (isCacheValid() && "getting linkage from invalid cache"
) ? void (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "clang/include/clang/AST/Type.h", 1603, __extension__ __PRETTY_FUNCTION__
))
;
1604 return CachedLocalOrUnnamed;
1605 }
1606 };
1607 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1608
1609protected:
1610 // These classes allow subclasses to somewhat cleanly pack bitfields
1611 // into Type.
1612
1613 class ArrayTypeBitfields {
1614 friend class ArrayType;
1615
1616 unsigned : NumTypeBits;
1617
1618 /// CVR qualifiers from declarations like
1619 /// 'int X[static restrict 4]'. For function parameters only.
1620 unsigned IndexTypeQuals : 3;
1621
1622 /// Storage class qualifiers from declarations like
1623 /// 'int X[static restrict 4]'. For function parameters only.
1624 /// Actually an ArrayType::ArraySizeModifier.
1625 unsigned SizeModifier : 3;
1626 };
1627
1628 class ConstantArrayTypeBitfields {
1629 friend class ConstantArrayType;
1630
1631 unsigned : NumTypeBits + 3 + 3;
1632
1633 /// Whether we have a stored size expression.
1634 unsigned HasStoredSizeExpr : 1;
1635 };
1636
1637 class BuiltinTypeBitfields {
1638 friend class BuiltinType;
1639
1640 unsigned : NumTypeBits;
1641
1642 /// The kind (BuiltinType::Kind) of builtin type this is.
1643 unsigned Kind : 8;
1644 };
1645
1646 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1647 /// Only common bits are stored here. Additional uncommon bits are stored
1648 /// in a trailing object after FunctionProtoType.
1649 class FunctionTypeBitfields {
1650 friend class FunctionProtoType;
1651 friend class FunctionType;
1652
1653 unsigned : NumTypeBits;
1654
1655 /// Extra information which affects how the function is called, like
1656 /// regparm and the calling convention.
1657 unsigned ExtInfo : 13;
1658
1659 /// The ref-qualifier associated with a \c FunctionProtoType.
1660 ///
1661 /// This is a value of type \c RefQualifierKind.
1662 unsigned RefQualifier : 2;
1663
1664 /// Used only by FunctionProtoType, put here to pack with the
1665 /// other bitfields.
1666 /// The qualifiers are part of FunctionProtoType because...
1667 ///
1668 /// C++ 8.3.5p4: The return type, the parameter type list and the
1669 /// cv-qualifier-seq, [...], are part of the function type.
1670 unsigned FastTypeQuals : Qualifiers::FastWidth;
1671 /// Whether this function has extended Qualifiers.
1672 unsigned HasExtQuals : 1;
1673
1674 /// The number of parameters this function has, not counting '...'.
1675 /// According to [implimits] 8 bits should be enough here but this is
1676 /// somewhat easy to exceed with metaprogramming and so we would like to
1677 /// keep NumParams as wide as reasonably possible.
1678 unsigned NumParams : 16;
1679
1680 /// The type of exception specification this function has.
1681 unsigned ExceptionSpecType : 4;
1682
1683 /// Whether this function has extended parameter information.
1684 unsigned HasExtParameterInfos : 1;
1685
1686 /// Whether this function has extra bitfields for the prototype.
1687 unsigned HasExtraBitfields : 1;
1688
1689 /// Whether the function is variadic.
1690 unsigned Variadic : 1;
1691
1692 /// Whether this function has a trailing return type.
1693 unsigned HasTrailingReturn : 1;
1694 };
1695
1696 class ObjCObjectTypeBitfields {
1697 friend class ObjCObjectType;
1698
1699 unsigned : NumTypeBits;
1700
1701 /// The number of type arguments stored directly on this object type.
1702 unsigned NumTypeArgs : 7;
1703
1704 /// The number of protocols stored directly on this object type.
1705 unsigned NumProtocols : 6;
1706
1707 /// Whether this is a "kindof" type.
1708 unsigned IsKindOf : 1;
1709 };
1710
1711 class ReferenceTypeBitfields {
1712 friend class ReferenceType;
1713
1714 unsigned : NumTypeBits;
1715
1716 /// True if the type was originally spelled with an lvalue sigil.
1717 /// This is never true of rvalue references but can also be false
1718 /// on lvalue references because of C++0x [dcl.typedef]p9,
1719 /// as follows:
1720 ///
1721 /// typedef int &ref; // lvalue, spelled lvalue
1722 /// typedef int &&rvref; // rvalue
1723 /// ref &a; // lvalue, inner ref, spelled lvalue
1724 /// ref &&a; // lvalue, inner ref
1725 /// rvref &a; // lvalue, inner ref, spelled lvalue
1726 /// rvref &&a; // rvalue, inner ref
1727 unsigned SpelledAsLValue : 1;
1728
1729 /// True if the inner type is a reference type. This only happens
1730 /// in non-canonical forms.
1731 unsigned InnerRef : 1;
1732 };
1733
1734 class TypeWithKeywordBitfields {
1735 friend class TypeWithKeyword;
1736
1737 unsigned : NumTypeBits;
1738
1739 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1740 unsigned Keyword : 8;
1741 };
1742
1743 enum { NumTypeWithKeywordBits = 8 };
1744
1745 class ElaboratedTypeBitfields {
1746 friend class ElaboratedType;
1747
1748 unsigned : NumTypeBits;
1749 unsigned : NumTypeWithKeywordBits;
1750
1751 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1752 unsigned HasOwnedTagDecl : 1;
1753 };
1754
1755 class VectorTypeBitfields {
1756 friend class VectorType;
1757 friend class DependentVectorType;
1758
1759 unsigned : NumTypeBits;
1760
1761 /// The kind of vector, either a generic vector type or some
1762 /// target-specific vector type such as for AltiVec or Neon.
1763 unsigned VecKind : 3;
1764 /// The number of elements in the vector.
1765 uint32_t NumElements;
1766 };
1767
1768 class AttributedTypeBitfields {
1769 friend class AttributedType;
1770
1771 unsigned : NumTypeBits;
1772
1773 /// An AttributedType::Kind
1774 unsigned AttrKind : 32 - NumTypeBits;
1775 };
1776
1777 class AutoTypeBitfields {
1778 friend class AutoType;
1779
1780 unsigned : NumTypeBits;
1781
1782 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1783 /// or '__auto_type'? AutoTypeKeyword value.
1784 unsigned Keyword : 2;
1785
1786 /// The number of template arguments in the type-constraints, which is
1787 /// expected to be able to hold at least 1024 according to [implimits].
1788 /// However as this limit is somewhat easy to hit with template
1789 /// metaprogramming we'd prefer to keep it as large as possible.
1790 /// At the moment it has been left as a non-bitfield since this type
1791 /// safely fits in 64 bits as an unsigned, so there is no reason to
1792 /// introduce the performance impact of a bitfield.
1793 unsigned NumArgs;
1794 };
1795
1796 class SubstTemplateTypeParmPackTypeBitfields {
1797 friend class SubstTemplateTypeParmPackType;
1798
1799 unsigned : NumTypeBits;
1800
1801 /// The number of template arguments in \c Arguments, which is
1802 /// expected to be able to hold at least 1024 according to [implimits].
1803 /// However as this limit is somewhat easy to hit with template
1804 /// metaprogramming we'd prefer to keep it as large as possible.
1805 /// At the moment it has been left as a non-bitfield since this type
1806 /// safely fits in 64 bits as an unsigned, so there is no reason to
1807 /// introduce the performance impact of a bitfield.
1808 unsigned NumArgs;
1809 };
1810
1811 class TemplateSpecializationTypeBitfields {
1812 friend class TemplateSpecializationType;
1813
1814 unsigned : NumTypeBits;
1815
1816 /// Whether this template specialization type is a substituted type alias.
1817 unsigned TypeAlias : 1;
1818
1819 /// The number of template arguments named in this class template
1820 /// specialization, which is expected to be able to hold at least 1024
1821 /// according to [implimits]. However, as this limit is somewhat easy to
1822 /// hit with template metaprogramming we'd prefer to keep it as large
1823 /// as possible. At the moment it has been left as a non-bitfield since
1824 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1825 /// to introduce the performance impact of a bitfield.
1826 unsigned NumArgs;
1827 };
1828
1829 class DependentTemplateSpecializationTypeBitfields {
1830 friend class DependentTemplateSpecializationType;
1831
1832 unsigned : NumTypeBits;
1833 unsigned : NumTypeWithKeywordBits;
1834
1835 /// The number of template arguments named in this class template
1836 /// specialization, which is expected to be able to hold at least 1024
1837 /// according to [implimits]. However, as this limit is somewhat easy to
1838 /// hit with template metaprogramming we'd prefer to keep it as large
1839 /// as possible. At the moment it has been left as a non-bitfield since
1840 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1841 /// to introduce the performance impact of a bitfield.
1842 unsigned NumArgs;
1843 };
1844
1845 class PackExpansionTypeBitfields {
1846 friend class PackExpansionType;
1847
1848 unsigned : NumTypeBits;
1849
1850 /// The number of expansions that this pack expansion will
1851 /// generate when substituted (+1), which is expected to be able to
1852 /// hold at least 1024 according to [implimits]. However, as this limit
1853 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1854 /// keep it as large as possible. At the moment it has been left as a
1855 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1856 /// there is no reason to introduce the performance impact of a bitfield.
1857 ///
1858 /// This field will only have a non-zero value when some of the parameter
1859 /// packs that occur within the pattern have been substituted but others
1860 /// have not.
1861 unsigned NumExpansions;
1862 };
1863
1864 union {
1865 TypeBitfields TypeBits;
1866 ArrayTypeBitfields ArrayTypeBits;
1867 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1868 AttributedTypeBitfields AttributedTypeBits;
1869 AutoTypeBitfields AutoTypeBits;
1870 BuiltinTypeBitfields BuiltinTypeBits;
1871 FunctionTypeBitfields FunctionTypeBits;
1872 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1873 ReferenceTypeBitfields ReferenceTypeBits;
1874 TypeWithKeywordBitfields TypeWithKeywordBits;
1875 ElaboratedTypeBitfields ElaboratedTypeBits;
1876 VectorTypeBitfields VectorTypeBits;
1877 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1878 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1879 DependentTemplateSpecializationTypeBitfields
1880 DependentTemplateSpecializationTypeBits;
1881 PackExpansionTypeBitfields PackExpansionTypeBits;
1882 };
1883
1884private:
1885 template <class T> friend class TypePropertyCache;
1886
1887 /// Set whether this type comes from an AST file.
1888 void setFromAST(bool V = true) const {
1889 TypeBits.FromAST = V;
1890 }
1891
1892protected:
1893 friend class ASTContext;
1894
1895 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1896 : ExtQualsTypeCommonBase(this,
1897 canon.isNull() ? QualType(this_(), 0) : canon) {
1898 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1899 "changing bitfields changed sizeof(Type)!");
1900 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1901 "Insufficient alignment!");
1902 TypeBits.TC = tc;
1903 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1904 TypeBits.CacheValid = false;
1905 TypeBits.CachedLocalOrUnnamed = false;
1906 TypeBits.CachedLinkage = NoLinkage;
1907 TypeBits.FromAST = false;
1908 }
1909
1910 // silence VC++ warning C4355: 'this' : used in base member initializer list
1911 Type *this_() { return this; }
1912
1913 void setDependence(TypeDependence D) {
1914 TypeBits.Dependence = static_cast<unsigned>(D);
1915 }
1916
1917 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1918
1919public:
1920 friend class ASTReader;
1921 friend class ASTWriter;
1922 template <class T> friend class serialization::AbstractTypeReader;
1923 template <class T> friend class serialization::AbstractTypeWriter;
1924
1925 Type(const Type &) = delete;
1926 Type(Type &&) = delete;
1927 Type &operator=(const Type &) = delete;
1928 Type &operator=(Type &&) = delete;
1929
1930 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1931
1932 /// Whether this type comes from an AST file.
1933 bool isFromAST() const { return TypeBits.FromAST; }
1934
1935 /// Whether this type is or contains an unexpanded parameter
1936 /// pack, used to support C++0x variadic templates.
1937 ///
1938 /// A type that contains a parameter pack shall be expanded by the
1939 /// ellipsis operator at some point. For example, the typedef in the
1940 /// following example contains an unexpanded parameter pack 'T':
1941 ///
1942 /// \code
1943 /// template<typename ...T>
1944 /// struct X {
1945 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1946 /// };
1947 /// \endcode
1948 ///
1949 /// Note that this routine does not specify which
1950 bool containsUnexpandedParameterPack() const {
1951 return getDependence() & TypeDependence::UnexpandedPack;
1952 }
1953
1954 /// Determines if this type would be canonical if it had no further
1955 /// qualification.
1956 bool isCanonicalUnqualified() const {
1957 return CanonicalType == QualType(this, 0);
1958 }
1959
1960 /// Pull a single level of sugar off of this locally-unqualified type.
1961 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1962 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1963 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1964
1965 /// As an extension, we classify types as one of "sized" or "sizeless";
1966 /// every type is one or the other. Standard types are all sized;
1967 /// sizeless types are purely an extension.
1968 ///
1969 /// Sizeless types contain data with no specified size, alignment,
1970 /// or layout.
1971 bool isSizelessType() const;
1972 bool isSizelessBuiltinType() const;
1973
1974 /// Determines if this is a sizeless type supported by the
1975 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1976 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1977 bool isVLSTBuiltinType() const;
1978
1979 /// Returns the representative type for the element of an SVE builtin type.
1980 /// This is used to represent fixed-length SVE vectors created with the
1981 /// 'arm_sve_vector_bits' type attribute as VectorType.
1982 QualType getSveEltType(const ASTContext &Ctx) const;
1983
1984 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1985 /// object types, function types, and incomplete types.
1986
1987 /// Return true if this is an incomplete type.
1988 /// A type that can describe objects, but which lacks information needed to
1989 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1990 /// routine will need to determine if the size is actually required.
1991 ///
1992 /// Def If non-null, and the type refers to some kind of declaration
1993 /// that can be completed (such as a C struct, C++ class, or Objective-C
1994 /// class), will be set to the declaration.
1995 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1996
1997 /// Return true if this is an incomplete or object
1998 /// type, in other words, not a function type.
1999 bool isIncompleteOrObjectType() const {
2000 return !isFunctionType();
2001 }
2002
2003 /// Determine whether this type is an object type.
2004 bool isObjectType() const {
2005 // C++ [basic.types]p8:
2006 // An object type is a (possibly cv-qualified) type that is not a
2007 // function type, not a reference type, and not a void type.
2008 return !isReferenceType() && !isFunctionType() && !isVoidType();
2009 }
2010
2011 /// Return true if this is a literal type
2012 /// (C++11 [basic.types]p10)
2013 bool isLiteralType(const ASTContext &Ctx) const;
2014
2015 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
2016 bool isStructuralType() const;
2017
2018 /// Test if this type is a standard-layout type.
2019 /// (C++0x [basic.type]p9)
2020 bool isStandardLayoutType() const;
2021
2022 /// Helper methods to distinguish type categories. All type predicates
2023 /// operate on the canonical type, ignoring typedefs and qualifiers.
2024
2025 /// Returns true if the type is a builtin type.
2026 bool isBuiltinType() const;
2027
2028 /// Test for a particular builtin type.
2029 bool isSpecificBuiltinType(unsigned K) const;
2030
2031 /// Test for a type which does not represent an actual type-system type but
2032 /// is instead used as a placeholder for various convenient purposes within
2033 /// Clang. All such types are BuiltinTypes.
2034 bool isPlaceholderType() const;
2035 const BuiltinType *getAsPlaceholderType() const;
2036
2037 /// Test for a specific placeholder type.
2038 bool isSpecificPlaceholderType(unsigned K) const;
2039
2040 /// Test for a placeholder type other than Overload; see
2041 /// BuiltinType::isNonOverloadPlaceholderType.
2042 bool isNonOverloadPlaceholderType() const;
2043
2044 /// isIntegerType() does *not* include complex integers (a GCC extension).
2045 /// isComplexIntegerType() can be used to test for complex integers.
2046 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
2047 bool isEnumeralType() const;
2048
2049 /// Determine whether this type is a scoped enumeration type.
2050 bool isScopedEnumeralType() const;
2051 bool isBooleanType() const;
2052 bool isCharType() const;
2053 bool isWideCharType() const;
2054 bool isChar8Type() const;
2055 bool isChar16Type() const;
2056 bool isChar32Type() const;
2057 bool isAnyCharacterType() const;
2058 bool isIntegralType(const ASTContext &Ctx) const;
2059
2060 /// Determine whether this type is an integral or enumeration type.
2061 bool isIntegralOrEnumerationType() const;
2062
2063 /// Determine whether this type is an integral or unscoped enumeration type.
2064 bool isIntegralOrUnscopedEnumerationType() const;
2065 bool isUnscopedEnumerationType() const;
2066
2067 /// Floating point categories.
2068 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
2069 /// isComplexType() does *not* include complex integers (a GCC extension).
2070 /// isComplexIntegerType() can be used to test for complex integers.
2071 bool isComplexType() const; // C99 6.2.5p11 (complex)
2072 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
2073 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
2074 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
2075 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
2076 bool isBFloat16Type() const;
2077 bool isFloat128Type() const;
2078 bool isIbm128Type() const;
2079 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
2080 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
2081 bool isVoidType() const; // C99 6.2.5p19
2082 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
2083 bool isAggregateType() const;
2084 bool isFundamentalType() const;
2085 bool isCompoundType() const;
2086
2087 // Type Predicates: Check to see if this type is structurally the specified
2088 // type, ignoring typedefs and qualifiers.
2089 bool isFunctionType() const;
2090 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2091 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2092 bool isPointerType() const;
2093 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2094 bool isBlockPointerType() const;
2095 bool isVoidPointerType() const;
2096 bool isReferenceType() const;
2097 bool isLValueReferenceType() const;
2098 bool isRValueReferenceType() const;
2099 bool isObjectPointerType() const;
2100 bool isFunctionPointerType() const;
2101 bool isFunctionReferenceType() const;
2102 bool isMemberPointerType() const;
2103 bool isMemberFunctionPointerType() const;
2104 bool isMemberDataPointerType() const;
2105 bool isArrayType() const;
2106 bool isConstantArrayType() const;
2107 bool isIncompleteArrayType() const;
2108 bool isVariableArrayType() const;
2109 bool isDependentSizedArrayType() const;
2110 bool isRecordType() const;
2111 bool isClassType() const;
2112 bool isStructureType() const;
2113 bool isObjCBoxableRecordType() const;
2114 bool isInterfaceType() const;
2115 bool isStructureOrClassType() const;
2116 bool isUnionType() const;
2117 bool isComplexIntegerType() const; // GCC _Complex integer type.
2118 bool isVectorType() const; // GCC vector type.
2119 bool isExtVectorType() const; // Extended vector type.
2120 bool isExtVectorBoolType() const; // Extended vector type with bool element.
2121 bool isMatrixType() const; // Matrix type.
2122 bool isConstantMatrixType() const; // Constant matrix type.
2123 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2124 bool isObjCObjectPointerType() const; // pointer to ObjC object
2125 bool isObjCRetainableType() const; // ObjC object or block pointer
2126 bool isObjCLifetimeType() const; // (array of)* retainable type
2127 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2128 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2129 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2130 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2131 // for the common case.
2132 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2133 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2134 bool isObjCQualifiedIdType() const; // id<foo>
2135 bool isObjCQualifiedClassType() const; // Class<foo>
2136 bool isObjCObjectOrInterfaceType() const;
2137 bool isObjCIdType() const; // id
2138 bool isDecltypeType() const;
2139 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2140 /// qualifier?
2141 ///
2142 /// This approximates the answer to the following question: if this
2143 /// translation unit were compiled in ARC, would this type be qualified
2144 /// with __unsafe_unretained?
2145 bool isObjCInertUnsafeUnretainedType() const {
2146 return hasAttr(attr::ObjCInertUnsafeUnretained);
2147 }
2148
2149 /// Whether the type is Objective-C 'id' or a __kindof type of an
2150 /// object type, e.g., __kindof NSView * or __kindof id
2151 /// <NSCopying>.
2152 ///
2153 /// \param bound Will be set to the bound on non-id subtype types,
2154 /// which will be (possibly specialized) Objective-C class type, or
2155 /// null for 'id.
2156 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2157 const ObjCObjectType *&bound) const;
2158
2159 bool isObjCClassType() const; // Class
2160
2161 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2162 /// Class type, e.g., __kindof Class <NSCopying>.
2163 ///
2164 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2165 /// here because Objective-C's type system cannot express "a class
2166 /// object for a subclass of NSFoo".
2167 bool isObjCClassOrClassKindOfType() const;
2168
2169 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2170 bool isObjCSelType() const; // Class
2171 bool isObjCBuiltinType() const; // 'id' or 'Class'
2172 bool isObjCARCBridgableType() const;
2173 bool isCARCBridgableType() const;
2174 bool isTemplateTypeParmType() const; // C++ template type parameter
2175 bool isNullPtrType() const; // C++11 std::nullptr_t
2176 bool isNothrowT() const; // C++ std::nothrow_t
2177 bool isAlignValT() const; // C++17 std::align_val_t
2178 bool isStdByteType() const; // C++17 std::byte
2179 bool isAtomicType() const; // C11 _Atomic()
2180 bool isUndeducedAutoType() const; // C++11 auto or
2181 // C++14 decltype(auto)
2182 bool isTypedefNameType() const; // typedef or alias template
2183
2184#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2185 bool is##Id##Type() const;
2186#include "clang/Basic/OpenCLImageTypes.def"
2187
2188 bool isImageType() const; // Any OpenCL image type
2189
2190 bool isSamplerT() const; // OpenCL sampler_t
2191 bool isEventT() const; // OpenCL event_t
2192 bool isClkEventT() const; // OpenCL clk_event_t
2193 bool isQueueT() const; // OpenCL queue_t
2194 bool isReserveIDT() const; // OpenCL reserve_id_t
2195
2196#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2197 bool is##Id##Type() const;
2198#include "clang/Basic/OpenCLExtensionTypes.def"
2199 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2200 bool isOCLIntelSubgroupAVCType() const;
2201 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2202
2203 bool isPipeType() const; // OpenCL pipe type
2204 bool isBitIntType() const; // Bit-precise integer type
2205 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2206
2207 /// Determines if this type, which must satisfy
2208 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2209 /// than implicitly __strong.
2210 bool isObjCARCImplicitlyUnretainedType() const;
2211
2212 /// Check if the type is the CUDA device builtin surface type.
2213 bool isCUDADeviceBuiltinSurfaceType() const;
2214 /// Check if the type is the CUDA device builtin texture type.
2215 bool isCUDADeviceBuiltinTextureType() const;
2216
2217 /// Return the implicit lifetime for this type, which must not be dependent.
2218 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2219
2220 enum ScalarTypeKind {
2221 STK_CPointer,
2222 STK_BlockPointer,
2223 STK_ObjCObjectPointer,
2224 STK_MemberPointer,
2225 STK_Bool,
2226 STK_Integral,
2227 STK_Floating,
2228 STK_IntegralComplex,
2229 STK_FloatingComplex,
2230 STK_FixedPoint
2231 };
2232
2233 /// Given that this is a scalar type, classify it.
2234 ScalarTypeKind getScalarTypeKind() const;
2235
2236 TypeDependence getDependence() const {
2237 return static_cast<TypeDependence>(TypeBits.Dependence);
2238 }
2239
2240 /// Whether this type is an error type.
2241 bool containsErrors() const {
2242 return getDependence() & TypeDependence::Error;
2243 }
2244
2245 /// Whether this type is a dependent type, meaning that its definition
2246 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2247 bool isDependentType() const {
2248 return getDependence() & TypeDependence::Dependent;
2249 }
2250
2251 /// Determine whether this type is an instantiation-dependent type,
2252 /// meaning that the type involves a template parameter (even if the
2253 /// definition does not actually depend on the type substituted for that
2254 /// template parameter).
2255 bool isInstantiationDependentType() const {
2256 return getDependence() & TypeDependence::Instantiation;
2257 }
2258
2259 /// Determine whether this type is an undeduced type, meaning that
2260 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2261 /// deduced.
2262 bool isUndeducedType() const;
2263
2264 /// Whether this type is a variably-modified type (C99 6.7.5).
2265 bool isVariablyModifiedType() const {
2266 return getDependence() & TypeDependence::VariablyModified;
2267 }
2268
2269 /// Whether this type involves a variable-length array type
2270 /// with a definite size.
2271 bool hasSizedVLAType() const;
2272
2273 /// Whether this type is or contains a local or unnamed type.
2274 bool hasUnnamedOrLocalType() const;
2275
2276 bool isOverloadableType() const;
2277
2278 /// Determine wither this type is a C++ elaborated-type-specifier.
2279 bool isElaboratedTypeSpecifier() const;
2280
2281 bool canDecayToPointerType() const;
2282
2283 /// Whether this type is represented natively as a pointer. This includes
2284 /// pointers, references, block pointers, and Objective-C interface,
2285 /// qualified id, and qualified interface types, as well as nullptr_t.
2286 bool hasPointerRepresentation() const;
2287
2288 /// Whether this type can represent an objective pointer type for the
2289 /// purpose of GC'ability
2290 bool hasObjCPointerRepresentation() const;
2291
2292 /// Determine whether this type has an integer representation
2293 /// of some sort, e.g., it is an integer type or a vector.
2294 bool hasIntegerRepresentation() const;
2295
2296 /// Determine whether this type has an signed integer representation
2297 /// of some sort, e.g., it is an signed integer type or a vector.
2298 bool hasSignedIntegerRepresentation() const;
2299
2300 /// Determine whether this type has an unsigned integer representation
2301 /// of some sort, e.g., it is an unsigned integer type or a vector.
2302 bool hasUnsignedIntegerRepresentation() const;
2303
2304 /// Determine whether this type has a floating-point representation
2305 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2306 bool hasFloatingRepresentation() const;
2307
2308 // Type Checking Functions: Check to see if this type is structurally the
2309 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2310 // the best type we can.
2311 const RecordType *getAsStructureType() const;
2312 /// NOTE: getAs*ArrayType are methods on ASTContext.
2313 const RecordType *getAsUnionType() const;
2314 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2315 const ObjCObjectType *getAsObjCInterfaceType() const;
2316
2317 // The following is a convenience method that returns an ObjCObjectPointerType
2318 // for object declared using an interface.
2319 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2320 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2321 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2322 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2323
2324 /// Retrieves the CXXRecordDecl that this type refers to, either
2325 /// because the type is a RecordType or because it is the injected-class-name
2326 /// type of a class template or class template partial specialization.
2327 CXXRecordDecl *getAsCXXRecordDecl() const;
2328
2329 /// Retrieves the RecordDecl this type refers to.
2330 RecordDecl *getAsRecordDecl() const;
2331
2332 /// Retrieves the TagDecl that this type refers to, either
2333 /// because the type is a TagType or because it is the injected-class-name
2334 /// type of a class template or class template partial specialization.
2335 TagDecl *getAsTagDecl() const;
2336
2337 /// If this is a pointer or reference to a RecordType, return the
2338 /// CXXRecordDecl that the type refers to.
2339 ///
2340 /// If this is not a pointer or reference, or the type being pointed to does
2341 /// not refer to a CXXRecordDecl, returns NULL.
2342 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2343
2344 /// Get the DeducedType whose type will be deduced for a variable with
2345 /// an initializer of this type. This looks through declarators like pointer
2346 /// types, but not through decltype or typedefs.
2347 DeducedType *getContainedDeducedType() const;
2348
2349 /// Get the AutoType whose type will be deduced for a variable with
2350 /// an initializer of this type. This looks through declarators like pointer
2351 /// types, but not through decltype or typedefs.
2352 AutoType *getContainedAutoType() const {
2353 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2354 }
2355
2356 /// Determine whether this type was written with a leading 'auto'
2357 /// corresponding to a trailing return type (possibly for a nested
2358 /// function type within a pointer to function type or similar).
2359 bool hasAutoForTrailingReturnType() const;
2360
2361 /// Member-template getAs<specific type>'. Look through sugar for
2362 /// an instance of \<specific type>. This scheme will eventually
2363 /// replace the specific getAsXXXX methods above.
2364 ///
2365 /// There are some specializations of this member template listed
2366 /// immediately following this class.
2367 template <typename T> const T *getAs() const;
2368
2369 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2370 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2371 /// This is used when you need to walk over sugar nodes that represent some
2372 /// kind of type adjustment from a type that was written as a \<specific type>
2373 /// to another type that is still canonically a \<specific type>.
2374 template <typename T> const T *getAsAdjusted() const;
2375
2376 /// A variant of getAs<> for array types which silently discards
2377 /// qualifiers from the outermost type.
2378 const ArrayType *getAsArrayTypeUnsafe() const;
2379
2380 /// Member-template castAs<specific type>. Look through sugar for
2381 /// the underlying instance of \<specific type>.
2382 ///
2383 /// This method has the same relationship to getAs<T> as cast<T> has
2384 /// to dyn_cast<T>; which is to say, the underlying type *must*
2385 /// have the intended type, and this method will never return null.
2386 template <typename T> const T *castAs() const;
2387
2388 /// A variant of castAs<> for array type which silently discards
2389 /// qualifiers from the outermost type.
2390 const ArrayType *castAsArrayTypeUnsafe() const;
2391
2392 /// Determine whether this type had the specified attribute applied to it
2393 /// (looking through top-level type sugar).
2394 bool hasAttr(attr::Kind AK) const;
2395
2396 /// Get the base element type of this type, potentially discarding type
2397 /// qualifiers. This should never be used when type qualifiers
2398 /// are meaningful.
2399 const Type *getBaseElementTypeUnsafe() const;
2400
2401 /// If this is an array type, return the element type of the array,
2402 /// potentially with type qualifiers missing.
2403 /// This should never be used when type qualifiers are meaningful.
2404 const Type *getArrayElementTypeNoTypeQual() const;
2405
2406 /// If this is a pointer type, return the pointee type.
2407 /// If this is an array type, return the array element type.
2408 /// This should never be used when type qualifiers are meaningful.
2409 const Type *getPointeeOrArrayElementType() const;
2410
2411 /// If this is a pointer, ObjC object pointer, or block
2412 /// pointer, this returns the respective pointee.
2413 QualType getPointeeType() const;
2414
2415 /// Return the specified type with any "sugar" removed from the type,
2416 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2417 const Type *getUnqualifiedDesugaredType() const;
2418
2419 /// More type predicates useful for type checking/promotion
2420 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2421
2422 /// Return true if this is an integer type that is
2423 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2424 /// or an enum decl which has a signed representation.
2425 bool isSignedIntegerType() const;
2426
2427 /// Return true if this is an integer type that is
2428 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2429 /// or an enum decl which has an unsigned representation.
2430 bool isUnsignedIntegerType() const;
2431
2432 /// Determines whether this is an integer type that is signed or an
2433 /// enumeration types whose underlying type is a signed integer type.
2434 bool isSignedIntegerOrEnumerationType() const;
2435
2436 /// Determines whether this is an integer type that is unsigned or an
2437 /// enumeration types whose underlying type is a unsigned integer type.
2438 bool isUnsignedIntegerOrEnumerationType() const;
2439
2440 /// Return true if this is a fixed point type according to
2441 /// ISO/IEC JTC1 SC22 WG14 N1169.
2442 bool isFixedPointType() const;
2443
2444 /// Return true if this is a fixed point or integer type.
2445 bool isFixedPointOrIntegerType() const;
2446
2447 /// Return true if this is a saturated fixed point type according to
2448 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2449 bool isSaturatedFixedPointType() const;
2450
2451 /// Return true if this is a saturated fixed point type according to
2452 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2453 bool isUnsaturatedFixedPointType() const;
2454
2455 /// Return true if this is a fixed point type that is signed according
2456 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2457 bool isSignedFixedPointType() const;
2458
2459 /// Return true if this is a fixed point type that is unsigned according
2460 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2461 bool isUnsignedFixedPointType() const;
2462
2463 /// Return true if this is not a variable sized type,
2464 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2465 /// incomplete types.
2466 bool isConstantSizeType() const;
2467
2468 /// Returns true if this type can be represented by some
2469 /// set of type specifiers.
2470 bool isSpecifierType() const;
2471
2472 /// Determine the linkage of this type.
2473 Linkage getLinkage() const;
2474
2475 /// Determine the visibility of this type.
2476 Visibility getVisibility() const {
2477 return getLinkageAndVisibility().getVisibility();
2478 }
2479
2480 /// Return true if the visibility was explicitly set is the code.
2481 bool isVisibilityExplicit() const {
2482 return getLinkageAndVisibility().isVisibilityExplicit();
2483 }
2484
2485 /// Determine the linkage and visibility of this type.
2486 LinkageInfo getLinkageAndVisibility() const;
2487
2488 /// True if the computed linkage is valid. Used for consistency
2489 /// checking. Should always return true.
2490 bool isLinkageValid() const;
2491
2492 /// Determine the nullability of the given type.
2493 ///
2494 /// Note that nullability is only captured as sugar within the type
2495 /// system, not as part of the canonical type, so nullability will
2496 /// be lost by canonicalization and desugaring.
2497 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2498
2499 /// Determine whether the given type can have a nullability
2500 /// specifier applied to it, i.e., if it is any kind of pointer type.
2501 ///
2502 /// \param ResultIfUnknown The value to return if we don't yet know whether
2503 /// this type can have nullability because it is dependent.
2504 bool canHaveNullability(bool ResultIfUnknown = true) const;
2505
2506 /// Retrieve the set of substitutions required when accessing a member
2507 /// of the Objective-C receiver type that is declared in the given context.
2508 ///
2509 /// \c *this is the type of the object we're operating on, e.g., the
2510 /// receiver for a message send or the base of a property access, and is
2511 /// expected to be of some object or object pointer type.
2512 ///
2513 /// \param dc The declaration context for which we are building up a
2514 /// substitution mapping, which should be an Objective-C class, extension,
2515 /// category, or method within.
2516 ///
2517 /// \returns an array of type arguments that can be substituted for
2518 /// the type parameters of the given declaration context in any type described
2519 /// within that context, or an empty optional to indicate that no
2520 /// substitution is required.
2521 Optional<ArrayRef<QualType>>
2522 getObjCSubstitutions(const DeclContext *dc) const;
2523
2524 /// Determines if this is an ObjC interface type that may accept type
2525 /// parameters.
2526 bool acceptsObjCTypeParams() const;
2527
2528 const char *getTypeClassName() const;
2529
2530 QualType getCanonicalTypeInternal() const {
2531 return CanonicalType;
2532 }
2533
2534 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2535 void dump() const;
2536 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2537};
2538
2539/// This will check for a TypedefType by removing any existing sugar
2540/// until it reaches a TypedefType or a non-sugared type.
2541template <> const TypedefType *Type::getAs() const;
2542
2543/// This will check for a TemplateSpecializationType by removing any
2544/// existing sugar until it reaches a TemplateSpecializationType or a
2545/// non-sugared type.
2546template <> const TemplateSpecializationType *Type::getAs() const;
2547
2548/// This will check for an AttributedType by removing any existing sugar
2549/// until it reaches an AttributedType or a non-sugared type.
2550template <> const AttributedType *Type::getAs() const;
2551
2552// We can do canonical leaf types faster, because we don't have to
2553// worry about preserving child type decoration.
2554#define TYPE(Class, Base)
2555#define LEAF_TYPE(Class) \
2556template <> inline const Class##Type *Type::getAs() const { \
2557 return dyn_cast<Class##Type>(CanonicalType); \
2558} \
2559template <> inline const Class##Type *Type::castAs() const { \
2560 return cast<Class##Type>(CanonicalType); \
2561}
2562#include "clang/AST/TypeNodes.inc"
2563
2564/// This class is used for builtin types like 'int'. Builtin
2565/// types are always canonical and have a literal name field.
2566class BuiltinType : public Type {
2567public:
2568 enum Kind {
2569// OpenCL image types
2570#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2571#include "clang/Basic/OpenCLImageTypes.def"
2572// OpenCL extension types
2573#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2574#include "clang/Basic/OpenCLExtensionTypes.def"
2575// SVE Types
2576#define SVE_TYPE(Name, Id, SingletonId) Id,
2577#include "clang/Basic/AArch64SVEACLETypes.def"
2578// PPC MMA Types
2579#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2580#include "clang/Basic/PPCTypes.def"
2581// RVV Types
2582#define RVV_TYPE(Name, Id, SingletonId) Id,
2583#include "clang/Basic/RISCVVTypes.def"
2584// All other builtin types
2585#define BUILTIN_TYPE(Id, SingletonId) Id,
2586#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2587#include "clang/AST/BuiltinTypes.def"
2588 };
2589
2590private:
2591 friend class ASTContext; // ASTContext creates these.
2592
2593 BuiltinType(Kind K)
2594 : Type(Builtin, QualType(),
2595 K == Dependent ? TypeDependence::DependentInstantiation
2596 : TypeDependence::None) {
2597 BuiltinTypeBits.Kind = K;
2598 }
2599
2600public:
2601 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2602 StringRef getName(const PrintingPolicy &Policy) const;
2603
2604 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2605 // The StringRef is null-terminated.
2606 StringRef str = getName(Policy);
2607 assert(!str.empty() && str.data()[str.size()] == '\0')(static_cast <bool> (!str.empty() && str.data()
[str.size()] == '\0') ? void (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "clang/include/clang/AST/Type.h", 2607, __extension__ __PRETTY_FUNCTION__
))
;
2608 return str.data();
2609 }
2610
2611 bool isSugared() const { return false; }
2612 QualType desugar() const { return QualType(this, 0); }
2613
2614 bool isInteger() const {
2615 return getKind() >= Bool && getKind() <= Int128;
2616 }
2617
2618 bool isSignedInteger() const {
2619 return getKind() >= Char_S && getKind() <= Int128;
2620 }
2621
2622 bool isUnsignedInteger() const {
2623 return getKind() >= Bool && getKind() <= UInt128;
2624 }
2625
2626 bool isFloatingPoint() const {
2627 return getKind() >= Half && getKind() <= Ibm128;
2628 }
2629
2630 bool isSVEBool() const { return getKind() == Kind::SveBool; }
2631
2632 /// Determines whether the given kind corresponds to a placeholder type.
2633 static bool isPlaceholderTypeKind(Kind K) {
2634 return K >= Overload;
2635 }
2636
2637 /// Determines whether this type is a placeholder type, i.e. a type
2638 /// which cannot appear in arbitrary positions in a fully-formed
2639 /// expression.
2640 bool isPlaceholderType() const {
2641 return isPlaceholderTypeKind(getKind());
2642 }
2643
2644 /// Determines whether this type is a placeholder type other than
2645 /// Overload. Most placeholder types require only syntactic
2646 /// information about their context in order to be resolved (e.g.
2647 /// whether it is a call expression), which means they can (and
2648 /// should) be resolved in an earlier "phase" of analysis.
2649 /// Overload expressions sometimes pick up further information
2650 /// from their context, like whether the context expects a
2651 /// specific function-pointer type, and so frequently need
2652 /// special treatment.
2653 bool isNonOverloadPlaceholderType() const {
2654 return getKind() > Overload;
2655 }
2656
2657 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2658};
2659
2660/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2661/// types (_Complex float etc) as well as the GCC integer complex extensions.
2662class ComplexType : public Type, public llvm::FoldingSetNode {
2663 friend class ASTContext; // ASTContext creates these.
2664
2665 QualType ElementType;
2666
2667 ComplexType(QualType Element, QualType CanonicalPtr)
2668 : Type(Complex, CanonicalPtr, Element->getDependence()),
2669 ElementType(Element) {}
2670
2671public:
2672 QualType getElementType() const { return ElementType; }
2673
2674 bool isSugared() const { return false; }
2675 QualType desugar() const { return QualType(this, 0); }
2676
2677 void Profile(llvm::FoldingSetNodeID &ID) {
2678 Profile(ID, getElementType());
2679 }
2680
2681 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2682 ID.AddPointer(Element.getAsOpaquePtr());
2683 }
2684
2685 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2686};
2687
2688/// Sugar for parentheses used when specifying types.
2689class ParenType : public Type, public llvm::FoldingSetNode {
2690 friend class ASTContext; // ASTContext creates these.
2691
2692 QualType Inner;
2693
2694 ParenType(QualType InnerType, QualType CanonType)
2695 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2696
2697public:
2698 QualType getInnerType() const { return Inner; }
2699
2700 bool isSugared() const { return true; }
2701 QualType desugar() const { return getInnerType(); }
2702
2703 void Profile(llvm::FoldingSetNodeID &ID) {
2704 Profile(ID, getInnerType());
2705 }
2706
2707 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2708 Inner.Profile(ID);
2709 }
2710
2711 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2712};
2713
2714/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2715class PointerType : public Type, public llvm::FoldingSetNode {
2716 friend class ASTContext; // ASTContext creates these.
2717
2718 QualType PointeeType;
2719
2720 PointerType(QualType Pointee, QualType CanonicalPtr)
2721 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2722 PointeeType(Pointee) {}
2723
2724public:
2725 QualType getPointeeType() const { return PointeeType; }
2726
2727 bool isSugared() const { return false; }
2728 QualType desugar() const { return QualType(this, 0); }
2729
2730 void Profile(llvm::FoldingSetNodeID &ID) {
2731 Profile(ID, getPointeeType());
2732 }
2733
2734 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2735 ID.AddPointer(Pointee.getAsOpaquePtr());
2736 }
2737
2738 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2739};
2740
2741/// Represents a type which was implicitly adjusted by the semantic
2742/// engine for arbitrary reasons. For example, array and function types can
2743/// decay, and function types can have their calling conventions adjusted.
2744class AdjustedType : public Type, public llvm::FoldingSetNode {
2745 QualType OriginalTy;
2746 QualType AdjustedTy;
2747
2748protected:
2749 friend class ASTContext; // ASTContext creates these.
2750
2751 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2752 QualType CanonicalPtr)
2753 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2754 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2755
2756public:
2757 QualType getOriginalType() const { return OriginalTy; }
2758 QualType getAdjustedType() const { return AdjustedTy; }
2759
2760 bool isSugared() const { return true; }
2761 QualType desugar() const { return AdjustedTy; }
2762
2763 void Profile(llvm::FoldingSetNodeID &ID) {
2764 Profile(ID, OriginalTy, AdjustedTy);
2765 }
2766
2767 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2768 ID.AddPointer(Orig.getAsOpaquePtr());
2769 ID.AddPointer(New.getAsOpaquePtr());
2770 }
2771
2772 static bool classof(const Type *T) {
2773 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2774 }
2775};
2776
2777/// Represents a pointer type decayed from an array or function type.
2778class DecayedType : public AdjustedType {
2779 friend class ASTContext; // ASTContext creates these.
2780
2781 inline
2782 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2783
2784public:
2785 QualType getDecayedType() const { return getAdjustedType(); }
2786
2787 inline QualType getPointeeType() const;
2788
2789 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2790};
2791
2792/// Pointer to a block type.
2793/// This type is to represent types syntactically represented as
2794/// "void (^)(int)", etc. Pointee is required to always be a function type.
2795class BlockPointerType : public Type, public llvm::FoldingSetNode {
2796 friend class ASTContext; // ASTContext creates these.
2797
2798 // Block is some kind of pointer type
2799 QualType PointeeType;
2800
2801 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2802 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2803 PointeeType(Pointee) {}
2804
2805public:
2806 // Get the pointee type. Pointee is required to always be a function type.
2807 QualType getPointeeType() const { return PointeeType; }
2808
2809 bool isSugared() const { return false; }
2810 QualType desugar() const { return QualType(this, 0); }
2811
2812 void Profile(llvm::FoldingSetNodeID &ID) {
2813 Profile(ID, getPointeeType());
2814 }
2815
2816 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2817 ID.AddPointer(Pointee.getAsOpaquePtr());
2818 }
2819
2820 static bool classof(const Type *T) {
2821 return T->getTypeClass() == BlockPointer;
2822 }
2823};
2824
2825/// Base for LValueReferenceType and RValueReferenceType
2826class ReferenceType : public Type, public llvm::FoldingSetNode {
2827 QualType PointeeType;
2828
2829protected:
2830 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2831 bool SpelledAsLValue)
2832 : Type(tc, CanonicalRef, Referencee->getDependence()),
2833 PointeeType(Referencee) {
2834 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2835 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2836 }
2837
2838public:
2839 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2840 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2841
2842 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2843
2844 QualType getPointeeType() const {
2845 // FIXME: this might strip inner qualifiers; okay?
2846 const ReferenceType *T = this;
2847 while (T->isInnerRef())
2848 T = T->PointeeType->castAs<ReferenceType>();
2849 return T->PointeeType;
2850 }
2851
2852 void Profile(llvm::FoldingSetNodeID &ID) {
2853 Profile(ID, PointeeType, isSpelledAsLValue());
2854 }
2855
2856 static void Profile(llvm::FoldingSetNodeID &ID,
2857 QualType Referencee,
2858 bool SpelledAsLValue) {
2859 ID.AddPointer(Referencee.getAsOpaquePtr());
2860 ID.AddBoolean(SpelledAsLValue);
2861 }
2862
2863 static bool classof(const Type *T) {
2864 return T->getTypeClass() == LValueReference ||
2865 T->getTypeClass() == RValueReference;
2866 }
2867};
2868
2869/// An lvalue reference type, per C++11 [dcl.ref].
2870class LValueReferenceType : public ReferenceType {
2871 friend class ASTContext; // ASTContext creates these
2872
2873 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2874 bool SpelledAsLValue)
2875 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2876 SpelledAsLValue) {}
2877
2878public:
2879 bool isSugared() const { return false; }
2880 QualType desugar() const { return QualType(this, 0); }
2881
2882 static bool classof(const Type *T) {
2883 return T->getTypeClass() == LValueReference;
2884 }
2885};
2886
2887/// An rvalue reference type, per C++11 [dcl.ref].
2888class RValueReferenceType : public ReferenceType {
2889 friend class ASTContext; // ASTContext creates these
2890
2891 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2892 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2893
2894public:
2895 bool isSugared() const { return false; }
2896 QualType desugar() const { return QualType(this, 0); }
2897
2898 static bool classof(const Type *T) {
2899 return T->getTypeClass() == RValueReference;
2900 }
2901};
2902
2903/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2904///
2905/// This includes both pointers to data members and pointer to member functions.
2906class MemberPointerType : public Type, public llvm::FoldingSetNode {
2907 friend class ASTContext; // ASTContext creates these.
2908
2909 QualType PointeeType;
2910
2911 /// The class of which the pointee is a member. Must ultimately be a
2912 /// RecordType, but could be a typedef or a template parameter too.
2913 const Type *Class;
2914
2915 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2916 : Type(MemberPointer, CanonicalPtr,
2917 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2918 Pointee->getDependence()),
2919 PointeeType(Pointee), Class(Cls) {}
2920
2921public:
2922 QualType getPointeeType() const { return PointeeType; }
2923
2924 /// Returns true if the member type (i.e. the pointee type) is a
2925 /// function type rather than a data-member type.
2926 bool isMemberFunctionPointer() const {
2927 return PointeeType->isFunctionProtoType();
2928 }
2929
2930 /// Returns true if the member type (i.e. the pointee type) is a
2931 /// data type rather than a function type.
2932 bool isMemberDataPointer() const {
2933 return !PointeeType->isFunctionProtoType();
2934 }
2935
2936 const Type *getClass() const { return Class; }
2937 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2938
2939 bool isSugared() const { return false; }
2940 QualType desugar() const { return QualType(this, 0); }
2941
2942 void Profile(llvm::FoldingSetNodeID &ID) {
2943 Profile(ID, getPointeeType(), getClass());
2944 }
2945
2946 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2947 const Type *Class) {
2948 ID.AddPointer(Pointee.getAsOpaquePtr());
2949 ID.AddPointer(Class);
2950 }
2951
2952 static bool classof(const Type *T) {
2953 return T->getTypeClass() == MemberPointer;
2954 }
2955};
2956
2957/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2958class ArrayType : public Type, public llvm::FoldingSetNode {
2959public:
2960 /// Capture whether this is a normal array (e.g. int X[4])
2961 /// an array with a static size (e.g. int X[static 4]), or an array
2962 /// with a star size (e.g. int X[*]).
2963 /// 'static' is only allowed on function parameters.
2964 enum ArraySizeModifier {
2965 Normal, Static, Star
2966 };
2967
2968private:
2969 /// The element type of the array.
2970 QualType ElementType;
2971
2972protected:
2973 friend class ASTContext; // ASTContext creates these.
2974
2975 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2976 unsigned tq, const Expr *sz = nullptr);
2977
2978public:
2979 QualType getElementType() const { return ElementType; }
2980
2981 ArraySizeModifier getSizeModifier() const {
2982 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2983 }
2984
2985 Qualifiers getIndexTypeQualifiers() const {
2986 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2987 }
2988
2989 unsigned getIndexTypeCVRQualifiers() const {
2990 return ArrayTypeBits.IndexTypeQuals;
2991 }
2992
2993 static bool classof(const Type *T) {
2994 return T->getTypeClass() == ConstantArray ||
2995 T->getTypeClass() == VariableArray ||
2996 T->getTypeClass() == IncompleteArray ||
2997 T->getTypeClass() == DependentSizedArray;
2998 }
2999};
3000
3001/// Represents the canonical version of C arrays with a specified constant size.
3002/// For example, the canonical type for 'int A[4 + 4*100]' is a
3003/// ConstantArrayType where the element type is 'int' and the size is 404.
3004class ConstantArrayType final
3005 : public ArrayType,
3006 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
3007 friend class ASTContext; // ASTContext creates these.
3008 friend TrailingObjects;
3009
3010 llvm::APInt Size; // Allows us to unique the type.
3011
3012 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
3013 const Expr *sz, ArraySizeModifier sm, unsigned tq)
3014 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
3015 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
3016 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
3017 assert(!can.isNull() && "canonical constant array should not have size")(static_cast <bool> (!can.isNull() && "canonical constant array should not have size"
) ? void (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "clang/include/clang/AST/Type.h", 3017, __extension__ __PRETTY_FUNCTION__
))
;
3018 *getTrailingObjects<const Expr*>() = sz;
3019 }
3020 }
3021
3022 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
3023 return ConstantArrayTypeBits.HasStoredSizeExpr;
3024 }
3025
3026public:
3027 const llvm::APInt &getSize() const { return Size; }
3028 const Expr *getSizeExpr() const {
3029 return ConstantArrayTypeBits.HasStoredSizeExpr
3030 ? *getTrailingObjects<const Expr *>()
3031