clang 10.0.0git

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