Bug Summary

File:clang/lib/Analysis/CalledOnceCheck.cpp
Warning:line 986, column 26
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 -disable-llvm-verifier -discard-value-names -main-file-name CalledOnceCheck.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Analysis -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/Analysis -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp

1//===- CalledOnceCheck.cpp - Check 'called once' parameters ---------------===//
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#include "clang/Analysis/Analyses/CalledOnceCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclBase.h"
14#include "clang/AST/Expr.h"
15#include "clang/AST/ExprObjC.h"
16#include "clang/AST/OperationKinds.h"
17#include "clang/AST/ParentMap.h"
18#include "clang/AST/RecursiveASTVisitor.h"
19#include "clang/AST/Stmt.h"
20#include "clang/AST/StmtObjC.h"
21#include "clang/AST/StmtVisitor.h"
22#include "clang/AST/Type.h"
23#include "clang/Analysis/AnalysisDeclContext.h"
24#include "clang/Analysis/CFG.h"
25#include "clang/Analysis/FlowSensitive/DataflowWorklist.h"
26#include "clang/Basic/Builtins.h"
27#include "clang/Basic/IdentifierTable.h"
28#include "clang/Basic/LLVM.h"
29#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/BitmaskEnum.h"
31#include "llvm/ADT/Optional.h"
32#include "llvm/ADT/PointerIntPair.h"
33#include "llvm/ADT/STLExtras.h"
34#include "llvm/ADT/Sequence.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringRef.h"
37#include "llvm/Support/Casting.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/ErrorHandling.h"
40#include <memory>
41
42using namespace clang;
43
44namespace {
45static constexpr unsigned EXPECTED_MAX_NUMBER_OF_PARAMS = 2;
46template <class T>
47using ParamSizedVector = llvm::SmallVector<T, EXPECTED_MAX_NUMBER_OF_PARAMS>;
48static constexpr unsigned EXPECTED_NUMBER_OF_BASIC_BLOCKS = 8;
49template <class T>
50using CFGSizedVector = llvm::SmallVector<T, EXPECTED_NUMBER_OF_BASIC_BLOCKS>;
51constexpr llvm::StringLiteral CONVENTIONAL_NAMES[] = {
52 "completionHandler", "completion", "withCompletionHandler",
53 "withCompletion", "completionBlock", "withCompletionBlock",
54 "replyTo", "reply", "withReplyTo"};
55constexpr llvm::StringLiteral CONVENTIONAL_SUFFIXES[] = {
56 "WithCompletionHandler", "WithCompletion", "WithCompletionBlock",
57 "WithReplyTo", "WithReply"};
58constexpr llvm::StringLiteral CONVENTIONAL_CONDITIONS[] = {
59 "error", "cancel", "shouldCall", "done", "OK", "success"};
60
61struct KnownCalledOnceParameter {
62 llvm::StringLiteral FunctionName;
63 unsigned ParamIndex;
64};
65constexpr KnownCalledOnceParameter KNOWN_CALLED_ONCE_PARAMETERS[] = {
66 {llvm::StringLiteral{"dispatch_async"}, 1},
67 {llvm::StringLiteral{"dispatch_async_and_wait"}, 1},
68 {llvm::StringLiteral{"dispatch_after"}, 2},
69 {llvm::StringLiteral{"dispatch_sync"}, 1},
70 {llvm::StringLiteral{"dispatch_once"}, 1},
71 {llvm::StringLiteral{"dispatch_barrier_async"}, 1},
72 {llvm::StringLiteral{"dispatch_barrier_async_and_wait"}, 1},
73 {llvm::StringLiteral{"dispatch_barrier_sync"}, 1}};
74
75class ParameterStatus {
76public:
77 // Status kind is basically the main part of parameter's status.
78 // The kind represents our knowledge (so far) about a tracked parameter
79 // in the context of this analysis.
80 //
81 // Since we want to report on missing and extraneous calls, we need to
82 // track the fact whether paramater was called or not. This automatically
83 // decides two kinds: `NotCalled` and `Called`.
84 //
85 // One of the erroneous situations is the case when parameter is called only
86 // on some of the paths. We could've considered it `NotCalled`, but we want
87 // to report double call warnings even if these two calls are not guaranteed
88 // to happen in every execution. We also don't want to have it as `Called`
89 // because not calling tracked parameter on all of the paths is an error
90 // on its own. For these reasons, we need to have a separate kind,
91 // `MaybeCalled`, and change `Called` to `DefinitelyCalled` to avoid
92 // confusion.
93 //
94 // Two violations of calling parameter more than once and not calling it on
95 // every path are not, however, mutually exclusive. In situations where both
96 // violations take place, we prefer to report ONLY double call. It's always
97 // harder to pinpoint a bug that has arisen when a user neglects to take the
98 // right action (and therefore, no action is taken), than when a user takes
99 // the wrong action. And, in order to remember that we already reported
100 // a double call, we need another kind: `Reported`.
101 //
102 // Our analysis is intra-procedural and, while in the perfect world,
103 // developers only use tracked parameters to call them, in the real world,
104 // the picture might be different. Parameters can be stored in global
105 // variables or leaked into other functions that we know nothing about.
106 // We try to be lenient and trust users. Another kind `Escaped` reflects
107 // such situations. We don't know if it gets called there or not, but we
108 // should always think of `Escaped` as the best possible option.
109 //
110 // Some of the paths in the analyzed functions might end with a call
111 // to noreturn functions. Such paths are not required to have parameter
112 // calls and we want to track that. For the purposes of better diagnostics,
113 // we don't want to reuse `Escaped` and, thus, have another kind `NoReturn`.
114 //
115 // Additionally, we have `NotVisited` kind that tells us nothing about
116 // a tracked parameter, but is used for tracking analyzed (aka visited)
117 // basic blocks.
118 //
119 // If we consider `|` to be a JOIN operation of two kinds coming from
120 // two different paths, the following properties must hold:
121 //
122 // 1. for any Kind K: K | K == K
123 // Joining two identical kinds should result in the same kind.
124 //
125 // 2. for any Kind K: Reported | K == Reported
126 // Doesn't matter on which path it was reported, it still is.
127 //
128 // 3. for any Kind K: NoReturn | K == K
129 // We can totally ignore noreturn paths during merges.
130 //
131 // 4. DefinitelyCalled | NotCalled == MaybeCalled
132 // Called on one path, not called on another - that's simply
133 // a definition for MaybeCalled.
134 //
135 // 5. for any Kind K in [DefinitelyCalled, NotCalled, MaybeCalled]:
136 // Escaped | K == K
137 // Escaped mirrors other statuses after joins.
138 // Every situation, when we join any of the listed kinds K,
139 // is a violation. For this reason, in order to assume the
140 // best outcome for this escape, we consider it to be the
141 // same as the other path.
142 //
143 // 6. for any Kind K in [DefinitelyCalled, NotCalled]:
144 // MaybeCalled | K == MaybeCalled
145 // MaybeCalled should basically stay after almost every join.
146 enum Kind {
147 // No-return paths should be absolutely transparent for the analysis.
148 // 0x0 is the identity element for selected join operation (binary or).
149 NoReturn = 0x0, /* 0000 */
150 // Escaped marks situations when marked parameter escaped into
151 // another function (so we can assume that it was possibly called there).
152 Escaped = 0x1, /* 0001 */
153 // Parameter was definitely called once at this point.
154 DefinitelyCalled = 0x3, /* 0011 */
155 // Kinds less or equal to NON_ERROR_STATUS are not considered errors.
156 NON_ERROR_STATUS = DefinitelyCalled,
157 // Parameter was not yet called.
158 NotCalled = 0x5, /* 0101 */
159 // Parameter was not called at least on one path leading to this point,
160 // while there is also at least one path that it gets called.
161 MaybeCalled = 0x7, /* 0111 */
162 // Parameter was not yet analyzed.
163 NotVisited = 0x8, /* 1000 */
164 // We already reported a violation and stopped tracking calls for this
165 // parameter.
166 Reported = 0x15, /* 1111 */
167 LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ Reported)LLVM_BITMASK_LARGEST_ENUMERATOR = Reported
168 };
169
170 constexpr ParameterStatus() = default;
171 /* implicit */ ParameterStatus(Kind K) : StatusKind(K) {
172 assert(!seenAnyCalls(K) && "Can't initialize status without a call")((!seenAnyCalls(K) && "Can't initialize status without a call"
) ? static_cast<void> (0) : __assert_fail ("!seenAnyCalls(K) && \"Can't initialize status without a call\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 172, __PRETTY_FUNCTION__))
;
173 }
174 ParameterStatus(Kind K, const Expr *Call) : StatusKind(K), Call(Call) {
175 assert(seenAnyCalls(K) && "This kind is not supposed to have a call")((seenAnyCalls(K) && "This kind is not supposed to have a call"
) ? static_cast<void> (0) : __assert_fail ("seenAnyCalls(K) && \"This kind is not supposed to have a call\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 175, __PRETTY_FUNCTION__))
;
176 }
177
178 const Expr &getCall() const {
179 assert(seenAnyCalls(getKind()) && "ParameterStatus doesn't have a call")((seenAnyCalls(getKind()) && "ParameterStatus doesn't have a call"
) ? static_cast<void> (0) : __assert_fail ("seenAnyCalls(getKind()) && \"ParameterStatus doesn't have a call\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 179, __PRETTY_FUNCTION__))
;
180 return *Call;
181 }
182 static bool seenAnyCalls(Kind K) {
183 return (K & DefinitelyCalled) == DefinitelyCalled && K != Reported;
184 }
185 bool seenAnyCalls() const { return seenAnyCalls(getKind()); }
186
187 static bool isErrorStatus(Kind K) { return K > NON_ERROR_STATUS; }
188 bool isErrorStatus() const { return isErrorStatus(getKind()); }
189
190 Kind getKind() const { return StatusKind; }
191
192 void join(const ParameterStatus &Other) {
193 // If we have a pointer already, let's keep it.
194 // For the purposes of the analysis, it doesn't really matter
195 // which call we report.
196 //
197 // If we don't have a pointer, let's take whatever gets joined.
198 if (!Call) {
199 Call = Other.Call;
200 }
201 // Join kinds.
202 StatusKind |= Other.getKind();
203 }
204
205 bool operator==(const ParameterStatus &Other) const {
206 // We compare only kinds, pointers on their own is only additional
207 // information.
208 return getKind() == Other.getKind();
209 }
210
211private:
212 // It would've been a perfect place to use llvm::PointerIntPair, but
213 // unfortunately NumLowBitsAvailable for clang::Expr had been reduced to 2.
214 Kind StatusKind = NotVisited;
215 const Expr *Call = nullptr;
216};
217
218/// State aggregates statuses of all tracked parameters.
219class State {
220public:
221 State(unsigned Size, ParameterStatus::Kind K = ParameterStatus::NotVisited)
222 : ParamData(Size, K) {}
223
224 /// Return status of a parameter with the given index.
225 /// \{
226 ParameterStatus &getStatusFor(unsigned Index) { return ParamData[Index]; }
227 const ParameterStatus &getStatusFor(unsigned Index) const {
228 return ParamData[Index];
229 }
230 /// \}
231
232 /// Return true if parameter with the given index can be called.
233 bool seenAnyCalls(unsigned Index) const {
234 return getStatusFor(Index).seenAnyCalls();
235 }
236 /// Return a reference that we consider a call.
237 ///
238 /// Should only be used for parameters that can be called.
239 const Expr &getCallFor(unsigned Index) const {
240 return getStatusFor(Index).getCall();
241 }
242 /// Return status kind of parameter with the given index.
243 ParameterStatus::Kind getKindFor(unsigned Index) const {
244 return getStatusFor(Index).getKind();
245 }
246
247 bool isVisited() const {
248 return llvm::all_of(ParamData, [](const ParameterStatus &S) {
249 return S.getKind() != ParameterStatus::NotVisited;
250 });
251 }
252
253 // Join other state into the current state.
254 void join(const State &Other) {
255 assert(ParamData.size() == Other.ParamData.size() &&((ParamData.size() == Other.ParamData.size() && "Couldn't join statuses with different sizes"
) ? static_cast<void> (0) : __assert_fail ("ParamData.size() == Other.ParamData.size() && \"Couldn't join statuses with different sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 256, __PRETTY_FUNCTION__))
256 "Couldn't join statuses with different sizes")((ParamData.size() == Other.ParamData.size() && "Couldn't join statuses with different sizes"
) ? static_cast<void> (0) : __assert_fail ("ParamData.size() == Other.ParamData.size() && \"Couldn't join statuses with different sizes\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 256, __PRETTY_FUNCTION__))
;
257 for (auto Pair : llvm::zip(ParamData, Other.ParamData)) {
258 std::get<0>(Pair).join(std::get<1>(Pair));
259 }
260 }
261
262 using iterator = ParamSizedVector<ParameterStatus>::iterator;
263 using const_iterator = ParamSizedVector<ParameterStatus>::const_iterator;
264
265 iterator begin() { return ParamData.begin(); }
266 iterator end() { return ParamData.end(); }
267
268 const_iterator begin() const { return ParamData.begin(); }
269 const_iterator end() const { return ParamData.end(); }
270
271 bool operator==(const State &Other) const {
272 return ParamData == Other.ParamData;
273 }
274
275private:
276 ParamSizedVector<ParameterStatus> ParamData;
277};
278
279/// A simple class that finds DeclRefExpr in the given expression.
280///
281/// However, we don't want to find ANY nested DeclRefExpr skipping whatever
282/// expressions on our way. Only certain expressions considered "no-op"
283/// for our task are indeed skipped.
284class DeclRefFinder
285 : public ConstStmtVisitor<DeclRefFinder, const DeclRefExpr *> {
286public:
287 /// Find a DeclRefExpr in the given expression.
288 ///
289 /// In its most basic form (ShouldRetrieveFromComparisons == false),
290 /// this function can be simply reduced to the following question:
291 ///
292 /// - If expression E is used as a function argument, could we say
293 /// that DeclRefExpr nested in E is used as an argument?
294 ///
295 /// According to this rule, we can say that parens, casts and dereferencing
296 /// (dereferencing only applied to function pointers, but this is our case)
297 /// can be skipped.
298 ///
299 /// When we should look into comparisons the question changes to:
300 ///
301 /// - If expression E is used as a condition, could we say that
302 /// DeclRefExpr is being checked?
303 ///
304 /// And even though, these are two different questions, they have quite a lot
305 /// in common. Actually, we can say that whatever expression answers
306 /// positively the first question also fits the second question as well.
307 ///
308 /// In addition, we skip binary operators == and !=, and unary opeartor !.
309 static const DeclRefExpr *find(const Expr *E,
310 bool ShouldRetrieveFromComparisons = false) {
311 return DeclRefFinder(ShouldRetrieveFromComparisons).Visit(E);
312 }
313
314 const DeclRefExpr *VisitDeclRefExpr(const DeclRefExpr *DR) { return DR; }
315
316 const DeclRefExpr *VisitUnaryOperator(const UnaryOperator *UO) {
317 switch (UO->getOpcode()) {
318 case UO_LNot:
319 // We care about logical not only if we care about comparisons.
320 if (!ShouldRetrieveFromComparisons)
321 return nullptr;
322 LLVM_FALLTHROUGH[[gnu::fallthrough]];
323 // Function pointer/references can be dereferenced before a call.
324 // That doesn't make it, however, any different from a regular call.
325 // For this reason, dereference operation is a "no-op".
326 case UO_Deref:
327 return Visit(UO->getSubExpr());
328 default:
329 return nullptr;
330 }
331 }
332
333 const DeclRefExpr *VisitBinaryOperator(const BinaryOperator *BO) {
334 if (!ShouldRetrieveFromComparisons)
335 return nullptr;
336
337 switch (BO->getOpcode()) {
338 case BO_EQ:
339 case BO_NE: {
340 const DeclRefExpr *LHS = Visit(BO->getLHS());
341 return LHS ? LHS : Visit(BO->getRHS());
342 }
343 default:
344 return nullptr;
345 }
346 }
347
348 const DeclRefExpr *VisitOpaqueValueExpr(const OpaqueValueExpr *OVE) {
349 return Visit(OVE->getSourceExpr());
350 }
351
352 const DeclRefExpr *VisitCallExpr(const CallExpr *CE) {
353 if (!ShouldRetrieveFromComparisons)
354 return nullptr;
355
356 // We want to see through some of the boolean builtin functions
357 // that we are likely to see in conditions.
358 switch (CE->getBuiltinCallee()) {
359 case Builtin::BI__builtin_expect:
360 case Builtin::BI__builtin_expect_with_probability: {
361 assert(CE->getNumArgs() >= 2)((CE->getNumArgs() >= 2) ? static_cast<void> (0) :
__assert_fail ("CE->getNumArgs() >= 2", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 361, __PRETTY_FUNCTION__))
;
362
363 const DeclRefExpr *Candidate = Visit(CE->getArg(0));
364 return Candidate != nullptr ? Candidate : Visit(CE->getArg(1));
365 }
366
367 case Builtin::BI__builtin_unpredictable:
368 return Visit(CE->getArg(0));
369
370 default:
371 return nullptr;
372 }
373 }
374
375 const DeclRefExpr *VisitExpr(const Expr *E) {
376 // It is a fallback method that gets called whenever the actual type
377 // of the given expression is not covered.
378 //
379 // We first check if we have anything to skip. And then repeat the whole
380 // procedure for a nested expression instead.
381 const Expr *DeclutteredExpr = E->IgnoreParenCasts();
382 return E != DeclutteredExpr ? Visit(DeclutteredExpr) : nullptr;
383 }
384
385private:
386 DeclRefFinder(bool ShouldRetrieveFromComparisons)
387 : ShouldRetrieveFromComparisons(ShouldRetrieveFromComparisons) {}
388
389 bool ShouldRetrieveFromComparisons;
390};
391
392const DeclRefExpr *findDeclRefExpr(const Expr *In,
393 bool ShouldRetrieveFromComparisons = false) {
394 return DeclRefFinder::find(In, ShouldRetrieveFromComparisons);
395}
396
397const ParmVarDecl *
398findReferencedParmVarDecl(const Expr *In,
399 bool ShouldRetrieveFromComparisons = false) {
400 if (const DeclRefExpr *DR =
401 findDeclRefExpr(In, ShouldRetrieveFromComparisons)) {
402 return dyn_cast<ParmVarDecl>(DR->getDecl());
403 }
404
405 return nullptr;
406}
407
408/// Return conditions expression of a statement if it has one.
409const Expr *getCondition(const Stmt *S) {
410 if (!S) {
411 return nullptr;
412 }
413
414 if (const auto *If = dyn_cast<IfStmt>(S)) {
415 return If->getCond();
416 }
417 if (const auto *Ternary = dyn_cast<AbstractConditionalOperator>(S)) {
418 return Ternary->getCond();
419 }
420
421 return nullptr;
422}
423
424/// A small helper class that collects all named identifiers in the given
425/// expression. It traverses it recursively, so names from deeper levels
426/// of the AST will end up in the results.
427/// Results might have duplicate names, if this is a problem, convert to
428/// string sets afterwards.
429class NamesCollector : public RecursiveASTVisitor<NamesCollector> {
430public:
431 static constexpr unsigned EXPECTED_NUMBER_OF_NAMES = 5;
432 using NameCollection =
433 llvm::SmallVector<llvm::StringRef, EXPECTED_NUMBER_OF_NAMES>;
434
435 static NameCollection collect(const Expr *From) {
436 NamesCollector Impl;
437 Impl.TraverseStmt(const_cast<Expr *>(From));
438 return Impl.Result;
439 }
440
441 bool VisitDeclRefExpr(const DeclRefExpr *E) {
442 Result.push_back(E->getDecl()->getName());
443 return true;
444 }
445
446 bool VisitObjCPropertyRefExpr(const ObjCPropertyRefExpr *E) {
447 llvm::StringRef Name;
448
449 if (E->isImplicitProperty()) {
450 ObjCMethodDecl *PropertyMethodDecl = nullptr;
451 if (E->isMessagingGetter()) {
452 PropertyMethodDecl = E->getImplicitPropertyGetter();
453 } else {
454 PropertyMethodDecl = E->getImplicitPropertySetter();
455 }
456 assert(PropertyMethodDecl &&((PropertyMethodDecl && "Implicit property must have associated declaration"
) ? static_cast<void> (0) : __assert_fail ("PropertyMethodDecl && \"Implicit property must have associated declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 457, __PRETTY_FUNCTION__))
457 "Implicit property must have associated declaration")((PropertyMethodDecl && "Implicit property must have associated declaration"
) ? static_cast<void> (0) : __assert_fail ("PropertyMethodDecl && \"Implicit property must have associated declaration\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 457, __PRETTY_FUNCTION__))
;
458 Name = PropertyMethodDecl->getSelector().getNameForSlot(0);
459 } else {
460 assert(E->isExplicitProperty())((E->isExplicitProperty()) ? static_cast<void> (0) :
__assert_fail ("E->isExplicitProperty()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 460, __PRETTY_FUNCTION__))
;
461 Name = E->getExplicitProperty()->getName();
462 }
463
464 Result.push_back(Name);
465 return true;
466 }
467
468private:
469 NamesCollector() = default;
470 NameCollection Result;
471};
472
473/// Check whether the given expression mentions any of conventional names.
474bool mentionsAnyOfConventionalNames(const Expr *E) {
475 NamesCollector::NameCollection MentionedNames = NamesCollector::collect(E);
476
477 return llvm::any_of(MentionedNames, [](llvm::StringRef ConditionName) {
478 return llvm::any_of(
479 CONVENTIONAL_CONDITIONS,
480 [ConditionName](const llvm::StringLiteral &Conventional) {
481 return ConditionName.contains_lower(Conventional);
482 });
483 });
484}
485
486/// Clarification is a simple pair of a reason why parameter is not called
487/// on every path and a statement to blame.
488struct Clarification {
489 NeverCalledReason Reason;
490 const Stmt *Location;
491};
492
493/// A helper class that can produce a clarification based on the given pair
494/// of basic blocks.
495class NotCalledClarifier
496 : public ConstStmtVisitor<NotCalledClarifier,
497 llvm::Optional<Clarification>> {
498public:
499 /// The main entrypoint for the class, the function that tries to find the
500 /// clarification of how to explain which sub-path starts with a CFG edge
501 /// from Conditional to SuccWithoutCall.
502 ///
503 /// This means that this function has one precondition:
504 /// SuccWithoutCall should be a successor block for Conditional.
505 ///
506 /// Because clarification is not needed for non-trivial pairs of blocks
507 /// (i.e. SuccWithoutCall is not the only successor), it returns meaningful
508 /// results only for such cases. For this very reason, the parent basic
509 /// block, Conditional, is named that way, so it is clear what kind of
510 /// block is expected.
511 static llvm::Optional<Clarification>
512 clarify(const CFGBlock *Conditional, const CFGBlock *SuccWithoutCall) {
513 if (const Stmt *Terminator = Conditional->getTerminatorStmt()) {
514 return NotCalledClarifier{Conditional, SuccWithoutCall}.Visit(Terminator);
515 }
516 return llvm::None;
517 }
518
519 llvm::Optional<Clarification> VisitIfStmt(const IfStmt *If) {
520 return VisitBranchingBlock(If, NeverCalledReason::IfThen);
521 }
522
523 llvm::Optional<Clarification>
524 VisitAbstractConditionalOperator(const AbstractConditionalOperator *Ternary) {
525 return VisitBranchingBlock(Ternary, NeverCalledReason::IfThen);
526 }
527
528 llvm::Optional<Clarification> VisitSwitchStmt(const SwitchStmt *Switch) {
529 const Stmt *CaseToBlame = SuccInQuestion->getLabel();
530 if (!CaseToBlame) {
531 // If interesting basic block is not labeled, it means that this
532 // basic block does not represent any of the cases.
533 return Clarification{NeverCalledReason::SwitchSkipped, Switch};
534 }
535
536 for (const SwitchCase *Case = Switch->getSwitchCaseList(); Case;
537 Case = Case->getNextSwitchCase()) {
538 if (Case == CaseToBlame) {
539 return Clarification{NeverCalledReason::Switch, Case};
540 }
541 }
542
543 llvm_unreachable("Found unexpected switch structure")::llvm::llvm_unreachable_internal("Found unexpected switch structure"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 543)
;
544 }
545
546 llvm::Optional<Clarification> VisitForStmt(const ForStmt *For) {
547 return VisitBranchingBlock(For, NeverCalledReason::LoopEntered);
548 }
549
550 llvm::Optional<Clarification> VisitWhileStmt(const WhileStmt *While) {
551 return VisitBranchingBlock(While, NeverCalledReason::LoopEntered);
552 }
553
554 llvm::Optional<Clarification>
555 VisitBranchingBlock(const Stmt *Terminator, NeverCalledReason DefaultReason) {
556 assert(Parent->succ_size() == 2 &&((Parent->succ_size() == 2 && "Branching block should have exactly two successors"
) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() == 2 && \"Branching block should have exactly two successors\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 557, __PRETTY_FUNCTION__))
557 "Branching block should have exactly two successors")((Parent->succ_size() == 2 && "Branching block should have exactly two successors"
) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() == 2 && \"Branching block should have exactly two successors\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 557, __PRETTY_FUNCTION__))
;
558 unsigned SuccessorIndex = getSuccessorIndex(Parent, SuccInQuestion);
559 NeverCalledReason ActualReason =
560 updateForSuccessor(DefaultReason, SuccessorIndex);
561 return Clarification{ActualReason, Terminator};
562 }
563
564 llvm::Optional<Clarification> VisitBinaryOperator(const BinaryOperator *) {
565 // We don't want to report on short-curcuit logical operations.
566 return llvm::None;
567 }
568
569 llvm::Optional<Clarification> VisitStmt(const Stmt *Terminator) {
570 // If we got here, we didn't have a visit function for more derived
571 // classes of statement that this terminator actually belongs to.
572 //
573 // This is not a good scenario and should not happen in practice, but
574 // at least we'll warn the user.
575 return Clarification{NeverCalledReason::FallbackReason, Terminator};
576 }
577
578 static unsigned getSuccessorIndex(const CFGBlock *Parent,
579 const CFGBlock *Child) {
580 CFGBlock::const_succ_iterator It = llvm::find(Parent->succs(), Child);
581 assert(It != Parent->succ_end() &&((It != Parent->succ_end() && "Given blocks should be in parent-child relationship"
) ? static_cast<void> (0) : __assert_fail ("It != Parent->succ_end() && \"Given blocks should be in parent-child relationship\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 582, __PRETTY_FUNCTION__))
582 "Given blocks should be in parent-child relationship")((It != Parent->succ_end() && "Given blocks should be in parent-child relationship"
) ? static_cast<void> (0) : __assert_fail ("It != Parent->succ_end() && \"Given blocks should be in parent-child relationship\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 582, __PRETTY_FUNCTION__))
;
583 return It - Parent->succ_begin();
584 }
585
586 static NeverCalledReason
587 updateForSuccessor(NeverCalledReason ReasonForTrueBranch,
588 unsigned SuccessorIndex) {
589 assert(SuccessorIndex <= 1)((SuccessorIndex <= 1) ? static_cast<void> (0) : __assert_fail
("SuccessorIndex <= 1", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 589, __PRETTY_FUNCTION__))
;
590 unsigned RawReason =
591 static_cast<unsigned>(ReasonForTrueBranch) + SuccessorIndex;
592 assert(RawReason <=((RawReason <= static_cast<unsigned>(NeverCalledReason
::LARGEST_VALUE)) ? static_cast<void> (0) : __assert_fail
("RawReason <= static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 593, __PRETTY_FUNCTION__))
593 static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE))((RawReason <= static_cast<unsigned>(NeverCalledReason
::LARGEST_VALUE)) ? static_cast<void> (0) : __assert_fail
("RawReason <= static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 593, __PRETTY_FUNCTION__))
;
594 return static_cast<NeverCalledReason>(RawReason);
595 }
596
597private:
598 NotCalledClarifier(const CFGBlock *Parent, const CFGBlock *SuccInQuestion)
599 : Parent(Parent), SuccInQuestion(SuccInQuestion) {}
600
601 const CFGBlock *Parent, *SuccInQuestion;
602};
603
604class CalledOnceChecker : public ConstStmtVisitor<CalledOnceChecker> {
605public:
606 static void check(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler,
607 bool CheckConventionalParameters) {
608 CalledOnceChecker(AC, Handler, CheckConventionalParameters).check();
609 }
610
611private:
612 CalledOnceChecker(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler,
613 bool CheckConventionalParameters)
614 : FunctionCFG(*AC.getCFG()), AC(AC), Handler(Handler),
615 CheckConventionalParameters(CheckConventionalParameters),
616 CurrentState(0) {
617 initDataStructures();
618 assert((size() == 0 || !States.empty()) &&(((size() == 0 || !States.empty()) && "Data structures are inconsistent"
) ? static_cast<void> (0) : __assert_fail ("(size() == 0 || !States.empty()) && \"Data structures are inconsistent\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 619, __PRETTY_FUNCTION__))
619 "Data structures are inconsistent")(((size() == 0 || !States.empty()) && "Data structures are inconsistent"
) ? static_cast<void> (0) : __assert_fail ("(size() == 0 || !States.empty()) && \"Data structures are inconsistent\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 619, __PRETTY_FUNCTION__))
;
620 }
621
622 //===----------------------------------------------------------------------===//
623 // Initializing functions
624 //===----------------------------------------------------------------------===//
625
626 void initDataStructures() {
627 const Decl *AnalyzedDecl = AC.getDecl();
628
629 if (const auto *Function = dyn_cast<FunctionDecl>(AnalyzedDecl)) {
630 findParamsToTrack(Function);
631 } else if (const auto *Method = dyn_cast<ObjCMethodDecl>(AnalyzedDecl)) {
632 findParamsToTrack(Method);
633 } else if (const auto *Block = dyn_cast<BlockDecl>(AnalyzedDecl)) {
634 findCapturesToTrack(Block);
635 findParamsToTrack(Block);
636 }
637
638 // Have something to track, let's init states for every block from the CFG.
639 if (size() != 0) {
640 States =
641 CFGSizedVector<State>(FunctionCFG.getNumBlockIDs(), State(size()));
642 }
643 }
644
645 void findCapturesToTrack(const BlockDecl *Block) {
646 for (const auto &Capture : Block->captures()) {
647 if (const auto *P = dyn_cast<ParmVarDecl>(Capture.getVariable())) {
648 // Parameter DeclContext is its owning function or method.
649 const DeclContext *ParamContext = P->getDeclContext();
650 if (shouldBeCalledOnce(ParamContext, P)) {
651 TrackedParams.push_back(P);
652 }
653 }
654 }
655 }
656
657 template <class FunctionLikeDecl>
658 void findParamsToTrack(const FunctionLikeDecl *Function) {
659 for (unsigned Index : llvm::seq<unsigned>(0u, Function->param_size())) {
660 if (shouldBeCalledOnce(Function, Index)) {
661 TrackedParams.push_back(Function->getParamDecl(Index));
662 }
663 }
664 }
665
666 //===----------------------------------------------------------------------===//
667 // Main logic 'check' functions
668 //===----------------------------------------------------------------------===//
669
670 void check() {
671 // Nothing to check here: we don't have marked parameters.
672 if (size() == 0 || isPossiblyEmptyImpl())
673 return;
674
675 assert(((llvm::none_of(States, [](const State &S) { return S.isVisited
(); }) && "None of the blocks should be 'visited' before the analysis"
) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 677, __PRETTY_FUNCTION__))
676 llvm::none_of(States, [](const State &S) { return S.isVisited(); }) &&((llvm::none_of(States, [](const State &S) { return S.isVisited
(); }) && "None of the blocks should be 'visited' before the analysis"
) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 677, __PRETTY_FUNCTION__))
677 "None of the blocks should be 'visited' before the analysis")((llvm::none_of(States, [](const State &S) { return S.isVisited
(); }) && "None of the blocks should be 'visited' before the analysis"
) ? static_cast<void> (0) : __assert_fail ("llvm::none_of(States, [](const State &S) { return S.isVisited(); }) && \"None of the blocks should be 'visited' before the analysis\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 677, __PRETTY_FUNCTION__))
;
678
679 // For our task, both backward and forward approaches suite well.
680 // However, in order to report better diagnostics, we decided to go with
681 // backward analysis.
682 //
683 // Let's consider the following CFG and how forward and backward analyses
684 // will work for it.
685 //
686 // FORWARD: | BACKWARD:
687 // #1 | #1
688 // +---------+ | +-----------+
689 // | if | | |MaybeCalled|
690 // +---------+ | +-----------+
691 // |NotCalled| | | if |
692 // +---------+ | +-----------+
693 // / \ | / \
694 // #2 / \ #3 | #2 / \ #3
695 // +----------------+ +---------+ | +----------------+ +---------+
696 // | foo() | | ... | | |DefinitelyCalled| |NotCalled|
697 // +----------------+ +---------+ | +----------------+ +---------+
698 // |DefinitelyCalled| |NotCalled| | | foo() | | ... |
699 // +----------------+ +---------+ | +----------------+ +---------+
700 // \ / | \ /
701 // \ #4 / | \ #4 /
702 // +-----------+ | +---------+
703 // | ... | | |NotCalled|
704 // +-----------+ | +---------+
705 // |MaybeCalled| | | ... |
706 // +-----------+ | +---------+
707 //
708 // The most natural way to report lacking call in the block #3 would be to
709 // message that the false branch of the if statement in the block #1 doesn't
710 // have a call. And while with the forward approach we'll need to find a
711 // least common ancestor or something like that to find the 'if' to blame,
712 // backward analysis gives it to us out of the box.
713 BackwardDataflowWorklist Worklist(FunctionCFG, AC);
714
715 // Let's visit EXIT.
716 const CFGBlock *Exit = &FunctionCFG.getExit();
717 assignState(Exit, State(size(), ParameterStatus::NotCalled));
718 Worklist.enqueuePredecessors(Exit);
719
720 while (const CFGBlock *BB = Worklist.dequeue()) {
721 assert(BB && "Worklist should filter out null blocks")((BB && "Worklist should filter out null blocks") ? static_cast
<void> (0) : __assert_fail ("BB && \"Worklist should filter out null blocks\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 721, __PRETTY_FUNCTION__))
;
722 check(BB);
723 assert(CurrentState.isVisited() &&((CurrentState.isVisited() && "After the check, basic block should be visited"
) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"After the check, basic block should be visited\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 724, __PRETTY_FUNCTION__))
724 "After the check, basic block should be visited")((CurrentState.isVisited() && "After the check, basic block should be visited"
) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"After the check, basic block should be visited\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 724, __PRETTY_FUNCTION__))
;
725
726 // Traverse successor basic blocks if the status of this block
727 // has changed.
728 if (assignState(BB, CurrentState)) {
729 Worklist.enqueuePredecessors(BB);
730 }
731 }
732
733 // Check that we have all tracked parameters at the last block.
734 // As we are performing a backward version of the analysis,
735 // it should be the ENTRY block.
736 checkEntry(&FunctionCFG.getEntry());
737 }
738
739 void check(const CFGBlock *BB) {
740 // We start with a state 'inherited' from all the successors.
741 CurrentState = joinSuccessors(BB);
742 assert(CurrentState.isVisited() &&((CurrentState.isVisited() && "Shouldn't start with a 'not visited' state"
) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"Shouldn't start with a 'not visited' state\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 743, __PRETTY_FUNCTION__))
743 "Shouldn't start with a 'not visited' state")((CurrentState.isVisited() && "Shouldn't start with a 'not visited' state"
) ? static_cast<void> (0) : __assert_fail ("CurrentState.isVisited() && \"Shouldn't start with a 'not visited' state\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 743, __PRETTY_FUNCTION__))
;
744
745 // This is the 'exit' situation, broken promises are probably OK
746 // in such scenarios.
747 if (BB->hasNoReturnElement()) {
748 markNoReturn();
749 // This block still can have calls (even multiple calls) and
750 // for this reason there is no early return here.
751 }
752
753 // We use a backward dataflow propagation and for this reason we
754 // should traverse basic blocks bottom-up.
755 for (const CFGElement &Element : llvm::reverse(*BB)) {
756 if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
757 check(S->getStmt());
758 }
759 }
760 }
761 void check(const Stmt *S) { Visit(S); }
762
763 void checkEntry(const CFGBlock *Entry) {
764 // We finalize this algorithm with the ENTRY block because
765 // we use a backward version of the analysis. This is where
766 // we can judge that some of the tracked parameters are not called on
767 // every path from ENTRY to EXIT.
768
769 const State &EntryStatus = getState(Entry);
770 llvm::BitVector NotCalledOnEveryPath(size(), false);
771 llvm::BitVector NotUsedOnEveryPath(size(), false);
772
773 // Check if there are no calls of the marked parameter at all
774 for (const auto &IndexedStatus : llvm::enumerate(EntryStatus)) {
775 const ParmVarDecl *Parameter = getParameter(IndexedStatus.index());
776
777 switch (IndexedStatus.value().getKind()) {
778 case ParameterStatus::NotCalled:
779 // If there were places where this parameter escapes (aka being used),
780 // we can provide a more useful diagnostic by pointing at the exact
781 // branches where it is not even mentioned.
782 if (!hasEverEscaped(IndexedStatus.index())) {
783 // This parameter is was not used at all, so we should report the
784 // most generic version of the warning.
785 if (isCaptured(Parameter)) {
786 // We want to specify that it was captured by the block.
787 Handler.handleCapturedNeverCalled(Parameter, AC.getDecl(),
788 !isExplicitlyMarked(Parameter));
789 } else {
790 Handler.handleNeverCalled(Parameter,
791 !isExplicitlyMarked(Parameter));
792 }
793 } else {
794 // Mark it as 'interesting' to figure out which paths don't even
795 // have escapes.
796 NotUsedOnEveryPath[IndexedStatus.index()] = true;
797 }
798
799 break;
800 case ParameterStatus::MaybeCalled:
801 // If we have 'maybe called' at this point, we have an error
802 // that there is at least one path where this parameter
803 // is not called.
804 //
805 // However, reporting the warning with only that information can be
806 // too vague for the users. For this reason, we mark such parameters
807 // as "interesting" for further analysis.
808 NotCalledOnEveryPath[IndexedStatus.index()] = true;
809 break;
810 default:
811 break;
812 }
813 }
814
815 // Early exit if we don't have parameters for extra analysis...
816 if (NotCalledOnEveryPath.none() && NotUsedOnEveryPath.none() &&
817 // ... or if we've seen variables with cleanup functions.
818 // We can't reason that we've seen every path in this case,
819 // and thus abandon reporting any warnings that imply that.
820 !FunctionHasCleanupVars)
821 return;
822
823 // We are looking for a pair of blocks A, B so that the following is true:
824 // * A is a predecessor of B
825 // * B is marked as NotCalled
826 // * A has at least one successor marked as either
827 // Escaped or DefinitelyCalled
828 //
829 // In that situation, it is guaranteed that B is the first block of the path
830 // where the user doesn't call or use parameter in question.
831 //
832 // For this reason, branch A -> B can be used for reporting.
833 //
834 // This part of the algorithm is guarded by a condition that the function
835 // does indeed have a violation of contract. For this reason, we can
836 // spend more time to find a good spot to place the warning.
837 //
838 // The following algorithm has the worst case complexity of O(V + E),
839 // where V is the number of basic blocks in FunctionCFG,
840 // E is the number of edges between blocks in FunctionCFG.
841 for (const CFGBlock *BB : FunctionCFG) {
842 if (!BB)
843 continue;
844
845 const State &BlockState = getState(BB);
846
847 for (unsigned Index : llvm::seq(0u, size())) {
848 // We don't want to use 'isLosingCall' here because we want to report
849 // the following situation as well:
850 //
851 // MaybeCalled
852 // | ... |
853 // MaybeCalled NotCalled
854 //
855 // Even though successor is not 'DefinitelyCalled', it is still useful
856 // to report it, it is still a path without a call.
857 if (NotCalledOnEveryPath[Index] &&
858 BlockState.getKindFor(Index) == ParameterStatus::MaybeCalled) {
859
860 findAndReportNotCalledBranches(BB, Index);
861 } else if (NotUsedOnEveryPath[Index] &&
862 isLosingEscape(BlockState, BB, Index)) {
863
864 findAndReportNotCalledBranches(BB, Index, /* IsEscape = */ true);
865 }
866 }
867 }
868 }
869
870 /// Check potential call of a tracked parameter.
871 void checkDirectCall(const CallExpr *Call) {
872 if (auto Index = getIndexOfCallee(Call)) {
873 processCallFor(*Index, Call);
874 }
875 }
876
877 /// Check the call expression for being an indirect call of one of the tracked
878 /// parameters. It is indirect in the sense that this particular call is not
879 /// calling the parameter itself, but rather uses it as the argument.
880 template <class CallLikeExpr>
881 void checkIndirectCall(const CallLikeExpr *CallOrMessage) {
882 // CallExpr::arguments does not interact nicely with llvm::enumerate.
883 llvm::ArrayRef<const Expr *> Arguments = llvm::makeArrayRef(
884 CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
885
886 // Let's check if any of the call arguments is a point of interest.
887 for (const auto &Argument : llvm::enumerate(Arguments)) {
888 if (auto Index = getIndexOfExpression(Argument.value())) {
2
Taking true branch
4
Taking true branch
889 if (shouldBeCalledOnce(CallOrMessage, Argument.index())) {
3
Taking false branch
5
Calling 'CalledOnceChecker::shouldBeCalledOnce'
890 // If the corresponding parameter is marked as 'called_once' we should
891 // consider it as a call.
892 processCallFor(*Index, CallOrMessage);
893 } else {
894 // Otherwise, we mark this parameter as escaped, which can be
895 // interpreted both as called or not called depending on the context.
896 processEscapeFor(*Index);
897 }
898 // Otherwise, let's keep the state as it is.
899 }
900 }
901 }
902
903 /// Process call of the parameter with the given index
904 void processCallFor(unsigned Index, const Expr *Call) {
905 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
906
907 if (CurrentParamStatus.seenAnyCalls()) {
908
909 // At this point, this parameter was called, so this is a second call.
910 const ParmVarDecl *Parameter = getParameter(Index);
911 Handler.handleDoubleCall(
912 Parameter, &CurrentState.getCallFor(Index), Call,
913 !isExplicitlyMarked(Parameter),
914 // We are sure that the second call is definitely
915 // going to happen if the status is 'DefinitelyCalled'.
916 CurrentParamStatus.getKind() == ParameterStatus::DefinitelyCalled);
917
918 // Mark this parameter as already reported on, so we don't repeat
919 // warnings.
920 CurrentParamStatus = ParameterStatus::Reported;
921
922 } else if (CurrentParamStatus.getKind() != ParameterStatus::Reported) {
923 // If we didn't report anything yet, let's mark this parameter
924 // as called.
925 ParameterStatus Called(ParameterStatus::DefinitelyCalled, Call);
926 CurrentParamStatus = Called;
927 }
928 }
929
930 /// Process escape of the parameter with the given index
931 void processEscapeFor(unsigned Index) {
932 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
933
934 // Escape overrides whatever error we think happened.
935 if (CurrentParamStatus.isErrorStatus()) {
936 CurrentParamStatus = ParameterStatus::Escaped;
937 }
938 }
939
940 void findAndReportNotCalledBranches(const CFGBlock *Parent, unsigned Index,
941 bool IsEscape = false) {
942 for (const CFGBlock *Succ : Parent->succs()) {
943 if (!Succ)
944 continue;
945
946 if (getState(Succ).getKindFor(Index) == ParameterStatus::NotCalled) {
947 assert(Parent->succ_size() >= 2 &&((Parent->succ_size() >= 2 && "Block should have at least two successors at this point"
) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() >= 2 && \"Block should have at least two successors at this point\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 948, __PRETTY_FUNCTION__))
948 "Block should have at least two successors at this point")((Parent->succ_size() >= 2 && "Block should have at least two successors at this point"
) ? static_cast<void> (0) : __assert_fail ("Parent->succ_size() >= 2 && \"Block should have at least two successors at this point\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 948, __PRETTY_FUNCTION__))
;
949 if (auto Clarification = NotCalledClarifier::clarify(Parent, Succ)) {
950 const ParmVarDecl *Parameter = getParameter(Index);
951 Handler.handleNeverCalled(
952 Parameter, AC.getDecl(), Clarification->Location,
953 Clarification->Reason, !IsEscape, !isExplicitlyMarked(Parameter));
954 }
955 }
956 }
957 }
958
959 //===----------------------------------------------------------------------===//
960 // Predicate functions to check parameters
961 //===----------------------------------------------------------------------===//
962
963 /// Return true if parameter is explicitly marked as 'called_once'.
964 static bool isExplicitlyMarked(const ParmVarDecl *Parameter) {
965 return Parameter->hasAttr<CalledOnceAttr>();
966 }
967
968 /// Return true if the given name matches conventional pattens.
969 static bool isConventional(llvm::StringRef Name) {
970 return llvm::count(CONVENTIONAL_NAMES, Name) != 0;
971 }
972
973 /// Return true if the given name has conventional suffixes.
974 static bool hasConventionalSuffix(llvm::StringRef Name) {
975 return llvm::any_of(CONVENTIONAL_SUFFIXES, [Name](llvm::StringRef Suffix) {
976 return Name.endswith(Suffix);
977 });
978 }
979
980 /// Return true if the given type can be used for conventional parameters.
981 static bool isConventional(QualType Ty) {
982 if (!Ty->isBlockPointerType()) {
13
Calling 'Type::isBlockPointerType'
16
Returning from 'Type::isBlockPointerType'
17
Taking false branch
983 return false;
984 }
985
986 QualType BlockType = Ty->getAs<BlockPointerType>()->getPointeeType();
18
Assuming the object is not a 'BlockPointerType'
19
Called C++ object pointer is null
987 // Completion handlers should have a block type with void return type.
988 return BlockType->getAs<FunctionType>()->getReturnType()->isVoidType();
989 }
990
991 /// Return true if the only parameter of the function is conventional.
992 static bool isOnlyParameterConventional(const FunctionDecl *Function) {
993 IdentifierInfo *II = Function->getIdentifier();
994 return Function->getNumParams() == 1 && II &&
995 hasConventionalSuffix(II->getName());
996 }
997
998 /// Return true/false if 'swift_async' attribute states that the given
999 /// parameter is conventionally called once.
1000 /// Return llvm::None if the given declaration doesn't have 'swift_async'
1001 /// attribute.
1002 static llvm::Optional<bool> isConventionalSwiftAsync(const Decl *D,
1003 unsigned ParamIndex) {
1004 if (const SwiftAsyncAttr *A = D->getAttr<SwiftAsyncAttr>()) {
1005 if (A->getKind() == SwiftAsyncAttr::None) {
1006 return false;
1007 }
1008
1009 return A->getCompletionHandlerIndex().getASTIndex() == ParamIndex;
1010 }
1011 return llvm::None;
1012 }
1013
1014 /// Return true if the specified selector piece matches conventions.
1015 static bool isConventionalSelectorPiece(Selector MethodSelector,
1016 unsigned PieceIndex,
1017 QualType PieceType) {
1018 if (!isConventional(PieceType)) {
1019 return false;
1020 }
1021
1022 if (MethodSelector.getNumArgs() == 1) {
1023 assert(PieceIndex == 0)((PieceIndex == 0) ? static_cast<void> (0) : __assert_fail
("PieceIndex == 0", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1023, __PRETTY_FUNCTION__))
;
1024 return hasConventionalSuffix(MethodSelector.getNameForSlot(0));
1025 }
1026
1027 llvm::StringRef PieceName = MethodSelector.getNameForSlot(PieceIndex);
1028 return isConventional(PieceName) || hasConventionalSuffix(PieceName);
1029 }
1030
1031 bool shouldBeCalledOnce(const ParmVarDecl *Parameter) const {
1032 return isExplicitlyMarked(Parameter) ||
1033 (CheckConventionalParameters &&
11
Assuming field 'CheckConventionalParameters' is true
1034 (isConventional(Parameter->getName()) ||
1035 hasConventionalSuffix(Parameter->getName())) &&
1036 isConventional(Parameter->getType()));
12
Calling 'CalledOnceChecker::isConventional'
1037 }
1038
1039 bool shouldBeCalledOnce(const DeclContext *ParamContext,
1040 const ParmVarDecl *Param) {
1041 unsigned ParamIndex = Param->getFunctionScopeIndex();
1042 if (const auto *Function = dyn_cast<FunctionDecl>(ParamContext)) {
1043 return shouldBeCalledOnce(Function, ParamIndex);
1044 }
1045 if (const auto *Method = dyn_cast<ObjCMethodDecl>(ParamContext)) {
1046 return shouldBeCalledOnce(Method, ParamIndex);
1047 }
1048 return shouldBeCalledOnce(Param);
1049 }
1050
1051 bool shouldBeCalledOnce(const BlockDecl *Block, unsigned ParamIndex) const {
1052 return shouldBeCalledOnce(Block->getParamDecl(ParamIndex));
1053 }
1054
1055 bool shouldBeCalledOnce(const FunctionDecl *Function,
1056 unsigned ParamIndex) const {
1057 if (ParamIndex >= Function->getNumParams()) {
7
Assuming the condition is false
8
Taking false branch
1058 return false;
1059 }
1060 // 'swift_async' goes first and overrides anything else.
1061 if (auto ConventionalAsync =
9
Taking false branch
1062 isConventionalSwiftAsync(Function, ParamIndex)) {
1063 return ConventionalAsync.getValue();
1064 }
1065
1066 return shouldBeCalledOnce(Function->getParamDecl(ParamIndex)) ||
10
Calling 'CalledOnceChecker::shouldBeCalledOnce'
1067 (CheckConventionalParameters &&
1068 isOnlyParameterConventional(Function));
1069 }
1070
1071 bool shouldBeCalledOnce(const ObjCMethodDecl *Method,
1072 unsigned ParamIndex) const {
1073 Selector MethodSelector = Method->getSelector();
1074 if (ParamIndex >= MethodSelector.getNumArgs()) {
1075 return false;
1076 }
1077
1078 // 'swift_async' goes first and overrides anything else.
1079 if (auto ConventionalAsync = isConventionalSwiftAsync(Method, ParamIndex)) {
1080 return ConventionalAsync.getValue();
1081 }
1082
1083 const ParmVarDecl *Parameter = Method->getParamDecl(ParamIndex);
1084 return shouldBeCalledOnce(Parameter) ||
1085 (CheckConventionalParameters &&
1086 isConventionalSelectorPiece(MethodSelector, ParamIndex,
1087 Parameter->getType()));
1088 }
1089
1090 bool shouldBeCalledOnce(const CallExpr *Call, unsigned ParamIndex) const {
1091 const FunctionDecl *Function = Call->getDirectCallee();
1092 return Function
5.1
'Function' is non-null
5.1
'Function' is non-null
&& shouldBeCalledOnce(Function, ParamIndex);
6
Calling 'CalledOnceChecker::shouldBeCalledOnce'
1093 }
1094
1095 bool shouldBeCalledOnce(const ObjCMessageExpr *Message,
1096 unsigned ParamIndex) const {
1097 const ObjCMethodDecl *Method = Message->getMethodDecl();
1098 return Method && ParamIndex < Method->param_size() &&
1099 shouldBeCalledOnce(Method, ParamIndex);
1100 }
1101
1102 //===----------------------------------------------------------------------===//
1103 // Utility methods
1104 //===----------------------------------------------------------------------===//
1105
1106 bool isCaptured(const ParmVarDecl *Parameter) const {
1107 if (const BlockDecl *Block = dyn_cast<BlockDecl>(AC.getDecl())) {
1108 return Block->capturesVariable(Parameter);
1109 }
1110 return false;
1111 }
1112
1113 // Return a call site where the block is called exactly once or null otherwise
1114 const Expr *getBlockGuaraneedCallSite(const BlockExpr *Block) const {
1115 ParentMap &PM = AC.getParentMap();
1116
1117 // We don't want to track the block through assignments and so on, instead
1118 // we simply see how the block used and if it's used directly in a call,
1119 // we decide based on call to what it is.
1120 //
1121 // In order to do this, we go up the parents of the block looking for
1122 // a call or a message expressions. These might not be immediate parents
1123 // of the actual block expression due to casts and parens, so we skip them.
1124 for (const Stmt *Prev = Block, *Current = PM.getParent(Block);
1125 Current != nullptr; Prev = Current, Current = PM.getParent(Current)) {
1126 // Skip no-op (for our case) operations.
1127 if (isa<CastExpr>(Current) || isa<ParenExpr>(Current))
1128 continue;
1129
1130 // At this point, Prev represents our block as an immediate child of the
1131 // call.
1132 if (const auto *Call = dyn_cast<CallExpr>(Current)) {
1133 // It might be the call of the Block itself...
1134 if (Call->getCallee() == Prev)
1135 return Call;
1136
1137 // ...or it can be an indirect call of the block.
1138 return shouldBlockArgumentBeCalledOnce(Call, Prev) ? Call : nullptr;
1139 }
1140 if (const auto *Message = dyn_cast<ObjCMessageExpr>(Current)) {
1141 return shouldBlockArgumentBeCalledOnce(Message, Prev) ? Message
1142 : nullptr;
1143 }
1144
1145 break;
1146 }
1147
1148 return nullptr;
1149 }
1150
1151 template <class CallLikeExpr>
1152 bool shouldBlockArgumentBeCalledOnce(const CallLikeExpr *CallOrMessage,
1153 const Stmt *BlockArgument) const {
1154 // CallExpr::arguments does not interact nicely with llvm::enumerate.
1155 llvm::ArrayRef<const Expr *> Arguments = llvm::makeArrayRef(
1156 CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
1157
1158 for (const auto &Argument : llvm::enumerate(Arguments)) {
1159 if (Argument.value() == BlockArgument) {
1160 return shouldBlockArgumentBeCalledOnce(CallOrMessage, Argument.index());
1161 }
1162 }
1163
1164 return false;
1165 }
1166
1167 bool shouldBlockArgumentBeCalledOnce(const CallExpr *Call,
1168 unsigned ParamIndex) const {
1169 const FunctionDecl *Function = Call->getDirectCallee();
1170 return shouldBlockArgumentBeCalledOnce(Function, ParamIndex) ||
1171 shouldBeCalledOnce(Call, ParamIndex);
1172 }
1173
1174 bool shouldBlockArgumentBeCalledOnce(const ObjCMessageExpr *Message,
1175 unsigned ParamIndex) const {
1176 // At the moment, we don't have any Obj-C methods we want to specifically
1177 // check in here.
1178 return shouldBeCalledOnce(Message, ParamIndex);
1179 }
1180
1181 static bool shouldBlockArgumentBeCalledOnce(const FunctionDecl *Function,
1182 unsigned ParamIndex) {
1183 // There is a list of important API functions that while not following
1184 // conventions nor being directly annotated, still guarantee that the
1185 // callback parameter will be called exactly once.
1186 //
1187 // Here we check if this is the case.
1188 return Function &&
1189 llvm::any_of(KNOWN_CALLED_ONCE_PARAMETERS,
1190 [Function, ParamIndex](
1191 const KnownCalledOnceParameter &Reference) {
1192 return Reference.FunctionName ==
1193 Function->getName() &&
1194 Reference.ParamIndex == ParamIndex;
1195 });
1196 }
1197
1198 /// Return true if the analyzed function is actually a default implementation
1199 /// of the method that has to be overriden.
1200 ///
1201 /// These functions can have tracked parameters, but wouldn't call them
1202 /// because they are not designed to perform any meaningful actions.
1203 ///
1204 /// There are a couple of flavors of such default implementations:
1205 /// 1. Empty methods or methods with a single return statement
1206 /// 2. Methods that have one block with a call to no return function
1207 /// 3. Methods with only assertion-like operations
1208 bool isPossiblyEmptyImpl() const {
1209 if (!isa<ObjCMethodDecl>(AC.getDecl())) {
1210 // We care only about functions that are not supposed to be called.
1211 // Only methods can be overriden.
1212 return false;
1213 }
1214
1215 // Case #1 (without return statements)
1216 if (FunctionCFG.size() == 2) {
1217 // Method has only two blocks: ENTRY and EXIT.
1218 // This is equivalent to empty function.
1219 return true;
1220 }
1221
1222 // Case #2
1223 if (FunctionCFG.size() == 3) {
1224 const CFGBlock &Entry = FunctionCFG.getEntry();
1225 if (Entry.succ_empty()) {
1226 return false;
1227 }
1228
1229 const CFGBlock *OnlyBlock = *Entry.succ_begin();
1230 // Method has only one block, let's see if it has a no-return
1231 // element.
1232 if (OnlyBlock && OnlyBlock->hasNoReturnElement()) {
1233 return true;
1234 }
1235 // Fallthrough, CFGs with only one block can fall into #1 and #3 as well.
1236 }
1237
1238 // Cases #1 (return statements) and #3.
1239 //
1240 // It is hard to detect that something is an assertion or came
1241 // from assertion. Here we use a simple heuristic:
1242 //
1243 // - If it came from a macro, it can be an assertion.
1244 //
1245 // Additionally, we can't assume a number of basic blocks or the CFG's
1246 // structure because assertions might include loops and conditions.
1247 return llvm::all_of(FunctionCFG, [](const CFGBlock *BB) {
1248 if (!BB) {
1249 // Unreachable blocks are totally fine.
1250 return true;
1251 }
1252
1253 // Return statements can have sub-expressions that are represented as
1254 // separate statements of a basic block. We should allow this.
1255 // This parent map will be initialized with a parent tree for all
1256 // subexpressions of the block's return statement (if it has one).
1257 std::unique_ptr<ParentMap> ReturnChildren;
1258
1259 return llvm::all_of(
1260 llvm::reverse(*BB), // we should start with return statements, if we
1261 // have any, i.e. from the bottom of the block
1262 [&ReturnChildren](const CFGElement &Element) {
1263 if (Optional<CFGStmt> S = Element.getAs<CFGStmt>()) {
1264 const Stmt *SuspiciousStmt = S->getStmt();
1265
1266 if (isa<ReturnStmt>(SuspiciousStmt)) {
1267 // Let's initialize this structure to test whether
1268 // some further statement is a part of this return.
1269 ReturnChildren = std::make_unique<ParentMap>(
1270 const_cast<Stmt *>(SuspiciousStmt));
1271 // Return statements are allowed as part of #1.
1272 return true;
1273 }
1274
1275 return SuspiciousStmt->getBeginLoc().isMacroID() ||
1276 (ReturnChildren &&
1277 ReturnChildren->hasParent(SuspiciousStmt));
1278 }
1279 return true;
1280 });
1281 });
1282 }
1283
1284 /// Check if parameter with the given index has ever escaped.
1285 bool hasEverEscaped(unsigned Index) const {
1286 return llvm::any_of(States, [Index](const State &StateForOneBB) {
1287 return StateForOneBB.getKindFor(Index) == ParameterStatus::Escaped;
1288 });
1289 }
1290
1291 /// Return status stored for the given basic block.
1292 /// \{
1293 State &getState(const CFGBlock *BB) {
1294 assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1294, __PRETTY_FUNCTION__))
;
1295 return States[BB->getBlockID()];
1296 }
1297 const State &getState(const CFGBlock *BB) const {
1298 assert(BB)((BB) ? static_cast<void> (0) : __assert_fail ("BB", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1298, __PRETTY_FUNCTION__))
;
1299 return States[BB->getBlockID()];
1300 }
1301 /// \}
1302
1303 /// Assign status to the given basic block.
1304 ///
1305 /// Returns true when the stored status changed.
1306 bool assignState(const CFGBlock *BB, const State &ToAssign) {
1307 State &Current = getState(BB);
1308 if (Current == ToAssign) {
1309 return false;
1310 }
1311
1312 Current = ToAssign;
1313 return true;
1314 }
1315
1316 /// Join all incoming statuses for the given basic block.
1317 State joinSuccessors(const CFGBlock *BB) const {
1318 auto Succs =
1319 llvm::make_filter_range(BB->succs(), [this](const CFGBlock *Succ) {
1320 return Succ && this->getState(Succ).isVisited();
1321 });
1322 // We came to this block from somewhere after all.
1323 assert(!Succs.empty() &&((!Succs.empty() && "Basic block should have at least one visited successor"
) ? static_cast<void> (0) : __assert_fail ("!Succs.empty() && \"Basic block should have at least one visited successor\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1324, __PRETTY_FUNCTION__))
1324 "Basic block should have at least one visited successor")((!Succs.empty() && "Basic block should have at least one visited successor"
) ? static_cast<void> (0) : __assert_fail ("!Succs.empty() && \"Basic block should have at least one visited successor\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1324, __PRETTY_FUNCTION__))
;
1325
1326 State Result = getState(*Succs.begin());
1327
1328 for (const CFGBlock *Succ : llvm::drop_begin(Succs, 1)) {
1329 Result.join(getState(Succ));
1330 }
1331
1332 if (const Expr *Condition = getCondition(BB->getTerminatorStmt())) {
1333 handleConditional(BB, Condition, Result);
1334 }
1335
1336 return Result;
1337 }
1338
1339 void handleConditional(const CFGBlock *BB, const Expr *Condition,
1340 State &ToAlter) const {
1341 handleParameterCheck(BB, Condition, ToAlter);
1342 if (SuppressOnConventionalErrorPaths) {
1343 handleConventionalCheck(BB, Condition, ToAlter);
1344 }
1345 }
1346
1347 void handleParameterCheck(const CFGBlock *BB, const Expr *Condition,
1348 State &ToAlter) const {
1349 // In this function, we try to deal with the following pattern:
1350 //
1351 // if (parameter)
1352 // parameter(...);
1353 //
1354 // It's not good to show a warning here because clearly 'parameter'
1355 // couldn't and shouldn't be called on the 'else' path.
1356 //
1357 // Let's check if this if statement has a check involving one of
1358 // the tracked parameters.
1359 if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(
1360 Condition,
1361 /* ShouldRetrieveFromComparisons = */ true)) {
1362 if (const auto Index = getIndex(*Parameter)) {
1363 ParameterStatus &CurrentStatus = ToAlter.getStatusFor(*Index);
1364
1365 // We don't want to deep dive into semantics of the check and
1366 // figure out if that check was for null or something else.
1367 // We simply trust the user that they know what they are doing.
1368 //
1369 // For this reason, in the following loop we look for the
1370 // best-looking option.
1371 for (const CFGBlock *Succ : BB->succs()) {
1372 if (!Succ)
1373 continue;
1374
1375 const ParameterStatus &StatusInSucc =
1376 getState(Succ).getStatusFor(*Index);
1377
1378 if (StatusInSucc.isErrorStatus()) {
1379 continue;
1380 }
1381
1382 // Let's use this status instead.
1383 CurrentStatus = StatusInSucc;
1384
1385 if (StatusInSucc.getKind() == ParameterStatus::DefinitelyCalled) {
1386 // This is the best option to have and we already found it.
1387 break;
1388 }
1389
1390 // If we found 'Escaped' first, we still might find 'DefinitelyCalled'
1391 // on the other branch. And we prefer the latter.
1392 }
1393 }
1394 }
1395 }
1396
1397 void handleConventionalCheck(const CFGBlock *BB, const Expr *Condition,
1398 State &ToAlter) const {
1399 // Even when the analysis is technically correct, it is a widespread pattern
1400 // not to call completion handlers in some scenarios. These usually have
1401 // typical conditional names, such as 'error' or 'cancel'.
1402 if (!mentionsAnyOfConventionalNames(Condition)) {
1403 return;
1404 }
1405
1406 for (const auto &IndexedStatus : llvm::enumerate(ToAlter)) {
1407 const ParmVarDecl *Parameter = getParameter(IndexedStatus.index());
1408 // Conventions do not apply to explicitly marked parameters.
1409 if (isExplicitlyMarked(Parameter)) {
1410 continue;
1411 }
1412
1413 ParameterStatus &CurrentStatus = IndexedStatus.value();
1414 // If we did find that on one of the branches the user uses the callback
1415 // and doesn't on the other path, we believe that they know what they are
1416 // doing and trust them.
1417 //
1418 // There are two possible scenarios for that:
1419 // 1. Current status is 'MaybeCalled' and one of the branches is
1420 // 'DefinitelyCalled'
1421 // 2. Current status is 'NotCalled' and one of the branches is 'Escaped'
1422 if (isLosingCall(ToAlter, BB, IndexedStatus.index()) ||
1423 isLosingEscape(ToAlter, BB, IndexedStatus.index())) {
1424 CurrentStatus = ParameterStatus::Escaped;
1425 }
1426 }
1427 }
1428
1429 bool isLosingCall(const State &StateAfterJoin, const CFGBlock *JoinBlock,
1430 unsigned ParameterIndex) const {
1431 // Let's check if the block represents DefinitelyCalled -> MaybeCalled
1432 // transition.
1433 return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1434 ParameterStatus::MaybeCalled,
1435 ParameterStatus::DefinitelyCalled);
1436 }
1437
1438 bool isLosingEscape(const State &StateAfterJoin, const CFGBlock *JoinBlock,
1439 unsigned ParameterIndex) const {
1440 // Let's check if the block represents Escaped -> NotCalled transition.
1441 return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1442 ParameterStatus::NotCalled, ParameterStatus::Escaped);
1443 }
1444
1445 bool isLosingJoin(const State &StateAfterJoin, const CFGBlock *JoinBlock,
1446 unsigned ParameterIndex, ParameterStatus::Kind AfterJoin,
1447 ParameterStatus::Kind BeforeJoin) const {
1448 assert(!ParameterStatus::isErrorStatus(BeforeJoin) &&((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus
::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent "
"correct-to-error transition") ? static_cast<void> (0)
: __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1451, __PRETTY_FUNCTION__))
1449 ParameterStatus::isErrorStatus(AfterJoin) &&((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus
::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent "
"correct-to-error transition") ? static_cast<void> (0)
: __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1451, __PRETTY_FUNCTION__))
1450 "It's not a losing join if statuses do not represent "((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus
::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent "
"correct-to-error transition") ? static_cast<void> (0)
: __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1451, __PRETTY_FUNCTION__))
1451 "correct-to-error transition")((!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus
::isErrorStatus(AfterJoin) && "It's not a losing join if statuses do not represent "
"correct-to-error transition") ? static_cast<void> (0)
: __assert_fail ("!ParameterStatus::isErrorStatus(BeforeJoin) && ParameterStatus::isErrorStatus(AfterJoin) && \"It's not a losing join if statuses do not represent \" \"correct-to-error transition\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1451, __PRETTY_FUNCTION__))
;
1452
1453 const ParameterStatus &CurrentStatus =
1454 StateAfterJoin.getStatusFor(ParameterIndex);
1455
1456 return CurrentStatus.getKind() == AfterJoin &&
1457 anySuccessorHasStatus(JoinBlock, ParameterIndex, BeforeJoin);
1458 }
1459
1460 /// Return true if any of the successors of the given basic block has
1461 /// a specified status for the given parameter.
1462 bool anySuccessorHasStatus(const CFGBlock *Parent, unsigned ParameterIndex,
1463 ParameterStatus::Kind ToFind) const {
1464 return llvm::any_of(
1465 Parent->succs(), [this, ParameterIndex, ToFind](const CFGBlock *Succ) {
1466 return Succ && getState(Succ).getKindFor(ParameterIndex) == ToFind;
1467 });
1468 }
1469
1470 /// Check given expression that was discovered to escape.
1471 void checkEscapee(const Expr *E) {
1472 if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(E)) {
1473 checkEscapee(*Parameter);
1474 }
1475 }
1476
1477 /// Check given parameter that was discovered to escape.
1478 void checkEscapee(const ParmVarDecl &Parameter) {
1479 if (auto Index = getIndex(Parameter)) {
1480 processEscapeFor(*Index);
1481 }
1482 }
1483
1484 /// Mark all parameters in the current state as 'no-return'.
1485 void markNoReturn() {
1486 for (ParameterStatus &PS : CurrentState) {
1487 PS = ParameterStatus::NoReturn;
1488 }
1489 }
1490
1491 /// Check if the given assignment represents suppression and act on it.
1492 void checkSuppression(const BinaryOperator *Assignment) {
1493 // Suppression has the following form:
1494 // parameter = 0;
1495 // 0 can be of any form (NULL, nil, etc.)
1496 if (auto Index = getIndexOfExpression(Assignment->getLHS())) {
1497
1498 // We don't care what is written in the RHS, it could be whatever
1499 // we can interpret as 0.
1500 if (auto Constant =
1501 Assignment->getRHS()->IgnoreParenCasts()->getIntegerConstantExpr(
1502 AC.getASTContext())) {
1503
1504 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index);
1505
1506 if (0 == *Constant && CurrentParamStatus.seenAnyCalls()) {
1507 // Even though this suppression mechanism is introduced to tackle
1508 // false positives for multiple calls, the fact that the user has
1509 // to use suppression can also tell us that we couldn't figure out
1510 // how different paths cancel each other out. And if that is true,
1511 // we will most certainly have false positives about parameters not
1512 // being called on certain paths.
1513 //
1514 // For this reason, we abandon tracking this parameter altogether.
1515 CurrentParamStatus = ParameterStatus::Reported;
1516 }
1517 }
1518 }
1519 }
1520
1521public:
1522 //===----------------------------------------------------------------------===//
1523 // Tree traversal methods
1524 //===----------------------------------------------------------------------===//
1525
1526 void VisitCallExpr(const CallExpr *Call) {
1527 // This call might be a direct call, i.e. a parameter call...
1528 checkDirectCall(Call);
1529 // ... or an indirect call, i.e. when parameter is an argument.
1530 checkIndirectCall(Call);
1
Calling 'CalledOnceChecker::checkIndirectCall'
1531 }
1532
1533 void VisitObjCMessageExpr(const ObjCMessageExpr *Message) {
1534 // The most common situation that we are defending against here is
1535 // copying a tracked parameter.
1536 if (const Expr *Receiver = Message->getInstanceReceiver()) {
1537 checkEscapee(Receiver);
1538 }
1539 // Message expressions unlike calls, could not be direct.
1540 checkIndirectCall(Message);
1541 }
1542
1543 void VisitBlockExpr(const BlockExpr *Block) {
1544 // Block expressions are tricky. It is a very common practice to capture
1545 // completion handlers by blocks and use them there.
1546 // For this reason, it is important to analyze blocks and report warnings
1547 // for completion handler misuse in blocks.
1548 //
1549 // However, it can be quite difficult to track how the block itself is being
1550 // used. The full precise anlysis of that will be similar to alias analysis
1551 // for completion handlers and can be too heavyweight for a compile-time
1552 // diagnostic. Instead, we judge about the immediate use of the block.
1553 //
1554 // Here, we try to find a call expression where we know due to conventions,
1555 // annotations, or other reasons that the block is called once and only
1556 // once.
1557 const Expr *CalledOnceCallSite = getBlockGuaraneedCallSite(Block);
1558
1559 // We need to report this information to the handler because in the
1560 // situation when we know that the block is called exactly once, we can be
1561 // stricter in terms of reported diagnostics.
1562 if (CalledOnceCallSite) {
1563 Handler.handleBlockThatIsGuaranteedToBeCalledOnce(Block->getBlockDecl());
1564 } else {
1565 Handler.handleBlockWithNoGuarantees(Block->getBlockDecl());
1566 }
1567
1568 for (const auto &Capture : Block->getBlockDecl()->captures()) {
1569 if (const auto *Param = dyn_cast<ParmVarDecl>(Capture.getVariable())) {
1570 if (auto Index = getIndex(*Param)) {
1571 if (CalledOnceCallSite) {
1572 // The call site of a block can be considered a call site of the
1573 // captured parameter we track.
1574 processCallFor(*Index, CalledOnceCallSite);
1575 } else {
1576 // We still should consider this block as an escape for parameter,
1577 // if we don't know about its call site or the number of time it
1578 // can be invoked.
1579 processEscapeFor(*Index);
1580 }
1581 }
1582 }
1583 }
1584 }
1585
1586 void VisitBinaryOperator(const BinaryOperator *Op) {
1587 if (Op->getOpcode() == clang::BO_Assign) {
1588 // Let's check if one of the tracked parameters is assigned into
1589 // something, and if it is we don't want to track extra variables, so we
1590 // consider it as an escapee.
1591 checkEscapee(Op->getRHS());
1592
1593 // Let's check whether this assignment is a suppression.
1594 checkSuppression(Op);
1595 }
1596 }
1597
1598 void VisitDeclStmt(const DeclStmt *DS) {
1599 // Variable initialization is not assignment and should be handled
1600 // separately.
1601 //
1602 // Multiple declarations can be a part of declaration statement.
1603 for (const auto *Declaration : DS->getDeclGroup()) {
1604 if (const auto *Var = dyn_cast<VarDecl>(Declaration)) {
1605 if (Var->getInit()) {
1606 checkEscapee(Var->getInit());
1607 }
1608
1609 if (Var->hasAttr<CleanupAttr>()) {
1610 FunctionHasCleanupVars = true;
1611 }
1612 }
1613 }
1614 }
1615
1616 void VisitCStyleCastExpr(const CStyleCastExpr *Cast) {
1617 // We consider '(void)parameter' as a manual no-op escape.
1618 // It should be used to explicitly tell the analysis that this parameter
1619 // is intentionally not called on this path.
1620 if (Cast->getType().getCanonicalType()->isVoidType()) {
1621 checkEscapee(Cast->getSubExpr());
1622 }
1623 }
1624
1625 void VisitObjCAtThrowStmt(const ObjCAtThrowStmt *) {
1626 // It is OK not to call marked parameters on exceptional paths.
1627 markNoReturn();
1628 }
1629
1630private:
1631 unsigned size() const { return TrackedParams.size(); }
1632
1633 llvm::Optional<unsigned> getIndexOfCallee(const CallExpr *Call) const {
1634 return getIndexOfExpression(Call->getCallee());
1635 }
1636
1637 llvm::Optional<unsigned> getIndexOfExpression(const Expr *E) const {
1638 if (const ParmVarDecl *Parameter = findReferencedParmVarDecl(E)) {
1639 return getIndex(*Parameter);
1640 }
1641
1642 return llvm::None;
1643 }
1644
1645 llvm::Optional<unsigned> getIndex(const ParmVarDecl &Parameter) const {
1646 // Expected number of parameters that we actually track is 1.
1647 //
1648 // Also, the maximum number of declared parameters could not be on a scale
1649 // of hundreds of thousands.
1650 //
1651 // In this setting, linear search seems reasonable and even performs better
1652 // than bisection.
1653 ParamSizedVector<const ParmVarDecl *>::const_iterator It =
1654 llvm::find(TrackedParams, &Parameter);
1655
1656 if (It != TrackedParams.end()) {
1657 return It - TrackedParams.begin();
1658 }
1659
1660 return llvm::None;
1661 }
1662
1663 const ParmVarDecl *getParameter(unsigned Index) const {
1664 assert(Index < TrackedParams.size())((Index < TrackedParams.size()) ? static_cast<void> (
0) : __assert_fail ("Index < TrackedParams.size()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/Analysis/CalledOnceCheck.cpp"
, 1664, __PRETTY_FUNCTION__))
;
1665 return TrackedParams[Index];
1666 }
1667
1668 const CFG &FunctionCFG;
1669 AnalysisDeclContext &AC;
1670 CalledOnceCheckHandler &Handler;
1671 bool CheckConventionalParameters;
1672 // As of now, we turn this behavior off. So, we still are going to report
1673 // missing calls on paths that look like it was intentional.
1674 // Technically such reports are true positives, but they can make some users
1675 // grumpy because of the sheer number of warnings.
1676 // It can be turned back on if we decide that we want to have the other way
1677 // around.
1678 bool SuppressOnConventionalErrorPaths = false;
1679
1680 // The user can annotate variable declarations with cleanup functions, which
1681 // essentially imposes a custom destructor logic on that variable.
1682 // It is possible to use it, however, to call tracked parameters on all exits
1683 // from the function. For this reason, we track the fact that the function
1684 // actually has these.
1685 bool FunctionHasCleanupVars = false;
1686
1687 State CurrentState;
1688 ParamSizedVector<const ParmVarDecl *> TrackedParams;
1689 CFGSizedVector<State> States;
1690};
1691
1692} // end anonymous namespace
1693
1694namespace clang {
1695void checkCalledOnceParameters(AnalysisDeclContext &AC,
1696 CalledOnceCheckHandler &Handler,
1697 bool CheckConventionalParameters) {
1698 CalledOnceChecker::check(AC, Handler, CheckConventionalParameters);
1699}
1700} // end namespace clang

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/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 ExtQuals;
61class QualType;
62class ConceptDecl;
63class TagDecl;
64class TemplateParameterList;
65class Type;
66
67enum {
68 TypeAlignmentInBits = 4,
69 TypeAlignment = 1 << TypeAlignmentInBits
70};
71
72namespace serialization {
73 template <class T> class AbstractTypeReader;
74 template <class T> class AbstractTypeWriter;
75}
76
77} // namespace clang
78
79namespace llvm {
80
81 template <typename T>
82 struct PointerLikeTypeTraits;
83 template<>
84 struct PointerLikeTypeTraits< ::clang::Type*> {
85 static inline void *getAsVoidPointer(::clang::Type *P) { return P; }
86
87 static inline ::clang::Type *getFromVoidPointer(void *P) {
88 return static_cast< ::clang::Type*>(P);
89 }
90
91 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
92 };
93
94 template<>
95 struct PointerLikeTypeTraits< ::clang::ExtQuals*> {
96 static inline void *getAsVoidPointer(::clang::ExtQuals *P) { return P; }
97
98 static inline ::clang::ExtQuals *getFromVoidPointer(void *P) {
99 return static_cast< ::clang::ExtQuals*>(P);
100 }
101
102 static constexpr int NumLowBitsAvailable = clang::TypeAlignmentInBits;
103 };
104
105} // namespace llvm
106
107namespace clang {
108
109class ASTContext;
110template <typename> class CanQual;
111class CXXRecordDecl;
112class DeclContext;
113class EnumDecl;
114class Expr;
115class ExtQualsTypeCommonBase;
116class FunctionDecl;
117class IdentifierInfo;
118class NamedDecl;
119class ObjCInterfaceDecl;
120class ObjCProtocolDecl;
121class ObjCTypeParamDecl;
122struct PrintingPolicy;
123class RecordDecl;
124class Stmt;
125class TagDecl;
126class TemplateArgument;
127class TemplateArgumentListInfo;
128class TemplateArgumentLoc;
129class TemplateTypeParmDecl;
130class TypedefNameDecl;
131class UnresolvedUsingTypenameDecl;
132
133using CanQualType = CanQual<Type>;
134
135// Provide forward declarations for all of the *Type classes.
136#define TYPE(Class, Base) class Class##Type;
137#include "clang/AST/TypeNodes.inc"
138
139/// The collection of all-type qualifiers we support.
140/// Clang supports five independent qualifiers:
141/// * C99: const, volatile, and restrict
142/// * MS: __unaligned
143/// * Embedded C (TR18037): address spaces
144/// * Objective C: the GC attributes (none, weak, or strong)
145class Qualifiers {
146public:
147 enum TQ { // NOTE: These flags must be kept in sync with DeclSpec::TQ.
148 Const = 0x1,
149 Restrict = 0x2,
150 Volatile = 0x4,
151 CVRMask = Const | Volatile | Restrict
152 };
153
154 enum GC {
155 GCNone = 0,
156 Weak,
157 Strong
158 };
159
160 enum ObjCLifetime {
161 /// There is no lifetime qualification on this type.
162 OCL_None,
163
164 /// This object can be modified without requiring retains or
165 /// releases.
166 OCL_ExplicitNone,
167
168 /// Assigning into this object requires the old value to be
169 /// released and the new value to be retained. The timing of the
170 /// release of the old value is inexact: it may be moved to
171 /// immediately after the last known point where the value is
172 /// live.
173 OCL_Strong,
174
175 /// Reading or writing from this object requires a barrier call.
176 OCL_Weak,
177
178 /// Assigning into this object requires a lifetime extension.
179 OCL_Autoreleasing
180 };
181
182 enum {
183 /// The maximum supported address space number.
184 /// 23 bits should be enough for anyone.
185 MaxAddressSpace = 0x7fffffu,
186
187 /// The width of the "fast" qualifier mask.
188 FastWidth = 3,
189
190 /// The fast qualifier mask.
191 FastMask = (1 << FastWidth) - 1
192 };
193
194 /// Returns the common set of qualifiers while removing them from
195 /// the given sets.
196 static Qualifiers removeCommonQualifiers(Qualifiers &L, Qualifiers &R) {
197 // If both are only CVR-qualified, bit operations are sufficient.
198 if (!(L.Mask & ~CVRMask) && !(R.Mask & ~CVRMask)) {
199 Qualifiers Q;
200 Q.Mask = L.Mask & R.Mask;
201 L.Mask &= ~Q.Mask;
202 R.Mask &= ~Q.Mask;
203 return Q;
204 }
205
206 Qualifiers Q;
207 unsigned CommonCRV = L.getCVRQualifiers() & R.getCVRQualifiers();
208 Q.addCVRQualifiers(CommonCRV);
209 L.removeCVRQualifiers(CommonCRV);
210 R.removeCVRQualifiers(CommonCRV);
211
212 if (L.getObjCGCAttr() == R.getObjCGCAttr()) {
213 Q.setObjCGCAttr(L.getObjCGCAttr());
214 L.removeObjCGCAttr();
215 R.removeObjCGCAttr();
216 }
217
218 if (L.getObjCLifetime() == R.getObjCLifetime()) {
219 Q.setObjCLifetime(L.getObjCLifetime());
220 L.removeObjCLifetime();
221 R.removeObjCLifetime();
222 }
223
224 if (L.getAddressSpace() == R.getAddressSpace()) {
225 Q.setAddressSpace(L.getAddressSpace());
226 L.removeAddressSpace();
227 R.removeAddressSpace();
228 }
229 return Q;
230 }
231
232 static Qualifiers fromFastMask(unsigned Mask) {
233 Qualifiers Qs;
234 Qs.addFastQualifiers(Mask);
235 return Qs;
236 }
237
238 static Qualifiers fromCVRMask(unsigned CVR) {
239 Qualifiers Qs;
240 Qs.addCVRQualifiers(CVR);
241 return Qs;
242 }
243
244 static Qualifiers fromCVRUMask(unsigned CVRU) {
245 Qualifiers Qs;
246 Qs.addCVRUQualifiers(CVRU);
247 return Qs;
248 }
249
250 // Deserialize qualifiers from an opaque representation.
251 static Qualifiers fromOpaqueValue(unsigned opaque) {
252 Qualifiers Qs;
253 Qs.Mask = opaque;
254 return Qs;
255 }
256
257 // Serialize these qualifiers into an opaque representation.
258 unsigned getAsOpaqueValue() const {
259 return Mask;
260 }
261
262 bool hasConst() const { return Mask & Const; }
263 bool hasOnlyConst() const { return Mask == Const; }
264 void removeConst() { Mask &= ~Const; }
265 void addConst() { Mask |= Const; }
266
267 bool hasVolatile() const { return Mask & Volatile; }
268 bool hasOnlyVolatile() const { return Mask == Volatile; }
269 void removeVolatile() { Mask &= ~Volatile; }
270 void addVolatile() { Mask |= Volatile; }
271
272 bool hasRestrict() const { return Mask & Restrict; }
273 bool hasOnlyRestrict() const { return Mask == Restrict; }
274 void removeRestrict() { Mask &= ~Restrict; }
275 void addRestrict() { Mask |= Restrict; }
276
277 bool hasCVRQualifiers() const { return getCVRQualifiers(); }
278 unsigned getCVRQualifiers() const { return Mask & CVRMask; }
279 unsigned getCVRUQualifiers() const { return Mask & (CVRMask | UMask); }
280
281 void setCVRQualifiers(unsigned mask) {
282 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 282, __PRETTY_FUNCTION__))
;
283 Mask = (Mask & ~CVRMask) | mask;
284 }
285 void removeCVRQualifiers(unsigned mask) {
286 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 286, __PRETTY_FUNCTION__))
;
287 Mask &= ~mask;
288 }
289 void removeCVRQualifiers() {
290 removeCVRQualifiers(CVRMask);
291 }
292 void addCVRQualifiers(unsigned mask) {
293 assert(!(mask & ~CVRMask) && "bitmask contains non-CVR bits")((!(mask & ~CVRMask) && "bitmask contains non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask) && \"bitmask contains non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 293, __PRETTY_FUNCTION__))
;
294 Mask |= mask;
295 }
296 void addCVRUQualifiers(unsigned mask) {
297 assert(!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits")((!(mask & ~CVRMask & ~UMask) && "bitmask contains non-CVRU bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~CVRMask & ~UMask) && \"bitmask contains non-CVRU bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 297, __PRETTY_FUNCTION__))
;
298 Mask |= mask;
299 }
300
301 bool hasUnaligned() const { return Mask & UMask; }
302 void setUnaligned(bool flag) {
303 Mask = (Mask & ~UMask) | (flag ? UMask : 0);
304 }
305 void removeUnaligned() { Mask &= ~UMask; }
306 void addUnaligned() { Mask |= UMask; }
307
308 bool hasObjCGCAttr() const { return Mask & GCAttrMask; }
309 GC getObjCGCAttr() const { return GC((Mask & GCAttrMask) >> GCAttrShift); }
310 void setObjCGCAttr(GC type) {
311 Mask = (Mask & ~GCAttrMask) | (type << GCAttrShift);
312 }
313 void removeObjCGCAttr() { setObjCGCAttr(GCNone); }
314 void addObjCGCAttr(GC type) {
315 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 315, __PRETTY_FUNCTION__))
;
316 setObjCGCAttr(type);
317 }
318 Qualifiers withoutObjCGCAttr() const {
319 Qualifiers qs = *this;
320 qs.removeObjCGCAttr();
321 return qs;
322 }
323 Qualifiers withoutObjCLifetime() const {
324 Qualifiers qs = *this;
325 qs.removeObjCLifetime();
326 return qs;
327 }
328 Qualifiers withoutAddressSpace() const {
329 Qualifiers qs = *this;
330 qs.removeAddressSpace();
331 return qs;
332 }
333
334 bool hasObjCLifetime() const { return Mask & LifetimeMask; }
335 ObjCLifetime getObjCLifetime() const {
336 return ObjCLifetime((Mask & LifetimeMask) >> LifetimeShift);
337 }
338 void setObjCLifetime(ObjCLifetime type) {
339 Mask = (Mask & ~LifetimeMask) | (type << LifetimeShift);
340 }
341 void removeObjCLifetime() { setObjCLifetime(OCL_None); }
342 void addObjCLifetime(ObjCLifetime type) {
343 assert(type)((type) ? static_cast<void> (0) : __assert_fail ("type"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 343, __PRETTY_FUNCTION__))
;
344 assert(!hasObjCLifetime())((!hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("!hasObjCLifetime()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 344, __PRETTY_FUNCTION__))
;
345 Mask |= (type << LifetimeShift);
346 }
347
348 /// True if the lifetime is neither None or ExplicitNone.
349 bool hasNonTrivialObjCLifetime() const {
350 ObjCLifetime lifetime = getObjCLifetime();
351 return (lifetime > OCL_ExplicitNone);
352 }
353
354 /// True if the lifetime is either strong or weak.
355 bool hasStrongOrWeakObjCLifetime() const {
356 ObjCLifetime lifetime = getObjCLifetime();
357 return (lifetime == OCL_Strong || lifetime == OCL_Weak);
358 }
359
360 bool hasAddressSpace() const { return Mask & AddressSpaceMask; }
361 LangAS getAddressSpace() const {
362 return static_cast<LangAS>(Mask >> AddressSpaceShift);
363 }
364 bool hasTargetSpecificAddressSpace() const {
365 return isTargetAddressSpace(getAddressSpace());
366 }
367 /// Get the address space attribute value to be printed by diagnostics.
368 unsigned getAddressSpaceAttributePrintValue() const {
369 auto Addr = getAddressSpace();
370 // This function is not supposed to be used with language specific
371 // address spaces. If that happens, the diagnostic message should consider
372 // printing the QualType instead of the address space value.
373 assert(Addr == LangAS::Default || hasTargetSpecificAddressSpace())((Addr == LangAS::Default || hasTargetSpecificAddressSpace())
? static_cast<void> (0) : __assert_fail ("Addr == LangAS::Default || hasTargetSpecificAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 373, __PRETTY_FUNCTION__))
;
374 if (Addr != LangAS::Default)
375 return toTargetAddressSpace(Addr);
376 // TODO: The diagnostic messages where Addr may be 0 should be fixed
377 // since it cannot differentiate the situation where 0 denotes the default
378 // address space or user specified __attribute__((address_space(0))).
379 return 0;
380 }
381 void setAddressSpace(LangAS space) {
382 assert((unsigned)space <= MaxAddressSpace)(((unsigned)space <= MaxAddressSpace) ? static_cast<void
> (0) : __assert_fail ("(unsigned)space <= MaxAddressSpace"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 382, __PRETTY_FUNCTION__))
;
383 Mask = (Mask & ~AddressSpaceMask)
384 | (((uint32_t) space) << AddressSpaceShift);
385 }
386 void removeAddressSpace() { setAddressSpace(LangAS::Default); }
387 void addAddressSpace(LangAS space) {
388 assert(space != LangAS::Default)((space != LangAS::Default) ? static_cast<void> (0) : __assert_fail
("space != LangAS::Default", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 388, __PRETTY_FUNCTION__))
;
389 setAddressSpace(space);
390 }
391
392 // Fast qualifiers are those that can be allocated directly
393 // on a QualType object.
394 bool hasFastQualifiers() const { return getFastQualifiers(); }
395 unsigned getFastQualifiers() const { return Mask & FastMask; }
396 void setFastQualifiers(unsigned mask) {
397 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 397, __PRETTY_FUNCTION__))
;
398 Mask = (Mask & ~FastMask) | mask;
399 }
400 void removeFastQualifiers(unsigned mask) {
401 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 401, __PRETTY_FUNCTION__))
;
402 Mask &= ~mask;
403 }
404 void removeFastQualifiers() {
405 removeFastQualifiers(FastMask);
406 }
407 void addFastQualifiers(unsigned mask) {
408 assert(!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits")((!(mask & ~FastMask) && "bitmask contains non-fast qualifier bits"
) ? static_cast<void> (0) : __assert_fail ("!(mask & ~FastMask) && \"bitmask contains non-fast qualifier bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 408, __PRETTY_FUNCTION__))
;
409 Mask |= mask;
410 }
411
412 /// Return true if the set contains any qualifiers which require an ExtQuals
413 /// node to be allocated.
414 bool hasNonFastQualifiers() const { return Mask & ~FastMask; }
415 Qualifiers getNonFastQualifiers() const {
416 Qualifiers Quals = *this;
417 Quals.setFastQualifiers(0);
418 return Quals;
419 }
420
421 /// Return true if the set contains any qualifiers.
422 bool hasQualifiers() const { return Mask; }
423 bool empty() const { return !Mask; }
424
425 /// Add the qualifiers from the given set to this set.
426 void addQualifiers(Qualifiers Q) {
427 // If the other set doesn't have any non-boolean qualifiers, just
428 // bit-or it in.
429 if (!(Q.Mask & ~CVRMask))
430 Mask |= Q.Mask;
431 else {
432 Mask |= (Q.Mask & CVRMask);
433 if (Q.hasAddressSpace())
434 addAddressSpace(Q.getAddressSpace());
435 if (Q.hasObjCGCAttr())
436 addObjCGCAttr(Q.getObjCGCAttr());
437 if (Q.hasObjCLifetime())
438 addObjCLifetime(Q.getObjCLifetime());
439 }
440 }
441
442 /// Remove the qualifiers from the given set from this set.
443 void removeQualifiers(Qualifiers Q) {
444 // If the other set doesn't have any non-boolean qualifiers, just
445 // bit-and the inverse in.
446 if (!(Q.Mask & ~CVRMask))
447 Mask &= ~Q.Mask;
448 else {
449 Mask &= ~(Q.Mask & CVRMask);
450 if (getObjCGCAttr() == Q.getObjCGCAttr())
451 removeObjCGCAttr();
452 if (getObjCLifetime() == Q.getObjCLifetime())
453 removeObjCLifetime();
454 if (getAddressSpace() == Q.getAddressSpace())
455 removeAddressSpace();
456 }
457 }
458
459 /// Add the qualifiers from the given set to this set, given that
460 /// they don't conflict.
461 void addConsistentQualifiers(Qualifiers qs) {
462 assert(getAddressSpace() == qs.getAddressSpace() ||((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 463, __PRETTY_FUNCTION__))
463 !hasAddressSpace() || !qs.hasAddressSpace())((getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace
() || !qs.hasAddressSpace()) ? static_cast<void> (0) : __assert_fail
("getAddressSpace() == qs.getAddressSpace() || !hasAddressSpace() || !qs.hasAddressSpace()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 463, __PRETTY_FUNCTION__))
;
464 assert(getObjCGCAttr() == qs.getObjCGCAttr() ||((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 465, __PRETTY_FUNCTION__))
465 !hasObjCGCAttr() || !qs.hasObjCGCAttr())((getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() ||
!qs.hasObjCGCAttr()) ? static_cast<void> (0) : __assert_fail
("getObjCGCAttr() == qs.getObjCGCAttr() || !hasObjCGCAttr() || !qs.hasObjCGCAttr()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 465, __PRETTY_FUNCTION__))
;
466 assert(getObjCLifetime() == qs.getObjCLifetime() ||((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 467, __PRETTY_FUNCTION__))
467 !hasObjCLifetime() || !qs.hasObjCLifetime())((getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime
() || !qs.hasObjCLifetime()) ? static_cast<void> (0) : __assert_fail
("getObjCLifetime() == qs.getObjCLifetime() || !hasObjCLifetime() || !qs.hasObjCLifetime()"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 467, __PRETTY_FUNCTION__))
;
468 Mask |= qs.Mask;
469 }
470
471 /// Returns true if address space A is equal to or a superset of B.
472 /// OpenCL v2.0 defines conversion rules (OpenCLC v2.0 s6.5.5) and notion of
473 /// overlapping address spaces.
474 /// CL1.1 or CL1.2:
475 /// every address space is a superset of itself.
476 /// CL2.0 adds:
477 /// __generic is a superset of any address space except for __constant.
478 static bool isAddressSpaceSupersetOf(LangAS A, LangAS B) {
479 // Address spaces must match exactly.
480 return A == B ||
481 // Otherwise in OpenCLC v2.0 s6.5.5: every address space except
482 // for __constant can be used as __generic.
483 (A == LangAS::opencl_generic && B != LangAS::opencl_constant) ||
484 // We also define global_device and global_host address spaces,
485 // to distinguish global pointers allocated on host from pointers
486 // allocated on device, which are a subset of __global.
487 (A == LangAS::opencl_global && (B == LangAS::opencl_global_device ||
488 B == LangAS::opencl_global_host)) ||
489 // Consider pointer size address spaces to be equivalent to default.
490 ((isPtrSizeAddressSpace(A) || A == LangAS::Default) &&
491 (isPtrSizeAddressSpace(B) || B == LangAS::Default));
492 }
493
494 /// Returns true if the address space in these qualifiers is equal to or
495 /// a superset of the address space in the argument qualifiers.
496 bool isAddressSpaceSupersetOf(Qualifiers other) const {
497 return isAddressSpaceSupersetOf(getAddressSpace(), other.getAddressSpace());
498 }
499
500 /// Determines if these qualifiers compatibly include another set.
501 /// Generally this answers the question of whether an object with the other
502 /// qualifiers can be safely used as an object with these qualifiers.
503 bool compatiblyIncludes(Qualifiers other) const {
504 return isAddressSpaceSupersetOf(other) &&
505 // ObjC GC qualifiers can match, be added, or be removed, but can't
506 // be changed.
507 (getObjCGCAttr() == other.getObjCGCAttr() || !hasObjCGCAttr() ||
508 !other.hasObjCGCAttr()) &&
509 // ObjC lifetime qualifiers must match exactly.
510 getObjCLifetime() == other.getObjCLifetime() &&
511 // CVR qualifiers may subset.
512 (((Mask & CVRMask) | (other.Mask & CVRMask)) == (Mask & CVRMask)) &&
513 // U qualifier may superset.
514 (!other.hasUnaligned() || hasUnaligned());
515 }
516
517 /// Determines if these qualifiers compatibly include another set of
518 /// qualifiers from the narrow perspective of Objective-C ARC lifetime.
519 ///
520 /// One set of Objective-C lifetime qualifiers compatibly includes the other
521 /// if the lifetime qualifiers match, or if both are non-__weak and the
522 /// including set also contains the 'const' qualifier, or both are non-__weak
523 /// and one is None (which can only happen in non-ARC modes).
524 bool compatiblyIncludesObjCLifetime(Qualifiers other) const {
525 if (getObjCLifetime() == other.getObjCLifetime())
526 return true;
527
528 if (getObjCLifetime() == OCL_Weak || other.getObjCLifetime() == OCL_Weak)
529 return false;
530
531 if (getObjCLifetime() == OCL_None || other.getObjCLifetime() == OCL_None)
532 return true;
533
534 return hasConst();
535 }
536
537 /// Determine whether this set of qualifiers is a strict superset of
538 /// another set of qualifiers, not considering qualifier compatibility.
539 bool isStrictSupersetOf(Qualifiers Other) const;
540
541 bool operator==(Qualifiers Other) const { return Mask == Other.Mask; }
542 bool operator!=(Qualifiers Other) const { return Mask != Other.Mask; }
543
544 explicit operator bool() const { return hasQualifiers(); }
545
546 Qualifiers &operator+=(Qualifiers R) {
547 addQualifiers(R);
548 return *this;
549 }
550
551 // Union two qualifier sets. If an enumerated qualifier appears
552 // in both sets, use the one from the right.
553 friend Qualifiers operator+(Qualifiers L, Qualifiers R) {
554 L += R;
555 return L;
556 }
557
558 Qualifiers &operator-=(Qualifiers R) {
559 removeQualifiers(R);
560 return *this;
561 }
562
563 /// Compute the difference between two qualifier sets.
564 friend Qualifiers operator-(Qualifiers L, Qualifiers R) {
565 L -= R;
566 return L;
567 }
568
569 std::string getAsString() const;
570 std::string getAsString(const PrintingPolicy &Policy) const;
571
572 static std::string getAddrSpaceAsString(LangAS AS);
573
574 bool isEmptyWhenPrinted(const PrintingPolicy &Policy) const;
575 void print(raw_ostream &OS, const PrintingPolicy &Policy,
576 bool appendSpaceIfNonEmpty = false) const;
577
578 void Profile(llvm::FoldingSetNodeID &ID) const {
579 ID.AddInteger(Mask);
580 }
581
582private:
583 // bits: |0 1 2|3|4 .. 5|6 .. 8|9 ... 31|
584 // |C R V|U|GCAttr|Lifetime|AddressSpace|
585 uint32_t Mask = 0;
586
587 static const uint32_t UMask = 0x8;
588 static const uint32_t UShift = 3;
589 static const uint32_t GCAttrMask = 0x30;
590 static const uint32_t GCAttrShift = 4;
591 static const uint32_t LifetimeMask = 0x1C0;
592 static const uint32_t LifetimeShift = 6;
593 static const uint32_t AddressSpaceMask =
594 ~(CVRMask | UMask | GCAttrMask | LifetimeMask);
595 static const uint32_t AddressSpaceShift = 9;
596};
597
598/// A std::pair-like structure for storing a qualified type split
599/// into its local qualifiers and its locally-unqualified type.
600struct SplitQualType {
601 /// The locally-unqualified type.
602 const Type *Ty = nullptr;
603
604 /// The local qualifiers.
605 Qualifiers Quals;
606
607 SplitQualType() = default;
608 SplitQualType(const Type *ty, Qualifiers qs) : Ty(ty), Quals(qs) {}
609
610 SplitQualType getSingleStepDesugaredType() const; // end of this file
611
612 // Make std::tie work.
613 std::pair<const Type *,Qualifiers> asPair() const {
614 return std::pair<const Type *, Qualifiers>(Ty, Quals);
615 }
616
617 friend bool operator==(SplitQualType a, SplitQualType b) {
618 return a.Ty == b.Ty && a.Quals == b.Quals;
619 }
620 friend bool operator!=(SplitQualType a, SplitQualType b) {
621 return a.Ty != b.Ty || a.Quals != b.Quals;
622 }
623};
624
625/// The kind of type we are substituting Objective-C type arguments into.
626///
627/// The kind of substitution affects the replacement of type parameters when
628/// no concrete type information is provided, e.g., when dealing with an
629/// unspecialized type.
630enum class ObjCSubstitutionContext {
631 /// An ordinary type.
632 Ordinary,
633
634 /// The result type of a method or function.
635 Result,
636
637 /// The parameter type of a method or function.
638 Parameter,
639
640 /// The type of a property.
641 Property,
642
643 /// The superclass of a type.
644 Superclass,
645};
646
647/// A (possibly-)qualified type.
648///
649/// For efficiency, we don't store CV-qualified types as nodes on their
650/// own: instead each reference to a type stores the qualifiers. This
651/// greatly reduces the number of nodes we need to allocate for types (for
652/// example we only need one for 'int', 'const int', 'volatile int',
653/// 'const volatile int', etc).
654///
655/// As an added efficiency bonus, instead of making this a pair, we
656/// just store the two bits we care about in the low bits of the
657/// pointer. To handle the packing/unpacking, we make QualType be a
658/// simple wrapper class that acts like a smart pointer. A third bit
659/// indicates whether there are extended qualifiers present, in which
660/// case the pointer points to a special structure.
661class QualType {
662 friend class QualifierCollector;
663
664 // Thankfully, these are efficiently composable.
665 llvm::PointerIntPair<llvm::PointerUnion<const Type *, const ExtQuals *>,
666 Qualifiers::FastWidth> Value;
667
668 const ExtQuals *getExtQualsUnsafe() const {
669 return Value.getPointer().get<const ExtQuals*>();
670 }
671
672 const Type *getTypePtrUnsafe() const {
673 return Value.getPointer().get<const Type*>();
674 }
675
676 const ExtQualsTypeCommonBase *getCommonPtr() const {
677 assert(!isNull() && "Cannot retrieve a NULL type pointer")((!isNull() && "Cannot retrieve a NULL type pointer")
? static_cast<void> (0) : __assert_fail ("!isNull() && \"Cannot retrieve a NULL type pointer\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 677, __PRETTY_FUNCTION__))
;
678 auto CommonPtrVal = reinterpret_cast<uintptr_t>(Value.getOpaqueValue());
679 CommonPtrVal &= ~(uintptr_t)((1 << TypeAlignmentInBits) - 1);
680 return reinterpret_cast<ExtQualsTypeCommonBase*>(CommonPtrVal);
681 }
682
683public:
684 QualType() = default;
685 QualType(const Type *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
686 QualType(const ExtQuals *Ptr, unsigned Quals) : Value(Ptr, Quals) {}
687
688 unsigned getLocalFastQualifiers() const { return Value.getInt(); }
689 void setLocalFastQualifiers(unsigned Quals) { Value.setInt(Quals); }
690
691 /// Retrieves a pointer to the underlying (unqualified) type.
692 ///
693 /// This function requires that the type not be NULL. If the type might be
694 /// NULL, use the (slightly less efficient) \c getTypePtrOrNull().
695 const Type *getTypePtr() const;
696
697 const Type *getTypePtrOrNull() const;
698
699 /// Retrieves a pointer to the name of the base type.
700 const IdentifierInfo *getBaseTypeIdentifier() const;
701
702 /// Divides a QualType into its unqualified type and a set of local
703 /// qualifiers.
704 SplitQualType split() const;
705
706 void *getAsOpaquePtr() const { return Value.getOpaqueValue(); }
707
708 static QualType getFromOpaquePtr(const void *Ptr) {
709 QualType T;
710 T.Value.setFromOpaqueValue(const_cast<void*>(Ptr));
711 return T;
712 }
713
714 const Type &operator*() const {
715 return *getTypePtr();
716 }
717
718 const Type *operator->() const {
719 return getTypePtr();
720 }
721
722 bool isCanonical() const;
723 bool isCanonicalAsParam() const;
724
725 /// Return true if this QualType doesn't point to a type yet.
726 bool isNull() const {
727 return Value.getPointer().isNull();
728 }
729
730 /// Determine whether this particular QualType instance has the
731 /// "const" qualifier set, without looking through typedefs that may have
732 /// added "const" at a different level.
733 bool isLocalConstQualified() const {
734 return (getLocalFastQualifiers() & Qualifiers::Const);
735 }
736
737 /// Determine whether this type is const-qualified.
738 bool isConstQualified() const;
739
740 /// Determine whether this particular QualType instance has the
741 /// "restrict" qualifier set, without looking through typedefs that may have
742 /// added "restrict" at a different level.
743 bool isLocalRestrictQualified() const {
744 return (getLocalFastQualifiers() & Qualifiers::Restrict);
745 }
746
747 /// Determine whether this type is restrict-qualified.
748 bool isRestrictQualified() const;
749
750 /// Determine whether this particular QualType instance has the
751 /// "volatile" qualifier set, without looking through typedefs that may have
752 /// added "volatile" at a different level.
753 bool isLocalVolatileQualified() const {
754 return (getLocalFastQualifiers() & Qualifiers::Volatile);
755 }
756
757 /// Determine whether this type is volatile-qualified.
758 bool isVolatileQualified() const;
759
760 /// Determine whether this particular QualType instance has any
761 /// qualifiers, without looking through any typedefs that might add
762 /// qualifiers at a different level.
763 bool hasLocalQualifiers() const {
764 return getLocalFastQualifiers() || hasLocalNonFastQualifiers();
765 }
766
767 /// Determine whether this type has any qualifiers.
768 bool hasQualifiers() const;
769
770 /// Determine whether this particular QualType instance has any
771 /// "non-fast" qualifiers, e.g., those that are stored in an ExtQualType
772 /// instance.
773 bool hasLocalNonFastQualifiers() const {
774 return Value.getPointer().is<const ExtQuals*>();
775 }
776
777 /// Retrieve the set of qualifiers local to this particular QualType
778 /// instance, not including any qualifiers acquired through typedefs or
779 /// other sugar.
780 Qualifiers getLocalQualifiers() const;
781
782 /// Retrieve the set of qualifiers applied to this type.
783 Qualifiers getQualifiers() const;
784
785 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
786 /// local to this particular QualType instance, not including any qualifiers
787 /// acquired through typedefs or other sugar.
788 unsigned getLocalCVRQualifiers() const {
789 return getLocalFastQualifiers();
790 }
791
792 /// Retrieve the set of CVR (const-volatile-restrict) qualifiers
793 /// applied to this type.
794 unsigned getCVRQualifiers() const;
795
796 bool isConstant(const ASTContext& Ctx) const {
797 return QualType::isConstant(*this, Ctx);
798 }
799
800 /// Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
801 bool isPODType(const ASTContext &Context) const;
802
803 /// Return true if this is a POD type according to the rules of the C++98
804 /// standard, regardless of the current compilation's language.
805 bool isCXX98PODType(const ASTContext &Context) const;
806
807 /// Return true if this is a POD type according to the more relaxed rules
808 /// of the C++11 standard, regardless of the current compilation's language.
809 /// (C++0x [basic.types]p9). Note that, unlike
810 /// CXXRecordDecl::isCXX11StandardLayout, this takes DRs into account.
811 bool isCXX11PODType(const ASTContext &Context) const;
812
813 /// Return true if this is a trivial type per (C++0x [basic.types]p9)
814 bool isTrivialType(const ASTContext &Context) const;
815
816 /// Return true if this is a trivially copyable type (C++0x [basic.types]p9)
817 bool isTriviallyCopyableType(const ASTContext &Context) const;
818
819
820 /// Returns true if it is a class and it might be dynamic.
821 bool mayBeDynamicClass() const;
822
823 /// Returns true if it is not a class or if the class might not be dynamic.
824 bool mayBeNotDynamicClass() const;
825
826 // Don't promise in the API that anything besides 'const' can be
827 // easily added.
828
829 /// Add the `const` type qualifier to this QualType.
830 void addConst() {
831 addFastQualifiers(Qualifiers::Const);
832 }
833 QualType withConst() const {
834 return withFastQualifiers(Qualifiers::Const);
835 }
836
837 /// Add the `volatile` type qualifier to this QualType.
838 void addVolatile() {
839 addFastQualifiers(Qualifiers::Volatile);
840 }
841 QualType withVolatile() const {
842 return withFastQualifiers(Qualifiers::Volatile);
843 }
844
845 /// Add the `restrict` qualifier to this QualType.
846 void addRestrict() {
847 addFastQualifiers(Qualifiers::Restrict);
848 }
849 QualType withRestrict() const {
850 return withFastQualifiers(Qualifiers::Restrict);
851 }
852
853 QualType withCVRQualifiers(unsigned CVR) const {
854 return withFastQualifiers(CVR);
855 }
856
857 void addFastQualifiers(unsigned TQs) {
858 assert(!(TQs & ~Qualifiers::FastMask)((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 859, __PRETTY_FUNCTION__))
859 && "non-fast qualifier bits set in mask!")((!(TQs & ~Qualifiers::FastMask) && "non-fast qualifier bits set in mask!"
) ? static_cast<void> (0) : __assert_fail ("!(TQs & ~Qualifiers::FastMask) && \"non-fast qualifier bits set in mask!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 859, __PRETTY_FUNCTION__))
;
860 Value.setInt(Value.getInt() | TQs);
861 }
862
863 void removeLocalConst();
864 void removeLocalVolatile();
865 void removeLocalRestrict();
866 void removeLocalCVRQualifiers(unsigned Mask);
867
868 void removeLocalFastQualifiers() { Value.setInt(0); }
869 void removeLocalFastQualifiers(unsigned Mask) {
870 assert(!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers")((!(Mask & ~Qualifiers::FastMask) && "mask has non-fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::FastMask) && \"mask has non-fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 870, __PRETTY_FUNCTION__))
;
871 Value.setInt(Value.getInt() & ~Mask);
872 }
873
874 // Creates a type with the given qualifiers in addition to any
875 // qualifiers already on this type.
876 QualType withFastQualifiers(unsigned TQs) const {
877 QualType T = *this;
878 T.addFastQualifiers(TQs);
879 return T;
880 }
881
882 // Creates a type with exactly the given fast qualifiers, removing
883 // any existing fast qualifiers.
884 QualType withExactLocalFastQualifiers(unsigned TQs) const {
885 return withoutLocalFastQualifiers().withFastQualifiers(TQs);
886 }
887
888 // Removes fast qualifiers, but leaves any extended qualifiers in place.
889 QualType withoutLocalFastQualifiers() const {
890 QualType T = *this;
891 T.removeLocalFastQualifiers();
892 return T;
893 }
894
895 QualType getCanonicalType() const;
896
897 /// Return this type with all of the instance-specific qualifiers
898 /// removed, but without removing any qualifiers that may have been applied
899 /// through typedefs.
900 QualType getLocalUnqualifiedType() const { return QualType(getTypePtr(), 0); }
901
902 /// Retrieve the unqualified variant of the given type,
903 /// removing as little sugar as possible.
904 ///
905 /// This routine looks through various kinds of sugar to find the
906 /// least-desugared type that is unqualified. For example, given:
907 ///
908 /// \code
909 /// typedef int Integer;
910 /// typedef const Integer CInteger;
911 /// typedef CInteger DifferenceType;
912 /// \endcode
913 ///
914 /// Executing \c getUnqualifiedType() on the type \c DifferenceType will
915 /// desugar until we hit the type \c Integer, which has no qualifiers on it.
916 ///
917 /// The resulting type might still be qualified if it's sugar for an array
918 /// type. To strip qualifiers even from within a sugared array type, use
919 /// ASTContext::getUnqualifiedArrayType.
920 inline QualType getUnqualifiedType() const;
921
922 /// Retrieve the unqualified variant of the given type, removing as little
923 /// sugar as possible.
924 ///
925 /// Like getUnqualifiedType(), but also returns the set of
926 /// qualifiers that were built up.
927 ///
928 /// The resulting type might still be qualified if it's sugar for an array
929 /// type. To strip qualifiers even from within a sugared array type, use
930 /// ASTContext::getUnqualifiedArrayType.
931 inline SplitQualType getSplitUnqualifiedType() const;
932
933 /// Determine whether this type is more qualified than the other
934 /// given type, requiring exact equality for non-CVR qualifiers.
935 bool isMoreQualifiedThan(QualType Other) const;
936
937 /// Determine whether this type is at least as qualified as the other
938 /// given type, requiring exact equality for non-CVR qualifiers.
939 bool isAtLeastAsQualifiedAs(QualType Other) const;
940
941 QualType getNonReferenceType() const;
942
943 /// Determine the type of a (typically non-lvalue) expression with the
944 /// specified result type.
945 ///
946 /// This routine should be used for expressions for which the return type is
947 /// explicitly specified (e.g., in a cast or call) and isn't necessarily
948 /// an lvalue. It removes a top-level reference (since there are no
949 /// expressions of reference type) and deletes top-level cvr-qualifiers
950 /// from non-class types (in C++) or all types (in C).
951 QualType getNonLValueExprType(const ASTContext &Context) const;
952
953 /// Remove an outer pack expansion type (if any) from this type. Used as part
954 /// of converting the type of a declaration to the type of an expression that
955 /// references that expression. It's meaningless for an expression to have a
956 /// pack expansion type.
957 QualType getNonPackExpansionType() const;
958
959 /// Return the specified type with any "sugar" removed from
960 /// the type. This takes off typedefs, typeof's etc. If the outer level of
961 /// the type is already concrete, it returns it unmodified. This is similar
962 /// to getting the canonical type, but it doesn't remove *all* typedefs. For
963 /// example, it returns "T*" as "T*", (not as "int*"), because the pointer is
964 /// concrete.
965 ///
966 /// Qualifiers are left in place.
967 QualType getDesugaredType(const ASTContext &Context) const {
968 return getDesugaredType(*this, Context);
969 }
970
971 SplitQualType getSplitDesugaredType() const {
972 return getSplitDesugaredType(*this);
973 }
974
975 /// Return the specified type with one level of "sugar" removed from
976 /// the type.
977 ///
978 /// This routine takes off the first typedef, typeof, etc. If the outer level
979 /// of the type is already concrete, it returns it unmodified.
980 QualType getSingleStepDesugaredType(const ASTContext &Context) const {
981 return getSingleStepDesugaredTypeImpl(*this, Context);
982 }
983
984 /// Returns the specified type after dropping any
985 /// outer-level parentheses.
986 QualType IgnoreParens() const {
987 if (isa<ParenType>(*this))
988 return QualType::IgnoreParens(*this);
989 return *this;
990 }
991
992 /// Indicate whether the specified types and qualifiers are identical.
993 friend bool operator==(const QualType &LHS, const QualType &RHS) {
994 return LHS.Value == RHS.Value;
995 }
996 friend bool operator!=(const QualType &LHS, const QualType &RHS) {
997 return LHS.Value != RHS.Value;
998 }
999 friend bool operator<(const QualType &LHS, const QualType &RHS) {
1000 return LHS.Value < RHS.Value;
1001 }
1002
1003 static std::string getAsString(SplitQualType split,
1004 const PrintingPolicy &Policy) {
1005 return getAsString(split.Ty, split.Quals, Policy);
1006 }
1007 static std::string getAsString(const Type *ty, Qualifiers qs,
1008 const PrintingPolicy &Policy);
1009
1010 std::string getAsString() const;
1011 std::string getAsString(const PrintingPolicy &Policy) const;
1012
1013 void print(raw_ostream &OS, const PrintingPolicy &Policy,
1014 const Twine &PlaceHolder = Twine(),
1015 unsigned Indentation = 0) const;
1016
1017 static void print(SplitQualType split, raw_ostream &OS,
1018 const PrintingPolicy &policy, const Twine &PlaceHolder,
1019 unsigned Indentation = 0) {
1020 return print(split.Ty, split.Quals, OS, policy, PlaceHolder, Indentation);
1021 }
1022
1023 static void print(const Type *ty, Qualifiers qs,
1024 raw_ostream &OS, const PrintingPolicy &policy,
1025 const Twine &PlaceHolder,
1026 unsigned Indentation = 0);
1027
1028 void getAsStringInternal(std::string &Str,
1029 const PrintingPolicy &Policy) const;
1030
1031 static void getAsStringInternal(SplitQualType split, std::string &out,
1032 const PrintingPolicy &policy) {
1033 return getAsStringInternal(split.Ty, split.Quals, out, policy);
1034 }
1035
1036 static void getAsStringInternal(const Type *ty, Qualifiers qs,
1037 std::string &out,
1038 const PrintingPolicy &policy);
1039
1040 class StreamedQualTypeHelper {
1041 const QualType &T;
1042 const PrintingPolicy &Policy;
1043 const Twine &PlaceHolder;
1044 unsigned Indentation;
1045
1046 public:
1047 StreamedQualTypeHelper(const QualType &T, const PrintingPolicy &Policy,
1048 const Twine &PlaceHolder, unsigned Indentation)
1049 : T(T), Policy(Policy), PlaceHolder(PlaceHolder),
1050 Indentation(Indentation) {}
1051
1052 friend raw_ostream &operator<<(raw_ostream &OS,
1053 const StreamedQualTypeHelper &SQT) {
1054 SQT.T.print(OS, SQT.Policy, SQT.PlaceHolder, SQT.Indentation);
1055 return OS;
1056 }
1057 };
1058
1059 StreamedQualTypeHelper stream(const PrintingPolicy &Policy,
1060 const Twine &PlaceHolder = Twine(),
1061 unsigned Indentation = 0) const {
1062 return StreamedQualTypeHelper(*this, Policy, PlaceHolder, Indentation);
1063 }
1064
1065 void dump(const char *s) const;
1066 void dump() const;
1067 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
1068
1069 void Profile(llvm::FoldingSetNodeID &ID) const {
1070 ID.AddPointer(getAsOpaquePtr());
1071 }
1072
1073 /// Check if this type has any address space qualifier.
1074 inline bool hasAddressSpace() const;
1075
1076 /// Return the address space of this type.
1077 inline LangAS getAddressSpace() const;
1078
1079 /// Returns true if address space qualifiers overlap with T address space
1080 /// qualifiers.
1081 /// OpenCL C defines conversion rules for pointers to different address spaces
1082 /// and notion of overlapping address spaces.
1083 /// CL1.1 or CL1.2:
1084 /// address spaces overlap iff they are they same.
1085 /// OpenCL C v2.0 s6.5.5 adds:
1086 /// __generic overlaps with any address space except for __constant.
1087 bool isAddressSpaceOverlapping(QualType T) const {
1088 Qualifiers Q = getQualifiers();
1089 Qualifiers TQ = T.getQualifiers();
1090 // Address spaces overlap if at least one of them is a superset of another
1091 return Q.isAddressSpaceSupersetOf(TQ) || TQ.isAddressSpaceSupersetOf(Q);
1092 }
1093
1094 /// Returns gc attribute of this type.
1095 inline Qualifiers::GC getObjCGCAttr() const;
1096
1097 /// true when Type is objc's weak.
1098 bool isObjCGCWeak() const {
1099 return getObjCGCAttr() == Qualifiers::Weak;
1100 }
1101
1102 /// true when Type is objc's strong.
1103 bool isObjCGCStrong() const {
1104 return getObjCGCAttr() == Qualifiers::Strong;
1105 }
1106
1107 /// Returns lifetime attribute of this type.
1108 Qualifiers::ObjCLifetime getObjCLifetime() const {
1109 return getQualifiers().getObjCLifetime();
1110 }
1111
1112 bool hasNonTrivialObjCLifetime() const {
1113 return getQualifiers().hasNonTrivialObjCLifetime();
1114 }
1115
1116 bool hasStrongOrWeakObjCLifetime() const {
1117 return getQualifiers().hasStrongOrWeakObjCLifetime();
1118 }
1119
1120 // true when Type is objc's weak and weak is enabled but ARC isn't.
1121 bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const;
1122
1123 enum PrimitiveDefaultInitializeKind {
1124 /// The type does not fall into any of the following categories. Note that
1125 /// this case is zero-valued so that values of this enum can be used as a
1126 /// boolean condition for non-triviality.
1127 PDIK_Trivial,
1128
1129 /// The type is an Objective-C retainable pointer type that is qualified
1130 /// with the ARC __strong qualifier.
1131 PDIK_ARCStrong,
1132
1133 /// The type is an Objective-C retainable pointer type that is qualified
1134 /// with the ARC __weak qualifier.
1135 PDIK_ARCWeak,
1136
1137 /// The type is a struct containing a field whose type is not PCK_Trivial.
1138 PDIK_Struct
1139 };
1140
1141 /// Functions to query basic properties of non-trivial C struct types.
1142
1143 /// Check if this is a non-trivial type that would cause a C struct
1144 /// transitively containing this type to be non-trivial to default initialize
1145 /// and return the kind.
1146 PrimitiveDefaultInitializeKind
1147 isNonTrivialToPrimitiveDefaultInitialize() const;
1148
1149 enum PrimitiveCopyKind {
1150 /// The type does not fall into any of the following categories. Note that
1151 /// this case is zero-valued so that values of this enum can be used as a
1152 /// boolean condition for non-triviality.
1153 PCK_Trivial,
1154
1155 /// The type would be trivial except that it is volatile-qualified. Types
1156 /// that fall into one of the other non-trivial cases may additionally be
1157 /// volatile-qualified.
1158 PCK_VolatileTrivial,
1159
1160 /// The type is an Objective-C retainable pointer type that is qualified
1161 /// with the ARC __strong qualifier.
1162 PCK_ARCStrong,
1163
1164 /// The type is an Objective-C retainable pointer type that is qualified
1165 /// with the ARC __weak qualifier.
1166 PCK_ARCWeak,
1167
1168 /// The type is a struct containing a field whose type is neither
1169 /// PCK_Trivial nor PCK_VolatileTrivial.
1170 /// Note that a C++ struct type does not necessarily match this; C++ copying
1171 /// semantics are too complex to express here, in part because they depend
1172 /// on the exact constructor or assignment operator that is chosen by
1173 /// overload resolution to do the copy.
1174 PCK_Struct
1175 };
1176
1177 /// Check if this is a non-trivial type that would cause a C struct
1178 /// transitively containing this type to be non-trivial to copy and return the
1179 /// kind.
1180 PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const;
1181
1182 /// Check if this is a non-trivial type that would cause a C struct
1183 /// transitively containing this type to be non-trivial to destructively
1184 /// move and return the kind. Destructive move in this context is a C++-style
1185 /// move in which the source object is placed in a valid but unspecified state
1186 /// after it is moved, as opposed to a truly destructive move in which the
1187 /// source object is placed in an uninitialized state.
1188 PrimitiveCopyKind isNonTrivialToPrimitiveDestructiveMove() const;
1189
1190 enum DestructionKind {
1191 DK_none,
1192 DK_cxx_destructor,
1193 DK_objc_strong_lifetime,
1194 DK_objc_weak_lifetime,
1195 DK_nontrivial_c_struct
1196 };
1197
1198 /// Returns a nonzero value if objects of this type require
1199 /// non-trivial work to clean up after. Non-zero because it's
1200 /// conceivable that qualifiers (objc_gc(weak)?) could make
1201 /// something require destruction.
1202 DestructionKind isDestructedType() const {
1203 return isDestructedTypeImpl(*this);
1204 }
1205
1206 /// Check if this is or contains a C union that is non-trivial to
1207 /// default-initialize, which is a union that has a member that is non-trivial
1208 /// to default-initialize. If this returns true,
1209 /// isNonTrivialToPrimitiveDefaultInitialize returns PDIK_Struct.
1210 bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const;
1211
1212 /// Check if this is or contains a C union that is non-trivial to destruct,
1213 /// which is a union that has a member that is non-trivial to destruct. If
1214 /// this returns true, isDestructedType returns DK_nontrivial_c_struct.
1215 bool hasNonTrivialToPrimitiveDestructCUnion() const;
1216
1217 /// Check if this is or contains a C union that is non-trivial to copy, which
1218 /// is a union that has a member that is non-trivial to copy. If this returns
1219 /// true, isNonTrivialToPrimitiveCopy returns PCK_Struct.
1220 bool hasNonTrivialToPrimitiveCopyCUnion() const;
1221
1222 /// Determine whether expressions of the given type are forbidden
1223 /// from being lvalues in C.
1224 ///
1225 /// The expression types that are forbidden to be lvalues are:
1226 /// - 'void', but not qualified void
1227 /// - function types
1228 ///
1229 /// The exact rule here is C99 6.3.2.1:
1230 /// An lvalue is an expression with an object type or an incomplete
1231 /// type other than void.
1232 bool isCForbiddenLValueType() const;
1233
1234 /// Substitute type arguments for the Objective-C type parameters used in the
1235 /// subject type.
1236 ///
1237 /// \param ctx ASTContext in which the type exists.
1238 ///
1239 /// \param typeArgs The type arguments that will be substituted for the
1240 /// Objective-C type parameters in the subject type, which are generally
1241 /// computed via \c Type::getObjCSubstitutions. If empty, the type
1242 /// parameters will be replaced with their bounds or id/Class, as appropriate
1243 /// for the context.
1244 ///
1245 /// \param context The context in which the subject type was written.
1246 ///
1247 /// \returns the resulting type.
1248 QualType substObjCTypeArgs(ASTContext &ctx,
1249 ArrayRef<QualType> typeArgs,
1250 ObjCSubstitutionContext context) const;
1251
1252 /// Substitute type arguments from an object type for the Objective-C type
1253 /// parameters used in the subject type.
1254 ///
1255 /// This operation combines the computation of type arguments for
1256 /// substitution (\c Type::getObjCSubstitutions) with the actual process of
1257 /// substitution (\c QualType::substObjCTypeArgs) for the convenience of
1258 /// callers that need to perform a single substitution in isolation.
1259 ///
1260 /// \param objectType The type of the object whose member type we're
1261 /// substituting into. For example, this might be the receiver of a message
1262 /// or the base of a property access.
1263 ///
1264 /// \param dc The declaration context from which the subject type was
1265 /// retrieved, which indicates (for example) which type parameters should
1266 /// be substituted.
1267 ///
1268 /// \param context The context in which the subject type was written.
1269 ///
1270 /// \returns the subject type after replacing all of the Objective-C type
1271 /// parameters with their corresponding arguments.
1272 QualType substObjCMemberType(QualType objectType,
1273 const DeclContext *dc,
1274 ObjCSubstitutionContext context) const;
1275
1276 /// Strip Objective-C "__kindof" types from the given type.
1277 QualType stripObjCKindOfType(const ASTContext &ctx) const;
1278
1279 /// Remove all qualifiers including _Atomic.
1280 QualType getAtomicUnqualifiedType() const;
1281
1282private:
1283 // These methods are implemented in a separate translation unit;
1284 // "static"-ize them to avoid creating temporary QualTypes in the
1285 // caller.
1286 static bool isConstant(QualType T, const ASTContext& Ctx);
1287 static QualType getDesugaredType(QualType T, const ASTContext &Context);
1288 static SplitQualType getSplitDesugaredType(QualType T);
1289 static SplitQualType getSplitUnqualifiedTypeImpl(QualType type);
1290 static QualType getSingleStepDesugaredTypeImpl(QualType type,
1291 const ASTContext &C);
1292 static QualType IgnoreParens(QualType T);
1293 static DestructionKind isDestructedTypeImpl(QualType type);
1294
1295 /// Check if \param RD is or contains a non-trivial C union.
1296 static bool hasNonTrivialToPrimitiveDefaultInitializeCUnion(const RecordDecl *RD);
1297 static bool hasNonTrivialToPrimitiveDestructCUnion(const RecordDecl *RD);
1298 static bool hasNonTrivialToPrimitiveCopyCUnion(const RecordDecl *RD);
1299};
1300
1301} // namespace clang
1302
1303namespace llvm {
1304
1305/// Implement simplify_type for QualType, so that we can dyn_cast from QualType
1306/// to a specific Type class.
1307template<> struct simplify_type< ::clang::QualType> {
1308 using SimpleType = const ::clang::Type *;
1309
1310 static SimpleType getSimplifiedValue(::clang::QualType Val) {
1311 return Val.getTypePtr();
1312 }
1313};
1314
1315// Teach SmallPtrSet that QualType is "basically a pointer".
1316template<>
1317struct PointerLikeTypeTraits<clang::QualType> {
1318 static inline void *getAsVoidPointer(clang::QualType P) {
1319 return P.getAsOpaquePtr();
1320 }
1321
1322 static inline clang::QualType getFromVoidPointer(void *P) {
1323 return clang::QualType::getFromOpaquePtr(P);
1324 }
1325
1326 // Various qualifiers go in low bits.
1327 static constexpr int NumLowBitsAvailable = 0;
1328};
1329
1330} // namespace llvm
1331
1332namespace clang {
1333
1334/// Base class that is common to both the \c ExtQuals and \c Type
1335/// classes, which allows \c QualType to access the common fields between the
1336/// two.
1337class ExtQualsTypeCommonBase {
1338 friend class ExtQuals;
1339 friend class QualType;
1340 friend class Type;
1341
1342 /// The "base" type of an extended qualifiers type (\c ExtQuals) or
1343 /// a self-referential pointer (for \c Type).
1344 ///
1345 /// This pointer allows an efficient mapping from a QualType to its
1346 /// underlying type pointer.
1347 const Type *const BaseType;
1348
1349 /// The canonical type of this type. A QualType.
1350 QualType CanonicalType;
1351
1352 ExtQualsTypeCommonBase(const Type *baseType, QualType canon)
1353 : BaseType(baseType), CanonicalType(canon) {}
1354};
1355
1356/// We can encode up to four bits in the low bits of a
1357/// type pointer, but there are many more type qualifiers that we want
1358/// to be able to apply to an arbitrary type. Therefore we have this
1359/// struct, intended to be heap-allocated and used by QualType to
1360/// store qualifiers.
1361///
1362/// The current design tags the 'const', 'restrict', and 'volatile' qualifiers
1363/// in three low bits on the QualType pointer; a fourth bit records whether
1364/// the pointer is an ExtQuals node. The extended qualifiers (address spaces,
1365/// Objective-C GC attributes) are much more rare.
1366class ExtQuals : public ExtQualsTypeCommonBase, public llvm::FoldingSetNode {
1367 // NOTE: changing the fast qualifiers should be straightforward as
1368 // long as you don't make 'const' non-fast.
1369 // 1. Qualifiers:
1370 // a) Modify the bitmasks (Qualifiers::TQ and DeclSpec::TQ).
1371 // Fast qualifiers must occupy the low-order bits.
1372 // b) Update Qualifiers::FastWidth and FastMask.
1373 // 2. QualType:
1374 // a) Update is{Volatile,Restrict}Qualified(), defined inline.
1375 // b) Update remove{Volatile,Restrict}, defined near the end of
1376 // this header.
1377 // 3. ASTContext:
1378 // a) Update get{Volatile,Restrict}Type.
1379
1380 /// The immutable set of qualifiers applied by this node. Always contains
1381 /// extended qualifiers.
1382 Qualifiers Quals;
1383
1384 ExtQuals *this_() { return this; }
1385
1386public:
1387 ExtQuals(const Type *baseType, QualType canon, Qualifiers quals)
1388 : ExtQualsTypeCommonBase(baseType,
1389 canon.isNull() ? QualType(this_(), 0) : canon),
1390 Quals(quals) {
1391 assert(Quals.hasNonFastQualifiers()((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1392, __PRETTY_FUNCTION__))
1392 && "ExtQuals created with no fast qualifiers")((Quals.hasNonFastQualifiers() && "ExtQuals created with no fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("Quals.hasNonFastQualifiers() && \"ExtQuals created with no fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1392, __PRETTY_FUNCTION__))
;
1393 assert(!Quals.hasFastQualifiers()((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1394, __PRETTY_FUNCTION__))
1394 && "ExtQuals created with fast qualifiers")((!Quals.hasFastQualifiers() && "ExtQuals created with fast qualifiers"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"ExtQuals created with fast qualifiers\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1394, __PRETTY_FUNCTION__))
;
1395 }
1396
1397 Qualifiers getQualifiers() const { return Quals; }
1398
1399 bool hasObjCGCAttr() const { return Quals.hasObjCGCAttr(); }
1400 Qualifiers::GC getObjCGCAttr() const { return Quals.getObjCGCAttr(); }
1401
1402 bool hasObjCLifetime() const { return Quals.hasObjCLifetime(); }
1403 Qualifiers::ObjCLifetime getObjCLifetime() const {
1404 return Quals.getObjCLifetime();
1405 }
1406
1407 bool hasAddressSpace() const { return Quals.hasAddressSpace(); }
1408 LangAS getAddressSpace() const { return Quals.getAddressSpace(); }
1409
1410 const Type *getBaseType() const { return BaseType; }
1411
1412public:
1413 void Profile(llvm::FoldingSetNodeID &ID) const {
1414 Profile(ID, getBaseType(), Quals);
1415 }
1416
1417 static void Profile(llvm::FoldingSetNodeID &ID,
1418 const Type *BaseType,
1419 Qualifiers Quals) {
1420 assert(!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!")((!Quals.hasFastQualifiers() && "fast qualifiers in ExtQuals hash!"
) ? static_cast<void> (0) : __assert_fail ("!Quals.hasFastQualifiers() && \"fast qualifiers in ExtQuals hash!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1420, __PRETTY_FUNCTION__))
;
1421 ID.AddPointer(BaseType);
1422 Quals.Profile(ID);
1423 }
1424};
1425
1426/// The kind of C++11 ref-qualifier associated with a function type.
1427/// This determines whether a member function's "this" object can be an
1428/// lvalue, rvalue, or neither.
1429enum RefQualifierKind {
1430 /// No ref-qualifier was provided.
1431 RQ_None = 0,
1432
1433 /// An lvalue ref-qualifier was provided (\c &).
1434 RQ_LValue,
1435
1436 /// An rvalue ref-qualifier was provided (\c &&).
1437 RQ_RValue
1438};
1439
1440/// Which keyword(s) were used to create an AutoType.
1441enum class AutoTypeKeyword {
1442 /// auto
1443 Auto,
1444
1445 /// decltype(auto)
1446 DecltypeAuto,
1447
1448 /// __auto_type (GNU extension)
1449 GNUAutoType
1450};
1451
1452/// The base class of the type hierarchy.
1453///
1454/// A central concept with types is that each type always has a canonical
1455/// type. A canonical type is the type with any typedef names stripped out
1456/// of it or the types it references. For example, consider:
1457///
1458/// typedef int foo;
1459/// typedef foo* bar;
1460/// 'int *' 'foo *' 'bar'
1461///
1462/// There will be a Type object created for 'int'. Since int is canonical, its
1463/// CanonicalType pointer points to itself. There is also a Type for 'foo' (a
1464/// TypedefType). Its CanonicalType pointer points to the 'int' Type. Next
1465/// there is a PointerType that represents 'int*', which, like 'int', is
1466/// canonical. Finally, there is a PointerType type for 'foo*' whose canonical
1467/// type is 'int*', and there is a TypedefType for 'bar', whose canonical type
1468/// is also 'int*'.
1469///
1470/// Non-canonical types are useful for emitting diagnostics, without losing
1471/// information about typedefs being used. Canonical types are useful for type
1472/// comparisons (they allow by-pointer equality tests) and useful for reasoning
1473/// about whether something has a particular form (e.g. is a function type),
1474/// because they implicitly, recursively, strip all typedefs out of a type.
1475///
1476/// Types, once created, are immutable.
1477///
1478class alignas(8) Type : public ExtQualsTypeCommonBase {
1479public:
1480 enum TypeClass {
1481#define TYPE(Class, Base) Class,
1482#define LAST_TYPE(Class) TypeLast = Class
1483#define ABSTRACT_TYPE(Class, Base)
1484#include "clang/AST/TypeNodes.inc"
1485 };
1486
1487private:
1488 /// Bitfields required by the Type class.
1489 class TypeBitfields {
1490 friend class Type;
1491 template <class T> friend class TypePropertyCache;
1492
1493 /// TypeClass bitfield - Enum that specifies what subclass this belongs to.
1494 unsigned TC : 8;
1495
1496 /// Store information on the type dependency.
1497 unsigned Dependence : llvm::BitWidth<TypeDependence>;
1498
1499 /// True if the cache (i.e. the bitfields here starting with
1500 /// 'Cache') is valid.
1501 mutable unsigned CacheValid : 1;
1502
1503 /// Linkage of this type.
1504 mutable unsigned CachedLinkage : 3;
1505
1506 /// Whether this type involves and local or unnamed types.
1507 mutable unsigned CachedLocalOrUnnamed : 1;
1508
1509 /// Whether this type comes from an AST file.
1510 mutable unsigned FromAST : 1;
1511
1512 bool isCacheValid() const {
1513 return CacheValid;
1514 }
1515
1516 Linkage getLinkage() const {
1517 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1517, __PRETTY_FUNCTION__))
;
1518 return static_cast<Linkage>(CachedLinkage);
1519 }
1520
1521 bool hasLocalOrUnnamedType() const {
1522 assert(isCacheValid() && "getting linkage from invalid cache")((isCacheValid() && "getting linkage from invalid cache"
) ? static_cast<void> (0) : __assert_fail ("isCacheValid() && \"getting linkage from invalid cache\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 1522, __PRETTY_FUNCTION__))
;
1523 return CachedLocalOrUnnamed;
1524 }
1525 };
1526 enum { NumTypeBits = 8 + llvm::BitWidth<TypeDependence> + 6 };
1527
1528protected:
1529 // These classes allow subclasses to somewhat cleanly pack bitfields
1530 // into Type.
1531
1532 class ArrayTypeBitfields {
1533 friend class ArrayType;
1534
1535 unsigned : NumTypeBits;
1536
1537 /// CVR qualifiers from declarations like
1538 /// 'int X[static restrict 4]'. For function parameters only.
1539 unsigned IndexTypeQuals : 3;
1540
1541 /// Storage class qualifiers from declarations like
1542 /// 'int X[static restrict 4]'. For function parameters only.
1543 /// Actually an ArrayType::ArraySizeModifier.
1544 unsigned SizeModifier : 3;
1545 };
1546
1547 class ConstantArrayTypeBitfields {
1548 friend class ConstantArrayType;
1549
1550 unsigned : NumTypeBits + 3 + 3;
1551
1552 /// Whether we have a stored size expression.
1553 unsigned HasStoredSizeExpr : 1;
1554 };
1555
1556 class BuiltinTypeBitfields {
1557 friend class BuiltinType;
1558
1559 unsigned : NumTypeBits;
1560
1561 /// The kind (BuiltinType::Kind) of builtin type this is.
1562 unsigned Kind : 8;
1563 };
1564
1565 /// FunctionTypeBitfields store various bits belonging to FunctionProtoType.
1566 /// Only common bits are stored here. Additional uncommon bits are stored
1567 /// in a trailing object after FunctionProtoType.
1568 class FunctionTypeBitfields {
1569 friend class FunctionProtoType;
1570 friend class FunctionType;
1571
1572 unsigned : NumTypeBits;
1573
1574 /// Extra information which affects how the function is called, like
1575 /// regparm and the calling convention.
1576 unsigned ExtInfo : 13;
1577
1578 /// The ref-qualifier associated with a \c FunctionProtoType.
1579 ///
1580 /// This is a value of type \c RefQualifierKind.
1581 unsigned RefQualifier : 2;
1582
1583 /// Used only by FunctionProtoType, put here to pack with the
1584 /// other bitfields.
1585 /// The qualifiers are part of FunctionProtoType because...
1586 ///
1587 /// C++ 8.3.5p4: The return type, the parameter type list and the
1588 /// cv-qualifier-seq, [...], are part of the function type.
1589 unsigned FastTypeQuals : Qualifiers::FastWidth;
1590 /// Whether this function has extended Qualifiers.
1591 unsigned HasExtQuals : 1;
1592
1593 /// The number of parameters this function has, not counting '...'.
1594 /// According to [implimits] 8 bits should be enough here but this is
1595 /// somewhat easy to exceed with metaprogramming and so we would like to
1596 /// keep NumParams as wide as reasonably possible.
1597 unsigned NumParams : 16;
1598
1599 /// The type of exception specification this function has.
1600 unsigned ExceptionSpecType : 4;
1601
1602 /// Whether this function has extended parameter information.
1603 unsigned HasExtParameterInfos : 1;
1604
1605 /// Whether the function is variadic.
1606 unsigned Variadic : 1;
1607
1608 /// Whether this function has a trailing return type.
1609 unsigned HasTrailingReturn : 1;
1610 };
1611
1612 class ObjCObjectTypeBitfields {
1613 friend class ObjCObjectType;
1614
1615 unsigned : NumTypeBits;
1616
1617 /// The number of type arguments stored directly on this object type.
1618 unsigned NumTypeArgs : 7;
1619
1620 /// The number of protocols stored directly on this object type.
1621 unsigned NumProtocols : 6;
1622
1623 /// Whether this is a "kindof" type.
1624 unsigned IsKindOf : 1;
1625 };
1626
1627 class ReferenceTypeBitfields {
1628 friend class ReferenceType;
1629
1630 unsigned : NumTypeBits;
1631
1632 /// True if the type was originally spelled with an lvalue sigil.
1633 /// This is never true of rvalue references but can also be false
1634 /// on lvalue references because of C++0x [dcl.typedef]p9,
1635 /// as follows:
1636 ///
1637 /// typedef int &ref; // lvalue, spelled lvalue
1638 /// typedef int &&rvref; // rvalue
1639 /// ref &a; // lvalue, inner ref, spelled lvalue
1640 /// ref &&a; // lvalue, inner ref
1641 /// rvref &a; // lvalue, inner ref, spelled lvalue
1642 /// rvref &&a; // rvalue, inner ref
1643 unsigned SpelledAsLValue : 1;
1644
1645 /// True if the inner type is a reference type. This only happens
1646 /// in non-canonical forms.
1647 unsigned InnerRef : 1;
1648 };
1649
1650 class TypeWithKeywordBitfields {
1651 friend class TypeWithKeyword;
1652
1653 unsigned : NumTypeBits;
1654
1655 /// An ElaboratedTypeKeyword. 8 bits for efficient access.
1656 unsigned Keyword : 8;
1657 };
1658
1659 enum { NumTypeWithKeywordBits = 8 };
1660
1661 class ElaboratedTypeBitfields {
1662 friend class ElaboratedType;
1663
1664 unsigned : NumTypeBits;
1665 unsigned : NumTypeWithKeywordBits;
1666
1667 /// Whether the ElaboratedType has a trailing OwnedTagDecl.
1668 unsigned HasOwnedTagDecl : 1;
1669 };
1670
1671 class VectorTypeBitfields {
1672 friend class VectorType;
1673 friend class DependentVectorType;
1674
1675 unsigned : NumTypeBits;
1676
1677 /// The kind of vector, either a generic vector type or some
1678 /// target-specific vector type such as for AltiVec or Neon.
1679 unsigned VecKind : 3;
1680 /// The number of elements in the vector.
1681 uint32_t NumElements;
1682 };
1683
1684 class AttributedTypeBitfields {
1685 friend class AttributedType;
1686
1687 unsigned : NumTypeBits;
1688
1689 /// An AttributedType::Kind
1690 unsigned AttrKind : 32 - NumTypeBits;
1691 };
1692
1693 class AutoTypeBitfields {
1694 friend class AutoType;
1695
1696 unsigned : NumTypeBits;
1697
1698 /// Was this placeholder type spelled as 'auto', 'decltype(auto)',
1699 /// or '__auto_type'? AutoTypeKeyword value.
1700 unsigned Keyword : 2;
1701
1702 /// The number of template arguments in the type-constraints, which is
1703 /// expected to be able to hold at least 1024 according to [implimits].
1704 /// However as this limit is somewhat easy to hit with template
1705 /// metaprogramming we'd prefer to keep it as large as possible.
1706 /// At the moment it has been left as a non-bitfield since this type
1707 /// safely fits in 64 bits as an unsigned, so there is no reason to
1708 /// introduce the performance impact of a bitfield.
1709 unsigned NumArgs;
1710 };
1711
1712 class SubstTemplateTypeParmPackTypeBitfields {
1713 friend class SubstTemplateTypeParmPackType;
1714
1715 unsigned : NumTypeBits;
1716
1717 /// The number of template arguments in \c Arguments, which is
1718 /// expected to be able to hold at least 1024 according to [implimits].
1719 /// However as this limit is somewhat easy to hit with template
1720 /// metaprogramming we'd prefer to keep it as large as possible.
1721 /// At the moment it has been left as a non-bitfield since this type
1722 /// safely fits in 64 bits as an unsigned, so there is no reason to
1723 /// introduce the performance impact of a bitfield.
1724 unsigned NumArgs;
1725 };
1726
1727 class TemplateSpecializationTypeBitfields {
1728 friend class TemplateSpecializationType;
1729
1730 unsigned : NumTypeBits;
1731
1732 /// Whether this template specialization type is a substituted type alias.
1733 unsigned TypeAlias : 1;
1734
1735 /// The number of template arguments named in this class template
1736 /// specialization, which is expected to be able to hold at least 1024
1737 /// according to [implimits]. However, as this limit is somewhat easy to
1738 /// hit with template metaprogramming we'd prefer to keep it as large
1739 /// as possible. At the moment it has been left as a non-bitfield since
1740 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1741 /// to introduce the performance impact of a bitfield.
1742 unsigned NumArgs;
1743 };
1744
1745 class DependentTemplateSpecializationTypeBitfields {
1746 friend class DependentTemplateSpecializationType;
1747
1748 unsigned : NumTypeBits;
1749 unsigned : NumTypeWithKeywordBits;
1750
1751 /// The number of template arguments named in this class template
1752 /// specialization, which is expected to be able to hold at least 1024
1753 /// according to [implimits]. However, as this limit is somewhat easy to
1754 /// hit with template metaprogramming we'd prefer to keep it as large
1755 /// as possible. At the moment it has been left as a non-bitfield since
1756 /// this type safely fits in 64 bits as an unsigned, so there is no reason
1757 /// to introduce the performance impact of a bitfield.
1758 unsigned NumArgs;
1759 };
1760
1761 class PackExpansionTypeBitfields {
1762 friend class PackExpansionType;
1763
1764 unsigned : NumTypeBits;
1765
1766 /// The number of expansions that this pack expansion will
1767 /// generate when substituted (+1), which is expected to be able to
1768 /// hold at least 1024 according to [implimits]. However, as this limit
1769 /// is somewhat easy to hit with template metaprogramming we'd prefer to
1770 /// keep it as large as possible. At the moment it has been left as a
1771 /// non-bitfield since this type safely fits in 64 bits as an unsigned, so
1772 /// there is no reason to introduce the performance impact of a bitfield.
1773 ///
1774 /// This field will only have a non-zero value when some of the parameter
1775 /// packs that occur within the pattern have been substituted but others
1776 /// have not.
1777 unsigned NumExpansions;
1778 };
1779
1780 union {
1781 TypeBitfields TypeBits;
1782 ArrayTypeBitfields ArrayTypeBits;
1783 ConstantArrayTypeBitfields ConstantArrayTypeBits;
1784 AttributedTypeBitfields AttributedTypeBits;
1785 AutoTypeBitfields AutoTypeBits;
1786 BuiltinTypeBitfields BuiltinTypeBits;
1787 FunctionTypeBitfields FunctionTypeBits;
1788 ObjCObjectTypeBitfields ObjCObjectTypeBits;
1789 ReferenceTypeBitfields ReferenceTypeBits;
1790 TypeWithKeywordBitfields TypeWithKeywordBits;
1791 ElaboratedTypeBitfields ElaboratedTypeBits;
1792 VectorTypeBitfields VectorTypeBits;
1793 SubstTemplateTypeParmPackTypeBitfields SubstTemplateTypeParmPackTypeBits;
1794 TemplateSpecializationTypeBitfields TemplateSpecializationTypeBits;
1795 DependentTemplateSpecializationTypeBitfields
1796 DependentTemplateSpecializationTypeBits;
1797 PackExpansionTypeBitfields PackExpansionTypeBits;
1798 };
1799
1800private:
1801 template <class T> friend class TypePropertyCache;
1802
1803 /// Set whether this type comes from an AST file.
1804 void setFromAST(bool V = true) const {
1805 TypeBits.FromAST = V;
1806 }
1807
1808protected:
1809 friend class ASTContext;
1810
1811 Type(TypeClass tc, QualType canon, TypeDependence Dependence)
1812 : ExtQualsTypeCommonBase(this,
1813 canon.isNull() ? QualType(this_(), 0) : canon) {
1814 static_assert(sizeof(*this) <= 8 + sizeof(ExtQualsTypeCommonBase),
1815 "changing bitfields changed sizeof(Type)!");
1816 static_assert(alignof(decltype(*this)) % sizeof(void *) == 0,
1817 "Insufficient alignment!");
1818 TypeBits.TC = tc;
1819 TypeBits.Dependence = static_cast<unsigned>(Dependence);
1820 TypeBits.CacheValid = false;
1821 TypeBits.CachedLocalOrUnnamed = false;
1822 TypeBits.CachedLinkage = NoLinkage;
1823 TypeBits.FromAST = false;
1824 }
1825
1826 // silence VC++ warning C4355: 'this' : used in base member initializer list
1827 Type *this_() { return this; }
1828
1829 void setDependence(TypeDependence D) {
1830 TypeBits.Dependence = static_cast<unsigned>(D);
1831 }
1832
1833 void addDependence(TypeDependence D) { setDependence(getDependence() | D); }
1834
1835public:
1836 friend class ASTReader;
1837 friend class ASTWriter;
1838 template <class T> friend class serialization::AbstractTypeReader;
1839 template <class T> friend class serialization::AbstractTypeWriter;
1840
1841 Type(const Type &) = delete;
1842 Type(Type &&) = delete;
1843 Type &operator=(const Type &) = delete;
1844 Type &operator=(Type &&) = delete;
1845
1846 TypeClass getTypeClass() const { return static_cast<TypeClass>(TypeBits.TC); }
1847
1848 /// Whether this type comes from an AST file.
1849 bool isFromAST() const { return TypeBits.FromAST; }
1850
1851 /// Whether this type is or contains an unexpanded parameter
1852 /// pack, used to support C++0x variadic templates.
1853 ///
1854 /// A type that contains a parameter pack shall be expanded by the
1855 /// ellipsis operator at some point. For example, the typedef in the
1856 /// following example contains an unexpanded parameter pack 'T':
1857 ///
1858 /// \code
1859 /// template<typename ...T>
1860 /// struct X {
1861 /// typedef T* pointer_types; // ill-formed; T is a parameter pack.
1862 /// };
1863 /// \endcode
1864 ///
1865 /// Note that this routine does not specify which
1866 bool containsUnexpandedParameterPack() const {
1867 return getDependence() & TypeDependence::UnexpandedPack;
1868 }
1869
1870 /// Determines if this type would be canonical if it had no further
1871 /// qualification.
1872 bool isCanonicalUnqualified() const {
1873 return CanonicalType == QualType(this, 0);
1874 }
1875
1876 /// Pull a single level of sugar off of this locally-unqualified type.
1877 /// Users should generally prefer SplitQualType::getSingleStepDesugaredType()
1878 /// or QualType::getSingleStepDesugaredType(const ASTContext&).
1879 QualType getLocallyUnqualifiedSingleStepDesugaredType() const;
1880
1881 /// As an extension, we classify types as one of "sized" or "sizeless";
1882 /// every type is one or the other. Standard types are all sized;
1883 /// sizeless types are purely an extension.
1884 ///
1885 /// Sizeless types contain data with no specified size, alignment,
1886 /// or layout.
1887 bool isSizelessType() const;
1888 bool isSizelessBuiltinType() const;
1889
1890 /// Determines if this is a sizeless type supported by the
1891 /// 'arm_sve_vector_bits' type attribute, which can be applied to a single
1892 /// SVE vector or predicate, excluding tuple types such as svint32x4_t.
1893 bool isVLSTBuiltinType() const;
1894
1895 /// Returns the representative type for the element of an SVE builtin type.
1896 /// This is used to represent fixed-length SVE vectors created with the
1897 /// 'arm_sve_vector_bits' type attribute as VectorType.
1898 QualType getSveEltType(const ASTContext &Ctx) const;
1899
1900 /// Types are partitioned into 3 broad categories (C99 6.2.5p1):
1901 /// object types, function types, and incomplete types.
1902
1903 /// Return true if this is an incomplete type.
1904 /// A type that can describe objects, but which lacks information needed to
1905 /// determine its size (e.g. void, or a fwd declared struct). Clients of this
1906 /// routine will need to determine if the size is actually required.
1907 ///
1908 /// Def If non-null, and the type refers to some kind of declaration
1909 /// that can be completed (such as a C struct, C++ class, or Objective-C
1910 /// class), will be set to the declaration.
1911 bool isIncompleteType(NamedDecl **Def = nullptr) const;
1912
1913 /// Return true if this is an incomplete or object
1914 /// type, in other words, not a function type.
1915 bool isIncompleteOrObjectType() const {
1916 return !isFunctionType();
1917 }
1918
1919 /// Determine whether this type is an object type.
1920 bool isObjectType() const {
1921 // C++ [basic.types]p8:
1922 // An object type is a (possibly cv-qualified) type that is not a
1923 // function type, not a reference type, and not a void type.
1924 return !isReferenceType() && !isFunctionType() && !isVoidType();
1925 }
1926
1927 /// Return true if this is a literal type
1928 /// (C++11 [basic.types]p10)
1929 bool isLiteralType(const ASTContext &Ctx) const;
1930
1931 /// Determine if this type is a structural type, per C++20 [temp.param]p7.
1932 bool isStructuralType() const;
1933
1934 /// Test if this type is a standard-layout type.
1935 /// (C++0x [basic.type]p9)
1936 bool isStandardLayoutType() const;
1937
1938 /// Helper methods to distinguish type categories. All type predicates
1939 /// operate on the canonical type, ignoring typedefs and qualifiers.
1940
1941 /// Returns true if the type is a builtin type.
1942 bool isBuiltinType() const;
1943
1944 /// Test for a particular builtin type.
1945 bool isSpecificBuiltinType(unsigned K) const;
1946
1947 /// Test for a type which does not represent an actual type-system type but
1948 /// is instead used as a placeholder for various convenient purposes within
1949 /// Clang. All such types are BuiltinTypes.
1950 bool isPlaceholderType() const;
1951 const BuiltinType *getAsPlaceholderType() const;
1952
1953 /// Test for a specific placeholder type.
1954 bool isSpecificPlaceholderType(unsigned K) const;
1955
1956 /// Test for a placeholder type other than Overload; see
1957 /// BuiltinType::isNonOverloadPlaceholderType.
1958 bool isNonOverloadPlaceholderType() const;
1959
1960 /// isIntegerType() does *not* include complex integers (a GCC extension).
1961 /// isComplexIntegerType() can be used to test for complex integers.
1962 bool isIntegerType() const; // C99 6.2.5p17 (int, char, bool, enum)
1963 bool isEnumeralType() const;
1964
1965 /// Determine whether this type is a scoped enumeration type.
1966 bool isScopedEnumeralType() const;
1967 bool isBooleanType() const;
1968 bool isCharType() const;
1969 bool isWideCharType() const;
1970 bool isChar8Type() const;
1971 bool isChar16Type() const;
1972 bool isChar32Type() const;
1973 bool isAnyCharacterType() const;
1974 bool isIntegralType(const ASTContext &Ctx) const;
1975
1976 /// Determine whether this type is an integral or enumeration type.
1977 bool isIntegralOrEnumerationType() const;
1978
1979 /// Determine whether this type is an integral or unscoped enumeration type.
1980 bool isIntegralOrUnscopedEnumerationType() const;
1981 bool isUnscopedEnumerationType() const;
1982
1983 /// Floating point categories.
1984 bool isRealFloatingType() const; // C99 6.2.5p10 (float, double, long double)
1985 /// isComplexType() does *not* include complex integers (a GCC extension).
1986 /// isComplexIntegerType() can be used to test for complex integers.
1987 bool isComplexType() const; // C99 6.2.5p11 (complex)
1988 bool isAnyComplexType() const; // C99 6.2.5p11 (complex) + Complex Int.
1989 bool isFloatingType() const; // C99 6.2.5p11 (real floating + complex)
1990 bool isHalfType() const; // OpenCL 6.1.1.1, NEON (IEEE 754-2008 half)
1991 bool isFloat16Type() const; // C11 extension ISO/IEC TS 18661
1992 bool isBFloat16Type() const;
1993 bool isFloat128Type() const;
1994 bool isRealType() const; // C99 6.2.5p17 (real floating + integer)
1995 bool isArithmeticType() const; // C99 6.2.5p18 (integer + floating)
1996 bool isVoidType() const; // C99 6.2.5p19
1997 bool isScalarType() const; // C99 6.2.5p21 (arithmetic + pointers)
1998 bool isAggregateType() const;
1999 bool isFundamentalType() const;
2000 bool isCompoundType() const;
2001
2002 // Type Predicates: Check to see if this type is structurally the specified
2003 // type, ignoring typedefs and qualifiers.
2004 bool isFunctionType() const;
2005 bool isFunctionNoProtoType() const { return getAs<FunctionNoProtoType>(); }
2006 bool isFunctionProtoType() const { return getAs<FunctionProtoType>(); }
2007 bool isPointerType() const;
2008 bool isAnyPointerType() const; // Any C pointer or ObjC object pointer
2009 bool isBlockPointerType() const;
2010 bool isVoidPointerType() const;
2011 bool isReferenceType() const;
2012 bool isLValueReferenceType() const;
2013 bool isRValueReferenceType() const;
2014 bool isObjectPointerType() const;
2015 bool isFunctionPointerType() const;
2016 bool isFunctionReferenceType() const;
2017 bool isMemberPointerType() const;
2018 bool isMemberFunctionPointerType() const;
2019 bool isMemberDataPointerType() const;
2020 bool isArrayType() const;
2021 bool isConstantArrayType() const;
2022 bool isIncompleteArrayType() const;
2023 bool isVariableArrayType() const;
2024 bool isDependentSizedArrayType() const;
2025 bool isRecordType() const;
2026 bool isClassType() const;
2027 bool isStructureType() const;
2028 bool isObjCBoxableRecordType() const;
2029 bool isInterfaceType() const;
2030 bool isStructureOrClassType() const;
2031 bool isUnionType() const;
2032 bool isComplexIntegerType() const; // GCC _Complex integer type.
2033 bool isVectorType() const; // GCC vector type.
2034 bool isExtVectorType() const; // Extended vector type.
2035 bool isMatrixType() const; // Matrix type.
2036 bool isConstantMatrixType() const; // Constant matrix type.
2037 bool isDependentAddressSpaceType() const; // value-dependent address space qualifier
2038 bool isObjCObjectPointerType() const; // pointer to ObjC object
2039 bool isObjCRetainableType() const; // ObjC object or block pointer
2040 bool isObjCLifetimeType() const; // (array of)* retainable type
2041 bool isObjCIndirectLifetimeType() const; // (pointer to)* lifetime type
2042 bool isObjCNSObjectType() const; // __attribute__((NSObject))
2043 bool isObjCIndependentClassType() const; // __attribute__((objc_independent_class))
2044 // FIXME: change this to 'raw' interface type, so we can used 'interface' type
2045 // for the common case.
2046 bool isObjCObjectType() const; // NSString or typeof(*(id)0)
2047 bool isObjCQualifiedInterfaceType() const; // NSString<foo>
2048 bool isObjCQualifiedIdType() const; // id<foo>
2049 bool isObjCQualifiedClassType() const; // Class<foo>
2050 bool isObjCObjectOrInterfaceType() const;
2051 bool isObjCIdType() const; // id
2052 bool isDecltypeType() const;
2053 /// Was this type written with the special inert-in-ARC __unsafe_unretained
2054 /// qualifier?
2055 ///
2056 /// This approximates the answer to the following question: if this
2057 /// translation unit were compiled in ARC, would this type be qualified
2058 /// with __unsafe_unretained?
2059 bool isObjCInertUnsafeUnretainedType() const {
2060 return hasAttr(attr::ObjCInertUnsafeUnretained);
2061 }
2062
2063 /// Whether the type is Objective-C 'id' or a __kindof type of an
2064 /// object type, e.g., __kindof NSView * or __kindof id
2065 /// <NSCopying>.
2066 ///
2067 /// \param bound Will be set to the bound on non-id subtype types,
2068 /// which will be (possibly specialized) Objective-C class type, or
2069 /// null for 'id.
2070 bool isObjCIdOrObjectKindOfType(const ASTContext &ctx,
2071 const ObjCObjectType *&bound) const;
2072
2073 bool isObjCClassType() const; // Class
2074
2075 /// Whether the type is Objective-C 'Class' or a __kindof type of an
2076 /// Class type, e.g., __kindof Class <NSCopying>.
2077 ///
2078 /// Unlike \c isObjCIdOrObjectKindOfType, there is no relevant bound
2079 /// here because Objective-C's type system cannot express "a class
2080 /// object for a subclass of NSFoo".
2081 bool isObjCClassOrClassKindOfType() const;
2082
2083 bool isBlockCompatibleObjCPointerType(ASTContext &ctx) const;
2084 bool isObjCSelType() const; // Class
2085 bool isObjCBuiltinType() const; // 'id' or 'Class'
2086 bool isObjCARCBridgableType() const;
2087 bool isCARCBridgableType() const;
2088 bool isTemplateTypeParmType() const; // C++ template type parameter
2089 bool isNullPtrType() const; // C++11 std::nullptr_t
2090 bool isNothrowT() const; // C++ std::nothrow_t
2091 bool isAlignValT() const; // C++17 std::align_val_t
2092 bool isStdByteType() const; // C++17 std::byte
2093 bool isAtomicType() const; // C11 _Atomic()
2094 bool isUndeducedAutoType() const; // C++11 auto or
2095 // C++14 decltype(auto)
2096 bool isTypedefNameType() const; // typedef or alias template
2097
2098#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2099 bool is##Id##Type() const;
2100#include "clang/Basic/OpenCLImageTypes.def"
2101
2102 bool isImageType() const; // Any OpenCL image type
2103
2104 bool isSamplerT() const; // OpenCL sampler_t
2105 bool isEventT() const; // OpenCL event_t
2106 bool isClkEventT() const; // OpenCL clk_event_t
2107 bool isQueueT() const; // OpenCL queue_t
2108 bool isReserveIDT() const; // OpenCL reserve_id_t
2109
2110#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2111 bool is##Id##Type() const;
2112#include "clang/Basic/OpenCLExtensionTypes.def"
2113 // Type defined in cl_intel_device_side_avc_motion_estimation OpenCL extension
2114 bool isOCLIntelSubgroupAVCType() const;
2115 bool isOCLExtOpaqueType() const; // Any OpenCL extension type
2116
2117 bool isPipeType() const; // OpenCL pipe type
2118 bool isExtIntType() const; // Extended Int Type
2119 bool isOpenCLSpecificType() const; // Any OpenCL specific type
2120
2121 /// Determines if this type, which must satisfy
2122 /// isObjCLifetimeType(), is implicitly __unsafe_unretained rather
2123 /// than implicitly __strong.
2124 bool isObjCARCImplicitlyUnretainedType() const;
2125
2126 /// Check if the type is the CUDA device builtin surface type.
2127 bool isCUDADeviceBuiltinSurfaceType() const;
2128 /// Check if the type is the CUDA device builtin texture type.
2129 bool isCUDADeviceBuiltinTextureType() const;
2130
2131 /// Return the implicit lifetime for this type, which must not be dependent.
2132 Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const;
2133
2134 enum ScalarTypeKind {
2135 STK_CPointer,
2136 STK_BlockPointer,
2137 STK_ObjCObjectPointer,
2138 STK_MemberPointer,
2139 STK_Bool,
2140 STK_Integral,
2141 STK_Floating,
2142 STK_IntegralComplex,
2143 STK_FloatingComplex,
2144 STK_FixedPoint
2145 };
2146
2147 /// Given that this is a scalar type, classify it.
2148 ScalarTypeKind getScalarTypeKind() const;
2149
2150 TypeDependence getDependence() const {
2151 return static_cast<TypeDependence>(TypeBits.Dependence);
2152 }
2153
2154 /// Whether this type is an error type.
2155 bool containsErrors() const {
2156 return getDependence() & TypeDependence::Error;
2157 }
2158
2159 /// Whether this type is a dependent type, meaning that its definition
2160 /// somehow depends on a template parameter (C++ [temp.dep.type]).
2161 bool isDependentType() const {
2162 return getDependence() & TypeDependence::Dependent;
2163 }
2164
2165 /// Determine whether this type is an instantiation-dependent type,
2166 /// meaning that the type involves a template parameter (even if the
2167 /// definition does not actually depend on the type substituted for that
2168 /// template parameter).
2169 bool isInstantiationDependentType() const {
2170 return getDependence() & TypeDependence::Instantiation;
2171 }
2172
2173 /// Determine whether this type is an undeduced type, meaning that
2174 /// it somehow involves a C++11 'auto' type or similar which has not yet been
2175 /// deduced.
2176 bool isUndeducedType() const;
2177
2178 /// Whether this type is a variably-modified type (C99 6.7.5).
2179 bool isVariablyModifiedType() const {
2180 return getDependence() & TypeDependence::VariablyModified;
2181 }
2182
2183 /// Whether this type involves a variable-length array type
2184 /// with a definite size.
2185 bool hasSizedVLAType() const;
2186
2187 /// Whether this type is or contains a local or unnamed type.
2188 bool hasUnnamedOrLocalType() const;
2189
2190 bool isOverloadableType() const;
2191
2192 /// Determine wither this type is a C++ elaborated-type-specifier.
2193 bool isElaboratedTypeSpecifier() const;
2194
2195 bool canDecayToPointerType() const;
2196
2197 /// Whether this type is represented natively as a pointer. This includes
2198 /// pointers, references, block pointers, and Objective-C interface,
2199 /// qualified id, and qualified interface types, as well as nullptr_t.
2200 bool hasPointerRepresentation() const;
2201
2202 /// Whether this type can represent an objective pointer type for the
2203 /// purpose of GC'ability
2204 bool hasObjCPointerRepresentation() const;
2205
2206 /// Determine whether this type has an integer representation
2207 /// of some sort, e.g., it is an integer type or a vector.
2208 bool hasIntegerRepresentation() const;
2209
2210 /// Determine whether this type has an signed integer representation
2211 /// of some sort, e.g., it is an signed integer type or a vector.
2212 bool hasSignedIntegerRepresentation() const;
2213
2214 /// Determine whether this type has an unsigned integer representation
2215 /// of some sort, e.g., it is an unsigned integer type or a vector.
2216 bool hasUnsignedIntegerRepresentation() const;
2217
2218 /// Determine whether this type has a floating-point representation
2219 /// of some sort, e.g., it is a floating-point type or a vector thereof.
2220 bool hasFloatingRepresentation() const;
2221
2222 // Type Checking Functions: Check to see if this type is structurally the
2223 // specified type, ignoring typedefs and qualifiers, and return a pointer to
2224 // the best type we can.
2225 const RecordType *getAsStructureType() const;
2226 /// NOTE: getAs*ArrayType are methods on ASTContext.
2227 const RecordType *getAsUnionType() const;
2228 const ComplexType *getAsComplexIntegerType() const; // GCC complex int type.
2229 const ObjCObjectType *getAsObjCInterfaceType() const;
2230
2231 // The following is a convenience method that returns an ObjCObjectPointerType
2232 // for object declared using an interface.
2233 const ObjCObjectPointerType *getAsObjCInterfacePointerType() const;
2234 const ObjCObjectPointerType *getAsObjCQualifiedIdType() const;
2235 const ObjCObjectPointerType *getAsObjCQualifiedClassType() const;
2236 const ObjCObjectType *getAsObjCQualifiedInterfaceType() const;
2237
2238 /// Retrieves the CXXRecordDecl that this type refers to, either
2239 /// because the type is a RecordType or because it is the injected-class-name
2240 /// type of a class template or class template partial specialization.
2241 CXXRecordDecl *getAsCXXRecordDecl() const;
2242
2243 /// Retrieves the RecordDecl this type refers to.
2244 RecordDecl *getAsRecordDecl() const;
2245
2246 /// Retrieves the TagDecl that this type refers to, either
2247 /// because the type is a TagType or because it is the injected-class-name
2248 /// type of a class template or class template partial specialization.
2249 TagDecl *getAsTagDecl() const;
2250
2251 /// If this is a pointer or reference to a RecordType, return the
2252 /// CXXRecordDecl that the type refers to.
2253 ///
2254 /// If this is not a pointer or reference, or the type being pointed to does
2255 /// not refer to a CXXRecordDecl, returns NULL.
2256 const CXXRecordDecl *getPointeeCXXRecordDecl() const;
2257
2258 /// Get the DeducedType whose type will be deduced for a variable with
2259 /// an initializer of this type. This looks through declarators like pointer
2260 /// types, but not through decltype or typedefs.
2261 DeducedType *getContainedDeducedType() const;
2262
2263 /// Get the AutoType whose type will be deduced for a variable with
2264 /// an initializer of this type. This looks through declarators like pointer
2265 /// types, but not through decltype or typedefs.
2266 AutoType *getContainedAutoType() const {
2267 return dyn_cast_or_null<AutoType>(getContainedDeducedType());
2268 }
2269
2270 /// Determine whether this type was written with a leading 'auto'
2271 /// corresponding to a trailing return type (possibly for a nested
2272 /// function type within a pointer to function type or similar).
2273 bool hasAutoForTrailingReturnType() const;
2274
2275 /// Member-template getAs<specific type>'. Look through sugar for
2276 /// an instance of \<specific type>. This scheme will eventually
2277 /// replace the specific getAsXXXX methods above.
2278 ///
2279 /// There are some specializations of this member template listed
2280 /// immediately following this class.
2281 template <typename T> const T *getAs() const;
2282
2283 /// Member-template getAsAdjusted<specific type>. Look through specific kinds
2284 /// of sugar (parens, attributes, etc) for an instance of \<specific type>.
2285 /// This is used when you need to walk over sugar nodes that represent some
2286 /// kind of type adjustment from a type that was written as a \<specific type>
2287 /// to another type that is still canonically a \<specific type>.
2288 template <typename T> const T *getAsAdjusted() const;
2289
2290 /// A variant of getAs<> for array types which silently discards
2291 /// qualifiers from the outermost type.
2292 const ArrayType *getAsArrayTypeUnsafe() const;
2293
2294 /// Member-template castAs<specific type>. Look through sugar for
2295 /// the underlying instance of \<specific type>.
2296 ///
2297 /// This method has the same relationship to getAs<T> as cast<T> has
2298 /// to dyn_cast<T>; which is to say, the underlying type *must*
2299 /// have the intended type, and this method will never return null.
2300 template <typename T> const T *castAs() const;
2301
2302 /// A variant of castAs<> for array type which silently discards
2303 /// qualifiers from the outermost type.
2304 const ArrayType *castAsArrayTypeUnsafe() const;
2305
2306 /// Determine whether this type had the specified attribute applied to it
2307 /// (looking through top-level type sugar).
2308 bool hasAttr(attr::Kind AK) const;
2309
2310 /// Get the base element type of this type, potentially discarding type
2311 /// qualifiers. This should never be used when type qualifiers
2312 /// are meaningful.
2313 const Type *getBaseElementTypeUnsafe() const;
2314
2315 /// If this is an array type, return the element type of the array,
2316 /// potentially with type qualifiers missing.
2317 /// This should never be used when type qualifiers are meaningful.
2318 const Type *getArrayElementTypeNoTypeQual() const;
2319
2320 /// If this is a pointer type, return the pointee type.
2321 /// If this is an array type, return the array element type.
2322 /// This should never be used when type qualifiers are meaningful.
2323 const Type *getPointeeOrArrayElementType() const;
2324
2325 /// If this is a pointer, ObjC object pointer, or block
2326 /// pointer, this returns the respective pointee.
2327 QualType getPointeeType() const;
2328
2329 /// Return the specified type with any "sugar" removed from the type,
2330 /// removing any typedefs, typeofs, etc., as well as any qualifiers.
2331 const Type *getUnqualifiedDesugaredType() const;
2332
2333 /// More type predicates useful for type checking/promotion
2334 bool isPromotableIntegerType() const; // C99 6.3.1.1p2
2335
2336 /// Return true if this is an integer type that is
2337 /// signed, according to C99 6.2.5p4 [char, signed char, short, int, long..],
2338 /// or an enum decl which has a signed representation.
2339 bool isSignedIntegerType() const;
2340
2341 /// Return true if this is an integer type that is
2342 /// unsigned, according to C99 6.2.5p6 [which returns true for _Bool],
2343 /// or an enum decl which has an unsigned representation.
2344 bool isUnsignedIntegerType() const;
2345
2346 /// Determines whether this is an integer type that is signed or an
2347 /// enumeration types whose underlying type is a signed integer type.
2348 bool isSignedIntegerOrEnumerationType() const;
2349
2350 /// Determines whether this is an integer type that is unsigned or an
2351 /// enumeration types whose underlying type is a unsigned integer type.
2352 bool isUnsignedIntegerOrEnumerationType() const;
2353
2354 /// Return true if this is a fixed point type according to
2355 /// ISO/IEC JTC1 SC22 WG14 N1169.
2356 bool isFixedPointType() const;
2357
2358 /// Return true if this is a fixed point or integer type.
2359 bool isFixedPointOrIntegerType() const;
2360
2361 /// Return true if this is a saturated fixed point type according to
2362 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2363 bool isSaturatedFixedPointType() const;
2364
2365 /// Return true if this is a saturated fixed point type according to
2366 /// ISO/IEC JTC1 SC22 WG14 N1169. This type can be signed or unsigned.
2367 bool isUnsaturatedFixedPointType() const;
2368
2369 /// Return true if this is a fixed point type that is signed according
2370 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2371 bool isSignedFixedPointType() const;
2372
2373 /// Return true if this is a fixed point type that is unsigned according
2374 /// to ISO/IEC JTC1 SC22 WG14 N1169. This type can also be saturated.
2375 bool isUnsignedFixedPointType() const;
2376
2377 /// Return true if this is not a variable sized type,
2378 /// according to the rules of C99 6.7.5p3. It is not legal to call this on
2379 /// incomplete types.
2380 bool isConstantSizeType() const;
2381
2382 /// Returns true if this type can be represented by some
2383 /// set of type specifiers.
2384 bool isSpecifierType() const;
2385
2386 /// Determine the linkage of this type.
2387 Linkage getLinkage() const;
2388
2389 /// Determine the visibility of this type.
2390 Visibility getVisibility() const {
2391 return getLinkageAndVisibility().getVisibility();
2392 }
2393
2394 /// Return true if the visibility was explicitly set is the code.
2395 bool isVisibilityExplicit() const {
2396 return getLinkageAndVisibility().isVisibilityExplicit();
2397 }
2398
2399 /// Determine the linkage and visibility of this type.
2400 LinkageInfo getLinkageAndVisibility() const;
2401
2402 /// True if the computed linkage is valid. Used for consistency
2403 /// checking. Should always return true.
2404 bool isLinkageValid() const;
2405
2406 /// Determine the nullability of the given type.
2407 ///
2408 /// Note that nullability is only captured as sugar within the type
2409 /// system, not as part of the canonical type, so nullability will
2410 /// be lost by canonicalization and desugaring.
2411 Optional<NullabilityKind> getNullability(const ASTContext &context) const;
2412
2413 /// Determine whether the given type can have a nullability
2414 /// specifier applied to it, i.e., if it is any kind of pointer type.
2415 ///
2416 /// \param ResultIfUnknown The value to return if we don't yet know whether
2417 /// this type can have nullability because it is dependent.
2418 bool canHaveNullability(bool ResultIfUnknown = true) const;
2419
2420 /// Retrieve the set of substitutions required when accessing a member
2421 /// of the Objective-C receiver type that is declared in the given context.
2422 ///
2423 /// \c *this is the type of the object we're operating on, e.g., the
2424 /// receiver for a message send or the base of a property access, and is
2425 /// expected to be of some object or object pointer type.
2426 ///
2427 /// \param dc The declaration context for which we are building up a
2428 /// substitution mapping, which should be an Objective-C class, extension,
2429 /// category, or method within.
2430 ///
2431 /// \returns an array of type arguments that can be substituted for
2432 /// the type parameters of the given declaration context in any type described
2433 /// within that context, or an empty optional to indicate that no
2434 /// substitution is required.
2435 Optional<ArrayRef<QualType>>
2436 getObjCSubstitutions(const DeclContext *dc) const;
2437
2438 /// Determines if this is an ObjC interface type that may accept type
2439 /// parameters.
2440 bool acceptsObjCTypeParams() const;
2441
2442 const char *getTypeClassName() const;
2443
2444 QualType getCanonicalTypeInternal() const {
2445 return CanonicalType;
2446 }
2447
2448 CanQualType getCanonicalTypeUnqualified() const; // in CanonicalType.h
2449 void dump() const;
2450 void dump(llvm::raw_ostream &OS, const ASTContext &Context) const;
2451};
2452
2453/// This will check for a TypedefType by removing any existing sugar
2454/// until it reaches a TypedefType or a non-sugared type.
2455template <> const TypedefType *Type::getAs() const;
2456
2457/// This will check for a TemplateSpecializationType by removing any
2458/// existing sugar until it reaches a TemplateSpecializationType or a
2459/// non-sugared type.
2460template <> const TemplateSpecializationType *Type::getAs() const;
2461
2462/// This will check for an AttributedType by removing any existing sugar
2463/// until it reaches an AttributedType or a non-sugared type.
2464template <> const AttributedType *Type::getAs() const;
2465
2466// We can do canonical leaf types faster, because we don't have to
2467// worry about preserving child type decoration.
2468#define TYPE(Class, Base)
2469#define LEAF_TYPE(Class) \
2470template <> inline const Class##Type *Type::getAs() const { \
2471 return dyn_cast<Class##Type>(CanonicalType); \
2472} \
2473template <> inline const Class##Type *Type::castAs() const { \
2474 return cast<Class##Type>(CanonicalType); \
2475}
2476#include "clang/AST/TypeNodes.inc"
2477
2478/// This class is used for builtin types like 'int'. Builtin
2479/// types are always canonical and have a literal name field.
2480class BuiltinType : public Type {
2481public:
2482 enum Kind {
2483// OpenCL image types
2484#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) Id,
2485#include "clang/Basic/OpenCLImageTypes.def"
2486// OpenCL extension types
2487#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) Id,
2488#include "clang/Basic/OpenCLExtensionTypes.def"
2489// SVE Types
2490#define SVE_TYPE(Name, Id, SingletonId) Id,
2491#include "clang/Basic/AArch64SVEACLETypes.def"
2492// PPC MMA Types
2493#define PPC_VECTOR_TYPE(Name, Id, Size) Id,
2494#include "clang/Basic/PPCTypes.def"
2495// RVV Types
2496#define RVV_TYPE(Name, Id, SingletonId) Id,
2497#include "clang/Basic/RISCVVTypes.def"
2498// All other builtin types
2499#define BUILTIN_TYPE(Id, SingletonId) Id,
2500#define LAST_BUILTIN_TYPE(Id) LastKind = Id
2501#include "clang/AST/BuiltinTypes.def"
2502 };
2503
2504private:
2505 friend class ASTContext; // ASTContext creates these.
2506
2507 BuiltinType(Kind K)
2508 : Type(Builtin, QualType(),
2509 K == Dependent ? TypeDependence::DependentInstantiation
2510 : TypeDependence::None) {
2511 BuiltinTypeBits.Kind = K;
2512 }
2513
2514public:
2515 Kind getKind() const { return static_cast<Kind>(BuiltinTypeBits.Kind); }
2516 StringRef getName(const PrintingPolicy &Policy) const;
2517
2518 const char *getNameAsCString(const PrintingPolicy &Policy) const {
2519 // The StringRef is null-terminated.
2520 StringRef str = getName(Policy);
2521 assert(!str.empty() && str.data()[str.size()] == '\0')((!str.empty() && str.data()[str.size()] == '\0') ? static_cast
<void> (0) : __assert_fail ("!str.empty() && str.data()[str.size()] == '\\0'"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 2521, __PRETTY_FUNCTION__))
;
2522 return str.data();
2523 }
2524
2525 bool isSugared() const { return false; }
2526 QualType desugar() const { return QualType(this, 0); }
2527
2528 bool isInteger() const {
2529 return getKind() >= Bool && getKind() <= Int128;
2530 }
2531
2532 bool isSignedInteger() const {
2533 return getKind() >= Char_S && getKind() <= Int128;
2534 }
2535
2536 bool isUnsignedInteger() const {
2537 return getKind() >= Bool && getKind() <= UInt128;
2538 }
2539
2540 bool isFloatingPoint() const {
2541 return getKind() >= Half && getKind() <= Float128;
2542 }
2543
2544 /// Determines whether the given kind corresponds to a placeholder type.
2545 static bool isPlaceholderTypeKind(Kind K) {
2546 return K >= Overload;
2547 }
2548
2549 /// Determines whether this type is a placeholder type, i.e. a type
2550 /// which cannot appear in arbitrary positions in a fully-formed
2551 /// expression.
2552 bool isPlaceholderType() const {
2553 return isPlaceholderTypeKind(getKind());
2554 }
2555
2556 /// Determines whether this type is a placeholder type other than
2557 /// Overload. Most placeholder types require only syntactic
2558 /// information about their context in order to be resolved (e.g.
2559 /// whether it is a call expression), which means they can (and
2560 /// should) be resolved in an earlier "phase" of analysis.
2561 /// Overload expressions sometimes pick up further information
2562 /// from their context, like whether the context expects a
2563 /// specific function-pointer type, and so frequently need
2564 /// special treatment.
2565 bool isNonOverloadPlaceholderType() const {
2566 return getKind() > Overload;
2567 }
2568
2569 static bool classof(const Type *T) { return T->getTypeClass() == Builtin; }
2570};
2571
2572/// Complex values, per C99 6.2.5p11. This supports the C99 complex
2573/// types (_Complex float etc) as well as the GCC integer complex extensions.
2574class ComplexType : public Type, public llvm::FoldingSetNode {
2575 friend class ASTContext; // ASTContext creates these.
2576
2577 QualType ElementType;
2578
2579 ComplexType(QualType Element, QualType CanonicalPtr)
2580 : Type(Complex, CanonicalPtr, Element->getDependence()),
2581 ElementType(Element) {}
2582
2583public:
2584 QualType getElementType() const { return ElementType; }
2585
2586 bool isSugared() const { return false; }
2587 QualType desugar() const { return QualType(this, 0); }
2588
2589 void Profile(llvm::FoldingSetNodeID &ID) {
2590 Profile(ID, getElementType());
2591 }
2592
2593 static void Profile(llvm::FoldingSetNodeID &ID, QualType Element) {
2594 ID.AddPointer(Element.getAsOpaquePtr());
2595 }
2596
2597 static bool classof(const Type *T) { return T->getTypeClass() == Complex; }
2598};
2599
2600/// Sugar for parentheses used when specifying types.
2601class ParenType : public Type, public llvm::FoldingSetNode {
2602 friend class ASTContext; // ASTContext creates these.
2603
2604 QualType Inner;
2605
2606 ParenType(QualType InnerType, QualType CanonType)
2607 : Type(Paren, CanonType, InnerType->getDependence()), Inner(InnerType) {}
2608
2609public:
2610 QualType getInnerType() const { return Inner; }
2611
2612 bool isSugared() const { return true; }
2613 QualType desugar() const { return getInnerType(); }
2614
2615 void Profile(llvm::FoldingSetNodeID &ID) {
2616 Profile(ID, getInnerType());
2617 }
2618
2619 static void Profile(llvm::FoldingSetNodeID &ID, QualType Inner) {
2620 Inner.Profile(ID);
2621 }
2622
2623 static bool classof(const Type *T) { return T->getTypeClass() == Paren; }
2624};
2625
2626/// PointerType - C99 6.7.5.1 - Pointer Declarators.
2627class PointerType : public Type, public llvm::FoldingSetNode {
2628 friend class ASTContext; // ASTContext creates these.
2629
2630 QualType PointeeType;
2631
2632 PointerType(QualType Pointee, QualType CanonicalPtr)
2633 : Type(Pointer, CanonicalPtr, Pointee->getDependence()),
2634 PointeeType(Pointee) {}
2635
2636public:
2637 QualType getPointeeType() const { return PointeeType; }
2638
2639 bool isSugared() const { return false; }
2640 QualType desugar() const { return QualType(this, 0); }
2641
2642 void Profile(llvm::FoldingSetNodeID &ID) {
2643 Profile(ID, getPointeeType());
2644 }
2645
2646 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2647 ID.AddPointer(Pointee.getAsOpaquePtr());
2648 }
2649
2650 static bool classof(const Type *T) { return T->getTypeClass() == Pointer; }
2651};
2652
2653/// Represents a type which was implicitly adjusted by the semantic
2654/// engine for arbitrary reasons. For example, array and function types can
2655/// decay, and function types can have their calling conventions adjusted.
2656class AdjustedType : public Type, public llvm::FoldingSetNode {
2657 QualType OriginalTy;
2658 QualType AdjustedTy;
2659
2660protected:
2661 friend class ASTContext; // ASTContext creates these.
2662
2663 AdjustedType(TypeClass TC, QualType OriginalTy, QualType AdjustedTy,
2664 QualType CanonicalPtr)
2665 : Type(TC, CanonicalPtr, OriginalTy->getDependence()),
2666 OriginalTy(OriginalTy), AdjustedTy(AdjustedTy) {}
2667
2668public:
2669 QualType getOriginalType() const { return OriginalTy; }
2670 QualType getAdjustedType() const { return AdjustedTy; }
2671
2672 bool isSugared() const { return true; }
2673 QualType desugar() const { return AdjustedTy; }
2674
2675 void Profile(llvm::FoldingSetNodeID &ID) {
2676 Profile(ID, OriginalTy, AdjustedTy);
2677 }
2678
2679 static void Profile(llvm::FoldingSetNodeID &ID, QualType Orig, QualType New) {
2680 ID.AddPointer(Orig.getAsOpaquePtr());
2681 ID.AddPointer(New.getAsOpaquePtr());
2682 }
2683
2684 static bool classof(const Type *T) {
2685 return T->getTypeClass() == Adjusted || T->getTypeClass() == Decayed;
2686 }
2687};
2688
2689/// Represents a pointer type decayed from an array or function type.
2690class DecayedType : public AdjustedType {
2691 friend class ASTContext; // ASTContext creates these.
2692
2693 inline
2694 DecayedType(QualType OriginalType, QualType Decayed, QualType Canonical);
2695
2696public:
2697 QualType getDecayedType() const { return getAdjustedType(); }
2698
2699 inline QualType getPointeeType() const;
2700
2701 static bool classof(const Type *T) { return T->getTypeClass() == Decayed; }
2702};
2703
2704/// Pointer to a block type.
2705/// This type is to represent types syntactically represented as
2706/// "void (^)(int)", etc. Pointee is required to always be a function type.
2707class BlockPointerType : public Type, public llvm::FoldingSetNode {
2708 friend class ASTContext; // ASTContext creates these.
2709
2710 // Block is some kind of pointer type
2711 QualType PointeeType;
2712
2713 BlockPointerType(QualType Pointee, QualType CanonicalCls)
2714 : Type(BlockPointer, CanonicalCls, Pointee->getDependence()),
2715 PointeeType(Pointee) {}
2716
2717public:
2718 // Get the pointee type. Pointee is required to always be a function type.
2719 QualType getPointeeType() const { return PointeeType; }
2720
2721 bool isSugared() const { return false; }
2722 QualType desugar() const { return QualType(this, 0); }
2723
2724 void Profile(llvm::FoldingSetNodeID &ID) {
2725 Profile(ID, getPointeeType());
2726 }
2727
2728 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee) {
2729 ID.AddPointer(Pointee.getAsOpaquePtr());
2730 }
2731
2732 static bool classof(const Type *T) {
2733 return T->getTypeClass() == BlockPointer;
2734 }
2735};
2736
2737/// Base for LValueReferenceType and RValueReferenceType
2738class ReferenceType : public Type, public llvm::FoldingSetNode {
2739 QualType PointeeType;
2740
2741protected:
2742 ReferenceType(TypeClass tc, QualType Referencee, QualType CanonicalRef,
2743 bool SpelledAsLValue)
2744 : Type(tc, CanonicalRef, Referencee->getDependence()),
2745 PointeeType(Referencee) {
2746 ReferenceTypeBits.SpelledAsLValue = SpelledAsLValue;
2747 ReferenceTypeBits.InnerRef = Referencee->isReferenceType();
2748 }
2749
2750public:
2751 bool isSpelledAsLValue() const { return ReferenceTypeBits.SpelledAsLValue; }
2752 bool isInnerRef() const { return ReferenceTypeBits.InnerRef; }
2753
2754 QualType getPointeeTypeAsWritten() const { return PointeeType; }
2755
2756 QualType getPointeeType() const {
2757 // FIXME: this might strip inner qualifiers; okay?
2758 const ReferenceType *T = this;
2759 while (T->isInnerRef())
2760 T = T->PointeeType->castAs<ReferenceType>();
2761 return T->PointeeType;
2762 }
2763
2764 void Profile(llvm::FoldingSetNodeID &ID) {
2765 Profile(ID, PointeeType, isSpelledAsLValue());
2766 }
2767
2768 static void Profile(llvm::FoldingSetNodeID &ID,
2769 QualType Referencee,
2770 bool SpelledAsLValue) {
2771 ID.AddPointer(Referencee.getAsOpaquePtr());
2772 ID.AddBoolean(SpelledAsLValue);
2773 }
2774
2775 static bool classof(const Type *T) {
2776 return T->getTypeClass() == LValueReference ||
2777 T->getTypeClass() == RValueReference;
2778 }
2779};
2780
2781/// An lvalue reference type, per C++11 [dcl.ref].
2782class LValueReferenceType : public ReferenceType {
2783 friend class ASTContext; // ASTContext creates these
2784
2785 LValueReferenceType(QualType Referencee, QualType CanonicalRef,
2786 bool SpelledAsLValue)
2787 : ReferenceType(LValueReference, Referencee, CanonicalRef,
2788 SpelledAsLValue) {}
2789
2790public:
2791 bool isSugared() const { return false; }
2792 QualType desugar() const { return QualType(this, 0); }
2793
2794 static bool classof(const Type *T) {
2795 return T->getTypeClass() == LValueReference;
2796 }
2797};
2798
2799/// An rvalue reference type, per C++11 [dcl.ref].
2800class RValueReferenceType : public ReferenceType {
2801 friend class ASTContext; // ASTContext creates these
2802
2803 RValueReferenceType(QualType Referencee, QualType CanonicalRef)
2804 : ReferenceType(RValueReference, Referencee, CanonicalRef, false) {}
2805
2806public:
2807 bool isSugared() const { return false; }
2808 QualType desugar() const { return QualType(this, 0); }
2809
2810 static bool classof(const Type *T) {
2811 return T->getTypeClass() == RValueReference;
2812 }
2813};
2814
2815/// A pointer to member type per C++ 8.3.3 - Pointers to members.
2816///
2817/// This includes both pointers to data members and pointer to member functions.
2818class MemberPointerType : public Type, public llvm::FoldingSetNode {
2819 friend class ASTContext; // ASTContext creates these.
2820
2821 QualType PointeeType;
2822
2823 /// The class of which the pointee is a member. Must ultimately be a
2824 /// RecordType, but could be a typedef or a template parameter too.
2825 const Type *Class;
2826
2827 MemberPointerType(QualType Pointee, const Type *Cls, QualType CanonicalPtr)
2828 : Type(MemberPointer, CanonicalPtr,
2829 (Cls->getDependence() & ~TypeDependence::VariablyModified) |
2830 Pointee->getDependence()),
2831 PointeeType(Pointee), Class(Cls) {}
2832
2833public:
2834 QualType getPointeeType() const { return PointeeType; }
2835
2836 /// Returns true if the member type (i.e. the pointee type) is a
2837 /// function type rather than a data-member type.
2838 bool isMemberFunctionPointer() const {
2839 return PointeeType->isFunctionProtoType();
2840 }
2841
2842 /// Returns true if the member type (i.e. the pointee type) is a
2843 /// data type rather than a function type.
2844 bool isMemberDataPointer() const {
2845 return !PointeeType->isFunctionProtoType();
2846 }
2847
2848 const Type *getClass() const { return Class; }
2849 CXXRecordDecl *getMostRecentCXXRecordDecl() const;
2850
2851 bool isSugared() const { return false; }
2852 QualType desugar() const { return QualType(this, 0); }
2853
2854 void Profile(llvm::FoldingSetNodeID &ID) {
2855 Profile(ID, getPointeeType(), getClass());
2856 }
2857
2858 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pointee,
2859 const Type *Class) {
2860 ID.AddPointer(Pointee.getAsOpaquePtr());
2861 ID.AddPointer(Class);
2862 }
2863
2864 static bool classof(const Type *T) {
2865 return T->getTypeClass() == MemberPointer;
2866 }
2867};
2868
2869/// Represents an array type, per C99 6.7.5.2 - Array Declarators.
2870class ArrayType : public Type, public llvm::FoldingSetNode {
2871public:
2872 /// Capture whether this is a normal array (e.g. int X[4])
2873 /// an array with a static size (e.g. int X[static 4]), or an array
2874 /// with a star size (e.g. int X[*]).
2875 /// 'static' is only allowed on function parameters.
2876 enum ArraySizeModifier {
2877 Normal, Static, Star
2878 };
2879
2880private:
2881 /// The element type of the array.
2882 QualType ElementType;
2883
2884protected:
2885 friend class ASTContext; // ASTContext creates these.
2886
2887 ArrayType(TypeClass tc, QualType et, QualType can, ArraySizeModifier sm,
2888 unsigned tq, const Expr *sz = nullptr);
2889
2890public:
2891 QualType getElementType() const { return ElementType; }
2892
2893 ArraySizeModifier getSizeModifier() const {
2894 return ArraySizeModifier(ArrayTypeBits.SizeModifier);
2895 }
2896
2897 Qualifiers getIndexTypeQualifiers() const {
2898 return Qualifiers::fromCVRMask(getIndexTypeCVRQualifiers());
2899 }
2900
2901 unsigned getIndexTypeCVRQualifiers() const {
2902 return ArrayTypeBits.IndexTypeQuals;
2903 }
2904
2905 static bool classof(const Type *T) {
2906 return T->getTypeClass() == ConstantArray ||
2907 T->getTypeClass() == VariableArray ||
2908 T->getTypeClass() == IncompleteArray ||
2909 T->getTypeClass() == DependentSizedArray;
2910 }
2911};
2912
2913/// Represents the canonical version of C arrays with a specified constant size.
2914/// For example, the canonical type for 'int A[4 + 4*100]' is a
2915/// ConstantArrayType where the element type is 'int' and the size is 404.
2916class ConstantArrayType final
2917 : public ArrayType,
2918 private llvm::TrailingObjects<ConstantArrayType, const Expr *> {
2919 friend class ASTContext; // ASTContext creates these.
2920 friend TrailingObjects;
2921
2922 llvm::APInt Size; // Allows us to unique the type.
2923
2924 ConstantArrayType(QualType et, QualType can, const llvm::APInt &size,
2925 const Expr *sz, ArraySizeModifier sm, unsigned tq)
2926 : ArrayType(ConstantArray, et, can, sm, tq, sz), Size(size) {
2927 ConstantArrayTypeBits.HasStoredSizeExpr = sz != nullptr;
2928 if (ConstantArrayTypeBits.HasStoredSizeExpr) {
2929 assert(!can.isNull() && "canonical constant array should not have size")((!can.isNull() && "canonical constant array should not have size"
) ? static_cast<void> (0) : __assert_fail ("!can.isNull() && \"canonical constant array should not have size\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 2929, __PRETTY_FUNCTION__))
;
2930 *getTrailingObjects<const Expr*>() = sz;
2931 }
2932 }
2933
2934 unsigned numTrailingObjects(OverloadToken<const Expr*>) const {
2935 return ConstantArrayTypeBits.HasStoredSizeExpr;
2936 }
2937
2938public:
2939 const llvm::APInt &getSize() const { return Size; }
2940 const Expr *getSizeExpr() const {
2941 return ConstantArrayTypeBits.HasStoredSizeExpr
2942 ? *getTrailingObjects<const Expr *>()
2943 : nullptr;
2944 }
2945 bool isSugared() const { return false; }
2946 QualType desugar() const { return QualType(this, 0); }
2947
2948 /// Determine the number of bits required to address a member of
2949 // an array with the given element type and number of elements.
2950 static unsigned getNumAddressingBits(const ASTContext &Context,
2951 QualType ElementType,
2952 const llvm::APInt &NumElements);
2953
2954 /// Determine the maximum number of active bits that an array's size
2955 /// can require, which limits the maximum size of the array.
2956 static unsigned getMaxSizeBits(const ASTContext &Context);
2957
2958 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
2959 Profile(ID, Ctx, getElementType(), getSize(), getSizeExpr(),
2960 getSizeModifier(), getIndexTypeCVRQualifiers());
2961 }
2962
2963 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx,
2964 QualType ET, const llvm::APInt &ArraySize,
2965 const Expr *SizeExpr, ArraySizeModifier SizeMod,
2966 unsigned TypeQuals);
2967
2968 static bool classof(const Type *T) {
2969 return T->getTypeClass() == ConstantArray;
2970 }
2971};
2972
2973/// Represents a C array with an unspecified size. For example 'int A[]' has
2974/// an IncompleteArrayType where the element type is 'int' and the size is
2975/// unspecified.
2976class IncompleteArrayType : public ArrayType {
2977 friend class ASTContext; // ASTContext creates these.
2978
2979 IncompleteArrayType(QualType et, QualType can,
2980 ArraySizeModifier sm, unsigned tq)
2981 : ArrayType(IncompleteArray, et, can, sm, tq) {}
2982
2983public:
2984 friend class StmtIteratorBase;
2985
2986 bool isSugared() const { return false; }
2987 QualType desugar() const { return QualType(this, 0); }
2988
2989 static bool classof(const Type *T) {
2990 return T->getTypeClass() == IncompleteArray;
2991 }
2992
2993 void Profile(llvm::FoldingSetNodeID &ID) {
2994 Profile(ID, getElementType(), getSizeModifier(),
2995 getIndexTypeCVRQualifiers());
2996 }
2997
2998 static void Profile(llvm::FoldingSetNodeID &ID, QualType ET,
2999 ArraySizeModifier SizeMod, unsigned TypeQuals) {
3000 ID.AddPointer(ET.getAsOpaquePtr());
3001 ID.AddInteger(SizeMod);
3002 ID.AddInteger(TypeQuals);
3003 }
3004};
3005
3006/// Represents a C array with a specified size that is not an
3007/// integer-constant-expression. For example, 'int s[x+foo()]'.
3008/// Since the size expression is an arbitrary expression, we store it as such.
3009///
3010/// Note: VariableArrayType's aren't uniqued (since the expressions aren't) and
3011/// should not be: two lexically equivalent variable array types could mean
3012/// different things, for example, these variables do not have the same type
3013/// dynamically:
3014///
3015/// void foo(int x) {
3016/// int Y[x];
3017/// ++x;
3018/// int Z[x];
3019/// }
3020class VariableArrayType : public ArrayType {
3021 friend class ASTContext; // ASTContext creates these.
3022
3023 /// An assignment-expression. VLA's are only permitted within
3024 /// a function block.
3025 Stmt *SizeExpr;
3026
3027 /// The range spanned by the left and right array brackets.
3028 SourceRange Brackets;
3029
3030 VariableArrayType(QualType et, QualType can, Expr *e,
3031 ArraySizeModifier sm, unsigned tq,
3032 SourceRange brackets)
3033 : ArrayType(VariableArray, et, can, sm, tq, e),
3034 SizeExpr((Stmt*) e), Brackets(brackets) {}
3035
3036public:
3037 friend class StmtIteratorBase;
3038
3039 Expr *getSizeExpr() const {
3040 // We use C-style casts instead of cast<> here because we do not wish
3041 // to have a dependency of Type.h on Stmt.h/Expr.h.
3042 return (Expr*) SizeExpr;
3043 }
3044
3045 SourceRange getBracketsRange() const { return Brackets; }
3046 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3047 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3048
3049 bool isSugared() const { return false; }
3050 QualType desugar() const { return QualType(this, 0); }
3051
3052 static bool classof(const Type *T) {
3053 return T->getTypeClass() == VariableArray;
3054 }
3055
3056 void Profile(llvm::FoldingSetNodeID &ID) {
3057 llvm_unreachable("Cannot unique VariableArrayTypes.")::llvm::llvm_unreachable_internal("Cannot unique VariableArrayTypes."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3057)
;
3058 }
3059};
3060
3061/// Represents an array type in C++ whose size is a value-dependent expression.
3062///
3063/// For example:
3064/// \code
3065/// template<typename T, int Size>
3066/// class array {
3067/// T data[Size];
3068/// };
3069/// \endcode
3070///
3071/// For these types, we won't actually know what the array bound is
3072/// until template instantiation occurs, at which point this will
3073/// become either a ConstantArrayType or a VariableArrayType.
3074class DependentSizedArrayType : public ArrayType {
3075 friend class ASTContext; // ASTContext creates these.
3076
3077 const ASTContext &Context;
3078
3079 /// An assignment expression that will instantiate to the
3080 /// size of the array.
3081 ///
3082 /// The expression itself might be null, in which case the array
3083 /// type will have its size deduced from an initializer.
3084 Stmt *SizeExpr;
3085
3086 /// The range spanned by the left and right array brackets.
3087 SourceRange Brackets;
3088
3089 DependentSizedArrayType(const ASTContext &Context, QualType et, QualType can,
3090 Expr *e, ArraySizeModifier sm, unsigned tq,
3091 SourceRange brackets);
3092
3093public:
3094 friend class StmtIteratorBase;
3095
3096 Expr *getSizeExpr() const {
3097 // We use C-style casts instead of cast<> here because we do not wish
3098 // to have a dependency of Type.h on Stmt.h/Expr.h.
3099 return (Expr*) SizeExpr;
3100 }
3101
3102 SourceRange getBracketsRange() const { return Brackets; }
3103 SourceLocation getLBracketLoc() const { return Brackets.getBegin(); }
3104 SourceLocation getRBracketLoc() const { return Brackets.getEnd(); }
3105
3106 bool isSugared() const { return false; }
3107 QualType desugar() const { return QualType(this, 0); }
3108
3109 static bool classof(const Type *T) {
3110 return T->getTypeClass() == DependentSizedArray;
3111 }
3112
3113 void Profile(llvm::FoldingSetNodeID &ID) {
3114 Profile(ID, Context, getElementType(),
3115 getSizeModifier(), getIndexTypeCVRQualifiers(), getSizeExpr());
3116 }
3117
3118 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3119 QualType ET, ArraySizeModifier SizeMod,
3120 unsigned TypeQuals, Expr *E);
3121};
3122
3123/// Represents an extended address space qualifier where the input address space
3124/// value is dependent. Non-dependent address spaces are not represented with a
3125/// special Type subclass; they are stored on an ExtQuals node as part of a QualType.
3126///
3127/// For example:
3128/// \code
3129/// template<typename T, int AddrSpace>
3130/// class AddressSpace {
3131/// typedef T __attribute__((address_space(AddrSpace))) type;
3132/// }
3133/// \endcode
3134class DependentAddressSpaceType : public Type, public llvm::FoldingSetNode {
3135 friend class ASTContext;
3136
3137 const ASTContext &Context;
3138 Expr *AddrSpaceExpr;
3139 QualType PointeeType;
3140 SourceLocation loc;
3141
3142 DependentAddressSpaceType(const ASTContext &Context, QualType PointeeType,
3143 QualType can, Expr *AddrSpaceExpr,
3144 SourceLocation loc);
3145
3146public:
3147 Expr *getAddrSpaceExpr() const { return AddrSpaceExpr; }
3148 QualType getPointeeType() const { return PointeeType; }
3149 SourceLocation getAttributeLoc() const { return loc; }
3150
3151 bool isSugared() const { return false; }
3152 QualType desugar() const { return QualType(this, 0); }
3153
3154 static bool classof(const Type *T) {
3155 return T->getTypeClass() == DependentAddressSpace;
3156 }
3157
3158 void Profile(llvm::FoldingSetNodeID &ID) {
3159 Profile(ID, Context, getPointeeType(), getAddrSpaceExpr());
3160 }
3161
3162 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3163 QualType PointeeType, Expr *AddrSpaceExpr);
3164};
3165
3166/// Represents an extended vector type where either the type or size is
3167/// dependent.
3168///
3169/// For example:
3170/// \code
3171/// template<typename T, int Size>
3172/// class vector {
3173/// typedef T __attribute__((ext_vector_type(Size))) type;
3174/// }
3175/// \endcode
3176class DependentSizedExtVectorType : public Type, public llvm::FoldingSetNode {
3177 friend class ASTContext;
3178
3179 const ASTContext &Context;
3180 Expr *SizeExpr;
3181
3182 /// The element type of the array.
3183 QualType ElementType;
3184
3185 SourceLocation loc;
3186
3187 DependentSizedExtVectorType(const ASTContext &Context, QualType ElementType,
3188 QualType can, Expr *SizeExpr, SourceLocation loc);
3189
3190public:
3191 Expr *getSizeExpr() const { return SizeExpr; }
3192 QualType getElementType() const { return ElementType; }
3193 SourceLocation getAttributeLoc() const { return loc; }
3194
3195 bool isSugared() const { return false; }
3196 QualType desugar() const { return QualType(this, 0); }
3197
3198 static bool classof(const Type *T) {
3199 return T->getTypeClass() == DependentSizedExtVector;
3200 }
3201
3202 void Profile(llvm::FoldingSetNodeID &ID) {
3203 Profile(ID, Context, getElementType(), getSizeExpr());
3204 }
3205
3206 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3207 QualType ElementType, Expr *SizeExpr);
3208};
3209
3210
3211/// Represents a GCC generic vector type. This type is created using
3212/// __attribute__((vector_size(n)), where "n" specifies the vector size in
3213/// bytes; or from an Altivec __vector or vector declaration.
3214/// Since the constructor takes the number of vector elements, the
3215/// client is responsible for converting the size into the number of elements.
3216class VectorType : public Type, public llvm::FoldingSetNode {
3217public:
3218 enum VectorKind {
3219 /// not a target-specific vector type
3220 GenericVector,
3221
3222 /// is AltiVec vector
3223 AltiVecVector,
3224
3225 /// is AltiVec 'vector Pixel'
3226 AltiVecPixel,
3227
3228 /// is AltiVec 'vector bool ...'
3229 AltiVecBool,
3230
3231 /// is ARM Neon vector
3232 NeonVector,
3233
3234 /// is ARM Neon polynomial vector
3235 NeonPolyVector,
3236
3237 /// is AArch64 SVE fixed-length data vector
3238 SveFixedLengthDataVector,
3239
3240 /// is AArch64 SVE fixed-length predicate vector
3241 SveFixedLengthPredicateVector
3242 };
3243
3244protected:
3245 friend class ASTContext; // ASTContext creates these.
3246
3247 /// The element type of the vector.
3248 QualType ElementType;
3249
3250 VectorType(QualType vecType, unsigned nElements, QualType canonType,
3251 VectorKind vecKind);
3252
3253 VectorType(TypeClass tc, QualType vecType, unsigned nElements,
3254 QualType canonType, VectorKind vecKind);
3255
3256public:
3257 QualType getElementType() const { return ElementType; }
3258 unsigned getNumElements() const { return VectorTypeBits.NumElements; }
3259
3260 bool isSugared() const { return false; }
3261 QualType desugar() const { return QualType(this, 0); }
3262
3263 VectorKind getVectorKind() const {
3264 return VectorKind(VectorTypeBits.VecKind);
3265 }
3266
3267 void Profile(llvm::FoldingSetNodeID &ID) {
3268 Profile(ID, getElementType(), getNumElements(),
3269 getTypeClass(), getVectorKind());
3270 }
3271
3272 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3273 unsigned NumElements, TypeClass TypeClass,
3274 VectorKind VecKind) {
3275 ID.AddPointer(ElementType.getAsOpaquePtr());
3276 ID.AddInteger(NumElements);
3277 ID.AddInteger(TypeClass);
3278 ID.AddInteger(VecKind);
3279 }
3280
3281 static bool classof(const Type *T) {
3282 return T->getTypeClass() == Vector || T->getTypeClass() == ExtVector;
3283 }
3284};
3285
3286/// Represents a vector type where either the type or size is dependent.
3287////
3288/// For example:
3289/// \code
3290/// template<typename T, int Size>
3291/// class vector {
3292/// typedef T __attribute__((vector_size(Size))) type;
3293/// }
3294/// \endcode
3295class DependentVectorType : public Type, public llvm::FoldingSetNode {
3296 friend class ASTContext;
3297
3298 const ASTContext &Context;
3299 QualType ElementType;
3300 Expr *SizeExpr;
3301 SourceLocation Loc;
3302
3303 DependentVectorType(const ASTContext &Context, QualType ElementType,
3304 QualType CanonType, Expr *SizeExpr,
3305 SourceLocation Loc, VectorType::VectorKind vecKind);
3306
3307public:
3308 Expr *getSizeExpr() const { return SizeExpr; }
3309 QualType getElementType() const { return ElementType; }
3310 SourceLocation getAttributeLoc() const { return Loc; }
3311 VectorType::VectorKind getVectorKind() const {
3312 return VectorType::VectorKind(VectorTypeBits.VecKind);
3313 }
3314
3315 bool isSugared() const { return false; }
3316 QualType desugar() const { return QualType(this, 0); }
3317
3318 static bool classof(const Type *T) {
3319 return T->getTypeClass() == DependentVector;
3320 }
3321
3322 void Profile(llvm::FoldingSetNodeID &ID) {
3323 Profile(ID, Context, getElementType(), getSizeExpr(), getVectorKind());
3324 }
3325
3326 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3327 QualType ElementType, const Expr *SizeExpr,
3328 VectorType::VectorKind VecKind);
3329};
3330
3331/// ExtVectorType - Extended vector type. This type is created using
3332/// __attribute__((ext_vector_type(n)), where "n" is the number of elements.
3333/// Unlike vector_size, ext_vector_type is only allowed on typedef's. This
3334/// class enables syntactic extensions, like Vector Components for accessing
3335/// points (as .xyzw), colors (as .rgba), and textures (modeled after OpenGL
3336/// Shading Language).
3337class ExtVectorType : public VectorType {
3338 friend class ASTContext; // ASTContext creates these.
3339
3340 ExtVectorType(QualType vecType, unsigned nElements, QualType canonType)
3341 : VectorType(ExtVector, vecType, nElements, canonType, GenericVector) {}
3342
3343public:
3344 static int getPointAccessorIdx(char c) {
3345 switch (c) {
3346 default: return -1;
3347 case 'x': case 'r': return 0;
3348 case 'y': case 'g': return 1;
3349 case 'z': case 'b': return 2;
3350 case 'w': case 'a': return 3;
3351 }
3352 }
3353
3354 static int getNumericAccessorIdx(char c) {
3355 switch (c) {
3356 default: return -1;
3357 case '0': return 0;
3358 case '1': return 1;
3359 case '2': return 2;
3360 case '3': return 3;
3361 case '4': return 4;
3362 case '5': return 5;
3363 case '6': return 6;
3364 case '7': return 7;
3365 case '8': return 8;
3366 case '9': return 9;
3367 case 'A':
3368 case 'a': return 10;
3369 case 'B':
3370 case 'b': return 11;
3371 case 'C':
3372 case 'c': return 12;
3373 case 'D':
3374 case 'd': return 13;
3375 case 'E':
3376 case 'e': return 14;
3377 case 'F':
3378 case 'f': return 15;
3379 }
3380 }
3381
3382 static int getAccessorIdx(char c, bool isNumericAccessor) {
3383 if (isNumericAccessor)
3384 return getNumericAccessorIdx(c);
3385 else
3386 return getPointAccessorIdx(c);
3387 }
3388
3389 bool isAccessorWithinNumElements(char c, bool isNumericAccessor) const {
3390 if (int idx = getAccessorIdx(c, isNumericAccessor)+1)
3391 return unsigned(idx-1) < getNumElements();
3392 return false;
3393 }
3394
3395 bool isSugared() const { return false; }
3396 QualType desugar() const { return QualType(this, 0); }
3397
3398 static bool classof(const Type *T) {
3399 return T->getTypeClass() == ExtVector;
3400 }
3401};
3402
3403/// Represents a matrix type, as defined in the Matrix Types clang extensions.
3404/// __attribute__((matrix_type(rows, columns))), where "rows" specifies
3405/// number of rows and "columns" specifies the number of columns.
3406class MatrixType : public Type, public llvm::FoldingSetNode {
3407protected:
3408 friend class ASTContext;
3409
3410 /// The element type of the matrix.
3411 QualType ElementType;
3412
3413 MatrixType(QualType ElementTy, QualType CanonElementTy);
3414
3415 MatrixType(TypeClass TypeClass, QualType ElementTy, QualType CanonElementTy,
3416 const Expr *RowExpr = nullptr, const Expr *ColumnExpr = nullptr);
3417
3418public:
3419 /// Returns type of the elements being stored in the matrix
3420 QualType getElementType() const { return ElementType; }
3421
3422 /// Valid elements types are the following:
3423 /// * an integer type (as in C2x 6.2.5p19), but excluding enumerated types
3424 /// and _Bool
3425 /// * the standard floating types float or double
3426 /// * a half-precision floating point type, if one is supported on the target
3427 static bool isValidElementType(QualType T) {
3428 return T->isDependentType() ||
3429 (T->isRealType() && !T->isBooleanType() && !T->isEnumeralType());
3430 }
3431
3432 bool isSugared() const { return false; }
3433 QualType desugar() const { return QualType(this, 0); }
3434
3435 static bool classof(const Type *T) {
3436 return T->getTypeClass() == ConstantMatrix ||
3437 T->getTypeClass() == DependentSizedMatrix;
3438 }
3439};
3440
3441/// Represents a concrete matrix type with constant number of rows and columns
3442class ConstantMatrixType final : public MatrixType {
3443protected:
3444 friend class ASTContext;
3445
3446 /// The element type of the matrix.
3447 // FIXME: Appears to be unused? There is also MatrixType::ElementType...
3448 QualType ElementType;
3449
3450 /// Number of rows and columns.
3451 unsigned NumRows;
3452 unsigned NumColumns;
3453
3454 static constexpr unsigned MaxElementsPerDimension = (1 << 20) - 1;
3455
3456 ConstantMatrixType(QualType MatrixElementType, unsigned NRows,
3457 unsigned NColumns, QualType CanonElementType);
3458
3459 ConstantMatrixType(TypeClass typeClass, QualType MatrixType, unsigned NRows,
3460 unsigned NColumns, QualType CanonElementType);
3461
3462public:
3463 /// Returns the number of rows in the matrix.
3464 unsigned getNumRows() const { return NumRows; }
3465
3466 /// Returns the number of columns in the matrix.
3467 unsigned getNumColumns() const { return NumColumns; }
3468
3469 /// Returns the number of elements required to embed the matrix into a vector.
3470 unsigned getNumElementsFlattened() const {
3471 return getNumRows() * getNumColumns();
3472 }
3473
3474 /// Returns true if \p NumElements is a valid matrix dimension.
3475 static constexpr bool isDimensionValid(size_t NumElements) {
3476 return NumElements > 0 && NumElements <= MaxElementsPerDimension;
3477 }
3478
3479 /// Returns the maximum number of elements per dimension.
3480 static constexpr unsigned getMaxElementsPerDimension() {
3481 return MaxElementsPerDimension;
3482 }
3483
3484 void Profile(llvm::FoldingSetNodeID &ID) {
3485 Profile(ID, getElementType(), getNumRows(), getNumColumns(),
3486 getTypeClass());
3487 }
3488
3489 static void Profile(llvm::FoldingSetNodeID &ID, QualType ElementType,
3490 unsigned NumRows, unsigned NumColumns,
3491 TypeClass TypeClass) {
3492 ID.AddPointer(ElementType.getAsOpaquePtr());
3493 ID.AddInteger(NumRows);
3494 ID.AddInteger(NumColumns);
3495 ID.AddInteger(TypeClass);
3496 }
3497
3498 static bool classof(const Type *T) {
3499 return T->getTypeClass() == ConstantMatrix;
3500 }
3501};
3502
3503/// Represents a matrix type where the type and the number of rows and columns
3504/// is dependent on a template.
3505class DependentSizedMatrixType final : public MatrixType {
3506 friend class ASTContext;
3507
3508 const ASTContext &Context;
3509 Expr *RowExpr;
3510 Expr *ColumnExpr;
3511
3512 SourceLocation loc;
3513
3514 DependentSizedMatrixType(const ASTContext &Context, QualType ElementType,
3515 QualType CanonicalType, Expr *RowExpr,
3516 Expr *ColumnExpr, SourceLocation loc);
3517
3518public:
3519 QualType getElementType() const { return ElementType; }
3520 Expr *getRowExpr() const { return RowExpr; }
3521 Expr *getColumnExpr() const { return ColumnExpr; }
3522 SourceLocation getAttributeLoc() const { return loc; }
3523
3524 bool isSugared() const { return false; }
3525 QualType desugar() const { return QualType(this, 0); }
3526
3527 static bool classof(const Type *T) {
3528 return T->getTypeClass() == DependentSizedMatrix;
3529 }
3530
3531 void Profile(llvm::FoldingSetNodeID &ID) {
3532 Profile(ID, Context, getElementType(), getRowExpr(), getColumnExpr());
3533 }
3534
3535 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
3536 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr);
3537};
3538
3539/// FunctionType - C99 6.7.5.3 - Function Declarators. This is the common base
3540/// class of FunctionNoProtoType and FunctionProtoType.
3541class FunctionType : public Type {
3542 // The type returned by the function.
3543 QualType ResultType;
3544
3545public:
3546 /// Interesting information about a specific parameter that can't simply
3547 /// be reflected in parameter's type. This is only used by FunctionProtoType
3548 /// but is in FunctionType to make this class available during the
3549 /// specification of the bases of FunctionProtoType.
3550 ///
3551 /// It makes sense to model language features this way when there's some
3552 /// sort of parameter-specific override (such as an attribute) that
3553 /// affects how the function is called. For example, the ARC ns_consumed
3554 /// attribute changes whether a parameter is passed at +0 (the default)
3555 /// or +1 (ns_consumed). This must be reflected in the function type,
3556 /// but isn't really a change to the parameter type.
3557 ///
3558 /// One serious disadvantage of modelling language features this way is
3559 /// that they generally do not work with language features that attempt
3560 /// to destructure types. For example, template argument deduction will
3561 /// not be able to match a parameter declared as
3562 /// T (*)(U)
3563 /// against an argument of type
3564 /// void (*)(__attribute__((ns_consumed)) id)
3565 /// because the substitution of T=void, U=id into the former will
3566 /// not produce the latter.
3567 class ExtParameterInfo {
3568 enum {
3569 ABIMask = 0x0F,
3570 IsConsumed = 0x10,
3571 HasPassObjSize = 0x20,
3572 IsNoEscape = 0x40,
3573 };
3574 unsigned char Data = 0;
3575
3576 public:
3577 ExtParameterInfo() = default;
3578
3579 /// Return the ABI treatment of this parameter.
3580 ParameterABI getABI() const { return ParameterABI(Data & ABIMask); }
3581 ExtParameterInfo withABI(ParameterABI kind) const {
3582 ExtParameterInfo copy = *this;
3583 copy.Data = (copy.Data & ~ABIMask) | unsigned(kind);
3584 return copy;
3585 }
3586
3587 /// Is this parameter considered "consumed" by Objective-C ARC?
3588 /// Consumed parameters must have retainable object type.
3589 bool isConsumed() const { return (Data & IsConsumed); }
3590 ExtParameterInfo withIsConsumed(bool consumed) const {
3591 ExtParameterInfo copy = *this;
3592 if (consumed)
3593 copy.Data |= IsConsumed;
3594 else
3595 copy.Data &= ~IsConsumed;
3596 return copy;
3597 }
3598
3599 bool hasPassObjectSize() const { return Data & HasPassObjSize; }
3600 ExtParameterInfo withHasPassObjectSize() const {
3601 ExtParameterInfo Copy = *this;
3602 Copy.Data |= HasPassObjSize;
3603 return Copy;
3604 }
3605
3606 bool isNoEscape() const { return Data & IsNoEscape; }
3607 ExtParameterInfo withIsNoEscape(bool NoEscape) const {
3608 ExtParameterInfo Copy = *this;
3609 if (NoEscape)
3610 Copy.Data |= IsNoEscape;
3611 else
3612 Copy.Data &= ~IsNoEscape;
3613 return Copy;
3614 }
3615
3616 unsigned char getOpaqueValue() const { return Data; }
3617 static ExtParameterInfo getFromOpaqueValue(unsigned char data) {
3618 ExtParameterInfo result;
3619 result.Data = data;
3620 return result;
3621 }
3622
3623 friend bool operator==(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3624 return lhs.Data == rhs.Data;
3625 }
3626
3627 friend bool operator!=(ExtParameterInfo lhs, ExtParameterInfo rhs) {
3628 return lhs.Data != rhs.Data;
3629 }
3630 };
3631
3632 /// A class which abstracts out some details necessary for
3633 /// making a call.
3634 ///
3635 /// It is not actually used directly for storing this information in
3636 /// a FunctionType, although FunctionType does currently use the
3637 /// same bit-pattern.
3638 ///
3639 // If you add a field (say Foo), other than the obvious places (both,
3640 // constructors, compile failures), what you need to update is
3641 // * Operator==
3642 // * getFoo
3643 // * withFoo
3644 // * functionType. Add Foo, getFoo.
3645 // * ASTContext::getFooType
3646 // * ASTContext::mergeFunctionTypes
3647 // * FunctionNoProtoType::Profile
3648 // * FunctionProtoType::Profile
3649 // * TypePrinter::PrintFunctionProto
3650 // * AST read and write
3651 // * Codegen
3652 class ExtInfo {
3653 friend class FunctionType;
3654
3655 // Feel free to rearrange or add bits, but if you go over 16, you'll need to
3656 // adjust the Bits field below, and if you add bits, you'll need to adjust
3657 // Type::FunctionTypeBitfields::ExtInfo as well.
3658
3659 // | CC |noreturn|produces|nocallersavedregs|regparm|nocfcheck|cmsenscall|
3660 // |0 .. 4| 5 | 6 | 7 |8 .. 10| 11 | 12 |
3661 //
3662 // regparm is either 0 (no regparm attribute) or the regparm value+1.
3663 enum { CallConvMask = 0x1F };
3664 enum { NoReturnMask = 0x20 };
3665 enum { ProducesResultMask = 0x40 };
3666 enum { NoCallerSavedRegsMask = 0x80 };
3667 enum {
3668 RegParmMask = 0x700,
3669 RegParmOffset = 8
3670 };
3671 enum { NoCfCheckMask = 0x800 };
3672 enum { CmseNSCallMask = 0x1000 };
3673 uint16_t Bits = CC_C;
3674
3675 ExtInfo(unsigned Bits) : Bits(static_cast<uint16_t>(Bits)) {}
3676
3677 public:
3678 // Constructor with no defaults. Use this when you know that you
3679 // have all the elements (when reading an AST file for example).
3680 ExtInfo(bool noReturn, bool hasRegParm, unsigned regParm, CallingConv cc,
3681 bool producesResult, bool noCallerSavedRegs, bool NoCfCheck,
3682 bool cmseNSCall) {
3683 assert((!hasRegParm || regParm < 7) && "Invalid regparm value")(((!hasRegParm || regParm < 7) && "Invalid regparm value"
) ? static_cast<void> (0) : __assert_fail ("(!hasRegParm || regParm < 7) && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3683, __PRETTY_FUNCTION__))
;
3684 Bits = ((unsigned)cc) | (noReturn ? NoReturnMask : 0) |
3685 (producesResult ? ProducesResultMask : 0) |
3686 (noCallerSavedRegs ? NoCallerSavedRegsMask : 0) |
3687 (hasRegParm ? ((regParm + 1) << RegParmOffset) : 0) |
3688 (NoCfCheck ? NoCfCheckMask : 0) |
3689 (cmseNSCall ? CmseNSCallMask : 0);
3690 }
3691
3692 // Constructor with all defaults. Use when for example creating a
3693 // function known to use defaults.
3694 ExtInfo() = default;
3695
3696 // Constructor with just the calling convention, which is an important part
3697 // of the canonical type.
3698 ExtInfo(CallingConv CC) : Bits(CC) {}
3699
3700 bool getNoReturn() const { return Bits & NoReturnMask; }
3701 bool getProducesResult() const { return Bits & ProducesResultMask; }
3702 bool getCmseNSCall() const { return Bits & CmseNSCallMask; }
3703 bool getNoCallerSavedRegs() const { return Bits & NoCallerSavedRegsMask; }
3704 bool getNoCfCheck() const { return Bits & NoCfCheckMask; }
3705 bool getHasRegParm() const { return ((Bits & RegParmMask) >> RegParmOffset) != 0; }
3706
3707 unsigned getRegParm() const {
3708 unsigned RegParm = (Bits & RegParmMask) >> RegParmOffset;
3709 if (RegParm > 0)
3710 --RegParm;
3711 return RegParm;
3712 }
3713
3714 CallingConv getCC() const { return CallingConv(Bits & CallConvMask); }
3715
3716 bool operator==(ExtInfo Other) const {
3717 return Bits == Other.Bits;
3718 }
3719 bool operator!=(ExtInfo Other) const {
3720 return Bits != Other.Bits;
3721 }
3722
3723 // Note that we don't have setters. That is by design, use
3724 // the following with methods instead of mutating these objects.
3725
3726 ExtInfo withNoReturn(bool noReturn) const {
3727 if (noReturn)
3728 return ExtInfo(Bits | NoReturnMask);
3729 else
3730 return ExtInfo(Bits & ~NoReturnMask);
3731 }
3732
3733 ExtInfo withProducesResult(bool producesResult) const {
3734 if (producesResult)
3735 return ExtInfo(Bits | ProducesResultMask);
3736 else
3737 return ExtInfo(Bits & ~ProducesResultMask);
3738 }
3739
3740 ExtInfo withCmseNSCall(bool cmseNSCall) const {
3741 if (cmseNSCall)
3742 return ExtInfo(Bits | CmseNSCallMask);
3743 else
3744 return ExtInfo(Bits & ~CmseNSCallMask);
3745 }
3746
3747 ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const {
3748 if (noCallerSavedRegs)
3749 return ExtInfo(Bits | NoCallerSavedRegsMask);
3750 else
3751 return ExtInfo(Bits & ~NoCallerSavedRegsMask);
3752 }
3753
3754 ExtInfo withNoCfCheck(bool noCfCheck) const {
3755 if (noCfCheck)
3756 return ExtInfo(Bits | NoCfCheckMask);
3757 else
3758 return ExtInfo(Bits & ~NoCfCheckMask);
3759 }
3760
3761 ExtInfo withRegParm(unsigned RegParm) const {
3762 assert(RegParm < 7 && "Invalid regparm value")((RegParm < 7 && "Invalid regparm value") ? static_cast
<void> (0) : __assert_fail ("RegParm < 7 && \"Invalid regparm value\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 3762, __PRETTY_FUNCTION__))
;
3763 return ExtInfo((Bits & ~RegParmMask) |
3764 ((RegParm + 1) << RegParmOffset));
3765 }
3766
3767 ExtInfo withCallingConv(CallingConv cc) const {
3768 return ExtInfo((Bits & ~CallConvMask) | (unsigned) cc);
3769 }
3770
3771 void Profile(llvm::FoldingSetNodeID &ID) const {
3772 ID.AddInteger(Bits);
3773 }
3774 };
3775
3776 /// A simple holder for a QualType representing a type in an
3777 /// exception specification. Unfortunately needed by FunctionProtoType
3778 /// because TrailingObjects cannot handle repeated types.
3779 struct ExceptionType { QualType Type; };
3780
3781 /// A simple holder for various uncommon bits which do not fit in
3782 /// FunctionTypeBitfields. Aligned to alignof(void *) to maintain the
3783 /// alignment of subsequent objects in TrailingObjects. You must update
3784 /// hasExtraBitfields in FunctionProtoType after adding extra data here.
3785 struct alignas(void *) FunctionTypeExtraBitfields {
3786 /// The number of types in the exception specification.
3787 /// A whole unsigned is not needed here and according to
3788 /// [implimits] 8 bits would be enough here.
3789 unsigned NumExceptionType;
3790 };
3791
3792protected:
3793 FunctionType(TypeClass tc, QualType res, QualType Canonical,
3794 TypeDependence Dependence, ExtInfo Info)
3795 : Type(tc, Canonical, Dependence), ResultType(res) {
3796 FunctionTypeBits.ExtInfo = Info.Bits;
3797 }
3798
3799 Qualifiers getFastTypeQuals() const {
3800 return Qualifiers::fromFastMask(FunctionTypeBits.FastTypeQuals);
3801 }
3802
3803public:
3804 QualType getReturnType() const { return ResultType; }
3805
3806 bool getHasRegParm() const { return getExtInfo().getHasRegParm(); }
3807 unsigned getRegParmType() const { return getExtInfo().getRegParm(); }
3808
3809 /// Determine whether this function type includes the GNU noreturn
3810 /// attribute. The C++11 [[noreturn]] attribute does not affect the function
3811 /// type.
3812 bool getNoReturnAttr() const { return getExtInfo().getNoReturn(); }
3813
3814 bool getCmseNSCallAttr() const { return getExtInfo().getCmseNSCall(); }
3815 CallingConv getCallConv() const { return getExtInfo().getCC(); }
3816 ExtInfo getExtInfo() const { return ExtInfo(FunctionTypeBits.ExtInfo); }
3817
3818 static_assert((~Qualifiers::FastMask & Qualifiers::CVRMask) == 0,
3819 "Const, volatile and restrict are assumed to be a subset of "
3820 "the fast qualifiers.");
3821
3822 bool isConst() const { return getFastTypeQuals().hasConst(); }
3823 bool isVolatile() const { return getFastTypeQuals().hasVolatile(); }
3824 bool isRestrict() const { return getFastTypeQuals().hasRestrict(); }
3825
3826 /// Determine the type of an expression that calls a function of
3827 /// this type.
3828 QualType getCallResultType(const ASTContext &Context) const {
3829 return getReturnType().getNonLValueExprType(Context);
3830 }
3831
3832 static StringRef getNameForCallConv(CallingConv CC);
3833
3834 static bool classof(const Type *T) {
3835 return T->getTypeClass() == FunctionNoProto ||
3836 T->getTypeClass() == FunctionProto;
3837 }
3838};
3839
3840/// Represents a K&R-style 'int foo()' function, which has
3841/// no information available about its arguments.
3842class FunctionNoProtoType : public FunctionType, public llvm::FoldingSetNode {
3843 friend class ASTContext; // ASTContext creates these.
3844
3845 FunctionNoProtoType(QualType Result, QualType Canonical, ExtInfo Info)
3846 : FunctionType(FunctionNoProto, Result, Canonical,
3847 Result->getDependence() &
3848 ~(TypeDependence::DependentInstantiation |
3849 TypeDependence::UnexpandedPack),
3850 Info) {}
3851
3852public:
3853 // No additional state past what FunctionType provides.
3854
3855 bool isSugared() const { return false; }
3856 QualType desugar() const { return QualType(this, 0); }
3857
3858 void Profile(llvm::FoldingSetNodeID &ID) {
3859 Profile(ID, getReturnType(), getExtInfo());
3860 }
3861
3862 static void Profile(llvm::FoldingSetNodeID &ID, QualType ResultType,
3863 ExtInfo Info) {
3864 Info.Profile(ID);
3865 ID.AddPointer(ResultType.getAsOpaquePtr());
3866 }
3867
3868 static bool classof(const Type *T) {
3869 return T->getTypeClass() == FunctionNoProto;
3870 }
3871};
3872
3873/// Represents a prototype with parameter type info, e.g.
3874/// 'int foo(int)' or 'int foo(void)'. 'void' is represented as having no
3875/// parameters, not as having a single void parameter. Such a type can have
3876/// an exception specification, but this specification is not part of the
3877/// canonical type. FunctionProtoType has several trailing objects, some of
3878/// which optional. For more information about the trailing objects see
3879/// the first comment inside FunctionProtoType.
3880class FunctionProtoType final
3881 : public FunctionType,
3882 public llvm::FoldingSetNode,
3883 private llvm::TrailingObjects<
3884 FunctionProtoType, QualType, SourceLocation,
3885 FunctionType::FunctionTypeExtraBitfields, FunctionType::ExceptionType,
3886 Expr *, FunctionDecl *, FunctionType::ExtParameterInfo, Qualifiers> {
3887 friend class ASTContext; // ASTContext creates these.
3888 friend TrailingObjects;
3889
3890 // FunctionProtoType is followed by several trailing objects, some of
3891 // which optional. They are in order:
3892 //
3893 // * An array of getNumParams() QualType holding the parameter types.
3894 // Always present. Note that for the vast majority of FunctionProtoType,
3895 // these will be the only trailing objects.
3896 //
3897 // * Optionally if the function is variadic, the SourceLocation of the
3898 // ellipsis.
3899 //
3900 // * Optionally if some extra data is stored in FunctionTypeExtraBitfields
3901 // (see FunctionTypeExtraBitfields and FunctionTypeBitfields):
3902 // a single FunctionTypeExtraBitfields. Present if and only if
3903 // hasExtraBitfields() is true.
3904 //
3905 // * Optionally exactly one of:
3906 // * an array of getNumExceptions() ExceptionType,
3907 // * a single Expr *,
3908 // * a pair of FunctionDecl *,
3909 // * a single FunctionDecl *
3910 // used to store information about the various types of exception
3911 // specification. See getExceptionSpecSize for the details.
3912 //
3913 // * Optionally an array of getNumParams() ExtParameterInfo holding
3914 // an ExtParameterInfo for each of the parameters. Present if and
3915 // only if hasExtParameterInfos() is true.
3916 //
3917 // * Optionally a Qualifiers object to represent extra qualifiers that can't
3918 // be represented by FunctionTypeBitfields.FastTypeQuals. Present if and only
3919 // if hasExtQualifiers() is true.
3920 //
3921 // The optional FunctionTypeExtraBitfields has to be before the data
3922 // related to the exception specification since it contains the number
3923 // of exception types.
3924 //
3925 // We put the ExtParameterInfos last. If all were equal, it would make
3926 // more sense to put these before the exception specification, because
3927 // it's much easier to skip past them compared to the elaborate switch
3928 // required to skip the exception specification. However, all is not
3929 // equal; ExtParameterInfos are used to model very uncommon features,
3930 // and it's better not to burden the more common paths.
3931
3932public:
3933 /// Holds information about the various types of exception specification.
3934 /// ExceptionSpecInfo is not stored as such in FunctionProtoType but is
3935 /// used to group together the various bits of information about the
3936 /// exception specification.
3937 struct ExceptionSpecInfo {
3938 /// The kind of exception specification this is.
3939 ExceptionSpecificationType Type = EST_None;
3940
3941 /// Explicitly-specified list of exception types.
3942 ArrayRef<QualType> Exceptions;
3943
3944 /// Noexcept expression, if this is a computed noexcept specification.
3945 Expr *NoexceptExpr = nullptr;
3946
3947 /// The function whose exception specification this is, for
3948 /// EST_Unevaluated and EST_Uninstantiated.
3949 FunctionDecl *SourceDecl = nullptr;
3950
3951 /// The function template whose exception specification this is instantiated
3952 /// from, for EST_Uninstantiated.
3953 FunctionDecl *SourceTemplate = nullptr;
3954
3955 ExceptionSpecInfo() = default;
3956
3957 ExceptionSpecInfo(ExceptionSpecificationType EST) : Type(EST) {}
3958 };
3959
3960 /// Extra information about a function prototype. ExtProtoInfo is not
3961 /// stored as such in FunctionProtoType but is used to group together
3962 /// the various bits of extra information about a function prototype.
3963 struct ExtProtoInfo {
3964 FunctionType::ExtInfo ExtInfo;
3965 bool Variadic : 1;
3966 bool HasTrailingReturn : 1;
3967 Qualifiers TypeQuals;
3968 RefQualifierKind RefQualifier = RQ_None;
3969 ExceptionSpecInfo ExceptionSpec;
3970 const ExtParameterInfo *ExtParameterInfos = nullptr;
3971 SourceLocation EllipsisLoc;
3972
3973 ExtProtoInfo() : Variadic(false), HasTrailingReturn(false) {}
3974
3975 ExtProtoInfo(CallingConv CC)
3976 : ExtInfo(CC), Variadic(false), HasTrailingReturn(false) {}
3977
3978 ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI) {
3979 ExtProtoInfo Result(*this);
3980 Result.ExceptionSpec = ESI;
3981 return Result;
3982 }
3983 };
3984
3985private:
3986 unsigned numTrailingObjects(OverloadToken<QualType>) const {
3987 return getNumParams();
3988 }
3989
3990 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
3991 return isVariadic();
3992 }
3993
3994 unsigned numTrailingObjects(OverloadToken<FunctionTypeExtraBitfields>) const {
3995 return hasExtraBitfields();
3996 }
3997
3998 unsigned numTrailingObjects(OverloadToken<ExceptionType>) const {
3999 return getExceptionSpecSize().NumExceptionType;
4000 }
4001
4002 unsigned numTrailingObjects(OverloadToken<Expr *>) const {
4003 return getExceptionSpecSize().NumExprPtr;
4004 }
4005
4006 unsigned numTrailingObjects(OverloadToken<FunctionDecl *>) const {
4007 return getExceptionSpecSize().NumFunctionDeclPtr;
4008 }
4009
4010 unsigned numTrailingObjects(OverloadToken<ExtParameterInfo>) const {
4011 return hasExtParameterInfos() ? getNumParams() : 0;
4012 }
4013
4014 /// Determine whether there are any argument types that
4015 /// contain an unexpanded parameter pack.
4016 static bool containsAnyUnexpandedParameterPack(const QualType *ArgArray,
4017 unsigned numArgs) {
4018 for (unsigned Idx = 0; Idx < numArgs; ++Idx)
4019 if (ArgArray[Idx]->containsUnexpandedParameterPack())
4020 return true;
4021
4022 return false;
4023 }
4024
4025 FunctionProtoType(QualType result, ArrayRef<QualType> params,
4026 QualType canonical, const ExtProtoInfo &epi);
4027
4028 /// This struct is returned by getExceptionSpecSize and is used to
4029 /// translate an ExceptionSpecificationType to the number and kind
4030 /// of trailing objects related to the exception specification.
4031 struct ExceptionSpecSizeHolder {
4032 unsigned NumExceptionType;
4033 unsigned NumExprPtr;
4034 unsigned NumFunctionDeclPtr;
4035 };
4036
4037 /// Return the number and kind of trailing objects
4038 /// related to the exception specification.
4039 static ExceptionSpecSizeHolder
4040 getExceptionSpecSize(ExceptionSpecificationType EST, unsigned NumExceptions) {
4041 switch (EST) {
4042 case EST_None:
4043 case EST_DynamicNone:
4044 case EST_MSAny:
4045 case EST_BasicNoexcept:
4046 case EST_Unparsed:
4047 case EST_NoThrow:
4048 return {0, 0, 0};
4049
4050 case EST_Dynamic:
4051 return {NumExceptions, 0, 0};
4052
4053 case EST_DependentNoexcept:
4054 case EST_NoexceptFalse:
4055 case EST_NoexceptTrue:
4056 return {0, 1, 0};
4057
4058 case EST_Uninstantiated:
4059 return {0, 0, 2};
4060
4061 case EST_Unevaluated:
4062 return {0, 0, 1};
4063 }
4064 llvm_unreachable("bad exception specification kind")::llvm::llvm_unreachable_internal("bad exception specification kind"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4064)
;
4065 }
4066
4067 /// Return the number and kind of trailing objects
4068 /// related to the exception specification.
4069 ExceptionSpecSizeHolder getExceptionSpecSize() const {
4070 return getExceptionSpecSize(getExceptionSpecType(), getNumExceptions());
4071 }
4072
4073 /// Whether the trailing FunctionTypeExtraBitfields is present.
4074 static bool hasExtraBitfields(ExceptionSpecificationType EST) {
4075 // If the exception spec type is EST_Dynamic then we have > 0 exception
4076 // types and the exact number is stored in FunctionTypeExtraBitfields.
4077 return EST == EST_Dynamic;
4078 }
4079
4080 /// Whether the trailing FunctionTypeExtraBitfields is present.
4081 bool hasExtraBitfields() const {
4082 return hasExtraBitfields(getExceptionSpecType());
4083 }
4084
4085 bool hasExtQualifiers() const {
4086 return FunctionTypeBits.HasExtQuals;
4087 }
4088
4089public:
4090 unsigned getNumParams() const { return FunctionTypeBits.NumParams; }
4091
4092 QualType getParamType(unsigned i) const {
4093 assert(i < getNumParams() && "invalid parameter index")((i < getNumParams() && "invalid parameter index")
? static_cast<void> (0) : __assert_fail ("i < getNumParams() && \"invalid parameter index\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4093, __PRETTY_FUNCTION__))
;
4094 return param_type_begin()[i];
4095 }
4096
4097 ArrayRef<QualType> getParamTypes() const {
4098 return llvm::makeArrayRef(param_type_begin(), param_type_end());
4099 }
4100
4101 ExtProtoInfo getExtProtoInfo() const {
4102 ExtProtoInfo EPI;
4103 EPI.ExtInfo = getExtInfo();
4104 EPI.Variadic = isVariadic();
4105 EPI.EllipsisLoc = getEllipsisLoc();
4106 EPI.HasTrailingReturn = hasTrailingReturn();
4107 EPI.ExceptionSpec = getExceptionSpecInfo();
4108 EPI.TypeQuals = getMethodQuals();
4109 EPI.RefQualifier = getRefQualifier();
4110 EPI.ExtParameterInfos = getExtParameterInfosOrNull();
4111 return EPI;
4112 }
4113
4114 /// Get the kind of exception specification on this function.
4115 ExceptionSpecificationType getExceptionSpecType() const {
4116 return static_cast<ExceptionSpecificationType>(
4117 FunctionTypeBits.ExceptionSpecType);
4118 }
4119
4120 /// Return whether this function has any kind of exception spec.
4121 bool hasExceptionSpec() const { return getExceptionSpecType() != EST_None; }
4122
4123 /// Return whether this function has a dynamic (throw) exception spec.
4124 bool hasDynamicExceptionSpec() const {
4125 return isDynamicExceptionSpec(getExceptionSpecType());
4126 }
4127
4128 /// Return whether this function has a noexcept exception spec.
4129 bool hasNoexceptExceptionSpec() const {
4130 return isNoexceptExceptionSpec(getExceptionSpecType());
4131 }
4132
4133 /// Return whether this function has a dependent exception spec.
4134 bool hasDependentExceptionSpec() const;
4135
4136 /// Return whether this function has an instantiation-dependent exception
4137 /// spec.
4138 bool hasInstantiationDependentExceptionSpec() const;
4139
4140 /// Return all the available information about this type's exception spec.
4141 ExceptionSpecInfo getExceptionSpecInfo() const {
4142 ExceptionSpecInfo Result;
4143 Result.Type = getExceptionSpecType();
4144 if (Result.Type == EST_Dynamic) {
4145 Result.Exceptions = exceptions();
4146 } else if (isComputedNoexcept(Result.Type)) {
4147 Result.NoexceptExpr = getNoexceptExpr();
4148 } else if (Result.Type == EST_Uninstantiated) {
4149 Result.SourceDecl = getExceptionSpecDecl();
4150 Result.SourceTemplate = getExceptionSpecTemplate();
4151 } else if (Result.Type == EST_Unevaluated) {
4152 Result.SourceDecl = getExceptionSpecDecl();
4153 }
4154 return Result;
4155 }
4156
4157 /// Return the number of types in the exception specification.
4158 unsigned getNumExceptions() const {
4159 return getExceptionSpecType() == EST_Dynamic
4160 ? getTrailingObjects<FunctionTypeExtraBitfields>()
4161 ->NumExceptionType
4162 : 0;
4163 }
4164
4165 /// Return the ith exception type, where 0 <= i < getNumExceptions().
4166 QualType getExceptionType(unsigned i) const {
4167 assert(i < getNumExceptions() && "Invalid exception number!")((i < getNumExceptions() && "Invalid exception number!"
) ? static_cast<void> (0) : __assert_fail ("i < getNumExceptions() && \"Invalid exception number!\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4167, __PRETTY_FUNCTION__))
;
4168 return exception_begin()[i];
4169 }
4170
4171 /// Return the expression inside noexcept(expression), or a null pointer
4172 /// if there is none (because the exception spec is not of this form).
4173 Expr *getNoexceptExpr() const {
4174 if (!isComputedNoexcept(getExceptionSpecType()))
4175 return nullptr;
4176 return *getTrailingObjects<Expr *>();
4177 }
4178
4179 /// If this function type has an exception specification which hasn't
4180 /// been determined yet (either because it has not been evaluated or because
4181 /// it has not been instantiated), this is the function whose exception
4182 /// specification is represented by this type.
4183 FunctionDecl *getExceptionSpecDecl() const {
4184 if (getExceptionSpecType() != EST_Uninstantiated &&
4185 getExceptionSpecType() != EST_Unevaluated)
4186 return nullptr;
4187 return getTrailingObjects<FunctionDecl *>()[0];
4188 }
4189
4190 /// If this function type has an uninstantiated exception
4191 /// specification, this is the function whose exception specification
4192 /// should be instantiated to find the exception specification for
4193 /// this type.
4194 FunctionDecl *getExceptionSpecTemplate() const {
4195 if (getExceptionSpecType() != EST_Uninstantiated)
4196 return nullptr;
4197 return getTrailingObjects<FunctionDecl *>()[1];
4198 }
4199
4200 /// Determine whether this function type has a non-throwing exception
4201 /// specification.
4202 CanThrowResult canThrow() const;
4203
4204 /// Determine whether this function type has a non-throwing exception
4205 /// specification. If this depends on template arguments, returns
4206 /// \c ResultIfDependent.
4207 bool isNothrow(bool ResultIfDependent = false) const {
4208 return ResultIfDependent ? canThrow() != CT_Can : canThrow() == CT_Cannot;
4209 }
4210
4211 /// Whether this function prototype is variadic.
4212 bool isVariadic() const { return FunctionTypeBits.Variadic; }
4213
4214 SourceLocation getEllipsisLoc() const {
4215 return isVariadic() ? *getTrailingObjects<SourceLocation>()
4216 : SourceLocation();
4217 }
4218
4219 /// Determines whether this function prototype contains a
4220 /// parameter pack at the end.
4221 ///
4222 /// A function template whose last parameter is a parameter pack can be
4223 /// called with an arbitrary number of arguments, much like a variadic
4224 /// function.
4225 bool isTemplateVariadic() const;
4226
4227 /// Whether this function prototype has a trailing return type.
4228 bool hasTrailingReturn() const { return FunctionTypeBits.HasTrailingReturn; }
4229
4230 Qualifiers getMethodQuals() const {
4231 if (hasExtQualifiers())
4232 return *getTrailingObjects<Qualifiers>();
4233 else
4234 return getFastTypeQuals();
4235 }
4236
4237 /// Retrieve the ref-qualifier associated with this function type.
4238 RefQualifierKind getRefQualifier() const {
4239 return static_cast<RefQualifierKind>(FunctionTypeBits.RefQualifier);
4240 }
4241
4242 using param_type_iterator = const QualType *;
4243 using param_type_range = llvm::iterator_range<param_type_iterator>;
4244
4245 param_type_range param_types() const {
4246 return param_type_range(param_type_begin(), param_type_end());
4247 }
4248
4249 param_type_iterator param_type_begin() const {
4250 return getTrailingObjects<QualType>();
4251 }
4252
4253 param_type_iterator param_type_end() const {
4254 return param_type_begin() + getNumParams();
4255 }
4256
4257 using exception_iterator = const QualType *;
4258
4259 ArrayRef<QualType> exceptions() const {
4260 return llvm::makeArrayRef(exception_begin(), exception_end());
4261 }
4262
4263 exception_iterator exception_begin() const {
4264 return reinterpret_cast<exception_iterator>(
4265 getTrailingObjects<ExceptionType>());
4266 }
4267
4268 exception_iterator exception_end() const {
4269 return exception_begin() + getNumExceptions();
4270 }
4271
4272 /// Is there any interesting extra information for any of the parameters
4273 /// of this function type?
4274 bool hasExtParameterInfos() const {
4275 return FunctionTypeBits.HasExtParameterInfos;
4276 }
4277
4278 ArrayRef<ExtParameterInfo> getExtParameterInfos() const {
4279 assert(hasExtParameterInfos())((hasExtParameterInfos()) ? static_cast<void> (0) : __assert_fail
("hasExtParameterInfos()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4279, __PRETTY_FUNCTION__))
;
4280 return ArrayRef<ExtParameterInfo>(getTrailingObjects<ExtParameterInfo>(),
4281 getNumParams());
4282 }
4283
4284 /// Return a pointer to the beginning of the array of extra parameter
4285 /// information, if present, or else null if none of the parameters
4286 /// carry it. This is equivalent to getExtProtoInfo().ExtParameterInfos.
4287 const ExtParameterInfo *getExtParameterInfosOrNull() const {
4288 if (!hasExtParameterInfos())
4289 return nullptr;
4290 return getTrailingObjects<ExtParameterInfo>();
4291 }
4292
4293 ExtParameterInfo getExtParameterInfo(unsigned I) const {
4294 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4294, __PRETTY_FUNCTION__))
;
4295 if (hasExtParameterInfos())
4296 return getTrailingObjects<ExtParameterInfo>()[I];
4297 return ExtParameterInfo();
4298 }
4299
4300 ParameterABI getParameterABI(unsigned I) const {
4301 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4301, __PRETTY_FUNCTION__))
;
4302 if (hasExtParameterInfos())
4303 return getTrailingObjects<ExtParameterInfo>()[I].getABI();
4304 return ParameterABI::Ordinary;
4305 }
4306
4307 bool isParamConsumed(unsigned I) const {
4308 assert(I < getNumParams() && "parameter index out of range")((I < getNumParams() && "parameter index out of range"
) ? static_cast<void> (0) : __assert_fail ("I < getNumParams() && \"parameter index out of range\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4308, __PRETTY_FUNCTION__))
;
4309 if (hasExtParameterInfos())
4310 return getTrailingObjects<ExtParameterInfo>()[I].isConsumed();
4311 return false;
4312 }
4313
4314 bool isSugared() const { return false; }
4315 QualType desugar() const { return QualType(this, 0); }
4316
4317 void printExceptionSpecification(raw_ostream &OS,
4318 const PrintingPolicy &Policy) const;
4319
4320 static bool classof(const Type *T) {
4321 return T->getTypeClass() == FunctionProto;
4322 }
4323
4324 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx);
4325 static void Profile(llvm::FoldingSetNodeID &ID, QualType Result,
4326 param_type_iterator ArgTys, unsigned NumArgs,
4327 const ExtProtoInfo &EPI, const ASTContext &Context,
4328 bool Canonical);
4329};
4330
4331/// Represents the dependent type named by a dependently-scoped
4332/// typename using declaration, e.g.
4333/// using typename Base<T>::foo;
4334///
4335/// Template instantiation turns these into the underlying type.
4336class UnresolvedUsingType : public Type {
4337 friend class ASTContext; // ASTContext creates these.
4338
4339 UnresolvedUsingTypenameDecl *Decl;
4340
4341 UnresolvedUsingType(const UnresolvedUsingTypenameDecl *D)
4342 : Type(UnresolvedUsing, QualType(),
4343 TypeDependence::DependentInstantiation),
4344 Decl(const_cast<UnresolvedUsingTypenameDecl *>(D)) {}
4345
4346public:
4347 UnresolvedUsingTypenameDecl *getDecl() const { return Decl; }
4348
4349 bool isSugared() const { return false; }
4350 QualType desugar() const { return QualType(this, 0); }
4351
4352 static bool classof(const Type *T) {
4353 return T->getTypeClass() == UnresolvedUsing;
4354 }
4355
4356 void Profile(llvm::FoldingSetNodeID &ID) {
4357 return Profile(ID, Decl);
4358 }
4359
4360 static void Profile(llvm::FoldingSetNodeID &ID,
4361 UnresolvedUsingTypenameDecl *D) {
4362 ID.AddPointer(D);
4363 }
4364};
4365
4366class TypedefType : public Type {
4367 TypedefNameDecl *Decl;
4368
4369private:
4370 friend class ASTContext; // ASTContext creates these.
4371
4372 TypedefType(TypeClass tc, const TypedefNameDecl *D, QualType underlying,
4373 QualType can);
4374
4375public:
4376 TypedefNameDecl *getDecl() const { return Decl; }
4377
4378 bool isSugared() const { return true; }
4379 QualType desugar() const;
4380
4381 static bool classof(const Type *T) { return T->getTypeClass() == Typedef; }
4382};
4383
4384/// Sugar type that represents a type that was qualified by a qualifier written
4385/// as a macro invocation.
4386class MacroQualifiedType : public Type {
4387 friend class ASTContext; // ASTContext creates these.
4388
4389 QualType UnderlyingTy;
4390 const IdentifierInfo *MacroII;
4391
4392 MacroQualifiedType(QualType UnderlyingTy, QualType CanonTy,
4393 const IdentifierInfo *MacroII)
4394 : Type(MacroQualified, CanonTy, UnderlyingTy->getDependence()),
4395 UnderlyingTy(UnderlyingTy), MacroII(MacroII) {
4396 assert(isa<AttributedType>(UnderlyingTy) &&((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4397, __PRETTY_FUNCTION__))
4397 "Expected a macro qualified type to only wrap attributed types.")((isa<AttributedType>(UnderlyingTy) && "Expected a macro qualified type to only wrap attributed types."
) ? static_cast<void> (0) : __assert_fail ("isa<AttributedType>(UnderlyingTy) && \"Expected a macro qualified type to only wrap attributed types.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4397, __PRETTY_FUNCTION__))
;
4398 }
4399
4400public:
4401 const IdentifierInfo *getMacroIdentifier() const { return MacroII; }
4402 QualType getUnderlyingType() const { return UnderlyingTy; }
4403
4404 /// Return this attributed type's modified type with no qualifiers attached to
4405 /// it.
4406 QualType getModifiedType() const;
4407
4408 bool isSugared() const { return true; }
4409 QualType desugar() const;
4410
4411 static bool classof(const Type *T) {
4412 return T->getTypeClass() == MacroQualified;
4413 }
4414};
4415
4416/// Represents a `typeof` (or __typeof__) expression (a GCC extension).
4417class TypeOfExprType : public Type {
4418 Expr *TOExpr;
4419
4420protected:
4421 friend class ASTContext; // ASTContext creates these.
4422
4423 TypeOfExprType(Expr *E, QualType can = QualType());
4424
4425public:
4426 Expr *getUnderlyingExpr() const { return TOExpr; }
4427
4428 /// Remove a single level of sugar.
4429 QualType desugar() const;
4430
4431 /// Returns whether this type directly provides sugar.
4432 bool isSugared() const;
4433
4434 static bool classof(const Type *T) { return T->getTypeClass() == TypeOfExpr; }
4435};
4436
4437/// Internal representation of canonical, dependent
4438/// `typeof(expr)` types.
4439///
4440/// This class is used internally by the ASTContext to manage
4441/// canonical, dependent types, only. Clients will only see instances
4442/// of this class via TypeOfExprType nodes.
4443class DependentTypeOfExprType
4444 : public TypeOfExprType, public llvm::FoldingSetNode {
4445 const ASTContext &Context;
4446
4447public:
4448 DependentTypeOfExprType(const ASTContext &Context, Expr *E)
4449 : TypeOfExprType(E), Context(Context) {}
4450
4451 void Profile(llvm::FoldingSetNodeID &ID) {
4452 Profile(ID, Context, getUnderlyingExpr());
4453 }
4454
4455 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4456 Expr *E);
4457};
4458
4459/// Represents `typeof(type)`, a GCC extension.
4460class TypeOfType : public Type {
4461 friend class ASTContext; // ASTContext creates these.
4462
4463 QualType TOType;
4464
4465 TypeOfType(QualType T, QualType can)
4466 : Type(TypeOf, can, T->getDependence()), TOType(T) {
4467 assert(!isa<TypedefType>(can) && "Invalid canonical type")((!isa<TypedefType>(can) && "Invalid canonical type"
) ? static_cast<void> (0) : __assert_fail ("!isa<TypedefType>(can) && \"Invalid canonical type\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4467, __PRETTY_FUNCTION__))
;
4468 }
4469
4470public:
4471 QualType getUnderlyingType() const { return TOType; }
4472
4473 /// Remove a single level of sugar.
4474 QualType desugar() const { return getUnderlyingType(); }
4475
4476 /// Returns whether this type directly provides sugar.
4477 bool isSugared() const { return true; }
4478
4479 static bool classof(const Type *T) { return T->getTypeClass() == TypeOf; }
4480};
4481
4482/// Represents the type `decltype(expr)` (C++11).
4483class DecltypeType : public Type {
4484 Expr *E;
4485 QualType UnderlyingType;
4486
4487protected:
4488 friend class ASTContext; // ASTContext creates these.
4489
4490 DecltypeType(Expr *E, QualType underlyingType, QualType can = QualType());
4491
4492public:
4493 Expr *getUnderlyingExpr() const { return E; }
4494 QualType getUnderlyingType() const { return UnderlyingType; }
4495
4496 /// Remove a single level of sugar.
4497 QualType desugar() const;
4498
4499 /// Returns whether this type directly provides sugar.
4500 bool isSugared() const;
4501
4502 static bool classof(const Type *T) { return T->getTypeClass() == Decltype; }
4503};
4504
4505/// Internal representation of canonical, dependent
4506/// decltype(expr) types.
4507///
4508/// This class is used internally by the ASTContext to manage
4509/// canonical, dependent types, only. Clients will only see instances
4510/// of this class via DecltypeType nodes.
4511class DependentDecltypeType : public DecltypeType, public llvm::FoldingSetNode {
4512 const ASTContext &Context;
4513
4514public:
4515 DependentDecltypeType(const ASTContext &Context, Expr *E);
4516
4517 void Profile(llvm::FoldingSetNodeID &ID) {
4518 Profile(ID, Context, getUnderlyingExpr());
4519 }
4520
4521 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
4522 Expr *E);
4523};
4524
4525/// A unary type transform, which is a type constructed from another.
4526class UnaryTransformType : public Type {
4527public:
4528 enum UTTKind {
4529 EnumUnderlyingType
4530 };
4531
4532private:
4533 /// The untransformed type.
4534 QualType BaseType;
4535
4536 /// The transformed type if not dependent, otherwise the same as BaseType.
4537 QualType UnderlyingType;
4538
4539 UTTKind UKind;
4540
4541protected:
4542 friend class ASTContext;
4543
4544 UnaryTransformType(QualType BaseTy, QualType UnderlyingTy, UTTKind UKind,
4545 QualType CanonicalTy);
4546
4547public:
4548 bool isSugared() const { return !isDependentType(); }
4549 QualType desugar() const { return UnderlyingType; }
4550
4551 QualType getUnderlyingType() const { return UnderlyingType; }
4552 QualType getBaseType() const { return BaseType; }
4553
4554 UTTKind getUTTKind() const { return UKind; }
4555
4556 static bool classof(const Type *T) {
4557 return T->getTypeClass() == UnaryTransform;
4558 }
4559};
4560
4561/// Internal representation of canonical, dependent
4562/// __underlying_type(type) types.
4563///
4564/// This class is used internally by the ASTContext to manage
4565/// canonical, dependent types, only. Clients will only see instances
4566/// of this class via UnaryTransformType nodes.
4567class DependentUnaryTransformType : public UnaryTransformType,
4568 public llvm::FoldingSetNode {
4569public:
4570 DependentUnaryTransformType(const ASTContext &C, QualType BaseType,
4571 UTTKind UKind);
4572
4573 void Profile(llvm::FoldingSetNodeID &ID) {
4574 Profile(ID, getBaseType(), getUTTKind());
4575 }
4576
4577 static void Profile(llvm::FoldingSetNodeID &ID, QualType BaseType,
4578 UTTKind UKind) {
4579 ID.AddPointer(BaseType.getAsOpaquePtr());
4580 ID.AddInteger((unsigned)UKind);
4581 }
4582};
4583
4584class TagType : public Type {
4585 friend class ASTReader;
4586 template <class T> friend class serialization::AbstractTypeReader;
4587
4588 /// Stores the TagDecl associated with this type. The decl may point to any
4589 /// TagDecl that declares the entity.
4590 TagDecl *decl;
4591
4592protected:
4593 TagType(TypeClass TC, const TagDecl *D, QualType can);
4594
4595public:
4596 TagDecl *getDecl() const;
4597
4598 /// Determines whether this type is in the process of being defined.
4599 bool isBeingDefined() const;
4600
4601 static bool classof(const Type *T) {
4602 return T->getTypeClass() == Enum || T->getTypeClass() == Record;
4603 }
4604};
4605
4606/// A helper class that allows the use of isa/cast/dyncast
4607/// to detect TagType objects of structs/unions/classes.
4608class RecordType : public TagType {
4609protected:
4610 friend class ASTContext; // ASTContext creates these.
4611
4612 explicit RecordType(const RecordDecl *D)
4613 : TagType(Record, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4614 explicit RecordType(TypeClass TC, RecordDecl *D)
4615 : TagType(TC, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4616
4617public:
4618 RecordDecl *getDecl() const {
4619 return reinterpret_cast<RecordDecl*>(TagType::getDecl());
4620 }
4621
4622 /// Recursively check all fields in the record for const-ness. If any field
4623 /// is declared const, return true. Otherwise, return false.
4624 bool hasConstFields() const;
4625
4626 bool isSugared() const { return false; }
4627 QualType desugar() const { return QualType(this, 0); }
4628
4629 static bool classof(const Type *T) { return T->getTypeClass() == Record; }
4630};
4631
4632/// A helper class that allows the use of isa/cast/dyncast
4633/// to detect TagType objects of enums.
4634class EnumType : public TagType {
4635 friend class ASTContext; // ASTContext creates these.
4636
4637 explicit EnumType(const EnumDecl *D)
4638 : TagType(Enum, reinterpret_cast<const TagDecl*>(D), QualType()) {}
4639
4640public:
4641 EnumDecl *getDecl() const {
4642 return reinterpret_cast<EnumDecl*>(TagType::getDecl());
4643 }
4644
4645 bool isSugared() const { return false; }
4646 QualType desugar() const { return QualType(this, 0); }
4647
4648 static bool classof(const Type *T) { return T->getTypeClass() == Enum; }
4649};
4650
4651/// An attributed type is a type to which a type attribute has been applied.
4652///
4653/// The "modified type" is the fully-sugared type to which the attributed
4654/// type was applied; generally it is not canonically equivalent to the
4655/// attributed type. The "equivalent type" is the minimally-desugared type
4656/// which the type is canonically equivalent to.
4657///
4658/// For example, in the following attributed type:
4659/// int32_t __attribute__((vector_size(16)))
4660/// - the modified type is the TypedefType for int32_t
4661/// - the equivalent type is VectorType(16, int32_t)
4662/// - the canonical type is VectorType(16, int)
4663class AttributedType : public Type, public llvm::FoldingSetNode {
4664public:
4665 using Kind = attr::Kind;
4666
4667private:
4668 friend class ASTContext; // ASTContext creates these
4669
4670 QualType ModifiedType;
4671 QualType EquivalentType;
4672
4673 AttributedType(QualType canon, attr::Kind attrKind, QualType modified,
4674 QualType equivalent)
4675 : Type(Attributed, canon, equivalent->getDependence()),
4676 ModifiedType(modified), EquivalentType(equivalent) {
4677 AttributedTypeBits.AttrKind = attrKind;
4678 }
4679
4680public:
4681 Kind getAttrKind() const {
4682 return static_cast<Kind>(AttributedTypeBits.AttrKind);
4683 }
4684
4685 QualType getModifiedType() const { return ModifiedType; }
4686 QualType getEquivalentType() const { return EquivalentType; }
4687
4688 bool isSugared() const { return true; }
4689 QualType desugar() const { return getEquivalentType(); }
4690
4691 /// Does this attribute behave like a type qualifier?
4692 ///
4693 /// A type qualifier adjusts a type to provide specialized rules for
4694 /// a specific object, like the standard const and volatile qualifiers.
4695 /// This includes attributes controlling things like nullability,
4696 /// address spaces, and ARC ownership. The value of the object is still
4697 /// largely described by the modified type.
4698 ///
4699 /// In contrast, many type attributes "rewrite" their modified type to
4700 /// produce a fundamentally different type, not necessarily related in any
4701 /// formalizable way to the original type. For example, calling convention
4702 /// and vector attributes are not simple type qualifiers.
4703 ///
4704 /// Type qualifiers are often, but not always, reflected in the canonical
4705 /// type.
4706 bool isQualifier() const;
4707
4708 bool isMSTypeSpec() const;
4709
4710 bool isCallingConv() const;
4711
4712 llvm::Optional<NullabilityKind> getImmediateNullability() const;
4713
4714 /// Retrieve the attribute kind corresponding to the given
4715 /// nullability kind.
4716 static Kind getNullabilityAttrKind(NullabilityKind kind) {
4717 switch (kind) {
4718 case NullabilityKind::NonNull:
4719 return attr::TypeNonNull;
4720
4721 case NullabilityKind::Nullable:
4722 return attr::TypeNullable;
4723
4724 case NullabilityKind::NullableResult:
4725 return attr::TypeNullableResult;
4726
4727 case NullabilityKind::Unspecified:
4728 return attr::TypeNullUnspecified;
4729 }
4730 llvm_unreachable("Unknown nullability kind.")::llvm::llvm_unreachable_internal("Unknown nullability kind."
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 4730)
;
4731 }
4732
4733 /// Strip off the top-level nullability annotation on the given
4734 /// type, if it's there.
4735 ///
4736 /// \param T The type to strip. If the type is exactly an
4737 /// AttributedType specifying nullability (without looking through
4738 /// type sugar), the nullability is returned and this type changed
4739 /// to the underlying modified type.
4740 ///
4741 /// \returns the top-level nullability, if present.
4742 static Optional<NullabilityKind> stripOuterNullability(QualType &T);
4743
4744 void Profile(llvm::FoldingSetNodeID &ID) {
4745 Profile(ID, getAttrKind(), ModifiedType, EquivalentType);
4746 }
4747
4748 static void Profile(llvm::FoldingSetNodeID &ID, Kind attrKind,
4749 QualType modified, QualType equivalent) {
4750 ID.AddInteger(attrKind);
4751 ID.AddPointer(modified.getAsOpaquePtr());
4752 ID.AddPointer(equivalent.getAsOpaquePtr());
4753 }
4754
4755 static bool classof(const Type *T) {
4756 return T->getTypeClass() == Attributed;
4757 }
4758};
4759
4760class TemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4761 friend class ASTContext; // ASTContext creates these
4762
4763 // Helper data collector for canonical types.
4764 struct CanonicalTTPTInfo {
4765 unsigned Depth : 15;
4766 unsigned ParameterPack : 1;
4767 unsigned Index : 16;
4768 };
4769
4770 union {
4771 // Info for the canonical type.
4772 CanonicalTTPTInfo CanTTPTInfo;
4773
4774 // Info for the non-canonical type.
4775 TemplateTypeParmDecl *TTPDecl;
4776 };
4777
4778 /// Build a non-canonical type.
4779 TemplateTypeParmType(TemplateTypeParmDecl *TTPDecl, QualType Canon)
4780 : Type(TemplateTypeParm, Canon,
4781 TypeDependence::DependentInstantiation |
4782 (Canon->getDependence() & TypeDependence::UnexpandedPack)),
4783 TTPDecl(TTPDecl) {}
4784
4785 /// Build the canonical type.
4786 TemplateTypeParmType(unsigned D, unsigned I, bool PP)
4787 : Type(TemplateTypeParm, QualType(this, 0),
4788 TypeDependence::DependentInstantiation |
4789 (PP ? TypeDependence::UnexpandedPack : TypeDependence::None)) {
4790 CanTTPTInfo.Depth = D;
4791 CanTTPTInfo.Index = I;
4792 CanTTPTInfo.ParameterPack = PP;
4793 }
4794
4795 const CanonicalTTPTInfo& getCanTTPTInfo() const {
4796 QualType Can = getCanonicalTypeInternal();
4797 return Can->castAs<TemplateTypeParmType>()->CanTTPTInfo;
4798 }
4799
4800public:
4801 unsigned getDepth() const { return getCanTTPTInfo().Depth; }
4802 unsigned getIndex() const { return getCanTTPTInfo().Index; }
4803 bool isParameterPack() const { return getCanTTPTInfo().ParameterPack; }
4804
4805 TemplateTypeParmDecl *getDecl() const {
4806 return isCanonicalUnqualified() ? nullptr : TTPDecl;
4807 }
4808
4809 IdentifierInfo *getIdentifier() const;
4810
4811 bool isSugared() const { return false; }
4812 QualType desugar() const { return QualType(this, 0); }
4813
4814 void Profile(llvm::FoldingSetNodeID &ID) {
4815 Profile(ID, getDepth(), getIndex(), isParameterPack(), getDecl());
4816 }
4817
4818 static void Profile(llvm::FoldingSetNodeID &ID, unsigned Depth,
4819 unsigned Index, bool ParameterPack,
4820 TemplateTypeParmDecl *TTPDecl) {
4821 ID.AddInteger(Depth);
4822 ID.AddInteger(Index);
4823 ID.AddBoolean(ParameterPack);
4824 ID.AddPointer(TTPDecl);
4825 }
4826
4827 static bool classof(const Type *T) {
4828 return T->getTypeClass() == TemplateTypeParm;
4829 }
4830};
4831
4832/// Represents the result of substituting a type for a template
4833/// type parameter.
4834///
4835/// Within an instantiated template, all template type parameters have
4836/// been replaced with these. They are used solely to record that a
4837/// type was originally written as a template type parameter;
4838/// therefore they are never canonical.
4839class SubstTemplateTypeParmType : public Type, public llvm::FoldingSetNode {
4840 friend class ASTContext;
4841
4842 // The original type parameter.
4843 const TemplateTypeParmType *Replaced;
4844
4845 SubstTemplateTypeParmType(const TemplateTypeParmType *Param, QualType Canon)
4846 : Type(SubstTemplateTypeParm, Canon, Canon->getDependence()),
4847 Replaced(Param) {}
4848
4849public:
4850 /// Gets the template parameter that was substituted for.
4851 const TemplateTypeParmType *getReplacedParameter() const {
4852 return Replaced;
4853 }
4854
4855 /// Gets the type that was substituted for the template
4856 /// parameter.
4857 QualType getReplacementType() const {
4858 return getCanonicalTypeInternal();
4859 }
4860
4861 bool isSugared() const { return true; }
4862 QualType desugar() const { return getReplacementType(); }
4863
4864 void Profile(llvm::FoldingSetNodeID &ID) {
4865 Profile(ID, getReplacedParameter(), getReplacementType());
4866 }
4867
4868 static void Profile(llvm::FoldingSetNodeID &ID,
4869 const TemplateTypeParmType *Replaced,
4870 QualType Replacement) {
4871 ID.AddPointer(Replaced);
4872 ID.AddPointer(Replacement.getAsOpaquePtr());
4873 }
4874
4875 static bool classof(const Type *T) {
4876 return T->getTypeClass() == SubstTemplateTypeParm;
4877 }
4878};
4879
4880/// Represents the result of substituting a set of types for a template
4881/// type parameter pack.
4882///
4883/// When a pack expansion in the source code contains multiple parameter packs
4884/// and those parameter packs correspond to different levels of template
4885/// parameter lists, this type node is used to represent a template type
4886/// parameter pack from an outer level, which has already had its argument pack
4887/// substituted but that still lives within a pack expansion that itself
4888/// could not be instantiated. When actually performing a substitution into
4889/// that pack expansion (e.g., when all template parameters have corresponding
4890/// arguments), this type will be replaced with the \c SubstTemplateTypeParmType
4891/// at the current pack substitution index.
4892class SubstTemplateTypeParmPackType : public Type, public llvm::FoldingSetNode {
4893 friend class ASTContext;
4894
4895 /// The original type parameter.
4896 const TemplateTypeParmType *Replaced;
4897
4898 /// A pointer to the set of template arguments that this
4899 /// parameter pack is instantiated with.
4900 const TemplateArgument *Arguments;
4901
4902 SubstTemplateTypeParmPackType(const TemplateTypeParmType *Param,
4903 QualType Canon,
4904 const TemplateArgument &ArgPack);
4905
4906public:
4907 IdentifierInfo *getIdentifier() const { return Replaced->getIdentifier(); }
4908
4909 /// Gets the template parameter that was substituted for.
4910 const TemplateTypeParmType *getReplacedParameter() const {
4911 return Replaced;
4912 }
4913
4914 unsigned getNumArgs() const {
4915 return SubstTemplateTypeParmPackTypeBits.NumArgs;
4916 }
4917
4918 bool isSugared() const { return false; }
4919 QualType desugar() const { return QualType(this, 0); }
4920
4921 TemplateArgument getArgumentPack() const;
4922
4923 void Profile(llvm::FoldingSetNodeID &ID);
4924 static void Profile(llvm::FoldingSetNodeID &ID,
4925 const TemplateTypeParmType *Replaced,
4926 const TemplateArgument &ArgPack);
4927
4928 static bool classof(const Type *T) {
4929 return T->getTypeClass() == SubstTemplateTypeParmPack;
4930 }
4931};
4932
4933/// Common base class for placeholders for types that get replaced by
4934/// placeholder type deduction: C++11 auto, C++14 decltype(auto), C++17 deduced
4935/// class template types, and constrained type names.
4936///
4937/// These types are usually a placeholder for a deduced type. However, before
4938/// the initializer is attached, or (usually) if the initializer is
4939/// type-dependent, there is no deduced type and the type is canonical. In
4940/// the latter case, it is also a dependent type.
4941class DeducedType : public Type {
4942protected:
4943 DeducedType(TypeClass TC, QualType DeducedAsType,
4944 TypeDependence ExtraDependence)
4945 : Type(TC,
4946 // FIXME: Retain the sugared deduced type?
4947 DeducedAsType.isNull() ? QualType(this, 0)
4948 : DeducedAsType.getCanonicalType(),
4949 ExtraDependence | (DeducedAsType.isNull()
4950 ? TypeDependence::None
4951 : DeducedAsType->getDependence() &
4952 ~TypeDependence::VariablyModified)) {}
4953
4954public:
4955 bool isSugared() const { return !isCanonicalUnqualified(); }
4956 QualType desugar() const { return getCanonicalTypeInternal(); }
4957
4958 /// Get the type deduced for this placeholder type, or null if it's
4959 /// either not been deduced or was deduced to a dependent type.
4960 QualType getDeducedType() const {
4961 return !isCanonicalUnqualified() ? getCanonicalTypeInternal() : QualType();
4962 }
4963 bool isDeduced() const {
4964 return !isCanonicalUnqualified() || isDependentType();
4965 }
4966
4967 static bool classof(const Type *T) {
4968 return T->getTypeClass() == Auto ||
4969 T->getTypeClass() == DeducedTemplateSpecialization;
4970 }
4971};
4972
4973/// Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained
4974/// by a type-constraint.
4975class alignas(8) AutoType : public DeducedType, public llvm::FoldingSetNode {
4976 friend class ASTContext; // ASTContext creates these
4977
4978 ConceptDecl *TypeConstraintConcept;
4979
4980 AutoType(QualType DeducedAsType, AutoTypeKeyword Keyword,
4981 TypeDependence ExtraDependence, ConceptDecl *CD,
4982 ArrayRef<TemplateArgument> TypeConstraintArgs);
4983
4984 const TemplateArgument *getArgBuffer() const {
4985 return reinterpret_cast<const TemplateArgument*>(this+1);
4986 }
4987
4988 TemplateArgument *getArgBuffer() {
4989 return reinterpret_cast<TemplateArgument*>(this+1);
4990 }
4991
4992public:
4993 /// Retrieve the template arguments.
4994 const TemplateArgument *getArgs() const {
4995 return getArgBuffer();
4996 }
4997
4998 /// Retrieve the number of template arguments.
4999 unsigned getNumArgs() const {
5000 return AutoTypeBits.NumArgs;
5001 }
5002
5003 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5004
5005 ArrayRef<TemplateArgument> getTypeConstraintArguments() const {
5006 return {getArgs(), getNumArgs()};
5007 }
5008
5009 ConceptDecl *getTypeConstraintConcept() const {
5010 return TypeConstraintConcept;
5011 }
5012
5013 bool isConstrained() const {
5014 return TypeConstraintConcept != nullptr;
5015 }
5016
5017 bool isDecltypeAuto() const {
5018 return getKeyword() == AutoTypeKeyword::DecltypeAuto;
5019 }
5020
5021 AutoTypeKeyword getKeyword() const {
5022 return (AutoTypeKeyword)AutoTypeBits.Keyword;
5023 }
5024
5025 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5026 Profile(ID, Context, getDeducedType(), getKeyword(), isDependentType(),
5027 getTypeConstraintConcept(), getTypeConstraintArguments());
5028 }
5029
5030 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
5031 QualType Deduced, AutoTypeKeyword Keyword,
5032 bool IsDependent, ConceptDecl *CD,
5033 ArrayRef<TemplateArgument> Arguments);
5034
5035 static bool classof(const Type *T) {
5036 return T->getTypeClass() == Auto;
5037 }
5038};
5039
5040/// Represents a C++17 deduced template specialization type.
5041class DeducedTemplateSpecializationType : public DeducedType,
5042 public llvm::FoldingSetNode {
5043 friend class ASTContext; // ASTContext creates these
5044
5045 /// The name of the template whose arguments will be deduced.
5046 TemplateName Template;
5047
5048 DeducedTemplateSpecializationType(TemplateName Template,
5049 QualType DeducedAsType,
5050 bool IsDeducedAsDependent)
5051 : DeducedType(DeducedTemplateSpecialization, DeducedAsType,
5052 toTypeDependence(Template.getDependence()) |
5053 (IsDeducedAsDependent
5054 ? TypeDependence::DependentInstantiation
5055 : TypeDependence::None)),
5056 Template(Template) {}
5057
5058public:
5059 /// Retrieve the name of the template that we are deducing.
5060 TemplateName getTemplateName() const { return Template;}
5061
5062 void Profile(llvm::FoldingSetNodeID &ID) {
5063 Profile(ID, getTemplateName(), getDeducedType(), isDependentType());
5064 }
5065
5066 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName Template,
5067 QualType Deduced, bool IsDependent) {
5068 Template.Profile(ID);
5069 ID.AddPointer(Deduced.getAsOpaquePtr());
5070 ID.AddBoolean(IsDependent);
5071 }
5072
5073 static bool classof(const Type *T) {
5074 return T->getTypeClass() == DeducedTemplateSpecialization;
5075 }
5076};
5077
5078/// Represents a type template specialization; the template
5079/// must be a class template, a type alias template, or a template
5080/// template parameter. A template which cannot be resolved to one of
5081/// these, e.g. because it is written with a dependent scope
5082/// specifier, is instead represented as a
5083/// @c DependentTemplateSpecializationType.
5084///
5085/// A non-dependent template specialization type is always "sugar",
5086/// typically for a \c RecordType. For example, a class template
5087/// specialization type of \c vector<int> will refer to a tag type for
5088/// the instantiation \c std::vector<int, std::allocator<int>>
5089///
5090/// Template specializations are dependent if either the template or
5091/// any of the template arguments are dependent, in which case the
5092/// type may also be canonical.
5093///
5094/// Instances of this type are allocated with a trailing array of
5095/// TemplateArguments, followed by a QualType representing the
5096/// non-canonical aliased type when the template is a type alias
5097/// template.
5098class alignas(8) TemplateSpecializationType
5099 : public Type,
5100 public llvm::FoldingSetNode {
5101 friend class ASTContext; // ASTContext creates these
5102
5103 /// The name of the template being specialized. This is
5104 /// either a TemplateName::Template (in which case it is a
5105 /// ClassTemplateDecl*, a TemplateTemplateParmDecl*, or a
5106 /// TypeAliasTemplateDecl*), a
5107 /// TemplateName::SubstTemplateTemplateParmPack, or a
5108 /// TemplateName::SubstTemplateTemplateParm (in which case the
5109 /// replacement must, recursively, be one of these).
5110 TemplateName Template;
5111
5112 TemplateSpecializationType(TemplateName T,
5113 ArrayRef<TemplateArgument> Args,
5114 QualType Canon,
5115 QualType Aliased);
5116
5117public:
5118 /// Determine whether any of the given template arguments are dependent.
5119 ///
5120 /// The converted arguments should be supplied when known; whether an
5121 /// argument is dependent can depend on the conversions performed on it
5122 /// (for example, a 'const int' passed as a template argument might be
5123 /// dependent if the parameter is a reference but non-dependent if the
5124 /// parameter is an int).
5125 ///
5126 /// Note that the \p Args parameter is unused: this is intentional, to remind
5127 /// the caller that they need to pass in the converted arguments, not the
5128 /// specified arguments.
5129 static bool
5130 anyDependentTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
5131 ArrayRef<TemplateArgument> Converted);
5132 static bool
5133 anyDependentTemplateArguments(const TemplateArgumentListInfo &,
5134 ArrayRef<TemplateArgument> Converted);
5135 static bool anyInstantiationDependentTemplateArguments(
5136 ArrayRef<TemplateArgumentLoc> Args);
5137
5138 /// True if this template specialization type matches a current
5139 /// instantiation in the context in which it is found.
5140 bool isCurrentInstantiation() const {
5141 return isa<InjectedClassNameType>(getCanonicalTypeInternal());
5142 }
5143
5144 /// Determine if this template specialization type is for a type alias
5145 /// template that has been substituted.
5146 ///
5147 /// Nearly every template specialization type whose template is an alias
5148 /// template will be substituted. However, this is not the case when
5149 /// the specialization contains a pack expansion but the template alias
5150 /// does not have a corresponding parameter pack, e.g.,
5151 ///
5152 /// \code
5153 /// template<typename T, typename U, typename V> struct S;
5154 /// template<typename T, typename U> using A = S<T, int, U>;
5155 /// template<typename... Ts> struct X {
5156 /// typedef A<Ts...> type; // not a type alias
5157 /// };
5158 /// \endcode
5159 bool isTypeAlias() const { return TemplateSpecializationTypeBits.TypeAlias; }
5160
5161 /// Get the aliased type, if this is a specialization of a type alias
5162 /// template.
5163 QualType getAliasedType() const {
5164 assert(isTypeAlias() && "not a type alias template specialization")((isTypeAlias() && "not a type alias template specialization"
) ? static_cast<void> (0) : __assert_fail ("isTypeAlias() && \"not a type alias template specialization\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5164, __PRETTY_FUNCTION__))
;
5165 return *reinterpret_cast<const QualType*>(end());
5166 }
5167
5168 using iterator = const TemplateArgument *;
5169
5170 iterator begin() const { return getArgs(); }
5171 iterator end() const; // defined inline in TemplateBase.h
5172
5173 /// Retrieve the name of the template that we are specializing.
5174 TemplateName getTemplateName() const { return Template; }
5175
5176 /// Retrieve the template arguments.
5177 const TemplateArgument *getArgs() const {
5178 return reinterpret_cast<const TemplateArgument *>(this + 1);
5179 }
5180
5181 /// Retrieve the number of template arguments.
5182 unsigned getNumArgs() const {
5183 return TemplateSpecializationTypeBits.NumArgs;
5184 }
5185
5186 /// Retrieve a specific template argument as a type.
5187 /// \pre \c isArgType(Arg)
5188 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5189
5190 ArrayRef<TemplateArgument> template_arguments() const {
5191 return {getArgs(), getNumArgs()};
5192 }
5193
5194 bool isSugared() const {
5195 return !isDependentType() || isCurrentInstantiation() || isTypeAlias();
5196 }
5197
5198 QualType desugar() const {
5199 return isTypeAlias() ? getAliasedType() : getCanonicalTypeInternal();
5200 }
5201
5202 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Ctx) {
5203 Profile(ID, Template, template_arguments(), Ctx);
5204 if (isTypeAlias())
5205 getAliasedType().Profile(ID);
5206 }
5207
5208 static void Profile(llvm::FoldingSetNodeID &ID, TemplateName T,
5209 ArrayRef<TemplateArgument> Args,
5210 const ASTContext &Context);
5211
5212 static bool classof(const Type *T) {
5213 return T->getTypeClass() == TemplateSpecialization;
5214 }
5215};
5216
5217/// Print a template argument list, including the '<' and '>'
5218/// enclosing the template arguments.
5219void printTemplateArgumentList(raw_ostream &OS,
5220 ArrayRef<TemplateArgument> Args,
5221 const PrintingPolicy &Policy,
5222 const TemplateParameterList *TPL = nullptr);
5223
5224void printTemplateArgumentList(raw_ostream &OS,
5225 ArrayRef<TemplateArgumentLoc> Args,
5226 const PrintingPolicy &Policy,
5227 const TemplateParameterList *TPL = nullptr);
5228
5229void printTemplateArgumentList(raw_ostream &OS,
5230 const TemplateArgumentListInfo &Args,
5231 const PrintingPolicy &Policy,
5232 const TemplateParameterList *TPL = nullptr);
5233
5234/// The injected class name of a C++ class template or class
5235/// template partial specialization. Used to record that a type was
5236/// spelled with a bare identifier rather than as a template-id; the
5237/// equivalent for non-templated classes is just RecordType.
5238///
5239/// Injected class name types are always dependent. Template
5240/// instantiation turns these into RecordTypes.
5241///
5242/// Injected class name types are always canonical. This works
5243/// because it is impossible to compare an injected class name type
5244/// with the corresponding non-injected template type, for the same
5245/// reason that it is impossible to directly compare template
5246/// parameters from different dependent contexts: injected class name
5247/// types can only occur within the scope of a particular templated
5248/// declaration, and within that scope every template specialization
5249/// will canonicalize to the injected class name (when appropriate
5250/// according to the rules of the language).
5251class InjectedClassNameType : public Type {
5252 friend class ASTContext; // ASTContext creates these.
5253 friend class ASTNodeImporter;
5254 friend class ASTReader; // FIXME: ASTContext::getInjectedClassNameType is not
5255 // currently suitable for AST reading, too much
5256 // interdependencies.
5257 template <class T> friend class serialization::AbstractTypeReader;
5258
5259 CXXRecordDecl *Decl;
5260
5261 /// The template specialization which this type represents.
5262 /// For example, in
5263 /// template <class T> class A { ... };
5264 /// this is A<T>, whereas in
5265 /// template <class X, class Y> class A<B<X,Y> > { ... };
5266 /// this is A<B<X,Y> >.
5267 ///
5268 /// It is always unqualified, always a template specialization type,
5269 /// and always dependent.
5270 QualType InjectedType;
5271
5272 InjectedClassNameType(CXXRecordDecl *D, QualType TST)
5273 : Type(InjectedClassName, QualType(),
5274 TypeDependence::DependentInstantiation),
5275 Decl(D), InjectedType(TST) {
5276 assert(isa<TemplateSpecializationType>(TST))((isa<TemplateSpecializationType>(TST)) ? static_cast<
void> (0) : __assert_fail ("isa<TemplateSpecializationType>(TST)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5276, __PRETTY_FUNCTION__))
;
5277 assert(!TST.hasQualifiers())((!TST.hasQualifiers()) ? static_cast<void> (0) : __assert_fail
("!TST.hasQualifiers()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5277, __PRETTY_FUNCTION__))
;
5278 assert(TST->isDependentType())((TST->isDependentType()) ? static_cast<void> (0) : __assert_fail
("TST->isDependentType()", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5278, __PRETTY_FUNCTION__))
;
5279 }
5280
5281public:
5282 QualType getInjectedSpecializationType() const { return InjectedType; }
5283
5284 const TemplateSpecializationType *getInjectedTST() const {
5285 return cast<TemplateSpecializationType>(InjectedType.getTypePtr());
5286 }
5287
5288 TemplateName getTemplateName() const {
5289 return getInjectedTST()->getTemplateName();
5290 }
5291
5292 CXXRecordDecl *getDecl() const;
5293
5294 bool isSugared() const { return false; }
5295 QualType desugar() const { return QualType(this, 0); }
5296
5297 static bool classof(const Type *T) {
5298 return T->getTypeClass() == InjectedClassName;
5299 }
5300};
5301
5302/// The kind of a tag type.
5303enum TagTypeKind {
5304 /// The "struct" keyword.
5305 TTK_Struct,
5306
5307 /// The "__interface" keyword.
5308 TTK_Interface,
5309
5310 /// The "union" keyword.
5311 TTK_Union,
5312
5313 /// The "class" keyword.
5314 TTK_Class,
5315
5316 /// The "enum" keyword.
5317 TTK_Enum
5318};
5319
5320/// The elaboration keyword that precedes a qualified type name or
5321/// introduces an elaborated-type-specifier.
5322enum ElaboratedTypeKeyword {
5323 /// The "struct" keyword introduces the elaborated-type-specifier.
5324 ETK_Struct,
5325
5326 /// The "__interface" keyword introduces the elaborated-type-specifier.
5327 ETK_Interface,
5328
5329 /// The "union" keyword introduces the elaborated-type-specifier.
5330 ETK_Union,
5331
5332 /// The "class" keyword introduces the elaborated-type-specifier.
5333 ETK_Class,
5334
5335 /// The "enum" keyword introduces the elaborated-type-specifier.
5336 ETK_Enum,
5337
5338 /// The "typename" keyword precedes the qualified type name, e.g.,
5339 /// \c typename T::type.
5340 ETK_Typename,
5341
5342 /// No keyword precedes the qualified type name.
5343 ETK_None
5344};
5345
5346/// A helper class for Type nodes having an ElaboratedTypeKeyword.
5347/// The keyword in stored in the free bits of the base class.
5348/// Also provides a few static helpers for converting and printing
5349/// elaborated type keyword and tag type kind enumerations.
5350class TypeWithKeyword : public Type {
5351protected:
5352 TypeWithKeyword(ElaboratedTypeKeyword Keyword, TypeClass tc,
5353 QualType Canonical, TypeDependence Dependence)
5354 : Type(tc, Canonical, Dependence) {
5355 TypeWithKeywordBits.Keyword = Keyword;
5356 }
5357
5358public:
5359 ElaboratedTypeKeyword getKeyword() const {
5360 return static_cast<ElaboratedTypeKeyword>(TypeWithKeywordBits.Keyword);
5361 }
5362
5363 /// Converts a type specifier (DeclSpec::TST) into an elaborated type keyword.
5364 static ElaboratedTypeKeyword getKeywordForTypeSpec(unsigned TypeSpec);
5365
5366 /// Converts a type specifier (DeclSpec::TST) into a tag type kind.
5367 /// It is an error to provide a type specifier which *isn't* a tag kind here.
5368 static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec);
5369
5370 /// Converts a TagTypeKind into an elaborated type keyword.
5371 static ElaboratedTypeKeyword getKeywordForTagTypeKind(TagTypeKind Tag);
5372
5373 /// Converts an elaborated type keyword into a TagTypeKind.
5374 /// It is an error to provide an elaborated type keyword
5375 /// which *isn't* a tag kind here.
5376 static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword);
5377
5378 static bool KeywordIsTagTypeKind(ElaboratedTypeKeyword Keyword);
5379
5380 static StringRef getKeywordName(ElaboratedTypeKeyword Keyword);
5381
5382 static StringRef getTagTypeKindName(TagTypeKind Kind) {
5383 return getKeywordName(getKeywordForTagTypeKind(Kind));
5384 }
5385
5386 class CannotCastToThisType {};
5387 static CannotCastToThisType classof(const Type *);
5388};
5389
5390/// Represents a type that was referred to using an elaborated type
5391/// keyword, e.g., struct S, or via a qualified name, e.g., N::M::type,
5392/// or both.
5393///
5394/// This type is used to keep track of a type name as written in the
5395/// source code, including tag keywords and any nested-name-specifiers.
5396/// The type itself is always "sugar", used to express what was written
5397/// in the source code but containing no additional semantic information.
5398class ElaboratedType final
5399 : public TypeWithKeyword,
5400 public llvm::FoldingSetNode,
5401 private llvm::TrailingObjects<ElaboratedType, TagDecl *> {
5402 friend class ASTContext; // ASTContext creates these
5403 friend TrailingObjects;
5404
5405 /// The nested name specifier containing the qualifier.
5406 NestedNameSpecifier *NNS;
5407
5408 /// The type that this qualified name refers to.
5409 QualType NamedType;
5410
5411 /// The (re)declaration of this tag type owned by this occurrence is stored
5412 /// as a trailing object if there is one. Use getOwnedTagDecl to obtain
5413 /// it, or obtain a null pointer if there is none.
5414
5415 ElaboratedType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5416 QualType NamedType, QualType CanonType, TagDecl *OwnedTagDecl)
5417 : TypeWithKeyword(Keyword, Elaborated, CanonType,
5418 // Any semantic dependence on the qualifier will have
5419 // been incorporated into NamedType. We still need to
5420 // track syntactic (instantiation / error / pack)
5421 // dependence on the qualifier.
5422 NamedType->getDependence() |
5423 (NNS ? toSyntacticDependence(
5424 toTypeDependence(NNS->getDependence()))
5425 : TypeDependence::None)),
5426 NNS(NNS), NamedType(NamedType) {
5427 ElaboratedTypeBits.HasOwnedTagDecl = false;
5428 if (OwnedTagDecl) {
5429 ElaboratedTypeBits.HasOwnedTagDecl = true;
5430 *getTrailingObjects<TagDecl *>() = OwnedTagDecl;
5431 }
5432 assert(!(Keyword == ETK_None && NNS == nullptr) &&((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
5433 "ElaboratedType cannot have elaborated type keyword "((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
5434 "and name qualifier both null.")((!(Keyword == ETK_None && NNS == nullptr) &&
"ElaboratedType cannot have elaborated type keyword " "and name qualifier both null."
) ? static_cast<void> (0) : __assert_fail ("!(Keyword == ETK_None && NNS == nullptr) && \"ElaboratedType cannot have elaborated type keyword \" \"and name qualifier both null.\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5434, __PRETTY_FUNCTION__))
;
5435 }
5436
5437public:
5438 /// Retrieve the qualification on this type.
5439 NestedNameSpecifier *getQualifier() const { return NNS; }
5440
5441 /// Retrieve the type named by the qualified-id.
5442 QualType getNamedType() const { return NamedType; }
5443
5444 /// Remove a single level of sugar.
5445 QualType desugar() const { return getNamedType(); }
5446
5447 /// Returns whether this type directly provides sugar.
5448 bool isSugared() const { return true; }
5449
5450 /// Return the (re)declaration of this type owned by this occurrence of this
5451 /// type, or nullptr if there is none.
5452 TagDecl *getOwnedTagDecl() const {
5453 return ElaboratedTypeBits.HasOwnedTagDecl ? *getTrailingObjects<TagDecl *>()
5454 : nullptr;
5455 }
5456
5457 void Profile(llvm::FoldingSetNodeID &ID) {
5458 Profile(ID, getKeyword(), NNS, NamedType, getOwnedTagDecl());
5459 }
5460
5461 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5462 NestedNameSpecifier *NNS, QualType NamedType,
5463 TagDecl *OwnedTagDecl) {
5464 ID.AddInteger(Keyword);
5465 ID.AddPointer(NNS);
5466 NamedType.Profile(ID);
5467 ID.AddPointer(OwnedTagDecl);
5468 }
5469
5470 static bool classof(const Type *T) { return T->getTypeClass() == Elaborated; }
5471};
5472
5473/// Represents a qualified type name for which the type name is
5474/// dependent.
5475///
5476/// DependentNameType represents a class of dependent types that involve a
5477/// possibly dependent nested-name-specifier (e.g., "T::") followed by a
5478/// name of a type. The DependentNameType may start with a "typename" (for a
5479/// typename-specifier), "class", "struct", "union", or "enum" (for a
5480/// dependent elaborated-type-specifier), or nothing (in contexts where we
5481/// know that we must be referring to a type, e.g., in a base class specifier).
5482/// Typically the nested-name-specifier is dependent, but in MSVC compatibility
5483/// mode, this type is used with non-dependent names to delay name lookup until
5484/// instantiation.
5485class DependentNameType : public TypeWithKeyword, public llvm::FoldingSetNode {
5486 friend class ASTContext; // ASTContext creates these
5487
5488 /// The nested name specifier containing the qualifier.
5489 NestedNameSpecifier *NNS;
5490
5491 /// The type that this typename specifier refers to.
5492 const IdentifierInfo *Name;
5493
5494 DependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS,
5495 const IdentifierInfo *Name, QualType CanonType)
5496 : TypeWithKeyword(Keyword, DependentName, CanonType,
5497 TypeDependence::DependentInstantiation |
5498 toTypeDependence(NNS->getDependence())),
5499 NNS(NNS), Name(Name) {}
5500
5501public:
5502 /// Retrieve the qualification on this type.
5503 NestedNameSpecifier *getQualifier() const { return NNS; }
5504
5505 /// Retrieve the type named by the typename specifier as an identifier.
5506 ///
5507 /// This routine will return a non-NULL identifier pointer when the
5508 /// form of the original typename was terminated by an identifier,
5509 /// e.g., "typename T::type".
5510 const IdentifierInfo *getIdentifier() const {
5511 return Name;
5512 }
5513
5514 bool isSugared() const { return false; }
5515 QualType desugar() const { return QualType(this, 0); }
5516
5517 void Profile(llvm::FoldingSetNodeID &ID) {
5518 Profile(ID, getKeyword(), NNS, Name);
5519 }
5520
5521 static void Profile(llvm::FoldingSetNodeID &ID, ElaboratedTypeKeyword Keyword,
5522 NestedNameSpecifier *NNS, const IdentifierInfo *Name) {
5523 ID.AddInteger(Keyword);
5524 ID.AddPointer(NNS);
5525 ID.AddPointer(Name);
5526 }
5527
5528 static bool classof(const Type *T) {
5529 return T->getTypeClass() == DependentName;
5530 }
5531};
5532
5533/// Represents a template specialization type whose template cannot be
5534/// resolved, e.g.
5535/// A<T>::template B<T>
5536class alignas(8) DependentTemplateSpecializationType
5537 : public TypeWithKeyword,
5538 public llvm::FoldingSetNode {
5539 friend class ASTContext; // ASTContext creates these
5540
5541 /// The nested name specifier containing the qualifier.
5542 NestedNameSpecifier *NNS;
5543
5544 /// The identifier of the template.
5545 const IdentifierInfo *Name;
5546
5547 DependentTemplateSpecializationType(ElaboratedTypeKeyword Keyword,
5548 NestedNameSpecifier *NNS,
5549 const IdentifierInfo *Name,
5550 ArrayRef<TemplateArgument> Args,
5551 QualType Canon);
5552
5553 const TemplateArgument *getArgBuffer() const {
5554 return reinterpret_cast<const TemplateArgument*>(this+1);
5555 }
5556
5557 TemplateArgument *getArgBuffer() {
5558 return reinterpret_cast<TemplateArgument*>(this+1);
5559 }
5560
5561public:
5562 NestedNameSpecifier *getQualifier() const { return NNS; }
5563 const IdentifierInfo *getIdentifier() const { return Name; }
5564
5565 /// Retrieve the template arguments.
5566 const TemplateArgument *getArgs() const {
5567 return getArgBuffer();
5568 }
5569
5570 /// Retrieve the number of template arguments.
5571 unsigned getNumArgs() const {
5572 return DependentTemplateSpecializationTypeBits.NumArgs;
5573 }
5574
5575 const TemplateArgument &getArg(unsigned Idx) const; // in TemplateBase.h
5576
5577 ArrayRef<TemplateArgument> template_arguments() const {
5578 return {getArgs(), getNumArgs()};
5579 }
5580
5581 using iterator = const TemplateArgument *;
5582
5583 iterator begin() const { return getArgs(); }
5584 iterator end() const; // inline in TemplateBase.h
5585
5586 bool isSugared() const { return false; }
5587 QualType desugar() const { return QualType(this, 0); }
5588
5589 void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context) {
5590 Profile(ID, Context, getKeyword(), NNS, Name, {getArgs(), getNumArgs()});
5591 }
5592
5593 static void Profile(llvm::FoldingSetNodeID &ID,
5594 const ASTContext &Context,
5595 ElaboratedTypeKeyword Keyword,
5596 NestedNameSpecifier *Qualifier,
5597 const IdentifierInfo *Name,
5598 ArrayRef<TemplateArgument> Args);
5599
5600 static bool classof(const Type *T) {
5601 return T->getTypeClass() == DependentTemplateSpecialization;
5602 }
5603};
5604
5605/// Represents a pack expansion of types.
5606///
5607/// Pack expansions are part of C++11 variadic templates. A pack
5608/// expansion contains a pattern, which itself contains one or more
5609/// "unexpanded" parameter packs. When instantiated, a pack expansion
5610/// produces a series of types, each instantiated from the pattern of
5611/// the expansion, where the Ith instantiation of the pattern uses the
5612/// Ith arguments bound to each of the unexpanded parameter packs. The
5613/// pack expansion is considered to "expand" these unexpanded
5614/// parameter packs.
5615///
5616/// \code
5617/// template<typename ...Types> struct tuple;
5618///
5619/// template<typename ...Types>
5620/// struct tuple_of_references {
5621/// typedef tuple<Types&...> type;
5622/// };
5623/// \endcode
5624///
5625/// Here, the pack expansion \c Types&... is represented via a
5626/// PackExpansionType whose pattern is Types&.
5627class PackExpansionType : public Type, public llvm::FoldingSetNode {
5628 friend class ASTContext; // ASTContext creates these
5629
5630 /// The pattern of the pack expansion.
5631 QualType Pattern;
5632
5633 PackExpansionType(QualType Pattern, QualType Canon,
5634 Optional<unsigned> NumExpansions)
5635 : Type(PackExpansion, Canon,
5636 (Pattern->getDependence() | TypeDependence::Dependent |
5637 TypeDependence::Instantiation) &
5638 ~TypeDependence::UnexpandedPack),
5639 Pattern(Pattern) {
5640 PackExpansionTypeBits.NumExpansions =
5641 NumExpansions ? *NumExpansions + 1 : 0;
5642 }
5643
5644public:
5645 /// Retrieve the pattern of this pack expansion, which is the
5646 /// type that will be repeatedly instantiated when instantiating the
5647 /// pack expansion itself.
5648 QualType getPattern() const { return Pattern; }
5649
5650 /// Retrieve the number of expansions that this pack expansion will
5651 /// generate, if known.
5652 Optional<unsigned> getNumExpansions() const {
5653 if (PackExpansionTypeBits.NumExpansions)
5654 return PackExpansionTypeBits.NumExpansions - 1;
5655 return None;
5656 }
5657
5658 bool isSugared() const { return false; }
5659 QualType desugar() const { return QualType(this, 0); }
5660
5661 void Profile(llvm::FoldingSetNodeID &ID) {
5662 Profile(ID, getPattern(), getNumExpansions());
5663 }
5664
5665 static void Profile(llvm::FoldingSetNodeID &ID, QualType Pattern,
5666 Optional<unsigned> NumExpansions) {
5667 ID.AddPointer(Pattern.getAsOpaquePtr());
5668 ID.AddBoolean(NumExpansions.hasValue());
5669 if (NumExpansions)
5670 ID.AddInteger(*NumExpansions);
5671 }
5672
5673 static bool classof(const Type *T) {
5674 return T->getTypeClass() == PackExpansion;
5675 }
5676};
5677
5678/// This class wraps the list of protocol qualifiers. For types that can
5679/// take ObjC protocol qualifers, they can subclass this class.
5680template <class T>
5681class ObjCProtocolQualifiers {
5682protected:
5683 ObjCProtocolQualifiers() = default;
5684
5685 ObjCProtocolDecl * const *getProtocolStorage() const {
5686 return const_cast<ObjCProtocolQualifiers*>(this)->getProtocolStorage();
5687 }
5688
5689 ObjCProtocolDecl **getProtocolStorage() {
5690 return static_cast<T*>(this)->getProtocolStorageImpl();
5691 }
5692
5693 void setNumProtocols(unsigned N) {
5694 static_cast<T*>(this)->setNumProtocolsImpl(N);
5695 }
5696
5697 void initialize(ArrayRef<ObjCProtocolDecl *> protocols) {
5698 setNumProtocols(protocols.size());
5699 assert(getNumProtocols() == protocols.size() &&((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5700, __PRETTY_FUNCTION__))
5700 "bitfield overflow in protocol count")((getNumProtocols() == protocols.size() && "bitfield overflow in protocol count"
) ? static_cast<void> (0) : __assert_fail ("getNumProtocols() == protocols.size() && \"bitfield overflow in protocol count\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5700, __PRETTY_FUNCTION__))
;
5701 if (!protocols.empty())
5702 memcpy(getProtocolStorage(), protocols.data(),
5703 protocols.size() * sizeof(ObjCProtocolDecl*));
5704 }
5705
5706public:
5707 using qual_iterator = ObjCProtocolDecl * const *;
5708 using qual_range = llvm::iterator_range<qual_iterator>;
5709
5710 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
5711 qual_iterator qual_begin() const { return getProtocolStorage(); }
5712 qual_iterator qual_end() const { return qual_begin() + getNumProtocols(); }
5713
5714 bool qual_empty() const { return getNumProtocols() == 0; }
5715
5716 /// Return the number of qualifying protocols in this type, or 0 if
5717 /// there are none.
5718 unsigned getNumProtocols() const {
5719 return static_cast<const T*>(this)->getNumProtocolsImpl();
5720 }
5721
5722 /// Fetch a protocol by index.
5723 ObjCProtocolDecl *getProtocol(unsigned I) const {
5724 assert(I < getNumProtocols() && "Out-of-range protocol access")((I < getNumProtocols() && "Out-of-range protocol access"
) ? static_cast<void> (0) : __assert_fail ("I < getNumProtocols() && \"Out-of-range protocol access\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5724, __PRETTY_FUNCTION__))
;
5725 return qual_begin()[I];
5726 }
5727
5728 /// Retrieve all of the protocol qualifiers.
5729 ArrayRef<ObjCProtocolDecl *> getProtocols() const {
5730 return ArrayRef<ObjCProtocolDecl *>(qual_begin(), getNumProtocols());
5731 }
5732};
5733
5734/// Represents a type parameter type in Objective C. It can take
5735/// a list of protocols.
5736class ObjCTypeParamType : public Type,
5737 public ObjCProtocolQualifiers<ObjCTypeParamType>,
5738 public llvm::FoldingSetNode {
5739 friend class ASTContext;
5740 friend class ObjCProtocolQualifiers<ObjCTypeParamType>;
5741
5742 /// The number of protocols stored on this type.
5743 unsigned NumProtocols : 6;
5744
5745 ObjCTypeParamDecl *OTPDecl;
5746
5747 /// The protocols are stored after the ObjCTypeParamType node. In the
5748 /// canonical type, the list of protocols are sorted alphabetically
5749 /// and uniqued.
5750 ObjCProtocolDecl **getProtocolStorageImpl();
5751
5752 /// Return the number of qualifying protocols in this interface type,
5753 /// or 0 if there are none.
5754 unsigned getNumProtocolsImpl() const {
5755 return NumProtocols;
5756 }
5757
5758 void setNumProtocolsImpl(unsigned N) {
5759 NumProtocols = N;
5760 }
5761
5762 ObjCTypeParamType(const ObjCTypeParamDecl *D,
5763 QualType can,
5764 ArrayRef<ObjCProtocolDecl *> protocols);
5765
5766public:
5767 bool isSugared() const { return true; }
5768 QualType desugar() const { return getCanonicalTypeInternal(); }
5769
5770 static bool classof(const Type *T) {
5771 return T->getTypeClass() == ObjCTypeParam;
5772 }
5773
5774 void Profile(llvm::FoldingSetNodeID &ID);
5775 static void Profile(llvm::FoldingSetNodeID &ID,
5776 const ObjCTypeParamDecl *OTPDecl,
5777 QualType CanonicalType,
5778 ArrayRef<ObjCProtocolDecl *> protocols);
5779
5780 ObjCTypeParamDecl *getDecl() const { return OTPDecl; }
5781};
5782
5783/// Represents a class type in Objective C.
5784///
5785/// Every Objective C type is a combination of a base type, a set of
5786/// type arguments (optional, for parameterized classes) and a list of
5787/// protocols.
5788///
5789/// Given the following declarations:
5790/// \code
5791/// \@class C<T>;
5792/// \@protocol P;
5793/// \endcode
5794///
5795/// 'C' is an ObjCInterfaceType C. It is sugar for an ObjCObjectType
5796/// with base C and no protocols.
5797///
5798/// 'C<P>' is an unspecialized ObjCObjectType with base C and protocol list [P].
5799/// 'C<C*>' is a specialized ObjCObjectType with type arguments 'C*' and no
5800/// protocol list.
5801/// 'C<C*><P>' is a specialized ObjCObjectType with base C, type arguments 'C*',
5802/// and protocol list [P].
5803///
5804/// 'id' is a TypedefType which is sugar for an ObjCObjectPointerType whose
5805/// pointee is an ObjCObjectType with base BuiltinType::ObjCIdType
5806/// and no protocols.
5807///
5808/// 'id<P>' is an ObjCObjectPointerType whose pointee is an ObjCObjectType
5809/// with base BuiltinType::ObjCIdType and protocol list [P]. Eventually
5810/// this should get its own sugar class to better represent the source.
5811class ObjCObjectType : public Type,
5812 public ObjCProtocolQualifiers<ObjCObjectType> {
5813 friend class ObjCProtocolQualifiers<ObjCObjectType>;
5814
5815 // ObjCObjectType.NumTypeArgs - the number of type arguments stored
5816 // after the ObjCObjectPointerType node.
5817 // ObjCObjectType.NumProtocols - the number of protocols stored
5818 // after the type arguments of ObjCObjectPointerType node.
5819 //
5820 // These protocols are those written directly on the type. If
5821 // protocol qualifiers ever become additive, the iterators will need
5822 // to get kindof complicated.
5823 //
5824 // In the canonical object type, these are sorted alphabetically
5825 // and uniqued.
5826
5827 /// Either a BuiltinType or an InterfaceType or sugar for either.
5828 QualType BaseType;
5829
5830 /// Cached superclass type.
5831 mutable llvm::PointerIntPair<const ObjCObjectType *, 1, bool>
5832 CachedSuperClassType;
5833
5834 QualType *getTypeArgStorage();
5835 const QualType *getTypeArgStorage() const {
5836 return const_cast<ObjCObjectType *>(this)->getTypeArgStorage();
5837 }
5838
5839 ObjCProtocolDecl **getProtocolStorageImpl();
5840 /// Return the number of qualifying protocols in this interface type,
5841 /// or 0 if there are none.
5842 unsigned getNumProtocolsImpl() const {
5843 return ObjCObjectTypeBits.NumProtocols;
5844 }
5845 void setNumProtocolsImpl(unsigned N) {
5846 ObjCObjectTypeBits.NumProtocols = N;
5847 }
5848
5849protected:
5850 enum Nonce_ObjCInterface { Nonce_ObjCInterface };
5851
5852 ObjCObjectType(QualType Canonical, QualType Base,
5853 ArrayRef<QualType> typeArgs,
5854 ArrayRef<ObjCProtocolDecl *> protocols,
5855 bool isKindOf);
5856
5857 ObjCObjectType(enum Nonce_ObjCInterface)
5858 : Type(ObjCInterface, QualType(), TypeDependence::None),
5859 BaseType(QualType(this_(), 0)) {
5860 ObjCObjectTypeBits.NumProtocols = 0;
5861 ObjCObjectTypeBits.NumTypeArgs = 0;
5862 ObjCObjectTypeBits.IsKindOf = 0;
5863 }
5864
5865 void computeSuperClassTypeSlow() const;
5866
5867public:
5868 /// Gets the base type of this object type. This is always (possibly
5869 /// sugar for) one of:
5870 /// - the 'id' builtin type (as opposed to the 'id' type visible to the
5871 /// user, which is a typedef for an ObjCObjectPointerType)
5872 /// - the 'Class' builtin type (same caveat)
5873 /// - an ObjCObjectType (currently always an ObjCInterfaceType)
5874 QualType getBaseType() const { return BaseType; }
5875
5876 bool isObjCId() const {
5877 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCId);
5878 }
5879
5880 bool isObjCClass() const {
5881 return getBaseType()->isSpecificBuiltinType(BuiltinType::ObjCClass);
5882 }
5883
5884 bool isObjCUnqualifiedId() const { return qual_empty() && isObjCId(); }
5885 bool isObjCUnqualifiedClass() const { return qual_empty() && isObjCClass(); }
5886 bool isObjCUnqualifiedIdOrClass() const {
5887 if (!qual_empty()) return false;
5888 if (const BuiltinType *T = getBaseType()->getAs<BuiltinType>())
5889 return T->getKind() == BuiltinType::ObjCId ||
5890 T->getKind() == BuiltinType::ObjCClass;
5891 return false;
5892 }
5893 bool isObjCQualifiedId() const { return !qual_empty() && isObjCId(); }
5894 bool isObjCQualifiedClass() const { return !qual_empty() && isObjCClass(); }
5895
5896 /// Gets the interface declaration for this object type, if the base type
5897 /// really is an interface.
5898 ObjCInterfaceDecl *getInterface() const;
5899
5900 /// Determine whether this object type is "specialized", meaning
5901 /// that it has type arguments.
5902 bool isSpecialized() const;
5903
5904 /// Determine whether this object type was written with type arguments.
5905 bool isSpecializedAsWritten() const {
5906 return ObjCObjectTypeBits.NumTypeArgs > 0;
5907 }
5908
5909 /// Determine whether this object type is "unspecialized", meaning
5910 /// that it has no type arguments.
5911 bool isUnspecialized() const { return !isSpecialized(); }
5912
5913 /// Determine whether this object type is "unspecialized" as
5914 /// written, meaning that it has no type arguments.
5915 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
5916
5917 /// Retrieve the type arguments of this object type (semantically).
5918 ArrayRef<QualType> getTypeArgs() const;
5919
5920 /// Retrieve the type arguments of this object type as they were
5921 /// written.
5922 ArrayRef<QualType> getTypeArgsAsWritten() const {
5923 return llvm::makeArrayRef(getTypeArgStorage(),
5924 ObjCObjectTypeBits.NumTypeArgs);
5925 }
5926
5927 /// Whether this is a "__kindof" type as written.
5928 bool isKindOfTypeAsWritten() const { return ObjCObjectTypeBits.IsKindOf; }
5929
5930 /// Whether this ia a "__kindof" type (semantically).
5931 bool isKindOfType() const;
5932
5933 /// Retrieve the type of the superclass of this object type.
5934 ///
5935 /// This operation substitutes any type arguments into the
5936 /// superclass of the current class type, potentially producing a
5937 /// specialization of the superclass type. Produces a null type if
5938 /// there is no superclass.
5939 QualType getSuperClassType() const {
5940 if (!CachedSuperClassType.getInt())
5941 computeSuperClassTypeSlow();
5942
5943 assert(CachedSuperClassType.getInt() && "Superclass not set?")((CachedSuperClassType.getInt() && "Superclass not set?"
) ? static_cast<void> (0) : __assert_fail ("CachedSuperClassType.getInt() && \"Superclass not set?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 5943, __PRETTY_FUNCTION__))
;
5944 return QualType(CachedSuperClassType.getPointer(), 0);
5945 }
5946
5947 /// Strip off the Objective-C "kindof" type and (with it) any
5948 /// protocol qualifiers.
5949 QualType stripObjCKindOfTypeAndQuals(const ASTContext &ctx) const;
5950
5951 bool isSugared() const { return false; }
5952 QualType desugar() const { return QualType(this, 0); }
5953
5954 static bool classof(const Type *T) {
5955 return T->getTypeClass() == ObjCObject ||
5956 T->getTypeClass() == ObjCInterface;
5957 }
5958};
5959
5960/// A class providing a concrete implementation
5961/// of ObjCObjectType, so as to not increase the footprint of
5962/// ObjCInterfaceType. Code outside of ASTContext and the core type
5963/// system should not reference this type.
5964class ObjCObjectTypeImpl : public ObjCObjectType, public llvm::FoldingSetNode {
5965 friend class ASTContext;
5966
5967 // If anyone adds fields here, ObjCObjectType::getProtocolStorage()
5968 // will need to be modified.
5969
5970 ObjCObjectTypeImpl(QualType Canonical, QualType Base,
5971 ArrayRef<QualType> typeArgs,
5972 ArrayRef<ObjCProtocolDecl *> protocols,
5973 bool isKindOf)
5974 : ObjCObjectType(Canonical, Base, typeArgs, protocols, isKindOf) {}
5975
5976public:
5977 void Profile(llvm::FoldingSetNodeID &ID);
5978 static void Profile(llvm::FoldingSetNodeID &ID,
5979 QualType Base,
5980 ArrayRef<QualType> typeArgs,
5981 ArrayRef<ObjCProtocolDecl *> protocols,
5982 bool isKindOf);
5983};
5984
5985inline QualType *ObjCObjectType::getTypeArgStorage() {
5986 return reinterpret_cast<QualType *>(static_cast<ObjCObjectTypeImpl*>(this)+1);
5987}
5988
5989inline ObjCProtocolDecl **ObjCObjectType::getProtocolStorageImpl() {
5990 return reinterpret_cast<ObjCProtocolDecl**>(
5991 getTypeArgStorage() + ObjCObjectTypeBits.NumTypeArgs);
5992}
5993
5994inline ObjCProtocolDecl **ObjCTypeParamType::getProtocolStorageImpl() {
5995 return reinterpret_cast<ObjCProtocolDecl**>(
5996 static_cast<ObjCTypeParamType*>(this)+1);
5997}
5998
5999/// Interfaces are the core concept in Objective-C for object oriented design.
6000/// They basically correspond to C++ classes. There are two kinds of interface
6001/// types: normal interfaces like `NSString`, and qualified interfaces, which
6002/// are qualified with a protocol list like `NSString<NSCopyable, NSAmazing>`.
6003///
6004/// ObjCInterfaceType guarantees the following properties when considered
6005/// as a subtype of its superclass, ObjCObjectType:
6006/// - There are no protocol qualifiers. To reinforce this, code which
6007/// tries to invoke the protocol methods via an ObjCInterfaceType will
6008/// fail to compile.
6009/// - It is its own base type. That is, if T is an ObjCInterfaceType*,
6010/// T->getBaseType() == QualType(T, 0).
6011class ObjCInterfaceType : public ObjCObjectType {
6012 friend class ASTContext; // ASTContext creates these.
6013 friend class ASTReader;
6014 friend class ObjCInterfaceDecl;
6015 template <class T> friend class serialization::AbstractTypeReader;
6016
6017 mutable ObjCInterfaceDecl *Decl;
6018
6019 ObjCInterfaceType(const ObjCInterfaceDecl *D)
6020 : ObjCObjectType(Nonce_ObjCInterface),
6021 Decl(const_cast<ObjCInterfaceDecl*>(D)) {}
6022
6023public:
6024 /// Get the declaration of this interface.
6025 ObjCInterfaceDecl *getDecl() const { return Decl; }
6026
6027 bool isSugared() const { return false; }
6028 QualType desugar() const { return QualType(this, 0); }
6029
6030 static bool classof(const Type *T) {
6031 return T->getTypeClass() == ObjCInterface;
6032 }
6033
6034 // Nonsense to "hide" certain members of ObjCObjectType within this
6035 // class. People asking for protocols on an ObjCInterfaceType are
6036 // not going to get what they want: ObjCInterfaceTypes are
6037 // guaranteed to have no protocols.
6038 enum {
6039 qual_iterator,
6040 qual_begin,
6041 qual_end,
6042 getNumProtocols,
6043 getProtocol
6044 };
6045};
6046
6047inline ObjCInterfaceDecl *ObjCObjectType::getInterface() const {
6048 QualType baseType = getBaseType();
6049 while (const auto *ObjT = baseType->getAs<ObjCObjectType>()) {
6050 if (const auto *T = dyn_cast<ObjCInterfaceType>(ObjT))
6051 return T->getDecl();
6052
6053 baseType = ObjT->getBaseType();
6054 }
6055
6056 return nullptr;
6057}
6058
6059/// Represents a pointer to an Objective C object.
6060///
6061/// These are constructed from pointer declarators when the pointee type is
6062/// an ObjCObjectType (or sugar for one). In addition, the 'id' and 'Class'
6063/// types are typedefs for these, and the protocol-qualified types 'id<P>'
6064/// and 'Class<P>' are translated into these.
6065///
6066/// Pointers to pointers to Objective C objects are still PointerTypes;
6067/// only the first level of pointer gets it own type implementation.
6068class ObjCObjectPointerType : public Type, public llvm::FoldingSetNode {
6069 friend class ASTContext; // ASTContext creates these.
6070
6071 QualType PointeeType;
6072
6073 ObjCObjectPointerType(QualType Canonical, QualType Pointee)
6074 : Type(ObjCObjectPointer, Canonical, Pointee->getDependence()),
6075 PointeeType(Pointee) {}
6076
6077public:
6078 /// Gets the type pointed to by this ObjC pointer.
6079 /// The result will always be an ObjCObjectType or sugar thereof.
6080 QualType getPointeeType() const { return PointeeType; }
6081
6082 /// Gets the type pointed to by this ObjC pointer. Always returns non-null.
6083 ///
6084 /// This method is equivalent to getPointeeType() except that
6085 /// it discards any typedefs (or other sugar) between this
6086 /// type and the "outermost" object type. So for:
6087 /// \code
6088 /// \@class A; \@protocol P; \@protocol Q;
6089 /// typedef A<P> AP;
6090 /// typedef A A1;
6091 /// typedef A1<P> A1P;
6092 /// typedef A1P<Q> A1PQ;
6093 /// \endcode
6094 /// For 'A*', getObjectType() will return 'A'.
6095 /// For 'A<P>*', getObjectType() will return 'A<P>'.
6096 /// For 'AP*', getObjectType() will return 'A<P>'.
6097 /// For 'A1*', getObjectType() will return 'A'.
6098 /// For 'A1<P>*', getObjectType() will return 'A1<P>'.
6099 /// For 'A1P*', getObjectType() will return 'A1<P>'.
6100 /// For 'A1PQ*', getObjectType() will return 'A1<Q>', because
6101 /// adding protocols to a protocol-qualified base discards the
6102 /// old qualifiers (for now). But if it didn't, getObjectType()
6103 /// would return 'A1P<Q>' (and we'd have to make iterating over
6104 /// qualifiers more complicated).
6105 const ObjCObjectType *getObjectType() const {
6106 return PointeeType->castAs<ObjCObjectType>();
6107 }
6108
6109 /// If this pointer points to an Objective C
6110 /// \@interface type, gets the type for that interface. Any protocol
6111 /// qualifiers on the interface are ignored.
6112 ///
6113 /// \return null if the base type for this pointer is 'id' or 'Class'
6114 const ObjCInterfaceType *getInterfaceType() const;
6115
6116 /// If this pointer points to an Objective \@interface
6117 /// type, gets the declaration for that interface.
6118 ///
6119 /// \return null if the base type for this pointer is 'id' or 'Class'
6120 ObjCInterfaceDecl *getInterfaceDecl() const {
6121 return getObjectType()->getInterface();
6122 }
6123
6124 /// True if this is equivalent to the 'id' type, i.e. if
6125 /// its object type is the primitive 'id' type with no protocols.
6126 bool isObjCIdType() const {
6127 return getObjectType()->isObjCUnqualifiedId();
6128 }
6129
6130 /// True if this is equivalent to the 'Class' type,
6131 /// i.e. if its object tive is the primitive 'Class' type with no protocols.
6132 bool isObjCClassType() const {
6133 return getObjectType()->isObjCUnqualifiedClass();
6134 }
6135
6136 /// True if this is equivalent to the 'id' or 'Class' type,
6137 bool isObjCIdOrClassType() const {
6138 return getObjectType()->isObjCUnqualifiedIdOrClass();
6139 }
6140
6141 /// True if this is equivalent to 'id<P>' for some non-empty set of
6142 /// protocols.
6143 bool isObjCQualifiedIdType() const {
6144 return getObjectType()->isObjCQualifiedId();
6145 }
6146
6147 /// True if this is equivalent to 'Class<P>' for some non-empty set of
6148 /// protocols.
6149 bool isObjCQualifiedClassType() const {
6150 return getObjectType()->isObjCQualifiedClass();
6151 }
6152
6153 /// Whether this is a "__kindof" type.
6154 bool isKindOfType() const { return getObjectType()->isKindOfType(); }
6155
6156 /// Whether this type is specialized, meaning that it has type arguments.
6157 bool isSpecialized() const { return getObjectType()->isSpecialized(); }
6158
6159 /// Whether this type is specialized, meaning that it has type arguments.
6160 bool isSpecializedAsWritten() const {
6161 return getObjectType()->isSpecializedAsWritten();
6162 }
6163
6164 /// Whether this type is unspecialized, meaning that is has no type arguments.
6165 bool isUnspecialized() const { return getObjectType()->isUnspecialized(); }
6166
6167 /// Determine whether this object type is "unspecialized" as
6168 /// written, meaning that it has no type arguments.
6169 bool isUnspecializedAsWritten() const { return !isSpecializedAsWritten(); }
6170
6171 /// Retrieve the type arguments for this type.
6172 ArrayRef<QualType> getTypeArgs() const {
6173 return getObjectType()->getTypeArgs();
6174 }
6175
6176 /// Retrieve the type arguments for this type.
6177 ArrayRef<QualType> getTypeArgsAsWritten() const {
6178 return getObjectType()->getTypeArgsAsWritten();
6179 }
6180
6181 /// An iterator over the qualifiers on the object type. Provided
6182 /// for convenience. This will always iterate over the full set of
6183 /// protocols on a type, not just those provided directly.
6184 using qual_iterator = ObjCObjectType::qual_iterator;
6185 using qual_range = llvm::iterator_range<qual_iterator>;
6186
6187 qual_range quals() const { return qual_range(qual_begin(), qual_end()); }
6188
6189 qual_iterator qual_begin() const {
6190 return getObjectType()->qual_begin();
6191 }
6192
6193 qual_iterator qual_end() const {
6194 return getObjectType()->qual_end();
6195 }
6196
6197 bool qual_empty() const { return getObjectType()->qual_empty(); }
6198
6199 /// Return the number of qualifying protocols on the object type.
6200 unsigned getNumProtocols() const {
6201 return getObjectType()->getNumProtocols();
6202 }
6203
6204 /// Retrieve a qualifying protocol by index on the object type.
6205 ObjCProtocolDecl *getProtocol(unsigned I) const {
6206 return getObjectType()->getProtocol(I);
6207 }
6208
6209 bool isSugared() const { return false; }
6210 QualType desugar() const { return QualType(this, 0); }
6211
6212 /// Retrieve the type of the superclass of this object pointer type.
6213 ///
6214 /// This operation substitutes any type arguments into the
6215 /// superclass of the current class type, potentially producing a
6216 /// pointer to a specialization of the superclass type. Produces a
6217 /// null type if there is no superclass.
6218 QualType getSuperClassType() const;
6219
6220 /// Strip off the Objective-C "kindof" type and (with it) any
6221 /// protocol qualifiers.
6222 const ObjCObjectPointerType *stripObjCKindOfTypeAndQuals(
6223 const ASTContext &ctx) const;
6224
6225 void Profile(llvm::FoldingSetNodeID &ID) {
6226 Profile(ID, getPointeeType());
6227 }
6228
6229 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6230 ID.AddPointer(T.getAsOpaquePtr());
6231 }
6232
6233 static bool classof(const Type *T) {
6234 return T->getTypeClass() == ObjCObjectPointer;
6235 }
6236};
6237
6238class AtomicType : public Type, public llvm::FoldingSetNode {
6239 friend class ASTContext; // ASTContext creates these.
6240
6241 QualType ValueType;
6242
6243 AtomicType(QualType ValTy, QualType Canonical)
6244 : Type(Atomic, Canonical, ValTy->getDependence()), ValueType(ValTy) {}
6245
6246public:
6247 /// Gets the type contained by this atomic type, i.e.
6248 /// the type returned by performing an atomic load of this atomic type.
6249 QualType getValueType() const { return ValueType; }
6250
6251 bool isSugared() const { return false; }
6252 QualType desugar() const { return QualType(this, 0); }
6253
6254 void Profile(llvm::FoldingSetNodeID &ID) {
6255 Profile(ID, getValueType());
6256 }
6257
6258 static void Profile(llvm::FoldingSetNodeID &ID, QualType T) {
6259 ID.AddPointer(T.getAsOpaquePtr());
6260 }
6261
6262 static bool classof(const Type *T) {
6263 return T->getTypeClass() == Atomic;
6264 }
6265};
6266
6267/// PipeType - OpenCL20.
6268class PipeType : public Type, public llvm::FoldingSetNode {
6269 friend class ASTContext; // ASTContext creates these.
6270
6271 QualType ElementType;
6272 bool isRead;
6273
6274 PipeType(QualType elemType, QualType CanonicalPtr, bool isRead)
6275 : Type(Pipe, CanonicalPtr, elemType->getDependence()),
6276 ElementType(elemType), isRead(isRead) {}
6277
6278public:
6279 QualType getElementType() const { return ElementType; }
6280
6281 bool isSugared() const { return false; }
6282
6283 QualType desugar() const { return QualType(this, 0); }
6284
6285 void Profile(llvm::FoldingSetNodeID &ID) {
6286 Profile(ID, getElementType(), isReadOnly());
6287 }
6288
6289 static void Profile(llvm::FoldingSetNodeID &ID, QualType T, bool isRead) {
6290 ID.AddPointer(T.getAsOpaquePtr());
6291 ID.AddBoolean(isRead);
6292 }
6293
6294 static bool classof(const Type *T) {
6295 return T->getTypeClass() == Pipe;
6296 }
6297
6298 bool isReadOnly() const { return isRead; }
6299};
6300
6301/// A fixed int type of a specified bitwidth.
6302class ExtIntType final : public Type, public llvm::FoldingSetNode {
6303 friend class ASTContext;
6304 unsigned IsUnsigned : 1;
6305 unsigned NumBits : 24;
6306
6307protected:
6308 ExtIntType(bool isUnsigned, unsigned NumBits);
6309
6310public:
6311 bool isUnsigned() const { return IsUnsigned; }
6312 bool isSigned() const { return !IsUnsigned; }
6313 unsigned getNumBits() const { return NumBits; }
6314
6315 bool isSugared() const { return false; }
6316 QualType desugar() const { return QualType(this, 0); }
6317
6318 void Profile(llvm::FoldingSetNodeID &ID) {
6319 Profile(ID, isUnsigned(), getNumBits());
6320 }
6321
6322 static void Profile(llvm::FoldingSetNodeID &ID, bool IsUnsigned,
6323 unsigned NumBits) {
6324 ID.AddBoolean(IsUnsigned);
6325 ID.AddInteger(NumBits);
6326 }
6327
6328 static bool classof(const Type *T) { return T->getTypeClass() == ExtInt; }
6329};
6330
6331class DependentExtIntType final : public Type, public llvm::FoldingSetNode {
6332 friend class ASTContext;
6333 const ASTContext &Context;
6334 llvm::PointerIntPair<Expr*, 1, bool> ExprAndUnsigned;
6335
6336protected:
6337 DependentExtIntType(const ASTContext &Context, bool IsUnsigned,
6338 Expr *NumBits);
6339
6340public:
6341 bool isUnsigned() const;
6342 bool isSigned() const { return !isUnsigned(); }
6343 Expr *getNumBitsExpr() const;
6344
6345 bool isSugared() const { return false; }
6346 QualType desugar() const { return QualType(this, 0); }
6347
6348 void Profile(llvm::FoldingSetNodeID &ID) {
6349 Profile(ID, Context, isUnsigned(), getNumBitsExpr());
6350 }
6351 static void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context,
6352 bool IsUnsigned, Expr *NumBitsExpr);
6353
6354 static bool classof(const Type *T) {
6355 return T->getTypeClass() == DependentExtInt;
6356 }
6357};
6358
6359/// A qualifier set is used to build a set of qualifiers.
6360class QualifierCollector : public Qualifiers {
6361public:
6362 QualifierCollector(Qualifiers Qs = Qualifiers()) : Qualifiers(Qs) {}
6363
6364 /// Collect any qualifiers on the given type and return an
6365 /// unqualified type. The qualifiers are assumed to be consistent
6366 /// with those already in the type.
6367 const Type *strip(QualType type) {
6368 addFastQualifiers(type.getLocalFastQualifiers());
6369 if (!type.hasLocalNonFastQualifiers())
6370 return type.getTypePtrUnsafe();
6371
6372 const ExtQuals *extQuals = type.getExtQualsUnsafe();
6373 addConsistentQualifiers(extQuals->getQualifiers());
6374 return extQuals->getBaseType();
6375 }
6376
6377 /// Apply the collected qualifiers to the given type.
6378 QualType apply(const ASTContext &Context, QualType QT) const;
6379
6380 /// Apply the collected qualifiers to the given type.
6381 QualType apply(const ASTContext &Context, const Type* T) const;
6382};
6383
6384/// A container of type source information.
6385///
6386/// A client can read the relevant info using TypeLoc wrappers, e.g:
6387/// @code
6388/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
6389/// TL.getBeginLoc().print(OS, SrcMgr);
6390/// @endcode
6391class alignas(8) TypeSourceInfo {
6392 // Contains a memory block after the class, used for type source information,
6393 // allocated by ASTContext.
6394 friend class ASTContext;
6395
6396 QualType Ty;
6397
6398 TypeSourceInfo(QualType ty) : Ty(ty) {}
6399
6400public:
6401 /// Return the type wrapped by this type source info.
6402 QualType getType() const { return Ty; }
6403
6404 /// Return the TypeLoc wrapper for the type source info.
6405 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
6406
6407 /// Override the type stored in this TypeSourceInfo. Use with caution!
6408 void overrideType(QualType T) { Ty = T; }
6409};
6410
6411// Inline function definitions.
6412
6413inline SplitQualType SplitQualType::getSingleStepDesugaredType() const {
6414 SplitQualType desugar =
6415 Ty->getLocallyUnqualifiedSingleStepDesugaredType().split();
6416 desugar.Quals.addConsistentQualifiers(Quals);
6417 return desugar;
6418}
6419
6420inline const Type *QualType::getTypePtr() const {
6421 return getCommonPtr()->BaseType;
6422}
6423
6424inline const Type *QualType::getTypePtrOrNull() const {
6425 return (isNull() ? nullptr : getCommonPtr()->BaseType);
6426}
6427
6428inline SplitQualType QualType::split() const {
6429 if (!hasLocalNonFastQualifiers())
6430 return SplitQualType(getTypePtrUnsafe(),
6431 Qualifiers::fromFastMask(getLocalFastQualifiers()));
6432
6433 const ExtQuals *eq = getExtQualsUnsafe();
6434 Qualifiers qs = eq->getQualifiers();
6435 qs.addFastQualifiers(getLocalFastQualifiers());
6436 return SplitQualType(eq->getBaseType(), qs);
6437}
6438
6439inline Qualifiers QualType::getLocalQualifiers() const {
6440 Qualifiers Quals;
6441 if (hasLocalNonFastQualifiers())
6442 Quals = getExtQualsUnsafe()->getQualifiers();
6443 Quals.addFastQualifiers(getLocalFastQualifiers());
6444 return Quals;
6445}
6446
6447inline Qualifiers QualType::getQualifiers() const {
6448 Qualifiers quals = getCommonPtr()->CanonicalType.getLocalQualifiers();
6449 quals.addFastQualifiers(getLocalFastQualifiers());
6450 return quals;
6451}
6452
6453inline unsigned QualType::getCVRQualifiers() const {
6454 unsigned cvr = getCommonPtr()->CanonicalType.getLocalCVRQualifiers();
6455 cvr |= getLocalCVRQualifiers();
6456 return cvr;
6457}
6458
6459inline QualType QualType::getCanonicalType() const {
6460 QualType canon = getCommonPtr()->CanonicalType;
6461 return canon.withFastQualifiers(getLocalFastQualifiers());
6462}
6463
6464inline bool QualType::isCanonical() const {
6465 return getTypePtr()->isCanonicalUnqualified();
6466}
6467
6468inline bool QualType::isCanonicalAsParam() const {
6469 if (!isCanonical()) return false;
6470 if (hasLocalQualifiers()) return false;
6471
6472 const Type *T = getTypePtr();
6473 if (T->isVariablyModifiedType() && T->hasSizedVLAType())
6474 return false;
6475
6476 return !isa<FunctionType>(T) && !isa<ArrayType>(T);
6477}
6478
6479inline bool QualType::isConstQualified() const {
6480 return isLocalConstQualified() ||
6481 getCommonPtr()->CanonicalType.isLocalConstQualified();
6482}
6483
6484inline bool QualType::isRestrictQualified() const {
6485 return isLocalRestrictQualified() ||
6486 getCommonPtr()->CanonicalType.isLocalRestrictQualified();
6487}
6488
6489
6490inline bool QualType::isVolatileQualified() const {
6491 return isLocalVolatileQualified() ||
6492 getCommonPtr()->CanonicalType.isLocalVolatileQualified();
6493}
6494
6495inline bool QualType::hasQualifiers() const {
6496 return hasLocalQualifiers() ||
6497 getCommonPtr()->CanonicalType.hasLocalQualifiers();
6498}
6499
6500inline QualType QualType::getUnqualifiedType() const {
6501 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6502 return QualType(getTypePtr(), 0);
6503
6504 return QualType(getSplitUnqualifiedTypeImpl(*this).Ty, 0);
6505}
6506
6507inline SplitQualType QualType::getSplitUnqualifiedType() const {
6508 if (!getTypePtr()->getCanonicalTypeInternal().hasLocalQualifiers())
6509 return split();
6510
6511 return getSplitUnqualifiedTypeImpl(*this);
6512}
6513
6514inline void QualType::removeLocalConst() {
6515 removeLocalFastQualifiers(Qualifiers::Const);
6516}
6517
6518inline void QualType::removeLocalRestrict() {
6519 removeLocalFastQualifiers(Qualifiers::Restrict);
6520}
6521
6522inline void QualType::removeLocalVolatile() {
6523 removeLocalFastQualifiers(Qualifiers::Volatile);
6524}
6525
6526inline void QualType::removeLocalCVRQualifiers(unsigned Mask) {
6527 assert(!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits")((!(Mask & ~Qualifiers::CVRMask) && "mask has non-CVR bits"
) ? static_cast<void> (0) : __assert_fail ("!(Mask & ~Qualifiers::CVRMask) && \"mask has non-CVR bits\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 6527, __PRETTY_FUNCTION__))
;
6528 static_assert((int)Qualifiers::CVRMask == (int)Qualifiers::FastMask,
6529 "Fast bits differ from CVR bits!");
6530
6531 // Fast path: we don't need to touch the slow qualifiers.
6532 removeLocalFastQualifiers(Mask);
6533}
6534
6535/// Check if this type has any address space qualifier.
6536inline bool QualType::hasAddressSpace() const {
6537 return getQualifiers().hasAddressSpace();
6538}
6539
6540/// Return the address space of this type.
6541inline LangAS QualType::getAddressSpace() const {
6542 return getQualifiers().getAddressSpace();
6543}
6544
6545/// Return the gc attribute of this type.
6546inline Qualifiers::GC QualType::getObjCGCAttr() const {
6547 return getQualifiers().getObjCGCAttr();
6548}
6549
6550inline bool QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion() const {
6551 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6552 return hasNonTrivialToPrimitiveDefaultInitializeCUnion(RD);
6553 return false;
6554}
6555
6556inline bool QualType::hasNonTrivialToPrimitiveDestructCUnion() const {
6557 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6558 return hasNonTrivialToPrimitiveDestructCUnion(RD);
6559 return false;
6560}
6561
6562inline bool QualType::hasNonTrivialToPrimitiveCopyCUnion() const {
6563 if (auto *RD = getTypePtr()->getBaseElementTypeUnsafe()->getAsRecordDecl())
6564 return hasNonTrivialToPrimitiveCopyCUnion(RD);
6565 return false;
6566}
6567
6568inline FunctionType::ExtInfo getFunctionExtInfo(const Type &t) {
6569 if (const auto *PT = t.getAs<PointerType>()) {
6570 if (const auto *FT = PT->getPointeeType()->getAs<FunctionType>())
6571 return FT->getExtInfo();
6572 } else if (const auto *FT = t.getAs<FunctionType>())
6573 return FT->getExtInfo();
6574
6575 return FunctionType::ExtInfo();
6576}
6577
6578inline FunctionType::ExtInfo getFunctionExtInfo(QualType t) {
6579 return getFunctionExtInfo(*t);
6580}
6581
6582/// Determine whether this type is more
6583/// qualified than the Other type. For example, "const volatile int"
6584/// is more qualified than "const int", "volatile int", and
6585/// "int". However, it is not more qualified than "const volatile
6586/// int".
6587inline bool QualType::isMoreQualifiedThan(QualType other) const {
6588 Qualifiers MyQuals = getQualifiers();
6589 Qualifiers OtherQuals = other.getQualifiers();
6590 return (MyQuals != OtherQuals && MyQuals.compatiblyIncludes(OtherQuals));
6591}
6592
6593/// Determine whether this type is at last
6594/// as qualified as the Other type. For example, "const volatile
6595/// int" is at least as qualified as "const int", "volatile int",
6596/// "int", and "const volatile int".
6597inline bool QualType::isAtLeastAsQualifiedAs(QualType other) const {
6598 Qualifiers OtherQuals = other.getQualifiers();
6599
6600 // Ignore __unaligned qualifier if this type is a void.
6601 if (getUnqualifiedType()->isVoidType())
6602 OtherQuals.removeUnaligned();
6603
6604 return getQualifiers().compatiblyIncludes(OtherQuals);
6605}
6606
6607/// If Type is a reference type (e.g., const
6608/// int&), returns the type that the reference refers to ("const
6609/// int"). Otherwise, returns the type itself. This routine is used
6610/// throughout Sema to implement C++ 5p6:
6611///
6612/// If an expression initially has the type "reference to T" (8.3.2,
6613/// 8.5.3), the type is adjusted to "T" prior to any further
6614/// analysis, the expression designates the object or function
6615/// denoted by the reference, and the expression is an lvalue.
6616inline QualType QualType::getNonReferenceType() const {
6617 if (const auto *RefType = (*this)->getAs<ReferenceType>())
6618 return RefType->getPointeeType();
6619 else
6620 return *this;
6621}
6622
6623inline bool QualType::isCForbiddenLValueType() const {
6624 return ((getTypePtr()->isVoidType() && !hasQualifiers()) ||
6625 getTypePtr()->isFunctionType());
6626}
6627
6628/// Tests whether the type is categorized as a fundamental type.
6629///
6630/// \returns True for types specified in C++0x [basic.fundamental].
6631inline bool Type::isFundamentalType() const {
6632 return isVoidType() ||
6633 isNullPtrType() ||
6634 // FIXME: It's really annoying that we don't have an
6635 // 'isArithmeticType()' which agrees with the standard definition.
6636 (isArithmeticType() && !isEnumeralType());
6637}
6638
6639/// Tests whether the type is categorized as a compound type.
6640///
6641/// \returns True for types specified in C++0x [basic.compound].
6642inline bool Type::isCompoundType() const {
6643 // C++0x [basic.compound]p1:
6644 // Compound types can be constructed in the following ways:
6645 // -- arrays of objects of a given type [...];
6646 return isArrayType() ||
6647 // -- functions, which have parameters of given types [...];
6648 isFunctionType() ||
6649 // -- pointers to void or objects or functions [...];
6650 isPointerType() ||
6651 // -- references to objects or functions of a given type. [...]
6652 isReferenceType() ||
6653 // -- classes containing a sequence of objects of various types, [...];
6654 isRecordType() ||
6655 // -- unions, which are classes capable of containing objects of different
6656 // types at different times;
6657 isUnionType() ||
6658 // -- enumerations, which comprise a set of named constant values. [...];
6659 isEnumeralType() ||
6660 // -- pointers to non-static class members, [...].
6661 isMemberPointerType();
6662}
6663
6664inline bool Type::isFunctionType() const {
6665 return isa<FunctionType>(CanonicalType);
6666}
6667
6668inline bool Type::isPointerType() const {
6669 return isa<PointerType>(CanonicalType);
6670}
6671
6672inline bool Type::isAnyPointerType() const {
6673 return isPointerType() || isObjCObjectPointerType();
6674}
6675
6676inline bool Type::isBlockPointerType() const {
6677 return isa<BlockPointerType>(CanonicalType);
14
Assuming field 'CanonicalType' is a 'BlockPointerType'
15
Returning the value 1, which participates in a condition later
6678}
6679
6680inline bool Type::isReferenceType() const {
6681 return isa<ReferenceType>(CanonicalType);
6682}
6683
6684inline bool Type::isLValueReferenceType() const {
6685 return isa<LValueReferenceType>(CanonicalType);
6686}
6687
6688inline bool Type::isRValueReferenceType() const {
6689 return isa<RValueReferenceType>(CanonicalType);
6690}
6691
6692inline bool Type::isObjectPointerType() const {
6693 // Note: an "object pointer type" is not the same thing as a pointer to an
6694 // object type; rather, it is a pointer to an object type or a pointer to cv
6695 // void.
6696 if (const auto *T = getAs<PointerType>())
6697 return !T->getPointeeType()->isFunctionType();
6698 else
6699 return false;
6700}
6701
6702inline bool Type::isFunctionPointerType() const {
6703 if (const auto *T = getAs<PointerType>())
6704 return T->getPointeeType()->isFunctionType();
6705 else
6706 return false;
6707}
6708
6709inline bool Type::isFunctionReferenceType() const {
6710 if (const auto *T = getAs<ReferenceType>())
6711 return T->getPointeeType()->isFunctionType();
6712 else
6713 return false;
6714}
6715
6716inline bool Type::isMemberPointerType() const {
6717 return isa<MemberPointerType>(CanonicalType);
6718}
6719
6720inline bool Type::isMemberFunctionPointerType() const {
6721 if (const auto *T = getAs<MemberPointerType>())
6722 return T->isMemberFunctionPointer();
6723 else
6724 return false;
6725}
6726
6727inline bool Type::isMemberDataPointerType() const {
6728 if (const auto *T = getAs<MemberPointerType>())
6729 return T->isMemberDataPointer();
6730 else
6731 return false;
6732}
6733
6734inline bool Type::isArrayType() const {
6735 return isa<ArrayType>(CanonicalType);
6736}
6737
6738inline bool Type::isConstantArrayType() const {
6739 return isa<ConstantArrayType>(CanonicalType);
6740}
6741
6742inline bool Type::isIncompleteArrayType() const {
6743 return isa<IncompleteArrayType>(CanonicalType);
6744}
6745
6746inline bool Type::isVariableArrayType() const {
6747 return isa<VariableArrayType>(CanonicalType);
6748}
6749
6750inline bool Type::isDependentSizedArrayType() const {
6751 return isa<DependentSizedArrayType>(CanonicalType);
6752}
6753
6754inline bool Type::isBuiltinType() const {
6755 return isa<BuiltinType>(CanonicalType);
6756}
6757
6758inline bool Type::isRecordType() const {
6759 return isa<RecordType>(CanonicalType);
6760}
6761
6762inline bool Type::isEnumeralType() const {
6763 return isa<EnumType>(CanonicalType);
6764}
6765
6766inline bool Type::isAnyComplexType() const {
6767 return isa<ComplexType>(CanonicalType);
6768}
6769
6770inline bool Type::isVectorType() const {
6771 return isa<VectorType>(CanonicalType);
6772}
6773
6774inline bool Type::isExtVectorType() const {
6775 return isa<ExtVectorType>(CanonicalType);
6776}
6777
6778inline bool Type::isMatrixType() const {
6779 return isa<MatrixType>(CanonicalType);
6780}
6781
6782inline bool Type::isConstantMatrixType() const {
6783 return isa<ConstantMatrixType>(CanonicalType);
6784}
6785
6786inline bool Type::isDependentAddressSpaceType() const {
6787 return isa<DependentAddressSpaceType>(CanonicalType);
6788}
6789
6790inline bool Type::isObjCObjectPointerType() const {
6791 return isa<ObjCObjectPointerType>(CanonicalType);
6792}
6793
6794inline bool Type::isObjCObjectType() const {
6795 return isa<ObjCObjectType>(CanonicalType);
6796}
6797
6798inline bool Type::isObjCObjectOrInterfaceType() const {
6799 return isa<ObjCInterfaceType>(CanonicalType) ||
6800 isa<ObjCObjectType>(CanonicalType);
6801}
6802
6803inline bool Type::isAtomicType() const {
6804 return isa<AtomicType>(CanonicalType);
6805}
6806
6807inline bool Type::isUndeducedAutoType() const {
6808 return isa<AutoType>(CanonicalType);
6809}
6810
6811inline bool Type::isObjCQualifiedIdType() const {
6812 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6813 return OPT->isObjCQualifiedIdType();
6814 return false;
6815}
6816
6817inline bool Type::isObjCQualifiedClassType() const {
6818 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6819 return OPT->isObjCQualifiedClassType();
6820 return false;
6821}
6822
6823inline bool Type::isObjCIdType() const {
6824 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6825 return OPT->isObjCIdType();
6826 return false;
6827}
6828
6829inline bool Type::isObjCClassType() const {
6830 if (const auto *OPT = getAs<ObjCObjectPointerType>())
6831 return OPT->isObjCClassType();
6832 return false;
6833}
6834
6835inline bool Type::isObjCSelType() const {
6836 if (const auto *OPT = getAs<PointerType>())
6837 return OPT->getPointeeType()->isSpecificBuiltinType(BuiltinType::ObjCSel);
6838 return false;
6839}
6840
6841inline bool Type::isObjCBuiltinType() const {
6842 return isObjCIdType() || isObjCClassType() || isObjCSelType();
6843}
6844
6845inline bool Type::isDecltypeType() const {
6846 return isa<DecltypeType>(this);
6847}
6848
6849#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6850 inline bool Type::is##Id##Type() const { \
6851 return isSpecificBuiltinType(BuiltinType::Id); \
6852 }
6853#include "clang/Basic/OpenCLImageTypes.def"
6854
6855inline bool Type::isSamplerT() const {
6856 return isSpecificBuiltinType(BuiltinType::OCLSampler);
6857}
6858
6859inline bool Type::isEventT() const {
6860 return isSpecificBuiltinType(BuiltinType::OCLEvent);
6861}
6862
6863inline bool Type::isClkEventT() const {
6864 return isSpecificBuiltinType(BuiltinType::OCLClkEvent);
6865}
6866
6867inline bool Type::isQueueT() const {
6868 return isSpecificBuiltinType(BuiltinType::OCLQueue);
6869}
6870
6871inline bool Type::isReserveIDT() const {
6872 return isSpecificBuiltinType(BuiltinType::OCLReserveID);
6873}
6874
6875inline bool Type::isImageType() const {
6876#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) is##Id##Type() ||
6877 return
6878#include "clang/Basic/OpenCLImageTypes.def"
6879 false; // end boolean or operation
6880}
6881
6882inline bool Type::isPipeType() const {
6883 return isa<PipeType>(CanonicalType);
6884}
6885
6886inline bool Type::isExtIntType() const {
6887 return isa<ExtIntType>(CanonicalType);
6888}
6889
6890#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
6891 inline bool Type::is##Id##Type() const { \
6892 return isSpecificBuiltinType(BuiltinType::Id); \
6893 }
6894#include "clang/Basic/OpenCLExtensionTypes.def"
6895
6896inline bool Type::isOCLIntelSubgroupAVCType() const {
6897#define INTEL_SUBGROUP_AVC_TYPE(ExtType, Id) \
6898 isOCLIntelSubgroupAVC##Id##Type() ||
6899 return
6900#include "clang/Basic/OpenCLExtensionTypes.def"
6901 false; // end of boolean or operation
6902}
6903
6904inline bool Type::isOCLExtOpaqueType() const {
6905#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) is##Id##Type() ||
6906 return
6907#include "clang/Basic/OpenCLExtensionTypes.def"
6908 false; // end of boolean or operation
6909}
6910
6911inline bool Type::isOpenCLSpecificType() const {
6912 return isSamplerT() || isEventT() || isImageType() || isClkEventT() ||
6913 isQueueT() || isReserveIDT() || isPipeType() || isOCLExtOpaqueType();
6914}
6915
6916inline bool Type::isTemplateTypeParmType() const {
6917 return isa<TemplateTypeParmType>(CanonicalType);
6918}
6919
6920inline bool Type::isSpecificBuiltinType(unsigned K) const {
6921 if (const BuiltinType *BT = getAs<BuiltinType>()) {
6922 return BT->getKind() == static_cast<BuiltinType::Kind>(K);
6923 }
6924 return false;
6925}
6926
6927inline bool Type::isPlaceholderType() const {
6928 if (const auto *BT = dyn_cast<BuiltinType>(this))
6929 return BT->isPlaceholderType();
6930 return false;
6931}
6932
6933inline const BuiltinType *Type::getAsPlaceholderType() const {
6934 if (const auto *BT = dyn_cast<BuiltinType>(this))
6935 if (BT->isPlaceholderType())
6936 return BT;
6937 return nullptr;
6938}
6939
6940inline bool Type::isSpecificPlaceholderType(unsigned K) const {
6941 assert(BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K))((BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)) ?
static_cast<void> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind((BuiltinType::Kind) K)"
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 6941, __PRETTY_FUNCTION__))
;
6942 return isSpecificBuiltinType(K);
6943}
6944
6945inline bool Type::isNonOverloadPlaceholderType() const {
6946 if (const auto *BT = dyn_cast<BuiltinType>(this))
6947 return BT->isNonOverloadPlaceholderType();
6948 return false;
6949}
6950
6951inline bool Type::isVoidType() const {
6952 return isSpecificBuiltinType(BuiltinType::Void);
6953}
6954
6955inline bool Type::isHalfType() const {
6956 // FIXME: Should we allow complex __fp16? Probably not.
6957 return isSpecificBuiltinType(BuiltinType::Half);
6958}
6959
6960inline bool Type::isFloat16Type() const {
6961 return isSpecificBuiltinType(BuiltinType::Float16);
6962}
6963
6964inline bool Type::isBFloat16Type() const {
6965 return isSpecificBuiltinType(BuiltinType::BFloat16);
6966}
6967
6968inline bool Type::isFloat128Type() const {
6969 return isSpecificBuiltinType(BuiltinType::Float128);
6970}
6971
6972inline bool Type::isNullPtrType() const {
6973 return isSpecificBuiltinType(BuiltinType::NullPtr);
6974}
6975
6976bool IsEnumDeclComplete(EnumDecl *);
6977bool IsEnumDeclScoped(EnumDecl *);
6978
6979inline bool Type::isIntegerType() const {
6980 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
6981 return BT->getKind() >= BuiltinType::Bool &&
6982 BT->getKind() <= BuiltinType::Int128;
6983 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType)) {
6984 // Incomplete enum types are not treated as integer types.
6985 // FIXME: In C++, enum types are never integer types.
6986 return IsEnumDeclComplete(ET->getDecl()) &&
6987 !IsEnumDeclScoped(ET->getDecl());
6988 }
6989 return isExtIntType();
6990}
6991
6992inline bool Type::isFixedPointType() const {
6993 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
6994 return BT->getKind() >= BuiltinType::ShortAccum &&
6995 BT->getKind() <= BuiltinType::SatULongFract;
6996 }
6997 return false;
6998}
6999
7000inline bool Type::isFixedPointOrIntegerType() const {
7001 return isFixedPointType() || isIntegerType();
7002}
7003
7004inline bool Type::isSaturatedFixedPointType() const {
7005 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7006 return BT->getKind() >= BuiltinType::SatShortAccum &&
7007 BT->getKind() <= BuiltinType::SatULongFract;
7008 }
7009 return false;
7010}
7011
7012inline bool Type::isUnsaturatedFixedPointType() const {
7013 return isFixedPointType() && !isSaturatedFixedPointType();
7014}
7015
7016inline bool Type::isSignedFixedPointType() const {
7017 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType)) {
7018 return ((BT->getKind() >= BuiltinType::ShortAccum &&
7019 BT->getKind() <= BuiltinType::LongAccum) ||
7020 (BT->getKind() >= BuiltinType::ShortFract &&
7021 BT->getKind() <= BuiltinType::LongFract) ||
7022 (BT->getKind() >= BuiltinType::SatShortAccum &&
7023 BT->getKind() <= BuiltinType::SatLongAccum) ||
7024 (BT->getKind() >= BuiltinType::SatShortFract &&
7025 BT->getKind() <= BuiltinType::SatLongFract));
7026 }
7027 return false;
7028}
7029
7030inline bool Type::isUnsignedFixedPointType() const {
7031 return isFixedPointType() && !isSignedFixedPointType();
7032}
7033
7034inline bool Type::isScalarType() const {
7035 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7036 return BT->getKind() > BuiltinType::Void &&
7037 BT->getKind() <= BuiltinType::NullPtr;
7038 if (const EnumType *ET = dyn_cast<EnumType>(CanonicalType))
7039 // Enums are scalar types, but only if they are defined. Incomplete enums
7040 // are not treated as scalar types.
7041 return IsEnumDeclComplete(ET->getDecl());
7042 return isa<PointerType>(CanonicalType) ||
7043 isa<BlockPointerType>(CanonicalType) ||
7044 isa<MemberPointerType>(CanonicalType) ||
7045 isa<ComplexType>(CanonicalType) ||
7046 isa<ObjCObjectPointerType>(CanonicalType) ||
7047 isExtIntType();
7048}
7049
7050inline bool Type::isIntegralOrEnumerationType() const {
7051 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7052 return BT->getKind() >= BuiltinType::Bool &&
7053 BT->getKind() <= BuiltinType::Int128;
7054
7055 // Check for a complete enum type; incomplete enum types are not properly an
7056 // enumeration type in the sense required here.
7057 if (const auto *ET = dyn_cast<EnumType>(CanonicalType))
7058 return IsEnumDeclComplete(ET->getDecl());
7059
7060 return isExtIntType();
7061}
7062
7063inline bool Type::isBooleanType() const {
7064 if (const auto *BT = dyn_cast<BuiltinType>(CanonicalType))
7065 return BT->getKind() == BuiltinType::Bool;
7066 return false;
7067}
7068
7069inline bool Type::isUndeducedType() const {
7070 auto *DT = getContainedDeducedType();
7071 return DT && !DT->isDeduced();
7072}
7073
7074/// Determines whether this is a type for which one can define
7075/// an overloaded operator.
7076inline bool Type::isOverloadableType() const {
7077 return isDependentType() || isRecordType() || isEnumeralType();
7078}
7079
7080/// Determines whether this type is written as a typedef-name.
7081inline bool Type::isTypedefNameType() const {
7082 if (getAs<TypedefType>())
7083 return true;
7084 if (auto *TST = getAs<TemplateSpecializationType>())
7085 return TST->isTypeAlias();
7086 return false;
7087}
7088
7089/// Determines whether this type can decay to a pointer type.
7090inline bool Type::canDecayToPointerType() const {
7091 return isFunctionType() || isArrayType();
7092}
7093
7094inline bool Type::hasPointerRepresentation() const {
7095 return (isPointerType() || isReferenceType() || isBlockPointerType() ||
7096 isObjCObjectPointerType() || isNullPtrType());
7097}
7098
7099inline bool Type::hasObjCPointerRepresentation() const {
7100 return isObjCObjectPointerType();
7101}
7102
7103inline const Type *Type::getBaseElementTypeUnsafe() const {
7104 const Type *type = this;
7105 while (const ArrayType *arrayType = type->getAsArrayTypeUnsafe())
7106 type = arrayType->getElementType().getTypePtr();
7107 return type;
7108}
7109
7110inline const Type *Type::getPointeeOrArrayElementType() const {
7111 const Type *type = this;
7112 if (type->isAnyPointerType())
7113 return type->getPointeeType().getTypePtr();
7114 else if (type->isArrayType())
7115 return type->getBaseElementTypeUnsafe();
7116 return type;
7117}
7118/// Insertion operator for partial diagnostics. This allows sending adress
7119/// spaces into a diagnostic with <<.
7120inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7121 LangAS AS) {
7122 PD.AddTaggedVal(static_cast<std::underlying_type_t<LangAS>>(AS),
7123 DiagnosticsEngine::ArgumentKind::ak_addrspace);
7124 return PD;
7125}
7126
7127/// Insertion operator for partial diagnostics. This allows sending Qualifiers
7128/// into a diagnostic with <<.
7129inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7130 Qualifiers Q) {
7131 PD.AddTaggedVal(Q.getAsOpaqueValue(),
7132 DiagnosticsEngine::ArgumentKind::ak_qual);
7133 return PD;
7134}
7135
7136/// Insertion operator for partial diagnostics. This allows sending QualType's
7137/// into a diagnostic with <<.
7138inline const StreamingDiagnostic &operator<<(const StreamingDiagnostic &PD,
7139 QualType T) {
7140 PD.AddTaggedVal(reinterpret_cast<intptr_t>(T.getAsOpaquePtr()),
7141 DiagnosticsEngine::ak_qualtype);
7142 return PD;
7143}
7144
7145// Helper class template that is used by Type::getAs to ensure that one does
7146// not try to look through a qualified type to get to an array type.
7147template <typename T>
7148using TypeIsArrayType =
7149 std::integral_constant<bool, std::is_same<T, ArrayType>::value ||
7150 std::is_base_of<ArrayType, T>::value>;
7151
7152// Member-template getAs<specific type>'.
7153template <typename T> const T *Type::getAs() const {
7154 static_assert(!TypeIsArrayType<T>::value,
7155 "ArrayType cannot be used with getAs!");
7156
7157 // If this is directly a T type, return it.
7158 if (const auto *Ty = dyn_cast<T>(this))
7159 return Ty;
7160
7161 // If the canonical form of this type isn't the right kind, reject it.
7162 if (!isa<T>(CanonicalType))
7163 return nullptr;
7164
7165 // If this is a typedef for the type, strip the typedef off without
7166 // losing all typedef information.
7167 return cast<T>(getUnqualifiedDesugaredType());
7168}
7169
7170template <typename T> const T *Type::getAsAdjusted() const {
7171 static_assert(!TypeIsArrayType<T>::value, "ArrayType cannot be used with getAsAdjusted!");
7172
7173 // If this is directly a T type, return it.
7174 if (const auto *Ty = dyn_cast<T>(this))
7175 return Ty;
7176
7177 // If the canonical form of this type isn't the right kind, reject it.
7178 if (!isa<T>(CanonicalType))
7179 return nullptr;
7180
7181 // Strip off type adjustments that do not modify the underlying nature of the
7182 // type.
7183 const Type *Ty = this;
7184 while (Ty) {
7185 if (const auto *A = dyn_cast<AttributedType>(Ty))
7186 Ty = A->getModifiedType().getTypePtr();
7187 else if (const auto *E = dyn_cast<ElaboratedType>(Ty))
7188 Ty = E->desugar().getTypePtr();
7189 else if (const auto *P = dyn_cast<ParenType>(Ty))
7190 Ty = P->desugar().getTypePtr();
7191 else if (const auto *A = dyn_cast<AdjustedType>(Ty))
7192 Ty = A->desugar().getTypePtr();
7193 else if (const auto *M = dyn_cast<MacroQualifiedType>(Ty))
7194 Ty = M->desugar().getTypePtr();
7195 else
7196 break;
7197 }
7198
7199 // Just because the canonical type is correct does not mean we can use cast<>,
7200 // since we may not have stripped off all the sugar down to the base type.
7201 return dyn_cast<T>(Ty);
7202}
7203
7204inline const ArrayType *Type::getAsArrayTypeUnsafe() const {
7205 // If this is directly an array type, return it.
7206 if (const auto *arr = dyn_cast<ArrayType>(this))
7207 return arr;
7208
7209 // If the canonical form of this type isn't the right kind, reject it.
7210 if (!isa<ArrayType>(CanonicalType))
7211 return nullptr;
7212
7213 // If this is a typedef for the type, strip the typedef off without
7214 // losing all typedef information.
7215 return cast<ArrayType>(getUnqualifiedDesugaredType());
7216}
7217
7218template <typename T> const T *Type::castAs() const {
7219 static_assert(!TypeIsArrayType<T>::value,
7220 "ArrayType cannot be used with castAs!");
7221
7222 if (const auto *ty = dyn_cast<T>(this)) return ty;
7223 assert(isa<T>(CanonicalType))((isa<T>(CanonicalType)) ? static_cast<void> (0) :
__assert_fail ("isa<T>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7223, __PRETTY_FUNCTION__))
;
7224 return cast<T>(getUnqualifiedDesugaredType());
7225}
7226
7227inline const ArrayType *Type::castAsArrayTypeUnsafe() const {
7228 assert(isa<ArrayType>(CanonicalType))((isa<ArrayType>(CanonicalType)) ? static_cast<void>
(0) : __assert_fail ("isa<ArrayType>(CanonicalType)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7228, __PRETTY_FUNCTION__))
;
7229 if (const auto *arr = dyn_cast<ArrayType>(this)) return arr;
7230 return cast<ArrayType>(getUnqualifiedDesugaredType());
7231}
7232
7233DecayedType::DecayedType(QualType OriginalType, QualType DecayedPtr,
7234 QualType CanonicalPtr)
7235 : AdjustedType(Decayed, OriginalType, DecayedPtr, CanonicalPtr) {
7236#ifndef NDEBUG
7237 QualType Adjusted = getAdjustedType();
7238 (void)AttributedType::stripOuterNullability(Adjusted);
7239 assert(isa<PointerType>(Adjusted))((isa<PointerType>(Adjusted)) ? static_cast<void>
(0) : __assert_fail ("isa<PointerType>(Adjusted)", "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include/clang/AST/Type.h"
, 7239, __PRETTY_FUNCTION__))
;
7240#endif
7241}
7242
7243QualType DecayedType::getPointeeType() const {
7244 QualType Decayed = getDecayedType();
7245 (void)AttributedType::stripOuterNullability(Decayed);
7246 return cast<PointerType>(Decayed)->getPointeeType();
7247}
7248
7249// Get the decimal string representation of a fixed point type, represented
7250// as a scaled integer.
7251// TODO: At some point, we should change the arguments to instead just accept an
7252// APFixedPoint instead of APSInt and scale.
7253void FixedPointValueToString(SmallVectorImpl<char> &Str, llvm::APSInt Val,
7254 unsigned Scale);
7255
7256} // namespace clang
7257
7258#endif // LLVM_CLANG_AST_TYPE_H