Bug Summary

File:clang/lib/Sema/SemaCast.cpp
Warning:line 1260, column 14
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 SemaCast.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/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/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.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-12~++20200926111128+c6c5629f2fb/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb=. -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 -o /tmp/scan-build-2020-09-26-161721-17566-1 -x c++ /build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp

/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp

1//===--- SemaCast.cpp - Semantic Analysis for Casts -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for cast expressions, including
10// 1) C-style casts like '(int) x'
11// 2) C++ functional casts like 'int(x)'
12// 3) C++ named casts like 'static_cast<int>(x)'
13//
14//===----------------------------------------------------------------------===//
15
16#include "clang/Sema/SemaInternal.h"
17#include "clang/AST/ASTContext.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/AST/RecordLayout.h"
22#include "clang/Basic/PartialDiagnostic.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "llvm/ADT/SmallVector.h"
27#include <set>
28using namespace clang;
29
30
31
32enum TryCastResult {
33 TC_NotApplicable, ///< The cast method is not applicable.
34 TC_Success, ///< The cast method is appropriate and successful.
35 TC_Extension, ///< The cast method is appropriate and accepted as a
36 ///< language extension.
37 TC_Failed ///< The cast method is appropriate, but failed. A
38 ///< diagnostic has been emitted.
39};
40
41static bool isValidCast(TryCastResult TCR) {
42 return TCR == TC_Success || TCR == TC_Extension;
43}
44
45enum CastType {
46 CT_Const, ///< const_cast
47 CT_Static, ///< static_cast
48 CT_Reinterpret, ///< reinterpret_cast
49 CT_Dynamic, ///< dynamic_cast
50 CT_CStyle, ///< (Type)expr
51 CT_Functional, ///< Type(expr)
52 CT_Addrspace ///< addrspace_cast
53};
54
55namespace {
56 struct CastOperation {
57 CastOperation(Sema &S, QualType destType, ExprResult src)
58 : Self(S), SrcExpr(src), DestType(destType),
59 ResultType(destType.getNonLValueExprType(S.Context)),
60 ValueKind(Expr::getValueKindForType(destType)),
61 Kind(CK_Dependent), IsARCUnbridgedCast(false) {
62
63 if (const BuiltinType *placeholder =
64 src.get()->getType()->getAsPlaceholderType()) {
65 PlaceholderKind = placeholder->getKind();
66 } else {
67 PlaceholderKind = (BuiltinType::Kind) 0;
68 }
69 }
70
71 Sema &Self;
72 ExprResult SrcExpr;
73 QualType DestType;
74 QualType ResultType;
75 ExprValueKind ValueKind;
76 CastKind Kind;
77 BuiltinType::Kind PlaceholderKind;
78 CXXCastPath BasePath;
79 bool IsARCUnbridgedCast;
80
81 SourceRange OpRange;
82 SourceRange DestRange;
83
84 // Top-level semantics-checking routines.
85 void CheckConstCast();
86 void CheckReinterpretCast();
87 void CheckStaticCast();
88 void CheckDynamicCast();
89 void CheckCXXCStyleCast(bool FunctionalCast, bool ListInitialization);
90 void CheckCStyleCast();
91 void CheckBuiltinBitCast();
92 void CheckAddrspaceCast();
93
94 void updatePartOfExplicitCastFlags(CastExpr *CE) {
95 // Walk down from the CE to the OrigSrcExpr, and mark all immediate
96 // ImplicitCastExpr's as being part of ExplicitCastExpr. The original CE
97 // (which is a ExplicitCastExpr), and the OrigSrcExpr are not touched.
98 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(CE->getSubExpr()); CE = ICE)
99 ICE->setIsPartOfExplicitCast(true);
100 }
101
102 /// Complete an apparently-successful cast operation that yields
103 /// the given expression.
104 ExprResult complete(CastExpr *castExpr) {
105 // If this is an unbridged cast, wrap the result in an implicit
106 // cast that yields the unbridged-cast placeholder type.
107 if (IsARCUnbridgedCast) {
108 castExpr = ImplicitCastExpr::Create(
109 Self.Context, Self.Context.ARCUnbridgedCastTy, CK_Dependent,
110 castExpr, nullptr, castExpr->getValueKind(),
111 Self.CurFPFeatureOverrides());
112 }
113 updatePartOfExplicitCastFlags(castExpr);
114 return castExpr;
115 }
116
117 // Internal convenience methods.
118
119 /// Try to handle the given placeholder expression kind. Return
120 /// true if the source expression has the appropriate placeholder
121 /// kind. A placeholder can only be claimed once.
122 bool claimPlaceholder(BuiltinType::Kind K) {
123 if (PlaceholderKind != K) return false;
124
125 PlaceholderKind = (BuiltinType::Kind) 0;
126 return true;
127 }
128
129 bool isPlaceholder() const {
130 return PlaceholderKind != 0;
131 }
132 bool isPlaceholder(BuiltinType::Kind K) const {
133 return PlaceholderKind == K;
134 }
135
136 // Language specific cast restrictions for address spaces.
137 void checkAddressSpaceCast(QualType SrcType, QualType DestType);
138
139 void checkCastAlign() {
140 Self.CheckCastAlign(SrcExpr.get(), DestType, OpRange);
141 }
142
143 void checkObjCConversion(Sema::CheckedConversionKind CCK) {
144 assert(Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())((Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()
) ? static_cast<void> (0) : __assert_fail ("Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 144, __PRETTY_FUNCTION__))
;
145
146 Expr *src = SrcExpr.get();
147 if (Self.CheckObjCConversion(OpRange, DestType, src, CCK) ==
148 Sema::ACR_unbridged)
149 IsARCUnbridgedCast = true;
150 SrcExpr = src;
151 }
152
153 /// Check for and handle non-overload placeholder expressions.
154 void checkNonOverloadPlaceholders() {
155 if (!isPlaceholder() || isPlaceholder(BuiltinType::Overload))
156 return;
157
158 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
159 if (SrcExpr.isInvalid())
160 return;
161 PlaceholderKind = (BuiltinType::Kind) 0;
162 }
163 };
164
165 void CheckNoDeref(Sema &S, const QualType FromType, const QualType ToType,
166 SourceLocation OpLoc) {
167 if (const auto *PtrType = dyn_cast<PointerType>(FromType)) {
168 if (PtrType->getPointeeType()->hasAttr(attr::NoDeref)) {
169 if (const auto *DestType = dyn_cast<PointerType>(ToType)) {
170 if (!DestType->getPointeeType()->hasAttr(attr::NoDeref)) {
171 S.Diag(OpLoc, diag::warn_noderef_to_dereferenceable_pointer);
172 }
173 }
174 }
175 }
176 }
177
178 struct CheckNoDerefRAII {
179 CheckNoDerefRAII(CastOperation &Op) : Op(Op) {}
180 ~CheckNoDerefRAII() {
181 if (!Op.SrcExpr.isInvalid())
182 CheckNoDeref(Op.Self, Op.SrcExpr.get()->getType(), Op.ResultType,
183 Op.OpRange.getBegin());
184 }
185
186 CastOperation &Op;
187 };
188}
189
190static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
191 QualType DestType);
192
193// The Try functions attempt a specific way of casting. If they succeed, they
194// return TC_Success. If their way of casting is not appropriate for the given
195// arguments, they return TC_NotApplicable and *may* set diag to a diagnostic
196// to emit if no other way succeeds. If their way of casting is appropriate but
197// fails, they return TC_Failed and *must* set diag; they can set it to 0 if
198// they emit a specialized diagnostic.
199// All diagnostics returned by these functions must expect the same three
200// arguments:
201// %0: Cast Type (a value from the CastType enumeration)
202// %1: Source Type
203// %2: Destination Type
204static TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
205 QualType DestType, bool CStyle,
206 CastKind &Kind,
207 CXXCastPath &BasePath,
208 unsigned &msg);
209static TryCastResult TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr,
210 QualType DestType, bool CStyle,
211 SourceRange OpRange,
212 unsigned &msg,
213 CastKind &Kind,
214 CXXCastPath &BasePath);
215static TryCastResult TryStaticPointerDowncast(Sema &Self, QualType SrcType,
216 QualType DestType, bool CStyle,
217 SourceRange OpRange,
218 unsigned &msg,
219 CastKind &Kind,
220 CXXCastPath &BasePath);
221static TryCastResult TryStaticDowncast(Sema &Self, CanQualType SrcType,
222 CanQualType DestType, bool CStyle,
223 SourceRange OpRange,
224 QualType OrigSrcType,
225 QualType OrigDestType, unsigned &msg,
226 CastKind &Kind,
227 CXXCastPath &BasePath);
228static TryCastResult TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr,
229 QualType SrcType,
230 QualType DestType,bool CStyle,
231 SourceRange OpRange,
232 unsigned &msg,
233 CastKind &Kind,
234 CXXCastPath &BasePath);
235
236static TryCastResult TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr,
237 QualType DestType,
238 Sema::CheckedConversionKind CCK,
239 SourceRange OpRange,
240 unsigned &msg, CastKind &Kind,
241 bool ListInitialization);
242static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
243 QualType DestType,
244 Sema::CheckedConversionKind CCK,
245 SourceRange OpRange,
246 unsigned &msg, CastKind &Kind,
247 CXXCastPath &BasePath,
248 bool ListInitialization);
249static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
250 QualType DestType, bool CStyle,
251 unsigned &msg);
252static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
253 QualType DestType, bool CStyle,
254 SourceRange OpRange, unsigned &msg,
255 CastKind &Kind);
256static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
257 QualType DestType, bool CStyle,
258 unsigned &msg, CastKind &Kind);
259
260/// ActOnCXXNamedCast - Parse
261/// {dynamic,static,reinterpret,const,addrspace}_cast's.
262ExprResult
263Sema::ActOnCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
264 SourceLocation LAngleBracketLoc, Declarator &D,
265 SourceLocation RAngleBracketLoc,
266 SourceLocation LParenLoc, Expr *E,
267 SourceLocation RParenLoc) {
268
269 assert(!D.isInvalidType())((!D.isInvalidType()) ? static_cast<void> (0) : __assert_fail
("!D.isInvalidType()", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 269, __PRETTY_FUNCTION__))
;
1
'?' condition is true
270
271 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, E->getType());
272 if (D.isInvalidType())
2
Taking false branch
273 return ExprError();
274
275 if (getLangOpts().CPlusPlus) {
3
Assuming field 'CPlusPlus' is 0
4
Taking false branch
276 // Check that there are no default arguments (C++ only).
277 CheckExtraCXXDefaultArguments(D);
278 }
279
280 return BuildCXXNamedCast(OpLoc, Kind, TInfo, E,
5
Calling 'Sema::BuildCXXNamedCast'
281 SourceRange(LAngleBracketLoc, RAngleBracketLoc),
282 SourceRange(LParenLoc, RParenLoc));
283}
284
285ExprResult
286Sema::BuildCXXNamedCast(SourceLocation OpLoc, tok::TokenKind Kind,
287 TypeSourceInfo *DestTInfo, Expr *E,
288 SourceRange AngleBrackets, SourceRange Parens) {
289 ExprResult Ex = E;
290 QualType DestType = DestTInfo->getType();
291
292 // If the type is dependent, we won't do the semantic analysis now.
293 bool TypeDependent =
294 DestType->isDependentType() || Ex.get()->isTypeDependent();
6
Assuming the condition is false
295
296 CastOperation Op(*this, DestType, E);
297 Op.OpRange = SourceRange(OpLoc, Parens.getEnd());
298 Op.DestRange = AngleBrackets;
299
300 switch (Kind) {
7
Control jumps to 'case kw_static_cast:' at line 356
301 default: llvm_unreachable("Unknown C++ cast!")::llvm::llvm_unreachable_internal("Unknown C++ cast!", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 301)
;
302
303 case tok::kw_addrspace_cast:
304 if (!TypeDependent) {
305 Op.CheckAddrspaceCast();
306 if (Op.SrcExpr.isInvalid())
307 return ExprError();
308 }
309 return Op.complete(CXXAddrspaceCastExpr::Create(
310 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
311 DestTInfo, OpLoc, Parens.getEnd(), AngleBrackets));
312
313 case tok::kw_const_cast:
314 if (!TypeDependent) {
315 Op.CheckConstCast();
316 if (Op.SrcExpr.isInvalid())
317 return ExprError();
318 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
319 }
320 return Op.complete(CXXConstCastExpr::Create(Context, Op.ResultType,
321 Op.ValueKind, Op.SrcExpr.get(), DestTInfo,
322 OpLoc, Parens.getEnd(),
323 AngleBrackets));
324
325 case tok::kw_dynamic_cast: {
326 // dynamic_cast is not supported in C++ for OpenCL.
327 if (getLangOpts().OpenCLCPlusPlus) {
328 return ExprError(Diag(OpLoc, diag::err_openclcxx_not_supported)
329 << "dynamic_cast");
330 }
331
332 if (!TypeDependent) {
333 Op.CheckDynamicCast();
334 if (Op.SrcExpr.isInvalid())
335 return ExprError();
336 }
337 return Op.complete(CXXDynamicCastExpr::Create(Context, Op.ResultType,
338 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
339 &Op.BasePath, DestTInfo,
340 OpLoc, Parens.getEnd(),
341 AngleBrackets));
342 }
343 case tok::kw_reinterpret_cast: {
344 if (!TypeDependent) {
345 Op.CheckReinterpretCast();
346 if (Op.SrcExpr.isInvalid())
347 return ExprError();
348 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
349 }
350 return Op.complete(CXXReinterpretCastExpr::Create(Context, Op.ResultType,
351 Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
352 nullptr, DestTInfo, OpLoc,
353 Parens.getEnd(),
354 AngleBrackets));
355 }
356 case tok::kw_static_cast: {
357 if (!TypeDependent) {
8
Assuming 'TypeDependent' is false
9
Taking true branch
358 Op.CheckStaticCast();
10
Calling 'CastOperation::CheckStaticCast'
359 if (Op.SrcExpr.isInvalid())
360 return ExprError();
361 DiscardMisalignedMemberAddress(DestType.getTypePtr(), E);
362 }
363
364 return Op.complete(CXXStaticCastExpr::Create(
365 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
366 &Op.BasePath, DestTInfo, CurFPFeatureOverrides(), OpLoc,
367 Parens.getEnd(), AngleBrackets));
368 }
369 }
370}
371
372ExprResult Sema::ActOnBuiltinBitCastExpr(SourceLocation KWLoc, Declarator &D,
373 ExprResult Operand,
374 SourceLocation RParenLoc) {
375 assert(!D.isInvalidType())((!D.isInvalidType()) ? static_cast<void> (0) : __assert_fail
("!D.isInvalidType()", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 375, __PRETTY_FUNCTION__))
;
376
377 TypeSourceInfo *TInfo = GetTypeForDeclaratorCast(D, Operand.get()->getType());
378 if (D.isInvalidType())
379 return ExprError();
380
381 return BuildBuiltinBitCastExpr(KWLoc, TInfo, Operand.get(), RParenLoc);
382}
383
384ExprResult Sema::BuildBuiltinBitCastExpr(SourceLocation KWLoc,
385 TypeSourceInfo *TSI, Expr *Operand,
386 SourceLocation RParenLoc) {
387 CastOperation Op(*this, TSI->getType(), Operand);
388 Op.OpRange = SourceRange(KWLoc, RParenLoc);
389 TypeLoc TL = TSI->getTypeLoc();
390 Op.DestRange = SourceRange(TL.getBeginLoc(), TL.getEndLoc());
391
392 if (!Operand->isTypeDependent() && !TSI->getType()->isDependentType()) {
393 Op.CheckBuiltinBitCast();
394 if (Op.SrcExpr.isInvalid())
395 return ExprError();
396 }
397
398 BuiltinBitCastExpr *BCE =
399 new (Context) BuiltinBitCastExpr(Op.ResultType, Op.ValueKind, Op.Kind,
400 Op.SrcExpr.get(), TSI, KWLoc, RParenLoc);
401 return Op.complete(BCE);
402}
403
404/// Try to diagnose a failed overloaded cast. Returns true if
405/// diagnostics were emitted.
406static bool tryDiagnoseOverloadedCast(Sema &S, CastType CT,
407 SourceRange range, Expr *src,
408 QualType destType,
409 bool listInitialization) {
410 switch (CT) {
411 // These cast kinds don't consider user-defined conversions.
412 case CT_Const:
413 case CT_Reinterpret:
414 case CT_Dynamic:
415 case CT_Addrspace:
416 return false;
417
418 // These do.
419 case CT_Static:
420 case CT_CStyle:
421 case CT_Functional:
422 break;
423 }
424
425 QualType srcType = src->getType();
426 if (!destType->isRecordType() && !srcType->isRecordType())
427 return false;
428
429 InitializedEntity entity = InitializedEntity::InitializeTemporary(destType);
430 InitializationKind initKind
431 = (CT == CT_CStyle)? InitializationKind::CreateCStyleCast(range.getBegin(),
432 range, listInitialization)
433 : (CT == CT_Functional)? InitializationKind::CreateFunctionalCast(range,
434 listInitialization)
435 : InitializationKind::CreateCast(/*type range?*/ range);
436 InitializationSequence sequence(S, entity, initKind, src);
437
438 assert(sequence.Failed() && "initialization succeeded on second try?")((sequence.Failed() && "initialization succeeded on second try?"
) ? static_cast<void> (0) : __assert_fail ("sequence.Failed() && \"initialization succeeded on second try?\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 438, __PRETTY_FUNCTION__))
;
439 switch (sequence.getFailureKind()) {
440 default: return false;
441
442 case InitializationSequence::FK_ConstructorOverloadFailed:
443 case InitializationSequence::FK_UserConversionOverloadFailed:
444 break;
445 }
446
447 OverloadCandidateSet &candidates = sequence.getFailedCandidateSet();
448
449 unsigned msg = 0;
450 OverloadCandidateDisplayKind howManyCandidates = OCD_AllCandidates;
451
452 switch (sequence.getFailedOverloadResult()) {
453 case OR_Success: llvm_unreachable("successful failed overload")::llvm::llvm_unreachable_internal("successful failed overload"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 453)
;
454 case OR_No_Viable_Function:
455 if (candidates.empty())
456 msg = diag::err_ovl_no_conversion_in_cast;
457 else
458 msg = diag::err_ovl_no_viable_conversion_in_cast;
459 howManyCandidates = OCD_AllCandidates;
460 break;
461
462 case OR_Ambiguous:
463 msg = diag::err_ovl_ambiguous_conversion_in_cast;
464 howManyCandidates = OCD_AmbiguousCandidates;
465 break;
466
467 case OR_Deleted:
468 msg = diag::err_ovl_deleted_conversion_in_cast;
469 howManyCandidates = OCD_ViableCandidates;
470 break;
471 }
472
473 candidates.NoteCandidates(
474 PartialDiagnosticAt(range.getBegin(),
475 S.PDiag(msg) << CT << srcType << destType << range
476 << src->getSourceRange()),
477 S, howManyCandidates, src);
478
479 return true;
480}
481
482/// Diagnose a failed cast.
483static void diagnoseBadCast(Sema &S, unsigned msg, CastType castType,
484 SourceRange opRange, Expr *src, QualType destType,
485 bool listInitialization) {
486 if (msg == diag::err_bad_cxx_cast_generic &&
487 tryDiagnoseOverloadedCast(S, castType, opRange, src, destType,
488 listInitialization))
489 return;
490
491 S.Diag(opRange.getBegin(), msg) << castType
492 << src->getType() << destType << opRange << src->getSourceRange();
493
494 // Detect if both types are (ptr to) class, and note any incompleteness.
495 int DifferentPtrness = 0;
496 QualType From = destType;
497 if (auto Ptr = From->getAs<PointerType>()) {
498 From = Ptr->getPointeeType();
499 DifferentPtrness++;
500 }
501 QualType To = src->getType();
502 if (auto Ptr = To->getAs<PointerType>()) {
503 To = Ptr->getPointeeType();
504 DifferentPtrness--;
505 }
506 if (!DifferentPtrness) {
507 auto RecFrom = From->getAs<RecordType>();
508 auto RecTo = To->getAs<RecordType>();
509 if (RecFrom && RecTo) {
510 auto DeclFrom = RecFrom->getAsCXXRecordDecl();
511 if (!DeclFrom->isCompleteDefinition())
512 S.Diag(DeclFrom->getLocation(), diag::note_type_incomplete) << DeclFrom;
513 auto DeclTo = RecTo->getAsCXXRecordDecl();
514 if (!DeclTo->isCompleteDefinition())
515 S.Diag(DeclTo->getLocation(), diag::note_type_incomplete) << DeclTo;
516 }
517 }
518}
519
520namespace {
521/// The kind of unwrapping we did when determining whether a conversion casts
522/// away constness.
523enum CastAwayConstnessKind {
524 /// The conversion does not cast away constness.
525 CACK_None = 0,
526 /// We unwrapped similar types.
527 CACK_Similar = 1,
528 /// We unwrapped dissimilar types with similar representations (eg, a pointer
529 /// versus an Objective-C object pointer).
530 CACK_SimilarKind = 2,
531 /// We unwrapped representationally-unrelated types, such as a pointer versus
532 /// a pointer-to-member.
533 CACK_Incoherent = 3,
534};
535}
536
537/// Unwrap one level of types for CastsAwayConstness.
538///
539/// Like Sema::UnwrapSimilarTypes, this removes one level of indirection from
540/// both types, provided that they're both pointer-like or array-like. Unlike
541/// the Sema function, doesn't care if the unwrapped pieces are related.
542///
543/// This function may remove additional levels as necessary for correctness:
544/// the resulting T1 is unwrapped sufficiently that it is never an array type,
545/// so that its qualifiers can be directly compared to those of T2 (which will
546/// have the combined set of qualifiers from all indermediate levels of T2),
547/// as (effectively) required by [expr.const.cast]p7 replacing T1's qualifiers
548/// with those from T2.
549static CastAwayConstnessKind
550unwrapCastAwayConstnessLevel(ASTContext &Context, QualType &T1, QualType &T2) {
551 enum { None, Ptr, MemPtr, BlockPtr, Array };
552 auto Classify = [](QualType T) {
553 if (T->isAnyPointerType()) return Ptr;
554 if (T->isMemberPointerType()) return MemPtr;
555 if (T->isBlockPointerType()) return BlockPtr;
556 // We somewhat-arbitrarily don't look through VLA types here. This is at
557 // least consistent with the behavior of UnwrapSimilarTypes.
558 if (T->isConstantArrayType() || T->isIncompleteArrayType()) return Array;
559 return None;
560 };
561
562 auto Unwrap = [&](QualType T) {
563 if (auto *AT = Context.getAsArrayType(T))
564 return AT->getElementType();
565 return T->getPointeeType();
566 };
567
568 CastAwayConstnessKind Kind;
569
570 if (T2->isReferenceType()) {
571 // Special case: if the destination type is a reference type, unwrap it as
572 // the first level. (The source will have been an lvalue expression in this
573 // case, so there is no corresponding "reference to" in T1 to remove.) This
574 // simulates removing a "pointer to" from both sides.
575 T2 = T2->getPointeeType();
576 Kind = CastAwayConstnessKind::CACK_Similar;
577 } else if (Context.UnwrapSimilarTypes(T1, T2)) {
578 Kind = CastAwayConstnessKind::CACK_Similar;
579 } else {
580 // Try unwrapping mismatching levels.
581 int T1Class = Classify(T1);
582 if (T1Class == None)
583 return CastAwayConstnessKind::CACK_None;
584
585 int T2Class = Classify(T2);
586 if (T2Class == None)
587 return CastAwayConstnessKind::CACK_None;
588
589 T1 = Unwrap(T1);
590 T2 = Unwrap(T2);
591 Kind = T1Class == T2Class ? CastAwayConstnessKind::CACK_SimilarKind
592 : CastAwayConstnessKind::CACK_Incoherent;
593 }
594
595 // We've unwrapped at least one level. If the resulting T1 is a (possibly
596 // multidimensional) array type, any qualifier on any matching layer of
597 // T2 is considered to correspond to T1. Decompose down to the element
598 // type of T1 so that we can compare properly.
599 while (true) {
600 Context.UnwrapSimilarArrayTypes(T1, T2);
601
602 if (Classify(T1) != Array)
603 break;
604
605 auto T2Class = Classify(T2);
606 if (T2Class == None)
607 break;
608
609 if (T2Class != Array)
610 Kind = CastAwayConstnessKind::CACK_Incoherent;
611 else if (Kind != CastAwayConstnessKind::CACK_Incoherent)
612 Kind = CastAwayConstnessKind::CACK_SimilarKind;
613
614 T1 = Unwrap(T1);
615 T2 = Unwrap(T2).withCVRQualifiers(T2.getCVRQualifiers());
616 }
617
618 return Kind;
619}
620
621/// Check if the pointer conversion from SrcType to DestType casts away
622/// constness as defined in C++ [expr.const.cast]. This is used by the cast
623/// checkers. Both arguments must denote pointer (possibly to member) types.
624///
625/// \param CheckCVR Whether to check for const/volatile/restrict qualifiers.
626/// \param CheckObjCLifetime Whether to check Objective-C lifetime qualifiers.
627static CastAwayConstnessKind
628CastsAwayConstness(Sema &Self, QualType SrcType, QualType DestType,
629 bool CheckCVR, bool CheckObjCLifetime,
630 QualType *TheOffendingSrcType = nullptr,
631 QualType *TheOffendingDestType = nullptr,
632 Qualifiers *CastAwayQualifiers = nullptr) {
633 // If the only checking we care about is for Objective-C lifetime qualifiers,
634 // and we're not in ObjC mode, there's nothing to check.
635 if (!CheckCVR && CheckObjCLifetime && !Self.Context.getLangOpts().ObjC)
636 return CastAwayConstnessKind::CACK_None;
637
638 if (!DestType->isReferenceType()) {
639 assert((SrcType->isAnyPointerType() || SrcType->isMemberPointerType() ||(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType
() || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 641, __PRETTY_FUNCTION__))
640 SrcType->isBlockPointerType()) &&(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType
() || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 641, __PRETTY_FUNCTION__))
641 "Source type is not pointer or pointer to member.")(((SrcType->isAnyPointerType() || SrcType->isMemberPointerType
() || SrcType->isBlockPointerType()) && "Source type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(SrcType->isAnyPointerType() || SrcType->isMemberPointerType() || SrcType->isBlockPointerType()) && \"Source type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 641, __PRETTY_FUNCTION__))
;
642 assert((DestType->isAnyPointerType() || DestType->isMemberPointerType() ||(((DestType->isAnyPointerType() || DestType->isMemberPointerType
() || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 644, __PRETTY_FUNCTION__))
643 DestType->isBlockPointerType()) &&(((DestType->isAnyPointerType() || DestType->isMemberPointerType
() || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 644, __PRETTY_FUNCTION__))
644 "Destination type is not pointer or pointer to member.")(((DestType->isAnyPointerType() || DestType->isMemberPointerType
() || DestType->isBlockPointerType()) && "Destination type is not pointer or pointer to member."
) ? static_cast<void> (0) : __assert_fail ("(DestType->isAnyPointerType() || DestType->isMemberPointerType() || DestType->isBlockPointerType()) && \"Destination type is not pointer or pointer to member.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 644, __PRETTY_FUNCTION__))
;
645 }
646
647 QualType UnwrappedSrcType = Self.Context.getCanonicalType(SrcType),
648 UnwrappedDestType = Self.Context.getCanonicalType(DestType);
649
650 // Find the qualifiers. We only care about cvr-qualifiers for the
651 // purpose of this check, because other qualifiers (address spaces,
652 // Objective-C GC, etc.) are part of the type's identity.
653 QualType PrevUnwrappedSrcType = UnwrappedSrcType;
654 QualType PrevUnwrappedDestType = UnwrappedDestType;
655 auto WorstKind = CastAwayConstnessKind::CACK_Similar;
656 bool AllConstSoFar = true;
657 while (auto Kind = unwrapCastAwayConstnessLevel(
658 Self.Context, UnwrappedSrcType, UnwrappedDestType)) {
659 // Track the worst kind of unwrap we needed to do before we found a
660 // problem.
661 if (Kind > WorstKind)
662 WorstKind = Kind;
663
664 // Determine the relevant qualifiers at this level.
665 Qualifiers SrcQuals, DestQuals;
666 Self.Context.getUnqualifiedArrayType(UnwrappedSrcType, SrcQuals);
667 Self.Context.getUnqualifiedArrayType(UnwrappedDestType, DestQuals);
668
669 // We do not meaningfully track object const-ness of Objective-C object
670 // types. Remove const from the source type if either the source or
671 // the destination is an Objective-C object type.
672 if (UnwrappedSrcType->isObjCObjectType() ||
673 UnwrappedDestType->isObjCObjectType())
674 SrcQuals.removeConst();
675
676 if (CheckCVR) {
677 Qualifiers SrcCvrQuals =
678 Qualifiers::fromCVRMask(SrcQuals.getCVRQualifiers());
679 Qualifiers DestCvrQuals =
680 Qualifiers::fromCVRMask(DestQuals.getCVRQualifiers());
681
682 if (SrcCvrQuals != DestCvrQuals) {
683 if (CastAwayQualifiers)
684 *CastAwayQualifiers = SrcCvrQuals - DestCvrQuals;
685
686 // If we removed a cvr-qualifier, this is casting away 'constness'.
687 if (!DestCvrQuals.compatiblyIncludes(SrcCvrQuals)) {
688 if (TheOffendingSrcType)
689 *TheOffendingSrcType = PrevUnwrappedSrcType;
690 if (TheOffendingDestType)
691 *TheOffendingDestType = PrevUnwrappedDestType;
692 return WorstKind;
693 }
694
695 // If any prior level was not 'const', this is also casting away
696 // 'constness'. We noted the outermost type missing a 'const' already.
697 if (!AllConstSoFar)
698 return WorstKind;
699 }
700 }
701
702 if (CheckObjCLifetime &&
703 !DestQuals.compatiblyIncludesObjCLifetime(SrcQuals))
704 return WorstKind;
705
706 // If we found our first non-const-qualified type, this may be the place
707 // where things start to go wrong.
708 if (AllConstSoFar && !DestQuals.hasConst()) {
709 AllConstSoFar = false;
710 if (TheOffendingSrcType)
711 *TheOffendingSrcType = PrevUnwrappedSrcType;
712 if (TheOffendingDestType)
713 *TheOffendingDestType = PrevUnwrappedDestType;
714 }
715
716 PrevUnwrappedSrcType = UnwrappedSrcType;
717 PrevUnwrappedDestType = UnwrappedDestType;
718 }
719
720 return CastAwayConstnessKind::CACK_None;
721}
722
723static TryCastResult getCastAwayConstnessCastKind(CastAwayConstnessKind CACK,
724 unsigned &DiagID) {
725 switch (CACK) {
726 case CastAwayConstnessKind::CACK_None:
727 llvm_unreachable("did not cast away constness")::llvm::llvm_unreachable_internal("did not cast away constness"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 727)
;
728
729 case CastAwayConstnessKind::CACK_Similar:
730 // FIXME: Accept these as an extension too?
731 case CastAwayConstnessKind::CACK_SimilarKind:
732 DiagID = diag::err_bad_cxx_cast_qualifiers_away;
733 return TC_Failed;
734
735 case CastAwayConstnessKind::CACK_Incoherent:
736 DiagID = diag::ext_bad_cxx_cast_qualifiers_away_incoherent;
737 return TC_Extension;
738 }
739
740 llvm_unreachable("unexpected cast away constness kind")::llvm::llvm_unreachable_internal("unexpected cast away constness kind"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 740)
;
741}
742
743/// CheckDynamicCast - Check that a dynamic_cast\<DestType\>(SrcExpr) is valid.
744/// Refer to C++ 5.2.7 for details. Dynamic casts are used mostly for runtime-
745/// checked downcasts in class hierarchies.
746void CastOperation::CheckDynamicCast() {
747 CheckNoDerefRAII NoderefCheck(*this);
748
749 if (ValueKind == VK_RValue)
750 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
751 else if (isPlaceholder())
752 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
753 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
754 return;
755
756 QualType OrigSrcType = SrcExpr.get()->getType();
757 QualType DestType = Self.Context.getCanonicalType(this->DestType);
758
759 // C++ 5.2.7p1: T shall be a pointer or reference to a complete class type,
760 // or "pointer to cv void".
761
762 QualType DestPointee;
763 const PointerType *DestPointer = DestType->getAs<PointerType>();
764 const ReferenceType *DestReference = nullptr;
765 if (DestPointer) {
766 DestPointee = DestPointer->getPointeeType();
767 } else if ((DestReference = DestType->getAs<ReferenceType>())) {
768 DestPointee = DestReference->getPointeeType();
769 } else {
770 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ref_or_ptr)
771 << this->DestType << DestRange;
772 SrcExpr = ExprError();
773 return;
774 }
775
776 const RecordType *DestRecord = DestPointee->getAs<RecordType>();
777 if (DestPointee->isVoidType()) {
778 assert(DestPointer && "Reference to void is not possible")((DestPointer && "Reference to void is not possible")
? static_cast<void> (0) : __assert_fail ("DestPointer && \"Reference to void is not possible\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 778, __PRETTY_FUNCTION__))
;
779 } else if (DestRecord) {
780 if (Self.RequireCompleteType(OpRange.getBegin(), DestPointee,
781 diag::err_bad_cast_incomplete,
782 DestRange)) {
783 SrcExpr = ExprError();
784 return;
785 }
786 } else {
787 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
788 << DestPointee.getUnqualifiedType() << DestRange;
789 SrcExpr = ExprError();
790 return;
791 }
792
793 // C++0x 5.2.7p2: If T is a pointer type, v shall be an rvalue of a pointer to
794 // complete class type, [...]. If T is an lvalue reference type, v shall be
795 // an lvalue of a complete class type, [...]. If T is an rvalue reference
796 // type, v shall be an expression having a complete class type, [...]
797 QualType SrcType = Self.Context.getCanonicalType(OrigSrcType);
798 QualType SrcPointee;
799 if (DestPointer) {
800 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
801 SrcPointee = SrcPointer->getPointeeType();
802 } else {
803 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_ptr)
804 << OrigSrcType << this->DestType << SrcExpr.get()->getSourceRange();
805 SrcExpr = ExprError();
806 return;
807 }
808 } else if (DestReference->isLValueReferenceType()) {
809 if (!SrcExpr.get()->isLValue()) {
810 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_rvalue)
811 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
812 }
813 SrcPointee = SrcType;
814 } else {
815 // If we're dynamic_casting from a prvalue to an rvalue reference, we need
816 // to materialize the prvalue before we bind the reference to it.
817 if (SrcExpr.get()->isRValue())
818 SrcExpr = Self.CreateMaterializeTemporaryExpr(
819 SrcType, SrcExpr.get(), /*IsLValueReference*/ false);
820 SrcPointee = SrcType;
821 }
822
823 const RecordType *SrcRecord = SrcPointee->getAs<RecordType>();
824 if (SrcRecord) {
825 if (Self.RequireCompleteType(OpRange.getBegin(), SrcPointee,
826 diag::err_bad_cast_incomplete,
827 SrcExpr.get())) {
828 SrcExpr = ExprError();
829 return;
830 }
831 } else {
832 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_class)
833 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
834 SrcExpr = ExprError();
835 return;
836 }
837
838 assert((DestPointer || DestReference) &&(((DestPointer || DestReference) && "Bad destination non-ptr/ref slipped through."
) ? static_cast<void> (0) : __assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 839, __PRETTY_FUNCTION__))
839 "Bad destination non-ptr/ref slipped through.")(((DestPointer || DestReference) && "Bad destination non-ptr/ref slipped through."
) ? static_cast<void> (0) : __assert_fail ("(DestPointer || DestReference) && \"Bad destination non-ptr/ref slipped through.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 839, __PRETTY_FUNCTION__))
;
840 assert((DestRecord || DestPointee->isVoidType()) &&(((DestRecord || DestPointee->isVoidType()) && "Bad destination pointee slipped through."
) ? static_cast<void> (0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 841, __PRETTY_FUNCTION__))
841 "Bad destination pointee slipped through.")(((DestRecord || DestPointee->isVoidType()) && "Bad destination pointee slipped through."
) ? static_cast<void> (0) : __assert_fail ("(DestRecord || DestPointee->isVoidType()) && \"Bad destination pointee slipped through.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 841, __PRETTY_FUNCTION__))
;
842 assert(SrcRecord && "Bad source pointee slipped through.")((SrcRecord && "Bad source pointee slipped through.")
? static_cast<void> (0) : __assert_fail ("SrcRecord && \"Bad source pointee slipped through.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 842, __PRETTY_FUNCTION__))
;
843
844 // C++ 5.2.7p1: The dynamic_cast operator shall not cast away constness.
845 if (!DestPointee.isAtLeastAsQualifiedAs(SrcPointee)) {
846 Self.Diag(OpRange.getBegin(), diag::err_bad_cxx_cast_qualifiers_away)
847 << CT_Dynamic << OrigSrcType << this->DestType << OpRange;
848 SrcExpr = ExprError();
849 return;
850 }
851
852 // C++ 5.2.7p3: If the type of v is the same as the required result type,
853 // [except for cv].
854 if (DestRecord == SrcRecord) {
855 Kind = CK_NoOp;
856 return;
857 }
858
859 // C++ 5.2.7p5
860 // Upcasts are resolved statically.
861 if (DestRecord &&
862 Self.IsDerivedFrom(OpRange.getBegin(), SrcPointee, DestPointee)) {
863 if (Self.CheckDerivedToBaseConversion(SrcPointee, DestPointee,
864 OpRange.getBegin(), OpRange,
865 &BasePath)) {
866 SrcExpr = ExprError();
867 return;
868 }
869
870 Kind = CK_DerivedToBase;
871 return;
872 }
873
874 // C++ 5.2.7p6: Otherwise, v shall be [polymorphic].
875 const RecordDecl *SrcDecl = SrcRecord->getDecl()->getDefinition();
876 assert(SrcDecl && "Definition missing")((SrcDecl && "Definition missing") ? static_cast<void
> (0) : __assert_fail ("SrcDecl && \"Definition missing\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 876, __PRETTY_FUNCTION__))
;
877 if (!cast<CXXRecordDecl>(SrcDecl)->isPolymorphic()) {
878 Self.Diag(OpRange.getBegin(), diag::err_bad_dynamic_cast_not_polymorphic)
879 << SrcPointee.getUnqualifiedType() << SrcExpr.get()->getSourceRange();
880 SrcExpr = ExprError();
881 }
882
883 // dynamic_cast is not available with -fno-rtti.
884 // As an exception, dynamic_cast to void* is available because it doesn't
885 // use RTTI.
886 if (!Self.getLangOpts().RTTI && !DestPointee->isVoidType()) {
887 Self.Diag(OpRange.getBegin(), diag::err_no_dynamic_cast_with_fno_rtti);
888 SrcExpr = ExprError();
889 return;
890 }
891
892 // Warns when dynamic_cast is used with RTTI data disabled.
893 if (!Self.getLangOpts().RTTIData) {
894 bool MicrosoftABI =
895 Self.getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
896 bool isClangCL = Self.getDiagnostics().getDiagnosticOptions().getFormat() ==
897 DiagnosticOptions::MSVC;
898 if (MicrosoftABI || !DestPointee->isVoidType())
899 Self.Diag(OpRange.getBegin(),
900 diag::warn_no_dynamic_cast_with_rtti_disabled)
901 << isClangCL;
902 }
903
904 // Done. Everything else is run-time checks.
905 Kind = CK_Dynamic;
906}
907
908/// CheckConstCast - Check that a const_cast\<DestType\>(SrcExpr) is valid.
909/// Refer to C++ 5.2.11 for details. const_cast is typically used in code
910/// like this:
911/// const char *str = "literal";
912/// legacy_function(const_cast\<char*\>(str));
913void CastOperation::CheckConstCast() {
914 CheckNoDerefRAII NoderefCheck(*this);
915
916 if (ValueKind == VK_RValue)
917 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
918 else if (isPlaceholder())
919 SrcExpr = Self.CheckPlaceholderExpr(SrcExpr.get());
920 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
921 return;
922
923 unsigned msg = diag::err_bad_cxx_cast_generic;
924 auto TCR = TryConstCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg);
925 if (TCR != TC_Success && msg != 0) {
926 Self.Diag(OpRange.getBegin(), msg) << CT_Const
927 << SrcExpr.get()->getType() << DestType << OpRange;
928 }
929 if (!isValidCast(TCR))
930 SrcExpr = ExprError();
931}
932
933void CastOperation::CheckAddrspaceCast() {
934 unsigned msg = diag::err_bad_cxx_cast_generic;
935 auto TCR =
936 TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ false, msg, Kind);
937 if (TCR != TC_Success && msg != 0) {
938 Self.Diag(OpRange.getBegin(), msg)
939 << CT_Addrspace << SrcExpr.get()->getType() << DestType << OpRange;
940 }
941 if (!isValidCast(TCR))
942 SrcExpr = ExprError();
943}
944
945/// Check that a reinterpret_cast\<DestType\>(SrcExpr) is not used as upcast
946/// or downcast between respective pointers or references.
947static void DiagnoseReinterpretUpDownCast(Sema &Self, const Expr *SrcExpr,
948 QualType DestType,
949 SourceRange OpRange) {
950 QualType SrcType = SrcExpr->getType();
951 // When casting from pointer or reference, get pointee type; use original
952 // type otherwise.
953 const CXXRecordDecl *SrcPointeeRD = SrcType->getPointeeCXXRecordDecl();
954 const CXXRecordDecl *SrcRD =
955 SrcPointeeRD ? SrcPointeeRD : SrcType->getAsCXXRecordDecl();
956
957 // Examining subobjects for records is only possible if the complete and
958 // valid definition is available. Also, template instantiation is not
959 // allowed here.
960 if (!SrcRD || !SrcRD->isCompleteDefinition() || SrcRD->isInvalidDecl())
961 return;
962
963 const CXXRecordDecl *DestRD = DestType->getPointeeCXXRecordDecl();
964
965 if (!DestRD || !DestRD->isCompleteDefinition() || DestRD->isInvalidDecl())
966 return;
967
968 enum {
969 ReinterpretUpcast,
970 ReinterpretDowncast
971 } ReinterpretKind;
972
973 CXXBasePaths BasePaths;
974
975 if (SrcRD->isDerivedFrom(DestRD, BasePaths))
976 ReinterpretKind = ReinterpretUpcast;
977 else if (DestRD->isDerivedFrom(SrcRD, BasePaths))
978 ReinterpretKind = ReinterpretDowncast;
979 else
980 return;
981
982 bool VirtualBase = true;
983 bool NonZeroOffset = false;
984 for (CXXBasePaths::const_paths_iterator I = BasePaths.begin(),
985 E = BasePaths.end();
986 I != E; ++I) {
987 const CXXBasePath &Path = *I;
988 CharUnits Offset = CharUnits::Zero();
989 bool IsVirtual = false;
990 for (CXXBasePath::const_iterator IElem = Path.begin(), EElem = Path.end();
991 IElem != EElem; ++IElem) {
992 IsVirtual = IElem->Base->isVirtual();
993 if (IsVirtual)
994 break;
995 const CXXRecordDecl *BaseRD = IElem->Base->getType()->getAsCXXRecordDecl();
996 assert(BaseRD && "Base type should be a valid unqualified class type")((BaseRD && "Base type should be a valid unqualified class type"
) ? static_cast<void> (0) : __assert_fail ("BaseRD && \"Base type should be a valid unqualified class type\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 996, __PRETTY_FUNCTION__))
;
997 // Don't check if any base has invalid declaration or has no definition
998 // since it has no layout info.
999 const CXXRecordDecl *Class = IElem->Class,
1000 *ClassDefinition = Class->getDefinition();
1001 if (Class->isInvalidDecl() || !ClassDefinition ||
1002 !ClassDefinition->isCompleteDefinition())
1003 return;
1004
1005 const ASTRecordLayout &DerivedLayout =
1006 Self.Context.getASTRecordLayout(Class);
1007 Offset += DerivedLayout.getBaseClassOffset(BaseRD);
1008 }
1009 if (!IsVirtual) {
1010 // Don't warn if any path is a non-virtually derived base at offset zero.
1011 if (Offset.isZero())
1012 return;
1013 // Offset makes sense only for non-virtual bases.
1014 else
1015 NonZeroOffset = true;
1016 }
1017 VirtualBase = VirtualBase && IsVirtual;
1018 }
1019
1020 (void) NonZeroOffset; // Silence set but not used warning.
1021 assert((VirtualBase || NonZeroOffset) &&(((VirtualBase || NonZeroOffset) && "Should have returned if has non-virtual base with zero offset"
) ? static_cast<void> (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 1022, __PRETTY_FUNCTION__))
1022 "Should have returned if has non-virtual base with zero offset")(((VirtualBase || NonZeroOffset) && "Should have returned if has non-virtual base with zero offset"
) ? static_cast<void> (0) : __assert_fail ("(VirtualBase || NonZeroOffset) && \"Should have returned if has non-virtual base with zero offset\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 1022, __PRETTY_FUNCTION__))
;
1023
1024 QualType BaseType =
1025 ReinterpretKind == ReinterpretUpcast? DestType : SrcType;
1026 QualType DerivedType =
1027 ReinterpretKind == ReinterpretUpcast? SrcType : DestType;
1028
1029 SourceLocation BeginLoc = OpRange.getBegin();
1030 Self.Diag(BeginLoc, diag::warn_reinterpret_different_from_static)
1031 << DerivedType << BaseType << !VirtualBase << int(ReinterpretKind)
1032 << OpRange;
1033 Self.Diag(BeginLoc, diag::note_reinterpret_updowncast_use_static)
1034 << int(ReinterpretKind)
1035 << FixItHint::CreateReplacement(BeginLoc, "static_cast");
1036}
1037
1038/// CheckReinterpretCast - Check that a reinterpret_cast\<DestType\>(SrcExpr) is
1039/// valid.
1040/// Refer to C++ 5.2.10 for details. reinterpret_cast is typically used in code
1041/// like this:
1042/// char *bytes = reinterpret_cast\<char*\>(int_ptr);
1043void CastOperation::CheckReinterpretCast() {
1044 if (ValueKind == VK_RValue && !isPlaceholder(BuiltinType::Overload))
1045 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1046 else
1047 checkNonOverloadPlaceholders();
1048 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1049 return;
1050
1051 unsigned msg = diag::err_bad_cxx_cast_generic;
1052 TryCastResult tcr =
1053 TryReinterpretCast(Self, SrcExpr, DestType,
1054 /*CStyle*/false, OpRange, msg, Kind);
1055 if (tcr != TC_Success && msg != 0) {
1056 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1057 return;
1058 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1059 //FIXME: &f<int>; is overloaded and resolvable
1060 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_overload)
1061 << OverloadExpr::find(SrcExpr.get()).Expression->getName()
1062 << DestType << OpRange;
1063 Self.NoteAllOverloadCandidates(SrcExpr.get());
1064
1065 } else {
1066 diagnoseBadCast(Self, msg, CT_Reinterpret, OpRange, SrcExpr.get(),
1067 DestType, /*listInitialization=*/false);
1068 }
1069 }
1070
1071 if (isValidCast(tcr)) {
1072 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1073 checkObjCConversion(Sema::CCK_OtherCast);
1074 DiagnoseReinterpretUpDownCast(Self, SrcExpr.get(), DestType, OpRange);
1075 } else {
1076 SrcExpr = ExprError();
1077 }
1078}
1079
1080
1081/// CheckStaticCast - Check that a static_cast\<DestType\>(SrcExpr) is valid.
1082/// Refer to C++ 5.2.9 for details. Static casts are mostly used for making
1083/// implicit conversions explicit and getting rid of data loss warnings.
1084void CastOperation::CheckStaticCast() {
1085 CheckNoDerefRAII NoderefCheck(*this);
1086
1087 if (isPlaceholder()) {
11
Taking false branch
1088 checkNonOverloadPlaceholders();
1089 if (SrcExpr.isInvalid())
1090 return;
1091 }
1092
1093 // This test is outside everything else because it's the only case where
1094 // a non-lvalue-reference target type does not lead to decay.
1095 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1096 if (DestType->isVoidType()) {
12
Taking false branch
1097 Kind = CK_ToVoid;
1098
1099 if (claimPlaceholder(BuiltinType::Overload)) {
1100 Self.ResolveAndFixSingleFunctionTemplateSpecialization(SrcExpr,
1101 false, // Decay Function to ptr
1102 true, // Complain
1103 OpRange, DestType, diag::err_bad_static_cast_overload);
1104 if (SrcExpr.isInvalid())
1105 return;
1106 }
1107
1108 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
1109 return;
1110 }
1111
1112 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
13
Assuming field 'ValueKind' is not equal to VK_RValue
1113 !isPlaceholder(BuiltinType::Overload)) {
1114 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
1115 if (SrcExpr.isInvalid()) // if conversion failed, don't report another error
1116 return;
1117 }
1118
1119 unsigned msg = diag::err_bad_cxx_cast_generic;
1120 TryCastResult tcr
1121 = TryStaticCast(Self, SrcExpr, DestType, Sema::CCK_OtherCast, OpRange, msg,
14
Calling 'TryStaticCast'
1122 Kind, BasePath, /*ListInitialization=*/false);
1123 if (tcr != TC_Success && msg != 0) {
1124 if (SrcExpr.isInvalid())
1125 return;
1126 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1127 OverloadExpr* oe = OverloadExpr::find(SrcExpr.get()).Expression;
1128 Self.Diag(OpRange.getBegin(), diag::err_bad_static_cast_overload)
1129 << oe->getName() << DestType << OpRange
1130 << oe->getQualifierLoc().getSourceRange();
1131 Self.NoteAllOverloadCandidates(SrcExpr.get());
1132 } else {
1133 diagnoseBadCast(Self, msg, CT_Static, OpRange, SrcExpr.get(), DestType,
1134 /*listInitialization=*/false);
1135 }
1136 }
1137
1138 if (isValidCast(tcr)) {
1139 if (Kind == CK_BitCast)
1140 checkCastAlign();
1141 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers())
1142 checkObjCConversion(Sema::CCK_OtherCast);
1143 } else {
1144 SrcExpr = ExprError();
1145 }
1146}
1147
1148static bool IsAddressSpaceConversion(QualType SrcType, QualType DestType) {
1149 auto *SrcPtrType = SrcType->getAs<PointerType>();
1150 if (!SrcPtrType)
1151 return false;
1152 auto *DestPtrType = DestType->getAs<PointerType>();
1153 if (!DestPtrType)
1154 return false;
1155 return SrcPtrType->getPointeeType().getAddressSpace() !=
1156 DestPtrType->getPointeeType().getAddressSpace();
1157}
1158
1159/// TryStaticCast - Check if a static cast can be performed, and do so if
1160/// possible. If @p CStyle, ignore access restrictions on hierarchy casting
1161/// and casting away constness.
1162static TryCastResult TryStaticCast(Sema &Self, ExprResult &SrcExpr,
1163 QualType DestType,
1164 Sema::CheckedConversionKind CCK,
1165 SourceRange OpRange, unsigned &msg,
1166 CastKind &Kind, CXXCastPath &BasePath,
1167 bool ListInitialization) {
1168 // Determine whether we have the semantics of a C-style cast.
1169 bool CStyle
1170 = (CCK
14.1
'CCK' is not equal to CCK_CStyleCast
14.1
'CCK' is not equal to CCK_CStyleCast
== Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1171
1172 // The order the tests is not entirely arbitrary. There is one conversion
1173 // that can be handled in two different ways. Given:
1174 // struct A {};
1175 // struct B : public A {
1176 // B(); B(const A&);
1177 // };
1178 // const A &a = B();
1179 // the cast static_cast<const B&>(a) could be seen as either a static
1180 // reference downcast, or an explicit invocation of the user-defined
1181 // conversion using B's conversion constructor.
1182 // DR 427 specifies that the downcast is to be applied here.
1183
1184 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
1185 // Done outside this function.
1186
1187 TryCastResult tcr;
1188
1189 // C++ 5.2.9p5, reference downcast.
1190 // See the function for details.
1191 // DR 427 specifies that this is to be applied before paragraph 2.
1192 tcr = TryStaticReferenceDowncast(Self, SrcExpr.get(), DestType, CStyle,
1193 OpRange, msg, Kind, BasePath);
1194 if (tcr
14.2
'tcr' is equal to TC_NotApplicable
14.2
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
15
Taking false branch
1195 return tcr;
1196
1197 // C++11 [expr.static.cast]p3:
1198 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to cv2
1199 // T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1200 tcr = TryLValueToRValueCast(Self, SrcExpr.get(), DestType, CStyle, Kind,
1201 BasePath, msg);
1202 if (tcr
15.1
'tcr' is equal to TC_NotApplicable
15.1
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
16
Taking false branch
1203 return tcr;
1204
1205 // C++ 5.2.9p2: An expression e can be explicitly converted to a type T
1206 // [...] if the declaration "T t(e);" is well-formed, [...].
1207 tcr = TryStaticImplicitCast(Self, SrcExpr, DestType, CCK, OpRange, msg,
1208 Kind, ListInitialization);
1209 if (SrcExpr.isInvalid())
17
Assuming the condition is false
18
Taking false branch
1210 return TC_Failed;
1211 if (tcr
18.1
'tcr' is equal to TC_NotApplicable
18.1
'tcr' is equal to TC_NotApplicable
!= TC_NotApplicable)
19
Taking false branch
1212 return tcr;
1213
1214 // C++ 5.2.9p6: May apply the reverse of any standard conversion, except
1215 // lvalue-to-rvalue, array-to-pointer, function-to-pointer, and boolean
1216 // conversions, subject to further restrictions.
1217 // Also, C++ 5.2.9p1 forbids casting away constness, which makes reversal
1218 // of qualification conversions impossible.
1219 // In the CStyle case, the earlier attempt to const_cast should have taken
1220 // care of reverse qualification conversions.
1221
1222 QualType SrcType = Self.Context.getCanonicalType(SrcExpr.get()->getType());
1223
1224 // C++0x 5.2.9p9: A value of a scoped enumeration type can be explicitly
1225 // converted to an integral type. [...] A value of a scoped enumeration type
1226 // can also be explicitly converted to a floating-point type [...].
1227 if (const EnumType *Enum
20.1
'Enum' is null
20.1
'Enum' is null
= SrcType->getAs<EnumType>()) {
20
Assuming the object is not a 'EnumType'
21
Taking false branch
1228 if (Enum->getDecl()->isScoped()) {
1229 if (DestType->isBooleanType()) {
1230 Kind = CK_IntegralToBoolean;
1231 return TC_Success;
1232 } else if (DestType->isIntegralType(Self.Context)) {
1233 Kind = CK_IntegralCast;
1234 return TC_Success;
1235 } else if (DestType->isRealFloatingType()) {
1236 Kind = CK_IntegralToFloating;
1237 return TC_Success;
1238 }
1239 }
1240 }
1241
1242 // Reverse integral promotion/conversion. All such conversions are themselves
1243 // again integral promotions or conversions and are thus already handled by
1244 // p2 (TryDirectInitialization above).
1245 // (Note: any data loss warnings should be suppressed.)
1246 // The exception is the reverse of enum->integer, i.e. integer->enum (and
1247 // enum->enum). See also C++ 5.2.9p7.
1248 // The same goes for reverse floating point promotion/conversion and
1249 // floating-integral conversions. Again, only floating->enum is relevant.
1250 if (DestType->isEnumeralType()) {
22
Calling 'Type::isEnumeralType'
25
Returning from 'Type::isEnumeralType'
26
Taking true branch
1251 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
27
Assuming the condition is false
28
Taking false branch
1252 diag::err_bad_cast_incomplete)) {
1253 SrcExpr = ExprError();
1254 return TC_Failed;
1255 }
1256 if (SrcType->isIntegralOrEnumerationType()) {
29
Calling 'Type::isIntegralOrEnumerationType'
39
Returning from 'Type::isIntegralOrEnumerationType'
40
Taking true branch
1257 // [expr.static.cast]p10 If the enumeration type has a fixed underlying
1258 // type, the value is first converted to that type by integral conversion
1259 const EnumType *Enum = DestType->getAs<EnumType>();
41
Assuming the object is not a 'EnumType'
42
'Enum' initialized to a null pointer value
1260 Kind = Enum->getDecl()->isFixed() &&
43
Called C++ object pointer is null
1261 Enum->getDecl()->getIntegerType()->isBooleanType()
1262 ? CK_IntegralToBoolean
1263 : CK_IntegralCast;
1264 return TC_Success;
1265 } else if (SrcType->isRealFloatingType()) {
1266 Kind = CK_FloatingToIntegral;
1267 return TC_Success;
1268 }
1269 }
1270
1271 // Reverse pointer upcast. C++ 4.10p3 specifies pointer upcast.
1272 // C++ 5.2.9p8 additionally disallows a cast path through virtual inheritance.
1273 tcr = TryStaticPointerDowncast(Self, SrcType, DestType, CStyle, OpRange, msg,
1274 Kind, BasePath);
1275 if (tcr != TC_NotApplicable)
1276 return tcr;
1277
1278 // Reverse member pointer conversion. C++ 4.11 specifies member pointer
1279 // conversion. C++ 5.2.9p9 has additional information.
1280 // DR54's access restrictions apply here also.
1281 tcr = TryStaticMemberPointerUpcast(Self, SrcExpr, SrcType, DestType, CStyle,
1282 OpRange, msg, Kind, BasePath);
1283 if (tcr != TC_NotApplicable)
1284 return tcr;
1285
1286 // Reverse pointer conversion to void*. C++ 4.10.p2 specifies conversion to
1287 // void*. C++ 5.2.9p10 specifies additional restrictions, which really is
1288 // just the usual constness stuff.
1289 if (const PointerType *SrcPointer = SrcType->getAs<PointerType>()) {
1290 QualType SrcPointee = SrcPointer->getPointeeType();
1291 if (SrcPointee->isVoidType()) {
1292 if (const PointerType *DestPointer = DestType->getAs<PointerType>()) {
1293 QualType DestPointee = DestPointer->getPointeeType();
1294 if (DestPointee->isIncompleteOrObjectType()) {
1295 // This is definitely the intended conversion, but it might fail due
1296 // to a qualifier violation. Note that we permit Objective-C lifetime
1297 // and GC qualifier mismatches here.
1298 if (!CStyle) {
1299 Qualifiers DestPointeeQuals = DestPointee.getQualifiers();
1300 Qualifiers SrcPointeeQuals = SrcPointee.getQualifiers();
1301 DestPointeeQuals.removeObjCGCAttr();
1302 DestPointeeQuals.removeObjCLifetime();
1303 SrcPointeeQuals.removeObjCGCAttr();
1304 SrcPointeeQuals.removeObjCLifetime();
1305 if (DestPointeeQuals != SrcPointeeQuals &&
1306 !DestPointeeQuals.compatiblyIncludes(SrcPointeeQuals)) {
1307 msg = diag::err_bad_cxx_cast_qualifiers_away;
1308 return TC_Failed;
1309 }
1310 }
1311 Kind = IsAddressSpaceConversion(SrcType, DestType)
1312 ? CK_AddressSpaceConversion
1313 : CK_BitCast;
1314 return TC_Success;
1315 }
1316
1317 // Microsoft permits static_cast from 'pointer-to-void' to
1318 // 'pointer-to-function'.
1319 if (!CStyle && Self.getLangOpts().MSVCCompat &&
1320 DestPointee->isFunctionType()) {
1321 Self.Diag(OpRange.getBegin(), diag::ext_ms_cast_fn_obj) << OpRange;
1322 Kind = CK_BitCast;
1323 return TC_Success;
1324 }
1325 }
1326 else if (DestType->isObjCObjectPointerType()) {
1327 // allow both c-style cast and static_cast of objective-c pointers as
1328 // they are pervasive.
1329 Kind = CK_CPointerToObjCPointerCast;
1330 return TC_Success;
1331 }
1332 else if (CStyle && DestType->isBlockPointerType()) {
1333 // allow c-style cast of void * to block pointers.
1334 Kind = CK_AnyPointerToBlockPointerCast;
1335 return TC_Success;
1336 }
1337 }
1338 }
1339 // Allow arbitrary objective-c pointer conversion with static casts.
1340 if (SrcType->isObjCObjectPointerType() &&
1341 DestType->isObjCObjectPointerType()) {
1342 Kind = CK_BitCast;
1343 return TC_Success;
1344 }
1345 // Allow ns-pointer to cf-pointer conversion in either direction
1346 // with static casts.
1347 if (!CStyle &&
1348 Self.CheckTollFreeBridgeStaticCast(DestType, SrcExpr.get(), Kind))
1349 return TC_Success;
1350
1351 // See if it looks like the user is trying to convert between
1352 // related record types, and select a better diagnostic if so.
1353 if (auto SrcPointer = SrcType->getAs<PointerType>())
1354 if (auto DestPointer = DestType->getAs<PointerType>())
1355 if (SrcPointer->getPointeeType()->getAs<RecordType>() &&
1356 DestPointer->getPointeeType()->getAs<RecordType>())
1357 msg = diag::err_bad_cxx_cast_unrelated_class;
1358
1359 // We tried everything. Everything! Nothing works! :-(
1360 return TC_NotApplicable;
1361}
1362
1363/// Tests whether a conversion according to N2844 is valid.
1364TryCastResult TryLValueToRValueCast(Sema &Self, Expr *SrcExpr,
1365 QualType DestType, bool CStyle,
1366 CastKind &Kind, CXXCastPath &BasePath,
1367 unsigned &msg) {
1368 // C++11 [expr.static.cast]p3:
1369 // A glvalue of type "cv1 T1" can be cast to type "rvalue reference to
1370 // cv2 T2" if "cv2 T2" is reference-compatible with "cv1 T1".
1371 const RValueReferenceType *R = DestType->getAs<RValueReferenceType>();
1372 if (!R)
1373 return TC_NotApplicable;
1374
1375 if (!SrcExpr->isGLValue())
1376 return TC_NotApplicable;
1377
1378 // Because we try the reference downcast before this function, from now on
1379 // this is the only cast possibility, so we issue an error if we fail now.
1380 // FIXME: Should allow casting away constness if CStyle.
1381 QualType FromType = SrcExpr->getType();
1382 QualType ToType = R->getPointeeType();
1383 if (CStyle) {
1384 FromType = FromType.getUnqualifiedType();
1385 ToType = ToType.getUnqualifiedType();
1386 }
1387
1388 Sema::ReferenceConversions RefConv;
1389 Sema::ReferenceCompareResult RefResult = Self.CompareReferenceRelationship(
1390 SrcExpr->getBeginLoc(), ToType, FromType, &RefConv);
1391 if (RefResult != Sema::Ref_Compatible) {
1392 if (CStyle || RefResult == Sema::Ref_Incompatible)
1393 return TC_NotApplicable;
1394 // Diagnose types which are reference-related but not compatible here since
1395 // we can provide better diagnostics. In these cases forwarding to
1396 // [expr.static.cast]p4 should never result in a well-formed cast.
1397 msg = SrcExpr->isLValue() ? diag::err_bad_lvalue_to_rvalue_cast
1398 : diag::err_bad_rvalue_to_rvalue_cast;
1399 return TC_Failed;
1400 }
1401
1402 if (RefConv & Sema::ReferenceConversions::DerivedToBase) {
1403 Kind = CK_DerivedToBase;
1404 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1405 /*DetectVirtual=*/true);
1406 if (!Self.IsDerivedFrom(SrcExpr->getBeginLoc(), SrcExpr->getType(),
1407 R->getPointeeType(), Paths))
1408 return TC_NotApplicable;
1409
1410 Self.BuildBasePathArray(Paths, BasePath);
1411 } else
1412 Kind = CK_NoOp;
1413
1414 return TC_Success;
1415}
1416
1417/// Tests whether a conversion according to C++ 5.2.9p5 is valid.
1418TryCastResult
1419TryStaticReferenceDowncast(Sema &Self, Expr *SrcExpr, QualType DestType,
1420 bool CStyle, SourceRange OpRange,
1421 unsigned &msg, CastKind &Kind,
1422 CXXCastPath &BasePath) {
1423 // C++ 5.2.9p5: An lvalue of type "cv1 B", where B is a class type, can be
1424 // cast to type "reference to cv2 D", where D is a class derived from B,
1425 // if a valid standard conversion from "pointer to D" to "pointer to B"
1426 // exists, cv2 >= cv1, and B is not a virtual base class of D.
1427 // In addition, DR54 clarifies that the base must be accessible in the
1428 // current context. Although the wording of DR54 only applies to the pointer
1429 // variant of this rule, the intent is clearly for it to apply to the this
1430 // conversion as well.
1431
1432 const ReferenceType *DestReference = DestType->getAs<ReferenceType>();
1433 if (!DestReference) {
1434 return TC_NotApplicable;
1435 }
1436 bool RValueRef = DestReference->isRValueReferenceType();
1437 if (!RValueRef && !SrcExpr->isLValue()) {
1438 // We know the left side is an lvalue reference, so we can suggest a reason.
1439 msg = diag::err_bad_cxx_cast_rvalue;
1440 return TC_NotApplicable;
1441 }
1442
1443 QualType DestPointee = DestReference->getPointeeType();
1444
1445 // FIXME: If the source is a prvalue, we should issue a warning (because the
1446 // cast always has undefined behavior), and for AST consistency, we should
1447 // materialize a temporary.
1448 return TryStaticDowncast(Self,
1449 Self.Context.getCanonicalType(SrcExpr->getType()),
1450 Self.Context.getCanonicalType(DestPointee), CStyle,
1451 OpRange, SrcExpr->getType(), DestType, msg, Kind,
1452 BasePath);
1453}
1454
1455/// Tests whether a conversion according to C++ 5.2.9p8 is valid.
1456TryCastResult
1457TryStaticPointerDowncast(Sema &Self, QualType SrcType, QualType DestType,
1458 bool CStyle, SourceRange OpRange,
1459 unsigned &msg, CastKind &Kind,
1460 CXXCastPath &BasePath) {
1461 // C++ 5.2.9p8: An rvalue of type "pointer to cv1 B", where B is a class
1462 // type, can be converted to an rvalue of type "pointer to cv2 D", where D
1463 // is a class derived from B, if a valid standard conversion from "pointer
1464 // to D" to "pointer to B" exists, cv2 >= cv1, and B is not a virtual base
1465 // class of D.
1466 // In addition, DR54 clarifies that the base must be accessible in the
1467 // current context.
1468
1469 const PointerType *DestPointer = DestType->getAs<PointerType>();
1470 if (!DestPointer) {
1471 return TC_NotApplicable;
1472 }
1473
1474 const PointerType *SrcPointer = SrcType->getAs<PointerType>();
1475 if (!SrcPointer) {
1476 msg = diag::err_bad_static_cast_pointer_nonpointer;
1477 return TC_NotApplicable;
1478 }
1479
1480 return TryStaticDowncast(Self,
1481 Self.Context.getCanonicalType(SrcPointer->getPointeeType()),
1482 Self.Context.getCanonicalType(DestPointer->getPointeeType()),
1483 CStyle, OpRange, SrcType, DestType, msg, Kind,
1484 BasePath);
1485}
1486
1487/// TryStaticDowncast - Common functionality of TryStaticReferenceDowncast and
1488/// TryStaticPointerDowncast. Tests whether a static downcast from SrcType to
1489/// DestType is possible and allowed.
1490TryCastResult
1491TryStaticDowncast(Sema &Self, CanQualType SrcType, CanQualType DestType,
1492 bool CStyle, SourceRange OpRange, QualType OrigSrcType,
1493 QualType OrigDestType, unsigned &msg,
1494 CastKind &Kind, CXXCastPath &BasePath) {
1495 // We can only work with complete types. But don't complain if it doesn't work
1496 if (!Self.isCompleteType(OpRange.getBegin(), SrcType) ||
1497 !Self.isCompleteType(OpRange.getBegin(), DestType))
1498 return TC_NotApplicable;
1499
1500 // Downcast can only happen in class hierarchies, so we need classes.
1501 if (!DestType->getAs<RecordType>() || !SrcType->getAs<RecordType>()) {
1502 return TC_NotApplicable;
1503 }
1504
1505 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1506 /*DetectVirtual=*/true);
1507 if (!Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths)) {
1508 return TC_NotApplicable;
1509 }
1510
1511 // Target type does derive from source type. Now we're serious. If an error
1512 // appears now, it's not ignored.
1513 // This may not be entirely in line with the standard. Take for example:
1514 // struct A {};
1515 // struct B : virtual A {
1516 // B(A&);
1517 // };
1518 //
1519 // void f()
1520 // {
1521 // (void)static_cast<const B&>(*((A*)0));
1522 // }
1523 // As far as the standard is concerned, p5 does not apply (A is virtual), so
1524 // p2 should be used instead - "const B& t(*((A*)0));" is perfectly valid.
1525 // However, both GCC and Comeau reject this example, and accepting it would
1526 // mean more complex code if we're to preserve the nice error message.
1527 // FIXME: Being 100% compliant here would be nice to have.
1528
1529 // Must preserve cv, as always, unless we're in C-style mode.
1530 if (!CStyle && !DestType.isAtLeastAsQualifiedAs(SrcType)) {
1531 msg = diag::err_bad_cxx_cast_qualifiers_away;
1532 return TC_Failed;
1533 }
1534
1535 if (Paths.isAmbiguous(SrcType.getUnqualifiedType())) {
1536 // This code is analoguous to that in CheckDerivedToBaseConversion, except
1537 // that it builds the paths in reverse order.
1538 // To sum up: record all paths to the base and build a nice string from
1539 // them. Use it to spice up the error message.
1540 if (!Paths.isRecordingPaths()) {
1541 Paths.clear();
1542 Paths.setRecordingPaths(true);
1543 Self.IsDerivedFrom(OpRange.getBegin(), DestType, SrcType, Paths);
1544 }
1545 std::string PathDisplayStr;
1546 std::set<unsigned> DisplayedPaths;
1547 for (clang::CXXBasePath &Path : Paths) {
1548 if (DisplayedPaths.insert(Path.back().SubobjectNumber).second) {
1549 // We haven't displayed a path to this particular base
1550 // class subobject yet.
1551 PathDisplayStr += "\n ";
1552 for (CXXBasePathElement &PE : llvm::reverse(Path))
1553 PathDisplayStr += PE.Base->getType().getAsString() + " -> ";
1554 PathDisplayStr += QualType(DestType).getAsString();
1555 }
1556 }
1557
1558 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_base_to_derived_cast)
1559 << QualType(SrcType).getUnqualifiedType()
1560 << QualType(DestType).getUnqualifiedType()
1561 << PathDisplayStr << OpRange;
1562 msg = 0;
1563 return TC_Failed;
1564 }
1565
1566 if (Paths.getDetectedVirtual() != nullptr) {
1567 QualType VirtualBase(Paths.getDetectedVirtual(), 0);
1568 Self.Diag(OpRange.getBegin(), diag::err_static_downcast_via_virtual)
1569 << OrigSrcType << OrigDestType << VirtualBase << OpRange;
1570 msg = 0;
1571 return TC_Failed;
1572 }
1573
1574 if (!CStyle) {
1575 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1576 SrcType, DestType,
1577 Paths.front(),
1578 diag::err_downcast_from_inaccessible_base)) {
1579 case Sema::AR_accessible:
1580 case Sema::AR_delayed: // be optimistic
1581 case Sema::AR_dependent: // be optimistic
1582 break;
1583
1584 case Sema::AR_inaccessible:
1585 msg = 0;
1586 return TC_Failed;
1587 }
1588 }
1589
1590 Self.BuildBasePathArray(Paths, BasePath);
1591 Kind = CK_BaseToDerived;
1592 return TC_Success;
1593}
1594
1595/// TryStaticMemberPointerUpcast - Tests whether a conversion according to
1596/// C++ 5.2.9p9 is valid:
1597///
1598/// An rvalue of type "pointer to member of D of type cv1 T" can be
1599/// converted to an rvalue of type "pointer to member of B of type cv2 T",
1600/// where B is a base class of D [...].
1601///
1602TryCastResult
1603TryStaticMemberPointerUpcast(Sema &Self, ExprResult &SrcExpr, QualType SrcType,
1604 QualType DestType, bool CStyle,
1605 SourceRange OpRange,
1606 unsigned &msg, CastKind &Kind,
1607 CXXCastPath &BasePath) {
1608 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>();
1609 if (!DestMemPtr)
1610 return TC_NotApplicable;
1611
1612 bool WasOverloadedFunction = false;
1613 DeclAccessPair FoundOverload;
1614 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
1615 if (FunctionDecl *Fn
1616 = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(), DestType, false,
1617 FoundOverload)) {
1618 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
1619 SrcType = Self.Context.getMemberPointerType(Fn->getType(),
1620 Self.Context.getTypeDeclType(M->getParent()).getTypePtr());
1621 WasOverloadedFunction = true;
1622 }
1623 }
1624
1625 const MemberPointerType *SrcMemPtr = SrcType->getAs<MemberPointerType>();
1626 if (!SrcMemPtr) {
1627 msg = diag::err_bad_static_cast_member_pointer_nonmp;
1628 return TC_NotApplicable;
1629 }
1630
1631 // Lock down the inheritance model right now in MS ABI, whether or not the
1632 // pointee types are the same.
1633 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1634 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
1635 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
1636 }
1637
1638 // T == T, modulo cv
1639 if (!Self.Context.hasSameUnqualifiedType(SrcMemPtr->getPointeeType(),
1640 DestMemPtr->getPointeeType()))
1641 return TC_NotApplicable;
1642
1643 // B base of D
1644 QualType SrcClass(SrcMemPtr->getClass(), 0);
1645 QualType DestClass(DestMemPtr->getClass(), 0);
1646 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
1647 /*DetectVirtual=*/true);
1648 if (!Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths))
1649 return TC_NotApplicable;
1650
1651 // B is a base of D. But is it an allowed base? If not, it's a hard error.
1652 if (Paths.isAmbiguous(Self.Context.getCanonicalType(DestClass))) {
1653 Paths.clear();
1654 Paths.setRecordingPaths(true);
1655 bool StillOkay =
1656 Self.IsDerivedFrom(OpRange.getBegin(), SrcClass, DestClass, Paths);
1657 assert(StillOkay)((StillOkay) ? static_cast<void> (0) : __assert_fail ("StillOkay"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 1657, __PRETTY_FUNCTION__))
;
1658 (void)StillOkay;
1659 std::string PathDisplayStr = Self.getAmbiguousPathsDisplayString(Paths);
1660 Self.Diag(OpRange.getBegin(), diag::err_ambiguous_memptr_conv)
1661 << 1 << SrcClass << DestClass << PathDisplayStr << OpRange;
1662 msg = 0;
1663 return TC_Failed;
1664 }
1665
1666 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
1667 Self.Diag(OpRange.getBegin(), diag::err_memptr_conv_via_virtual)
1668 << SrcClass << DestClass << QualType(VBase, 0) << OpRange;
1669 msg = 0;
1670 return TC_Failed;
1671 }
1672
1673 if (!CStyle) {
1674 switch (Self.CheckBaseClassAccess(OpRange.getBegin(),
1675 DestClass, SrcClass,
1676 Paths.front(),
1677 diag::err_upcast_to_inaccessible_base)) {
1678 case Sema::AR_accessible:
1679 case Sema::AR_delayed:
1680 case Sema::AR_dependent:
1681 // Optimistically assume that the delayed and dependent cases
1682 // will work out.
1683 break;
1684
1685 case Sema::AR_inaccessible:
1686 msg = 0;
1687 return TC_Failed;
1688 }
1689 }
1690
1691 if (WasOverloadedFunction) {
1692 // Resolve the address of the overloaded function again, this time
1693 // allowing complaints if something goes wrong.
1694 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
1695 DestType,
1696 true,
1697 FoundOverload);
1698 if (!Fn) {
1699 msg = 0;
1700 return TC_Failed;
1701 }
1702
1703 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr, FoundOverload, Fn);
1704 if (!SrcExpr.isUsable()) {
1705 msg = 0;
1706 return TC_Failed;
1707 }
1708 }
1709
1710 Self.BuildBasePathArray(Paths, BasePath);
1711 Kind = CK_DerivedToBaseMemberPointer;
1712 return TC_Success;
1713}
1714
1715/// TryStaticImplicitCast - Tests whether a conversion according to C++ 5.2.9p2
1716/// is valid:
1717///
1718/// An expression e can be explicitly converted to a type T using a
1719/// @c static_cast if the declaration "T t(e);" is well-formed [...].
1720TryCastResult
1721TryStaticImplicitCast(Sema &Self, ExprResult &SrcExpr, QualType DestType,
1722 Sema::CheckedConversionKind CCK,
1723 SourceRange OpRange, unsigned &msg,
1724 CastKind &Kind, bool ListInitialization) {
1725 if (DestType->isRecordType()) {
1726 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
1727 diag::err_bad_cast_incomplete) ||
1728 Self.RequireNonAbstractType(OpRange.getBegin(), DestType,
1729 diag::err_allocation_of_abstract_type)) {
1730 msg = 0;
1731 return TC_Failed;
1732 }
1733 }
1734
1735 InitializedEntity Entity = InitializedEntity::InitializeTemporary(DestType);
1736 InitializationKind InitKind
1737 = (CCK == Sema::CCK_CStyleCast)
1738 ? InitializationKind::CreateCStyleCast(OpRange.getBegin(), OpRange,
1739 ListInitialization)
1740 : (CCK == Sema::CCK_FunctionalCast)
1741 ? InitializationKind::CreateFunctionalCast(OpRange, ListInitialization)
1742 : InitializationKind::CreateCast(OpRange);
1743 Expr *SrcExprRaw = SrcExpr.get();
1744 // FIXME: Per DR242, we should check for an implicit conversion sequence
1745 // or for a constructor that could be invoked by direct-initialization
1746 // here, not for an initialization sequence.
1747 InitializationSequence InitSeq(Self, Entity, InitKind, SrcExprRaw);
1748
1749 // At this point of CheckStaticCast, if the destination is a reference,
1750 // or the expression is an overload expression this has to work.
1751 // There is no other way that works.
1752 // On the other hand, if we're checking a C-style cast, we've still got
1753 // the reinterpret_cast way.
1754 bool CStyle
1755 = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
1756 if (InitSeq.Failed() && (CStyle || !DestType->isReferenceType()))
1757 return TC_NotApplicable;
1758
1759 ExprResult Result = InitSeq.Perform(Self, Entity, InitKind, SrcExprRaw);
1760 if (Result.isInvalid()) {
1761 msg = 0;
1762 return TC_Failed;
1763 }
1764
1765 if (InitSeq.isConstructorInitialization())
1766 Kind = CK_ConstructorConversion;
1767 else
1768 Kind = CK_NoOp;
1769
1770 SrcExpr = Result;
1771 return TC_Success;
1772}
1773
1774/// TryConstCast - See if a const_cast from source to destination is allowed,
1775/// and perform it if it is.
1776static TryCastResult TryConstCast(Sema &Self, ExprResult &SrcExpr,
1777 QualType DestType, bool CStyle,
1778 unsigned &msg) {
1779 DestType = Self.Context.getCanonicalType(DestType);
1780 QualType SrcType = SrcExpr.get()->getType();
1781 bool NeedToMaterializeTemporary = false;
1782
1783 if (const ReferenceType *DestTypeTmp =DestType->getAs<ReferenceType>()) {
1784 // C++11 5.2.11p4:
1785 // if a pointer to T1 can be explicitly converted to the type "pointer to
1786 // T2" using a const_cast, then the following conversions can also be
1787 // made:
1788 // -- an lvalue of type T1 can be explicitly converted to an lvalue of
1789 // type T2 using the cast const_cast<T2&>;
1790 // -- a glvalue of type T1 can be explicitly converted to an xvalue of
1791 // type T2 using the cast const_cast<T2&&>; and
1792 // -- if T1 is a class type, a prvalue of type T1 can be explicitly
1793 // converted to an xvalue of type T2 using the cast const_cast<T2&&>.
1794
1795 if (isa<LValueReferenceType>(DestTypeTmp) && !SrcExpr.get()->isLValue()) {
1796 // Cannot const_cast non-lvalue to lvalue reference type. But if this
1797 // is C-style, static_cast might find a way, so we simply suggest a
1798 // message and tell the parent to keep searching.
1799 msg = diag::err_bad_cxx_cast_rvalue;
1800 return TC_NotApplicable;
1801 }
1802
1803 if (isa<RValueReferenceType>(DestTypeTmp) && SrcExpr.get()->isRValue()) {
1804 if (!SrcType->isRecordType()) {
1805 // Cannot const_cast non-class prvalue to rvalue reference type. But if
1806 // this is C-style, static_cast can do this.
1807 msg = diag::err_bad_cxx_cast_rvalue;
1808 return TC_NotApplicable;
1809 }
1810
1811 // Materialize the class prvalue so that the const_cast can bind a
1812 // reference to it.
1813 NeedToMaterializeTemporary = true;
1814 }
1815
1816 // It's not completely clear under the standard whether we can
1817 // const_cast bit-field gl-values. Doing so would not be
1818 // intrinsically complicated, but for now, we say no for
1819 // consistency with other compilers and await the word of the
1820 // committee.
1821 if (SrcExpr.get()->refersToBitField()) {
1822 msg = diag::err_bad_cxx_cast_bitfield;
1823 return TC_NotApplicable;
1824 }
1825
1826 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
1827 SrcType = Self.Context.getPointerType(SrcType);
1828 }
1829
1830 // C++ 5.2.11p5: For a const_cast involving pointers to data members [...]
1831 // the rules for const_cast are the same as those used for pointers.
1832
1833 if (!DestType->isPointerType() &&
1834 !DestType->isMemberPointerType() &&
1835 !DestType->isObjCObjectPointerType()) {
1836 // Cannot cast to non-pointer, non-reference type. Note that, if DestType
1837 // was a reference type, we converted it to a pointer above.
1838 // The status of rvalue references isn't entirely clear, but it looks like
1839 // conversion to them is simply invalid.
1840 // C++ 5.2.11p3: For two pointer types [...]
1841 if (!CStyle)
1842 msg = diag::err_bad_const_cast_dest;
1843 return TC_NotApplicable;
1844 }
1845 if (DestType->isFunctionPointerType() ||
1846 DestType->isMemberFunctionPointerType()) {
1847 // Cannot cast direct function pointers.
1848 // C++ 5.2.11p2: [...] where T is any object type or the void type [...]
1849 // T is the ultimate pointee of source and target type.
1850 if (!CStyle)
1851 msg = diag::err_bad_const_cast_dest;
1852 return TC_NotApplicable;
1853 }
1854
1855 // C++ [expr.const.cast]p3:
1856 // "For two similar types T1 and T2, [...]"
1857 //
1858 // We only allow a const_cast to change cvr-qualifiers, not other kinds of
1859 // type qualifiers. (Likewise, we ignore other changes when determining
1860 // whether a cast casts away constness.)
1861 if (!Self.Context.hasCvrSimilarType(SrcType, DestType))
1862 return TC_NotApplicable;
1863
1864 if (NeedToMaterializeTemporary)
1865 // This is a const_cast from a class prvalue to an rvalue reference type.
1866 // Materialize a temporary to store the result of the conversion.
1867 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcExpr.get()->getType(),
1868 SrcExpr.get(),
1869 /*IsLValueReference*/ false);
1870
1871 return TC_Success;
1872}
1873
1874// Checks for undefined behavior in reinterpret_cast.
1875// The cases that is checked for is:
1876// *reinterpret_cast<T*>(&a)
1877// reinterpret_cast<T&>(a)
1878// where accessing 'a' as type 'T' will result in undefined behavior.
1879void Sema::CheckCompatibleReinterpretCast(QualType SrcType, QualType DestType,
1880 bool IsDereference,
1881 SourceRange Range) {
1882 unsigned DiagID = IsDereference ?
1883 diag::warn_pointer_indirection_from_incompatible_type :
1884 diag::warn_undefined_reinterpret_cast;
1885
1886 if (Diags.isIgnored(DiagID, Range.getBegin()))
1887 return;
1888
1889 QualType SrcTy, DestTy;
1890 if (IsDereference) {
1891 if (!SrcType->getAs<PointerType>() || !DestType->getAs<PointerType>()) {
1892 return;
1893 }
1894 SrcTy = SrcType->getPointeeType();
1895 DestTy = DestType->getPointeeType();
1896 } else {
1897 if (!DestType->getAs<ReferenceType>()) {
1898 return;
1899 }
1900 SrcTy = SrcType;
1901 DestTy = DestType->getPointeeType();
1902 }
1903
1904 // Cast is compatible if the types are the same.
1905 if (Context.hasSameUnqualifiedType(DestTy, SrcTy)) {
1906 return;
1907 }
1908 // or one of the types is a char or void type
1909 if (DestTy->isAnyCharacterType() || DestTy->isVoidType() ||
1910 SrcTy->isAnyCharacterType() || SrcTy->isVoidType()) {
1911 return;
1912 }
1913 // or one of the types is a tag type.
1914 if (SrcTy->getAs<TagType>() || DestTy->getAs<TagType>()) {
1915 return;
1916 }
1917
1918 // FIXME: Scoped enums?
1919 if ((SrcTy->isUnsignedIntegerType() && DestTy->isSignedIntegerType()) ||
1920 (SrcTy->isSignedIntegerType() && DestTy->isUnsignedIntegerType())) {
1921 if (Context.getTypeSize(DestTy) == Context.getTypeSize(SrcTy)) {
1922 return;
1923 }
1924 }
1925
1926 Diag(Range.getBegin(), DiagID) << SrcType << DestType << Range;
1927}
1928
1929static void DiagnoseCastOfObjCSEL(Sema &Self, const ExprResult &SrcExpr,
1930 QualType DestType) {
1931 QualType SrcType = SrcExpr.get()->getType();
1932 if (Self.Context.hasSameType(SrcType, DestType))
1933 return;
1934 if (const PointerType *SrcPtrTy = SrcType->getAs<PointerType>())
1935 if (SrcPtrTy->isObjCSelType()) {
1936 QualType DT = DestType;
1937 if (isa<PointerType>(DestType))
1938 DT = DestType->getPointeeType();
1939 if (!DT.getUnqualifiedType()->isVoidType())
1940 Self.Diag(SrcExpr.get()->getExprLoc(),
1941 diag::warn_cast_pointer_from_sel)
1942 << SrcType << DestType << SrcExpr.get()->getSourceRange();
1943 }
1944}
1945
1946/// Diagnose casts that change the calling convention of a pointer to a function
1947/// defined in the current TU.
1948static void DiagnoseCallingConvCast(Sema &Self, const ExprResult &SrcExpr,
1949 QualType DstType, SourceRange OpRange) {
1950 // Check if this cast would change the calling convention of a function
1951 // pointer type.
1952 QualType SrcType = SrcExpr.get()->getType();
1953 if (Self.Context.hasSameType(SrcType, DstType) ||
1954 !SrcType->isFunctionPointerType() || !DstType->isFunctionPointerType())
1955 return;
1956 const auto *SrcFTy =
1957 SrcType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1958 const auto *DstFTy =
1959 DstType->castAs<PointerType>()->getPointeeType()->castAs<FunctionType>();
1960 CallingConv SrcCC = SrcFTy->getCallConv();
1961 CallingConv DstCC = DstFTy->getCallConv();
1962 if (SrcCC == DstCC)
1963 return;
1964
1965 // We have a calling convention cast. Check if the source is a pointer to a
1966 // known, specific function that has already been defined.
1967 Expr *Src = SrcExpr.get()->IgnoreParenImpCasts();
1968 if (auto *UO = dyn_cast<UnaryOperator>(Src))
1969 if (UO->getOpcode() == UO_AddrOf)
1970 Src = UO->getSubExpr()->IgnoreParenImpCasts();
1971 auto *DRE = dyn_cast<DeclRefExpr>(Src);
1972 if (!DRE)
1973 return;
1974 auto *FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1975 if (!FD)
1976 return;
1977
1978 // Only warn if we are casting from the default convention to a non-default
1979 // convention. This can happen when the programmer forgot to apply the calling
1980 // convention to the function declaration and then inserted this cast to
1981 // satisfy the type system.
1982 CallingConv DefaultCC = Self.getASTContext().getDefaultCallingConvention(
1983 FD->isVariadic(), FD->isCXXInstanceMember());
1984 if (DstCC == DefaultCC || SrcCC != DefaultCC)
1985 return;
1986
1987 // Diagnose this cast, as it is probably bad.
1988 StringRef SrcCCName = FunctionType::getNameForCallConv(SrcCC);
1989 StringRef DstCCName = FunctionType::getNameForCallConv(DstCC);
1990 Self.Diag(OpRange.getBegin(), diag::warn_cast_calling_conv)
1991 << SrcCCName << DstCCName << OpRange;
1992
1993 // The checks above are cheaper than checking if the diagnostic is enabled.
1994 // However, it's worth checking if the warning is enabled before we construct
1995 // a fixit.
1996 if (Self.Diags.isIgnored(diag::warn_cast_calling_conv, OpRange.getBegin()))
1997 return;
1998
1999 // Try to suggest a fixit to change the calling convention of the function
2000 // whose address was taken. Try to use the latest macro for the convention.
2001 // For example, users probably want to write "WINAPI" instead of "__stdcall"
2002 // to match the Windows header declarations.
2003 SourceLocation NameLoc = FD->getFirstDecl()->getNameInfo().getLoc();
2004 Preprocessor &PP = Self.getPreprocessor();
2005 SmallVector<TokenValue, 6> AttrTokens;
2006 SmallString<64> CCAttrText;
2007 llvm::raw_svector_ostream OS(CCAttrText);
2008 if (Self.getLangOpts().MicrosoftExt) {
2009 // __stdcall or __vectorcall
2010 OS << "__" << DstCCName;
2011 IdentifierInfo *II = PP.getIdentifierInfo(OS.str());
2012 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2013 ? TokenValue(II->getTokenID())
2014 : TokenValue(II));
2015 } else {
2016 // __attribute__((stdcall)) or __attribute__((vectorcall))
2017 OS << "__attribute__((" << DstCCName << "))";
2018 AttrTokens.push_back(tok::kw___attribute);
2019 AttrTokens.push_back(tok::l_paren);
2020 AttrTokens.push_back(tok::l_paren);
2021 IdentifierInfo *II = PP.getIdentifierInfo(DstCCName);
2022 AttrTokens.push_back(II->isKeyword(Self.getLangOpts())
2023 ? TokenValue(II->getTokenID())
2024 : TokenValue(II));
2025 AttrTokens.push_back(tok::r_paren);
2026 AttrTokens.push_back(tok::r_paren);
2027 }
2028 StringRef AttrSpelling = PP.getLastMacroWithSpelling(NameLoc, AttrTokens);
2029 if (!AttrSpelling.empty())
2030 CCAttrText = AttrSpelling;
2031 OS << ' ';
2032 Self.Diag(NameLoc, diag::note_change_calling_conv_fixit)
2033 << FD << DstCCName << FixItHint::CreateInsertion(NameLoc, CCAttrText);
2034}
2035
2036static void checkIntToPointerCast(bool CStyle, const SourceRange &OpRange,
2037 const Expr *SrcExpr, QualType DestType,
2038 Sema &Self) {
2039 QualType SrcType = SrcExpr->getType();
2040
2041 // Not warning on reinterpret_cast, boolean, constant expressions, etc
2042 // are not explicit design choices, but consistent with GCC's behavior.
2043 // Feel free to modify them if you've reason/evidence for an alternative.
2044 if (CStyle && SrcType->isIntegralType(Self.Context)
2045 && !SrcType->isBooleanType()
2046 && !SrcType->isEnumeralType()
2047 && !SrcExpr->isIntegerConstantExpr(Self.Context)
2048 && Self.Context.getTypeSize(DestType) >
2049 Self.Context.getTypeSize(SrcType)) {
2050 // Separate between casts to void* and non-void* pointers.
2051 // Some APIs use (abuse) void* for something like a user context,
2052 // and often that value is an integer even if it isn't a pointer itself.
2053 // Having a separate warning flag allows users to control the warning
2054 // for their workflow.
2055 unsigned Diag = DestType->isVoidPointerType() ?
2056 diag::warn_int_to_void_pointer_cast
2057 : diag::warn_int_to_pointer_cast;
2058 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2059 }
2060}
2061
2062static bool fixOverloadedReinterpretCastExpr(Sema &Self, QualType DestType,
2063 ExprResult &Result) {
2064 // We can only fix an overloaded reinterpret_cast if
2065 // - it is a template with explicit arguments that resolves to an lvalue
2066 // unambiguously, or
2067 // - it is the only function in an overload set that may have its address
2068 // taken.
2069
2070 Expr *E = Result.get();
2071 // TODO: what if this fails because of DiagnoseUseOfDecl or something
2072 // like it?
2073 if (Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2074 Result,
2075 Expr::getValueKindForType(DestType) == VK_RValue // Convert Fun to Ptr
2076 ) &&
2077 Result.isUsable())
2078 return true;
2079
2080 // No guarantees that ResolveAndFixSingleFunctionTemplateSpecialization
2081 // preserves Result.
2082 Result = E;
2083 if (!Self.resolveAndFixAddressOfSingleOverloadCandidate(
2084 Result, /*DoFunctionPointerConversion=*/true))
2085 return false;
2086 return Result.isUsable();
2087}
2088
2089static TryCastResult TryReinterpretCast(Sema &Self, ExprResult &SrcExpr,
2090 QualType DestType, bool CStyle,
2091 SourceRange OpRange,
2092 unsigned &msg,
2093 CastKind &Kind) {
2094 bool IsLValueCast = false;
2095
2096 DestType = Self.Context.getCanonicalType(DestType);
2097 QualType SrcType = SrcExpr.get()->getType();
2098
2099 // Is the source an overloaded name? (i.e. &foo)
2100 // If so, reinterpret_cast generally can not help us here (13.4, p1, bullet 5)
2101 if (SrcType == Self.Context.OverloadTy) {
2102 ExprResult FixedExpr = SrcExpr;
2103 if (!fixOverloadedReinterpretCastExpr(Self, DestType, FixedExpr))
2104 return TC_NotApplicable;
2105
2106 assert(FixedExpr.isUsable() && "Invalid result fixing overloaded expr")((FixedExpr.isUsable() && "Invalid result fixing overloaded expr"
) ? static_cast<void> (0) : __assert_fail ("FixedExpr.isUsable() && \"Invalid result fixing overloaded expr\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2106, __PRETTY_FUNCTION__))
;
2107 SrcExpr = FixedExpr;
2108 SrcType = SrcExpr.get()->getType();
2109 }
2110
2111 if (const ReferenceType *DestTypeTmp = DestType->getAs<ReferenceType>()) {
2112 if (!SrcExpr.get()->isGLValue()) {
2113 // Cannot cast non-glvalue to (lvalue or rvalue) reference type. See the
2114 // similar comment in const_cast.
2115 msg = diag::err_bad_cxx_cast_rvalue;
2116 return TC_NotApplicable;
2117 }
2118
2119 if (!CStyle) {
2120 Self.CheckCompatibleReinterpretCast(SrcType, DestType,
2121 /*IsDereference=*/false, OpRange);
2122 }
2123
2124 // C++ 5.2.10p10: [...] a reference cast reinterpret_cast<T&>(x) has the
2125 // same effect as the conversion *reinterpret_cast<T*>(&x) with the
2126 // built-in & and * operators.
2127
2128 const char *inappropriate = nullptr;
2129 switch (SrcExpr.get()->getObjectKind()) {
2130 case OK_Ordinary:
2131 break;
2132 case OK_BitField:
2133 msg = diag::err_bad_cxx_cast_bitfield;
2134 return TC_NotApplicable;
2135 // FIXME: Use a specific diagnostic for the rest of these cases.
2136 case OK_VectorComponent: inappropriate = "vector element"; break;
2137 case OK_MatrixComponent:
2138 inappropriate = "matrix element";
2139 break;
2140 case OK_ObjCProperty: inappropriate = "property expression"; break;
2141 case OK_ObjCSubscript: inappropriate = "container subscripting expression";
2142 break;
2143 }
2144 if (inappropriate) {
2145 Self.Diag(OpRange.getBegin(), diag::err_bad_reinterpret_cast_reference)
2146 << inappropriate << DestType
2147 << OpRange << SrcExpr.get()->getSourceRange();
2148 msg = 0; SrcExpr = ExprError();
2149 return TC_NotApplicable;
2150 }
2151
2152 // This code does this transformation for the checked types.
2153 DestType = Self.Context.getPointerType(DestTypeTmp->getPointeeType());
2154 SrcType = Self.Context.getPointerType(SrcType);
2155
2156 IsLValueCast = true;
2157 }
2158
2159 // Canonicalize source for comparison.
2160 SrcType = Self.Context.getCanonicalType(SrcType);
2161
2162 const MemberPointerType *DestMemPtr = DestType->getAs<MemberPointerType>(),
2163 *SrcMemPtr = SrcType->getAs<MemberPointerType>();
2164 if (DestMemPtr && SrcMemPtr) {
2165 // C++ 5.2.10p9: An rvalue of type "pointer to member of X of type T1"
2166 // can be explicitly converted to an rvalue of type "pointer to member
2167 // of Y of type T2" if T1 and T2 are both function types or both object
2168 // types.
2169 if (DestMemPtr->isMemberFunctionPointer() !=
2170 SrcMemPtr->isMemberFunctionPointer())
2171 return TC_NotApplicable;
2172
2173 if (Self.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2174 // We need to determine the inheritance model that the class will use if
2175 // haven't yet.
2176 (void)Self.isCompleteType(OpRange.getBegin(), SrcType);
2177 (void)Self.isCompleteType(OpRange.getBegin(), DestType);
2178 }
2179
2180 // Don't allow casting between member pointers of different sizes.
2181 if (Self.Context.getTypeSize(DestMemPtr) !=
2182 Self.Context.getTypeSize(SrcMemPtr)) {
2183 msg = diag::err_bad_cxx_cast_member_pointer_size;
2184 return TC_Failed;
2185 }
2186
2187 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away
2188 // constness.
2189 // A reinterpret_cast followed by a const_cast can, though, so in C-style,
2190 // we accept it.
2191 if (auto CACK =
2192 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2193 /*CheckObjCLifetime=*/CStyle))
2194 return getCastAwayConstnessCastKind(CACK, msg);
2195
2196 // A valid member pointer cast.
2197 assert(!IsLValueCast)((!IsLValueCast) ? static_cast<void> (0) : __assert_fail
("!IsLValueCast", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2197, __PRETTY_FUNCTION__))
;
2198 Kind = CK_ReinterpretMemberPointer;
2199 return TC_Success;
2200 }
2201
2202 // See below for the enumeral issue.
2203 if (SrcType->isNullPtrType() && DestType->isIntegralType(Self.Context)) {
2204 // C++0x 5.2.10p4: A pointer can be explicitly converted to any integral
2205 // type large enough to hold it. A value of std::nullptr_t can be
2206 // converted to an integral type; the conversion has the same meaning
2207 // and validity as a conversion of (void*)0 to the integral type.
2208 if (Self.Context.getTypeSize(SrcType) >
2209 Self.Context.getTypeSize(DestType)) {
2210 msg = diag::err_bad_reinterpret_cast_small_int;
2211 return TC_Failed;
2212 }
2213 Kind = CK_PointerToIntegral;
2214 return TC_Success;
2215 }
2216
2217 // Allow reinterpret_casts between vectors of the same size and
2218 // between vectors and integers of the same size.
2219 bool destIsVector = DestType->isVectorType();
2220 bool srcIsVector = SrcType->isVectorType();
2221 if (srcIsVector || destIsVector) {
2222 // The non-vector type, if any, must have integral type. This is
2223 // the same rule that C vector casts use; note, however, that enum
2224 // types are not integral in C++.
2225 if ((!destIsVector && !DestType->isIntegralType(Self.Context)) ||
2226 (!srcIsVector && !SrcType->isIntegralType(Self.Context)))
2227 return TC_NotApplicable;
2228
2229 // The size we want to consider is eltCount * eltSize.
2230 // That's exactly what the lax-conversion rules will check.
2231 if (Self.areLaxCompatibleVectorTypes(SrcType, DestType)) {
2232 Kind = CK_BitCast;
2233 return TC_Success;
2234 }
2235
2236 // Otherwise, pick a reasonable diagnostic.
2237 if (!destIsVector)
2238 msg = diag::err_bad_cxx_cast_vector_to_scalar_different_size;
2239 else if (!srcIsVector)
2240 msg = diag::err_bad_cxx_cast_scalar_to_vector_different_size;
2241 else
2242 msg = diag::err_bad_cxx_cast_vector_to_vector_different_size;
2243
2244 return TC_Failed;
2245 }
2246
2247 if (SrcType == DestType) {
2248 // C++ 5.2.10p2 has a note that mentions that, subject to all other
2249 // restrictions, a cast to the same type is allowed so long as it does not
2250 // cast away constness. In C++98, the intent was not entirely clear here,
2251 // since all other paragraphs explicitly forbid casts to the same type.
2252 // C++11 clarifies this case with p2.
2253 //
2254 // The only allowed types are: integral, enumeration, pointer, or
2255 // pointer-to-member types. We also won't restrict Obj-C pointers either.
2256 Kind = CK_NoOp;
2257 TryCastResult Result = TC_NotApplicable;
2258 if (SrcType->isIntegralOrEnumerationType() ||
2259 SrcType->isAnyPointerType() ||
2260 SrcType->isMemberPointerType() ||
2261 SrcType->isBlockPointerType()) {
2262 Result = TC_Success;
2263 }
2264 return Result;
2265 }
2266
2267 bool destIsPtr = DestType->isAnyPointerType() ||
2268 DestType->isBlockPointerType();
2269 bool srcIsPtr = SrcType->isAnyPointerType() ||
2270 SrcType->isBlockPointerType();
2271 if (!destIsPtr && !srcIsPtr) {
2272 // Except for std::nullptr_t->integer and lvalue->reference, which are
2273 // handled above, at least one of the two arguments must be a pointer.
2274 return TC_NotApplicable;
2275 }
2276
2277 if (DestType->isIntegralType(Self.Context)) {
2278 assert(srcIsPtr && "One type must be a pointer")((srcIsPtr && "One type must be a pointer") ? static_cast
<void> (0) : __assert_fail ("srcIsPtr && \"One type must be a pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2278, __PRETTY_FUNCTION__))
;
2279 // C++ 5.2.10p4: A pointer can be explicitly converted to any integral
2280 // type large enough to hold it; except in Microsoft mode, where the
2281 // integral type size doesn't matter (except we don't allow bool).
2282 if ((Self.Context.getTypeSize(SrcType) >
2283 Self.Context.getTypeSize(DestType))) {
2284 bool MicrosoftException =
2285 Self.getLangOpts().MicrosoftExt && !DestType->isBooleanType();
2286 if (MicrosoftException) {
2287 unsigned Diag = SrcType->isVoidPointerType()
2288 ? diag::warn_void_pointer_to_int_cast
2289 : diag::warn_pointer_to_int_cast;
2290 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2291 } else {
2292 msg = diag::err_bad_reinterpret_cast_small_int;
2293 return TC_Failed;
2294 }
2295 }
2296 Kind = CK_PointerToIntegral;
2297 return TC_Success;
2298 }
2299
2300 if (SrcType->isIntegralOrEnumerationType()) {
2301 assert(destIsPtr && "One type must be a pointer")((destIsPtr && "One type must be a pointer") ? static_cast
<void> (0) : __assert_fail ("destIsPtr && \"One type must be a pointer\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2301, __PRETTY_FUNCTION__))
;
2302 checkIntToPointerCast(CStyle, OpRange, SrcExpr.get(), DestType, Self);
2303 // C++ 5.2.10p5: A value of integral or enumeration type can be explicitly
2304 // converted to a pointer.
2305 // C++ 5.2.10p9: [Note: ...a null pointer constant of integral type is not
2306 // necessarily converted to a null pointer value.]
2307 Kind = CK_IntegralToPointer;
2308 return TC_Success;
2309 }
2310
2311 if (!destIsPtr || !srcIsPtr) {
2312 // With the valid non-pointer conversions out of the way, we can be even
2313 // more stringent.
2314 return TC_NotApplicable;
2315 }
2316
2317 // Cannot convert between block pointers and Objective-C object pointers.
2318 if ((SrcType->isBlockPointerType() && DestType->isObjCObjectPointerType()) ||
2319 (DestType->isBlockPointerType() && SrcType->isObjCObjectPointerType()))
2320 return TC_NotApplicable;
2321
2322 // C++ 5.2.10p2: The reinterpret_cast operator shall not cast away constness.
2323 // The C-style cast operator can.
2324 TryCastResult SuccessResult = TC_Success;
2325 if (auto CACK =
2326 CastsAwayConstness(Self, SrcType, DestType, /*CheckCVR=*/!CStyle,
2327 /*CheckObjCLifetime=*/CStyle))
2328 SuccessResult = getCastAwayConstnessCastKind(CACK, msg);
2329
2330 if (IsAddressSpaceConversion(SrcType, DestType)) {
2331 Kind = CK_AddressSpaceConversion;
2332 assert(SrcType->isPointerType() && DestType->isPointerType())((SrcType->isPointerType() && DestType->isPointerType
()) ? static_cast<void> (0) : __assert_fail ("SrcType->isPointerType() && DestType->isPointerType()"
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2332, __PRETTY_FUNCTION__))
;
2333 if (!CStyle &&
2334 !DestType->getPointeeType().getQualifiers().isAddressSpaceSupersetOf(
2335 SrcType->getPointeeType().getQualifiers())) {
2336 SuccessResult = TC_Failed;
2337 }
2338 } else if (IsLValueCast) {
2339 Kind = CK_LValueBitCast;
2340 } else if (DestType->isObjCObjectPointerType()) {
2341 Kind = Self.PrepareCastToObjCObjectPointer(SrcExpr);
2342 } else if (DestType->isBlockPointerType()) {
2343 if (!SrcType->isBlockPointerType()) {
2344 Kind = CK_AnyPointerToBlockPointerCast;
2345 } else {
2346 Kind = CK_BitCast;
2347 }
2348 } else {
2349 Kind = CK_BitCast;
2350 }
2351
2352 // Any pointer can be cast to an Objective-C pointer type with a C-style
2353 // cast.
2354 if (CStyle && DestType->isObjCObjectPointerType()) {
2355 return SuccessResult;
2356 }
2357 if (CStyle)
2358 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2359
2360 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2361
2362 // Not casting away constness, so the only remaining check is for compatible
2363 // pointer categories.
2364
2365 if (SrcType->isFunctionPointerType()) {
2366 if (DestType->isFunctionPointerType()) {
2367 // C++ 5.2.10p6: A pointer to a function can be explicitly converted to
2368 // a pointer to a function of a different type.
2369 return SuccessResult;
2370 }
2371
2372 // C++0x 5.2.10p8: Converting a pointer to a function into a pointer to
2373 // an object type or vice versa is conditionally-supported.
2374 // Compilers support it in C++03 too, though, because it's necessary for
2375 // casting the return value of dlsym() and GetProcAddress().
2376 // FIXME: Conditionally-supported behavior should be configurable in the
2377 // TargetInfo or similar.
2378 Self.Diag(OpRange.getBegin(),
2379 Self.getLangOpts().CPlusPlus11 ?
2380 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2381 << OpRange;
2382 return SuccessResult;
2383 }
2384
2385 if (DestType->isFunctionPointerType()) {
2386 // See above.
2387 Self.Diag(OpRange.getBegin(),
2388 Self.getLangOpts().CPlusPlus11 ?
2389 diag::warn_cxx98_compat_cast_fn_obj : diag::ext_cast_fn_obj)
2390 << OpRange;
2391 return SuccessResult;
2392 }
2393
2394 // Diagnose address space conversion in nested pointers.
2395 QualType DestPtee = DestType->getPointeeType().isNull()
2396 ? DestType->getPointeeType()
2397 : DestType->getPointeeType()->getPointeeType();
2398 QualType SrcPtee = SrcType->getPointeeType().isNull()
2399 ? SrcType->getPointeeType()
2400 : SrcType->getPointeeType()->getPointeeType();
2401 while (!DestPtee.isNull() && !SrcPtee.isNull()) {
2402 if (DestPtee.getAddressSpace() != SrcPtee.getAddressSpace()) {
2403 Self.Diag(OpRange.getBegin(),
2404 diag::warn_bad_cxx_cast_nested_pointer_addr_space)
2405 << CStyle << SrcType << DestType << SrcExpr.get()->getSourceRange();
2406 break;
2407 }
2408 DestPtee = DestPtee->getPointeeType();
2409 SrcPtee = SrcPtee->getPointeeType();
2410 }
2411
2412 // C++ 5.2.10p7: A pointer to an object can be explicitly converted to
2413 // a pointer to an object of different type.
2414 // Void pointers are not specified, but supported by every compiler out there.
2415 // So we finish by allowing everything that remains - it's got to be two
2416 // object pointers.
2417 return SuccessResult;
2418}
2419
2420static TryCastResult TryAddressSpaceCast(Sema &Self, ExprResult &SrcExpr,
2421 QualType DestType, bool CStyle,
2422 unsigned &msg, CastKind &Kind) {
2423 if (!Self.getLangOpts().OpenCL)
2424 // FIXME: As compiler doesn't have any information about overlapping addr
2425 // spaces at the moment we have to be permissive here.
2426 return TC_NotApplicable;
2427 // Even though the logic below is general enough and can be applied to
2428 // non-OpenCL mode too, we fast-path above because no other languages
2429 // define overlapping address spaces currently.
2430 auto SrcType = SrcExpr.get()->getType();
2431 // FIXME: Should this be generalized to references? The reference parameter
2432 // however becomes a reference pointee type here and therefore rejected.
2433 // Perhaps this is the right behavior though according to C++.
2434 auto SrcPtrType = SrcType->getAs<PointerType>();
2435 if (!SrcPtrType)
2436 return TC_NotApplicable;
2437 auto DestPtrType = DestType->getAs<PointerType>();
2438 if (!DestPtrType)
2439 return TC_NotApplicable;
2440 auto SrcPointeeType = SrcPtrType->getPointeeType();
2441 auto DestPointeeType = DestPtrType->getPointeeType();
2442 if (!DestPointeeType.isAddressSpaceOverlapping(SrcPointeeType)) {
2443 msg = diag::err_bad_cxx_cast_addr_space_mismatch;
2444 return TC_Failed;
2445 }
2446 auto SrcPointeeTypeWithoutAS =
2447 Self.Context.removeAddrSpaceQualType(SrcPointeeType.getCanonicalType());
2448 auto DestPointeeTypeWithoutAS =
2449 Self.Context.removeAddrSpaceQualType(DestPointeeType.getCanonicalType());
2450 if (Self.Context.hasSameType(SrcPointeeTypeWithoutAS,
2451 DestPointeeTypeWithoutAS)) {
2452 Kind = SrcPointeeType.getAddressSpace() == DestPointeeType.getAddressSpace()
2453 ? CK_NoOp
2454 : CK_AddressSpaceConversion;
2455 return TC_Success;
2456 } else {
2457 return TC_NotApplicable;
2458 }
2459}
2460
2461void CastOperation::checkAddressSpaceCast(QualType SrcType, QualType DestType) {
2462 // In OpenCL only conversions between pointers to objects in overlapping
2463 // addr spaces are allowed. v2.0 s6.5.5 - Generic addr space overlaps
2464 // with any named one, except for constant.
2465
2466 // Converting the top level pointee addrspace is permitted for compatible
2467 // addrspaces (such as 'generic int *' to 'local int *' or vice versa), but
2468 // if any of the nested pointee addrspaces differ, we emit a warning
2469 // regardless of addrspace compatibility. This makes
2470 // local int ** p;
2471 // return (generic int **) p;
2472 // warn even though local -> generic is permitted.
2473 if (Self.getLangOpts().OpenCL) {
2474 const Type *DestPtr, *SrcPtr;
2475 bool Nested = false;
2476 unsigned DiagID = diag::err_typecheck_incompatible_address_space;
2477 DestPtr = Self.getASTContext().getCanonicalType(DestType.getTypePtr()),
2478 SrcPtr = Self.getASTContext().getCanonicalType(SrcType.getTypePtr());
2479
2480 while (isa<PointerType>(DestPtr) && isa<PointerType>(SrcPtr)) {
2481 const PointerType *DestPPtr = cast<PointerType>(DestPtr);
2482 const PointerType *SrcPPtr = cast<PointerType>(SrcPtr);
2483 QualType DestPPointee = DestPPtr->getPointeeType();
2484 QualType SrcPPointee = SrcPPtr->getPointeeType();
2485 if (Nested
2486 ? DestPPointee.getAddressSpace() != SrcPPointee.getAddressSpace()
2487 : !DestPPointee.isAddressSpaceOverlapping(SrcPPointee)) {
2488 Self.Diag(OpRange.getBegin(), DiagID)
2489 << SrcType << DestType << Sema::AA_Casting
2490 << SrcExpr.get()->getSourceRange();
2491 if (!Nested)
2492 SrcExpr = ExprError();
2493 return;
2494 }
2495
2496 DestPtr = DestPPtr->getPointeeType().getTypePtr();
2497 SrcPtr = SrcPPtr->getPointeeType().getTypePtr();
2498 Nested = true;
2499 DiagID = diag::ext_nested_pointer_qualifier_mismatch;
2500 }
2501 }
2502}
2503
2504void CastOperation::CheckCXXCStyleCast(bool FunctionalStyle,
2505 bool ListInitialization) {
2506 assert(Self.getLangOpts().CPlusPlus)((Self.getLangOpts().CPlusPlus) ? static_cast<void> (0)
: __assert_fail ("Self.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2506, __PRETTY_FUNCTION__))
;
2507
2508 // Handle placeholders.
2509 if (isPlaceholder()) {
2510 // C-style casts can resolve __unknown_any types.
2511 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2512 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2513 SrcExpr.get(), Kind,
2514 ValueKind, BasePath);
2515 return;
2516 }
2517
2518 checkNonOverloadPlaceholders();
2519 if (SrcExpr.isInvalid())
2520 return;
2521 }
2522
2523 // C++ 5.2.9p4: Any expression can be explicitly converted to type "cv void".
2524 // This test is outside everything else because it's the only case where
2525 // a non-lvalue-reference target type does not lead to decay.
2526 if (DestType->isVoidType()) {
2527 Kind = CK_ToVoid;
2528
2529 if (claimPlaceholder(BuiltinType::Overload)) {
2530 Self.ResolveAndFixSingleFunctionTemplateSpecialization(
2531 SrcExpr, /* Decay Function to ptr */ false,
2532 /* Complain */ true, DestRange, DestType,
2533 diag::err_bad_cstyle_cast_overload);
2534 if (SrcExpr.isInvalid())
2535 return;
2536 }
2537
2538 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2539 return;
2540 }
2541
2542 // If the type is dependent, we won't do any other semantic analysis now.
2543 if (DestType->isDependentType() || SrcExpr.get()->isTypeDependent() ||
2544 SrcExpr.get()->isValueDependent()) {
2545 assert(Kind == CK_Dependent)((Kind == CK_Dependent) ? static_cast<void> (0) : __assert_fail
("Kind == CK_Dependent", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2545, __PRETTY_FUNCTION__))
;
2546 return;
2547 }
2548
2549 if (ValueKind == VK_RValue && !DestType->isRecordType() &&
2550 !isPlaceholder(BuiltinType::Overload)) {
2551 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2552 if (SrcExpr.isInvalid())
2553 return;
2554 }
2555
2556 // AltiVec vector initialization with a single literal.
2557 if (const VectorType *vecTy = DestType->getAs<VectorType>())
2558 if (vecTy->getVectorKind() == VectorType::AltiVecVector
2559 && (SrcExpr.get()->getType()->isIntegerType()
2560 || SrcExpr.get()->getType()->isFloatingType())) {
2561 Kind = CK_VectorSplat;
2562 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2563 return;
2564 }
2565
2566 // C++ [expr.cast]p5: The conversions performed by
2567 // - a const_cast,
2568 // - a static_cast,
2569 // - a static_cast followed by a const_cast,
2570 // - a reinterpret_cast, or
2571 // - a reinterpret_cast followed by a const_cast,
2572 // can be performed using the cast notation of explicit type conversion.
2573 // [...] If a conversion can be interpreted in more than one of the ways
2574 // listed above, the interpretation that appears first in the list is used,
2575 // even if a cast resulting from that interpretation is ill-formed.
2576 // In plain language, this means trying a const_cast ...
2577 // Note that for address space we check compatibility after const_cast.
2578 unsigned msg = diag::err_bad_cxx_cast_generic;
2579 TryCastResult tcr = TryConstCast(Self, SrcExpr, DestType,
2580 /*CStyle*/ true, msg);
2581 if (SrcExpr.isInvalid())
2582 return;
2583 if (isValidCast(tcr))
2584 Kind = CK_NoOp;
2585
2586 Sema::CheckedConversionKind CCK =
2587 FunctionalStyle ? Sema::CCK_FunctionalCast : Sema::CCK_CStyleCast;
2588 if (tcr == TC_NotApplicable) {
2589 tcr = TryAddressSpaceCast(Self, SrcExpr, DestType, /*CStyle*/ true, msg,
2590 Kind);
2591 if (SrcExpr.isInvalid())
2592 return;
2593
2594 if (tcr == TC_NotApplicable) {
2595 // ... or if that is not possible, a static_cast, ignoring const and
2596 // addr space, ...
2597 tcr = TryStaticCast(Self, SrcExpr, DestType, CCK, OpRange, msg, Kind,
2598 BasePath, ListInitialization);
2599 if (SrcExpr.isInvalid())
2600 return;
2601
2602 if (tcr == TC_NotApplicable) {
2603 // ... and finally a reinterpret_cast, ignoring const and addr space.
2604 tcr = TryReinterpretCast(Self, SrcExpr, DestType, /*CStyle*/ true,
2605 OpRange, msg, Kind);
2606 if (SrcExpr.isInvalid())
2607 return;
2608 }
2609 }
2610 }
2611
2612 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers() &&
2613 isValidCast(tcr))
2614 checkObjCConversion(CCK);
2615
2616 if (tcr != TC_Success && msg != 0) {
2617 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2618 DeclAccessPair Found;
2619 FunctionDecl *Fn = Self.ResolveAddressOfOverloadedFunction(SrcExpr.get(),
2620 DestType,
2621 /*Complain*/ true,
2622 Found);
2623 if (Fn) {
2624 // If DestType is a function type (not to be confused with the function
2625 // pointer type), it will be possible to resolve the function address,
2626 // but the type cast should be considered as failure.
2627 OverloadExpr *OE = OverloadExpr::find(SrcExpr.get()).Expression;
2628 Self.Diag(OpRange.getBegin(), diag::err_bad_cstyle_cast_overload)
2629 << OE->getName() << DestType << OpRange
2630 << OE->getQualifierLoc().getSourceRange();
2631 Self.NoteAllOverloadCandidates(SrcExpr.get());
2632 }
2633 } else {
2634 diagnoseBadCast(Self, msg, (FunctionalStyle ? CT_Functional : CT_CStyle),
2635 OpRange, SrcExpr.get(), DestType, ListInitialization);
2636 }
2637 }
2638
2639 if (isValidCast(tcr)) {
2640 if (Kind == CK_BitCast)
2641 checkCastAlign();
2642 } else {
2643 SrcExpr = ExprError();
2644 }
2645}
2646
2647/// DiagnoseBadFunctionCast - Warn whenever a function call is cast to a
2648/// non-matching type. Such as enum function call to int, int call to
2649/// pointer; etc. Cast to 'void' is an exception.
2650static void DiagnoseBadFunctionCast(Sema &Self, const ExprResult &SrcExpr,
2651 QualType DestType) {
2652 if (Self.Diags.isIgnored(diag::warn_bad_function_cast,
2653 SrcExpr.get()->getExprLoc()))
2654 return;
2655
2656 if (!isa<CallExpr>(SrcExpr.get()))
2657 return;
2658
2659 QualType SrcType = SrcExpr.get()->getType();
2660 if (DestType.getUnqualifiedType()->isVoidType())
2661 return;
2662 if ((SrcType->isAnyPointerType() || SrcType->isBlockPointerType())
2663 && (DestType->isAnyPointerType() || DestType->isBlockPointerType()))
2664 return;
2665 if (SrcType->isIntegerType() && DestType->isIntegerType() &&
2666 (SrcType->isBooleanType() == DestType->isBooleanType()) &&
2667 (SrcType->isEnumeralType() == DestType->isEnumeralType()))
2668 return;
2669 if (SrcType->isRealFloatingType() && DestType->isRealFloatingType())
2670 return;
2671 if (SrcType->isEnumeralType() && DestType->isEnumeralType())
2672 return;
2673 if (SrcType->isComplexType() && DestType->isComplexType())
2674 return;
2675 if (SrcType->isComplexIntegerType() && DestType->isComplexIntegerType())
2676 return;
2677 if (SrcType->isFixedPointType() && DestType->isFixedPointType())
2678 return;
2679
2680 Self.Diag(SrcExpr.get()->getExprLoc(),
2681 diag::warn_bad_function_cast)
2682 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2683}
2684
2685/// Check the semantics of a C-style cast operation, in C.
2686void CastOperation::CheckCStyleCast() {
2687 assert(!Self.getLangOpts().CPlusPlus)((!Self.getLangOpts().CPlusPlus) ? static_cast<void> (0
) : __assert_fail ("!Self.getLangOpts().CPlusPlus", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2687, __PRETTY_FUNCTION__))
;
2688
2689 // C-style casts can resolve __unknown_any types.
2690 if (claimPlaceholder(BuiltinType::UnknownAny)) {
2691 SrcExpr = Self.checkUnknownAnyCast(DestRange, DestType,
2692 SrcExpr.get(), Kind,
2693 ValueKind, BasePath);
2694 return;
2695 }
2696
2697 // C99 6.5.4p2: the cast type needs to be void or scalar and the expression
2698 // type needs to be scalar.
2699 if (DestType->isVoidType()) {
2700 // We don't necessarily do lvalue-to-rvalue conversions on this.
2701 SrcExpr = Self.IgnoredValueConversions(SrcExpr.get());
2702 if (SrcExpr.isInvalid())
2703 return;
2704
2705 // Cast to void allows any expr type.
2706 Kind = CK_ToVoid;
2707 return;
2708 }
2709
2710 // Overloads are allowed with C extensions, so we need to support them.
2711 if (SrcExpr.get()->getType() == Self.Context.OverloadTy) {
2712 DeclAccessPair DAP;
2713 if (FunctionDecl *FD = Self.ResolveAddressOfOverloadedFunction(
2714 SrcExpr.get(), DestType, /*Complain=*/true, DAP))
2715 SrcExpr = Self.FixOverloadedFunctionReference(SrcExpr.get(), DAP, FD);
2716 else
2717 return;
2718 assert(SrcExpr.isUsable())((SrcExpr.isUsable()) ? static_cast<void> (0) : __assert_fail
("SrcExpr.isUsable()", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2718, __PRETTY_FUNCTION__))
;
2719 }
2720 SrcExpr = Self.DefaultFunctionArrayLvalueConversion(SrcExpr.get());
2721 if (SrcExpr.isInvalid())
2722 return;
2723 QualType SrcType = SrcExpr.get()->getType();
2724
2725 assert(!SrcType->isPlaceholderType())((!SrcType->isPlaceholderType()) ? static_cast<void>
(0) : __assert_fail ("!SrcType->isPlaceholderType()", "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 2725, __PRETTY_FUNCTION__))
;
2726
2727 checkAddressSpaceCast(SrcType, DestType);
2728 if (SrcExpr.isInvalid())
2729 return;
2730
2731 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2732 diag::err_typecheck_cast_to_incomplete)) {
2733 SrcExpr = ExprError();
2734 return;
2735 }
2736
2737 // Allow casting a sizeless built-in type to itself.
2738 if (DestType->isSizelessBuiltinType() &&
2739 Self.Context.hasSameUnqualifiedType(DestType, SrcType)) {
2740 Kind = CK_NoOp;
2741 return;
2742 }
2743
2744 if (!DestType->isScalarType() && !DestType->isVectorType()) {
2745 const RecordType *DestRecordTy = DestType->getAs<RecordType>();
2746
2747 if (DestRecordTy && Self.Context.hasSameUnqualifiedType(DestType, SrcType)){
2748 // GCC struct/union extension: allow cast to self.
2749 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_nonscalar)
2750 << DestType << SrcExpr.get()->getSourceRange();
2751 Kind = CK_NoOp;
2752 return;
2753 }
2754
2755 // GCC's cast to union extension.
2756 if (DestRecordTy && DestRecordTy->getDecl()->isUnion()) {
2757 RecordDecl *RD = DestRecordTy->getDecl();
2758 if (CastExpr::getTargetFieldForToUnionCast(RD, SrcType)) {
2759 Self.Diag(OpRange.getBegin(), diag::ext_typecheck_cast_to_union)
2760 << SrcExpr.get()->getSourceRange();
2761 Kind = CK_ToUnion;
2762 return;
2763 } else {
2764 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cast_to_union_no_type)
2765 << SrcType << SrcExpr.get()->getSourceRange();
2766 SrcExpr = ExprError();
2767 return;
2768 }
2769 }
2770
2771 // OpenCL v2.0 s6.13.10 - Allow casts from '0' to event_t type.
2772 if (Self.getLangOpts().OpenCL && DestType->isEventT()) {
2773 Expr::EvalResult Result;
2774 if (SrcExpr.get()->EvaluateAsInt(Result, Self.Context)) {
2775 llvm::APSInt CastInt = Result.Val.getInt();
2776 if (0 == CastInt) {
2777 Kind = CK_ZeroToOCLOpaqueType;
2778 return;
2779 }
2780 Self.Diag(OpRange.getBegin(),
2781 diag::err_opencl_cast_non_zero_to_event_t)
2782 << CastInt.toString(10) << SrcExpr.get()->getSourceRange();
2783 SrcExpr = ExprError();
2784 return;
2785 }
2786 }
2787
2788 // Reject any other conversions to non-scalar types.
2789 Self.Diag(OpRange.getBegin(), diag::err_typecheck_cond_expect_scalar)
2790 << DestType << SrcExpr.get()->getSourceRange();
2791 SrcExpr = ExprError();
2792 return;
2793 }
2794
2795 // The type we're casting to is known to be a scalar or vector.
2796
2797 // Require the operand to be a scalar or vector.
2798 if (!SrcType->isScalarType() && !SrcType->isVectorType()) {
2799 Self.Diag(SrcExpr.get()->getExprLoc(),
2800 diag::err_typecheck_expect_scalar_operand)
2801 << SrcType << SrcExpr.get()->getSourceRange();
2802 SrcExpr = ExprError();
2803 return;
2804 }
2805
2806 if (DestType->isExtVectorType()) {
2807 SrcExpr = Self.CheckExtVectorCast(OpRange, DestType, SrcExpr.get(), Kind);
2808 return;
2809 }
2810
2811 if (const VectorType *DestVecTy = DestType->getAs<VectorType>()) {
2812 if (DestVecTy->getVectorKind() == VectorType::AltiVecVector &&
2813 (SrcType->isIntegerType() || SrcType->isFloatingType())) {
2814 Kind = CK_VectorSplat;
2815 SrcExpr = Self.prepareVectorSplat(DestType, SrcExpr.get());
2816 } else if (Self.CheckVectorCast(OpRange, DestType, SrcType, Kind)) {
2817 SrcExpr = ExprError();
2818 }
2819 return;
2820 }
2821
2822 if (SrcType->isVectorType()) {
2823 if (Self.CheckVectorCast(OpRange, SrcType, DestType, Kind))
2824 SrcExpr = ExprError();
2825 return;
2826 }
2827
2828 // The source and target types are both scalars, i.e.
2829 // - arithmetic types (fundamental, enum, and complex)
2830 // - all kinds of pointers
2831 // Note that member pointers were filtered out with C++, above.
2832
2833 if (isa<ObjCSelectorExpr>(SrcExpr.get())) {
2834 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_selector_expr);
2835 SrcExpr = ExprError();
2836 return;
2837 }
2838
2839 // Can't cast to or from bfloat
2840 if (DestType->isBFloat16Type() && !SrcType->isBFloat16Type()) {
2841 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_to_bfloat16)
2842 << SrcExpr.get()->getSourceRange();
2843 SrcExpr = ExprError();
2844 return;
2845 }
2846 if (SrcType->isBFloat16Type() && !DestType->isBFloat16Type()) {
2847 Self.Diag(SrcExpr.get()->getExprLoc(), diag::err_cast_from_bfloat16)
2848 << SrcExpr.get()->getSourceRange();
2849 SrcExpr = ExprError();
2850 return;
2851 }
2852
2853 // If either type is a pointer, the other type has to be either an
2854 // integer or a pointer.
2855 if (!DestType->isArithmeticType()) {
2856 if (!SrcType->isIntegralType(Self.Context) && SrcType->isArithmeticType()) {
2857 Self.Diag(SrcExpr.get()->getExprLoc(),
2858 diag::err_cast_pointer_from_non_pointer_int)
2859 << SrcType << SrcExpr.get()->getSourceRange();
2860 SrcExpr = ExprError();
2861 return;
2862 }
2863 checkIntToPointerCast(/* CStyle */ true, OpRange, SrcExpr.get(), DestType,
2864 Self);
2865 } else if (!SrcType->isArithmeticType()) {
2866 if (!DestType->isIntegralType(Self.Context) &&
2867 DestType->isArithmeticType()) {
2868 Self.Diag(SrcExpr.get()->getBeginLoc(),
2869 diag::err_cast_pointer_to_non_pointer_int)
2870 << DestType << SrcExpr.get()->getSourceRange();
2871 SrcExpr = ExprError();
2872 return;
2873 }
2874
2875 if ((Self.Context.getTypeSize(SrcType) >
2876 Self.Context.getTypeSize(DestType)) &&
2877 !DestType->isBooleanType()) {
2878 // C 6.3.2.3p6: Any pointer type may be converted to an integer type.
2879 // Except as previously specified, the result is implementation-defined.
2880 // If the result cannot be represented in the integer type, the behavior
2881 // is undefined. The result need not be in the range of values of any
2882 // integer type.
2883 unsigned Diag;
2884 if (SrcType->isVoidPointerType())
2885 Diag = DestType->isEnumeralType() ? diag::warn_void_pointer_to_enum_cast
2886 : diag::warn_void_pointer_to_int_cast;
2887 else if (DestType->isEnumeralType())
2888 Diag = diag::warn_pointer_to_enum_cast;
2889 else
2890 Diag = diag::warn_pointer_to_int_cast;
2891 Self.Diag(OpRange.getBegin(), Diag) << SrcType << DestType << OpRange;
2892 }
2893 }
2894
2895 if (Self.getLangOpts().OpenCL &&
2896 !Self.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
2897 if (DestType->isHalfType()) {
2898 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::err_opencl_cast_to_half)
2899 << DestType << SrcExpr.get()->getSourceRange();
2900 SrcExpr = ExprError();
2901 return;
2902 }
2903 }
2904
2905 // ARC imposes extra restrictions on casts.
2906 if (Self.getLangOpts().allowsNonTrivialObjCLifetimeQualifiers()) {
2907 checkObjCConversion(Sema::CCK_CStyleCast);
2908 if (SrcExpr.isInvalid())
2909 return;
2910
2911 const PointerType *CastPtr = DestType->getAs<PointerType>();
2912 if (Self.getLangOpts().ObjCAutoRefCount && CastPtr) {
2913 if (const PointerType *ExprPtr = SrcType->getAs<PointerType>()) {
2914 Qualifiers CastQuals = CastPtr->getPointeeType().getQualifiers();
2915 Qualifiers ExprQuals = ExprPtr->getPointeeType().getQualifiers();
2916 if (CastPtr->getPointeeType()->isObjCLifetimeType() &&
2917 ExprPtr->getPointeeType()->isObjCLifetimeType() &&
2918 !CastQuals.compatiblyIncludesObjCLifetime(ExprQuals)) {
2919 Self.Diag(SrcExpr.get()->getBeginLoc(),
2920 diag::err_typecheck_incompatible_ownership)
2921 << SrcType << DestType << Sema::AA_Casting
2922 << SrcExpr.get()->getSourceRange();
2923 return;
2924 }
2925 }
2926 }
2927 else if (!Self.CheckObjCARCUnavailableWeakConversion(DestType, SrcType)) {
2928 Self.Diag(SrcExpr.get()->getBeginLoc(),
2929 diag::err_arc_convesion_of_weak_unavailable)
2930 << 1 << SrcType << DestType << SrcExpr.get()->getSourceRange();
2931 SrcExpr = ExprError();
2932 return;
2933 }
2934 }
2935
2936 DiagnoseCastOfObjCSEL(Self, SrcExpr, DestType);
2937 DiagnoseCallingConvCast(Self, SrcExpr, DestType, OpRange);
2938 DiagnoseBadFunctionCast(Self, SrcExpr, DestType);
2939 Kind = Self.PrepareScalarCast(SrcExpr, DestType);
2940 if (SrcExpr.isInvalid())
2941 return;
2942
2943 if (Kind == CK_BitCast)
2944 checkCastAlign();
2945}
2946
2947void CastOperation::CheckBuiltinBitCast() {
2948 QualType SrcType = SrcExpr.get()->getType();
2949
2950 if (Self.RequireCompleteType(OpRange.getBegin(), DestType,
2951 diag::err_typecheck_cast_to_incomplete) ||
2952 Self.RequireCompleteType(OpRange.getBegin(), SrcType,
2953 diag::err_incomplete_type)) {
2954 SrcExpr = ExprError();
2955 return;
2956 }
2957
2958 if (SrcExpr.get()->isRValue())
2959 SrcExpr = Self.CreateMaterializeTemporaryExpr(SrcType, SrcExpr.get(),
2960 /*IsLValueReference=*/false);
2961
2962 CharUnits DestSize = Self.Context.getTypeSizeInChars(DestType);
2963 CharUnits SourceSize = Self.Context.getTypeSizeInChars(SrcType);
2964 if (DestSize != SourceSize) {
2965 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_type_size_mismatch)
2966 << (int)SourceSize.getQuantity() << (int)DestSize.getQuantity();
2967 SrcExpr = ExprError();
2968 return;
2969 }
2970
2971 if (!DestType.isTriviallyCopyableType(Self.Context)) {
2972 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2973 << 1;
2974 SrcExpr = ExprError();
2975 return;
2976 }
2977
2978 if (!SrcType.isTriviallyCopyableType(Self.Context)) {
2979 Self.Diag(OpRange.getBegin(), diag::err_bit_cast_non_trivially_copyable)
2980 << 0;
2981 SrcExpr = ExprError();
2982 return;
2983 }
2984
2985 Kind = CK_LValueToRValueBitCast;
2986}
2987
2988/// DiagnoseCastQual - Warn whenever casts discards a qualifiers, be it either
2989/// const, volatile or both.
2990static void DiagnoseCastQual(Sema &Self, const ExprResult &SrcExpr,
2991 QualType DestType) {
2992 if (SrcExpr.isInvalid())
2993 return;
2994
2995 QualType SrcType = SrcExpr.get()->getType();
2996 if (!((SrcType->isAnyPointerType() && DestType->isAnyPointerType()) ||
2997 DestType->isLValueReferenceType()))
2998 return;
2999
3000 QualType TheOffendingSrcType, TheOffendingDestType;
3001 Qualifiers CastAwayQualifiers;
3002 if (CastsAwayConstness(Self, SrcType, DestType, true, false,
3003 &TheOffendingSrcType, &TheOffendingDestType,
3004 &CastAwayQualifiers) !=
3005 CastAwayConstnessKind::CACK_Similar)
3006 return;
3007
3008 // FIXME: 'restrict' is not properly handled here.
3009 int qualifiers = -1;
3010 if (CastAwayQualifiers.hasConst() && CastAwayQualifiers.hasVolatile()) {
3011 qualifiers = 0;
3012 } else if (CastAwayQualifiers.hasConst()) {
3013 qualifiers = 1;
3014 } else if (CastAwayQualifiers.hasVolatile()) {
3015 qualifiers = 2;
3016 }
3017 // This is a variant of int **x; const int **y = (const int **)x;
3018 if (qualifiers == -1)
3019 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual2)
3020 << SrcType << DestType;
3021 else
3022 Self.Diag(SrcExpr.get()->getBeginLoc(), diag::warn_cast_qual)
3023 << TheOffendingSrcType << TheOffendingDestType << qualifiers;
3024}
3025
3026ExprResult Sema::BuildCStyleCastExpr(SourceLocation LPLoc,
3027 TypeSourceInfo *CastTypeInfo,
3028 SourceLocation RPLoc,
3029 Expr *CastExpr) {
3030 CastOperation Op(*this, CastTypeInfo->getType(), CastExpr);
3031 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3032 Op.OpRange = SourceRange(LPLoc, CastExpr->getEndLoc());
3033
3034 if (getLangOpts().CPlusPlus) {
3035 Op.CheckCXXCStyleCast(/*FunctionalCast=*/ false,
3036 isa<InitListExpr>(CastExpr));
3037 } else {
3038 Op.CheckCStyleCast();
3039 }
3040
3041 if (Op.SrcExpr.isInvalid())
3042 return ExprError();
3043
3044 // -Wcast-qual
3045 DiagnoseCastQual(Op.Self, Op.SrcExpr, Op.DestType);
3046
3047 return Op.complete(CStyleCastExpr::Create(
3048 Context, Op.ResultType, Op.ValueKind, Op.Kind, Op.SrcExpr.get(),
3049 &Op.BasePath, CurFPFeatureOverrides(), CastTypeInfo, LPLoc, RPLoc));
3050}
3051
3052ExprResult Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
3053 QualType Type,
3054 SourceLocation LPLoc,
3055 Expr *CastExpr,
3056 SourceLocation RPLoc) {
3057 assert(LPLoc.isValid() && "List-initialization shouldn't get here.")((LPLoc.isValid() && "List-initialization shouldn't get here."
) ? static_cast<void> (0) : __assert_fail ("LPLoc.isValid() && \"List-initialization shouldn't get here.\""
, "/build/llvm-toolchain-snapshot-12~++20200926111128+c6c5629f2fb/clang/lib/Sema/SemaCast.cpp"
, 3057, __PRETTY_FUNCTION__))
;
3058 CastOperation Op(*this, Type, CastExpr);
3059 Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
3060 Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
3061
3062 Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
3063 if (Op.SrcExpr.isInvalid())
3064 return ExprError();
3065
3066 auto *SubExpr = Op.SrcExpr.get();
3067 if (auto *BindExpr = dyn_cast<CXXBindTemporaryExpr>(SubExpr))
3068 SubExpr = BindExpr->getSubExpr();
3069 if (auto *ConstructExpr = dyn_cast<CXXConstructExpr>(SubExpr))
3070 ConstructExpr->setParenOrBraceRange(SourceRange(LPLoc, RPLoc));
3071
3072 return Op.complete(CXXFunctionalCastExpr::Create(
3073 Context, Op.ResultType, Op.ValueKind, CastTypeInfo, Op.Kind,
3074 Op.SrcExpr.get(), &Op.BasePath, CurFPFeatureOverrides(), LPLoc, RPLoc));
3075}

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