36 #include "llvm/ADT/STLExtras.h"
37 #include "llvm/ADT/SmallBitVector.h"
38 #include "llvm/ADT/SmallString.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include "llvm/Support/raw_ostream.h"
42 using namespace clang;
46 unsigned ByteNo)
const {
55 if (argCount == desiredArgCount)
return false;
57 if (argCount < desiredArgCount)
58 return S.
Diag(call->
getLocEnd(), diag::err_typecheck_call_too_few_args)
59 << 0 << desiredArgCount << argCount
60 << call->getSourceRange();
64 call->
getArg(argCount - 1)->getLocEnd());
66 return S.
Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
67 << 0 << desiredArgCount << argCount
68 << call->
getArg(1)->getSourceRange();
81 S.
Diag(ValArg->getLocStart(), diag::err_builtin_annotation_first_arg)
82 << ValArg->getSourceRange();
89 if (!Literal || !Literal->
isAscii()) {
90 S.
Diag(StrArg->getLocStart(), diag::err_builtin_annotation_second_arg)
91 << StrArg->getSourceRange();
107 if (ResultType.isNull())
110 TheCall->
setArg(0, Arg.get());
120 for (
unsigned I = 0;
I < 2; ++
I) {
124 S.
Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_int)
125 << Ty << Arg->getSourceRange();
137 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
138 !PtrTy->getPointeeType().isConstQualified())) {
139 S.
Diag(Arg->getLocStart(), diag::err_overflow_builtin_must_be_ptr_int)
140 << Ty << Arg->getSourceRange();
149 CallExpr *TheCall,
unsigned SizeIdx,
150 unsigned DstSizeIdx) {
155 const Expr *SizeArg = TheCall->
getArg(SizeIdx);
156 const Expr *DstSizeArg = TheCall->
getArg(DstSizeIdx);
158 llvm::APSInt Size, DstSize;
165 if (Size.ule(DstSize))
173 S.
Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
185 if (Call->getStmtClass() != Stmt::CallExprClass) {
186 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
187 << Call->getSourceRange();
191 auto CE = cast<CallExpr>(Call);
192 if (CE->getCallee()->getType()->isBlockPointerType()) {
193 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
194 << Call->getSourceRange();
198 const Decl *TargetDecl = CE->getCalleeDecl();
199 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
200 if (FD->getBuiltinID()) {
201 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
202 << Call->getSourceRange();
206 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
207 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
208 << Call->getSourceRange();
216 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
217 << Chain->getSourceRange();
230 BuiltinCall->
setType(CE->getType());
234 BuiltinCall->
setArg(1, ChainResult.
get());
251 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
254 << DRE->getDecl()->getIdentifier();
262 Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
267 unsigned ICEArguments = 0;
274 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
276 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
279 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
281 ICEArguments &= ~(1 << ArgNo);
285 case Builtin::BI__builtin___CFStringMakeConstantString:
287 "Wrong # arguments to builtin CFStringMakeConstantString");
288 if (CheckObjCString(TheCall->
getArg(0)))
291 case Builtin::BI__builtin_stdarg_start:
292 case Builtin::BI__builtin_va_start:
293 if (SemaBuiltinVAStart(TheCall))
296 case Builtin::BI__va_start: {
298 case llvm::Triple::arm:
299 case llvm::Triple::thumb:
300 if (SemaBuiltinVAStartARM(TheCall))
304 if (SemaBuiltinVAStart(TheCall))
310 case Builtin::BI__builtin_isgreater:
311 case Builtin::BI__builtin_isgreaterequal:
312 case Builtin::BI__builtin_isless:
313 case Builtin::BI__builtin_islessequal:
314 case Builtin::BI__builtin_islessgreater:
315 case Builtin::BI__builtin_isunordered:
316 if (SemaBuiltinUnorderedCompare(TheCall))
319 case Builtin::BI__builtin_fpclassify:
320 if (SemaBuiltinFPClassification(TheCall, 6))
323 case Builtin::BI__builtin_isfinite:
324 case Builtin::BI__builtin_isinf:
325 case Builtin::BI__builtin_isinf_sign:
326 case Builtin::BI__builtin_isnan:
327 case Builtin::BI__builtin_isnormal:
328 if (SemaBuiltinFPClassification(TheCall, 1))
331 case Builtin::BI__builtin_shufflevector:
332 return SemaBuiltinShuffleVector(TheCall);
335 case Builtin::BI__builtin_prefetch:
336 if (SemaBuiltinPrefetch(TheCall))
339 case Builtin::BI__assume:
340 case Builtin::BI__builtin_assume:
341 if (SemaBuiltinAssume(TheCall))
344 case Builtin::BI__builtin_assume_aligned:
345 if (SemaBuiltinAssumeAligned(TheCall))
348 case Builtin::BI__builtin_object_size:
349 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
352 case Builtin::BI__builtin_longjmp:
353 if (SemaBuiltinLongjmp(TheCall))
356 case Builtin::BI__builtin_setjmp:
357 if (SemaBuiltinSetjmp(TheCall))
360 case Builtin::BI_setjmp:
361 case Builtin::BI_setjmpex:
366 case Builtin::BI__builtin_classify_type:
370 case Builtin::BI__builtin_constant_p:
374 case Builtin::BI__sync_fetch_and_add:
375 case Builtin::BI__sync_fetch_and_add_1:
376 case Builtin::BI__sync_fetch_and_add_2:
377 case Builtin::BI__sync_fetch_and_add_4:
378 case Builtin::BI__sync_fetch_and_add_8:
379 case Builtin::BI__sync_fetch_and_add_16:
380 case Builtin::BI__sync_fetch_and_sub:
381 case Builtin::BI__sync_fetch_and_sub_1:
382 case Builtin::BI__sync_fetch_and_sub_2:
383 case Builtin::BI__sync_fetch_and_sub_4:
384 case Builtin::BI__sync_fetch_and_sub_8:
385 case Builtin::BI__sync_fetch_and_sub_16:
386 case Builtin::BI__sync_fetch_and_or:
387 case Builtin::BI__sync_fetch_and_or_1:
388 case Builtin::BI__sync_fetch_and_or_2:
389 case Builtin::BI__sync_fetch_and_or_4:
390 case Builtin::BI__sync_fetch_and_or_8:
391 case Builtin::BI__sync_fetch_and_or_16:
392 case Builtin::BI__sync_fetch_and_and:
393 case Builtin::BI__sync_fetch_and_and_1:
394 case Builtin::BI__sync_fetch_and_and_2:
395 case Builtin::BI__sync_fetch_and_and_4:
396 case Builtin::BI__sync_fetch_and_and_8:
397 case Builtin::BI__sync_fetch_and_and_16:
398 case Builtin::BI__sync_fetch_and_xor:
399 case Builtin::BI__sync_fetch_and_xor_1:
400 case Builtin::BI__sync_fetch_and_xor_2:
401 case Builtin::BI__sync_fetch_and_xor_4:
402 case Builtin::BI__sync_fetch_and_xor_8:
403 case Builtin::BI__sync_fetch_and_xor_16:
404 case Builtin::BI__sync_fetch_and_nand:
405 case Builtin::BI__sync_fetch_and_nand_1:
406 case Builtin::BI__sync_fetch_and_nand_2:
407 case Builtin::BI__sync_fetch_and_nand_4:
408 case Builtin::BI__sync_fetch_and_nand_8:
409 case Builtin::BI__sync_fetch_and_nand_16:
410 case Builtin::BI__sync_add_and_fetch:
411 case Builtin::BI__sync_add_and_fetch_1:
412 case Builtin::BI__sync_add_and_fetch_2:
413 case Builtin::BI__sync_add_and_fetch_4:
414 case Builtin::BI__sync_add_and_fetch_8:
415 case Builtin::BI__sync_add_and_fetch_16:
416 case Builtin::BI__sync_sub_and_fetch:
417 case Builtin::BI__sync_sub_and_fetch_1:
418 case Builtin::BI__sync_sub_and_fetch_2:
419 case Builtin::BI__sync_sub_and_fetch_4:
420 case Builtin::BI__sync_sub_and_fetch_8:
421 case Builtin::BI__sync_sub_and_fetch_16:
422 case Builtin::BI__sync_and_and_fetch:
423 case Builtin::BI__sync_and_and_fetch_1:
424 case Builtin::BI__sync_and_and_fetch_2:
425 case Builtin::BI__sync_and_and_fetch_4:
426 case Builtin::BI__sync_and_and_fetch_8:
427 case Builtin::BI__sync_and_and_fetch_16:
428 case Builtin::BI__sync_or_and_fetch:
429 case Builtin::BI__sync_or_and_fetch_1:
430 case Builtin::BI__sync_or_and_fetch_2:
431 case Builtin::BI__sync_or_and_fetch_4:
432 case Builtin::BI__sync_or_and_fetch_8:
433 case Builtin::BI__sync_or_and_fetch_16:
434 case Builtin::BI__sync_xor_and_fetch:
435 case Builtin::BI__sync_xor_and_fetch_1:
436 case Builtin::BI__sync_xor_and_fetch_2:
437 case Builtin::BI__sync_xor_and_fetch_4:
438 case Builtin::BI__sync_xor_and_fetch_8:
439 case Builtin::BI__sync_xor_and_fetch_16:
440 case Builtin::BI__sync_nand_and_fetch:
441 case Builtin::BI__sync_nand_and_fetch_1:
442 case Builtin::BI__sync_nand_and_fetch_2:
443 case Builtin::BI__sync_nand_and_fetch_4:
444 case Builtin::BI__sync_nand_and_fetch_8:
445 case Builtin::BI__sync_nand_and_fetch_16:
446 case Builtin::BI__sync_val_compare_and_swap:
447 case Builtin::BI__sync_val_compare_and_swap_1:
448 case Builtin::BI__sync_val_compare_and_swap_2:
449 case Builtin::BI__sync_val_compare_and_swap_4:
450 case Builtin::BI__sync_val_compare_and_swap_8:
451 case Builtin::BI__sync_val_compare_and_swap_16:
452 case Builtin::BI__sync_bool_compare_and_swap:
453 case Builtin::BI__sync_bool_compare_and_swap_1:
454 case Builtin::BI__sync_bool_compare_and_swap_2:
455 case Builtin::BI__sync_bool_compare_and_swap_4:
456 case Builtin::BI__sync_bool_compare_and_swap_8:
457 case Builtin::BI__sync_bool_compare_and_swap_16:
458 case Builtin::BI__sync_lock_test_and_set:
459 case Builtin::BI__sync_lock_test_and_set_1:
460 case Builtin::BI__sync_lock_test_and_set_2:
461 case Builtin::BI__sync_lock_test_and_set_4:
462 case Builtin::BI__sync_lock_test_and_set_8:
463 case Builtin::BI__sync_lock_test_and_set_16:
464 case Builtin::BI__sync_lock_release:
465 case Builtin::BI__sync_lock_release_1:
466 case Builtin::BI__sync_lock_release_2:
467 case Builtin::BI__sync_lock_release_4:
468 case Builtin::BI__sync_lock_release_8:
469 case Builtin::BI__sync_lock_release_16:
470 case Builtin::BI__sync_swap:
471 case Builtin::BI__sync_swap_1:
472 case Builtin::BI__sync_swap_2:
473 case Builtin::BI__sync_swap_4:
474 case Builtin::BI__sync_swap_8:
475 case Builtin::BI__sync_swap_16:
476 return SemaBuiltinAtomicOverloaded(TheCallResult);
477 case Builtin::BI__builtin_nontemporal_load:
478 case Builtin::BI__builtin_nontemporal_store:
479 return SemaBuiltinNontemporalOverloaded(TheCallResult);
480 #define BUILTIN(ID, TYPE, ATTRS)
481 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
482 case Builtin::BI##ID: \
483 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
484 #include "clang/Basic/Builtins.def"
485 case Builtin::BI__builtin_annotation:
489 case Builtin::BI__builtin_addressof:
493 case Builtin::BI__builtin_add_overflow:
494 case Builtin::BI__builtin_sub_overflow:
495 case Builtin::BI__builtin_mul_overflow:
499 case Builtin::BI__builtin_operator_new:
500 case Builtin::BI__builtin_operator_delete:
503 << (BuiltinID == Builtin::BI__builtin_operator_new
504 ?
"__builtin_operator_new"
505 :
"__builtin_operator_delete")
511 DeclareGlobalNewDelete();
516 case Builtin::BI__builtin___memcpy_chk:
517 case Builtin::BI__builtin___memmove_chk:
518 case Builtin::BI__builtin___memset_chk:
519 case Builtin::BI__builtin___strlcat_chk:
520 case Builtin::BI__builtin___strlcpy_chk:
521 case Builtin::BI__builtin___strncat_chk:
522 case Builtin::BI__builtin___strncpy_chk:
523 case Builtin::BI__builtin___stpncpy_chk:
526 case Builtin::BI__builtin___memccpy_chk:
529 case Builtin::BI__builtin___snprintf_chk:
530 case Builtin::BI__builtin___vsnprintf_chk:
534 case Builtin::BI__builtin_call_with_static_chain:
539 case Builtin::BI__exception_code:
540 case Builtin::BI_exception_code: {
542 diag::err_seh___except_block))
546 case Builtin::BI__exception_info:
547 case Builtin::BI_exception_info: {
549 diag::err_seh___except_filter))
554 case Builtin::BI__GetExceptionInfo:
558 if (CheckCXXThrowOperand(
573 case llvm::Triple::arm:
574 case llvm::Triple::armeb:
575 case llvm::Triple::thumb:
576 case llvm::Triple::thumbeb:
577 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
580 case llvm::Triple::aarch64:
581 case llvm::Triple::aarch64_be:
582 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
585 case llvm::Triple::mips:
586 case llvm::Triple::mipsel:
587 case llvm::Triple::mips64:
588 case llvm::Triple::mips64el:
589 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
592 case llvm::Triple::systemz:
593 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
596 case llvm::Triple::x86:
597 case llvm::Triple::x86_64:
598 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
601 case llvm::Triple::ppc:
602 case llvm::Triple::ppc64:
603 case llvm::Triple::ppc64le:
604 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
612 return TheCallResult;
616 static unsigned RFT(
unsigned t,
bool shift =
false,
bool ForceQuad =
false) {
618 int IsQuad = ForceQuad ?
true : Type.
isQuad();
622 return shift ? 7 : (8 << IsQuad) - 1;
625 return shift ? 15 : (4 << IsQuad) - 1;
627 return shift ? 31 : (2 << IsQuad) - 1;
630 return shift ? 63 : (1 << IsQuad) - 1;
632 return shift ? 127 : (1 << IsQuad) - 1;
634 assert(!shift &&
"cannot shift float types!");
635 return (4 << IsQuad) - 1;
637 assert(!shift &&
"cannot shift float types!");
638 return (2 << IsQuad) - 1;
640 assert(!shift &&
"cannot shift float types!");
641 return (1 << IsQuad) - 1;
643 llvm_unreachable(
"Invalid NeonTypeFlag!");
650 bool IsPolyUnsigned,
bool IsInt64Long) {
682 llvm_unreachable(
"Invalid NeonTypeFlag!");
685 bool Sema::CheckNeonBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
690 bool HasConstPtr =
false;
692 #define GET_NEON_OVERLOAD_CHECK
693 #include "clang/Basic/arm_neon.inc"
694 #undef GET_NEON_OVERLOAD_CHECK
701 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
704 TV = Result.getLimitedValue(64);
705 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
707 << TheCall->
getArg(ImmArg)->getSourceRange();
710 if (PtrArgNum >= 0) {
714 Arg = ICE->getSubExpr();
715 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
719 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64;
727 AssignConvertType ConvTy;
728 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
731 if (DiagnoseAssignmentResult(ConvTy, Arg->getLocStart(), LHSTy, RHSTy,
732 RHS.
get(), AA_Assigning))
738 unsigned i = 0, l = 0, u = 0;
742 #define GET_NEON_IMMEDIATE_CHECK
743 #include "clang/Basic/arm_neon.inc"
744 #undef GET_NEON_IMMEDIATE_CHECK
747 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
750 bool Sema::CheckARMBuiltinExclusiveCall(
unsigned BuiltinID,
CallExpr *TheCall,
752 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
753 BuiltinID == ARM::BI__builtin_arm_ldaex ||
754 BuiltinID == ARM::BI__builtin_arm_strex ||
755 BuiltinID == ARM::BI__builtin_arm_stlex ||
756 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
757 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
758 BuiltinID == AArch64::BI__builtin_arm_strex ||
759 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
760 "unexpected ARM builtin");
761 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
762 BuiltinID == ARM::BI__builtin_arm_ldaex ||
763 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
764 BuiltinID == AArch64::BI__builtin_arm_ldaex;
776 Expr *PointerArg = TheCall->
getArg(IsLdrex ? 0 : 1);
777 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
780 PointerArg = PointerArgRes.
get();
785 << PointerArg->
getType() << PointerArg->getSourceRange();
801 Diag(DRE->
getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
804 << AA_Passing << PointerArg->getSourceRange();
809 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
812 PointerArg = PointerArgRes.
get();
814 TheCall->
setArg(IsLdrex ? 0 : 1, PointerArg);
819 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
820 << PointerArg->
getType() << PointerArg->getSourceRange();
826 assert(MaxWidth == 64 &&
"Diagnostic unexpectedly inaccurate");
827 Diag(DRE->
getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
828 << PointerArg->
getType() << PointerArg->getSourceRange();
842 << ValType << PointerArg->getSourceRange();
856 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
867 bool Sema::CheckARMBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
870 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
871 BuiltinID == ARM::BI__builtin_arm_ldaex ||
872 BuiltinID == ARM::BI__builtin_arm_strex ||
873 BuiltinID == ARM::BI__builtin_arm_stlex) {
874 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
877 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
878 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
879 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
882 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
883 BuiltinID == ARM::BI__builtin_arm_wsr64)
884 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3,
false);
886 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
887 BuiltinID == ARM::BI__builtin_arm_rsrp ||
888 BuiltinID == ARM::BI__builtin_arm_wsr ||
889 BuiltinID == ARM::BI__builtin_arm_wsrp)
890 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
892 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
897 unsigned i = 0, l = 0, u = 0;
899 default:
return false;
900 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31;
break;
901 case ARM::BI__builtin_arm_usat: i = 1; u = 31;
break;
902 case ARM::BI__builtin_arm_vcvtr_f:
903 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1;
break;
904 case ARM::BI__builtin_arm_dmb:
905 case ARM::BI__builtin_arm_dsb:
906 case ARM::BI__builtin_arm_isb:
907 case ARM::BI__builtin_arm_dbg: l = 0; u = 15;
break;
911 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
914 bool Sema::CheckAArch64BuiltinFunctionCall(
unsigned BuiltinID,
918 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
919 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
920 BuiltinID == AArch64::BI__builtin_arm_strex ||
921 BuiltinID == AArch64::BI__builtin_arm_stlex) {
922 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
925 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
926 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
927 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
928 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
929 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
932 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
933 BuiltinID == AArch64::BI__builtin_arm_wsr64)
934 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
false);
936 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
937 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
938 BuiltinID == AArch64::BI__builtin_arm_wsr ||
939 BuiltinID == AArch64::BI__builtin_arm_wsrp)
940 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
942 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
947 unsigned i = 0, l = 0, u = 0;
949 default:
return false;
950 case AArch64::BI__builtin_arm_dmb:
951 case AArch64::BI__builtin_arm_dsb:
952 case AArch64::BI__builtin_arm_isb: l = 0; u = 15;
break;
955 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
958 bool Sema::CheckMipsBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
959 unsigned i = 0, l = 0, u = 0;
961 default:
return false;
962 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63;
break;
963 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63;
break;
964 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31;
break;
965 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3;
break;
966 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31;
break;
967 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31;
break;
968 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31;
break;
971 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
974 bool Sema::CheckPPCBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
975 unsigned i = 0, l = 0, u = 0;
976 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
977 BuiltinID == PPC::BI__builtin_divdeu ||
978 BuiltinID == PPC::BI__builtin_bpermd;
982 .getIntPtrType()) == 64;
983 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
984 BuiltinID == PPC::BI__builtin_divweu ||
985 BuiltinID == PPC::BI__builtin_divde ||
986 BuiltinID == PPC::BI__builtin_divdeu;
988 if (Is64BitBltin && !IsTarget64Bit)
989 return Diag(TheCall->
getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
990 << TheCall->getSourceRange();
993 (BuiltinID == PPC::BI__builtin_bpermd &&
995 return Diag(TheCall->
getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
996 << TheCall->getSourceRange();
999 default:
return false;
1000 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1001 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1002 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1003 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1004 case PPC::BI__builtin_tbegin:
1005 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1;
break;
1006 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7;
break;
1007 case PPC::BI__builtin_tabortwc:
1008 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31;
break;
1009 case PPC::BI__builtin_tabortwci:
1010 case PPC::BI__builtin_tabortdci:
1011 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1012 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1014 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1017 bool Sema::CheckSystemZBuiltinFunctionCall(
unsigned BuiltinID,
1019 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1021 llvm::APSInt AbortCode(32);
1023 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1024 return Diag(Arg->getLocStart(), diag::err_systemz_invalid_tabort_code)
1025 << Arg->getSourceRange();
1030 unsigned i = 0, l = 0, u = 0;
1031 switch (BuiltinID) {
1032 default:
return false;
1033 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15;
break;
1034 case SystemZ::BI__builtin_s390_verimb:
1035 case SystemZ::BI__builtin_s390_verimh:
1036 case SystemZ::BI__builtin_s390_verimf:
1037 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255;
break;
1038 case SystemZ::BI__builtin_s390_vfaeb:
1039 case SystemZ::BI__builtin_s390_vfaeh:
1040 case SystemZ::BI__builtin_s390_vfaef:
1041 case SystemZ::BI__builtin_s390_vfaebs:
1042 case SystemZ::BI__builtin_s390_vfaehs:
1043 case SystemZ::BI__builtin_s390_vfaefs:
1044 case SystemZ::BI__builtin_s390_vfaezb:
1045 case SystemZ::BI__builtin_s390_vfaezh:
1046 case SystemZ::BI__builtin_s390_vfaezf:
1047 case SystemZ::BI__builtin_s390_vfaezbs:
1048 case SystemZ::BI__builtin_s390_vfaezhs:
1049 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15;
break;
1050 case SystemZ::BI__builtin_s390_vfidb:
1051 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1052 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1053 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095;
break;
1054 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15;
break;
1055 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15;
break;
1056 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15;
break;
1057 case SystemZ::BI__builtin_s390_vstrcb:
1058 case SystemZ::BI__builtin_s390_vstrch:
1059 case SystemZ::BI__builtin_s390_vstrcf:
1060 case SystemZ::BI__builtin_s390_vstrczb:
1061 case SystemZ::BI__builtin_s390_vstrczh:
1062 case SystemZ::BI__builtin_s390_vstrczf:
1063 case SystemZ::BI__builtin_s390_vstrcbs:
1064 case SystemZ::BI__builtin_s390_vstrchs:
1065 case SystemZ::BI__builtin_s390_vstrcfs:
1066 case SystemZ::BI__builtin_s390_vstrczbs:
1067 case SystemZ::BI__builtin_s390_vstrczhs:
1068 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15;
break;
1070 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1081 return S.
Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
1082 << Arg->getSourceRange();
1089 << Arg->getSourceRange();
1093 bool Sema::CheckX86BuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1094 unsigned i = 0, l = 0, u = 0;
1095 switch (BuiltinID) {
1096 default:
return false;
1097 case X86::BI__builtin_cpu_supports:
1099 case X86::BI__builtin_ms_va_start:
1100 return SemaBuiltinMSVAStart(TheCall);
1101 case X86::BI_mm_prefetch: i = 1; l = 0; u = 3;
break;
1102 case X86::BI__builtin_ia32_sha1rnds4: i = 2, l = 0; u = 3;
break;
1103 case X86::BI__builtin_ia32_vpermil2pd:
1104 case X86::BI__builtin_ia32_vpermil2pd256:
1105 case X86::BI__builtin_ia32_vpermil2ps:
1106 case X86::BI__builtin_ia32_vpermil2ps256: i = 3, l = 0; u = 3;
break;
1107 case X86::BI__builtin_ia32_cmpb128_mask:
1108 case X86::BI__builtin_ia32_cmpw128_mask:
1109 case X86::BI__builtin_ia32_cmpd128_mask:
1110 case X86::BI__builtin_ia32_cmpq128_mask:
1111 case X86::BI__builtin_ia32_cmpb256_mask:
1112 case X86::BI__builtin_ia32_cmpw256_mask:
1113 case X86::BI__builtin_ia32_cmpd256_mask:
1114 case X86::BI__builtin_ia32_cmpq256_mask:
1115 case X86::BI__builtin_ia32_cmpb512_mask:
1116 case X86::BI__builtin_ia32_cmpw512_mask:
1117 case X86::BI__builtin_ia32_cmpd512_mask:
1118 case X86::BI__builtin_ia32_cmpq512_mask:
1119 case X86::BI__builtin_ia32_ucmpb128_mask:
1120 case X86::BI__builtin_ia32_ucmpw128_mask:
1121 case X86::BI__builtin_ia32_ucmpd128_mask:
1122 case X86::BI__builtin_ia32_ucmpq128_mask:
1123 case X86::BI__builtin_ia32_ucmpb256_mask:
1124 case X86::BI__builtin_ia32_ucmpw256_mask:
1125 case X86::BI__builtin_ia32_ucmpd256_mask:
1126 case X86::BI__builtin_ia32_ucmpq256_mask:
1127 case X86::BI__builtin_ia32_ucmpb512_mask:
1128 case X86::BI__builtin_ia32_ucmpw512_mask:
1129 case X86::BI__builtin_ia32_ucmpd512_mask:
1130 case X86::BI__builtin_ia32_ucmpq512_mask: i = 2; l = 0; u = 7;
break;
1131 case X86::BI__builtin_ia32_roundps:
1132 case X86::BI__builtin_ia32_roundpd:
1133 case X86::BI__builtin_ia32_roundps256:
1134 case X86::BI__builtin_ia32_roundpd256: i = 1, l = 0; u = 15;
break;
1135 case X86::BI__builtin_ia32_roundss:
1136 case X86::BI__builtin_ia32_roundsd: i = 2, l = 0; u = 15;
break;
1137 case X86::BI__builtin_ia32_cmpps:
1138 case X86::BI__builtin_ia32_cmpss:
1139 case X86::BI__builtin_ia32_cmppd:
1140 case X86::BI__builtin_ia32_cmpsd:
1141 case X86::BI__builtin_ia32_cmpps256:
1142 case X86::BI__builtin_ia32_cmppd256:
1143 case X86::BI__builtin_ia32_cmpps512_mask:
1144 case X86::BI__builtin_ia32_cmppd512_mask: i = 2; l = 0; u = 31;
break;
1145 case X86::BI__builtin_ia32_vpcomub:
1146 case X86::BI__builtin_ia32_vpcomuw:
1147 case X86::BI__builtin_ia32_vpcomud:
1148 case X86::BI__builtin_ia32_vpcomuq:
1149 case X86::BI__builtin_ia32_vpcomb:
1150 case X86::BI__builtin_ia32_vpcomw:
1151 case X86::BI__builtin_ia32_vpcomd:
1152 case X86::BI__builtin_ia32_vpcomq: i = 2; l = 0; u = 7;
break;
1154 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1161 bool Sema::getFormatStringInfo(
const FormatAttr *Format,
bool IsCXXMember,
1162 FormatStringInfo *FSI) {
1163 FSI->HasVAListArg = Format->getFirstArg() == 0;
1164 FSI->FormatIdx = Format->getFormatIdx() - 1;
1165 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
1171 if(FSI->FormatIdx == 0)
1174 if (FSI->FirstDataArg != 0)
1175 --FSI->FirstDataArg;
1185 if (
auto nullability
1194 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
1196 dyn_cast<CompoundLiteralExpr>(Expr))
1198 dyn_cast<InitListExpr>(CLE->getInitializer()))
1199 Expr = ILE->getInit(0);
1209 const Expr *ArgExpr,
1213 S.
PDiag(diag::warn_null_arg) << ArgExpr->getSourceRange());
1217 FormatStringInfo FSI;
1218 if ((GetFormatStringType(Format) == FST_NSString) &&
1219 getFormatStringInfo(Format,
false, &FSI)) {
1220 Idx = FSI.FormatIdx;
1233 bool Format =
false;
1246 if (!Format || NumArgs <= Idx)
1248 const Expr *FormatExpr = Args[Idx];
1249 if (
const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
1250 FormatExpr = CSCE->getSubExpr();
1260 S.
Diag(FormatExpr->
getExprLoc(), diag::warn_objc_cdirective_format_string)
1280 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
1283 llvm::SmallBitVector NonNullArgs;
1289 for (
const auto *Arg : Args)
1295 for (
unsigned Val :
NonNull->args()) {
1296 if (Val >= Args.size())
1298 if (NonNullArgs.empty())
1299 NonNullArgs.resize(Args.size());
1300 NonNullArgs.set(Val);
1305 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
1309 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
1310 parms = FD->parameters();
1312 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
1314 unsigned ParamIndex = 0;
1316 I !=
E; ++
I, ++ParamIndex) {
1318 if (PVD->
hasAttr<NonNullAttr>() ||
1320 if (NonNullArgs.empty())
1321 NonNullArgs.resize(Args.size());
1323 NonNullArgs.set(ParamIndex);
1330 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
1349 if (NonNullArgs.empty())
1350 NonNullArgs.resize(Args.size());
1352 NonNullArgs.set(Index);
1361 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
1362 ArgIndex != ArgIndexEnd; ++ArgIndex) {
1363 if (NonNullArgs[ArgIndex])
1373 VariadicCallType CallType) {
1375 if (CurContext->isDependentContext())
1379 llvm::SmallBitVector CheckedVarArgs;
1383 CheckedVarArgs.resize(Args.size());
1385 CheckFormatArguments(
I, Args, IsMemberFunction, CallType, Loc, Range,
1392 if (CallType != VariadicDoesNotApply) {
1394 : FDecl && isa<FunctionDecl>(FDecl)
1395 ? cast<FunctionDecl>(FDecl)->getNumParams()
1396 : FDecl && isa<ObjCMethodDecl>(FDecl)
1397 ? cast<ObjCMethodDecl>(FDecl)->param_size()
1400 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
1402 if (
const Expr *Arg = Args[ArgIdx]) {
1403 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
1404 checkVariadicArgument(Arg, CallType);
1409 if (FDecl || Proto) {
1414 for (
const auto *
I : FDecl->
specific_attrs<ArgumentWithTypeTagAttr>())
1415 CheckArgumentWithTypeTag(
I, Args.data());
1426 VariadicCallType CallType =
1427 Proto->
isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
1428 checkCall(FDecl, Proto, Args,
true, Loc,
SourceRange(),
1436 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
1437 isa<CXXMethodDecl>(FDecl);
1438 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
1439 IsMemberOperatorCall;
1440 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
1444 if (IsMemberOperatorCall) {
1451 checkCall(FDecl, Proto, llvm::makeArrayRef(Args, NumArgs),
1453 TheCall->
getCallee()->getSourceRange(), CallType);
1461 CheckAbsoluteValueFunction(TheCall, FDecl, FnInfo);
1462 if (getLangOpts().ObjC1)
1470 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
1471 CheckStrlcpycatArguments(TheCall, FnInfo);
1472 else if (CMId == Builtin::BIstrncat)
1473 CheckStrncatArguments(TheCall, FnInfo);
1475 CheckMemaccessArguments(TheCall, CMId, FnInfo);
1482 VariadicCallType CallType =
1483 Method->
isVariadic() ? VariadicMethod : VariadicDoesNotApply;
1485 checkCall(Method,
nullptr, Args,
1495 if (
const auto *V = dyn_cast<VarDecl>(NDecl))
1496 Ty = V->getType().getNonReferenceType();
1497 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
1498 Ty = F->getType().getNonReferenceType();
1506 VariadicCallType CallType;
1508 CallType = VariadicDoesNotApply;
1510 CallType = VariadicBlock;
1512 CallType = VariadicFunction;
1515 checkCall(NDecl, Proto,
1518 TheCall->
getCallee()->getSourceRange(), CallType);
1526 VariadicCallType CallType = getVariadicCallType(
nullptr, Proto,
1528 checkCall(
nullptr, Proto,
1531 TheCall->
getCallee()->getSourceRange(), CallType);
1542 case AtomicExpr::AO__c11_atomic_init:
1543 llvm_unreachable(
"There is no ordering argument for an init");
1545 case AtomicExpr::AO__c11_atomic_load:
1546 case AtomicExpr::AO__atomic_load_n:
1547 case AtomicExpr::AO__atomic_load:
1551 case AtomicExpr::AO__c11_atomic_store:
1552 case AtomicExpr::AO__atomic_store:
1553 case AtomicExpr::AO__atomic_store_n:
1565 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
1587 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 4, 5, 6 };
1588 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 2, 2, 3 };
1596 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
1597 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
1598 AtomicExpr::AO__atomic_load,
1599 "need to update code for modified C11 atomics");
1600 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
1601 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
1602 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
1603 Op == AtomicExpr::AO__atomic_store_n ||
1604 Op == AtomicExpr::AO__atomic_exchange_n ||
1605 Op == AtomicExpr::AO__atomic_compare_exchange_n;
1606 bool IsAddSub =
false;
1609 case AtomicExpr::AO__c11_atomic_init:
1613 case AtomicExpr::AO__c11_atomic_load:
1614 case AtomicExpr::AO__atomic_load_n:
1618 case AtomicExpr::AO__c11_atomic_store:
1619 case AtomicExpr::AO__atomic_load:
1620 case AtomicExpr::AO__atomic_store:
1621 case AtomicExpr::AO__atomic_store_n:
1625 case AtomicExpr::AO__c11_atomic_fetch_add:
1626 case AtomicExpr::AO__c11_atomic_fetch_sub:
1627 case AtomicExpr::AO__atomic_fetch_add:
1628 case AtomicExpr::AO__atomic_fetch_sub:
1629 case AtomicExpr::AO__atomic_add_fetch:
1630 case AtomicExpr::AO__atomic_sub_fetch:
1633 case AtomicExpr::AO__c11_atomic_fetch_and:
1634 case AtomicExpr::AO__c11_atomic_fetch_or:
1635 case AtomicExpr::AO__c11_atomic_fetch_xor:
1636 case AtomicExpr::AO__atomic_fetch_and:
1637 case AtomicExpr::AO__atomic_fetch_or:
1638 case AtomicExpr::AO__atomic_fetch_xor:
1639 case AtomicExpr::AO__atomic_fetch_nand:
1640 case AtomicExpr::AO__atomic_and_fetch:
1641 case AtomicExpr::AO__atomic_or_fetch:
1642 case AtomicExpr::AO__atomic_xor_fetch:
1643 case AtomicExpr::AO__atomic_nand_fetch:
1647 case AtomicExpr::AO__c11_atomic_exchange:
1648 case AtomicExpr::AO__atomic_exchange_n:
1652 case AtomicExpr::AO__atomic_exchange:
1656 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1657 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1661 case AtomicExpr::AO__atomic_compare_exchange:
1662 case AtomicExpr::AO__atomic_compare_exchange_n:
1669 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
1670 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
1671 << TheCall->
getCallee()->getSourceRange();
1673 }
else if (TheCall->
getNumArgs() > NumArgs[Form]) {
1674 Diag(TheCall->
getArg(NumArgs[Form])->getLocStart(),
1675 diag::err_typecheck_call_too_many_args)
1676 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
1677 << TheCall->
getCallee()->getSourceRange();
1683 Ptr = DefaultFunctionArrayLvalueConversion(Ptr).get();
1686 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
1687 << Ptr->
getType() << Ptr->getSourceRange();
1696 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
1697 << Ptr->
getType() << Ptr->getSourceRange();
1701 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
1702 << Ptr->
getType() << Ptr->getSourceRange();
1706 }
else if (Form != Load && Op != AtomicExpr::AO__atomic_load) {
1708 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
1709 << Ptr->
getType() << Ptr->getSourceRange();
1715 if (Form == Arithmetic) {
1718 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1719 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1723 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
1724 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1728 RequireCompleteType(Ptr->getLocStart(), ValType->
getPointeeType(),
1729 diag::err_incomplete_type)) {
1735 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
1736 << IsC11 << Ptr->
getType() << Ptr->getSourceRange();
1744 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
1745 << Ptr->
getType() << Ptr->getSourceRange();
1760 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
1761 << ValType << Ptr->getSourceRange();
1770 if (Form == Copy || Form == GNUXchg || Form == Init)
1772 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
1788 for (
unsigned i = 1; i != NumArgs[Form]; ++i) {
1790 if (i < NumVals[Form] + 1) {
1797 assert(Form != Load);
1798 if (Form == Init || (Form == Arithmetic && ValType->
isIntegerType()))
1800 else if (Form == Copy || Form == Xchg)
1802 else if (Form == Arithmetic)
1810 AS = PtrTy->getPointeeType().getAddressSpace();
1842 SubExprs.push_back(Ptr);
1846 SubExprs.push_back(TheCall->
getArg(1));
1849 SubExprs.push_back(TheCall->
getArg(1));
1854 SubExprs.push_back(TheCall->
getArg(2));
1855 SubExprs.push_back(TheCall->
getArg(1));
1859 SubExprs.push_back(TheCall->
getArg(3));
1860 SubExprs.push_back(TheCall->
getArg(1));
1861 SubExprs.push_back(TheCall->
getArg(2));
1864 SubExprs.push_back(TheCall->
getArg(3));
1865 SubExprs.push_back(TheCall->
getArg(1));
1866 SubExprs.push_back(TheCall->
getArg(4));
1867 SubExprs.push_back(TheCall->
getArg(2));
1870 SubExprs.push_back(TheCall->
getArg(4));
1871 SubExprs.push_back(TheCall->
getArg(1));
1872 SubExprs.push_back(TheCall->
getArg(5));
1873 SubExprs.push_back(TheCall->
getArg(2));
1874 SubExprs.push_back(TheCall->
getArg(3));
1878 if (SubExprs.size() >= 2 && Form != Init) {
1879 llvm::APSInt Result(32);
1880 if (SubExprs[1]->isIntegerConstantExpr(Result,
Context) &&
1882 Diag(SubExprs[1]->getLocStart(),
1883 diag::warn_atomic_op_has_invalid_memory_order)
1884 << SubExprs[1]->getSourceRange();
1888 SubExprs, ResultType, Op,
1891 if ((Op == AtomicExpr::AO__c11_atomic_load ||
1892 (Op == AtomicExpr::AO__c11_atomic_store)) &&
1895 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
1910 assert(Fn &&
"builtin call without direct callee!");
1934 Sema::SemaBuiltinAtomicOverloaded(
ExprResult TheCallResult) {
1941 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
1943 << TheCall->
getCallee()->getSourceRange();
1953 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
1956 FirstArg = FirstArgResult.
get();
1957 TheCall->
setArg(0, FirstArg);
1962 << FirstArg->
getType() << FirstArg->getSourceRange();
1969 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
1970 << FirstArg->
getType() << FirstArg->getSourceRange();
1984 << ValType << FirstArg->getSourceRange();
1998 #define BUILTIN_ROW(x) \
1999 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
2000 Builtin::BI##x##_8, Builtin::BI##x##_16 }
2002 static const unsigned BuiltinIndices[][5] = {
2028 case 1: SizeIndex = 0;
break;
2029 case 2: SizeIndex = 1;
break;
2030 case 4: SizeIndex = 2;
break;
2031 case 8: SizeIndex = 3;
break;
2032 case 16: SizeIndex = 4;
break;
2035 << FirstArg->
getType() << FirstArg->getSourceRange();
2043 unsigned BuiltinID = FDecl->getBuiltinID();
2044 unsigned BuiltinIndex, NumFixed = 1;
2045 bool WarnAboutSemanticsChange =
false;
2046 switch (BuiltinID) {
2047 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
2048 case Builtin::BI__sync_fetch_and_add:
2049 case Builtin::BI__sync_fetch_and_add_1:
2050 case Builtin::BI__sync_fetch_and_add_2:
2051 case Builtin::BI__sync_fetch_and_add_4:
2052 case Builtin::BI__sync_fetch_and_add_8:
2053 case Builtin::BI__sync_fetch_and_add_16:
2057 case Builtin::BI__sync_fetch_and_sub:
2058 case Builtin::BI__sync_fetch_and_sub_1:
2059 case Builtin::BI__sync_fetch_and_sub_2:
2060 case Builtin::BI__sync_fetch_and_sub_4:
2061 case Builtin::BI__sync_fetch_and_sub_8:
2062 case Builtin::BI__sync_fetch_and_sub_16:
2066 case Builtin::BI__sync_fetch_and_or:
2067 case Builtin::BI__sync_fetch_and_or_1:
2068 case Builtin::BI__sync_fetch_and_or_2:
2069 case Builtin::BI__sync_fetch_and_or_4:
2070 case Builtin::BI__sync_fetch_and_or_8:
2071 case Builtin::BI__sync_fetch_and_or_16:
2075 case Builtin::BI__sync_fetch_and_and:
2076 case Builtin::BI__sync_fetch_and_and_1:
2077 case Builtin::BI__sync_fetch_and_and_2:
2078 case Builtin::BI__sync_fetch_and_and_4:
2079 case Builtin::BI__sync_fetch_and_and_8:
2080 case Builtin::BI__sync_fetch_and_and_16:
2084 case Builtin::BI__sync_fetch_and_xor:
2085 case Builtin::BI__sync_fetch_and_xor_1:
2086 case Builtin::BI__sync_fetch_and_xor_2:
2087 case Builtin::BI__sync_fetch_and_xor_4:
2088 case Builtin::BI__sync_fetch_and_xor_8:
2089 case Builtin::BI__sync_fetch_and_xor_16:
2093 case Builtin::BI__sync_fetch_and_nand:
2094 case Builtin::BI__sync_fetch_and_nand_1:
2095 case Builtin::BI__sync_fetch_and_nand_2:
2096 case Builtin::BI__sync_fetch_and_nand_4:
2097 case Builtin::BI__sync_fetch_and_nand_8:
2098 case Builtin::BI__sync_fetch_and_nand_16:
2100 WarnAboutSemanticsChange =
true;
2103 case Builtin::BI__sync_add_and_fetch:
2104 case Builtin::BI__sync_add_and_fetch_1:
2105 case Builtin::BI__sync_add_and_fetch_2:
2106 case Builtin::BI__sync_add_and_fetch_4:
2107 case Builtin::BI__sync_add_and_fetch_8:
2108 case Builtin::BI__sync_add_and_fetch_16:
2112 case Builtin::BI__sync_sub_and_fetch:
2113 case Builtin::BI__sync_sub_and_fetch_1:
2114 case Builtin::BI__sync_sub_and_fetch_2:
2115 case Builtin::BI__sync_sub_and_fetch_4:
2116 case Builtin::BI__sync_sub_and_fetch_8:
2117 case Builtin::BI__sync_sub_and_fetch_16:
2121 case Builtin::BI__sync_and_and_fetch:
2122 case Builtin::BI__sync_and_and_fetch_1:
2123 case Builtin::BI__sync_and_and_fetch_2:
2124 case Builtin::BI__sync_and_and_fetch_4:
2125 case Builtin::BI__sync_and_and_fetch_8:
2126 case Builtin::BI__sync_and_and_fetch_16:
2130 case Builtin::BI__sync_or_and_fetch:
2131 case Builtin::BI__sync_or_and_fetch_1:
2132 case Builtin::BI__sync_or_and_fetch_2:
2133 case Builtin::BI__sync_or_and_fetch_4:
2134 case Builtin::BI__sync_or_and_fetch_8:
2135 case Builtin::BI__sync_or_and_fetch_16:
2139 case Builtin::BI__sync_xor_and_fetch:
2140 case Builtin::BI__sync_xor_and_fetch_1:
2141 case Builtin::BI__sync_xor_and_fetch_2:
2142 case Builtin::BI__sync_xor_and_fetch_4:
2143 case Builtin::BI__sync_xor_and_fetch_8:
2144 case Builtin::BI__sync_xor_and_fetch_16:
2148 case Builtin::BI__sync_nand_and_fetch:
2149 case Builtin::BI__sync_nand_and_fetch_1:
2150 case Builtin::BI__sync_nand_and_fetch_2:
2151 case Builtin::BI__sync_nand_and_fetch_4:
2152 case Builtin::BI__sync_nand_and_fetch_8:
2153 case Builtin::BI__sync_nand_and_fetch_16:
2155 WarnAboutSemanticsChange =
true;
2158 case Builtin::BI__sync_val_compare_and_swap:
2159 case Builtin::BI__sync_val_compare_and_swap_1:
2160 case Builtin::BI__sync_val_compare_and_swap_2:
2161 case Builtin::BI__sync_val_compare_and_swap_4:
2162 case Builtin::BI__sync_val_compare_and_swap_8:
2163 case Builtin::BI__sync_val_compare_and_swap_16:
2168 case Builtin::BI__sync_bool_compare_and_swap:
2169 case Builtin::BI__sync_bool_compare_and_swap_1:
2170 case Builtin::BI__sync_bool_compare_and_swap_2:
2171 case Builtin::BI__sync_bool_compare_and_swap_4:
2172 case Builtin::BI__sync_bool_compare_and_swap_8:
2173 case Builtin::BI__sync_bool_compare_and_swap_16:
2179 case Builtin::BI__sync_lock_test_and_set:
2180 case Builtin::BI__sync_lock_test_and_set_1:
2181 case Builtin::BI__sync_lock_test_and_set_2:
2182 case Builtin::BI__sync_lock_test_and_set_4:
2183 case Builtin::BI__sync_lock_test_and_set_8:
2184 case Builtin::BI__sync_lock_test_and_set_16:
2188 case Builtin::BI__sync_lock_release:
2189 case Builtin::BI__sync_lock_release_1:
2190 case Builtin::BI__sync_lock_release_2:
2191 case Builtin::BI__sync_lock_release_4:
2192 case Builtin::BI__sync_lock_release_8:
2193 case Builtin::BI__sync_lock_release_16:
2199 case Builtin::BI__sync_swap:
2200 case Builtin::BI__sync_swap_1:
2201 case Builtin::BI__sync_swap_2:
2202 case Builtin::BI__sync_swap_4:
2203 case Builtin::BI__sync_swap_8:
2204 case Builtin::BI__sync_swap_16:
2212 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
2214 << TheCall->
getCallee()->getSourceRange();
2218 if (WarnAboutSemanticsChange) {
2219 Diag(TheCall->
getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
2220 << TheCall->
getCallee()->getSourceRange();
2225 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
2228 if (NewBuiltinID == BuiltinID)
2229 NewBuiltinDecl = FDecl;
2234 LookupName(Res, TUScope,
true);
2235 assert(Res.getFoundDecl());
2236 NewBuiltinDecl = dyn_cast<
FunctionDecl>(Res.getFoundDecl());
2237 if (!NewBuiltinDecl)
2244 for (
unsigned i = 0; i != NumFixed; ++i) {
2281 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
2290 return TheCallResult;
2304 unsigned BuiltinID = FDecl->getBuiltinID();
2305 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
2306 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
2307 "Unexpected nontemporal load/store builtin!");
2308 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
2309 unsigned numArgs = isStore ? 2 : 1;
2319 Expr *PointerArg = TheCall->
getArg(numArgs - 1);
2321 DefaultFunctionArrayLvalueConversion(PointerArg);
2325 PointerArg = PointerArgResult.
get();
2326 TheCall->
setArg(numArgs - 1, PointerArg);
2330 Diag(DRE->
getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
2331 << PointerArg->
getType() << PointerArg->getSourceRange();
2343 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
2344 << PointerArg->
getType() << PointerArg->getSourceRange();
2350 return TheCallResult;
2355 Context, ValType,
false);
2356 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
2362 return TheCallResult;
2369 bool Sema::CheckObjCString(
Expr *Arg) {
2373 if (!Literal || !Literal->
isAscii()) {
2374 Diag(Arg->getLocStart(), diag::err_cfstring_literal_not_string_constant)
2375 << Arg->getSourceRange();
2380 StringRef String = Literal->
getString();
2381 unsigned NumBytes = String.size();
2383 const UTF8 *FromPtr = (
const UTF8 *)String.data();
2384 UTF16 *ToPtr = &ToBuf[0];
2386 ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2387 &ToPtr, ToPtr + NumBytes,
2390 if (Result != conversionOK)
2391 Diag(Arg->getLocStart(),
2392 diag::warn_cfstring_truncated) << Arg->getSourceRange();
2400 bool Sema::SemaBuiltinVAStartImpl(
CallExpr *TheCall) {
2404 diag::err_typecheck_call_too_many_args)
2406 << Fn->getSourceRange()
2408 (*(TheCall->
arg_end()-1))->getLocEnd());
2414 diag::err_typecheck_call_too_few_args_at_least)
2428 isVariadic = FD->isVariadic();
2430 isVariadic = getCurMethodDecl()->isVariadic();
2433 Diag(Fn->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2439 bool SecondArgIsLastNamedArgument =
false;
2447 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
2448 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
2455 LastArg = *(FD->param_end()-1);
2457 LastArg = *(getCurMethodDecl()->param_end()-1);
2458 SecondArgIsLastNamedArgument = PV == LastArg;
2460 Type = PV->getType();
2461 ParamLoc = PV->getLocation();
2465 if (!SecondArgIsLastNamedArgument)
2467 diag::warn_second_parameter_of_va_start_not_last_named_argument);
2469 Diag(Arg->getLocStart(),
2470 diag::warn_va_start_of_reference_type_is_undefined);
2471 Diag(ParamLoc, diag::note_parameter_type) << Type;
2481 bool Sema::SemaBuiltinVAStart(
CallExpr *TheCall) {
2490 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
2494 diag::err_va_start_used_in_wrong_abi_function)
2495 << (OS != llvm::Triple::Win32);
2497 return SemaBuiltinVAStartImpl(TheCall);
2503 bool Sema::SemaBuiltinMSVAStart(
CallExpr *TheCall) {
2507 if (TT.getArch() != llvm::Triple::x86_64)
2508 return Diag(Callee->getLocStart(), diag::err_x86_builtin_32_bit_tgt);
2512 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
2515 return Diag(Callee->getLocStart(),
2516 diag::err_ms_va_start_used_in_sysv_function);
2517 return SemaBuiltinVAStartImpl(TheCall);
2520 bool Sema::SemaBuiltinVAStartARM(
CallExpr *Call) {
2528 diag::err_typecheck_call_too_few_args_at_least)
2536 IsVariadic = FD->isVariadic();
2538 IsVariadic = MD->isVariadic();
2540 llvm_unreachable(
"unexpected statement type");
2543 Diag(Func->getLocStart(), diag::err_va_start_used_in_non_variadic_function);
2554 } ArgumentTypes[] = {
2559 for (
const auto &AT : ArgumentTypes) {
2563 Diag(Arg->getLocStart(), diag::err_typecheck_convert_incompatible)
2564 << Arg->
getType() << AT.Type << 1
2566 << AT.ArgNo + 1 << Arg->
getType() << AT.Type;
2574 bool Sema::SemaBuiltinUnorderedCompare(
CallExpr *TheCall) {
2576 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2579 return Diag(TheCall->
getArg(2)->getLocStart(),
2580 diag::err_typecheck_call_too_many_args)
2583 (*(TheCall->
arg_end()-1))->getLocEnd());
2590 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1,
false);
2591 if (OrigArg0.isInvalid() || OrigArg1.
isInvalid())
2597 TheCall->
setArg(0, OrigArg0.get());
2606 return Diag(OrigArg0.get()->getLocStart(),
2607 diag::err_typecheck_call_invalid_ordered_compare)
2608 << OrigArg0.get()->getType() << OrigArg1.
get()->
getType()
2609 <<
SourceRange(OrigArg0.get()->getLocStart(), OrigArg1.
get()->getLocEnd());
2618 bool Sema::SemaBuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs) {
2620 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2623 return Diag(TheCall->
getArg(NumArgs)->getLocStart(),
2624 diag::err_typecheck_call_too_many_args)
2627 (*(TheCall->
arg_end()-1))->getLocEnd());
2631 if (OrigArg->isTypeDependent())
2635 if (!OrigArg->getType()->isRealFloatingType())
2636 return Diag(OrigArg->getLocStart(),
2637 diag::err_typecheck_call_invalid_unary_fp)
2638 << OrigArg->getType() << OrigArg->getSourceRange();
2642 Expr *CastArg = Cast->getSubExpr();
2644 assert(Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) &&
2645 "promotion from float to double is the only expected cast here");
2646 Cast->setSubExpr(
nullptr);
2647 TheCall->
setArg(NumArgs-1, CastArg);
2659 diag::err_typecheck_call_too_few_args_at_least)
2661 << TheCall->getSourceRange());
2668 unsigned numElements = 0;
2677 diag::err_shufflevector_non_vector)
2679 TheCall->
getArg(1)->getLocEnd()));
2682 unsigned numResElements = TheCall->
getNumArgs() - 2;
2691 diag::err_shufflevector_incompatible_vector)
2693 TheCall->
getArg(1)->getLocEnd()));
2696 diag::err_shufflevector_incompatible_vector)
2698 TheCall->
getArg(1)->getLocEnd()));
2699 }
else if (numElements != numResElements) {
2706 for (
unsigned i = 2; i < TheCall->
getNumArgs(); i++) {
2711 llvm::APSInt Result(32);
2714 diag::err_shufflevector_nonconstant_argument)
2715 << TheCall->
getArg(i)->getSourceRange());
2718 if (Result.isSigned() && Result.isAllOnesValue())
2721 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
2723 diag::err_shufflevector_argument_too_large)
2724 << TheCall->
getArg(i)->getSourceRange());
2729 for (
unsigned i = 0, e = TheCall->
getNumArgs(); i != e; i++) {
2730 exprs.push_back(TheCall->
getArg(i));
2731 TheCall->
setArg(i,
nullptr);
2750 diag::err_convertvector_non_vector)
2751 << E->getSourceRange());
2754 diag::err_convertvector_non_vector_type));
2759 if (SrcElts != DstElts)
2761 diag::err_convertvector_incompatible_vector)
2762 << E->getSourceRange());
2772 bool Sema::SemaBuiltinPrefetch(
CallExpr *TheCall) {
2777 diag::err_typecheck_call_too_many_args_at_most)
2778 << 0 << 3 << NumArgs
2779 << TheCall->getSourceRange();
2783 for (
unsigned i = 1; i !=
NumArgs; ++i)
2784 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
2793 bool Sema::SemaBuiltinAssume(
CallExpr *TheCall) {
2798 Diag(Arg->getLocStart(), diag::warn_assume_side_effects)
2799 << Arg->getSourceRange()
2807 bool Sema::SemaBuiltinAssumeAligned(
CallExpr *TheCall) {
2812 diag::err_typecheck_call_too_many_args_at_most)
2813 << 0 << 3 << NumArgs
2814 << TheCall->getSourceRange();
2821 llvm::APSInt Result;
2822 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2825 if (!Result.isPowerOf2())
2827 diag::err_alignment_not_power_of_two)
2828 << Arg->getSourceRange();
2836 if (Arg.isInvalid())
return true;
2837 TheCall->
setArg(2, Arg.get());
2845 bool Sema::SemaBuiltinConstantArg(
CallExpr *TheCall,
int ArgNum,
2846 llvm::APSInt &Result) {
2854 return Diag(TheCall->
getLocStart(), diag::err_constant_integer_arg_type)
2855 << FDecl->getDeclName() << Arg->getSourceRange();
2862 bool Sema::SemaBuiltinConstantArgRange(
CallExpr *TheCall,
int ArgNum,
2863 int Low,
int High) {
2864 llvm::APSInt Result;
2872 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2875 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
2877 << Low << High << Arg->getSourceRange();
2884 bool Sema::SemaBuiltinARMSpecialReg(
unsigned BuiltinID,
CallExpr *TheCall,
2885 int ArgNum,
unsigned ExpectedFieldNum,
2887 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2888 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
2889 BuiltinID == ARM::BI__builtin_arm_rsr ||
2890 BuiltinID == ARM::BI__builtin_arm_rsrp ||
2891 BuiltinID == ARM::BI__builtin_arm_wsr ||
2892 BuiltinID == ARM::BI__builtin_arm_wsrp;
2893 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2894 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
2895 BuiltinID == AArch64::BI__builtin_arm_rsr ||
2896 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2897 BuiltinID == AArch64::BI__builtin_arm_wsr ||
2898 BuiltinID == AArch64::BI__builtin_arm_wsrp;
2899 assert((IsARMBuiltin || IsAArch64Builtin) &&
"Unexpected ARM builtin.");
2908 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
2909 << Arg->getSourceRange();
2914 Reg.split(Fields,
":");
2916 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
2918 << Arg->getSourceRange();
2924 if (Fields.size() > 1) {
2925 bool FiveFields = Fields.size() == 5;
2927 bool ValidString =
true;
2929 ValidString &= Fields[0].startswith_lower(
"cp") ||
2930 Fields[0].startswith_lower(
"p");
2933 Fields[0].drop_front(Fields[0].startswith_lower(
"cp") ? 2 : 1);
2935 ValidString &= Fields[2].startswith_lower(
"c");
2937 Fields[2] = Fields[2].drop_front(1);
2940 ValidString &= Fields[3].startswith_lower(
"c");
2942 Fields[3] = Fields[3].drop_front(1);
2948 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 7, 15, 15});
2950 Ranges.append({15, 7, 15});
2952 for (
unsigned i=0; i<Fields.size(); ++i) {
2954 ValidString &= !Fields[i].getAsInteger(10, IntField);
2955 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
2960 << Arg->getSourceRange();
2962 }
else if (IsAArch64Builtin && Fields.size() == 1) {
2972 std::string RegLower = Reg.lower();
2973 if (RegLower !=
"spsel" && RegLower !=
"daifset" && RegLower !=
"daifclr" &&
2974 RegLower !=
"pan" && RegLower !=
"uao")
2977 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2986 bool Sema::SemaBuiltinLongjmp(
CallExpr *TheCall) {
2988 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_unsupported)
2992 llvm::APSInt Result;
2995 if (SemaBuiltinConstantArg(TheCall, 1, Result))
2999 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_invalid_val)
3000 <<
SourceRange(Arg->getLocStart(), Arg->getLocEnd());
3008 bool Sema::SemaBuiltinSetjmp(
CallExpr *TheCall) {
3010 return Diag(TheCall->
getLocStart(), diag::err_builtin_setjmp_unsupported)
3018 SLCT_UncheckedLiteral,
3029 bool HasVAListArg,
unsigned format_idx,
3032 llvm::SmallBitVector &CheckedVarArgs) {
3035 return SLCT_NotALiteral;
3044 return SLCT_UncheckedLiteral;
3046 switch (E->getStmtClass()) {
3047 case Stmt::BinaryConditionalOperatorClass:
3048 case Stmt::ConditionalOperatorClass: {
3052 cast<AbstractConditionalOperator>(
E);
3055 HasVAListArg, format_idx, firstDataArg,
3056 Type, CallType, InFunctionCall, CheckedVarArgs);
3057 if (Left == SLCT_NotALiteral)
3058 return SLCT_NotALiteral;
3061 HasVAListArg, format_idx, firstDataArg,
3062 Type, CallType, InFunctionCall, CheckedVarArgs);
3063 return Left < Right ? Left : Right;
3066 case Stmt::ImplicitCastExprClass: {
3067 E = cast<ImplicitCastExpr>(
E)->getSubExpr();
3071 case Stmt::OpaqueValueExprClass:
3072 if (
const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
3076 return SLCT_NotALiteral;
3078 case Stmt::PredefinedExprClass:
3082 return SLCT_UncheckedLiteral;
3084 case Stmt::DeclRefExprClass: {
3090 bool isConstant =
false;
3094 isConstant = AT->getElementType().isConstant(S.
Context);
3097 PT->getPointeeType().isConstant(S.
Context);
3105 if (
const Expr *Init = VD->getAnyInitializer()) {
3107 if (
const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3108 if (InitList->isStringLiteralInit())
3109 Init = InitList->getInit(0)->IgnoreParenImpCasts();
3112 HasVAListArg, format_idx,
3113 firstDataArg, Type, CallType,
3114 false, CheckedVarArgs);
3133 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
3134 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
3135 int PVIndex = PV->getFunctionScopeIndex() + 1;
3136 for (
const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
3139 if (MD->isInstance())
3143 if (PVIndex == PVFormat->getFormatIdx() &&
3145 return SLCT_UncheckedLiteral;
3152 return SLCT_NotALiteral;
3155 case Stmt::CallExprClass:
3156 case Stmt::CXXMemberCallExprClass: {
3159 if (
const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
3160 unsigned ArgIndex = FA->getFormatIdx();
3162 if (MD->isInstance())
3167 HasVAListArg, format_idx, firstDataArg,
3168 Type, CallType, InFunctionCall,
3170 }
else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
3171 unsigned BuiltinID = FD->getBuiltinID();
3172 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
3173 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
3176 HasVAListArg, format_idx,
3177 firstDataArg, Type, CallType,
3178 InFunctionCall, CheckedVarArgs);
3183 return SLCT_NotALiteral;
3185 case Stmt::ObjCStringLiteralClass:
3186 case Stmt::StringLiteralClass: {
3192 StrE = cast<StringLiteral>(
E);
3196 Type, InFunctionCall, CallType, CheckedVarArgs);
3197 return SLCT_CheckedLiteral;
3200 return SLCT_NotALiteral;
3204 return SLCT_NotALiteral;
3209 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
3210 .Case(
"scanf", FST_Scanf)
3211 .Cases(
"printf",
"printf0", FST_Printf)
3212 .Cases(
"NSString",
"CFString", FST_NSString)
3213 .Case(
"strftime", FST_Strftime)
3214 .Case(
"strfmon", FST_Strfmon)
3215 .Cases(
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err", FST_Kprintf)
3216 .Case(
"freebsd_kprintf", FST_FreeBSDKPrintf)
3217 .Case(
"os_trace", FST_OSTrace)
3218 .Default(FST_Unknown);
3224 bool Sema::CheckFormatArguments(
const FormatAttr *Format,
3227 VariadicCallType CallType,
3229 llvm::SmallBitVector &CheckedVarArgs) {
3230 FormatStringInfo FSI;
3231 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
3232 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
3233 FSI.FirstDataArg, GetFormatStringType(Format),
3234 CallType, Loc, Range, CheckedVarArgs);
3239 bool HasVAListArg,
unsigned format_idx,
3240 unsigned firstDataArg, FormatStringType Type,
3241 VariadicCallType CallType,
3243 llvm::SmallBitVector &CheckedVarArgs) {
3245 if (format_idx >= Args.size()) {
3246 Diag(Loc, diag::warn_missing_format_string) << Range;
3250 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
3266 format_idx, firstDataArg, Type, CallType,
3267 true, CheckedVarArgs);
3268 if (CT != SLCT_NotALiteral)
3270 return CT == SLCT_CheckedLiteral;
3274 if (Type == FST_Strftime)
3281 if (Type == FST_NSString &&
3287 if (Args.size() == firstDataArg)
3288 Diag(Args[format_idx]->getLocStart(),
3289 diag::warn_format_nonliteral_noargs)
3290 << OrigFormatExpr->getSourceRange();
3292 Diag(Args[format_idx]->getLocStart(),
3293 diag::warn_format_nonliteral)
3294 << OrigFormatExpr->getSourceRange();
3303 const Expr *OrigFormatExpr;
3304 const unsigned FirstDataArg;
3305 const unsigned NumDataArgs;
3307 const bool HasVAListArg;
3310 llvm::SmallBitVector CoveredArgs;
3311 bool usesPositionalArgs;
3313 bool inFunctionCall;
3315 llvm::SmallBitVector &CheckedVarArgs;
3318 const Expr *origFormatExpr,
unsigned firstDataArg,
3319 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
3321 unsigned formatIdx,
bool inFunctionCall,
3323 llvm::SmallBitVector &CheckedVarArgs)
3324 :
S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr),
3325 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs),
3326 Beg(beg), HasVAListArg(hasVAListArg),
3327 Args(Args), FormatIdx(formatIdx),
3328 usesPositionalArgs(
false), atFirstArg(
true),
3329 inFunctionCall(inFunctionCall), CallType(callType),
3330 CheckedVarArgs(CheckedVarArgs) {
3331 CoveredArgs.resize(numDataArgs);
3332 CoveredArgs.reset();
3335 void DoneProcessing();
3337 void HandleIncompleteSpecifier(
const char *startSpecifier,
3338 unsigned specifierLen)
override;
3340 void HandleInvalidLengthModifier(
3343 const char *startSpecifier,
unsigned specifierLen,
3346 void HandleNonStandardLengthModifier(
3348 const char *startSpecifier,
unsigned specifierLen);
3350 void HandleNonStandardConversionSpecifier(
3352 const char *startSpecifier,
unsigned specifierLen);
3354 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
3356 void HandleInvalidPosition(
const char *startSpecifier,
3357 unsigned specifierLen,
3360 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
3362 void HandleNullChar(
const char *nullCharacter)
override;
3364 template <
typename Range>
3365 static void EmitFormatDiagnostic(
Sema &
S,
bool inFunctionCall,
3366 const Expr *ArgumentExpr,
3369 bool IsStringLocation, Range StringRange,
3373 bool HandleInvalidConversionSpecifier(
unsigned argIndex,
SourceLocation Loc,
3374 const char *startSpec,
3375 unsigned specifierLen,
3376 const char *csStart,
unsigned csLen);
3379 const char *startSpec,
3380 unsigned specifierLen);
3384 unsigned specifierLen);
3387 const Expr *getDataArg(
unsigned i)
const;
3391 const char *startSpecifier,
unsigned specifierLen,
3394 template <
typename Range>
3396 bool IsStringLocation, Range StringRange,
3401 SourceRange CheckFormatHandler::getFormatStringRange() {
3402 return OrigFormatExpr->getSourceRange();
3406 getSpecifierRange(
const char *startSpecifier,
unsigned specifierLen) {
3416 SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
3420 void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
3421 unsigned specifierLen){
3422 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_incomplete_specifier),
3423 getLocationOfByte(startSpecifier),
3425 getSpecifierRange(startSpecifier, specifierLen));
3428 void CheckFormatHandler::HandleInvalidLengthModifier(
3431 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
3432 using namespace analyze_format_string;
3435 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3440 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
3441 getLocationOfByte(LM.getStart()),
3443 getSpecifierRange(startSpecifier, specifierLen));
3445 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3446 << FixedLM->toString()
3451 if (DiagID == diag::warn_format_nonsensical_length)
3454 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
3455 getLocationOfByte(LM.getStart()),
3457 getSpecifierRange(startSpecifier, specifierLen),
3462 void CheckFormatHandler::HandleNonStandardLengthModifier(
3464 const char *startSpecifier,
unsigned specifierLen) {
3465 using namespace analyze_format_string;
3468 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
3473 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3474 << LM.toString() << 0,
3475 getLocationOfByte(LM.getStart()),
3477 getSpecifierRange(startSpecifier, specifierLen));
3479 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
3480 << FixedLM->toString()
3484 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3485 << LM.toString() << 0,
3486 getLocationOfByte(LM.getStart()),
3488 getSpecifierRange(startSpecifier, specifierLen));
3492 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
3494 const char *startSpecifier,
unsigned specifierLen) {
3495 using namespace analyze_format_string;
3500 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3504 getSpecifierRange(startSpecifier, specifierLen));
3507 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
3508 << FixedCS->toString()
3511 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
3515 getSpecifierRange(startSpecifier, specifierLen));
3519 void CheckFormatHandler::HandlePosition(
const char *startPos,
3521 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard_positional_arg),
3522 getLocationOfByte(startPos),
3524 getSpecifierRange(startPos, posLen));
3528 CheckFormatHandler::HandleInvalidPosition(
const char *startPos,
unsigned posLen,
3530 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_positional_specifier)
3532 getLocationOfByte(startPos),
true,
3533 getSpecifierRange(startPos, posLen));
3536 void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
3538 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_zero_positional_specifier),
3539 getLocationOfByte(startPos),
3541 getSpecifierRange(startPos, posLen));
3544 void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
3545 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
3547 EmitFormatDiagnostic(
3548 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
3549 getLocationOfByte(nullCharacter),
true,
3550 getFormatStringRange());
3556 const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
3557 return Args[FirstDataArg + i];
3560 void CheckFormatHandler::DoneProcessing() {
3563 if (!HasVAListArg) {
3566 signed notCoveredArg = CoveredArgs.find_first();
3567 if (notCoveredArg >= 0) {
3568 assert((
unsigned)notCoveredArg < NumDataArgs);
3569 if (
const Expr *
E = getDataArg((
unsigned) notCoveredArg)) {
3572 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_data_arg_not_used),
3574 getFormatStringRange());
3582 CheckFormatHandler::HandleInvalidConversionSpecifier(
unsigned argIndex,
3584 const char *startSpec,
3585 unsigned specifierLen,
3586 const char *csStart,
3589 bool keepGoing =
true;
3590 if (argIndex < NumDataArgs) {
3593 CoveredArgs.set(argIndex);
3604 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_conversion)
3605 << StringRef(csStart, csLen),
3607 getSpecifierRange(startSpec, specifierLen));
3613 CheckFormatHandler::HandlePositionalNonpositionalArgs(
SourceLocation Loc,
3614 const char *startSpec,
3615 unsigned specifierLen) {
3616 EmitFormatDiagnostic(
3617 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args),
3618 Loc,
true, getSpecifierRange(startSpec, specifierLen));
3622 CheckFormatHandler::CheckNumArgs(
3625 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
3627 if (argIndex >= NumDataArgs) {
3629 ? (
S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
3630 << (argIndex+1) << NumDataArgs)
3631 :
S.
PDiag(diag::warn_printf_insufficient_data_args);
3632 EmitFormatDiagnostic(
3633 PDiag, getLocationOfByte(CS.
getStart()),
true,
3634 getSpecifierRange(startSpecifier, specifierLen));
3640 template<
typename Range>
3643 bool IsStringLocation,
3646 EmitFormatDiagnostic(
S, inFunctionCall, Args[FormatIdx], PDiag,
3647 Loc, IsStringLocation, StringRange, FixIt);
3677 template<
typename Range>
3678 void CheckFormatHandler::EmitFormatDiagnostic(
Sema &
S,
bool InFunctionCall,
3679 const Expr *ArgumentExpr,
3682 bool IsStringLocation,
3685 if (InFunctionCall) {
3690 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
3691 << ArgumentExpr->getSourceRange();
3694 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
3695 diag::note_format_string_defined);
3697 Note << StringRange;
3705 class CheckPrintfHandler :
public CheckFormatHandler {
3709 const Expr *origFormatExpr,
unsigned firstDataArg,
3710 unsigned numDataArgs,
bool isObjC,
3711 const char *beg,
bool hasVAListArg,
3713 unsigned formatIdx,
bool inFunctionCall,
3715 llvm::SmallBitVector &CheckedVarArgs)
3716 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
3717 numDataArgs, beg, hasVAListArg, Args,
3718 formatIdx, inFunctionCall, CallType, CheckedVarArgs),
3723 bool HandleInvalidPrintfConversionSpecifier(
3725 const char *startSpecifier,
3726 unsigned specifierLen)
override;
3729 const char *startSpecifier,
3730 unsigned specifierLen)
override;
3732 const char *StartSpecifier,
3733 unsigned SpecifierLen,
3737 const char *startSpecifier,
unsigned specifierLen);
3739 const analyze_printf::OptionalAmount &Amt,
3741 const char *startSpecifier,
unsigned specifierLen);
3743 const analyze_printf::OptionalFlag &flag,
3744 const char *startSpecifier,
unsigned specifierLen);
3746 const analyze_printf::OptionalFlag &ignoredFlag,
3747 const analyze_printf::OptionalFlag &flag,
3748 const char *startSpecifier,
unsigned specifierLen);
3749 bool checkForCStrMembers(
const analyze_printf::ArgType &AT,
3752 void HandleEmptyObjCModifierFlag(
const char *startFlag,
3753 unsigned flagLen)
override;
3755 void HandleInvalidObjCModifierFlag(
const char *startFlag,
3756 unsigned flagLen)
override;
3758 void HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
3759 const char *flagsEnd,
3760 const char *conversionPosition)
3765 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
3767 const char *startSpecifier,
3768 unsigned specifierLen) {
3772 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
3774 startSpecifier, specifierLen,
3778 bool CheckPrintfHandler::HandleAmount(
3780 unsigned k,
const char *startSpecifier,
3781 unsigned specifierLen) {
3784 if (!HasVAListArg) {
3786 if (argIndex >= NumDataArgs) {
3787 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
3791 getSpecifierRange(startSpecifier, specifierLen));
3801 CoveredArgs.set(argIndex);
3802 const Expr *Arg = getDataArg(argIndex);
3809 assert(AT.isValid());
3811 if (!AT.matchesType(S.
Context, T)) {
3812 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_wrong_type)
3813 << k << AT.getRepresentativeTypeName(S.
Context)
3814 << T << Arg->getSourceRange(),
3817 getSpecifierRange(startSpecifier, specifierLen));
3827 void CheckPrintfHandler::HandleInvalidAmount(
3829 const analyze_printf::OptionalAmount &Amt,
3831 const char *startSpecifier,
3832 unsigned specifierLen) {
3837 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
3839 Amt.getConstantLength()))
3842 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
3844 getLocationOfByte(Amt.getStart()),
3846 getSpecifierRange(startSpecifier, specifierLen),
3851 const analyze_printf::OptionalFlag &flag,
3852 const char *startSpecifier,
3853 unsigned specifierLen) {
3857 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_flag)
3858 << flag.toString() << CS.
toString(),
3859 getLocationOfByte(flag.getPosition()),
3861 getSpecifierRange(startSpecifier, specifierLen),
3863 getSpecifierRange(flag.getPosition(), 1)));
3866 void CheckPrintfHandler::HandleIgnoredFlag(
3868 const analyze_printf::OptionalFlag &ignoredFlag,
3869 const analyze_printf::OptionalFlag &flag,
3870 const char *startSpecifier,
3871 unsigned specifierLen) {
3873 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
3874 << ignoredFlag.toString() << flag.toString(),
3875 getLocationOfByte(ignoredFlag.getPosition()),
3877 getSpecifierRange(startSpecifier, specifierLen),
3879 getSpecifierRange(ignoredFlag.getPosition(), 1)));
3886 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
3889 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_empty_objc_flag),
3890 getLocationOfByte(startFlag),
3892 getSpecifierRange(startFlag, flagLen));
3895 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
3898 auto Range = getSpecifierRange(startFlag, flagLen);
3899 StringRef flag(startFlag, flagLen);
3900 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
3901 getLocationOfByte(startFlag),
3906 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
3907 const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {
3909 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
3910 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
3911 EmitFormatDiagnostic(S.
PDiag(diag) << StringRef(conversionPosition, 1),
3912 getLocationOfByte(conversionPosition),
3920 template<
typename MemberKind>
3921 static llvm::SmallPtrSet<MemberKind*, 1>
3924 llvm::SmallPtrSet<MemberKind*, 1> Results;
3941 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
3952 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3954 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", *
this, E->
getType());
3957 if ((*MI)->getMinRequiredArguments() == 0)
3965 bool CheckPrintfHandler::checkForCStrMembers(
3966 const analyze_printf::ArgType &AT,
const Expr *
E) {
3967 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
3970 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str",
S, E->
getType());
3979 S.Diag(E->getLocStart(), diag::note_printf_c_str)
3992 const char *startSpecifier,
3993 unsigned specifierLen) {
3995 using namespace analyze_format_string;
3996 using namespace analyze_printf;
4005 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
4006 startSpecifier, specifierLen);
4014 startSpecifier, specifierLen)) {
4019 startSpecifier, specifierLen)) {
4031 if (argIndex < NumDataArgs) {
4035 CoveredArgs.set(argIndex);
4039 if (CS.
getKind() == ConversionSpecifier::FreeBSDbArg ||
4040 CS.
getKind() == ConversionSpecifier::FreeBSDDArg) {
4042 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
4046 CoveredArgs.set(argIndex + 1);
4049 const Expr *Ex = getDataArg(argIndex);
4050 const analyze_printf::ArgType &AT =
4051 (CS.
getKind() == ConversionSpecifier::FreeBSDbArg) ?
4052 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
4053 if (AT.isValid() && !AT.matchesType(S.Context, Ex->
getType()))
4054 EmitFormatDiagnostic(
4055 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4056 << AT.getRepresentativeTypeName(S.Context) << Ex->
getType()
4057 <<
false << Ex->getSourceRange(),
4058 Ex->getLocStart(),
false,
4059 getSpecifierRange(startSpecifier, specifierLen));
4062 Ex = getDataArg(argIndex + 1);
4063 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
4064 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
4065 EmitFormatDiagnostic(
4066 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4067 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
4068 <<
false << Ex->getSourceRange(),
4069 Ex->getLocStart(),
false,
4070 getSpecifierRange(startSpecifier, specifierLen));
4078 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
4085 startSpecifier, specifierLen);
4091 startSpecifier, specifierLen);
4100 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
4102 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
4111 startSpecifier, specifierLen);
4114 startSpecifier, specifierLen);
4118 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4119 diag::warn_format_nonsensical_length);
4121 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4123 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4124 diag::warn_format_non_standard_conversion_spec);
4127 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4133 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4136 const Expr *Arg = getDataArg(argIndex);
4140 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
4151 switch (Inside->getStmtClass()) {
4152 case Stmt::ArraySubscriptExprClass:
4153 case Stmt::CallExprClass:
4154 case Stmt::CharacterLiteralClass:
4155 case Stmt::CXXBoolLiteralExprClass:
4156 case Stmt::DeclRefExprClass:
4157 case Stmt::FloatingLiteralClass:
4158 case Stmt::IntegerLiteralClass:
4159 case Stmt::MemberExprClass:
4160 case Stmt::ObjCArrayLiteralClass:
4161 case Stmt::ObjCBoolLiteralExprClass:
4162 case Stmt::ObjCBoxedExprClass:
4163 case Stmt::ObjCDictionaryLiteralClass:
4164 case Stmt::ObjCEncodeExprClass:
4165 case Stmt::ObjCIvarRefExprClass:
4166 case Stmt::ObjCMessageExprClass:
4167 case Stmt::ObjCPropertyRefExprClass:
4168 case Stmt::ObjCStringLiteralClass:
4169 case Stmt::ObjCSubscriptRefExprClass:
4170 case Stmt::ParenExprClass:
4171 case Stmt::StringLiteralClass:
4172 case Stmt::UnaryOperatorClass:
4179 static std::pair<QualType, StringRef>
4188 .Case(
"NSInteger", Context.
LongTy)
4190 .Case(
"SInt32", Context.
IntTy)
4195 return std::make_pair(CastTy, Name);
4197 TyTy = UserTy->desugar();
4201 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
4203 PE->getSubExpr()->getType(),
4212 StringRef TrueName, FalseName;
4214 std::tie(TrueTy, TrueName) =
4216 CO->getTrueExpr()->getType(),
4218 std::tie(FalseTy, FalseName) =
4220 CO->getFalseExpr()->getType(),
4221 CO->getFalseExpr());
4223 if (TrueTy == FalseTy)
4224 return std::make_pair(TrueTy, TrueName);
4225 else if (TrueTy.
isNull())
4226 return std::make_pair(FalseTy, FalseName);
4227 else if (FalseTy.
isNull())
4228 return std::make_pair(TrueTy, TrueName);
4231 return std::make_pair(
QualType(), StringRef());
4236 const char *StartSpecifier,
4237 unsigned SpecifierLen,
4239 using namespace analyze_format_string;
4240 using namespace analyze_printf;
4243 const analyze_printf::ArgType &AT = FS.
getArgType(S.Context,
4249 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
4250 ExprTy = TET->getUnderlyingExpr()->getType();
4253 analyze_printf::ArgType::MatchKind
match = AT.matchesType(S.Context, ExprTy);
4255 if (
match == analyze_printf::ArgType::Match) {
4266 E = ICE->getSubExpr();
4272 if (ICE->getType() == S.Context.IntTy ||
4273 ICE->getType() == S.Context.UnsignedIntTy) {
4275 if (AT.matchesType(S.Context, ExprTy))
4283 if (ExprTy == S.Context.IntTy)
4284 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
4285 ExprTy = S.Context.CharTy;
4289 bool IsEnum =
false;
4290 if (
auto EnumTy = ExprTy->getAs<
EnumType>()) {
4291 ExprTy = EnumTy->getDecl()->getIntegerType();
4301 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
4302 !ExprTy->isCharType()) {
4305 IntendedTy = S.Context.UnsignedShortTy;
4310 const llvm::APInt &V = IL->getValue();
4311 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
4315 LookupResult Result(S, &S.Context.Idents.get(
"unichar"), E->getLocStart(),
4317 if (S.LookupName(Result, S.getCurScope())) {
4320 if (TD->getUnderlyingType() == IntendedTy)
4321 IntendedTy = S.Context.getTypedefType(TD);
4328 bool ShouldNotPrintDirectly =
false; StringRef CastTyName;
4329 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
4333 IntendedTy = CastTy;
4334 ShouldNotPrintDirectly =
true;
4339 PrintfSpecifier fixedFS = FS;
4340 bool success = fixedFS.
fixType(IntendedTy, S.getLangOpts(),
4341 S.Context, ObjCContext);
4346 llvm::raw_svector_ostream os(buf);
4347 fixedFS.toString(os);
4349 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
4351 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
4352 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4354 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4358 EmitFormatDiagnostic(S.PDiag(diag)
4359 << AT.getRepresentativeTypeName(S.Context)
4360 << IntendedTy << IsEnum << E->getSourceRange(),
4374 llvm::raw_svector_ostream CastFix(CastBuf);
4376 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
4380 if (!AT.matchesType(S.Context, IntendedTy))
4385 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
4403 if (ShouldNotPrintDirectly) {
4408 if (
const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
4409 Name = TypedefTy->getDecl()->
getName();
4412 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
4413 << Name << IntendedTy << IsEnum
4414 << E->getSourceRange(),
4415 E->getLocStart(),
false,
4421 EmitFormatDiagnostic(
4422 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
4423 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
4424 << E->getSourceRange(),
4425 E->getLocStart(),
false,
4435 switch (S.isValidVarArgType(ExprTy)) {
4438 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4439 if (
match == analyze_printf::ArgType::NoMatchPedantic) {
4440 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4443 EmitFormatDiagnostic(
4444 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
4445 << IsEnum << CSR << E->getSourceRange(),
4446 E->getLocStart(),
false, CSR);
4451 EmitFormatDiagnostic(
4452 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
4453 << S.getLangOpts().CPlusPlus11
4456 << AT.getRepresentativeTypeName(S.Context)
4458 << E->getSourceRange(),
4459 E->getLocStart(),
false, CSR);
4460 checkForCStrMembers(AT, E);
4464 if (ExprTy->isObjCObjectType())
4465 EmitFormatDiagnostic(
4466 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
4467 << S.getLangOpts().CPlusPlus11
4470 << AT.getRepresentativeTypeName(S.Context)
4472 << E->getSourceRange(),
4473 E->getLocStart(),
false, CSR);
4477 S.Diag(E->getLocStart(), diag::err_cannot_pass_to_vararg_format)
4478 << isa<InitListExpr>(E) << ExprTy << CallType
4479 << AT.getRepresentativeTypeName(S.Context)
4480 << E->getSourceRange();
4484 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
4485 "format string specifier index out of range");
4486 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
4495 class CheckScanfHandler :
public CheckFormatHandler {
4498 const Expr *origFormatExpr,
unsigned firstDataArg,
4499 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
4501 unsigned formatIdx,
bool inFunctionCall,
4503 llvm::SmallBitVector &CheckedVarArgs)
4504 : CheckFormatHandler(s, fexpr, origFormatExpr, firstDataArg,
4505 numDataArgs, beg, hasVAListArg,
4506 Args, formatIdx, inFunctionCall, CallType,
4511 const char *startSpecifier,
4512 unsigned specifierLen)
override;
4514 bool HandleInvalidScanfConversionSpecifier(
4516 const char *startSpecifier,
4517 unsigned specifierLen)
override;
4519 void HandleIncompleteScanList(
const char *start,
const char *
end)
override;
4523 void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
4525 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
4526 getLocationOfByte(end),
true,
4527 getSpecifierRange(start, end - start));
4530 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
4532 const char *startSpecifier,
4533 unsigned specifierLen) {
4538 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
4540 startSpecifier, specifierLen,
4544 bool CheckScanfHandler::HandleScanfSpecifier(
4546 const char *startSpecifier,
4547 unsigned specifierLen) {
4549 using namespace analyze_scanf;
4550 using namespace analyze_format_string;
4562 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
4563 startSpecifier, specifierLen);
4570 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
4571 if (Amt.getConstantAmount() == 0) {
4573 Amt.getConstantLength());
4574 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
4575 getLocationOfByte(Amt.getStart()),
4577 FixItHint::CreateRemoval(R));
4589 if (argIndex < NumDataArgs) {
4593 CoveredArgs.set(argIndex);
4598 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4599 diag::warn_format_nonsensical_length);
4601 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
4603 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
4604 diag::warn_format_non_standard_conversion_spec);
4607 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
4613 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
4617 const Expr *Ex = getDataArg(argIndex);
4623 if (!AT.isValid()) {
4628 AT.matchesType(S.Context, Ex->getType());
4633 ScanfSpecifier fixedFS = FS;
4634 bool success = fixedFS.
fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
4635 S.getLangOpts(), S.Context);
4637 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
4639 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
4645 llvm::raw_svector_ostream os(buf);
4646 fixedFS.toString(os);
4648 EmitFormatDiagnostic(
4649 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
4650 << Ex->getType() <<
false << Ex->getSourceRange(),
4653 getSpecifierRange(startSpecifier, specifierLen),
4655 getSpecifierRange(startSpecifier, specifierLen), os.str()));
4657 EmitFormatDiagnostic(S.PDiag(diag)
4658 << AT.getRepresentativeTypeName(S.Context)
4659 << Ex->getType() <<
false << Ex->getSourceRange(),
4662 getSpecifierRange(startSpecifier, specifierLen));
4669 const Expr *OrigFormatExpr,
4671 bool HasVAListArg,
unsigned format_idx,
4674 llvm::SmallBitVector &CheckedVarArgs) {
4678 CheckFormatHandler::EmitFormatDiagnostic(
4679 *
this, inFunctionCall, Args[format_idx],
4680 PDiag(diag::warn_format_string_is_wide_literal), FExpr->
getLocStart(),
4681 true, OrigFormatExpr->getSourceRange());
4687 const char *Str = StrRef.data();
4690 assert(T &&
"String literal not of constant array type!");
4691 size_t TypeSize = T->
getSize().getZExtValue();
4692 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
4693 const unsigned numDataArgs = Args.size() - firstDataArg;
4697 if (TypeSize <= StrRef.size() &&
4698 StrRef.substr(0, TypeSize).find(
'\0') == StringRef::npos) {
4699 CheckFormatHandler::EmitFormatDiagnostic(
4700 *
this, inFunctionCall, Args[format_idx],
4701 PDiag(diag::warn_printf_format_string_not_null_terminated),
4703 true, OrigFormatExpr->getSourceRange());
4708 if (StrLen == 0 && numDataArgs > 0) {
4709 CheckFormatHandler::EmitFormatDiagnostic(
4710 *
this, inFunctionCall, Args[format_idx],
4711 PDiag(diag::warn_empty_format_string), FExpr->
getLocStart(),
4712 true, OrigFormatExpr->getSourceRange());
4716 if (Type == FST_Printf || Type == FST_NSString ||
4717 Type == FST_FreeBSDKPrintf || Type == FST_OSTrace) {
4718 CheckPrintfHandler H(*
this, FExpr, OrigFormatExpr, firstDataArg,
4719 numDataArgs, (Type == FST_NSString || Type == FST_OSTrace),
4720 Str, HasVAListArg, Args, format_idx,
4721 inFunctionCall, CallType, CheckedVarArgs);
4726 Type == FST_FreeBSDKPrintf))
4728 }
else if (Type == FST_Scanf) {
4729 CheckScanfHandler H(*
this, FExpr, OrigFormatExpr, firstDataArg, numDataArgs,
4730 Str, HasVAListArg, Args, format_idx,
4731 inFunctionCall, CallType, CheckedVarArgs);
4743 const char *Str = StrRef.data();
4746 assert(T &&
"String literal not of constant array type!");
4747 size_t TypeSize = T->
getSize().getZExtValue();
4748 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
4759 switch (AbsFunction) {
4763 case Builtin::BI__builtin_abs:
4764 return Builtin::BI__builtin_labs;
4765 case Builtin::BI__builtin_labs:
4766 return Builtin::BI__builtin_llabs;
4767 case Builtin::BI__builtin_llabs:
4770 case Builtin::BI__builtin_fabsf:
4771 return Builtin::BI__builtin_fabs;
4772 case Builtin::BI__builtin_fabs:
4773 return Builtin::BI__builtin_fabsl;
4774 case Builtin::BI__builtin_fabsl:
4777 case Builtin::BI__builtin_cabsf:
4778 return Builtin::BI__builtin_cabs;
4779 case Builtin::BI__builtin_cabs:
4780 return Builtin::BI__builtin_cabsl;
4781 case Builtin::BI__builtin_cabsl:
4784 case Builtin::BIabs:
4785 return Builtin::BIlabs;
4786 case Builtin::BIlabs:
4787 return Builtin::BIllabs;
4788 case Builtin::BIllabs:
4791 case Builtin::BIfabsf:
4792 return Builtin::BIfabs;
4793 case Builtin::BIfabs:
4794 return Builtin::BIfabsl;
4795 case Builtin::BIfabsl:
4798 case Builtin::BIcabsf:
4799 return Builtin::BIcabs;
4800 case Builtin::BIcabs:
4801 return Builtin::BIcabsl;
4802 case Builtin::BIcabsl:
4831 unsigned AbsFunctionKind) {
4832 unsigned BestKind = 0;
4834 for (
unsigned Kind = AbsFunctionKind;
Kind != 0;
4840 else if (Context.
hasSameType(ParamType, ArgType)) {
4863 llvm_unreachable(
"Type not integer, floating, or complex");
4870 switch (ValueKind) {
4875 case Builtin::BI__builtin_fabsf:
4876 case Builtin::BI__builtin_fabs:
4877 case Builtin::BI__builtin_fabsl:
4878 case Builtin::BI__builtin_cabsf:
4879 case Builtin::BI__builtin_cabs:
4880 case Builtin::BI__builtin_cabsl:
4881 return Builtin::BI__builtin_abs;
4882 case Builtin::BIfabsf:
4883 case Builtin::BIfabs:
4884 case Builtin::BIfabsl:
4885 case Builtin::BIcabsf:
4886 case Builtin::BIcabs:
4887 case Builtin::BIcabsl:
4888 return Builtin::BIabs;
4894 case Builtin::BI__builtin_abs:
4895 case Builtin::BI__builtin_labs:
4896 case Builtin::BI__builtin_llabs:
4897 case Builtin::BI__builtin_cabsf:
4898 case Builtin::BI__builtin_cabs:
4899 case Builtin::BI__builtin_cabsl:
4900 return Builtin::BI__builtin_fabsf;
4901 case Builtin::BIabs:
4902 case Builtin::BIlabs:
4903 case Builtin::BIllabs:
4904 case Builtin::BIcabsf:
4905 case Builtin::BIcabs:
4906 case Builtin::BIcabsl:
4907 return Builtin::BIfabsf;
4913 case Builtin::BI__builtin_abs:
4914 case Builtin::BI__builtin_labs:
4915 case Builtin::BI__builtin_llabs:
4916 case Builtin::BI__builtin_fabsf:
4917 case Builtin::BI__builtin_fabs:
4918 case Builtin::BI__builtin_fabsl:
4919 return Builtin::BI__builtin_cabsf;
4920 case Builtin::BIabs:
4921 case Builtin::BIlabs:
4922 case Builtin::BIllabs:
4923 case Builtin::BIfabsf:
4924 case Builtin::BIfabs:
4925 case Builtin::BIfabsl:
4926 return Builtin::BIcabsf;
4929 llvm_unreachable(
"Unable to convert function");
4940 case Builtin::BI__builtin_abs:
4941 case Builtin::BI__builtin_fabs:
4942 case Builtin::BI__builtin_fabsf:
4943 case Builtin::BI__builtin_fabsl:
4944 case Builtin::BI__builtin_labs:
4945 case Builtin::BI__builtin_llabs:
4946 case Builtin::BI__builtin_cabs:
4947 case Builtin::BI__builtin_cabsf:
4948 case Builtin::BI__builtin_cabsl:
4949 case Builtin::BIabs:
4950 case Builtin::BIlabs:
4951 case Builtin::BIllabs:
4952 case Builtin::BIfabs:
4953 case Builtin::BIfabsf:
4954 case Builtin::BIfabsl:
4955 case Builtin::BIcabs:
4956 case Builtin::BIcabsf:
4957 case Builtin::BIcabsl:
4960 llvm_unreachable(
"Unknown Builtin type");
4966 unsigned AbsKind,
QualType ArgType) {
4967 bool EmitHeaderHint =
true;
4968 const char *HeaderName =
nullptr;
4969 const char *FunctionName =
nullptr;
4971 FunctionName =
"std::abs";
4973 HeaderName =
"cstdlib";
4975 HeaderName =
"cmath";
4977 llvm_unreachable(
"Invalid Type");
4983 R.suppressDiagnostics();
4986 for (
const auto *
I : R) {
4989 FDecl = dyn_cast<
FunctionDecl>(UsingD->getTargetDecl());
5006 EmitHeaderHint =
false;
5018 R.suppressDiagnostics();
5021 if (R.isSingleResult()) {
5024 EmitHeaderHint =
false;
5028 }
else if (!R.empty()) {
5034 S.
Diag(Loc, diag::note_replace_abs_function)
5040 if (!EmitHeaderHint)
5043 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
5070 void Sema::CheckAbsoluteValueFunction(
const CallExpr *Call,
5078 if (AbsKind == 0 && !IsStdAbs)
5087 const char *FunctionName =
5089 Diag(Call->
getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
5092 << FixItHint::CreateRemoval(Call->
getCallee()->getSourceRange());
5099 unsigned DiagType = 0;
5105 Diag(Call->
getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
5119 if (ArgValueKind == ParamValueKind) {
5125 << FDecl << ArgType << ParamType;
5127 if (NewAbsKind == 0)
5131 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
5140 if (NewAbsKind == 0)
5144 << FDecl << ParamValueKind << ArgValueKind;
5147 Call->
getCallee()->getSourceRange(), NewAbsKind, ArgType);
5171 << SizeRange << FnName;
5172 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
5176 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
5187 bool &IsContained) {
5190 IsContained =
false;
5203 for (
auto *FD : RD->
fields()) {
5219 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5229 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
5231 return SizeOf->getTypeOfArgument();
5243 void Sema::CheckMemaccessArguments(
const CallExpr *Call,
5250 unsigned ExpectedNumArgs = (BId == Builtin::BIstrndup ? 2 : 3);
5254 unsigned LastArg = (BId == Builtin::BImemset ||
5255 BId == Builtin::BIstrndup ? 1 : 2);
5256 unsigned LenArg = (BId == Builtin::BIstrndup ? 1 : 2);
5266 llvm::FoldingSetNodeID SizeOfArgID;
5268 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
5287 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
5291 if (SizeOfArgID == llvm::FoldingSetNodeID())
5292 SizeOfArg->Profile(SizeOfArgID, Context,
true);
5293 llvm::FoldingSetNodeID DestID;
5294 Dest->Profile(DestID, Context,
true);
5295 if (DestID == SizeOfArgID) {
5298 unsigned ActionIdx = 0;
5299 StringRef ReadableName = FnName->
getName();
5301 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
5325 DiagRuntimeBehavior(SL, SizeOfArg,
5326 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
5332 DiagRuntimeBehavior(SL, SizeOfArg,
5333 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
5347 DiagRuntimeBehavior(LenExpr->
getExprLoc(), Dest,
5348 PDiag(diag::warn_sizeof_pointer_type_memaccess)
5349 << FnName << SizeOfArgTy << ArgIdx
5350 << PointeeTy << Dest->getSourceRange()
5351 << LenExpr->getSourceRange());
5367 unsigned OperationType = 0;
5370 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
5371 if (BId == Builtin::BImemcpy)
5373 else if(BId == Builtin::BImemmove)
5375 else if (BId == Builtin::BImemcmp)
5379 DiagRuntimeBehavior(
5381 PDiag(diag::warn_dyn_class_memaccess)
5382 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
5383 << FnName << IsContained << ContainedRD << OperationType
5384 << Call->
getCallee()->getSourceRange());
5386 BId != Builtin::BImemset)
5387 DiagRuntimeBehavior(
5389 PDiag(diag::warn_arc_object_memaccess)
5390 << ArgIdx << FnName << PointeeTy
5391 << Call->
getCallee()->getSourceRange());
5395 DiagRuntimeBehavior(
5397 PDiag(diag::note_bad_memaccess_silence)
5418 if (isa<IntegerLiteral>(RHS))
5420 else if (isa<IntegerLiteral>(LHS))
5434 if (CAT->getSize().getSExtValue() <= 1)
5444 void Sema::CheckStrlcpycatArguments(
const CallExpr *Call,
5449 if ((NumArgs != 3) && (NumArgs != 4))
5454 const Expr *CompareWithSrc =
nullptr;
5462 CompareWithSrc = Ex;
5465 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
5466 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
5467 SizeCall->getNumArgs() == 1)
5472 if (!CompareWithSrc)
5484 if (!CompareWithSrcDRE ||
5488 const Expr *OriginalSizeArg = Call->
getArg(2);
5489 Diag(CompareWithSrcDRE->
getLocStart(), diag::warn_strlcpycat_wrong_size)
5490 << OriginalSizeArg->getSourceRange() << FnName;
5501 llvm::raw_svector_ostream OS(sizeString);
5503 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5506 Diag(OriginalSizeArg->getLocStart(), diag::note_strlcpycat_wrong_size)
5513 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
5514 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
5515 return D1->getDecl() == D2->getDecl();
5520 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
5524 return CE->getArg(0)->IgnoreParenCasts();
5532 void Sema::CheckStrncatArguments(
const CallExpr *CE,
5547 unsigned PatternType = 0;
5555 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
5556 if (BE->getOpcode() ==
BO_Sub) {
5558 const Expr *R = BE->getRHS()->IgnoreParenCasts();
5569 if (PatternType == 0)
5588 if (!isKnownSizeArray) {
5589 if (PatternType == 1)
5590 Diag(SL, diag::warn_strncat_wrong_size) << SR;
5592 Diag(SL, diag::warn_strncat_src_size) << SR;
5596 if (PatternType == 1)
5597 Diag(SL, diag::warn_strncat_large_size) << SR;
5599 Diag(SL, diag::warn_strncat_src_size) << SR;
5602 llvm::raw_svector_ostream OS(sizeString);
5604 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5607 DstArg->printPretty(OS,
nullptr, getPrintingPolicy());
5610 Diag(SL, diag::note_strncat_wrong_size)
5616 static Expr *
EvalVal(
Expr *E, SmallVectorImpl<DeclRefExpr *> &refVars,
5627 Expr *stackE =
nullptr;
5634 stackE =
EvalAddr(RetValExp, refVars,
nullptr);
5636 stackE =
EvalVal(RetValExp, refVars,
nullptr);
5644 if (refVars.empty()) {
5645 diagLoc = stackE->getLocStart();
5646 diagRange = stackE->getSourceRange();
5652 diagLoc = refVars[0]->getLocStart();
5653 diagRange = refVars[0]->getSourceRange();
5656 if (
DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
5658 << DR->getDecl()->getDeclName() << diagRange;
5659 }
else if (isa<BlockExpr>(stackE)) {
5660 S.
Diag(diagLoc, diag::err_ret_local_block) << diagRange;
5661 }
else if (isa<AddrLabelExpr>(stackE)) {
5662 S.
Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
5664 S.
Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
5670 for (
unsigned i = 0, e = refVars.size(); i != e; ++i) {
5671 VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
5675 SourceRange range = (i < e-1) ? refVars[i+1]->getSourceRange()
5676 : stackE->getSourceRange();
5717 "EvalAddr only works on pointers");
5724 switch (E->getStmtClass()) {
5725 case Stmt::DeclRefExprClass: {
5735 if (V->hasLocalStorage() &&
5736 V->getType()->isReferenceType() && V->hasInit()) {
5738 refVars.push_back(DR);
5739 return EvalAddr(V->getInit(), refVars, ParentDecl);
5745 case Stmt::UnaryOperatorClass: {
5756 case Stmt::BinaryOperatorClass: {
5772 return EvalAddr(Base, refVars, ParentDecl);
5777 case Stmt::ConditionalOperatorClass: {
5784 if (!LHSExpr->getType()->isVoidType())
5785 if (
Expr *LHS =
EvalAddr(LHSExpr, refVars, ParentDecl))
5796 case Stmt::BlockExprClass:
5797 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
5801 case Stmt::AddrLabelExprClass:
5804 case Stmt::ExprWithCleanupsClass:
5805 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
5810 case Stmt::ImplicitCastExprClass:
5811 case Stmt::CStyleCastExprClass:
5812 case Stmt::CXXFunctionalCastExprClass:
5813 case Stmt::ObjCBridgedCastExprClass:
5814 case Stmt::CXXStaticCastExprClass:
5815 case Stmt::CXXDynamicCastExprClass:
5816 case Stmt::CXXConstCastExprClass:
5817 case Stmt::CXXReinterpretCastExprClass: {
5818 Expr* SubExpr = cast<CastExpr>(
E)->getSubExpr();
5819 switch (cast<CastExpr>(E)->getCastKind()) {
5829 return EvalAddr(SubExpr, refVars, ParentDecl);
5832 return EvalVal(SubExpr, refVars, ParentDecl);
5838 return EvalAddr(SubExpr, refVars, ParentDecl);
5847 case Stmt::MaterializeTemporaryExprClass:
5849 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5850 refVars, ParentDecl))
5876 switch (E->getStmtClass()) {
5877 case Stmt::ImplicitCastExprClass: {
5886 case Stmt::ExprWithCleanupsClass:
5887 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,ParentDecl);
5889 case Stmt::DeclRefExprClass: {
5901 if (V == ParentDecl)
5904 if (V->hasLocalStorage()) {
5905 if (!V->getType()->isReferenceType())
5912 refVars.push_back(DR);
5913 return EvalVal(V->getInit(), refVars, V);
5921 case Stmt::UnaryOperatorClass: {
5933 case Stmt::ArraySubscriptExprClass: {
5937 return EvalAddr(cast<ArraySubscriptExpr>(E)->getBase(), refVars,ParentDecl);
5940 case Stmt::OMPArraySectionExprClass: {
5941 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
5945 case Stmt::ConditionalOperatorClass: {
5953 if (!LHSExpr->getType()->isVoidType())
5954 if (
Expr *LHS =
EvalVal(LHSExpr, refVars, ParentDecl))
5966 case Stmt::MemberExprClass: {
5981 case Stmt::MaterializeTemporaryExprClass:
5983 cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
5984 refVars, ParentDecl))
6002 Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
6010 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
6013 Diag(ReturnLoc, diag::warn_null_ret)
6014 << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
6023 if (Op == OO_New || Op == OO_Array_New) {
6028 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
6029 << FD << getLangOpts().CPlusPlus11;
6045 if (
DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
6046 if (
DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
6047 if (DRL->getDecl() == DRR->getDecl())
6056 if (
FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
6060 if (
FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
6065 if (
CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
6066 if (CL->getBuiltinCallee())
6069 if (
CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
6070 if (CR->getBuiltinCallee())
6074 Diag(Loc, diag::warn_floatingpoint_eq)
6075 << LHS->getSourceRange() << RHS->getSourceRange();
6092 IntRange(
unsigned Width,
bool NonNegative)
6093 : Width(Width), NonNegative(NonNegative)
6097 static IntRange forBoolType() {
6098 return IntRange(1,
true);
6103 return forValueOfCanonicalType(C,
6108 static IntRange forValueOfCanonicalType(
ASTContext &C,
const Type *T) {
6111 if (
const VectorType *VT = dyn_cast<VectorType>(T))
6112 T = VT->getElementType().getTypePtr();
6113 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
6114 T = CT->getElementType().getTypePtr();
6115 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
6116 T = AT->getValueType().getTypePtr();
6119 if (
const EnumType *ET = dyn_cast<EnumType>(T)) {
6127 if (NumNegative == 0)
6128 return IntRange(NumPositive,
true);
6130 return IntRange(std::max(NumPositive + 1, NumNegative),
6145 static IntRange forTargetOfCanonicalType(
ASTContext &C,
const Type *T) {
6148 if (
const VectorType *VT = dyn_cast<VectorType>(T))
6149 T = VT->getElementType().getTypePtr();
6150 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
6151 T = CT->getElementType().getTypePtr();
6152 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
6153 T = AT->getValueType().getTypePtr();
6154 if (
const EnumType *ET = dyn_cast<EnumType>(T))
6164 static IntRange join(IntRange L, IntRange R) {
6165 return IntRange(std::max(L.Width, R.Width),
6166 L.NonNegative && R.NonNegative);
6170 static IntRange meet(IntRange L, IntRange R) {
6171 return IntRange(std::min(L.Width, R.Width),
6172 L.NonNegative || R.NonNegative);
6176 static IntRange GetValueRange(
ASTContext &C, llvm::APSInt &value,
6177 unsigned MaxWidth) {
6178 if (value.isSigned() && value.isNegative())
6179 return IntRange(value.getMinSignedBits(),
false);
6181 if (value.getBitWidth() > MaxWidth)
6182 value = value.trunc(MaxWidth);
6186 return IntRange(value.getActiveBits(),
true);
6190 unsigned MaxWidth) {
6192 return GetValueRange(C, result.
getInt(), MaxWidth);
6195 IntRange R = GetValueRange(C, result.
getVectorElt(0), Ty, MaxWidth);
6197 IntRange El = GetValueRange(C, result.
getVectorElt(i), Ty, MaxWidth);
6198 R = IntRange::join(R, El);
6206 return IntRange::join(R, I);
6221 Ty = AtomicRHS->getValueType();
6229 static IntRange GetExprRange(
ASTContext &C,
Expr *E,
unsigned MaxWidth) {
6235 return GetValueRange(C, result.
Val, GetExprType(E), MaxWidth);
6242 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
6244 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
6251 return OutputTypeRange;
6254 = GetExprRange(C, CE->getSubExpr(),
6255 std::min(MaxWidth, OutputTypeRange.Width));
6258 if (SubRange.Width >= OutputTypeRange.Width)
6259 return OutputTypeRange;
6263 return IntRange(SubRange.Width,
6264 SubRange.NonNegative || OutputTypeRange.NonNegative);
6270 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
6271 return GetExprRange(C, CondResult ? CO->getTrueExpr()
6272 : CO->getFalseExpr(),
6276 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
6277 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
6278 return IntRange::join(L, R);
6282 switch (BO->getOpcode()) {
6293 return IntRange::forBoolType();
6305 return IntRange::forValueOfType(C, GetExprType(E));
6311 return GetExprRange(C, BO->getRHS(), MaxWidth);
6316 return IntRange::forValueOfType(C, GetExprType(E));
6321 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
6322 GetExprRange(C, BO->getRHS(), MaxWidth));
6329 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
6330 if (I->getValue() == 1) {
6331 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
6332 return IntRange(R.Width,
true);
6338 return IntRange::forValueOfType(C, GetExprType(E));
6343 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6348 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
6349 shift.isNonNegative()) {
6350 unsigned zext = shift.getZExtValue();
6351 if (zext >= L.Width)
6352 L.Width = (L.NonNegative ? 0 : 1);
6362 return GetExprRange(C, BO->getRHS(), MaxWidth);
6366 if (BO->getLHS()->getType()->isPointerType())
6367 return IntRange::forValueOfType(C, GetExprType(E));
6375 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6378 llvm::APSInt divisor;
6379 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
6380 unsigned log2 = divisor.logBase2();
6381 if (log2 >= L.Width)
6382 L.Width = (L.NonNegative ? 0 : 1);
6384 L.Width = std::min(L.Width - log2, MaxWidth);
6389 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6390 return IntRange(L.Width, L.NonNegative && R.NonNegative);
6398 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
6399 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
6401 IntRange meet = IntRange::meet(L, R);
6402 meet.Width = std::min(meet.Width, MaxWidth);
6416 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
6417 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
6418 return IntRange::join(L, R);
6422 switch (UO->getOpcode()) {
6425 return IntRange::forBoolType();
6430 return IntRange::forValueOfType(C, GetExprType(E));
6433 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
6438 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
6441 return IntRange(BitField->getBitWidthValue(C),
6442 BitField->getType()->isUnsignedIntegerOrEnumerationType());
6444 return IntRange::forValueOfType(C, GetExprType(E));
6448 return GetExprRange(C, E, C.
getIntWidth(GetExprType(E)));
6454 static bool IsSameFloatAfterCast(
const llvm::APFloat &value,
6455 const llvm::fltSemantics &Src,
6456 const llvm::fltSemantics &Tgt) {
6457 llvm::APFloat truncated = value;
6460 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
6461 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
6463 return truncated.bitwiseIsEqual(value);
6471 static bool IsSameFloatAfterCast(
const APValue &value,
6472 const llvm::fltSemantics &Src,
6473 const llvm::fltSemantics &Tgt) {
6475 return IsSameFloatAfterCast(value.
getFloat(), Src, Tgt);
6479 if (!IsSameFloatAfterCast(value.
getVectorElt(i), Src, Tgt))
6491 static bool IsZero(
Sema &S,
Expr *E) {
6495 if (isa<EnumConstantDecl>(DR->getDecl()))
6499 if (E->getLocStart().isMacroID())
6506 static bool HasEnumType(
Expr *E) {
6510 ICE->getCastKind() !=
CK_NoOp)
6512 E = ICE->getSubExpr();
6529 <<
"< 0" <<
"false" << HasEnumType(E->
getLHS())
6530 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6531 }
else if (op ==
BO_GE && IsZero(S, E->
getRHS())) {
6533 <<
">= 0" <<
"true" << HasEnumType(E->
getLHS())
6534 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6535 }
else if (op ==
BO_GT && IsZero(S, E->
getLHS())) {
6537 <<
"0 >" <<
"false" << HasEnumType(E->
getRHS())
6538 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6539 }
else if (op ==
BO_LE && IsZero(S, E->
getLHS())) {
6541 <<
"0 <=" <<
"true" << HasEnumType(E->
getRHS())
6542 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange();
6558 OtherT = AT->getValueType();
6559 IntRange OtherRange = IntRange::forValueOfType(S.
Context, OtherT);
6560 unsigned OtherWidth = OtherRange.Width;
6565 if ((Value == 0) && (!OtherIsBooleanType))
6573 LiteralConstant = 0,
6576 } LiteralOrBoolConstant = LiteralConstant;
6578 if (!OtherIsBooleanType) {
6585 "comparison with non-integer type");
6590 bool EqualityOnly =
false;
6594 if (!OtherRange.NonNegative) {
6596 if (ConstantSigned) {
6597 if (OtherWidth >= Value.getMinSignedBits())
6600 if (OtherWidth >= Value.getActiveBits() + 1)
6606 if (ConstantSigned) {
6607 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
6610 if (OtherWidth >= Value.getActiveBits())
6615 if (OtherRange.NonNegative) {
6616 if (OtherWidth >= Value.getActiveBits())
6619 assert(!ConstantSigned &&
6620 "Two signed types converted to unsigned types.");
6622 if (OtherWidth > Value.getActiveBits())
6628 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
6633 EqualityOnly =
true;
6637 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
6640 IsTrue = op ==
BO_NE;
6641 }
else if (EqualityOnly) {
6643 }
else if (RhsConstant) {
6645 IsTrue = !PositiveConstant;
6647 IsTrue = PositiveConstant;
6650 IsTrue = !PositiveConstant;
6652 IsTrue = PositiveConstant;
6656 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
6657 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
6658 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
6660 static const struct LinkedConditions {
6661 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
6662 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
6663 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
6664 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
6665 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
6666 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
6671 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
6672 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
6673 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
6674 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
6675 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
6676 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
6679 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
6681 enum ConstantValue ConstVal = Zero;
6682 if (Value.isUnsigned() || Value.isNonNegative()) {
6684 LiteralOrBoolConstant =
6685 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
6687 }
else if (Value == 1) {
6688 LiteralOrBoolConstant =
6689 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
6692 LiteralOrBoolConstant = LiteralConstant;
6699 CompareBoolWithConstantResult CmpRes;
6703 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
6706 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
6709 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
6712 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
6715 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
6718 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
6725 if (CmpRes == AFals) {
6727 }
else if (CmpRes == ATrue) {
6737 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
6738 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
6741 llvm::raw_svector_ostream OS(PrettySourceValue);
6743 OS <<
'\'' << *ED <<
"' (" << Value <<
")";
6749 S.
PDiag(diag::warn_out_of_range_compare)
6750 << OS.str() << LiteralOrBoolConstant
6751 << OtherT << (OtherIsBooleanType && !OtherT->
isBooleanType()) << IsTrue
6752 << E->
getLHS()->getSourceRange() << E->
getRHS()->getSourceRange());
6772 return AnalyzeImpConvsInComparison(S, E);
6776 return AnalyzeImpConvsInComparison(S, E);
6781 bool IsComparisonConstant =
false;
6786 llvm::APSInt RHSValue;
6787 bool IsRHSIntegralLiteral =
6789 llvm::APSInt LHSValue;
6790 bool IsLHSIntegralLiteral =
6792 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
6793 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue,
true);
6794 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
6795 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue,
false);
6797 IsComparisonConstant =
6798 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
6809 return AnalyzeImpConvsInComparison(S, E);
6813 Expr *signedOperand, *unsignedOperand;
6816 "unsigned comparison between two signed integer expressions?");
6817 signedOperand = LHS;
6818 unsignedOperand = RHS;
6820 signedOperand = RHS;
6821 unsignedOperand = LHS;
6823 CheckTrivialUnsignedComparison(S, E);
6824 return AnalyzeImpConvsInComparison(S, E);
6828 IntRange signedRange = GetExprRange(S.
Context, signedOperand);
6838 if (signedRange.NonNegative)
6839 return CheckTrivialUnsignedComparison(S, E);
6847 IntRange unsignedRange = GetExprRange(S.
Context, unsignedOperand);
6851 assert(unsignedRange.NonNegative &&
"unsigned range includes negative?");
6853 if (unsignedRange.Width < comparisonWidth)
6858 S.
PDiag(diag::warn_mixed_sign_comparison)
6860 << LHS->getSourceRange() << RHS->getSourceRange());
6889 unsigned OriginalWidth = Value.getBitWidth();
6892 if (OriginalWidth <= FieldWidth)
6896 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
6900 TruncatedValue = TruncatedValue.extend(OriginalWidth);
6901 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
6906 if (FieldWidth == 1 && Value == 1)
6909 std::string PrettyValue = Value.toString(10);
6910 std::string PrettyTrunc = TruncatedValue.toString(10);
6912 S.
Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
6913 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
6914 << Init->getSourceRange();
6928 if (AnalyzeBitFieldAssignment(S, Bitfield, E->
getRHS(),
6942 bool pruneControlFlow =
false) {
6943 if (pruneControlFlow) {
6946 << SourceType << T << E->getSourceRange()
6951 << SourceType << T << E->getSourceRange() <<
SourceRange(CContext);
6957 bool pruneControlFlow =
false) {
6958 DiagnoseImpCast(S, E, E->
getType(), T, CContext, diag, pruneControlFlow);
6966 bool isExact =
false;
6967 const llvm::APFloat &Value = FL->
getValue();
6970 if (Value.convertToInteger(IntegerValue,
6971 llvm::APFloat::rmTowardZero, &isExact)
6972 == llvm::APFloat::opOK && isExact)
6981 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
6982 precision = (precision * 59 + 195) / 196;
6983 Value.toString(PrettySourceValue, precision);
6987 PrettyTargetValue = Value.isZero() ?
"false" :
"true";
6989 IntegerValue.toString(PrettyTargetValue);
6991 S.
Diag(FL->
getExprLoc(), diag::warn_impcast_literal_float_to_integer)
6993 << PrettyTargetValue << FL->getSourceRange() <<
SourceRange(CContext);
6996 std::string PrettyPrintInRange(
const llvm::APSInt &Value, IntRange Range) {
6997 if (!Range.Width)
return "0";
6999 llvm::APSInt ValueInRange =
Value;
7000 ValueInRange.setIsSigned(!Range.NonNegative);
7001 ValueInRange = ValueInRange.trunc(Range.Width);
7002 return ValueInRange.toString(10);
7005 static bool IsImplicitBoolFloatConversion(
Sema &S,
Expr *Ex,
bool ToBool) {
7006 if (!isa<ImplicitCastExpr>(Ex))
7011 const Type *Source =
7018 const Type *BoolCandidateType = ToBool ? Target : Source;
7020 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
7024 void CheckImplicitArgumentConversions(
Sema &S,
CallExpr *TheCall,
7027 for (
unsigned i = 0; i <
NumArgs; ++i) {
7029 if (!IsImplicitBoolFloatConversion(S, CurrA,
true))
7032 bool IsSwapped = ((i > 0) &&
7033 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i - 1),
false));
7034 IsSwapped |= ((i < (NumArgs - 1)) &&
7035 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i + 1),
false));
7040 diag::warn_impcast_floating_point_to_bool);
7047 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
7052 if (isa<CallExpr>(E))
7071 StringRef MacroName =
7073 if (MacroName ==
"NULL")
7082 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
7088 static void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
7090 static void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
7095 static void checkObjCCollectionLiteralElement(
Sema &S,
7098 unsigned ElementKind) {
7100 if (
auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
7103 Element = ICE->getSubExpr();
7113 S.
Diag(Element->getLocStart(),
7114 diag::warn_objc_collection_literal_element)
7115 << ElementType << ElementKind << TargetElementType
7116 << Element->getSourceRange();
7119 if (
auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
7120 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
7121 else if (
auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
7122 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
7127 static void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
7136 if (TargetObjCPtr->isUnspecialized() ||
7137 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7142 if (TypeArgs.size() != 1)
7145 QualType TargetElementType = TypeArgs[0];
7146 for (
unsigned I = 0, N = ArrayLiteral->
getNumElements(); I != N; ++
I) {
7147 checkObjCCollectionLiteralElement(S, TargetElementType,
7155 static void checkObjCDictionaryLiteral(
7165 if (TargetObjCPtr->isUnspecialized() ||
7166 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
7171 if (TypeArgs.size() != 2)
7174 QualType TargetKeyType = TypeArgs[0];
7175 QualType TargetObjectType = TypeArgs[1];
7176 for (
unsigned I = 0, N = DictionaryLiteral->
getNumElements(); I != N; ++
I) {
7178 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
7179 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
7189 if (Source == Target)
return;
7202 if (isa<StringLiteral>(E))
7206 return DiagnoseImpCast(S, E, T, CC,
7207 diag::warn_impcast_string_literal_to_bool);
7208 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(
E) ||
7209 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(
E)) {
7212 return DiagnoseImpCast(S, E, T, CC,
7213 diag::warn_impcast_objective_c_literal_to_bool);
7224 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
7225 checkObjCArrayLiteral(S,
QualType(Target, 0), ArrayLiteral);
7226 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
7227 checkObjCDictionaryLiteral(S,
QualType(Target, 0), DictionaryLiteral);
7230 if (isa<VectorType>(Source)) {
7231 if (!isa<VectorType>(Target)) {
7234 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
7242 Source = cast<VectorType>(Source)->
getElementType().getTypePtr();
7243 Target = cast<VectorType>(Target)->
getElementType().getTypePtr();
7245 if (
auto VecTy = dyn_cast<VectorType>(Target))
7246 Target = VecTy->getElementType().getTypePtr();
7249 if (isa<ComplexType>(Source)) {
7250 if (!isa<ComplexType>(Target)) {
7254 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
7257 Source = cast<ComplexType>(Source)->
getElementType().getTypePtr();
7258 Target = cast<ComplexType>(Target)->
getElementType().getTypePtr();
7267 if (TargetBT && TargetBT->isFloatingPoint()) {
7271 if (SourceBT->
getKind() > TargetBT->getKind()) {
7277 if (IsSameFloatAfterCast(result.
Val,
7286 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
7290 else if (TargetBT->getKind() > SourceBT->
getKind()) {
7294 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
7300 if (TargetBT && TargetBT->isInteger()) {
7311 DiagnoseFloatingLiteralImpCast(S, FL, T, CC);
7313 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_integer);
7333 if (isa<ImplicitCastExpr>(LastA) &&
7336 DiagnoseImpCast(S, E, T, CC,
7337 diag::warn_impcast_floating_point_to_bool);
7344 DiagnoseNullConversion(S, E, T, CC);
7355 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.
Context, Target);
7357 if (SourceRange.Width > TargetRange.Width) {
7360 llvm::APSInt
Value(32);
7365 std::string PrettySourceValue = Value.toString(10);
7366 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
7369 S.
PDiag(diag::warn_impcast_integer_precision_constant)
7370 << PrettySourceValue << PrettyTargetValue
7371 << E->
getType() << T << E->getSourceRange()
7381 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
7383 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
7386 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
7387 (!TargetRange.NonNegative && SourceRange.NonNegative &&
7388 SourceRange.Width == TargetRange.Width)) {
7393 unsigned DiagID = diag::warn_impcast_integer_sign;
7401 DiagID = diag::warn_impcast_integer_sign_conditional;
7405 return DiagnoseImpCast(S, E, T, CC, DiagID);
7415 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
7423 if (SourceEnum->getDecl()->hasNameForLinkage() &&
7424 TargetEnum->getDecl()->hasNameForLinkage() &&
7425 SourceEnum != TargetEnum) {
7429 return DiagnoseImpCast(S, E, SourceType, T, CC,
7430 diag::warn_impcast_different_enum_types);
7443 if (isa<ConditionalOperator>(E))
7444 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
7446 AnalyzeImplicitConversions(S, E, CC);
7448 return CheckImplicitConversion(S, E, T, CC, &ICContext);
7456 bool Suspicious =
false;
7457 CheckConditionalOperand(S, E->
getTrueExpr(), T, CC, Suspicious);
7458 CheckConditionalOperand(S, E->
getFalseExpr(), T, CC, Suspicious);
7462 if (!Suspicious)
return;
7465 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
7470 if (E->
getType() == T)
return;
7474 E->
getType(), CC, &Suspicious);
7477 E->
getType(), CC, &Suspicious);
7500 if (isa<ConditionalOperator>(E)) {
7502 CheckConditionalOperator(S, CO, CC, T);
7507 if (
CallExpr *Call = dyn_cast<CallExpr>(E))
7508 CheckImplicitArgumentConversions(S, Call, CC);
7514 CheckImplicitConversion(S, E, T, CC);
7522 for (
auto *SE : POE->semantics())
7523 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
7524 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
7528 if (isa<ExplicitCastExpr>(E)) {
7530 return AnalyzeImplicitConversions(S, E, CC);
7535 if (BO->isComparisonOp())
7536 return AnalyzeComparison(S, BO);
7540 return AnalyzeAssignment(S, BO);
7547 if (isa<StmtExpr>(E))
return;
7550 if (isa<UnaryExprOrTypeTraitExpr>(E))
return;
7556 for (
Stmt *SubStmt : E->children()) {
7557 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
7561 if (IsLogicalAndOperator &&
7566 AnalyzeImplicitConversions(S, ChildExpr, CC);
7571 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7572 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
7575 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
7576 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
7580 if (U->getOpcode() ==
UO_LNot)
7581 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
7594 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7597 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7598 if (!M->getMemberDecl()->getType()->isReferenceType())
7600 }
else if (
const CallExpr *Call = dyn_cast<CallExpr>(E)) {
7612 SemaRef.
Diag(FD->
getLocation(), diag::note_reference_is_return_value) << FD;
7642 bool IsEqual, SourceRange Range) {
7657 if (isa<CXXThisExpr>(E)) {
7658 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
7659 : diag::warn_this_bool_conversion;
7660 Diag(E->
getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
7664 bool IsAddressOf =
false;
7670 E = UO->getSubExpr();
7674 unsigned DiagID = IsCompare
7675 ? diag::warn_address_of_reference_null_compare
7676 : diag::warn_address_of_reference_bool_conversion;
7684 auto ComplainAboutNonnullParamOrCall = [&](
bool IsParam) {
7686 llvm::raw_string_ostream
S(Str);
7687 E->printPretty(S,
nullptr, getPrintingPolicy());
7688 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
7689 : diag::warn_cast_nonnull_to_bool;
7691 << E->getSourceRange() << Range << IsEqual;
7697 if (Callee->hasAttr<ReturnsNonNullAttr>()) {
7698 ComplainAboutNonnullParamOrCall(
false);
7708 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
7709 D = M->getMemberDecl();
7717 if (
const auto* PV = dyn_cast<ParmVarDecl>(D)) {
7718 if (getCurFunction() &&
7719 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
7720 if (PV->hasAttr<NonNullAttr>()) {
7721 ComplainAboutNonnullParamOrCall(
true);
7725 if (
const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
7728 unsigned ParamNo = std::distance(FD->
param_begin(), ParamIter);
7732 ComplainAboutNonnullParamOrCall(
true);
7736 for (
unsigned ArgNo :
NonNull->args()) {
7737 if (ArgNo == ParamNo) {
7738 ComplainAboutNonnullParamOrCall(
true);
7752 if (IsAddressOf && IsFunction) {
7757 if (!IsAddressOf && !IsFunction && !IsArray)
7762 llvm::raw_string_ostream
S(Str);
7763 E->printPretty(S,
nullptr, getPrintingPolicy());
7765 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
7766 : diag::warn_impcast_pointer_to_bool;
7773 DiagType = AddressOf;
7774 else if (IsFunction)
7775 DiagType = FunctionPointer;
7777 DiagType = ArrayPointer;
7779 llvm_unreachable(
"Could not determine diagnostic.");
7780 Diag(E->
getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
7781 << Range << IsEqual;
7793 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
7794 if (ReturnType.isNull())
7801 if (!ReturnType->isPointerType()) {
7804 if (!ReturnType->isIntegerType())
7813 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
7830 if (isUnevaluatedContext())
7840 CheckArrayAccess(E);
7843 AnalyzeImplicitConversions(*
this, E, CC);
7849 ::CheckBoolLikeConversion(*
this, E, CC);
7854 void Sema::CheckForIntOverflow (
Expr *E) {
7857 else if (
auto InitList = dyn_cast<InitListExpr>(E))
7858 for (
Expr *E : InitList->inits())
7874 class SequenceTree {
7876 explicit Value(
unsigned Parent) : Parent(Parent), Merged(
false) {}
7877 unsigned Parent : 31;
7886 explicit Seq(
unsigned N) : Index(N) {}
7888 friend class SequenceTree;
7893 SequenceTree() { Values.push_back(
Value(0)); }
7894 Seq root()
const {
return Seq(0); }
7899 Seq allocate(Seq Parent) {
7900 Values.push_back(
Value(Parent.Index));
7901 return Seq(Values.size() - 1);
7906 Values[S.Index].Merged =
true;
7912 bool isUnsequenced(Seq Cur, Seq Old) {
7913 unsigned C = representative(Cur.Index);
7914 unsigned Target = representative(Old.Index);
7915 while (C >= Target) {
7918 C = Values[
C].Parent;
7925 unsigned representative(
unsigned K) {
7926 if (Values[K].Merged)
7928 return Values[K].Parent = representative(Values[K].Parent);
7948 UK_Count = UK_ModAsSideEffect + 1
7952 Usage() : Use(nullptr), Seq() {}
7954 SequenceTree::Seq Seq;
7958 UsageInfo() : Diagnosed(
false) {}
7959 Usage Uses[UK_Count];
7963 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
7969 UsageInfoMap UsageMap;
7971 SequenceTree::Seq Region;
7974 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
7977 SmallVectorImpl<Expr *> &WorkList;
7984 struct SequencedSubexpression {
7985 SequencedSubexpression(SequenceChecker &Self)
7986 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
7987 Self.ModAsSideEffect = &ModAsSideEffect;
7989 ~SequencedSubexpression() {
7990 for (
auto MI = ModAsSideEffect.rbegin(), ME = ModAsSideEffect.rend();
7992 UsageInfo &U = Self.UsageMap[MI->first];
7993 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
7994 Self.addUsage(U, MI->first, SideEffectUsage.Use, UK_ModAsValue);
7995 SideEffectUsage = MI->second;
7997 Self.ModAsSideEffect = OldModAsSideEffect;
8000 SequenceChecker &Self;
8002 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
8009 class EvaluationTracker {
8011 EvaluationTracker(SequenceChecker &Self)
8012 : Self(Self), Prev(Self.EvalTracker), EvalOK(
true) {
8013 Self.EvalTracker =
this;
8015 ~EvaluationTracker() {
8016 Self.EvalTracker = Prev;
8018 Prev->EvalOK &= EvalOK;
8021 bool evaluate(
const Expr *E,
bool &Result) {
8029 SequenceChecker &Self;
8030 EvaluationTracker *Prev;
8036 Object getObject(
Expr *E,
bool Mod)
const {
8040 return getObject(UO->getSubExpr(), Mod);
8043 return getObject(BO->
getRHS(), Mod);
8045 return getObject(BO->
getLHS(), Mod);
8046 }
else if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
8048 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
8049 return ME->getMemberDecl();
8050 }
else if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8057 void addUsage(UsageInfo &UI, Object O,
Expr *Ref, UsageKind UK) {
8058 Usage &U = UI.Uses[UK];
8059 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
8060 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
8061 ModAsSideEffect->push_back(std::make_pair(O, U));
8067 void checkUsage(Object O, UsageInfo &UI,
Expr *Ref, UsageKind OtherKind,
8072 const Usage &U = UI.Uses[OtherKind];
8073 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
8077 Expr *ModOrUse = Ref;
8078 if (OtherKind == UK_Use)
8079 std::swap(Mod, ModOrUse);
8082 IsModMod ? diag::warn_unsequenced_mod_mod
8083 : diag::warn_unsequenced_mod_use)
8085 UI.Diagnosed =
true;
8088 void notePreUse(Object O,
Expr *Use) {
8089 UsageInfo &U = UsageMap[O];
8091 checkUsage(O, U, Use, UK_ModAsValue,
false);
8093 void notePostUse(Object O,
Expr *Use) {
8094 UsageInfo &U = UsageMap[O];
8095 checkUsage(O, U, Use, UK_ModAsSideEffect,
false);
8096 addUsage(U, O, Use, UK_Use);
8099 void notePreMod(Object O,
Expr *Mod) {
8100 UsageInfo &U = UsageMap[O];
8102 checkUsage(O, U, Mod, UK_ModAsValue,
true);
8103 checkUsage(O, U, Mod, UK_Use,
false);
8105 void notePostMod(Object O,
Expr *Use, UsageKind UK) {
8106 UsageInfo &U = UsageMap[O];
8107 checkUsage(O, U, Use, UK_ModAsSideEffect,
true);
8108 addUsage(U, O, Use, UK);
8112 SequenceChecker(
Sema &S,
Expr *E, SmallVectorImpl<Expr *> &WorkList)
8113 :
Base(S.Context), SemaRef(S), Region(Tree.root()),
8114 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
8118 void VisitStmt(
Stmt *S) {
8122 void VisitExpr(
Expr *E) {
8128 Object O = Object();
8144 SequenceTree::Seq LHS = Tree.allocate(Region);
8145 SequenceTree::Seq RHS = Tree.allocate(Region);
8146 SequenceTree::Seq OldRegion = Region;
8149 SequencedSubexpression SeqLHS(*
this);
8169 Object O = getObject(BO->
getLHS(),
true);
8171 return VisitExpr(BO);
8181 if (isa<CompoundAssignOperator>(BO))
8186 if (isa<CompoundAssignOperator>(BO))
8195 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8196 : UK_ModAsSideEffect);
8199 VisitBinAssign(CAO);
8202 void VisitUnaryPreInc(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8203 void VisitUnaryPreDec(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
8205 Object O = getObject(UO->
getSubExpr(),
true);
8207 return VisitExpr(UO);
8213 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
8214 : UK_ModAsSideEffect);
8217 void VisitUnaryPostInc(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8218 void VisitUnaryPostDec(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
8220 Object O = getObject(UO->
getSubExpr(),
true);
8222 return VisitExpr(UO);
8226 notePostMod(O, UO, UK_ModAsSideEffect);
8235 EvaluationTracker Eval(*
this);
8237 SequencedSubexpression Sequenced(*
this);
8242 if (Eval.evaluate(BO->
getLHS(), Result)) {
8252 WorkList.push_back(BO->
getRHS());
8256 EvaluationTracker Eval(*
this);
8258 SequencedSubexpression Sequenced(*
this);
8263 if (Eval.evaluate(BO->
getLHS(), Result)) {
8267 WorkList.push_back(BO->
getRHS());
8274 EvaluationTracker Eval(*
this);
8276 SequencedSubexpression Sequenced(*
this);
8281 if (Eval.evaluate(CO->
getCond(), Result))
8296 SequencedSubexpression Sequenced(*
this);
8297 Base::VisitCallExpr(CE);
8304 SequencedSubexpression Sequenced(*
this);
8307 return VisitExpr(CCE);
8311 SequenceTree::Seq Parent = Region;
8315 Region = Tree.allocate(Parent);
8316 Elts.push_back(Region);
8322 for (
unsigned I = 0; I < Elts.size(); ++
I)
8323 Tree.merge(Elts[I]);
8327 if (!SemaRef.getLangOpts().CPlusPlus11)
8328 return VisitExpr(ILE);
8332 SequenceTree::Seq Parent = Region;
8336 Region = Tree.allocate(Parent);
8337 Elts.push_back(Region);
8343 for (
unsigned I = 0; I < Elts.size(); ++
I)
8344 Tree.merge(Elts[I]);
8349 void Sema::CheckUnsequencedOperations(
Expr *E) {
8351 WorkList.push_back(E);
8352 while (!WorkList.empty()) {
8353 Expr *Item = WorkList.pop_back_val();
8354 SequenceChecker(*
this, Item, WorkList);
8360 CheckImplicitConversions(E, CheckLoc);
8361 CheckUnsequencedOperations(E);
8363 CheckForIntOverflow(E);
8369 (void) AnalyzeBitFieldAssignment(*
this, BitField, Init, InitLoc);
8376 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
8380 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
8384 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
8398 S.
Diag(Loc, diag::err_array_star_in_function_definition);
8408 bool CheckParameterNames) {
8409 bool HasInvalidParm =
false;
8410 for (; P != PEnd; ++
P) {
8420 diag::err_typecheck_decl_incomplete_type)) {
8422 HasInvalidParm =
true;
8427 if (CheckParameterNames &&
8430 !getLangOpts().CPlusPlus)
8452 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
8457 MarkFunctionReferenced(Param->
getLocation(), Destructor);
8458 DiagnoseUseOfDecl(Destructor, Param->
getLocation());
8468 if (
const auto *
Attr = Param->
getAttr<PassObjectSizeAttr>())
8474 return HasInvalidParm;
8482 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.
getBegin()))
8491 if (!DestPtr)
return;
8497 if (DestAlign.
isOne())
return;
8501 if (!SrcPtr)
return;
8511 if (SrcAlign >= DestAlign)
return;
8517 << TRange << Op->getSourceRange();
8536 if (Size != 1 || !ND)
return false;
8539 if (!FD)
return false;
8562 if (!RD)
return false;
8563 if (RD->
isUnion())
return false;
8564 if (
const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
8565 if (!CRD->isStandardLayout())
return false;
8571 if (isa<FieldDecl>(D))
8576 void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
8578 bool AllowOnePastEnd,
bool IndexNegated) {
8597 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8598 ND = dyn_cast<NamedDecl>(DRE->
getDecl());
8599 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8600 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8602 if (index.isUnsigned() || !index.isNegative()) {
8603 llvm::APInt size = ArrayTy->
getSize();
8604 if (!size.isStrictlyPositive())
8608 if (BaseType != EffectiveType) {
8610 uint64_t ptrarith_typesize = Context.
getTypeSize(EffectiveType);
8611 uint64_t array_typesize = Context.
getTypeSize(BaseType);
8613 if (!ptrarith_typesize) ptrarith_typesize = 1;
8614 if (ptrarith_typesize != array_typesize) {
8616 uint64_t ratio = array_typesize / ptrarith_typesize;
8619 if (ptrarith_typesize * ratio == array_typesize)
8620 size *= llvm::APInt(size.getBitWidth(), ratio);
8624 if (size.getBitWidth() > index.getBitWidth())
8625 index = index.zext(size.getBitWidth());
8626 else if (size.getBitWidth() < index.getBitWidth())
8627 size = size.zext(index.getBitWidth());
8633 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
8650 IndexExpr->getLocStart());
8656 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
8658 DiagID = diag::warn_array_index_exceeds_bounds;
8660 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8661 PDiag(DiagID) << index.toString(10,
true)
8662 << size.toString(10,
true)
8663 << (
unsigned)size.getLimitedValue(~0U)
8664 << IndexExpr->getSourceRange());
8666 unsigned DiagID = diag::warn_array_index_precedes_bounds;
8668 DiagID = diag::warn_ptr_arith_precedes_bounds;
8669 if (index.isNegative()) index = -index;
8672 DiagRuntimeBehavior(BaseExpr->getLocStart(), BaseExpr,
8673 PDiag(DiagID) << index.toString(10,
true)
8674 << IndexExpr->getSourceRange());
8680 dyn_cast<ArraySubscriptExpr>(BaseExpr))
8682 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
8684 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
8685 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
8690 PDiag(diag::note_array_index_out_of_bounds)
8694 void Sema::CheckArrayAccess(
const Expr *
expr) {
8695 int AllowOnePastEnd = 0;
8698 switch (expr->getStmtClass()) {
8699 case Stmt::ArraySubscriptExprClass: {
8702 AllowOnePastEnd > 0);
8705 case Stmt::OMPArraySectionExprClass: {
8709 nullptr, AllowOnePastEnd > 0);
8712 case Stmt::UnaryOperatorClass: {
8728 case Stmt::ConditionalOperatorClass: {
8731 CheckArrayAccess(lhs);
8733 CheckArrayAccess(rhs);
8745 struct RetainCycleOwner {
8746 RetainCycleOwner() : Variable(nullptr), Indirect(
false) {}
8752 void setLocsFrom(
Expr *e) {
8754 Range = e->getSourceRange();
8768 owner.Variable = var;
8770 owner.setLocsFrom(ref);
8778 switch (
cast->getCastKind()) {
8783 e =
cast->getSubExpr();
8800 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
8801 owner.Indirect =
true;
8805 if (
DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
8807 if (!var)
return false;
8811 if (
MemberExpr *member = dyn_cast<MemberExpr>(e)) {
8812 if (member->isArrow())
return false;
8815 e = member->getBase();
8824 if (!pre)
return false;
8827 if (!property->isRetaining() &&
8828 !(
property->getPropertyIvarDecl() &&
8829 property->getPropertyIvarDecl()->getType()
8833 owner.Indirect =
true;
8836 if (!owner.Variable)
8839 owner.Range = pre->getSourceRange();
8842 e =
const_cast<Expr*
>(cast<OpaqueValueExpr>(pre->
getBase())
8857 Context(Context), Variable(variable), Capturer(nullptr),
8858 VarWillBeReased(
false) {}
8862 bool VarWillBeReased;
8865 if (ref->
getDecl() == Variable && !Capturer)
8870 if (Capturer)
return;
8883 if (Capturer)
return;
8891 if (
const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
8892 if (DRE->
getDecl() != Variable)
8898 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
8908 assert(owner.Variable && owner.Loc.isValid());
8916 e = ME->getInstanceReceiver();
8919 e = e->IgnoreParenCasts();
8921 }
else if (
CallExpr *CE = dyn_cast<CallExpr>(e)) {
8926 if (FnI && FnI->
isStr(
"_Block_copy")) {
8937 FindCaptureVisitor visitor(S.
Context, owner.Variable);
8939 return visitor.VarWillBeReased ?
nullptr : visitor.Capturer;
8943 RetainCycleOwner &owner) {
8945 assert(owner.Variable && owner.Loc.isValid());
8948 << owner.Variable << capturer->getSourceRange();
8949 S.
Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
8950 << owner.Indirect << owner.Range;
8959 while (!str.empty() && str.front() ==
'_') str = str.substr(1);
8960 if (str.startswith(
"set"))
8961 str = str.substr(3);
8962 else if (str.startswith(
"add")) {
8964 if (sel.
getNumArgs() == 1 && str.startswith(
"addOperationWithBlock"))
8966 str = str.substr(3);
8971 if (str.empty())
return true;
8977 bool IsMutableArray = S.
NSAPIObj->isSubclassOfNSClass(
8980 if (!IsMutableArray) {
8987 S.
NSAPIObj->getNSArrayMethodKind(Sel);
9012 bool IsMutableDictionary = S.
NSAPIObj->isSubclassOfNSClass(
9015 if (!IsMutableDictionary) {
9022 S.
NSAPIObj->getNSDictionaryMethodKind(Sel);
9043 bool IsMutableSet = S.
NSAPIObj->isSubclassOfNSClass(
9047 bool IsMutableOrderedSet = S.
NSAPIObj->isSubclassOfNSClass(
9050 if (!IsMutableSet && !IsMutableOrderedSet) {
9089 int ArgIndex = *ArgOpt;
9097 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9098 if (ArgRE->isObjCSelfExpr()) {
9099 Diag(Message->getSourceRange().getBegin(),
9100 diag::warn_objc_circular_container)
9101 << ArgRE->getDecl()->getName() << StringRef(
"super");
9111 if (
DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
9112 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
9113 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
9115 Diag(Message->getSourceRange().getBegin(),
9116 diag::warn_objc_circular_container)
9118 if (!ArgRE->isObjCSelfExpr()) {
9120 diag::note_objc_circular_container_declared_here)
9125 }
else if (
ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
9127 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
9129 Diag(Message->getSourceRange().getBegin(),
9130 diag::warn_objc_circular_container)
9133 diag::note_objc_circular_container_declared_here)
9149 RetainCycleOwner owner;
9155 owner.Variable = getCurMethodDecl()->getSelfDecl();
9161 for (
unsigned i = 0, e = msg->
getNumArgs(); i != e; ++i)
9168 RetainCycleOwner owner;
9177 RetainCycleOwner Owner;
9191 Expr *RHS,
bool isProperty) {
9203 S.
Diag(Loc, diag::warn_arc_literal_assign)
9205 << (isProperty ? 0 : 1)
9206 << RHS->getSourceRange();
9213 Expr *RHS,
bool isProperty) {
9217 S.
Diag(Loc, diag::warn_arc_retained_assign)
9219 << (isProperty ? 0 : 1)
9220 << RHS->getSourceRange();
9223 RHS =
cast->getSubExpr();
9265 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
9266 getCurFunction()->markSafeWeakUse(LHS);
9269 if (checkUnsafeAssigns(Loc, LHSType, RHS))
9289 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
9295 Diag(Loc, diag::warn_arc_retained_property_assign)
9296 << RHS->getSourceRange();
9299 RHS =
cast->getSubExpr();
9325 bool StmtLineInvalid;
9328 if (StmtLineInvalid)
9331 bool BodyLineInvalid;
9334 if (BodyLineInvalid)
9338 if (StmtLine != BodyLine)
9350 if (CurrentInstantiationScope)
9359 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9363 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
9367 const Stmt *PossibleBody) {
9368 assert(!CurrentInstantiationScope);
9373 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
9374 StmtLoc = FS->getRParenLoc();
9375 Body = FS->getBody();
9376 DiagID = diag::warn_empty_for_body;
9377 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
9378 StmtLoc = WS->getCond()->getSourceRange().getEnd();
9379 Body = WS->getBody();
9380 DiagID = diag::warn_empty_while_body;
9390 if (Diags.isIgnored(DiagID, NBody->
getSemiLoc()))
9394 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
9408 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
9409 if (!ProbableTypo) {
9410 bool BodyColInvalid;
9412 PossibleBody->getLocStart(),
9417 bool StmtColInvalid;
9424 if (BodyCol > StmtCol)
9425 ProbableTypo =
true;
9430 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
9440 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
9443 if (!ActiveTemplateInstantiations.empty())
9468 if (LHSDeclRef && RHSDeclRef) {
9469 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
9475 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9476 << LHSExpr->getSourceRange()
9477 << RHSExpr->getSourceRange();
9485 const Expr *LHSBase = LHSExpr;
9486 const Expr *RHSBase = RHSExpr;
9489 if (!LHSME || !RHSME)
9492 while (LHSME && RHSME) {
9498 RHSBase = RHSME->getBase();
9505 if (LHSDeclRef && RHSDeclRef) {
9506 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
9512 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9513 << LHSExpr->getSourceRange()
9514 << RHSExpr->getSourceRange();
9518 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
9519 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
9520 << LHSExpr->getSourceRange()
9521 << RHSExpr->getSourceRange();
9541 if (!isLayoutCompatible(C, Field1->
getType(), Field2->
getType()))
9565 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
9575 Base1 = D1CXX->bases_begin(),
9576 BaseEnd1 = D1CXX->bases_end(),
9580 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
9583 }
else if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
9594 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
9595 if (!isLayoutCompatible(C, *Field1, *Field2))
9598 if (Field1 != Field1End || Field2 != Field2End)
9609 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
9610 for (
auto *Field2 : RD2->
fields())
9611 UnmatchedFields.insert(Field2);
9613 for (
auto *Field1 : RD1->
fields()) {
9615 I = UnmatchedFields.begin(),
9616 E = UnmatchedFields.end();
9618 for ( ; I !=
E; ++
I) {
9619 if (isLayoutCompatible(C, Field1, *I)) {
9620 bool Result = UnmatchedFields.erase(*I);
9630 return UnmatchedFields.empty();
9638 return isLayoutCompatibleUnion(C, RD1, RD2);
9640 return isLayoutCompatibleStruct(C, RD1, RD2);
9663 if (TC1 == Type::Enum) {
9664 return isLayoutCompatible(C,
9665 cast<EnumType>(T1)->getDecl(),
9666 cast<EnumType>(T2)->getDecl());
9667 }
else if (TC1 == Type::Record) {
9671 return isLayoutCompatible(C,
9672 cast<RecordType>(T1)->getDecl(),
9673 cast<RecordType>(T2)->getDecl());
9690 bool FindTypeTagExpr(
const Expr *TypeExpr,
const ASTContext &Ctx,
9691 const ValueDecl **VD, uint64_t *MagicValue) {
9698 switch (TypeExpr->getStmtClass()) {
9699 case Stmt::UnaryOperatorClass: {
9708 case Stmt::DeclRefExprClass: {
9709 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
9714 case Stmt::IntegerLiteralClass: {
9716 llvm::APInt MagicValueAPInt = IL->
getValue();
9717 if (MagicValueAPInt.getActiveBits() <= 64) {
9718 *MagicValue = MagicValueAPInt.getZExtValue();
9724 case Stmt::BinaryConditionalOperatorClass:
9725 case Stmt::ConditionalOperatorClass: {
9727 cast<AbstractConditionalOperator>(TypeExpr);
9739 case Stmt::BinaryOperatorClass: {
9766 bool GetMatchingCType(
9771 bool &FoundWrongKind,
9773 FoundWrongKind =
false;
9778 uint64_t MagicValue;
9780 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
9784 if (TypeTagForDatatypeAttr *I = VD->
getAttr<TypeTagForDatatypeAttr>()) {
9785 if (I->getArgumentKind() != ArgumentKind) {
9786 FoundWrongKind =
true;
9789 TypeInfo.
Type = I->getMatchingCType();
9802 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
9803 if (I == MagicValues->end())
9806 TypeInfo = I->second;
9812 uint64_t MagicValue,
QualType Type,
9813 bool LayoutCompatible,
9815 if (!TypeTagForDatatypeMagicValues)
9816 TypeTagForDatatypeMagicValues.reset(
9817 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
9820 (*TypeTagForDatatypeMagicValues)[Magic] =
9837 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
9838 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
9839 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
9840 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
9844 void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
9845 const Expr *
const *ExprArgs) {
9847 bool IsPointerAttr = Attr->getIsPointer();
9849 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
9850 bool FoundWrongKind;
9851 TypeTagData TypeInfo;
9852 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
9853 TypeTagForDatatypeMagicValues.get(),
9854 FoundWrongKind, TypeInfo)) {
9857 diag::warn_type_tag_for_datatype_wrong_kind)
9858 << TypeTagExpr->getSourceRange();
9862 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
9863 if (IsPointerAttr) {
9865 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
9866 if (ICE->getType()->isVoidPointerType() &&
9868 ArgumentExpr = ICE->getSubExpr();
9876 if (TypeInfo.MustBeNull) {
9881 diag::warn_type_safety_null_pointer_required)
9883 << ArgumentExpr->getSourceRange()
9884 << TypeTagExpr->getSourceRange();
9889 QualType RequiredType = TypeInfo.Type;
9893 bool mismatch =
false;
9894 if (!TypeInfo.LayoutCompatible) {
9895 mismatch = !Context.
hasSameType(ArgumentType, RequiredType);
9903 if ((IsPointerAttr && IsSameCharType(ArgumentType->
getPointeeType(),
9905 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
9909 mismatch = !isLayoutCompatible(Context,
9913 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
9916 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
9917 << ArgumentType << ArgumentKind
9918 << TypeInfo.LayoutCompatible << RequiredType
9919 << ArgumentExpr->getSourceRange()
9920 << TypeTagExpr->getSourceRange();
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
const OptionalFlag & hasSpacePrefix() const
unsigned getFlags() const
getFlags - Return the flags for this scope.
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)
bool isMacroArgExpansion(SourceLocation Loc, SourceLocation *StartLoc=nullptr) const
Tests whether the given source location represents a macro argument's expansion into the function-lik...
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
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
CK_LValueToRValue - A conversion which causes the extraction of an r-value from the operand gl-value...
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
getName - Get the name of identifier for this declaration as a StringRef.
static void CheckReturnStackAddr(Sema &S, Expr *RetValExp, QualType lhsType, SourceLocation ReturnLoc)
CheckReturnStackAddr - Check if a return statement returns the address of a stack variable...
Smart pointer class that efficiently represents Objective-C method names.
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
PointerType - C99 6.7.5.1 - Pointer Declarators.
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...
A (possibly-)qualified type.
unsigned getLength() const
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
bool isSpecificBuiltinType(unsigned K) const
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
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc...
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
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)
FunctionType - C99 6.7.5.3 - Function Declarators.
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
EnumConstantDecl - An instance of this object exists for each enum constant that is defined...
unsigned getIntWidth(QualType T) const
const ScanfConversionSpecifier & getConversionSpecifier() const
const Scope * getParent() const
getParent - Return the scope that this is nested in.
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()
Add the const 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.
Decl - This represents one declaration (or definition), e.g.
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
ParenExpr - This represents a parethesized expression, e.g.
Expr * getLowerBound()
Get lower bound of array section.
The base class of the type hierarchy.
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...
Represents an array type, per C99 6.7.5.2 - Array Declarators.
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.
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
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
Checks that a call expression's argument count is the desired number.
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)
Determine if type T is a valid subject for a nonnull and similar attributes.
ObjCDictionaryElement getKeyValueElement(unsigned Index) const
VarDecl - An instance of this class is created to represent a variable declaration or definition...
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
CK_IntegralCast - A cast between integral types (other than to boolean).
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
DiagnosticsEngine & Diags
CompoundLiteralExpr - [C99 6.5.2.5].
const Expr * getCallee() const
bool areArgsDestroyedLeftToRightInCallee() const
Are arguments to a call destroyed left to right in the callee? This is a fundamental language change...
APFloat & getComplexFloatReal()
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have...
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.
ObjCMethodDecl - Represents an instance or class method declaration.
Expr * IgnoreImplicit() LLVM_READONLY
IgnoreImplicit - Skip past any implicit AST nodes which might surround this expression.
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)
ParmVarDecl - Represents a parameter to a function.
bool isObjCRetainableType() const
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant...
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.
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
IgnoreImpCasts - Skip past any implicit casts which might surround this expression.
unsigned getNumParams() const
RecordDecl - Represents a struct/union/class.
static bool CheckForReference(Sema &SemaRef, const Expr *E, PartialDiagnostic PD)
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6...
One of these records is kept for each identifier that is lexed.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
bool isScalarType() const
bool isComplexInt() const
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
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
QualType getAddrSpaceQualType(QualType T, unsigned AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
bool isReferenceType() const
QualType getReturnType() const
virtual bool validateCpuSupports(StringRef Name) const
FieldDecl - An instance of this class is created by Sema::ActOnField to represent a member of a struc...
bool isCompleteDefinition() const
isCompleteDefinition - Return true if this decl has its body fully specified.
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.
The iterator over UnresolvedSets.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
CK_FloatingCast - Casting between floating types of different size.
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
getBody - If this Decl represents a declaration for a body of code, such as a function or method defi...
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp, [NSNumber numberWithInt:42]];.
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)
Warn if a for/while loop statement S, which is followed by PossibleBody, has a suspicious null statem...
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.
ForStmt - This represents a 'for (init;cond;inc)' stmt.
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()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
CharUnits - This is an opaque type for sizes expressed in character units.
APValue Val
Val - This is the value the expression can be folded to.
bool hasValidPlusPrefix() const
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
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
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
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
If true, Type should be compared with other expression's types for layout-compatibility.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body. ...
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Represents a typeof (or typeof) expression (a GCC extension).
A builtin binary operation expression such as "x + y" or "x <= y".
Selector getSelector() const
bool isValueDependent() const
isValueDependent - Determines whether this expression is value-dependent (C++ [temp.dep.constexpr]).
RecordDecl * getDecl() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
Expr * IgnoreParenCasts() LLVM_READONLY
IgnoreParenCasts - Ignore parentheses and casts.
ObjCStringLiteral, used for Objective-C string literals i.e.
Values of this type can never be null.
Scope - A scope is a transient data structure that is used while parsing the program.
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...
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
TypeClass getTypeClass() const
base_class_iterator bases_begin()
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
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...
AssignConvertType CheckSingleAssignmentConstraints(QualType LHSType, ExprResult &RHS, bool Diagnose=true, bool DiagnoseCFAudited=false, bool ConvertRHS=true)
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)
Member name lookup, which finds the names of class/struct/union members.
Expression is a GNU-style __null constant.
detail::InMemoryDirectory::const_iterator I
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.
This object can be modified without requiring retains or releases.
param_iterator param_begin()
field_iterator field_end() const
APValue & getVectorElt(unsigned I)
CK_AnyPointerToBlockPointerCast - Casting any non-block pointer to a block pointer.
bool isAddrLabelDiff() const
Decl * getNextDeclInContext()
OpenMP 4.0 [2.4, Array Sections].
ConditionalOperator - The ?: ternary operator.
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
Represents a prototype with parameter type info, e.g.
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
Returns lifetime attribute of this type.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
CastKind
CastKind - The kind of operation required for a conversion.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
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
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee...
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
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
ValueDecl - Represent the declaration of a variable (in which case it is an lvalue) a function (in wh...
Expr - This represents one expression.
StringRef getName() const
Return the actual identifier string.
Allow any unmodeled side effect.
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Represents a character-granular source range.
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
CK_BitCast - A conversion which causes a bit pattern of one type to be reinterpreted as a bit pattern...
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
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Represents a C++ destructor within a class.
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
This scope corresponds to an SEH except.
bool isVariableArrayType() const
const ParmVarDecl * getParamDecl(unsigned i) const
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
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
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
bool fixType(QualType QT, const LangOptions &LangOpt, ASTContext &Ctx, bool IsObjCLiteral)
Changes the specifier and length according to a QualType, retaining any flags or options.
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer...
const PrintfConversionSpecifier & getConversionSpecifier() const
An expression that sends a message to the given Objective-C object or class.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof), the postinc/postdec operators from postfix-expression, and various extensions.
SmallVector< ActiveTemplateInstantiation, 16 > ActiveTemplateInstantiations
List of active template instantiations.
Represents a GCC generic vector type.
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
class LLVM_ALIGNAS(8) TemplateSpecializationType unsigned NumArgs
Represents a type template specialization; the template must be a class template, a type alias templa...
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.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr.cast]), which uses the syntax (Type)expr.
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name, with source-location information.
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
SourceLocation getSemiLoc() const
void EvaluateForOverflow(const ASTContext &Ctx) const
TypeSourceInfo * getTypeSourceInfo() const
static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context, bool IsPolyUnsigned, bool IsInt64Long)
getNeonEltType - Return the QualType corresponding to the elements of the vector type specified by th...
Expr * getTrueExpr() const
CallingConv
CallingConv - Specifies the calling convention that a function uses.
static const Expr * getStrlenExprArg(const Expr *E)
static bool SemaBuiltinCpuSupports(Sema &S, CallExpr *TheCall)
SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
CK_ArrayToPointerDecay - Array to pointer decay.
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.
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
CK_CPointerToObjCPointerCast - Casting a C pointer kind to an Objective-C pointer.
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.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class...
Enumerates target-specific builtins in their own namespaces within namespace clang.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const
EvaluateAsBooleanCondition - Return true if this is a constant which we we can fold and convert to a ...
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
Assigning into this object requires the old value to be released and the new value to be retained...
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
const char * getSpelling() const
not a target-specific vector type
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner)
Consider whether capturing the given variable can possibly lead to a retain cycle.
Encodes a location in the source.
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
getNumParams - Return the number of parameters this function must have based on its FunctionType...
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
const TemplateArgument * iterator
Expression is not a Null pointer constant.
unsigned getBitWidthValue(const ASTContext &Ctx) const
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
static Expr * EvalAddr(Expr *E, SmallVectorImpl< DeclRefExpr * > &refVars, Decl *ParentDecl)
EvalAddr - EvalAddr and EvalVal are mutually recursive functions that check if the expression in a re...
void checkRetainCycles(ObjCMessageExpr *msg)
checkRetainCycles - Check whether an Objective-C message send might create an obvious 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?
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.
CK_DerivedToBase - A conversion from a C++ class pointer to a base class pointer. ...
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
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
isIntegerConstantExpr - Return true if this expression is a valid integer constant expression...
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>.
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.
Look up any declaration with any name.
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
EltType getEltType() const
bool FormatStringHasSArg(const StringLiteral *FExpr)
Represents one property declaration in an Objective-C interface.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
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.
const T * castAs() const
Member-template castAs<specific type>.
bool isTypeDependent() const
isTypeDependent - Determines whether this expression is type-dependent (C++ [temp.dep.expr]), which means that its type could change from one template instantiation to the next.
const IdentifierInfo * getIdentifier() 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
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
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
CompoundAssignOperator - For compound assignments (e.g.
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
getCallReturnType - Get the return type of the call expr.
CanQualType UnsignedShortTy
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
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
NullStmt - This is the null statement ";": C99 6.8.3p3.
bool isImplicitProperty() const
static const Type * getElementType(const Expr *BaseExpr)
EvalResult is a struct with detailed info about an evaluated expression.
static 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)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
static __inline__ uint32_t volatile uint32_t * p
bool isInvalidDecl() const
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
const OptionalFlag & hasThousandsGrouping() const
CK_BaseToDerived - A conversion from a C++ class pointer/reference to a derived class pointer/referen...
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.
QualType getExceptionObjectType(QualType T) const
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
DeclarationName - The name of a declaration.
Expression is a Null pointer constant built from a zero integer expression that is not a simple...
U cast(CodeGen::Address addr)
static bool isSetterLikeSelector(Selector sel)
Check for a keyword selector that starts with the word 'add' or 'set'.
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.
EnumDecl - Represents an enum.
Expression is a C++11 nullptr.
CK_BlockPointerToObjCPointerCast - Casting a block pointer to an ObjC pointer.
detail::InMemoryDirectory::const_iterator E
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
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)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner)
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext, providing only those that are of type SpecificDecl (or a class derived from it).
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
IgnoreParenImpCasts - Ignore parentheses and implicit casts.
param_iterator param_end()
static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall)
Represents a pointer to an Objective C object.
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)
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Complex values, per C99 6.2.5p11.
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
bool isTriviallyCopyableType(ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
SourceManager & getSourceManager() const
const T * getAs() const
Member-template getAs<specific type>'.
Expr * getFalseExpr() const
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
QualType getCanonicalType() const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
CanQualType UnsignedLongTy
bool isObjCQualifiedIdType() const
QualType getIntegerType() const
getIntegerType - Return the integer type this enum decl corresponds to.
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
CK_LValueBitCast - A conversion which reinterprets the address of an l-value as an l-value of a diffe...
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)
EvalVal - This function is complements EvalAddr in the mutual recursion.
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)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat]...
Represents a base class of a C++ class.
ObjCPropertyDecl * getExplicitProperty() const
CK_UncheckedDerivedToBase - A conversion from a C++ class pointer/reference to a base class that can ...
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
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)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body, and it is located on the same line.
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
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
ObjCIvarDecl - Represents an ObjC instance variable.
ArraySizeModifier getSizeModifier() const
WhileStmt - This represents a 'while' stmt.
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...
This class is used for builtin types like 'int'.
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.
StringLiteral - This represents a string literal expression, e.g.
Defines the clang::TargetInfo interface.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
PropertyAttributeKind getPropertyAttributesAsWritten() const
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
CK_NoOp - A conversion which does not affect the type other than (possibly) adding qualifiers...
A reference to a declared variable, function, enum, etc.
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)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
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)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type...
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
ExprIterator arg_iterator
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
NamedDecl - This represents a decl with a name.
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)
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
getLocationOfByte - Return a source location that points to the specified byte of this string literal...
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char, signed char, short, int, long..], or an enum decl which has a signed representation.
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
Return true if this QualType doesn't point to a type yet.
TypeSourceInfo * getTypeSourceInfo() const
static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
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
Determine the nullability of the given type.
static Expr * findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner)
Check whether the given argument is a block which captures a variable.
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.
Represents the canonical version of C arrays with a specified constant size.
unsigned getVectorLength() const
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c dictionary literal.
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)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Helper class that creates diagnostics with optional template instantiation stacks.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
CanQualType UnsignedIntTy
Expr * getBase()
An array section can be written only as Base[LowerBound:Length].
bool isPointerType() const
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any...