35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/SmallBitVector.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/Support/ConvertUTF.h"
39 #include "llvm/Support/raw_ostream.h"
41 using namespace clang;
45 unsigned ByteNo)
const {
54 if (argCount == desiredArgCount)
return false;
56 if (argCount < desiredArgCount)
57 return S.
Diag(call->
getLocEnd(), diag::err_typecheck_call_too_few_args)
58 << 0 << desiredArgCount << argCount
59 << call->getSourceRange();
63 call->
getArg(argCount - 1)->getLocEnd());
65 return S.
Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
66 << 0 << desiredArgCount << argCount
67 << call->
getArg(1)->getSourceRange();
80 S.
Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
81 << ValArg->getSourceRange();
88 if (!Literal || !Literal->
isAscii()) {
89 S.
Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
90 << StrArg->getSourceRange();
106 if (ResultType.isNull())
109 TheCall->
setArg(0, Arg.get());
115 CallExpr *TheCall,
unsigned SizeIdx,
116 unsigned DstSizeIdx) {
121 const Expr *SizeArg = TheCall->
getArg(SizeIdx);
122 const Expr *DstSizeArg = TheCall->
getArg(DstSizeIdx);
124 llvm::APSInt Size, DstSize;
131 if (Size.ule(DstSize))
139 S.
Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
151 if (Call->getStmtClass() != Stmt::CallExprClass) {
152 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
153 << Call->getSourceRange();
157 auto CE = cast<CallExpr>(Call);
158 if (CE->getCallee()->getType()->isBlockPointerType()) {
159 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
160 << Call->getSourceRange();
164 const Decl *TargetDecl = CE->getCalleeDecl();
165 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
166 if (FD->getBuiltinID()) {
167 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
168 << Call->getSourceRange();
172 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
173 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
174 << Call->getSourceRange();
182 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
183 << Chain->getSourceRange();
196 BuiltinCall->
setType(CE->getType());
200 BuiltinCall->
setArg(1, ChainResult.
get());
217 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
220 << DRE->getDecl()->getIdentifier();
228 Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
233 unsigned ICEArguments = 0;
240 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
242 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
245 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
247 ICEArguments &= ~(1 << ArgNo);
251 case Builtin::BI__builtin___CFStringMakeConstantString:
253 "Wrong # arguments to builtin CFStringMakeConstantString");
254 if (CheckObjCString(TheCall->
getArg(0)))
257 case Builtin::BI__builtin_stdarg_start:
258 case Builtin::BI__builtin_va_start:
259 if (SemaBuiltinVAStart(TheCall))
262 case Builtin::BI__va_start: {
264 case llvm::Triple::arm:
265 case llvm::Triple::thumb:
266 if (SemaBuiltinVAStartARM(TheCall))
270 if (SemaBuiltinVAStart(TheCall))
276 case Builtin::BI__builtin_isgreater:
277 case Builtin::BI__builtin_isgreaterequal:
278 case Builtin::BI__builtin_isless:
279 case Builtin::BI__builtin_islessequal:
280 case Builtin::BI__builtin_islessgreater:
281 case Builtin::BI__builtin_isunordered:
282 if (SemaBuiltinUnorderedCompare(TheCall))
285 case Builtin::BI__builtin_fpclassify:
286 if (SemaBuiltinFPClassification(TheCall, 6))
289 case Builtin::BI__builtin_isfinite:
290 case Builtin::BI__builtin_isinf:
291 case Builtin::BI__builtin_isinf_sign:
292 case Builtin::BI__builtin_isnan:
293 case Builtin::BI__builtin_isnormal:
294 if (SemaBuiltinFPClassification(TheCall, 1))
297 case Builtin::BI__builtin_shufflevector:
298 return SemaBuiltinShuffleVector(TheCall);
301 case Builtin::BI__builtin_prefetch:
302 if (SemaBuiltinPrefetch(TheCall))
305 case Builtin::BI__assume:
306 case Builtin::BI__builtin_assume:
307 if (SemaBuiltinAssume(TheCall))
310 case Builtin::BI__builtin_assume_aligned:
311 if (SemaBuiltinAssumeAligned(TheCall))
314 case Builtin::BI__builtin_object_size:
315 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
318 case Builtin::BI__builtin_longjmp:
319 if (SemaBuiltinLongjmp(TheCall))
322 case Builtin::BI__builtin_setjmp:
323 if (SemaBuiltinSetjmp(TheCall))
326 case Builtin::BI_setjmp:
327 case Builtin::BI_setjmpex:
332 case Builtin::BI__builtin_classify_type:
336 case Builtin::BI__builtin_constant_p:
340 case Builtin::BI__sync_fetch_and_add:
341 case Builtin::BI__sync_fetch_and_add_1:
342 case Builtin::BI__sync_fetch_and_add_2:
343 case Builtin::BI__sync_fetch_and_add_4:
344 case Builtin::BI__sync_fetch_and_add_8:
345 case Builtin::BI__sync_fetch_and_add_16:
346 case Builtin::BI__sync_fetch_and_sub:
347 case Builtin::BI__sync_fetch_and_sub_1:
348 case Builtin::BI__sync_fetch_and_sub_2:
349 case Builtin::BI__sync_fetch_and_sub_4:
350 case Builtin::BI__sync_fetch_and_sub_8:
351 case Builtin::BI__sync_fetch_and_sub_16:
352 case Builtin::BI__sync_fetch_and_or:
353 case Builtin::BI__sync_fetch_and_or_1:
354 case Builtin::BI__sync_fetch_and_or_2:
355 case Builtin::BI__sync_fetch_and_or_4:
356 case Builtin::BI__sync_fetch_and_or_8:
357 case Builtin::BI__sync_fetch_and_or_16:
358 case Builtin::BI__sync_fetch_and_and:
359 case Builtin::BI__sync_fetch_and_and_1:
360 case Builtin::BI__sync_fetch_and_and_2:
361 case Builtin::BI__sync_fetch_and_and_4:
362 case Builtin::BI__sync_fetch_and_and_8:
363 case Builtin::BI__sync_fetch_and_and_16:
364 case Builtin::BI__sync_fetch_and_xor:
365 case Builtin::BI__sync_fetch_and_xor_1:
366 case Builtin::BI__sync_fetch_and_xor_2:
367 case Builtin::BI__sync_fetch_and_xor_4:
368 case Builtin::BI__sync_fetch_and_xor_8:
369 case Builtin::BI__sync_fetch_and_xor_16:
370 case Builtin::BI__sync_fetch_and_nand:
371 case Builtin::BI__sync_fetch_and_nand_1:
372 case Builtin::BI__sync_fetch_and_nand_2:
373 case Builtin::BI__sync_fetch_and_nand_4:
374 case Builtin::BI__sync_fetch_and_nand_8:
375 case Builtin::BI__sync_fetch_and_nand_16:
376 case Builtin::BI__sync_add_and_fetch:
377 case Builtin::BI__sync_add_and_fetch_1:
378 case Builtin::BI__sync_add_and_fetch_2:
379 case Builtin::BI__sync_add_and_fetch_4:
380 case Builtin::BI__sync_add_and_fetch_8:
381 case Builtin::BI__sync_add_and_fetch_16:
382 case Builtin::BI__sync_sub_and_fetch:
383 case Builtin::BI__sync_sub_and_fetch_1:
384 case Builtin::BI__sync_sub_and_fetch_2:
385 case Builtin::BI__sync_sub_and_fetch_4:
386 case Builtin::BI__sync_sub_and_fetch_8:
387 case Builtin::BI__sync_sub_and_fetch_16:
388 case Builtin::BI__sync_and_and_fetch:
389 case Builtin::BI__sync_and_and_fetch_1:
390 case Builtin::BI__sync_and_and_fetch_2:
391 case Builtin::BI__sync_and_and_fetch_4:
392 case Builtin::BI__sync_and_and_fetch_8:
393 case Builtin::BI__sync_and_and_fetch_16:
394 case Builtin::BI__sync_or_and_fetch:
395 case Builtin::BI__sync_or_and_fetch_1:
396 case Builtin::BI__sync_or_and_fetch_2:
397 case Builtin::BI__sync_or_and_fetch_4:
398 case Builtin::BI__sync_or_and_fetch_8:
399 case Builtin::BI__sync_or_and_fetch_16:
400 case Builtin::BI__sync_xor_and_fetch:
401 case Builtin::BI__sync_xor_and_fetch_1:
402 case Builtin::BI__sync_xor_and_fetch_2:
403 case Builtin::BI__sync_xor_and_fetch_4:
404 case Builtin::BI__sync_xor_and_fetch_8:
405 case Builtin::BI__sync_xor_and_fetch_16:
406 case Builtin::BI__sync_nand_and_fetch:
407 case Builtin::BI__sync_nand_and_fetch_1:
408 case Builtin::BI__sync_nand_and_fetch_2:
409 case Builtin::BI__sync_nand_and_fetch_4:
410 case Builtin::BI__sync_nand_and_fetch_8:
411 case Builtin::BI__sync_nand_and_fetch_16:
412 case Builtin::BI__sync_val_compare_and_swap:
413 case Builtin::BI__sync_val_compare_and_swap_1:
414 case Builtin::BI__sync_val_compare_and_swap_2:
415 case Builtin::BI__sync_val_compare_and_swap_4:
416 case Builtin::BI__sync_val_compare_and_swap_8:
417 case Builtin::BI__sync_val_compare_and_swap_16:
418 case Builtin::BI__sync_bool_compare_and_swap:
419 case Builtin::BI__sync_bool_compare_and_swap_1:
420 case Builtin::BI__sync_bool_compare_and_swap_2:
421 case Builtin::BI__sync_bool_compare_and_swap_4:
422 case Builtin::BI__sync_bool_compare_and_swap_8:
423 case Builtin::BI__sync_bool_compare_and_swap_16:
424 case Builtin::BI__sync_lock_test_and_set:
425 case Builtin::BI__sync_lock_test_and_set_1:
426 case Builtin::BI__sync_lock_test_and_set_2:
427 case Builtin::BI__sync_lock_test_and_set_4:
428 case Builtin::BI__sync_lock_test_and_set_8:
429 case Builtin::BI__sync_lock_test_and_set_16:
430 case Builtin::BI__sync_lock_release:
431 case Builtin::BI__sync_lock_release_1:
432 case Builtin::BI__sync_lock_release_2:
433 case Builtin::BI__sync_lock_release_4:
434 case Builtin::BI__sync_lock_release_8:
435 case Builtin::BI__sync_lock_release_16:
436 case Builtin::BI__sync_swap:
437 case Builtin::BI__sync_swap_1:
438 case Builtin::BI__sync_swap_2:
439 case Builtin::BI__sync_swap_4:
440 case Builtin::BI__sync_swap_8:
441 case Builtin::BI__sync_swap_16:
442 return SemaBuiltinAtomicOverloaded(TheCallResult);
443 #define BUILTIN(ID, TYPE, ATTRS)
444 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
445 case Builtin::BI##ID: \
446 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
447 #include "clang/Basic/Builtins.def"
448 case Builtin::BI__builtin_annotation:
452 case Builtin::BI__builtin_addressof:
456 case Builtin::BI__builtin_operator_new:
457 case Builtin::BI__builtin_operator_delete:
460 << (BuiltinID == Builtin::BI__builtin_operator_new
461 ?
"__builtin_operator_new"
462 :
"__builtin_operator_delete")
468 DeclareGlobalNewDelete();
473 case Builtin::BI__builtin___memcpy_chk:
474 case Builtin::BI__builtin___memmove_chk:
475 case Builtin::BI__builtin___memset_chk:
476 case Builtin::BI__builtin___strlcat_chk:
477 case Builtin::BI__builtin___strlcpy_chk:
478 case Builtin::BI__builtin___strncat_chk:
479 case Builtin::BI__builtin___strncpy_chk:
480 case Builtin::BI__builtin___stpncpy_chk:
483 case Builtin::BI__builtin___memccpy_chk:
486 case Builtin::BI__builtin___snprintf_chk:
487 case Builtin::BI__builtin___vsnprintf_chk:
491 case Builtin::BI__builtin_call_with_static_chain:
496 case Builtin::BI__exception_code:
497 case Builtin::BI_exception_code: {
499 diag::err_seh___except_block))
503 case Builtin::BI__exception_info:
504 case Builtin::BI_exception_info: {
506 diag::err_seh___except_filter))
511 case Builtin::BI__GetExceptionInfo:
515 if (CheckCXXThrowOperand(
530 case llvm::Triple::arm:
531 case llvm::Triple::armeb:
532 case llvm::Triple::thumb:
533 case llvm::Triple::thumbeb:
534 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
537 case llvm::Triple::aarch64:
538 case llvm::Triple::aarch64_be:
539 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
542 case llvm::Triple::mips:
543 case llvm::Triple::mipsel:
544 case llvm::Triple::mips64:
545 case llvm::Triple::mips64el:
546 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
549 case llvm::Triple::systemz:
550 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
553 case llvm::Triple::x86:
554 case llvm::Triple::x86_64:
555 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
558 case llvm::Triple::ppc:
559 case llvm::Triple::ppc64:
560 case llvm::Triple::ppc64le:
561 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
569 return TheCallResult;
573 static unsigned RFT(
unsigned t,
bool shift =
false,
bool ForceQuad =
false) {
575 int IsQuad = ForceQuad ?
true : Type.
isQuad();
579 return shift ? 7 : (8 << IsQuad) - 1;
582 return shift ? 15 : (4 << IsQuad) - 1;
584 return shift ? 31 : (2 << IsQuad) - 1;
587 return shift ? 63 : (1 << IsQuad) - 1;
589 return shift ? 127 : (1 << IsQuad) - 1;
591 assert(!shift &&
"cannot shift float types!");
592 return (4 << IsQuad) - 1;
594 assert(!shift &&
"cannot shift float types!");
595 return (2 << IsQuad) - 1;
597 assert(!shift &&
"cannot shift float types!");
598 return (1 << IsQuad) - 1;
600 llvm_unreachable(
"Invalid NeonTypeFlag!");
607 bool IsPolyUnsigned,
bool IsInt64Long) {
639 llvm_unreachable(
"Invalid NeonTypeFlag!");
642 bool Sema::CheckNeonBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
647 bool HasConstPtr =
false;
649 #define GET_NEON_OVERLOAD_CHECK
650 #include "clang/Basic/arm_neon.inc"
651 #undef GET_NEON_OVERLOAD_CHECK
658 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
661 TV = Result.getLimitedValue(64);
662 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
664 << TheCall->
getArg(ImmArg)->getSourceRange();
667 if (PtrArgNum >= 0) {
671 Arg = ICE->getSubExpr();
672 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
676 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
684 AssignConvertType ConvTy;
685 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
688 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
689 RHS.
get(), AA_Assigning))
695 unsigned i = 0, l = 0, u = 0;
699 #define GET_NEON_IMMEDIATE_CHECK
700 #include "clang/Basic/arm_neon.inc"
701 #undef GET_NEON_IMMEDIATE_CHECK
704 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
707 bool Sema::CheckARMBuiltinExclusiveCall(
unsigned BuiltinID,
CallExpr *TheCall,
709 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
710 BuiltinID == ARM::BI__builtin_arm_ldaex ||
711 BuiltinID == ARM::BI__builtin_arm_strex ||
712 BuiltinID == ARM::BI__builtin_arm_stlex ||
713 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
714 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
715 BuiltinID == AArch64::BI__builtin_arm_strex ||
716 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
717 "unexpected ARM builtin");
718 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
719 BuiltinID == ARM::BI__builtin_arm_ldaex ||
720 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
721 BuiltinID == AArch64::BI__builtin_arm_ldaex;
733 Expr *PointerArg = TheCall->
getArg(IsLdrex ? 0 : 1);
734 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
737 PointerArg = PointerArgRes.
get();
742 << PointerArg->
getType() << PointerArg->getSourceRange();
758 Diag(DRE->
getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
761 << AA_Passing << PointerArg->getSourceRange();
766 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
769 PointerArg = PointerArgRes.
get();
771 TheCall->
setArg(IsLdrex ? 0 : 1, PointerArg);
776 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
777 << PointerArg->
getType() << PointerArg->getSourceRange();
783 assert(MaxWidth == 64 &&
"Diagnostic unexpectedly inaccurate");
784 Diag(DRE->
getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
785 << PointerArg->
getType() << PointerArg->getSourceRange();
799 << ValType << PointerArg->getSourceRange();
813 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
824 bool Sema::CheckARMBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
827 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
828 BuiltinID == ARM::BI__builtin_arm_ldaex ||
829 BuiltinID == ARM::BI__builtin_arm_strex ||
830 BuiltinID == ARM::BI__builtin_arm_stlex) {
831 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
834 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
835 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
836 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
839 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
840 BuiltinID == ARM::BI__builtin_arm_wsr64)
841 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3,
false);
843 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
844 BuiltinID == ARM::BI__builtin_arm_rsrp ||
845 BuiltinID == ARM::BI__builtin_arm_wsr ||
846 BuiltinID == ARM::BI__builtin_arm_wsrp)
847 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
849 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
854 unsigned i = 0, l = 0, u = 0;
856 default:
return false;
857 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31;
break;
858 case ARM::BI__builtin_arm_usat: i = 1; u = 31;
break;
859 case ARM::BI__builtin_arm_vcvtr_f:
860 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1;
break;
861 case ARM::BI__builtin_arm_dmb:
862 case ARM::BI__builtin_arm_dsb:
863 case ARM::BI__builtin_arm_isb:
864 case ARM::BI__builtin_arm_dbg: l = 0; u = 15;
break;
868 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
871 bool Sema::CheckAArch64BuiltinFunctionCall(
unsigned BuiltinID,
875 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
876 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
877 BuiltinID == AArch64::BI__builtin_arm_strex ||
878 BuiltinID == AArch64::BI__builtin_arm_stlex) {
879 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
882 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
883 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
884 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
885 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
886 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
889 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
890 BuiltinID == AArch64::BI__builtin_arm_wsr64)
891 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
false);
893 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
894 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
895 BuiltinID == AArch64::BI__builtin_arm_wsr ||
896 BuiltinID == AArch64::BI__builtin_arm_wsrp)
897 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
899 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
904 unsigned i = 0, l = 0, u = 0;
906 default:
return false;
907 case AArch64::BI__builtin_arm_dmb:
908 case AArch64::BI__builtin_arm_dsb:
909 case AArch64::BI__builtin_arm_isb: l = 0; u = 15;
break;
912 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
915 bool Sema::CheckMipsBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
916 unsigned i = 0, l = 0, u = 0;
918 default:
return false;
919 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63;
break;
920 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63;
break;
921 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31;
break;
922 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3;
break;
923 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31;
break;
924 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31;
break;
925 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31;
break;
928 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
931 bool Sema::CheckPPCBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
932 unsigned i = 0, l = 0, u = 0;
933 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
934 BuiltinID == PPC::BI__builtin_divdeu ||
935 BuiltinID == PPC::BI__builtin_bpermd;
939 .getIntPtrType()) == 64;
940 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
941 BuiltinID == PPC::BI__builtin_divweu ||
942 BuiltinID == PPC::BI__builtin_divde ||
943 BuiltinID == PPC::BI__builtin_divdeu;
945 if (Is64BitBltin && !IsTarget64Bit)
946 return Diag(TheCall->
getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
947 << TheCall->getSourceRange();
950 (BuiltinID == PPC::BI__builtin_bpermd &&
952 return Diag(TheCall->
getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
953 << TheCall->getSourceRange();
956 default:
return false;
957 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
958 case PPC::BI__builtin_altivec_crypto_vshasigmad:
959 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
960 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
961 case PPC::BI__builtin_tbegin:
962 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1;
break;
963 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7;
break;
964 case PPC::BI__builtin_tabortwc:
965 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31;
break;
966 case PPC::BI__builtin_tabortwci:
967 case PPC::BI__builtin_tabortdci:
968 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
969 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
974 bool Sema::CheckSystemZBuiltinFunctionCall(
unsigned BuiltinID,
976 if (BuiltinID == SystemZ::BI__builtin_tabort) {
978 llvm::APSInt AbortCode(32);
980 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
981 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
982 << Arg->getSourceRange();
987 unsigned i = 0, l = 0, u = 0;
989 default:
return false;
990 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15;
break;
991 case SystemZ::BI__builtin_s390_verimb:
992 case SystemZ::BI__builtin_s390_verimh:
993 case SystemZ::BI__builtin_s390_verimf:
994 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255;
break;
995 case SystemZ::BI__builtin_s390_vfaeb:
996 case SystemZ::BI__builtin_s390_vfaeh:
997 case SystemZ::BI__builtin_s390_vfaef:
998 case SystemZ::BI__builtin_s390_vfaebs:
999 case SystemZ::BI__builtin_s390_vfaehs:
1000 case SystemZ::BI__builtin_s390_vfaefs:
1001 case SystemZ::BI__builtin_s390_vfaezb:
1002 case SystemZ::BI__builtin_s390_vfaezh:
1003 case SystemZ::BI__builtin_s390_vfaezf:
1004 case SystemZ::BI__builtin_s390_vfaezbs:
1005 case SystemZ::BI__builtin_s390_vfaezhs:
1006 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15;
break;
1007 case SystemZ::BI__builtin_s390_vfidb:
1008 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1009 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1010 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095;
break;
1011 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15;
break;
1012 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15;
break;
1013 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15;
break;
1014 case SystemZ::BI__builtin_s390_vstrcb:
1015 case SystemZ::BI__builtin_s390_vstrch:
1016 case SystemZ::BI__builtin_s390_vstrcf:
1017 case SystemZ::BI__builtin_s390_vstrczb:
1018 case SystemZ::BI__builtin_s390_vstrczh:
1019 case SystemZ::BI__builtin_s390_vstrczf:
1020 case SystemZ::BI__builtin_s390_vstrcbs:
1021 case SystemZ::BI__builtin_s390_vstrchs:
1022 case SystemZ::BI__builtin_s390_vstrcfs:
1023 case SystemZ::BI__builtin_s390_vstrczbs:
1024 case SystemZ::BI__builtin_s390_vstrczhs:
1025 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15;
break;
1027 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1030 bool Sema::CheckX86BuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1031 unsigned i = 0, l = 0, u = 0;
1032 switch (BuiltinID) {
1033 default:
return false;
1034 case X86::BI__builtin_cpu_supports:
1035 return SemaBuiltinCpuSupports(TheCall);
1036 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3;
break;
1037 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3;
break;
1038 case X86::BI__builtin_ia32_vpermil2pd:
1039 case X86::BI__builtin_ia32_vpermil2pd256:
1040 case X86::BI__builtin_ia32_vpermil2ps:
1041 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3;
break;
1042 case X86::BI__builtin_ia32_cmpb128_mask:
1043 case X86::BI__builtin_ia32_cmpw128_mask:
1044 case X86::BI__builtin_ia32_cmpd128_mask:
1045 case X86::BI__builtin_ia32_cmpq128_mask:
1046 case X86::BI__builtin_ia32_cmpb256_mask:
1047 case X86::BI__builtin_ia32_cmpw256_mask:
1048 case X86::BI__builtin_ia32_cmpd256_mask:
1049 case X86::BI__builtin_ia32_cmpq256_mask:
1050 case X86::BI__builtin_ia32_cmpb512_mask:
1051 case X86::BI__builtin_ia32_cmpw512_mask:
1052 case X86::BI__builtin_ia32_cmpd512_mask:
1053 case X86::BI__builtin_ia32_cmpq512_mask:
1054 case X86::BI__builtin_ia32_ucmpb128_mask:
1055 case X86::BI__builtin_ia32_ucmpw128_mask:
1056 case X86::BI__builtin_ia32_ucmpd128_mask:
1057 case X86::BI__builtin_ia32_ucmpq128_mask:
1058 case X86::BI__builtin_ia32_ucmpb256_mask:
1059 case X86::BI__builtin_ia32_ucmpw256_mask:
1060 case X86::BI__builtin_ia32_ucmpd256_mask:
1061 case X86::BI__builtin_ia32_ucmpq256_mask:
1062 case X86::BI__builtin_ia32_ucmpb512_mask:
1063 case X86::BI__builtin_ia32_ucmpw512_mask:
1064 case X86::BI__builtin_ia32_ucmpd512_mask:
1065 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7;
break;
1066 case X86::BI__builtin_ia32_roundps:
1067 case X86::BI__builtin_ia32_roundpd:
1068 case X86::BI__builtin_ia32_roundps256:
1069 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15;
break;
1070 case X86::BI__builtin_ia32_roundss:
1071 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15;
break;
1072 case X86::BI__builtin_ia32_cmpps:
1073 case X86::BI__builtin_ia32_cmpss:
1074 case X86::BI__builtin_ia32_cmppd:
1075 case X86::BI__builtin_ia32_cmpsd:
1076 case X86::BI__builtin_ia32_cmpps256:
1077 case X86::BI__builtin_ia32_cmppd256:
1078 case X86::BI__builtin_ia32_cmpps512_mask:
1079 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31;
break;
1080 case X86::BI__builtin_ia32_vpcomub:
1081 case X86::BI__builtin_ia32_vpcomuw:
1082 case X86::BI__builtin_ia32_vpcomud:
1083 case X86::BI__builtin_ia32_vpcomuq:
1084 case X86::BI__builtin_ia32_vpcomb:
1085 case X86::BI__builtin_ia32_vpcomw:
1086 case X86::BI__builtin_ia32_vpcomd:
1087 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7;
break;
1089 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1096 bool Sema::getFormatStringInfo(
const FormatAttr *Format,
bool IsCXXMember,
1097 FormatStringInfo *FSI) {
1098 FSI->HasVAListArg = Format->getFirstArg() == 0;
1099 FSI->FormatIdx = Format->getFormatIdx() - 1;
1100 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1106 if(FSI->FormatIdx == 0)
1109 if (FSI->FirstDataArg != 0)
1110 --FSI->FirstDataArg;
1121 if (
auto nullability
1130 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1132 dyn_cast<CompoundLiteralExpr>(Expr))
1134 dyn_cast<InitListExpr>(CLE->getInitializer()))
1135 Expr = ILE->getInit(0);
1145 const Expr *ArgExpr,
1148 S.
Diag(CallSiteLoc, diag::warn_null_arg) << ArgExpr->getSourceRange();
1152 FormatStringInfo FSI;
1153 if ((GetFormatStringType(Format) == FST_NSString) &&
1154 getFormatStringInfo(Format,
false, &FSI)) {
1155 Idx = FSI.FormatIdx;
1168 bool Format =
false;
1181 if (!Format || NumArgs <= Idx)
1183 const Expr *FormatExpr = Args[Idx];
1184 if (
const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1185 FormatExpr = CSCE->getSubExpr();
1195 S.
Diag(FormatExpr->
getExprLoc(), diag::warn_objc_cdirective_format_string)
1215 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
1218 llvm::SmallBitVector NonNullArgs;
1224 for (
const auto *Arg : Args)
1230 for (
unsigned Val :
NonNull->args()) {
1231 if (Val >= Args.size())
1233 if (NonNullArgs.empty())
1234 NonNullArgs.resize(Args.size());
1235 NonNullArgs.set(Val);
1240 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1244 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1245 parms = FD->parameters();
1247 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1249 unsigned ParamIndex = 0;
1251 I != E; ++I, ++ParamIndex) {
1253 if (PVD->
hasAttr<NonNullAttr>() ||
1255 if (NonNullArgs.empty())
1256 NonNullArgs.resize(Args.size());
1258 NonNullArgs.set(ParamIndex);
1265 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1284 if (NonNullArgs.empty())
1285 NonNullArgs.resize(Args.size());
1287 NonNullArgs.set(Index);
1296 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1297 ArgIndex != ArgIndexEnd; ++ArgIndex) {
1298 if (NonNullArgs[ArgIndex])
1308 VariadicCallType CallType) {
1310 if (CurContext->isDependentContext())
1314 llvm::SmallBitVector CheckedVarArgs;
1318 CheckedVarArgs.resize(Args.size());
1320 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
1327 if (CallType != VariadicDoesNotApply) {
1329 : FDecl && isa<FunctionDecl>(FDecl)
1330 ? cast<FunctionDecl>(FDecl)->getNumParams()
1331 : FDecl && isa<ObjCMethodDecl>(FDecl)
1332 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1335 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1337 if (
const Expr *Arg = Args[ArgIdx]) {
1338 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1339 checkVariadicArgument(Arg, CallType);
1344 if (FDecl || Proto) {
1349 for (
const auto *I : FDecl->
specific_attrs<ArgumentWithTypeTagAttr>())
1350 CheckArgumentWithTypeTag(I, Args.data());
1361 VariadicCallType CallType =
1362 Proto->
isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1363 checkCall(FDecl, Proto, Args,
true, Loc,
SourceRange(),
1371 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1372 isa<CXXMethodDecl>(FDecl);
1373 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1374 IsMemberOperatorCall;
1375 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1379 if (IsMemberOperatorCall) {
1386 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1388 TheCall->
getCallee()->getSourceRange(), CallType);
1396 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1397 if (getLangOpts().ObjC1)
1405 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1406 CheckStrlcpycatArguments(TheCall, FnInfo);
1407 else if (CMId == Builtin::BIstrncat)
1408 CheckStrncatArguments(TheCall, FnInfo);
1410 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1417 VariadicCallType CallType =
1418 Method->
isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1420 checkCall(Method,
nullptr, Args,
1430 if (
const auto *V = dyn_cast<VarDecl>(NDecl))
1431 Ty = V->getType().getNonReferenceType();
1432 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
1433 Ty = F->getType().getNonReferenceType();
1441 VariadicCallType CallType;
1443 CallType = VariadicDoesNotApply;
1445 CallType = VariadicBlock;
1447 CallType = VariadicFunction;
1450 checkCall(NDecl, Proto,
1453 TheCall->
getCallee()->getSourceRange(), CallType);
1461 VariadicCallType CallType = getVariadicCallType(
nullptr, Proto,
1463 checkCall(
nullptr, Proto,
1466 TheCall->
getCallee()->getSourceRange(), CallType);
1477 case AtomicExpr::AO__c11_atomic_init:
1478 llvm_unreachable(
"There is no ordering argument for an init");
1480 case AtomicExpr::AO__c11_atomic_load:
1481 case AtomicExpr::AO__atomic_load_n:
1482 case AtomicExpr::AO__atomic_load:
1486 case AtomicExpr::AO__c11_atomic_store:
1487 case AtomicExpr::AO__atomic_store:
1488 case AtomicExpr::AO__atomic_store_n:
1500 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
1522 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1523 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1531 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1532 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1533 AtomicExpr::AO__atomic_load,
1534 "need to update code for modified C11 atomics");
1535 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1536 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1537 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1538 Op == AtomicExpr::AO__atomic_store_n ||
1539 Op == AtomicExpr::AO__atomic_exchange_n ||
1540 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1541 bool IsAddSub =
false;
1544 case AtomicExpr::AO__c11_atomic_init:
1548 case AtomicExpr::AO__c11_atomic_load:
1549 case AtomicExpr::AO__atomic_load_n:
1553 case AtomicExpr::AO__c11_atomic_store:
1554 case AtomicExpr::AO__atomic_load:
1555 case AtomicExpr::AO__atomic_store:
1556 case AtomicExpr::AO__atomic_store_n:
1560 case AtomicExpr::AO__c11_atomic_fetch_add:
1561 case AtomicExpr::AO__c11_atomic_fetch_sub:
1562 case AtomicExpr::AO__atomic_fetch_add:
1563 case AtomicExpr::AO__atomic_fetch_sub:
1564 case AtomicExpr::AO__atomic_add_fetch:
1565 case AtomicExpr::AO__atomic_sub_fetch:
1568 case AtomicExpr::AO__c11_atomic_fetch_and:
1569 case AtomicExpr::AO__c11_atomic_fetch_or:
1570 case AtomicExpr::AO__c11_atomic_fetch_xor:
1571 case AtomicExpr::AO__atomic_fetch_and:
1572 case AtomicExpr::AO__atomic_fetch_or:
1573 case AtomicExpr::AO__atomic_fetch_xor:
1574 case AtomicExpr::AO__atomic_fetch_nand:
1575 case AtomicExpr::AO__atomic_and_fetch:
1576 case AtomicExpr::AO__atomic_or_fetch:
1577 case AtomicExpr::AO__atomic_xor_fetch:
1578 case AtomicExpr::AO__atomic_nand_fetch:
1582 case AtomicExpr::AO__c11_atomic_exchange:
1583 case AtomicExpr::AO__atomic_exchange_n:
1587 case AtomicExpr::AO__atomic_exchange:
1591 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1592 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1596 case AtomicExpr::AO__atomic_compare_exchange:
1597 case AtomicExpr::AO__atomic_compare_exchange_n:
1604 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
1605 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
1606 << TheCall->
getCallee()->getSourceRange();
1608 }
else if (TheCall->
getNumArgs() > NumArgs[Form]) {
1609 Diag(TheCall->
getArg(NumArgs[Form])->getLocStart(),
1610 diag::err_typecheck_call_too_many_args)
1611 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
1612 << TheCall->
getCallee()->getSourceRange();
1618 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1621 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1622 << Ptr->
getType() << Ptr->getSourceRange();
1631 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1632 << Ptr->
getType() << Ptr->getSourceRange();
1636 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1637 << Ptr->
getType() << Ptr->getSourceRange();
1644 if (Form == Arithmetic) {
1647 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1648 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1652 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1653 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1657 RequireCompleteType(Ptr->getLocStart(), ValType->
getPointeeType(),
1658 diag::err_incomplete_type)) {
1664 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1665 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1673 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1674 << Ptr->
getType() << Ptr->getSourceRange();
1692 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1693 << ValType << Ptr->getSourceRange();
1702 if (Form == Copy || Form == GNUXchg || Form == Init)
1704 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1716 for (
unsigned i = 1; i != NumArgs[Form]; ++i) {
1718 if (i < NumVals[Form] + 1) {
1725 assert(Form != Load);
1726 if (Form == Init || (Form == Arithmetic && ValType->
isIntegerType()))
1728 else if (Form == Copy || Form == Xchg)
1730 else if (Form == Arithmetic)
1761 SubExprs.push_back(Ptr);
1765 SubExprs.push_back(TheCall->
getArg(1));
1768 SubExprs.push_back(TheCall->
getArg(1));
1773 SubExprs.push_back(TheCall->
getArg(2));
1774 SubExprs.push_back(TheCall->
getArg(1));
1778 SubExprs.push_back(TheCall->
getArg(3));
1779 SubExprs.push_back(TheCall->
getArg(1));
1780 SubExprs.push_back(TheCall->
getArg(2));
1783 SubExprs.push_back(TheCall->
getArg(3));
1784 SubExprs.push_back(TheCall->
getArg(1));
1785 SubExprs.push_back(TheCall->
getArg(4));
1786 SubExprs.push_back(TheCall->
getArg(2));
1789 SubExprs.push_back(TheCall->
getArg(4));
1790 SubExprs.push_back(TheCall->
getArg(1));
1791 SubExprs.push_back(TheCall->
getArg(5));
1792 SubExprs.push_back(TheCall->
getArg(2));
1793 SubExprs.push_back(TheCall->
getArg(3));
1797 if (SubExprs.size() >= 2 && Form != Init) {
1798 llvm::APSInt Result(32);
1799 if (SubExprs[1]->isIntegerConstantExpr(Result,
Context) &&
1801 Diag(SubExprs[1]->getLocStart(),
1802 diag::warn_atomic_op_has_invalid_memory_order)
1803 << SubExprs[1]->getSourceRange();
1807 SubExprs, ResultType, Op,
1810 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1811 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1814 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1829 assert(Fn &&
"builtin call without direct callee!");
1853 Sema::SemaBuiltinAtomicOverloaded(
ExprResult TheCallResult) {
1860 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1862 << TheCall->
getCallee()->getSourceRange();
1872 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1875 FirstArg = FirstArgResult.
get();
1876 TheCall->
setArg(0, FirstArg);
1881 << FirstArg->
getType() << FirstArg->getSourceRange();
1888 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1889 << FirstArg->
getType() << FirstArg->getSourceRange();
1903 << ValType << FirstArg->getSourceRange();
1917 #define BUILTIN_ROW(x) \
1918 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
1919 Builtin::BI##x##_8, Builtin::BI##x##_16 }
1921 static const unsigned BuiltinIndices[][5] = {
1947 case 1: SizeIndex = 0;
break;
1948 case 2: SizeIndex = 1;
break;
1949 case 4: SizeIndex = 2;
break;
1950 case 8: SizeIndex = 3;
break;
1951 case 16: SizeIndex = 4;
break;
1954 << FirstArg->
getType() << FirstArg->getSourceRange();
1962 unsigned BuiltinID = FDecl->getBuiltinID();
1963 unsigned BuiltinIndex, NumFixed = 1;
1964 bool WarnAboutSemanticsChange =
false;
1965 switch (BuiltinID) {
1966 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
1967 case Builtin::BI__sync_fetch_and_add:
1968 case Builtin::BI__sync_fetch_and_add_1:
1969 case Builtin::BI__sync_fetch_and_add_2:
1970 case Builtin::BI__sync_fetch_and_add_4:
1971 case Builtin::BI__sync_fetch_and_add_8:
1972 case Builtin::BI__sync_fetch_and_add_16:
1976 case Builtin::BI__sync_fetch_and_sub:
1977 case Builtin::BI__sync_fetch_and_sub_1:
1978 case Builtin::BI__sync_fetch_and_sub_2:
1979 case Builtin::BI__sync_fetch_and_sub_4:
1980 case Builtin::BI__sync_fetch_and_sub_8:
1981 case Builtin::BI__sync_fetch_and_sub_16:
1985 case Builtin::BI__sync_fetch_and_or:
1986 case Builtin::BI__sync_fetch_and_or_1:
1987 case Builtin::BI__sync_fetch_and_or_2:
1988 case Builtin::BI__sync_fetch_and_or_4:
1989 case Builtin::BI__sync_fetch_and_or_8:
1990 case Builtin::BI__sync_fetch_and_or_16:
1994 case Builtin::BI__sync_fetch_and_and:
1995 case Builtin::BI__sync_fetch_and_and_1:
1996 case Builtin::BI__sync_fetch_and_and_2:
1997 case Builtin::BI__sync_fetch_and_and_4:
1998 case Builtin::BI__sync_fetch_and_and_8:
1999 case Builtin::BI__sync_fetch_and_and_16:
2003 case Builtin::BI__sync_fetch_and_xor:
2004 case Builtin::BI__sync_fetch_and_xor_1:
2005 case Builtin::BI__sync_fetch_and_xor_2:
2006 case Builtin::BI__sync_fetch_and_xor_4:
2007 case Builtin::BI__sync_fetch_and_xor_8:
2008 case Builtin::BI__sync_fetch_and_xor_16:
2012 case Builtin::BI__sync_fetch_and_nand:
2013 case Builtin::BI__sync_fetch_and_nand_1:
2014 case Builtin::BI__sync_fetch_and_nand_2:
2015 case Builtin::BI__sync_fetch_and_nand_4:
2016 case Builtin::BI__sync_fetch_and_nand_8:
2017 case Builtin::BI__sync_fetch_and_nand_16:
2019 WarnAboutSemanticsChange =
true;
2022 case Builtin::BI__sync_add_and_fetch:
2023 case Builtin::BI__sync_add_and_fetch_1:
2024 case Builtin::BI__sync_add_and_fetch_2:
2025 case Builtin::BI__sync_add_and_fetch_4:
2026 case Builtin::BI__sync_add_and_fetch_8:
2027 case Builtin::BI__sync_add_and_fetch_16:
2031 case Builtin::BI__sync_sub_and_fetch:
2032 case Builtin::BI__sync_sub_and_fetch_1:
2033 case Builtin::BI__sync_sub_and_fetch_2:
2034 case Builtin::BI__sync_sub_and_fetch_4:
2035 case Builtin::BI__sync_sub_and_fetch_8:
2036 case Builtin::BI__sync_sub_and_fetch_16:
2040 case Builtin::BI__sync_and_and_fetch:
2041 case Builtin::BI__sync_and_and_fetch_1:
2042 case Builtin::BI__sync_and_and_fetch_2:
2043 case Builtin::BI__sync_and_and_fetch_4:
2044 case Builtin::BI__sync_and_and_fetch_8:
2045 case Builtin::BI__sync_and_and_fetch_16:
2049 case Builtin::BI__sync_or_and_fetch:
2050 case Builtin::BI__sync_or_and_fetch_1:
2051 case Builtin::BI__sync_or_and_fetch_2:
2052 case Builtin::BI__sync_or_and_fetch_4:
2053 case Builtin::BI__sync_or_and_fetch_8:
2054 case Builtin::BI__sync_or_and_fetch_16:
2058 case Builtin::BI__sync_xor_and_fetch:
2059 case Builtin::BI__sync_xor_and_fetch_1:
2060 case Builtin::BI__sync_xor_and_fetch_2:
2061 case Builtin::BI__sync_xor_and_fetch_4:
2062 case Builtin::BI__sync_xor_and_fetch_8:
2063 case Builtin::BI__sync_xor_and_fetch_16:
2067 case Builtin::BI__sync_nand_and_fetch:
2068 case Builtin::BI__sync_nand_and_fetch_1:
2069 case Builtin::BI__sync_nand_and_fetch_2:
2070 case Builtin::BI__sync_nand_and_fetch_4:
2071 case Builtin::BI__sync_nand_and_fetch_8:
2072 case Builtin::BI__sync_nand_and_fetch_16:
2074 WarnAboutSemanticsChange =
true;
2077 case Builtin::BI__sync_val_compare_and_swap:
2078 case Builtin::BI__sync_val_compare_and_swap_1:
2079 case Builtin::BI__sync_val_compare_and_swap_2:
2080 case Builtin::BI__sync_val_compare_and_swap_4:
2081 case Builtin::BI__sync_val_compare_and_swap_8:
2082 case Builtin::BI__sync_val_compare_and_swap_16:
2087 case Builtin::BI__sync_bool_compare_and_swap:
2088 case Builtin::BI__sync_bool_compare_and_swap_1:
2089 case Builtin::BI__sync_bool_compare_and_swap_2:
2090 case Builtin::BI__sync_bool_compare_and_swap_4:
2091 case Builtin::BI__sync_bool_compare_and_swap_8:
2092 case Builtin::BI__sync_bool_compare_and_swap_16:
2098 case Builtin::BI__sync_lock_test_and_set:
2099 case Builtin::BI__sync_lock_test_and_set_1:
2100 case Builtin::BI__sync_lock_test_and_set_2:
2101 case Builtin::BI__sync_lock_test_and_set_4:
2102 case Builtin::BI__sync_lock_test_and_set_8:
2103 case Builtin::BI__sync_lock_test_and_set_16:
2107 case Builtin::BI__sync_lock_release:
2108 case Builtin::BI__sync_lock_release_1:
2109 case Builtin::BI__sync_lock_release_2:
2110 case Builtin::BI__sync_lock_release_4:
2111 case Builtin::BI__sync_lock_release_8:
2112 case Builtin::BI__sync_lock_release_16:
2118 case Builtin::BI__sync_swap:
2119 case Builtin::BI__sync_swap_1:
2120 case Builtin::BI__sync_swap_2:
2121 case Builtin::BI__sync_swap_4:
2122 case Builtin::BI__sync_swap_8:
2123 case Builtin::BI__sync_swap_16:
2131 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2133 << TheCall->
getCallee()->getSourceRange();
2137 if (WarnAboutSemanticsChange) {
2138 Diag(TheCall->
getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2139 << TheCall->
getCallee()->getSourceRange();
2144 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2147 if (NewBuiltinID == BuiltinID)
2148 NewBuiltinDecl = FDecl;
2153 LookupName(Res, TUScope,
true);
2154 assert(Res.getFoundDecl());
2155 NewBuiltinDecl = dyn_cast<
FunctionDecl>(Res.getFoundDecl());
2156 if (!NewBuiltinDecl)
2163 for (
unsigned i = 0; i != NumFixed; ++i) {
2200 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2209 return TheCallResult;
2216 bool Sema::CheckObjCString(
Expr *Arg) {
2220 if (!Literal || !Literal->
isAscii()) {
2221 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2222 << Arg->getSourceRange();
2227 StringRef String = Literal->
getString();
2228 unsigned NumBytes = String.size();
2230 const UTF8 *FromPtr = (
const UTF8 *)String.data();
2231 UTF16 *ToPtr = &ToBuf[0];
2233 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2234 &ToPtr, ToPtr + NumBytes,
2237 if (Result != conversionOK)
2238 Diag(Arg->getLocStart(),
2239 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2246 bool Sema::SemaBuiltinVAStart(
CallExpr *TheCall) {
2250 diag::err_typecheck_call_too_many_args)
2252 << Fn->getSourceRange()
2254 (*(TheCall->
arg_end()-1))->getLocEnd());
2260 diag::err_typecheck_call_too_few_args_at_least)
2274 isVariadic = FD->isVariadic();
2276 isVariadic = getCurMethodDecl()->isVariadic();
2279 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2285 bool SecondArgIsLastNamedArgument =
false;
2293 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2294 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2301 LastArg = *(FD->param_end()-1);
2303 LastArg = *(getCurMethodDecl()->param_end()-1);
2304 SecondArgIsLastNamedArgument = PV == LastArg;
2306 Type = PV->getType();
2307 ParamLoc = PV->getLocation();
2311 if (!SecondArgIsLastNamedArgument)
2313 diag::warn_second_parameter_of_va_start_not_last_named_argument);
2315 Diag(Arg->getLocStart(),
2316 diag::warn_va_start_of_reference_type_is_undefined);
2317 Diag(ParamLoc, diag::note_parameter_type) << Type;
2324 bool Sema::SemaBuiltinVAStartARM(
CallExpr *Call) {
2332 diag::err_typecheck_call_too_few_args_at_least)
2340 IsVariadic = FD->isVariadic();
2342 IsVariadic = MD->isVariadic();
2344 llvm_unreachable(
"unexpected statement type");
2347 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2358 } ArgumentTypes[] = {
2363 for (
const auto &AT : ArgumentTypes) {
2367 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2368 << Arg->
getType() << AT.Type << 1
2370 << AT.ArgNo + 1 << Arg->
getType() << AT.Type;
2378 bool Sema::SemaBuiltinUnorderedCompare(
CallExpr *TheCall) {
2380 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2383 return Diag(TheCall->
getArg(2)->getLocStart(),
2384 diag::err_typecheck_call_too_many_args)
2387 (*(TheCall->
arg_end()-1))->getLocEnd());
2394 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1,
false);
2395 if (OrigArg0.isInvalid() || OrigArg1.
isInvalid())
2401 TheCall->
setArg(0, OrigArg0.get());
2410 return Diag(OrigArg0.get()->getLocStart(),
2411 diag::err_typecheck_call_invalid_ordered_compare)
2412 << OrigArg0.get()->getType() << OrigArg1.
get()->
getType()
2413 <<
SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.
get()->getLocEnd());
2422 bool Sema::SemaBuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs) {
2424 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2427 return Diag(TheCall->
getArg(NumArgs)->getLocStart(),
2428 diag::err_typecheck_call_too_many_args)
2431 (*(TheCall->
arg_end()-1))->getLocEnd());
2435 if (OrigArg->isTypeDependent())
2439 if (!OrigArg->getType()->isRealFloatingType())
2440 return Diag(OrigArg->getLocStart(),
2441 diag::err_typecheck_call_invalid_unary_fp)
2442 << OrigArg->getType() << OrigArg->getSourceRange();
2446 Expr *CastArg = Cast->getSubExpr();
2448 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2449 "promotion from float to double is the only expected cast here");
2450 Cast->setSubExpr(
nullptr);
2451 TheCall->
setArg(NumArgs-1, CastArg);
2463 diag::err_typecheck_call_too_few_args_at_least)
2465 << TheCall->getSourceRange());
2472 unsigned numElements = 0;
2481 diag::err_shufflevector_non_vector)
2483 TheCall->
getArg(1)->getLocEnd()));
2486 unsigned numResElements = TheCall->
getNumArgs() - 2;
2495 diag::err_shufflevector_incompatible_vector)
2497 TheCall->
getArg(1)->getLocEnd()));
2500 diag::err_shufflevector_incompatible_vector)
2502 TheCall->
getArg(1)->getLocEnd()));
2503 }
else if (numElements != numResElements) {
2510 for (
unsigned i = 2; i < TheCall->
getNumArgs(); i++) {
2515 llvm::APSInt Result(32);
2518 diag::err_shufflevector_nonconstant_argument)
2519 << TheCall->
getArg(i)->getSourceRange());
2522 if (Result.isSigned() && Result.isAllOnesValue())
2525 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2527 diag::err_shufflevector_argument_too_large)
2528 << TheCall->
getArg(i)->getSourceRange());
2533 for (
unsigned i = 0, e = TheCall->
getNumArgs(); i != e; i++) {
2534 exprs.push_back(TheCall->
getArg(i));
2535 TheCall->
setArg(i,
nullptr);
2554 diag::err_convertvector_non_vector)
2555 << E->getSourceRange());
2558 diag::err_convertvector_non_vector_type));
2563 if (SrcElts != DstElts)
2565 diag::err_convertvector_incompatible_vector)
2566 << E->getSourceRange());
2576 bool Sema::SemaBuiltinPrefetch(
CallExpr *TheCall) {
2581 diag::err_typecheck_call_too_many_args_at_most)
2582 << 0 << 3 << NumArgs
2583 << TheCall->getSourceRange();
2587 for (
unsigned i = 1; i != NumArgs; ++i)
2588 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2597 bool Sema::SemaBuiltinAssume(
CallExpr *TheCall) {
2602 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2603 << Arg->getSourceRange()
2604 << cast<FunctionDecl>(TheCall->
getCalleeDecl())->getIdentifier();
2611 bool Sema::SemaBuiltinAssumeAligned(
CallExpr *TheCall) {
2616 diag::err_typecheck_call_too_many_args_at_most)
2617 << 0 << 3 << NumArgs
2618 << TheCall->getSourceRange();
2625 llvm::APSInt Result;
2626 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2629 if (!Result.isPowerOf2())
2631 diag::err_alignment_not_power_of_two)
2632 << Arg->getSourceRange();
2640 if (Arg.isInvalid())
return true;
2641 TheCall->
setArg(2, Arg.get());
2649 bool Sema::SemaBuiltinConstantArg(
CallExpr *TheCall,
int ArgNum,
2650 llvm::APSInt &Result) {
2658 return Diag(TheCall->
getLocStart(), diag::err_constant_integer_arg_type)
2659 << FDecl->getDeclName() << Arg->getSourceRange();
2666 bool Sema::SemaBuiltinConstantArgRange(
CallExpr *TheCall,
int ArgNum,
2667 int Low,
int High) {
2668 llvm::APSInt Result;
2676 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2679 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2681 << Low << High << Arg->getSourceRange();
2688 bool Sema::SemaBuiltinARMSpecialReg(
unsigned BuiltinID,
CallExpr *TheCall,
2689 int ArgNum,
unsigned ExpectedFieldNum,
2691 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2692 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2693 BuiltinID == ARM::BI__builtin_arm_rsr ||
2694 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2695 BuiltinID == ARM::BI__builtin_arm_wsr ||
2696 BuiltinID == ARM::BI__builtin_arm_wsrp;
2697 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2698 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2699 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2700 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2701 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2702 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2703 assert((IsARMBuiltin || IsAArch64Builtin) &&
"Unexpected ARM builtin.");
2712 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
2713 << Arg->getSourceRange();
2718 Reg.split(Fields,
":");
2720 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2722 << Arg->getSourceRange();
2728 if (Fields.size() > 1) {
2729 bool FiveFields = Fields.size() == 5;
2731 bool ValidString =
true;
2733 ValidString &= Fields[0].startswith_lower(
"cp") ||
2734 Fields[0].startswith_lower(
"p");
2737 Fields[0].drop_front(Fields[0].startswith_lower(
"cp") ? 2 : 1);
2739 ValidString &= Fields[2].startswith_lower(
"c");
2741 Fields[2] = Fields[2].drop_front(1);
2744 ValidString &= Fields[3].startswith_lower(
"c");
2746 Fields[3] = Fields[3].drop_front(1);
2752 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2754 Ranges.append({15, 7, 15});
2756 for (
unsigned i=0; i<Fields.size(); ++i) {
2758 ValidString &= !Fields[i].getAsInteger(10, IntField);
2759 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2764 << Arg->getSourceRange();
2766 }
else if (IsAArch64Builtin && Fields.size() == 1) {
2776 std::string RegLower = Reg.lower();
2777 if (RegLower !=
"spsel" && RegLower !=
"daifset" && RegLower !=
"daifclr" &&
2778 RegLower !=
"pan" && RegLower !=
"uao")
2781 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2790 bool Sema::SemaBuiltinCpuSupports(
CallExpr *TheCall) {
2795 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
2796 << Arg->getSourceRange();
2803 << Arg->getSourceRange();
2810 bool Sema::SemaBuiltinLongjmp(
CallExpr *TheCall) {
2812 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_unsupported)
2816 llvm::APSInt Result;
2819 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2823 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_invalid_val)
2824 <<
SourceRange(Arg->getLocStart(), Arg->getLocEnd());
2832 bool Sema::SemaBuiltinSetjmp(
CallExpr *TheCall) {
2834 return Diag(TheCall->
getLocStart(), diag::err_builtin_setjmp_unsupported)
2842 SLCT_UncheckedLiteral,
2853 bool HasVAListArg,
unsigned format_idx,
2856 llvm::SmallBitVector &CheckedVarArgs) {
2859 return SLCT_NotALiteral;
2868 return SLCT_UncheckedLiteral;
2870 switch (E->getStmtClass()) {
2871 case Stmt::BinaryConditionalOperatorClass:
2872 case Stmt::ConditionalOperatorClass: {
2876 cast<AbstractConditionalOperator>(E);
2879 HasVAListArg, format_idx, firstDataArg,
2880 Type, CallType, InFunctionCall, CheckedVarArgs);
2881 if (Left == SLCT_NotALiteral)
2882 return SLCT_NotALiteral;
2885 HasVAListArg, format_idx, firstDataArg,
2886 Type, CallType, InFunctionCall, CheckedVarArgs);
2887 return Left < Right ? Left : Right;
2890 case Stmt::ImplicitCastExprClass: {
2891 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2895 case Stmt::OpaqueValueExprClass:
2896 if (
const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
2900 return SLCT_NotALiteral;
2902 case Stmt::PredefinedExprClass:
2906 return SLCT_UncheckedLiteral;
2908 case Stmt::DeclRefExprClass: {
2914 bool isConstant =
false;
2918 isConstant = AT->getElementType().isConstant(S.
Context);
2921 PT->getPointeeType().isConstant(S.
Context);
2929 if (
const Expr *Init = VD->getAnyInitializer()) {
2931 if (
const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
2932 if (InitList->isStringLiteralInit())
2933 Init = InitList->getInit(0)->IgnoreParenImpCasts();
2936 HasVAListArg, format_idx,
2937 firstDataArg, Type, CallType,
2938 false, CheckedVarArgs);
2957 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
2958 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
2959 int PVIndex = PV->getFunctionScopeIndex() + 1;
2960 for (
const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
2963 if (MD->isInstance())
2967 if (PVIndex == PVFormat->getFormatIdx() &&
2969 return SLCT_UncheckedLiteral;
2976 return SLCT_NotALiteral;
2979 case Stmt::CallExprClass:
2980 case Stmt::CXXMemberCallExprClass: {
2981 const CallExpr *CE = cast<CallExpr>(E);
2983 if (
const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
2984 unsigned ArgIndex = FA->getFormatIdx();
2986 if (MD->isInstance())
2991 HasVAListArg, format_idx, firstDataArg,
2992 Type, CallType, InFunctionCall,
2994 }
else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
2995 unsigned BuiltinID = FD->getBuiltinID();
2996 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
2997 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3000 HasVAListArg, format_idx,
3001 firstDataArg, Type, CallType,
3002 InFunctionCall, CheckedVarArgs);
3007 return SLCT_NotALiteral;
3009 case Stmt::ObjCStringLiteralClass:
3010 case Stmt::StringLiteralClass: {
3016 StrE = cast<StringLiteral>(E);
3020 Type, InFunctionCall, CallType, CheckedVarArgs);
3021 return SLCT_CheckedLiteral;
3024 return SLCT_NotALiteral;
3028 return SLCT_NotALiteral;
3033 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3034 .Case(
"scanf", FST_Scanf)
3035 .Cases(
"printf",
"printf0", FST_Printf)
3036 .Cases(
"NSString",
"CFString", FST_NSString)
3037 .Case(
"strftime", FST_Strftime)
3038 .Case(
"strfmon", FST_Strfmon)
3039 .Cases(
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err", FST_Kprintf)
3040 .Case(
"freebsd_kprintf", FST_FreeBSDKPrintf)
3041 .Case(
"os_trace", FST_OSTrace)
3042 .Default(FST_Unknown);
3048 bool Sema::CheckFormatArguments(
const FormatAttr *Format,
3051 VariadicCallType CallType,
3053 llvm::SmallBitVector &CheckedVarArgs) {
3054 FormatStringInfo FSI;
3055 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3056 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3057 FSI.FirstDataArg, GetFormatStringType(Format),
3058 CallType, Loc, Range, CheckedVarArgs);
3063 bool HasVAListArg,
unsigned format_idx,
3064 unsigned firstDataArg, FormatStringType Type,
3065 VariadicCallType CallType,
3067 llvm::SmallBitVector &CheckedVarArgs) {
3069 if (format_idx >= Args.size()) {
3070 Diag(Loc, diag::warn_missing_format_string) << Range;
3074 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3090 format_idx, firstDataArg, Type, CallType,
3091 true, CheckedVarArgs);
3092 if (CT != SLCT_NotALiteral)
3094 return CT == SLCT_CheckedLiteral;
3098 if (Type == FST_Strftime)
3105 if (Type == FST_NSString &&
3111 if (Args.size() == firstDataArg)
3112 Diag(Args[format_idx]->getLocStart(),
3113 diag::warn_format_nonliteral_noargs)
3114 << OrigFormatExpr->getSourceRange();
3116 Diag(Args[format_idx]->getLocStart(),
3117 diag::warn_format_nonliteral)
3118 << OrigFormatExpr->getSourceRange();
3127 const Expr *OrigFormatExpr;
3128 const unsigned FirstDataArg;
3129 const unsigned NumDataArgs;
3131 const bool HasVAListArg;
3134 llvm::SmallBitVector CoveredArgs;
3135 bool usesPositionalArgs;
3137 bool inFunctionCall;
3139 llvm::SmallBitVector &CheckedVarArgs;
3142 const Expr *origFormatExpr,
unsigned firstDataArg,
3143 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
3145 unsigned formatIdx,
bool inFunctionCall,
3147 llvm::SmallBitVector &CheckedVarArgs)
3148 :
S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3149 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3150 Beg(beg), HasVAListArg(hasVAListArg),
3151 Args(Args), FormatIdx(formatIdx),
3152 usesPositionalArgs(
false), atFirstArg(
true),
3153 inFunctionCall(inFunctionCall), CallType(callType),
3154 CheckedVarArgs(CheckedVarArgs) {
3155 CoveredArgs.resize(numDataArgs);
3156 CoveredArgs.reset();
3159 void DoneProcessing();
3161 void HandleIncompleteSpecifier(
const char *startSpecifier,
3162 unsigned specifierLen)
override;
3164 void HandleInvalidLengthModifier(
3167 const char *startSpecifier,
unsigned specifierLen,
3170 void HandleNonStandardLengthModifier(
3172 const char *startSpecifier,
unsigned specifierLen);
3174 void HandleNonStandardConversionSpecifier(
3176 const char *startSpecifier,
unsigned specifierLen);
3178 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
3180 void HandleInvalidPosition(
const char *startSpecifier,
3181 unsigned specifierLen,
3184 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
3186 void HandleNullChar(
const char *nullCharacter)
override;
3188 template <
typename Range>
3189 static void EmitFormatDiagnostic(
Sema &
S,
bool inFunctionCall,
3190 const Expr *ArgumentExpr,
3193 bool IsStringLocation, Range StringRange,
3197 bool HandleInvalidConversionSpecifier(
unsigned argIndex,
SourceLocation Loc,
3198 const char *startSpec,
3199 unsigned specifierLen,
3200 const char *csStart,
unsigned csLen);
3203 const char *startSpec,
3204 unsigned specifierLen);
3208 unsigned specifierLen);
3211 const Expr *getDataArg(
unsigned i)
const;
3215 const char *startSpecifier,
unsigned specifierLen,
3218 template <
typename Range>
3220 bool IsStringLocation, Range StringRange,
3225 SourceRange CheckFormatHandler::getFormatStringRange() {
3226 return OrigFormatExpr->getSourceRange();
3230 getSpecifierRange(
const char *startSpecifier,
unsigned specifierLen) {
3240 SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
3244 void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
3245 unsigned specifierLen){
3246 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_incomplete_specifier),
3247 getLocationOfByte(startSpecifier),
3249 getSpecifierRange(startSpecifier, specifierLen));
3252 void CheckFormatHandler::HandleInvalidLengthModifier(
3255 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
3256 using namespace analyze_format_string;
3259 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3264 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
3265 getLocationOfByte(LM.getStart()),
3267 getSpecifierRange(startSpecifier, specifierLen));
3269 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3270 << FixedLM->toString()
3275 if (DiagID == diag::warn_format_nonsensical_length)
3278 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
3279 getLocationOfByte(LM.getStart()),
3281 getSpecifierRange(startSpecifier, specifierLen),
3286 void CheckFormatHandler::HandleNonStandardLengthModifier(
3288 const char *startSpecifier,
unsigned specifierLen) {
3289 using namespace analyze_format_string;
3292 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3297 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3298 << LM.toString() << 0,
3299 getLocationOfByte(LM.getStart()),
3301 getSpecifierRange(startSpecifier, specifierLen));
3303 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3304 << FixedLM->toString()
3308 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3309 << LM.toString() << 0,
3310 getLocationOfByte(LM.getStart()),
3312 getSpecifierRange(startSpecifier, specifierLen));
3316 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3318 const char *startSpecifier,
unsigned specifierLen) {
3319 using namespace analyze_format_string;
3324 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3328 getSpecifierRange(startSpecifier, specifierLen));
3331 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
3332 << FixedCS->toString()
3335 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3339 getSpecifierRange(startSpecifier, specifierLen));
3343 void CheckFormatHandler::HandlePosition(
const char *startPos,
3345 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard_positional_arg),
3346 getLocationOfByte(startPos),
3348 getSpecifierRange(startPos, posLen));
3352 CheckFormatHandler::HandleInvalidPosition(
const char *startPos,
unsigned posLen,
3354 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_positional_specifier)
3356 getLocationOfByte(startPos),
true,
3357 getSpecifierRange(startPos, posLen));
3360 void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
3362 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_zero_positional_specifier),
3363 getLocationOfByte(startPos),
3365 getSpecifierRange(startPos, posLen));
3368 void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
3369 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3371 EmitFormatDiagnostic(
3372 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
3373 getLocationOfByte(nullCharacter),
true,
3374 getFormatStringRange());
3380 const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
3381 return Args[FirstDataArg + i];
3384 void CheckFormatHandler::DoneProcessing() {
3387 if (!HasVAListArg) {
3390 signed notCoveredArg = CoveredArgs.find_first();
3391 if (notCoveredArg >= 0) {
3392 assert((
unsigned)notCoveredArg < NumDataArgs);
3393 if (
const Expr *E = getDataArg((
unsigned) notCoveredArg)) {
3396 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_data_arg_not_used),
3398 getFormatStringRange());
3406 CheckFormatHandler::HandleInvalidConversionSpecifier(
unsigned argIndex,
3408 const char *startSpec,
3409 unsigned specifierLen,
3410 const char *csStart,
3413 bool keepGoing =
true;
3414 if (argIndex < NumDataArgs) {
3417 CoveredArgs.set(argIndex);
3428 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_conversion)
3429 << StringRef(csStart, csLen),
3431 getSpecifierRange(startSpec, specifierLen));
3437 CheckFormatHandler::HandlePositionalNonpositionalArgs(
SourceLocation Loc,
3438 const char *startSpec,
3439 unsigned specifierLen) {
3440 EmitFormatDiagnostic(
3441 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args),
3442 Loc,
true, getSpecifierRange(startSpec, specifierLen));
3446 CheckFormatHandler::CheckNumArgs(
3449 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
3451 if (argIndex >= NumDataArgs) {
3453 ? (
S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3454 << (argIndex+1) << NumDataArgs)
3455 :
S.
PDiag(diag::warn_printf_insufficient_data_args);
3456 EmitFormatDiagnostic(
3457 PDiag, getLocationOfByte(CS.
getStart()),
true,
3458 getSpecifierRange(startSpecifier, specifierLen));
3464 template<
typename Range>
3467 bool IsStringLocation,
3470 EmitFormatDiagnostic(
S, inFunctionCall, Args[FormatIdx], PDiag,
3471 Loc, IsStringLocation, StringRange, FixIt);
3501 template<
typename Range>
3502 void CheckFormatHandler::EmitFormatDiagnostic(
Sema &
S,
bool InFunctionCall,
3503 const Expr *ArgumentExpr,
3506 bool IsStringLocation,
3509 if (InFunctionCall) {
3514 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
3515 << ArgumentExpr->getSourceRange();
3518 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3519 diag::note_format_string_defined);
3521 Note << StringRange;
3529 class CheckPrintfHandler :
public CheckFormatHandler {
3533 const Expr *origFormatExpr,
unsigned firstDataArg,
3534 unsigned numDataArgs,
bool isObjC,
3535 const char *beg,
bool hasVAListArg,
3537 unsigned formatIdx,
bool inFunctionCall,
3539 llvm::SmallBitVector &CheckedVarArgs)
3540 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3541 numDataArgs, beg, hasVAListArg, Args,
3542 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3547 bool HandleInvalidPrintfConversionSpecifier(
3549 const char *startSpecifier,
3550 unsigned specifierLen)
override;
3553 const char *startSpecifier,
3554 unsigned specifierLen)
override;
3556 const char *StartSpecifier,
3557 unsigned SpecifierLen,
3561 const char *startSpecifier,
unsigned specifierLen);
3563 const analyze_printf::OptionalAmount &Amt,
3565 const char *startSpecifier,
unsigned specifierLen);
3567 const analyze_printf::OptionalFlag &flag,
3568 const char *startSpecifier,
unsigned specifierLen);
3570 const analyze_printf::OptionalFlag &ignoredFlag,
3571 const analyze_printf::OptionalFlag &flag,
3572 const char *startSpecifier,
unsigned specifierLen);
3573 bool checkForCStrMembers(
const analyze_printf::ArgType &AT,
3576 void HandleEmptyObjCModifierFlag(
const char *startFlag,
3577 unsigned flagLen)
override;
3579 void HandleInvalidObjCModifierFlag(
const char *startFlag,
3580 unsigned flagLen)
override;
3582 void HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
3583 const char *flagsEnd,
3584 const char *conversionPosition)
3589 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3591 const char *startSpecifier,
3592 unsigned specifierLen) {
3596 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
3598 startSpecifier, specifierLen,
3602 bool CheckPrintfHandler::HandleAmount(
3604 unsigned k,
const char *startSpecifier,
3605 unsigned specifierLen) {
3608 if (!HasVAListArg) {
3610 if (argIndex >= NumDataArgs) {
3611 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
3615 getSpecifierRange(startSpecifier, specifierLen));
3625 CoveredArgs.set(argIndex);
3626 const Expr *Arg = getDataArg(argIndex);
3633 assert(AT.isValid());
3635 if (!AT.matchesType(S.
Context, T)) {
3636 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_wrong_type)
3637 << k << AT.getRepresentativeTypeName(S.
Context)
3638 << T << Arg->getSourceRange(),
3641 getSpecifierRange(startSpecifier, specifierLen));
3651 void CheckPrintfHandler::HandleInvalidAmount(
3653 const analyze_printf::OptionalAmount &Amt,
3655 const char *startSpecifier,
3656 unsigned specifierLen) {
3661 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3663 Amt.getConstantLength()))
3666 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
3668 getLocationOfByte(Amt.getStart()),
3670 getSpecifierRange(startSpecifier, specifierLen),
3675 const analyze_printf::OptionalFlag &flag,
3676 const char *startSpecifier,
3677 unsigned specifierLen) {
3681 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_flag)
3682 << flag.toString() << CS.
toString(),
3683 getLocationOfByte(flag.getPosition()),
3685 getSpecifierRange(startSpecifier, specifierLen),
3687 getSpecifierRange(flag.getPosition(), 1)));
3690 void CheckPrintfHandler::HandleIgnoredFlag(
3692 const analyze_printf::OptionalFlag &ignoredFlag,
3693 const analyze_printf::OptionalFlag &flag,
3694 const char *startSpecifier,
3695 unsigned specifierLen) {
3697 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
3698 << ignoredFlag.toString() << flag.toString(),
3699 getLocationOfByte(ignoredFlag.getPosition()),
3701 getSpecifierRange(startSpecifier, specifierLen),
3703 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3710 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
3713 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_empty_objc_flag),
3714 getLocationOfByte(startFlag),
3716 getSpecifierRange(startFlag, flagLen));
3719 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
3722 auto Range = getSpecifierRange(startFlag, flagLen);
3723 StringRef flag(startFlag, flagLen);
3724 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3725 getLocationOfByte(startFlag),
3730 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3731 const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {
3733 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3734 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3735 EmitFormatDiagnostic(S.
PDiag(diag) << StringRef(conversionPosition, 1),
3736 getLocationOfByte(conversionPosition),
3744 template<
typename MemberKind>
3745 static llvm::SmallPtrSet<MemberKind*, 1>
3748 llvm::SmallPtrSet<MemberKind*, 1> Results;
3765 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3776 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3778 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", *
this, E->
getType());
3779 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3781 if ((*MI)->getMinRequiredArguments() == 0)
3789 bool CheckPrintfHandler::checkForCStrMembers(
3790 const analyze_printf::ArgType &AT,
const Expr *E) {
3791 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3794 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str",
S, E->
getType());
3796 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
3803 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3816 const char *startSpecifier,
3817 unsigned specifierLen) {
3819 using namespace analyze_format_string;
3820 using namespace analyze_printf;
3829 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
3830 startSpecifier, specifierLen);
3838 startSpecifier, specifierLen)) {
3843 startSpecifier, specifierLen)) {
3855 if (argIndex < NumDataArgs) {
3859 CoveredArgs.set(argIndex);
3863 if (CS.
getKind() == ConversionSpecifier::FreeBSDbArg ||
3864 CS.
getKind() == ConversionSpecifier::FreeBSDDArg) {
3866 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
3870 CoveredArgs.set(argIndex + 1);
3873 const Expr *Ex = getDataArg(argIndex);
3874 const analyze_printf::ArgType &AT =
3875 (CS.
getKind() == ConversionSpecifier::FreeBSDbArg) ?
3876 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
3877 if (AT.isValid() && !AT.matchesType(S.Context, Ex->
getType()))
3878 EmitFormatDiagnostic(
3879 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3880 << AT.getRepresentativeTypeName(S.Context) << Ex->
getType()
3881 <<
false << Ex->getSourceRange(),
3882 Ex->getLocStart(),
false,
3883 getSpecifierRange(startSpecifier, specifierLen));
3886 Ex = getDataArg(argIndex + 1);
3887 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
3888 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
3889 EmitFormatDiagnostic(
3890 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
3891 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
3892 <<
false << Ex->getSourceRange(),
3893 Ex->getLocStart(),
false,
3894 getSpecifierRange(startSpecifier, specifierLen));
3902 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
3909 startSpecifier, specifierLen);
3915 startSpecifier, specifierLen);
3924 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
3926 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
3935 startSpecifier, specifierLen);
3938 startSpecifier, specifierLen);
3942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3943 diag::warn_format_nonsensical_length);
3945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
3947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
3948 diag::warn_format_non_standard_conversion_spec);
3951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
3957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
3960 const Expr *Arg = getDataArg(argIndex);
3964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
3975 switch (Inside->getStmtClass()) {
3976 case Stmt::ArraySubscriptExprClass:
3977 case Stmt::CallExprClass:
3978 case Stmt::CharacterLiteralClass:
3979 case Stmt::CXXBoolLiteralExprClass:
3980 case Stmt::DeclRefExprClass:
3981 case Stmt::FloatingLiteralClass:
3982 case Stmt::IntegerLiteralClass:
3983 case Stmt::MemberExprClass:
3984 case Stmt::ObjCArrayLiteralClass:
3985 case Stmt::ObjCBoolLiteralExprClass:
3986 case Stmt::ObjCBoxedExprClass:
3987 case Stmt::ObjCDictionaryLiteralClass:
3988 case Stmt::ObjCEncodeExprClass:
3989 case Stmt::ObjCIvarRefExprClass:
3990 case Stmt::ObjCMessageExprClass:
3991 case Stmt::ObjCPropertyRefExprClass:
3992 case Stmt::ObjCStringLiteralClass:
3993 case Stmt::ObjCSubscriptRefExprClass:
3994 case Stmt::ParenExprClass:
3995 case Stmt::StringLiteralClass:
3996 case Stmt::UnaryOperatorClass:
4003 static std::pair<QualType, StringRef>
4010 StringRef Name = UserTy->getDecl()->getName();
4011 QualType CastTy = llvm::StringSwitch<QualType>(Name)
4012 .Case(
"NSInteger", Context.
LongTy)
4014 .Case(
"SInt32", Context.
IntTy)
4019 return std::make_pair(CastTy, Name);
4021 TyTy = UserTy->desugar();
4025 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4027 PE->getSubExpr()->getType(),
4036 StringRef TrueName, FalseName;
4038 std::tie(TrueTy, TrueName) =
4040 CO->getTrueExpr()->getType(),
4042 std::tie(FalseTy, FalseName) =
4044 CO->getFalseExpr()->getType(),
4045 CO->getFalseExpr());
4047 if (TrueTy == FalseTy)
4048 return std::make_pair(TrueTy, TrueName);
4049 else if (TrueTy.
isNull())
4050 return std::make_pair(FalseTy, FalseName);
4051 else if (FalseTy.
isNull())
4052 return std::make_pair(TrueTy, TrueName);
4055 return std::make_pair(
QualType(), StringRef());
4060 const char *StartSpecifier,
4061 unsigned SpecifierLen,
4063 using namespace analyze_format_string;
4064 using namespace analyze_printf;
4067 const analyze_printf::ArgType &AT = FS.
getArgType(S.Context,
4073 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4074 ExprTy = TET->getUnderlyingExpr()->getType();
4077 analyze_printf::ArgType::MatchKind
match = AT.matchesType(S.Context, ExprTy);
4079 if (
match == analyze_printf::ArgType::Match) {
4090 E = ICE->getSubExpr();
4096 if (ICE->getType() == S.Context.IntTy ||
4097 ICE->getType() == S.Context.UnsignedIntTy) {
4099 if (AT.matchesType(S.Context, ExprTy))
4107 if (ExprTy == S.Context.IntTy)
4108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4109 ExprTy = S.Context.CharTy;
4113 bool IsEnum =
false;
4114 if (
auto EnumTy = ExprTy->getAs<
EnumType>()) {
4115 ExprTy = EnumTy->getDecl()->getIntegerType();
4125 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4126 !ExprTy->isCharType()) {
4129 IntendedTy = S.Context.UnsignedShortTy;
4134 const llvm::APInt &V = IL->getValue();
4135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4139 LookupResult Result(S, &S.Context.Idents.get(
"unichar"), E->getLocStart(),
4141 if (S.LookupName(Result, S.getCurScope())) {
4144 if (TD->getUnderlyingType() == IntendedTy)
4145 IntendedTy = S.Context.getTypedefType(TD);
4152 bool ShouldNotPrintDirectly =
false; StringRef CastTyName;
4153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
4157 IntendedTy = CastTy;
4158 ShouldNotPrintDirectly =
true;
4163 PrintfSpecifier fixedFS = FS;
4164 bool success = fixedFS.
fixType(IntendedTy, S.getLangOpts(),
4165 S.Context, ObjCContext);
4170 llvm::raw_svector_ostream os(buf);
4171 fixedFS.toString(os);
4173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
4176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4182 EmitFormatDiagnostic(S.PDiag(diag)
4183 << AT.getRepresentativeTypeName(S.Context)
4184 << IntendedTy << IsEnum << E->getSourceRange(),
4198 llvm::raw_svector_ostream CastFix(CastBuf);
4200 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4204 if (!AT.matchesType(S.Context, IntendedTy))
4209 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4227 if (ShouldNotPrintDirectly) {
4232 if (
const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4233 Name = TypedefTy->getDecl()->getName();
4236 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
4237 << Name << IntendedTy << IsEnum
4238 << E->getSourceRange(),
4239 E->getLocStart(),
false,
4245 EmitFormatDiagnostic(
4246 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4247 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
4248 << E->getSourceRange(),
4249 E->getLocStart(),
false,
4259 switch (S.isValidVarArgType(ExprTy)) {
4262 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4263 if (
match == analyze_printf::ArgType::NoMatchPedantic) {
4264 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4267 EmitFormatDiagnostic(
4268 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4269 << IsEnum << CSR << E->getSourceRange(),
4270 E->getLocStart(),
false, CSR);
4275 EmitFormatDiagnostic(
4276 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4277 << S.getLangOpts().CPlusPlus11
4280 << AT.getRepresentativeTypeName(S.Context)
4282 << E->getSourceRange(),
4283 E->getLocStart(),
false, CSR);
4284 checkForCStrMembers(AT, E);
4288 if (ExprTy->isObjCObjectType())
4289 EmitFormatDiagnostic(
4290 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4291 << S.getLangOpts().CPlusPlus11
4294 << AT.getRepresentativeTypeName(S.Context)
4296 << E->getSourceRange(),
4297 E->getLocStart(),
false, CSR);
4301 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4302 << isa<InitListExpr>(E) << ExprTy << CallType
4303 << AT.getRepresentativeTypeName(S.Context)
4304 << E->getSourceRange();
4308 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
4309 "format string specifier index out of range");
4310 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
4319 class CheckScanfHandler :
public CheckFormatHandler {
4322 const Expr *origFormatExpr,
unsigned firstDataArg,
4323 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
4325 unsigned formatIdx,
bool inFunctionCall,
4327 llvm::SmallBitVector &CheckedVarArgs)
4328 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4329 numDataArgs, beg, hasVAListArg,
4330 Args, formatIdx, inFunctionCall, CallType,
4335 const char *startSpecifier,
4336 unsigned specifierLen)
override;
4338 bool HandleInvalidScanfConversionSpecifier(
4340 const char *startSpecifier,
4341 unsigned specifierLen)
override;
4343 void HandleIncompleteScanList(
const char *start,
const char *end)
override;
4347 void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
4349 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4350 getLocationOfByte(end),
true,
4351 getSpecifierRange(start, end - start));
4354 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4356 const char *startSpecifier,
4357 unsigned specifierLen) {
4362 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
4364 startSpecifier, specifierLen,
4368 bool CheckScanfHandler::HandleScanfSpecifier(
4370 const char *startSpecifier,
4371 unsigned specifierLen) {
4373 using namespace analyze_scanf;
4374 using namespace analyze_format_string;
4386 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
4387 startSpecifier, specifierLen);
4394 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4395 if (Amt.getConstantAmount() == 0) {
4397 Amt.getConstantLength());
4398 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4399 getLocationOfByte(Amt.getStart()),
4401 FixItHint::CreateRemoval(R));
4413 if (argIndex < NumDataArgs) {
4417 CoveredArgs.set(argIndex);
4422 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4423 diag::warn_format_nonsensical_length);
4425 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4427 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4428 diag::warn_format_non_standard_conversion_spec);
4431 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4437 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4441 const Expr *Ex = getDataArg(argIndex);
4447 if (!AT.isValid()) {
4452 AT.matchesType(S.Context, Ex->getType());
4457 ScanfSpecifier fixedFS = FS;
4458 bool success = fixedFS.
fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4459 S.getLangOpts(), S.Context);
4461 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4463 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4469 llvm::raw_svector_ostream os(buf);
4470 fixedFS.toString(os);
4472 EmitFormatDiagnostic(
4473 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4474 << Ex->getType() <<
false << Ex->getSourceRange(),
4477 getSpecifierRange(startSpecifier, specifierLen),
4479 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4481 EmitFormatDiagnostic(S.PDiag(diag)
4482 << AT.getRepresentativeTypeName(S.Context)
4483 << Ex->getType() <<
false << Ex->getSourceRange(),
4486 getSpecifierRange(startSpecifier, specifierLen));
4493 const Expr *OrigFormatExpr,
4495 bool HasVAListArg,
unsigned format_idx,
4498 llvm::SmallBitVector &CheckedVarArgs) {
4502 CheckFormatHandler::EmitFormatDiagnostic(
4503 *
this, inFunctionCall, Args[format_idx],
4504 PDiag(diag::warn_format_string_is_wide_literal), FExpr->
getLocStart(),
4505 true, OrigFormatExpr->getSourceRange());
4511 const char *Str = StrRef.data();
4514 assert(T &&
"String literal not of constant array type!");
4515 size_t TypeSize = T->
getSize().getZExtValue();
4516 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
4517 const unsigned numDataArgs = Args.size() - firstDataArg;
4521 if (TypeSize <= StrRef.size() &&
4522 StrRef.substr(0, TypeSize).find(
'\0') == StringRef::npos) {
4523 CheckFormatHandler::EmitFormatDiagnostic(
4524 *
this, inFunctionCall, Args[format_idx],
4525 PDiag(diag::warn_printf_format_string_not_null_terminated),
4527 true, OrigFormatExpr->getSourceRange());
4532 if (StrLen == 0 && numDataArgs > 0) {
4533 CheckFormatHandler::EmitFormatDiagnostic(
4534 *
this, inFunctionCall, Args[format_idx],
4535 PDiag(diag::warn_empty_format_string), FExpr->
getLocStart(),
4536 true, OrigFormatExpr->getSourceRange());
4540 if (Type == FST_Printf || Type == FST_NSString ||
4541 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4542 CheckPrintfHandler H(*
this, FExpr, OrigFormatExpr, firstDataArg,
4543 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4544 Str, HasVAListArg, Args, format_idx,
4545 inFunctionCall, CallType, CheckedVarArgs);
4550 Type == FST_FreeBSDKPrintf))
4552 }
else if (Type == FST_Scanf) {
4553 CheckScanfHandler H(*
this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4554 Str, HasVAListArg, Args, format_idx,
4555 inFunctionCall, CallType, CheckedVarArgs);
4567 const char *Str = StrRef.data();
4570 assert(T &&
"String literal not of constant array type!");
4571 size_t TypeSize = T->
getSize().getZExtValue();
4572 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
4583 switch (AbsFunction) {
4587 case Builtin::BI__builtin_abs:
4588 return Builtin::BI__builtin_labs;
4589 case Builtin::BI__builtin_labs:
4590 return Builtin::BI__builtin_llabs;
4591 case Builtin::BI__builtin_llabs:
4594 case Builtin::BI__builtin_fabsf:
4595 return Builtin::BI__builtin_fabs;
4596 case Builtin::BI__builtin_fabs:
4597 return Builtin::BI__builtin_fabsl;
4598 case Builtin::BI__builtin_fabsl:
4601 case Builtin::BI__builtin_cabsf:
4602 return Builtin::BI__builtin_cabs;
4603 case Builtin::BI__builtin_cabs:
4604 return Builtin::BI__builtin_cabsl;
4605 case Builtin::BI__builtin_cabsl:
4608 case Builtin::BIabs:
4609 return Builtin::BIlabs;
4610 case Builtin::BIlabs:
4611 return Builtin::BIllabs;
4612 case Builtin::BIllabs:
4615 case Builtin::BIfabsf:
4616 return Builtin::BIfabs;
4617 case Builtin::BIfabs:
4618 return Builtin::BIfabsl;
4619 case Builtin::BIfabsl:
4622 case Builtin::BIcabsf:
4623 return Builtin::BIcabs;
4624 case Builtin::BIcabs:
4625 return Builtin::BIcabsl;
4626 case Builtin::BIcabsl:
4655 unsigned AbsFunctionKind) {
4656 unsigned BestKind = 0;
4658 for (
unsigned Kind = AbsFunctionKind;
Kind != 0;
4664 else if (Context.
hasSameType(ParamType, ArgType)) {
4687 llvm_unreachable(
"Type not integer, floating, or complex");
4694 switch (ValueKind) {
4699 case Builtin::BI__builtin_fabsf:
4700 case Builtin::BI__builtin_fabs:
4701 case Builtin::BI__builtin_fabsl:
4702 case Builtin::BI__builtin_cabsf:
4703 case Builtin::BI__builtin_cabs:
4704 case Builtin::BI__builtin_cabsl:
4705 return Builtin::BI__builtin_abs;
4706 case Builtin::BIfabsf:
4707 case Builtin::BIfabs:
4708 case Builtin::BIfabsl:
4709 case Builtin::BIcabsf:
4710 case Builtin::BIcabs:
4711 case Builtin::BIcabsl:
4712 return Builtin::BIabs;
4718 case Builtin::BI__builtin_abs:
4719 case Builtin::BI__builtin_labs:
4720 case Builtin::BI__builtin_llabs:
4721 case Builtin::BI__builtin_cabsf:
4722 case Builtin::BI__builtin_cabs:
4723 case Builtin::BI__builtin_cabsl:
4724 return Builtin::BI__builtin_fabsf;
4725 case Builtin::BIabs:
4726 case Builtin::BIlabs:
4727 case Builtin::BIllabs:
4728 case Builtin::BIcabsf:
4729 case Builtin::BIcabs:
4730 case Builtin::BIcabsl:
4731 return Builtin::BIfabsf;
4737 case Builtin::BI__builtin_abs:
4738 case Builtin::BI__builtin_labs:
4739 case Builtin::BI__builtin_llabs:
4740 case Builtin::BI__builtin_fabsf:
4741 case Builtin::BI__builtin_fabs:
4742 case Builtin::BI__builtin_fabsl:
4743 return Builtin::BI__builtin_cabsf;
4744 case Builtin::BIabs:
4745 case Builtin::BIlabs:
4746 case Builtin::BIllabs:
4747 case Builtin::BIfabsf:
4748 case Builtin::BIfabs:
4749 case Builtin::BIfabsl:
4750 return Builtin::BIcabsf;
4753 llvm_unreachable(
"Unable to convert function");
4764 case Builtin::BI__builtin_abs:
4765 case Builtin::BI__builtin_fabs:
4766 case Builtin::BI__builtin_fabsf:
4767 case Builtin::BI__builtin_fabsl:
4768 case Builtin::BI__builtin_labs:
4769 case Builtin::BI__builtin_llabs:
4770 case Builtin::BI__builtin_cabs:
4771 case Builtin::BI__builtin_cabsf:
4772 case Builtin::BI__builtin_cabsl:
4773 case Builtin::BIabs:
4774 case Builtin::BIlabs:
4775 case Builtin::BIllabs:
4776 case Builtin::BIfabs:
4777 case Builtin::BIfabsf:
4778 case Builtin::BIfabsl:
4779 case Builtin::BIcabs:
4780 case Builtin::BIcabsf:
4781 case Builtin::BIcabsl:
4784 llvm_unreachable(
"Unknown Builtin type");
4790 unsigned AbsKind,
QualType ArgType) {
4791 bool EmitHeaderHint =
true;
4792 const char *HeaderName =
nullptr;
4793 const char *FunctionName =
nullptr;
4795 FunctionName =
"std::abs";
4797 HeaderName =
"cstdlib";
4799 HeaderName =
"cmath";
4801 llvm_unreachable(
"Invalid Type");
4807 R.suppressDiagnostics();
4810 for (
const auto *I : R) {
4813 FDecl = dyn_cast<
FunctionDecl>(UsingD->getTargetDecl());
4830 EmitHeaderHint =
false;
4842 R.suppressDiagnostics();
4845 if (R.isSingleResult()) {
4848 EmitHeaderHint =
false;
4852 }
else if (!R.empty()) {
4858 S.
Diag(Loc, diag::note_replace_abs_function)
4864 if (!EmitHeaderHint)
4867 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
4894 void Sema::CheckAbsoluteValueFunction(
const CallExpr *Call,
4902 if (AbsKind == 0 && !IsStdAbs)
4911 const char *FunctionName =
4913 Diag(Call->
getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
4916 << FixItHint::CreateRemoval(Call->
getCallee()->getSourceRange());
4930 if (ArgValueKind == ParamValueKind) {
4936 << FDecl << ArgType << ParamType;
4938 if (NewAbsKind == 0)
4942 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
4951 if (NewAbsKind == 0)
4955 << FDecl << ParamValueKind << ArgValueKind;
4958 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
4982 << SizeRange << FnName;
4983 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
4987 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
4998 bool &IsContained) {
5001 IsContained =
false;
5014 for (
auto *FD : RD->
fields()) {
5030 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5040 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5042 return SizeOf->getTypeOfArgument();
5054 void Sema::CheckMemaccessArguments(
const CallExpr *Call,
5061 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5065 unsigned LastArg = (BId == Builtin::BImemset ||
5066 BId == Builtin::BIstrndup ? 1 : 2);
5067 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5077 llvm::FoldingSetNodeID SizeOfArgID;
5079 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5098 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5102 if (SizeOfArgID == llvm::FoldingSetNodeID())
5103 SizeOfArg->Profile(SizeOfArgID, Context,
true);
5104 llvm::FoldingSetNodeID DestID;
5105 Dest->Profile(DestID, Context,
true);
5106 if (DestID == SizeOfArgID) {
5109 unsigned ActionIdx = 0;
5110 StringRef ReadableName = FnName->
getName();
5112 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5136 DiagRuntimeBehavior(SL, SizeOfArg,
5137 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5143 DiagRuntimeBehavior(SL, SizeOfArg,
5144 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5158 DiagRuntimeBehavior(LenExpr->
getExprLoc(), Dest,
5159 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5160 << FnName << SizeOfArgTy << ArgIdx
5161 << PointeeTy << Dest->getSourceRange()
5162 << LenExpr->getSourceRange());
5178 unsigned OperationType = 0;
5181 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5182 if (BId == Builtin::BImemcpy)
5184 else if(BId == Builtin::BImemmove)
5186 else if (BId == Builtin::BImemcmp)
5190 DiagRuntimeBehavior(
5192 PDiag(diag::warn_dyn_class_memaccess)
5193 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5194 << FnName << IsContained << ContainedRD << OperationType
5195 << Call->
getCallee()->getSourceRange());
5197 BId != Builtin::BImemset)
5198 DiagRuntimeBehavior(
5200 PDiag(diag::warn_arc_object_memaccess)
5201 << ArgIdx << FnName << PointeeTy
5202 << Call->
getCallee()->getSourceRange());
5206 DiagRuntimeBehavior(
5208 PDiag(diag::note_bad_memaccess_silence)
5229 if (isa<IntegerLiteral>(RHS))
5231 else if (isa<IntegerLiteral>(LHS))
5245 if (CAT->getSize().getSExtValue() <= 1)
5255 void Sema::CheckStrlcpycatArguments(
const CallExpr *Call,
5260 if ((NumArgs != 3) && (NumArgs != 4))
5265 const Expr *CompareWithSrc =
nullptr;
5273 CompareWithSrc = Ex;
5276 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5277 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5278 SizeCall->getNumArgs() == 1)
5283 if (!CompareWithSrc)
5295 if (!CompareWithSrcDRE ||
5299 const Expr *OriginalSizeArg = Call->
getArg(2);
5300 Diag(CompareWithSrcDRE->
getLocStart(), diag::warn_strlcpycat_wrong_size)
5301 << OriginalSizeArg->getSourceRange() << FnName;
5312 llvm::raw_svector_ostream OS(sizeString);
5314 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5317 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5324 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5325 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5326 return D1->getDecl() == D2->getDecl();
5331 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5335 return CE->getArg(0)->IgnoreParenCasts();
5343 void Sema::CheckStrncatArguments(
const CallExpr *CE,
5358 unsigned PatternType = 0;
5366 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5367 if (BE->getOpcode() ==
BO_Sub) {
5369 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5380 if (PatternType == 0)
5399 if (!isKnownSizeArray) {
5400 if (PatternType == 1)
5401 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5403 Diag(SL, diag::warn_strncat_src_size) << SR;
5407 if (PatternType == 1)
5408 Diag(SL, diag::warn_strncat_large_size) << SR;
5410 Diag(SL, diag::warn_strncat_src_size) << SR;
5413 llvm::raw_svector_ostream OS(sizeString);
5415 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5418 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5421 Diag(SL, diag::note_strncat_wrong_size)
5427 static Expr *
EvalVal(
Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5438 Expr *stackE =
nullptr;
5445 stackE =
EvalAddr(RetValExp, refVars,
nullptr);
5447 stackE =
EvalVal(RetValExp, refVars,
nullptr);
5455 if (refVars.empty()) {
5456 diagLoc = stackE->getLocStart();
5457 diagRange = stackE->getSourceRange();
5463 diagLoc = refVars[0]->getLocStart();
5464 diagRange = refVars[0]->getSourceRange();
5467 if (
DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
5469 : diag::warn_ret_stack_addr)
5470 << DR->getDecl()->getDeclName() << diagRange;
5471 }
else if (isa<BlockExpr>(stackE)) {
5472 S.
Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5473 }
else if (isa<AddrLabelExpr>(stackE)) {
5474 S.
Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5477 : diag::warn_ret_local_temp_addr)
5483 for (
unsigned i = 0, e = refVars.size(); i != e; ++i) {
5484 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5488 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5489 : stackE->getSourceRange();
5530 "EvalAddr only works on pointers");
5537 switch (E->getStmtClass()) {
5538 case Stmt::DeclRefExprClass: {
5548 if (V->hasLocalStorage() &&
5549 V->getType()->isReferenceType() && V->hasInit()) {
5551 refVars.push_back(DR);
5552 return EvalAddr(V->getInit(), refVars, ParentDecl);
5558 case Stmt::UnaryOperatorClass: {
5569 case Stmt::BinaryOperatorClass: {
5585 return EvalAddr(Base, refVars, ParentDecl);
5590 case Stmt::ConditionalOperatorClass: {
5597 if (!LHSExpr->getType()->isVoidType())
5598 if (
Expr *LHS =
EvalAddr(LHSExpr, refVars, ParentDecl))
5609 case Stmt::BlockExprClass:
5610 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5614 case Stmt::AddrLabelExprClass:
5617 case Stmt::ExprWithCleanupsClass:
5618 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5623 case Stmt::ImplicitCastExprClass:
5624 case Stmt::CStyleCastExprClass:
5625 case Stmt::CXXFunctionalCastExprClass:
5626 case Stmt::ObjCBridgedCastExprClass:
5627 case Stmt::CXXStaticCastExprClass:
5628 case Stmt::CXXDynamicCastExprClass:
5629 case Stmt::CXXConstCastExprClass:
5630 case Stmt::CXXReinterpretCastExprClass: {
5631 Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
5632 switch (cast<CastExpr>(E)->getCastKind()) {
5642 return EvalAddr(SubExpr, refVars, ParentDecl);
5645 return EvalVal(SubExpr, refVars, ParentDecl);
5651 return EvalAddr(SubExpr, refVars, ParentDecl);
5660 case Stmt::MaterializeTemporaryExprClass:
5662 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5663 refVars, ParentDecl))
5689 switch (E->getStmtClass()) {
5690 case Stmt::ImplicitCastExprClass: {
5699 case Stmt::ExprWithCleanupsClass:
5700 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5702 case Stmt::DeclRefExprClass: {
5714 if (V == ParentDecl)
5717 if (V->hasLocalStorage()) {
5718 if (!V->getType()->isReferenceType())
5725 refVars.push_back(DR);
5726 return EvalVal(V->getInit(), refVars, V);
5734 case Stmt::UnaryOperatorClass: {
5746 case Stmt::ArraySubscriptExprClass: {
5750 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5753 case Stmt::ConditionalOperatorClass: {
5761 if (!LHSExpr->getType()->isVoidType())
5762 if (
Expr *LHS =
EvalVal(LHSExpr, refVars, ParentDecl))
5774 case Stmt::MemberExprClass: {
5789 case Stmt::MaterializeTemporaryExprClass:
5791 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5792 refVars, ParentDecl))
5810 Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
5818 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
5821 Diag(ReturnLoc, diag::warn_null_ret)
5822 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
5831 if (Op == OO_New || Op == OO_Array_New) {
5836 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
5837 << FD << getLangOpts().CPlusPlus11;
5853 if (
DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
5854 if (
DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
5855 if (DRL->getDecl() == DRR->getDecl())
5864 if (
FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
5868 if (
FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
5873 if (
CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
5874 if (CL->getBuiltinCallee())
5877 if (
CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
5878 if (CR->getBuiltinCallee())
5882 Diag(Loc, diag::warn_floatingpoint_eq)
5883 << LHS->getSourceRange() << RHS->getSourceRange();
5900 IntRange(
unsigned Width,
bool NonNegative)
5901 : Width(Width), NonNegative(NonNegative)
5905 static IntRange forBoolType() {
5906 return IntRange(1,
true);
5911 return forValueOfCanonicalType(C,
5916 static IntRange forValueOfCanonicalType(
ASTContext &C,
const Type *T) {
5919 if (
const VectorType *VT = dyn_cast<VectorType>(T))
5920 T = VT->getElementType().getTypePtr();
5921 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
5922 T = CT->getElementType().getTypePtr();
5923 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
5924 T = AT->getValueType().getTypePtr();
5927 if (
const EnumType *ET = dyn_cast<EnumType>(T)) {
5935 if (NumNegative == 0)
5936 return IntRange(NumPositive,
true);
5938 return IntRange(std::max(NumPositive + 1, NumNegative),
5953 static IntRange forTargetOfCanonicalType(
ASTContext &C,
const Type *T) {
5956 if (
const VectorType *VT = dyn_cast<VectorType>(T))
5957 T = VT->getElementType().getTypePtr();
5958 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
5959 T = CT->getElementType().getTypePtr();
5960 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
5961 T = AT->getValueType().getTypePtr();
5962 if (
const EnumType *ET = dyn_cast<EnumType>(T))
5972 static IntRange join(IntRange L, IntRange R) {
5973 return IntRange(std::max(L.Width, R.Width),
5974 L.NonNegative && R.NonNegative);
5978 static IntRange meet(IntRange L, IntRange R) {
5979 return IntRange(std::min(L.Width, R.Width),
5980 L.NonNegative || R.NonNegative);
5984 static IntRange GetValueRange(
ASTContext &C, llvm::APSInt &value,
5985 unsigned MaxWidth) {
5986 if (value.isSigned() && value.isNegative())
5987 return IntRange(value.getMinSignedBits(),
false);
5989 if (value.getBitWidth() > MaxWidth)
5990 value = value.trunc(MaxWidth);
5994 return IntRange(value.getActiveBits(),
true);
5998 unsigned MaxWidth) {
6000 return GetValueRange(C, result.
getInt(), MaxWidth);
6003 IntRange R = GetValueRange(C, result.
getVectorElt(0), Ty, MaxWidth);
6005 IntRange El = GetValueRange(C, result.
getVectorElt(i), Ty, MaxWidth);
6006 R = IntRange::join(R, El);
6014 return IntRange::join(R, I);
6029 Ty = AtomicRHS->getValueType();
6037 static IntRange GetExprRange(
ASTContext &C,
Expr *E,
unsigned MaxWidth) {
6043 return GetValueRange(C, result.
Val, GetExprType(E), MaxWidth);
6050 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6052 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6058 return OutputTypeRange;
6061 = GetExprRange(C, CE->getSubExpr(),
6062 std::min(MaxWidth, OutputTypeRange.Width));
6065 if (SubRange.Width >= OutputTypeRange.Width)
6066 return OutputTypeRange;
6070 return IntRange(SubRange.Width,
6071 SubRange.NonNegative || OutputTypeRange.NonNegative);
6077 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6078 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6079 : CO->getFalseExpr(),
6083 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6084 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6085 return IntRange::join(L, R);
6089 switch (BO->getOpcode()) {
6100 return IntRange::forBoolType();
6112 return IntRange::forValueOfType(C, GetExprType(E));
6118 return GetExprRange(C, BO->getRHS(), MaxWidth);
6123 return IntRange::forValueOfType(C, GetExprType(E));
6128 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6129 GetExprRange(C, BO->getRHS(), MaxWidth));
6136 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6137 if (I->getValue() == 1) {
6138 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6139 return IntRange(R.Width,
true);
6145 return IntRange::forValueOfType(C, GetExprType(E));
6150 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6155 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6156 shift.isNonNegative()) {
6157 unsigned zext = shift.getZExtValue();
6158 if (zext >= L.Width)
6159 L.Width = (L.NonNegative ? 0 : 1);
6169 return GetExprRange(C, BO->getRHS(), MaxWidth);
6173 if (BO->getLHS()->getType()->isPointerType())
6174 return IntRange::forValueOfType(C, GetExprType(E));
6182 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6185 llvm::APSInt divisor;
6186 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6187 unsigned log2 = divisor.logBase2();
6188 if (log2 >= L.Width)
6189 L.Width = (L.NonNegative ? 0 : 1);
6191 L.Width = std::min(L.Width - log2, MaxWidth);
6196 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6197 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6205 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6206 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6208 IntRange meet = IntRange::meet(L, R);
6209 meet.Width = std::min(meet.Width, MaxWidth);
6223 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6224 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6225 return IntRange::join(L, R);
6229 switch (UO->getOpcode()) {
6232 return IntRange::forBoolType();
6237 return IntRange::forValueOfType(C, GetExprType(E));
6240 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6245 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6248 return IntRange(BitField->getBitWidthValue(C),
6249 BitField->getType()->isUnsignedIntegerOrEnumerationType());
6251 return IntRange::forValueOfType(C, GetExprType(E));
6255 return GetExprRange(C, E, C.
getIntWidth(GetExprType(E)));
6261 static bool IsSameFloatAfterCast(
const llvm::APFloat &value,
6262 const llvm::fltSemantics &Src,
6263 const llvm::fltSemantics &Tgt) {
6264 llvm::APFloat truncated = value;
6267 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6268 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6270 return truncated.bitwiseIsEqual(value);
6278 static bool IsSameFloatAfterCast(
const APValue &value,
6279 const llvm::fltSemantics &Src,
6280 const llvm::fltSemantics &Tgt) {
6282 return IsSameFloatAfterCast(value.
getFloat(), Src, Tgt);
6286 if (!IsSameFloatAfterCast(value.
getVectorElt(i), Src, Tgt))
6298 static bool IsZero(
Sema &S,
Expr *E) {
6302 if (isa<EnumConstantDecl>(DR->getDecl()))
6306 if (E->getLocStart().isMacroID())
6313 static bool HasEnumType(
Expr *E) {
6317 ICE->getCastKind() !=
CK_NoOp)
6319 E = ICE->getSubExpr();
6336 <<
"< 0" <<
"false" << HasEnumType(E->
getLHS())
6337 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6338 }
else if (op ==
BO_GE && IsZero(S, E->
getRHS())) {
6340 <<
">= 0" <<
"true" << HasEnumType(E->
getLHS())
6341 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6342 }
else if (op ==
BO_GT && IsZero(S, E->
getLHS())) {
6344 <<
"0 >" <<
"false" << HasEnumType(E->
getRHS())
6345 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6346 }
else if (op ==
BO_LE && IsZero(S, E->
getLHS())) {
6348 <<
"0 <=" <<
"true" << HasEnumType(E->
getRHS())
6349 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6365 OtherT = AT->getValueType();
6366 IntRange OtherRange = IntRange::forValueOfType(S.
Context, OtherT);
6367 unsigned OtherWidth = OtherRange.Width;
6372 if ((Value == 0) && (!OtherIsBooleanType))
6380 LiteralConstant = 0,
6383 } LiteralOrBoolConstant = LiteralConstant;
6385 if (!OtherIsBooleanType) {
6392 "comparison with non-integer type");
6397 bool EqualityOnly =
false;
6401 if (!OtherRange.NonNegative) {
6403 if (ConstantSigned) {
6404 if (OtherWidth >= Value.getMinSignedBits())
6407 if (OtherWidth >= Value.getActiveBits() + 1)
6413 if (ConstantSigned) {
6414 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6417 if (OtherWidth >= Value.getActiveBits())
6422 if (OtherRange.NonNegative) {
6423 if (OtherWidth >= Value.getActiveBits())
6426 assert(!ConstantSigned &&
6427 "Two signed types converted to unsigned types.");
6429 if (OtherWidth > Value.getActiveBits())
6435 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6440 EqualityOnly =
true;
6444 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6447 IsTrue = op ==
BO_NE;
6448 }
else if (EqualityOnly) {
6450 }
else if (RhsConstant) {
6452 IsTrue = !PositiveConstant;
6454 IsTrue = PositiveConstant;
6457 IsTrue = !PositiveConstant;
6459 IsTrue = PositiveConstant;
6463 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6464 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6465 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6467 static const struct LinkedConditions {
6468 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6469 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6470 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6471 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6472 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6473 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6478 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6479 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6480 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6481 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6482 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6483 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6486 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6488 enum ConstantValue ConstVal = Zero;
6489 if (Value.isUnsigned() || Value.isNonNegative()) {
6491 LiteralOrBoolConstant =
6492 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6494 }
else if (Value == 1) {
6495 LiteralOrBoolConstant =
6496 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6499 LiteralOrBoolConstant = LiteralConstant;
6506 CompareBoolWithConstantResult CmpRes;
6510 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6513 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6516 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6519 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6522 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6525 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6532 if (CmpRes == AFals) {
6534 }
else if (CmpRes == ATrue) {
6544 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6545 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6548 llvm::raw_svector_ostream OS(PrettySourceValue);
6550 OS <<
'\'' << *ED <<
"' (" << Value <<
")";
6556 S.
PDiag(diag::warn_out_of_range_compare)
6557 << OS.str() << LiteralOrBoolConstant
6558 << OtherT << (OtherIsBooleanType && !OtherT->
isBooleanType()) << IsTrue
6559 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange());
6579 return AnalyzeImpConvsInComparison(S, E);
6583 return AnalyzeImpConvsInComparison(S, E);
6588 bool IsComparisonConstant =
false;
6593 llvm::APSInt RHSValue;
6594 bool IsRHSIntegralLiteral =
6596 llvm::APSInt LHSValue;
6597 bool IsLHSIntegralLiteral =
6599 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6600 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue,
true);
6601 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6602 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue,
false);
6604 IsComparisonConstant =
6605 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6616 return AnalyzeImpConvsInComparison(S, E);
6620 Expr *signedOperand, *unsignedOperand;
6623 "unsigned comparison between two signed integer expressions?");
6624 signedOperand = LHS;
6625 unsignedOperand = RHS;
6627 signedOperand = RHS;
6628 unsignedOperand = LHS;
6630 CheckTrivialUnsignedComparison(S, E);
6631 return AnalyzeImpConvsInComparison(S, E);
6635 IntRange signedRange = GetExprRange(S.
Context, signedOperand);
6645 if (signedRange.NonNegative)
6646 return CheckTrivialUnsignedComparison(S, E);
6654 IntRange unsignedRange = GetExprRange(S.
Context, unsignedOperand);
6658 assert(unsignedRange.NonNegative &&
"unsigned range includes negative?");
6660 if (unsignedRange.Width < comparisonWidth)
6665 S.
PDiag(diag::warn_mixed_sign_comparison)
6667 << LHS->getSourceRange() << RHS->getSourceRange());
6696 unsigned OriginalWidth = Value.getBitWidth();
6699 if (OriginalWidth <= FieldWidth)
6703 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6707 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6708 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6713 if (FieldWidth == 1 && Value == 1)
6716 std::string PrettyValue = Value.toString(10);
6717 std::string PrettyTrunc = TruncatedValue.toString(10);
6719 S.
Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6720 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
6721 << Init->getSourceRange();
6735 if (AnalyzeBitFieldAssignment(S, Bitfield, E->
getRHS(),
6749 bool pruneControlFlow =
false) {
6750 if (pruneControlFlow) {
6753 << SourceType << T << E->getSourceRange()
6758 << SourceType << T << E->getSourceRange() <<
SourceRange(CContext);
6764 bool pruneControlFlow =
false) {
6765 DiagnoseImpCast(S, E, E->
getType(), T, CContext, diag, pruneControlFlow);
6773 bool isExact =
false;
6774 const llvm::APFloat &Value = FL->
getValue();
6777 if (Value.convertToInteger(IntegerValue,
6778 llvm::APFloat::rmTowardZero, &isExact)
6779 == llvm::APFloat::opOK && isExact)
6788 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6789 precision = (precision * 59 + 195) / 196;
6790 Value.toString(PrettySourceValue, precision);
6794 PrettyTargetValue = IntegerValue == 0 ?
"false" :
"true";
6796 IntegerValue.toString(PrettyTargetValue);
6798 S.
Diag(FL->
getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6800 << PrettyTargetValue << FL->getSourceRange() <<
SourceRange(CContext);
6803 std::string PrettyPrintInRange(
const llvm::APSInt &Value, IntRange Range) {
6804 if (!Range.Width)
return "0";
6806 llvm::APSInt ValueInRange =
Value;
6807 ValueInRange.setIsSigned(!Range.NonNegative);
6808 ValueInRange = ValueInRange.trunc(Range.Width);
6809 return ValueInRange.toString(10);
6812 static bool IsImplicitBoolFloatConversion(
Sema &S,
Expr *Ex,
bool ToBool) {
6813 if (!isa<ImplicitCastExpr>(Ex))
6818 const Type *Source =
6825 const Type *BoolCandidateType = ToBool ? Target : Source;
6827 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
6831 void CheckImplicitArgumentConversions(
Sema &S,
CallExpr *TheCall,
6834 for (
unsigned i = 0; i < NumArgs; ++i) {
6836 if (!IsImplicitBoolFloatConversion(S, CurrA,
true))
6839 bool IsSwapped = ((i > 0) &&
6840 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i - 1),
false));
6841 IsSwapped |= ((i < (NumArgs - 1)) &&
6842 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i + 1),
false));
6847 diag::warn_impcast_floating_point_to_bool);
6854 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
6881 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
6887 static void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
6889 static void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
6894 static void checkObjCCollectionLiteralElement(
Sema &S,
6897 unsigned ElementKind) {
6899 if (
auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
6902 Element = ICE->getSubExpr();
6912 S.
Diag(Element->getLocStart(),
6913 diag::warn_objc_collection_literal_element)
6914 << ElementType << ElementKind << TargetElementType
6915 << Element->getSourceRange();
6918 if (
auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
6919 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
6920 else if (
auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
6921 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
6926 static void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
6935 if (TargetObjCPtr->isUnspecialized() ||
6936 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
6941 if (TypeArgs.size() != 1)
6944 QualType TargetElementType = TypeArgs[0];
6945 for (
unsigned I = 0, N = ArrayLiteral->
getNumElements(); I != N; ++I) {
6946 checkObjCCollectionLiteralElement(S, TargetElementType,
6954 static void checkObjCDictionaryLiteral(
6964 if (TargetObjCPtr->isUnspecialized() ||
6965 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
6970 if (TypeArgs.size() != 2)
6973 QualType TargetKeyType = TypeArgs[0];
6974 QualType TargetObjectType = TypeArgs[1];
6975 for (
unsigned I = 0, N = DictionaryLiteral->
getNumElements(); I != N; ++I) {
6977 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
6978 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
6988 if (Source == Target)
return;
7001 if (isa<StringLiteral>(E))
7005 return DiagnoseImpCast(S, E, T, CC,
7006 diag::warn_impcast_string_literal_to_bool);
7007 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
7008 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
7011 return DiagnoseImpCast(S, E, T, CC,
7012 diag::warn_impcast_objective_c_literal_to_bool);
7023 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7024 checkObjCArrayLiteral(S,
QualType(Target, 0), ArrayLiteral);
7025 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7026 checkObjCDictionaryLiteral(S,
QualType(Target, 0), DictionaryLiteral);
7029 if (isa<VectorType>(Source)) {
7030 if (!isa<VectorType>(Target)) {
7033 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
7041 Source = cast<VectorType>(Source)->
getElementType().getTypePtr();
7042 Target = cast<VectorType>(Target)->
getElementType().getTypePtr();
7044 if (
auto VecTy = dyn_cast<VectorType>(Target))
7045 Target = VecTy->getElementType().getTypePtr();
7048 if (isa<ComplexType>(Source)) {
7049 if (!isa<ComplexType>(Target)) {
7053 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
7056 Source = cast<ComplexType>(Source)->
getElementType().getTypePtr();
7057 Target = cast<ComplexType>(Target)->
getElementType().getTypePtr();
7066 if (TargetBT && TargetBT->isFloatingPoint()) {
7070 if (SourceBT->
getKind() > TargetBT->getKind()) {
7076 if (IsSameFloatAfterCast(result.
Val,
7085 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
7091 if (TargetBT && TargetBT->isInteger()) {
7102 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
7104 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7119 const Type *InnerType =
7121 if (isa<ImplicitCastExpr>(LastA) && (InnerType == Target)) {
7123 DiagnoseImpCast(S, E, T, CC,
7124 diag::warn_impcast_floating_point_to_bool);
7131 DiagnoseNullConversion(S, E, T, CC);
7142 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.
Context, Target);
7144 if (SourceRange.Width > TargetRange.Width) {
7147 llvm::APSInt
Value(32);
7152 std::string PrettySourceValue = Value.toString(10);
7153 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7156 S.
PDiag(diag::warn_impcast_integer_precision_constant)
7157 << PrettySourceValue << PrettyTargetValue
7158 << E->
getType() << T << E->getSourceRange()
7168 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7170 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7173 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7174 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7175 SourceRange.Width == TargetRange.Width)) {
7180 unsigned DiagID = diag::warn_impcast_integer_sign;
7188 DiagID = diag::warn_impcast_integer_sign_conditional;
7192 return DiagnoseImpCast(S, E, T, CC, DiagID);
7202 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7210 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7211 TargetEnum->getDecl()->hasNameForLinkage() &&
7212 SourceEnum != TargetEnum) {
7216 return DiagnoseImpCast(S, E, SourceType, T, CC,
7217 diag::warn_impcast_different_enum_types);
7230 if (isa<ConditionalOperator>(E))
7231 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7233 AnalyzeImplicitConversions(S, E, CC);
7235 return CheckImplicitConversion(S, E, T, CC, &ICContext);
7243 bool Suspicious =
false;
7244 CheckConditionalOperand(S, E->
getTrueExpr(), T, CC, Suspicious);
7245 CheckConditionalOperand(S, E->
getFalseExpr(), T, CC, Suspicious);
7249 if (!Suspicious)
return;
7252 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7257 if (E->
getType() == T)
return;
7261 E->
getType(), CC, &Suspicious);
7264 E->
getType(), CC, &Suspicious);
7287 if (isa<ConditionalOperator>(E)) {
7289 CheckConditionalOperator(S, CO, CC, T);
7294 if (
CallExpr *Call = dyn_cast<CallExpr>(E))
7295 CheckImplicitArgumentConversions(S, Call, CC);
7301 CheckImplicitConversion(S, E, T, CC);
7306 if (POE->getResultExpr())
7307 E = POE->getResultExpr();
7311 if (OVE->getSourceExpr())
7312 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7317 if (isa<ExplicitCastExpr>(E)) {
7319 return AnalyzeImplicitConversions(S, E, CC);
7324 if (BO->isComparisonOp())
7325 return AnalyzeComparison(S, BO);
7329 return AnalyzeAssignment(S, BO);
7336 if (isa<StmtExpr>(E))
return;
7339 if (isa<UnaryExprOrTypeTraitExpr>(E))
return;
7345 for (
Stmt *SubStmt : E->children()) {
7346 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
7350 if (IsLogicalAndOperator &&
7355 AnalyzeImplicitConversions(S, ChildExpr, CC);
7360 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7361 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
7364 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7365 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
7369 if (U->getOpcode() ==
UO_LNot)
7370 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7389 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7392 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7393 if (!M->getMemberDecl()->getType()->isReferenceType())
7395 }
else if (
const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7407 SemaRef.
Diag(FD->
getLocation(), diag::note_reference_is_return_value) << FD;
7437 bool IsEqual, SourceRange Range) {
7452 if (isa<CXXThisExpr>(E)) {
7453 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7454 : diag::warn_this_bool_conversion;
7455 Diag(E->
getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7459 bool IsAddressOf =
false;
7465 E = UO->getSubExpr();
7469 unsigned DiagID = IsCompare
7470 ? diag::warn_address_of_reference_null_compare
7471 : diag::warn_address_of_reference_bool_conversion;
7483 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7484 D = M->getMemberDecl();
7492 if (
const ParmVarDecl* PV = dyn_cast<ParmVarDecl>(D)) {
7493 if (getCurFunction() && !getCurFunction()->ModifiedNonNullParams.count(PV))
7494 if (
const FunctionDecl* FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7496 llvm::SmallBitVector AttrNonNull(NumArgs);
7499 AttrNonNull.set(0, NumArgs);
7502 for (
unsigned Val :
NonNull->args()) {
7505 AttrNonNull.set(Val);
7508 if (!AttrNonNull.empty())
7509 for (
unsigned i = 0; i < NumArgs; ++i)
7511 (AttrNonNull[i] || PV->hasAttr<NonNullAttr>())) {
7513 llvm::raw_string_ostream
S(Str);
7514 E->printPretty(S,
nullptr, getPrintingPolicy());
7515 unsigned DiagID = IsCompare ? diag::warn_nonnull_parameter_compare
7516 : diag::warn_cast_nonnull_to_bool;
7518 << Range << IsEqual;
7529 if (IsAddressOf && IsFunction) {
7534 if (!IsAddressOf && !IsFunction && !IsArray)
7539 llvm::raw_string_ostream
S(Str);
7540 E->printPretty(S,
nullptr, getPrintingPolicy());
7542 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7543 : diag::warn_impcast_pointer_to_bool;
7547 else if (IsFunction)
7552 llvm_unreachable(
"Could not determine diagnostic.");
7553 Diag(E->
getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7554 << Range << IsEqual;
7566 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7567 if (ReturnType.isNull())
7574 if (!ReturnType->isPointerType()) {
7577 if (!ReturnType->isIntegerType())
7586 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7603 if (isUnevaluatedContext())
7613 CheckArrayAccess(E);
7616 AnalyzeImplicitConversions(*
this, E, CC);
7622 ::CheckBoolLikeConversion(*
this, E, CC);
7627 void Sema::CheckForIntOverflow (
Expr *E) {
7643 class SequenceTree {
7645 explicit Value(
unsigned Parent) : Parent(Parent), Merged(
false) {}
7646 unsigned Parent : 31;
7655 explicit Seq(
unsigned N) : Index(N) {}
7657 friend class SequenceTree;
7662 SequenceTree() { Values.push_back(
Value(0)); }
7663 Seq root()
const {
return Seq(0); }
7668 Seq allocate(Seq Parent) {
7669 Values.push_back(
Value(Parent.Index));
7670 return Seq(Values.size() - 1);
7675 Values[S.Index].Merged =
true;
7681 bool isUnsequenced(Seq Cur, Seq Old) {
7682 unsigned C = representative(Cur.Index);
7683 unsigned Target = representative(Old.Index);
7684 while (C >= Target) {
7687 C = Values[
C].Parent;
7694 unsigned representative(
unsigned K) {
7695 if (Values[K].Merged)
7697 return Values[K].Parent = representative(Values[K].Parent);
7717 UK_Count = UK_ModAsSideEffect + 1
7721 Usage() : Use(nullptr), Seq() {}
7723 SequenceTree::Seq Seq;
7727 UsageInfo() : Diagnosed(
false) {}
7728 Usage Uses[UK_Count];
7732 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7738 UsageInfoMap UsageMap;
7740 SequenceTree::Seq Region;
7743 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7746 SmallVectorImpl<Expr *> &WorkList;
7753 struct SequencedSubexpression {
7754 SequencedSubexpression(SequenceChecker &Self)
7755 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7756 Self.ModAsSideEffect = &ModAsSideEffect;
7758 ~SequencedSubexpression() {
7759 for (
auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7761 UsageInfo &U = Self.UsageMap[MI->first];
7762 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7763 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7764 SideEffectUsage = MI->second;
7766 Self.ModAsSideEffect = OldModAsSideEffect;
7769 SequenceChecker &Self;
7771 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
7778 class EvaluationTracker {
7780 EvaluationTracker(SequenceChecker &Self)
7781 : Self(Self), Prev(Self.EvalTracker), EvalOK(
true) {
7782 Self.EvalTracker =
this;
7784 ~EvaluationTracker() {
7785 Self.EvalTracker = Prev;
7787 Prev->EvalOK &= EvalOK;
7790 bool evaluate(
const Expr *E,
bool &Result) {
7798 SequenceChecker &Self;
7799 EvaluationTracker *Prev;
7805 Object getObject(
Expr *E,
bool Mod)
const {
7809 return getObject(UO->getSubExpr(), Mod);
7812 return getObject(BO->
getRHS(), Mod);
7814 return getObject(BO->
getLHS(), Mod);
7815 }
else if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7817 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
7818 return ME->getMemberDecl();
7819 }
else if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7826 void addUsage(UsageInfo &UI, Object O,
Expr *Ref, UsageKind UK) {
7827 Usage &U = UI.Uses[UK];
7828 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
7829 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
7830 ModAsSideEffect->push_back(std::make_pair(O, U));
7836 void checkUsage(Object O, UsageInfo &UI,
Expr *Ref, UsageKind OtherKind,
7841 const Usage &U = UI.Uses[OtherKind];
7842 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
7846 Expr *ModOrUse = Ref;
7847 if (OtherKind == UK_Use)
7848 std::swap(Mod, ModOrUse);
7851 IsModMod ? diag::warn_unsequenced_mod_mod
7852 : diag::warn_unsequenced_mod_use)
7854 UI.Diagnosed =
true;
7857 void notePreUse(Object O,
Expr *Use) {
7858 UsageInfo &U = UsageMap[O];
7860 checkUsage(O, U, Use, UK_ModAsValue,
false);
7862 void notePostUse(Object O,
Expr *Use) {
7863 UsageInfo &U = UsageMap[O];
7864 checkUsage(O, U, Use, UK_ModAsSideEffect,
false);
7865 addUsage(U, O, Use, UK_Use);
7868 void notePreMod(Object O,
Expr *Mod) {
7869 UsageInfo &U = UsageMap[O];
7871 checkUsage(O, U, Mod, UK_ModAsValue,
true);
7872 checkUsage(O, U, Mod, UK_Use,
false);
7874 void notePostMod(Object O,
Expr *Use, UsageKind UK) {
7875 UsageInfo &U = UsageMap[O];
7876 checkUsage(O, U, Use, UK_ModAsSideEffect,
true);
7877 addUsage(U, O, Use, UK);
7881 SequenceChecker(
Sema &S,
Expr *E, SmallVectorImpl<Expr *> &WorkList)
7882 :
Base(S.Context), SemaRef(S), Region(Tree.root()),
7883 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
7887 void VisitStmt(
Stmt *S) {
7891 void VisitExpr(
Expr *E) {
7897 Object O = Object();
7913 SequenceTree::Seq LHS = Tree.allocate(Region);
7914 SequenceTree::Seq RHS = Tree.allocate(Region);
7915 SequenceTree::Seq OldRegion = Region;
7918 SequencedSubexpression SeqLHS(*
this);
7938 Object O = getObject(BO->
getLHS(),
true);
7940 return VisitExpr(BO);
7950 if (isa<CompoundAssignOperator>(BO))
7955 if (isa<CompoundAssignOperator>(BO))
7964 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7965 : UK_ModAsSideEffect);
7968 VisitBinAssign(CAO);
7971 void VisitUnaryPreInc(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7972 void VisitUnaryPreDec(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
7974 Object O = getObject(UO->
getSubExpr(),
true);
7976 return VisitExpr(UO);
7982 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
7983 : UK_ModAsSideEffect);
7986 void VisitUnaryPostInc(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7987 void VisitUnaryPostDec(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
7989 Object O = getObject(UO->
getSubExpr(),
true);
7991 return VisitExpr(UO);
7995 notePostMod(O, UO, UK_ModAsSideEffect);
8004 EvaluationTracker Eval(*
this);
8006 SequencedSubexpression Sequenced(*
this);
8011 if (Eval.evaluate(BO->
getLHS(), Result)) {
8021 WorkList.push_back(BO->
getRHS());
8025 EvaluationTracker Eval(*
this);
8027 SequencedSubexpression Sequenced(*
this);
8032 if (Eval.evaluate(BO->
getLHS(), Result)) {
8036 WorkList.push_back(BO->
getRHS());
8043 EvaluationTracker Eval(*
this);
8045 SequencedSubexpression Sequenced(*
this);
8050 if (Eval.evaluate(CO->
getCond(), Result))
8065 SequencedSubexpression Sequenced(*
this);
8066 Base::VisitCallExpr(CE);
8073 SequencedSubexpression Sequenced(*
this);
8076 return VisitExpr(CCE);
8080 SequenceTree::Seq Parent = Region;
8084 Region = Tree.allocate(Parent);
8085 Elts.push_back(Region);
8091 for (
unsigned I = 0; I < Elts.size(); ++I)
8092 Tree.merge(Elts[I]);
8096 if (!SemaRef.getLangOpts().CPlusPlus11)
8097 return VisitExpr(ILE);
8101 SequenceTree::Seq Parent = Region;
8102 for (
unsigned I = 0; I < ILE->
getNumInits(); ++I) {
8105 Region = Tree.allocate(Parent);
8106 Elts.push_back(Region);
8112 for (
unsigned I = 0; I < Elts.size(); ++I)
8113 Tree.merge(Elts[I]);
8118 void Sema::CheckUnsequencedOperations(
Expr *E) {
8120 WorkList.push_back(E);
8121 while (!WorkList.empty()) {
8122 Expr *Item = WorkList.pop_back_val();
8123 SequenceChecker(*
this, Item, WorkList);
8129 CheckImplicitConversions(E, CheckLoc);
8130 CheckUnsequencedOperations(E);
8132 CheckForIntOverflow(E);
8138 (void) AnalyzeBitFieldAssignment(*
this, BitField, Init, InitLoc);
8145 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8149 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8153 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8167 S.
Diag(Loc, diag::err_array_star_in_function_definition);
8177 bool CheckParameterNames) {
8178 bool HasInvalidParm =
false;
8179 for (; P != PEnd; ++
P) {
8189 diag::err_typecheck_decl_incomplete_type)) {
8191 HasInvalidParm =
true;
8196 if (CheckParameterNames &&
8199 !getLangOpts().CPlusPlus)
8221 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8226 MarkFunctionReferenced(Param->
getLocation(), Destructor);
8227 DiagnoseUseOfDecl(Destructor, Param->
getLocation());
8234 return HasInvalidParm;
8242 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.
getBegin()))
8251 if (!DestPtr)
return;
8257 if (DestAlign.
isOne())
return;
8261 if (!SrcPtr)
return;
8271 if (SrcAlign >= DestAlign)
return;
8277 << TRange << Op->getSourceRange();
8296 if (Size != 1 || !ND)
return false;
8299 if (!FD)
return false;
8322 if (!RD)
return false;
8323 if (RD->
isUnion())
return false;
8324 if (
const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8325 if (!CRD->isStandardLayout())
return false;
8331 if (isa<FieldDecl>(D))
8336 void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
8338 bool AllowOnePastEnd,
bool IndexNegated) {
8357 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8358 ND = dyn_cast<NamedDecl>(DRE->
getDecl());
8359 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8360 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8362 if (index.isUnsigned() || !index.isNegative()) {
8363 llvm::APInt size = ArrayTy->
getSize();
8364 if (!size.isStrictlyPositive())
8368 if (BaseType != EffectiveType) {
8370 uint64_t ptrarith_typesize = Context.
getTypeSize(EffectiveType);
8371 uint64_t array_typesize = Context.
getTypeSize(BaseType);
8373 if (!ptrarith_typesize) ptrarith_typesize = 1;
8374 if (ptrarith_typesize != array_typesize) {
8376 uint64_t ratio = array_typesize / ptrarith_typesize;
8379 if (ptrarith_typesize * ratio == array_typesize)
8380 size *= llvm::APInt(size.getBitWidth(), ratio);
8384 if (size.getBitWidth() > index.getBitWidth())
8385 index = index.zext(size.getBitWidth());
8386 else if (size.getBitWidth() < index.getBitWidth())
8387 size = size.zext(index.getBitWidth());
8393 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8410 IndexExpr->getLocStart());
8416 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8418 DiagID = diag::warn_array_index_exceeds_bounds;
8420 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8421 PDiag(DiagID) << index.toString(10,
true)
8422 << size.toString(10,
true)
8423 << (
unsigned)size.getLimitedValue(~0U)
8424 << IndexExpr->getSourceRange());
8426 unsigned DiagID = diag::warn_array_index_precedes_bounds;
8428 DiagID = diag::warn_ptr_arith_precedes_bounds;
8429 if (index.isNegative()) index = -index;
8432 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8433 PDiag(DiagID) << index.toString(10,
true)
8434 << IndexExpr->getSourceRange());
8440 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8442 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8444 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8445 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8450 PDiag(diag::note_array_index_out_of_bounds)
8454 void Sema::CheckArrayAccess(
const Expr *
expr) {
8455 int AllowOnePastEnd = 0;
8458 switch (expr->getStmtClass()) {
8459 case Stmt::ArraySubscriptExprClass: {
8462 AllowOnePastEnd > 0);
8465 case Stmt::UnaryOperatorClass: {
8481 case Stmt::ConditionalOperatorClass: {
8484 CheckArrayAccess(lhs);
8486 CheckArrayAccess(rhs);
8498 struct RetainCycleOwner {
8499 RetainCycleOwner() : Variable(nullptr), Indirect(
false) {}
8505 void setLocsFrom(
Expr *e) {
8507 Range = e->getSourceRange();
8521 owner.Variable = var;
8523 owner.setLocsFrom(ref);
8530 if (
CastExpr *cast = dyn_cast<CastExpr>(e)) {
8531 switch (cast->getCastKind()) {
8536 e = cast->getSubExpr();
8553 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8554 owner.Indirect =
true;
8558 if (
DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8560 if (!var)
return false;
8564 if (
MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8565 if (member->isArrow())
return false;
8568 e = member->getBase();
8577 if (!pre)
return false;
8580 if (!property->isRetaining() &&
8581 !(
property->getPropertyIvarDecl() &&
8582 property->getPropertyIvarDecl()->getType()
8586 owner.Indirect =
true;
8589 if (!owner.Variable)
8592 owner.Range = pre->getSourceRange();
8595 e =
const_cast<Expr*
>(cast<OpaqueValueExpr>(pre->
getBase())
8610 Context(Context), Variable(variable), Capturer(nullptr),
8611 VarWillBeReased(
false) {}
8615 bool VarWillBeReased;
8618 if (ref->
getDecl() == Variable && !Capturer)
8623 if (Capturer)
return;
8636 if (Capturer)
return;
8644 if (
const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8645 if (DRE->
getDecl() != Variable)
8651 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8661 assert(owner.Variable && owner.Loc.isValid());
8669 e = ME->getInstanceReceiver();
8672 e = e->IgnoreParenCasts();
8674 }
else if (
CallExpr *CE = dyn_cast<CallExpr>(e)) {
8679 if (FnI && FnI->
isStr(
"_Block_copy")) {
8690 FindCaptureVisitor visitor(S.
Context, owner.Variable);
8692 return visitor.VarWillBeReased ?
nullptr : visitor.Capturer;
8696 RetainCycleOwner &owner) {
8698 assert(owner.Variable && owner.Loc.isValid());
8701 << owner.Variable << capturer->getSourceRange();
8702 S.
Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8703 << owner.Indirect << owner.Range;
8712 while (!str.empty() && str.front() ==
'_') str = str.substr(1);
8713 if (str.startswith(
"set"))
8714 str = str.substr(3);
8715 else if (str.startswith(
"add")) {
8717 if (sel.
getNumArgs() == 1 && str.startswith(
"addOperationWithBlock"))
8719 str = str.substr(3);
8724 if (str.empty())
return true;
8730 bool IsMutableArray = S.
NSAPIObj->isSubclassOfNSClass(
8733 if (!IsMutableArray) {
8740 S.
NSAPIObj->getNSArrayMethodKind(Sel);
8765 bool IsMutableDictionary = S.
NSAPIObj->isSubclassOfNSClass(
8768 if (!IsMutableDictionary) {
8775 S.
NSAPIObj->getNSDictionaryMethodKind(Sel);
8796 bool IsMutableSet = S.
NSAPIObj->isSubclassOfNSClass(
8800 bool IsMutableOrderedSet = S.
NSAPIObj->isSubclassOfNSClass(
8803 if (!IsMutableSet && !IsMutableOrderedSet) {
8842 int ArgIndex = *ArgOpt;
8850 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8851 if (ArgRE->isObjCSelfExpr()) {
8852 Diag(Message->getSourceRange().getBegin(),
8853 diag::warn_objc_circular_container)
8854 << ArgRE->getDecl()->getName() << StringRef(
"super");
8864 if (
DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
8865 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
8866 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
8868 Diag(Message->getSourceRange().getBegin(),
8869 diag::warn_objc_circular_container)
8871 if (!ArgRE->isObjCSelfExpr()) {
8873 diag::note_objc_circular_container_declared_here)
8878 }
else if (
ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
8880 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
8882 Diag(Message->getSourceRange().getBegin(),
8883 diag::warn_objc_circular_container)
8886 diag::note_objc_circular_container_declared_here)
8902 RetainCycleOwner owner;
8908 owner.Variable = getCurMethodDecl()->getSelfDecl();
8914 for (
unsigned i = 0, e = msg->
getNumArgs(); i != e; ++i)
8921 RetainCycleOwner owner;
8930 RetainCycleOwner Owner;
8944 Expr *RHS,
bool isProperty) {
8956 S.
Diag(Loc, diag::warn_arc_literal_assign)
8958 << (isProperty ? 0 : 1)
8959 << RHS->getSourceRange();
8966 Expr *RHS,
bool isProperty) {
8970 S.
Diag(Loc, diag::warn_arc_retained_assign)
8972 << (isProperty ? 0 : 1)
8973 << RHS->getSourceRange();
8976 RHS = cast->getSubExpr();
9018 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
9019 getCurFunction()->markSafeWeakUse(LHS);
9022 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9042 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9048 Diag(Loc, diag::warn_arc_retained_property_assign)
9049 << RHS->getSourceRange();
9052 RHS = cast->getSubExpr();
9078 bool StmtLineInvalid;
9081 if (StmtLineInvalid)
9084 bool BodyLineInvalid;
9087 if (BodyLineInvalid)
9091 if (StmtLine != BodyLine)
9103 if (CurrentInstantiationScope)
9112 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9116 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
9120 const Stmt *PossibleBody) {
9121 assert(!CurrentInstantiationScope);
9126 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9127 StmtLoc = FS->getRParenLoc();
9128 Body = FS->getBody();
9129 DiagID = diag::warn_empty_for_body;
9130 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9131 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9132 Body = WS->getBody();
9133 DiagID = diag::warn_empty_while_body;
9143 if (Diags.isIgnored(DiagID, NBody->
getSemiLoc()))
9147 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9161 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9162 if (!ProbableTypo) {
9163 bool BodyColInvalid;
9165 PossibleBody->getLocStart(),
9170 bool StmtColInvalid;
9177 if (BodyCol > StmtCol)
9178 ProbableTypo =
true;
9183 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
9193 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9196 if (!ActiveTemplateInstantiations.empty())
9221 if (LHSDeclRef && RHSDeclRef) {
9222 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
9228 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9229 << LHSExpr->getSourceRange()
9230 << RHSExpr->getSourceRange();
9238 const Expr *LHSBase = LHSExpr;
9239 const Expr *RHSBase = RHSExpr;
9242 if (!LHSME || !RHSME)
9245 while (LHSME && RHSME) {
9251 RHSBase = RHSME->getBase();
9258 if (LHSDeclRef && RHSDeclRef) {
9259 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
9265 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9266 << LHSExpr->getSourceRange()
9267 << RHSExpr->getSourceRange();
9271 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9272 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9273 << LHSExpr->getSourceRange()
9274 << RHSExpr->getSourceRange();
9294 if (!isLayoutCompatible(C, Field1->
getType(), Field2->
getType()))
9318 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9328 Base1 = D1CXX->bases_begin(),
9329 BaseEnd1 = D1CXX->bases_end(),
9333 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9336 }
else if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9347 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9348 if (!isLayoutCompatible(C, *Field1, *Field2))
9351 if (Field1 != Field1End || Field2 != Field2End)
9362 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9363 for (
auto *Field2 : RD2->
fields())
9364 UnmatchedFields.insert(Field2);
9366 for (
auto *Field1 : RD1->
fields()) {
9367 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
9368 I = UnmatchedFields.begin(),
9369 E = UnmatchedFields.end();
9371 for ( ; I != E; ++I) {
9372 if (isLayoutCompatible(C, Field1, *I)) {
9373 bool Result = UnmatchedFields.erase(*I);
9383 return UnmatchedFields.empty();
9391 return isLayoutCompatibleUnion(C, RD1, RD2);
9393 return isLayoutCompatibleStruct(C, RD1, RD2);
9416 if (TC1 == Type::Enum) {
9417 return isLayoutCompatible(C,
9418 cast<EnumType>(T1)->getDecl(),
9419 cast<EnumType>(T2)->getDecl());
9420 }
else if (TC1 == Type::Record) {
9424 return isLayoutCompatible(C,
9425 cast<RecordType>(T1)->getDecl(),
9426 cast<RecordType>(T2)->getDecl());
9443 bool FindTypeTagExpr(
const Expr *TypeExpr,
const ASTContext &Ctx,
9444 const ValueDecl **VD, uint64_t *MagicValue) {
9451 switch (TypeExpr->getStmtClass()) {
9452 case Stmt::UnaryOperatorClass: {
9461 case Stmt::DeclRefExprClass: {
9462 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9467 case Stmt::IntegerLiteralClass: {
9469 llvm::APInt MagicValueAPInt = IL->
getValue();
9470 if (MagicValueAPInt.getActiveBits() <= 64) {
9471 *MagicValue = MagicValueAPInt.getZExtValue();
9477 case Stmt::BinaryConditionalOperatorClass:
9478 case Stmt::ConditionalOperatorClass: {
9480 cast<AbstractConditionalOperator>(TypeExpr);
9492 case Stmt::BinaryOperatorClass: {
9519 bool GetMatchingCType(
9524 bool &FoundWrongKind,
9526 FoundWrongKind =
false;
9531 uint64_t MagicValue;
9533 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9537 if (TypeTagForDatatypeAttr *I = VD->
getAttr<TypeTagForDatatypeAttr>()) {
9538 if (I->getArgumentKind() != ArgumentKind) {
9539 FoundWrongKind =
true;
9542 TypeInfo.
Type = I->getMatchingCType();
9555 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9556 if (I == MagicValues->end())
9559 TypeInfo = I->second;
9565 uint64_t MagicValue,
QualType Type,
9566 bool LayoutCompatible,
9568 if (!TypeTagForDatatypeMagicValues)
9569 TypeTagForDatatypeMagicValues.reset(
9570 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9573 (*TypeTagForDatatypeMagicValues)[Magic] =
9590 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9591 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9592 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9593 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9597 void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
9598 const Expr *
const *ExprArgs) {
9600 bool IsPointerAttr = Attr->getIsPointer();
9602 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9603 bool FoundWrongKind;
9604 TypeTagData TypeInfo;
9605 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9606 TypeTagForDatatypeMagicValues.get(),
9607 FoundWrongKind, TypeInfo)) {
9610 diag::warn_type_tag_for_datatype_wrong_kind)
9611 << TypeTagExpr->getSourceRange();
9615 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9616 if (IsPointerAttr) {
9618 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9619 if (ICE->getType()->isVoidPointerType() &&
9621 ArgumentExpr = ICE->getSubExpr();
9629 if (TypeInfo.MustBeNull) {
9634 diag::warn_type_safety_null_pointer_required)
9636 << ArgumentExpr->getSourceRange()
9637 << TypeTagExpr->getSourceRange();
9642 QualType RequiredType = TypeInfo.Type;
9646 bool mismatch =
false;
9647 if (!TypeInfo.LayoutCompatible) {
9648 mismatch = !Context.
hasSameType(ArgumentType, RequiredType);
9656 if ((IsPointerAttr && IsSameCharType(ArgumentType->
getPointeeType(),
9658 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9662 mismatch = !isLayoutCompatible(Context,
9666 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9669 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
9670 << ArgumentType << ArgumentKind
9671 << TypeInfo.LayoutCompatible << RequiredType
9672 << ArgumentExpr->getSourceRange()
9673 << TypeTagExpr->getSourceRange();
const OptionalFlag & hasSpacePrefix() const
unsigned getFlags() const
The receiver is the instance of the superclass object.
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
static FormatStringType GetFormatStringType(const FormatAttr *Format)
Defines the clang::ASTContext interface.
unsigned getNumInits() const
SourceLocation getEnd() const
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
const Expr * getBase() const
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
CastKind getCastKind() const
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Expr ** getArgs()
Retrieve the call arguments.
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.
The receiver is an object instance.
Scope * getCurScope() const
Retrieve the parser's current scope.
bool isNullPtrType() const
StringRef getName() const
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
Smart pointer class that efficiently represents Objective-C method names.
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
EvaluatedExprVisitor - This class visits 'Expr *'s.
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
bool isAtLeastAsQualifiedAs(QualType Other) const
Determine whether this type is at least as qualified as the other given type, requiring exact equalit...
unsigned getLength() const
bool isCanonicalUnqualified() const
bool isSpecificBuiltinType(unsigned K) const
isSpecificBuiltinType - Test for a particular builtin type.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
bool isBitField() const
Determines whether this field is a bitfield.
ArrayRef< QualType > getTypeArgs() const
Retrieve the type arguments for this type.
bool hasLeadingEmptyMacro() const
bool isMemberPointerType() const
IdentifierInfo * getIdentifier() const
bool isOne() const
isOne - Test whether the quantity equals one.
const LangOptions & getLangOpts() const
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID. ...
static bool IsFunctionStdAbs(const FunctionDecl *FDecl)
static Optional< int > GetNSMutableArrayArgumentIndex(Sema &S, ObjCMessageExpr *Message)
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
unsigned getIntWidth(QualType T) const
const ScanfConversionSpecifier & getConversionSpecifier() const
const Scope * getParent() const
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef< const Expr * > Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, Sema::VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs)
void addConst()
addConst - add the specified type qualifier to this QualType.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
bool isRecordType() const
unsigned getSpellingLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
bool hasValidThousandsGroupingPrefix() const
param_iterator param_end()
bool isVoidPointerType() const
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
const OptionalFlag & hasLeadingZeros() const
bool isEnumeralType() const
bool isInStdNamespace() const
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
unsigned getPresumedLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool capturesVariable(const VarDecl *var) const
NSDictionaryMethodKind
Enumerates the NSDictionary/NSMutableDictionary methods used to generate literals and to apply some c...
NamespaceDecl - Represent a C++ namespace.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
bool usesPositionalArg() const
Represents a call to a C++ constructor.
Wrapper for source info for typedefs.
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
bool isBooleanType() const
A container of type source information.
SourceLocation getOperatorLoc() const
SourceLocation getLocStart() const LLVM_READONLY
bool isBlockPointerType() const
[ARC] Consumes a retainable object pointer that has just been produced, e.g. as the return value of a...
bool isInSystemMacro(SourceLocation loc)
Returns whether Loc is expanded from a macro in a system header.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
bool hasUnsignedIntegerRepresentation() const
Determine whether this type has an unsigned integer representation of some sort, e.g., it is an unsigned integer type or a vector.
bool consumesDataArgument() const
const llvm::APInt & getSize() const
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
DiagnosticsEngine & Diags
const Expr * getCallee() const
bool areArgsDestroyedLeftToRightInCallee() const
APFloat & getComplexFloatReal()
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
ExtProtoInfo - Extra information about a function prototype.
field_iterator field_begin() const
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Expr * IgnoreImplicit() LLVM_READONLY
CK_Dynamic - A C++ dynamic_cast.
Like System, but searched after the system directories.
Defines the Objective-C statement AST node classes.
static bool isAssignmentOp(Opcode Opc)
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false)
ParmVarDecl - Represents a parameter to a function.
bool isObjCRetainableType() const
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
Defines the clang::Expr interface and subclasses for C++ expressions.
ObjCInterfaceDecl * NSDictionaryDecl
The declaration of the Objective-C NSDictionary class.
SourceLocation getLocation() const
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat, etc and warns if it's a comparison.
Parse and apply any fixits to the source.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
QualType withConst() const
Retrieves a version of this type with const applied. Note that this does not always yield a canonical...
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool requiresParensToAddCast(const Expr *E)
Base wrapper for a particular "section" of type source info.
Expr * IgnoreImpCasts() LLVM_READONLY
unsigned getNumParams() const
static bool CheckForReference(Sema &SemaRef, const Expr *E, PartialDiagnostic PD)
ExprResult UsualUnaryConversions(Expr *E)
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
bool isScalarType() const
bool isComplexInt() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
ArrayRef< QualType > getParamTypes() const
bool isReferenceType() const
QualType getReturnType() const
virtual bool validateCpuSupports(StringRef Name) const
bool isCompleteDefinition() const
bool isAnyPointerType() const
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
CXXRecordDecl * getDefinition() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
bool isInlineNamespace() const
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr)
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Stmt * getBody() const override
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
SourceLocation getRParenLoc() const
void DiagnoseEmptyLoopBody(const Stmt *S, const Stmt *PossibleBody)
static Optional< int > GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message)
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
SourceLocation getSuperLoc() const
Retrieve the location of the 'super' keyword for a class or instance message to 'super', otherwise an invalid source location.
Describes an C or C++ initializer list.
static bool isEqualityOp(Opcode Opc)
Represents the results of name lookup.
const TargetInfo & getTargetInfo() const
SourceLocation getLocWithOffset(int Offset) const
Return a source location with the specified offset from this SourceLocation.
QualType getOriginalType() const
Expr * getTrueExpr() const
ObjCMethodDecl * getCurMethodDecl()
APValue Val
Val - This is the value the expression can be folded to.
bool hasValidPlusPrefix() const
unsigned getMinRequiredArguments() const
void CheckFormatString(const StringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs)
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
bool isSuperReceiver() const
static bool isNonNullType(ASTContext &ctx, QualType type)
Determine whether the given type has a non-null nullability annotation.
field_range fields() const
unsigned LayoutCompatible
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
const ArrayType * getAsArrayType(QualType T) const
TypeOfExprType (GCC extension).
A builtin binary operation expression such as "x + y" or "x <= y".
Selector getSelector() const
bool isValueDependent() const
RecordDecl * getDecl() const
bool isUnsignedIntegerType() const
Expr * IgnoreParenCasts() LLVM_READONLY
Values of this type can never be null.
NSSetMethodKind
Enumerates the NSMutableSet/NSOrderedSet methods used to apply some checks.
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr...
TypeClass getTypeClass() const
base_class_iterator bases_begin()
bool isIncompleteType(NamedDecl **Def=nullptr) const
Def If non-NULL, and the type refers to some kind of declaration that can be completed (such as a C s...
QualType withVolatile() const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name...
An ordinary object is located at an address in memory.
SmallVector< BoundNodes, 1 > match(MatcherT Matcher, const NodeT &Node, ASTContext &Context)
Returns the results of matching Matcher on Node.
static const CXXRecordDecl * getContainedDynamicClass(QualType T, bool &IsContained)
Determine whether the given type is or contains a dynamic class type (e.g., whether it has a vtable)...
const Expr * getBase() const
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
Expression is a GNU-style __null constant.
static void diagnoseRetainCycle(Sema &S, Expr *capturer, RetainCycleOwner &owner)
PropertyAttributeKind getPropertyAttributes() const
APSInt & getComplexIntReal()
QualType getCanonicalTypeInternal() const
CanQualType UnsignedCharTy
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
field_iterator field_end() const
APValue & getVectorElt(unsigned I)
bool isAddrLabelDiff() const
Decl * getNextDeclInContext()
Sema - This implements semantic analysis and AST building for C.
Expr * getFalseExpr() const
llvm::APInt getValue() const
bool AtomicUsesUnsupportedLibcall(const AtomicExpr *E) const
QualType getParamType(unsigned i) const
bool hasIrrelevantDestructor() const
Determine whether this class has a destructor which has no semantic effect.
bool isFloatingPoint() const
bool isInstanceMessage() const
Determine whether this is an instance message to either a computed object or to super.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
Qualifiers::ObjCLifetime getObjCLifetime() const
getObjCLifetime - Returns lifetime attribute of this type.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
CastKind
CastKind - The kind of operation required for a conversion.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on a template...
QualType getPointeeType() const
bool isUnarySelector() const
bool isFunctionPointerType() const
bool isRealFloatingType() const
Floating point categories.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
bool hasValidAlternativeForm() const
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
Retains information about a block that is currently being parsed.
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
bool isWrittenInSameFile(SourceLocation Loc1, SourceLocation Loc2) const
Returns true if the spelling locations for both SourceLocations are part of the same file buffer...
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
bool isKnownToHaveBooleanValue() const
StringRef getName() const
Return the actual identifier string.
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
unsigned getNumArgs() const
bool isAnyComplexType() const
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
Expr * getBitWidth() const
bool isComplexFloat() const
bool isAtomicType() const
bool isUnsignedInteger() const
Represents a C++ destructor within a class.
void setInvalidDecl(bool Invalid=true)
This scope corresponds to an SEH except.
bool isVariableArrayType() const
const ParmVarDecl * getParamDecl(unsigned i) const
bool hasValidFieldWidth() const
DeclContext * getDeclContext()
ObjCInterfaceDecl * getReceiverInterface() const
Retrieve the Objective-C interface to which this message is being directed, if known.
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
bool isFloatingType() const
ImplicitParamDecl * getSelfDecl() const
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
void removeLocalVolatile()
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
SourceLocation getQuestionLoc() const
SourceLocation getLocation() const
Expr * getSubExpr() const
Expr * getElement(unsigned Index)
getExpr - Return the Expr at the specified index.
bool isDependentType() const
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
const PrintfConversionSpecifier & getConversionSpecifier() const
An expression that sends a message to the given Objective-C object or class.
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
DeclarationName getDeclName() const
unsigned getNumBases() const
Retrieves the number of base classes of this class.
APSInt & getComplexIntImag()
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
The result type of a method or function.
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
bool isUnsignedIntegerOrEnumerationType() const
SourceLocation getSemiLoc() const
void EvaluateForOverflow(const ASTContext &Ctx) const
TypeSourceInfo * getTypeSourceInfo() const
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
Expr * getTrueExpr() const
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target) const
static const Expr * getStrlenExprArg(const Expr *E)
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static CharSourceRange getCharRange(SourceRange R)
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification. If this depends on t...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
SourceLocation getLocStart() const LLVM_READONLY
There is no lifetime qualification on this type.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Enumerates target-specific builtins in their own namespaces within namespace clang.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
bool hasIntegerRepresentation() const
Determine whether this type has an integer representation of some sort, e.g., it is an integer type o...
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
static bool IsTailPaddedMemberArray(Sema &S, llvm::APInt Size, const NamedDecl *ND)
Check whether this array fits the idiom of a size-one tail padded array member of a struct...
unsigned getNumParams() const
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
const Type * getTypePtr() const
Expression is not a Null pointer constant.
unsigned getBitWidthValue(const ASTContext &Ctx) const
Expr * getSourceExpr() const
static Expr * EvalAddr(Expr *E, SmallVectorImpl< DeclRefExpr * > &refVars, Decl *ParentDecl)
void checkRetainCycles(ObjCMessageExpr *msg)
Check a message send to see if it's likely to cause a retain cycle.
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
bool isConstant(ASTContext &Ctx) const
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
const char * GetName(unsigned ID) const
Return the identifier name for the specified builtin, e.g. "__builtin_abs".
QualType withConst() const
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Represents a static or instance method of a struct/union/class.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall)
SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Returns true if the value evaluates to null.
virtual bool hasSjLjLowering() const
const ConstantArrayType * getAsConstantArrayType(QualType T) const
static void DiagnoseCStringFormatDirectiveInCFAPI(Sema &S, const NamedDecl *FDecl, Expr **Args, unsigned NumArgs)
Diagnose use of s directive in an NSString which is being passed as formatting string to formatting m...
const OptionalFlag & hasPlusPrefix() const
bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
Specifies that a value-dependent expression should be considered to never be a null pointer constant...
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function. If the given function is a memory copy or setting func...
Look up any declaration with any name.
const Type * getBaseElementTypeUnsafe() const
EltType getEltType() const
bool FormatStringHasSArg(const StringLiteral *FExpr)
Represents one property declaration in an Objective-C interface.
bool hasValidPrecision() const
bool containsNonAsciiOrNull() const
SourceLocation getBegin() const
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isTypeDependent() const
bool isVectorType() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
static bool isLogicalOp(Opcode Opc)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
unsigned getBuiltinID() const
Returns a value indicating whether this function corresponds to a builtin function.
Assigning into this object requires a lifetime extension.
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
SourceLocation getLocStart() const LLVM_READONLY
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
const BlockDecl * getBlockDecl() const
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
We are currently in the filter expression of an SEH except block.
QualType getType() const
Return the type wrapped by this type source info.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
bool isDynamicClass() const
SourceLocation getExprLoc() const LLVM_READONLY
bool isFunctionProtoType() const
QualType getPointeeType() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
SourceLocation getRBracketLoc() const
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
QualType getCallReturnType(const ASTContext &Ctx) const
CanQualType UnsignedShortTy
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Base class for declarations which introduce a typedef-name.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
bool hasValidLeadingZeros() const
bool isImplicitProperty() const
static const Type * getElementType(const Expr *BaseExpr)
EvalResult is a struct with detailed info about an evaluated expression.
bool GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx)
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return 0.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_RValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CCK_ImplicitConversion)
static __inline__ uint32_t volatile uint32_t * p
bool isInvalidDecl() const
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
const OptionalFlag & hasThousandsGrouping() const
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
CanQualType UnsignedLongLongTy
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
std::pair< SourceLocation, SourceLocation > getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
bool isStandardLayoutType() const
Test if this type is a standard-layout type. (C++0x [basic.type]p9)
QualType getExceptionObjectType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
static bool isSetterLikeSelector(Selector sel)
A set of unresolved declarations.
SourceLocation getLocStart() const LLVM_READONLY
StringRef getString() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Expression is a C++11 nullptr.
unsigned getNumArgs() const
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Flags to identify the types for overloaded Neon builtins.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
ExprResult SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
SemaConvertVectorExpr - Handle __builtin_convertvector.
bool consumesDataArgument() const
llvm::APFloat getValue() const
[ARC] Reclaim a retainable object pointer object that may have been produced and autoreleased as part...
Expr * IgnoreParenImpCasts() LLVM_READONLY
static LLVM_READONLY bool isLowercase(unsigned char c)
Return true if this character is a lowercase ASCII letter: [a-z].
ArgType getArgType(ASTContext &Ctx) const
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum. These widths include the rightmost leading 1; that is:
bool isTriviallyCopyableType(ASTContext &Context) const
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>. Pointer - pointer requires t...
SourceManager & getSourceManager() const
Expr * getFalseExpr() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
QualType getCanonicalType() const
CanQualType UnsignedLongTy
bool isObjCQualifiedIdType() const
QualType getIntegerType() const
bool hasValidSpacePrefix() const
static unsigned RFT(unsigned t, bool shift=false, bool ForceQuad=false)
SourceLocation getLocStart() const LLVM_READONLY
const OptionalAmount & getPrecision() const
bool isFunctionType() const
const OptionalFlag & hasAlternativeForm() const
bool isComplete() const
Returns true if this can be considered a complete type.
static bool isAdditiveOp(Opcode Opc)
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
bool hasValidLeftJustified() const
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.
ObjCInterfaceDecl * NSArrayDecl
The declaration of the Objective-C NSArray class.
SourceLocation getLocEnd() const LLVM_READONLY
static Expr * EvalVal(Expr *E, SmallVectorImpl< DeclRefExpr * > &refVars, Decl *ParentDecl)
unsigned getNumArgs() const
Return the number of actual arguments in this message, not counting the receiver. ...
SourceLocation getExprLoc() const LLVM_READONLY
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
Represents a base class of a C++ class.
ObjCPropertyDecl * getExplicitProperty() const
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
ObjCIvarRefExpr - A reference to an ObjC instance variable.
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
bool hasNonTrivialObjCLifetime() const
Reading or writing from this object requires a barrier call.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Expression is a Null pointer constant built from a literal zero.
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
const OptionalFlag & isLeftJustified() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
APFloat & getComplexFloatImag()
unsigned getNumPositiveBits() const
Returns the width in bits required to store all the non-negative enumerators of this enum...
Represents a C++ struct/union/class.
Compatible - the types are compatible according to the standard.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
bool isObjCObjectPointerType() const
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
ArraySizeModifier getSizeModifier() const
IntType getInt64Type() const
Builtin::Context & BuiltinInfo
bool CheckParmsForFunctionDef(ParmVarDecl *const *Param, ParmVarDecl *const *ParamEnd, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorType::VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Defines the clang::TargetInfo interface.
PropertyAttributeKind getPropertyAttributesAsWritten() const
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
virtual bool hasFeature(StringRef Feature) const
Determine whether the given target has the given feature.
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall)
QualType getElementType() const
SourceManager & SourceMgr
const Expr * getInit(unsigned Init) const
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
void suppressDiagnostics()
An l-value expression is a reference to an object with independent storage.
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
bool isSignedIntegerType() const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g., it is an signed integer type or a vector.
bool isNull() const
isNull - Return true if this QualType doesn't point to a type yet.
TypeSourceInfo * getTypeSourceInfo() const
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall)
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
NamespaceDecl * getStdNamespace() const
static bool isComparisonOp(Opcode Opc)
Optional< NullabilityKind > getNullability(const ASTContext &context) const
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
static Optional< int > GetNSMutableDictionaryArgumentIndex(Sema &S, ObjCMessageExpr *Message)
static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
bool isIntegralType(ASTContext &Ctx) const
Determine whether this type is an integral type.
This class handles loading and caching of source files into memory.
unsigned getVectorLength() const
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
unsigned getNumElements() const
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant()...
Attr - This represents one attribute.
Represents a shadow declaration introduced into a scope by a (resolved) using declaration.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
bool isIntegerType() const
Helper class that creates diagnostics with optional template instantiation stacks.
Expr * IgnoreParens() LLVM_READONLY
CanQualType UnsignedIntTy
bool isPointerType() const
bool isMacroArgExpansion(SourceLocation Loc) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
OverloadedOperatorKind getOverloadedOperator() const