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/Format.h"
41 #include "llvm/Support/Locale.h"
42 #include "llvm/Support/raw_ostream.h"
44 using namespace clang;
48 unsigned ByteNo)
const {
57 if (argCount == desiredArgCount)
return false;
59 if (argCount < desiredArgCount)
60 return S.
Diag(call->
getLocEnd(), diag::err_typecheck_call_too_few_args)
61 << 0 << desiredArgCount << argCount
68 return S.
Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
69 << 0 << desiredArgCount << argCount
91 if (!Literal || !Literal->
isAscii()) {
109 if (ResultType.isNull())
112 TheCall->
setArg(0, Arg.get());
122 for (
unsigned I = 0;
I < 2; ++
I) {
139 if (!(PtrTy && PtrTy->getPointeeType()->isIntegerType() &&
140 !PtrTy->getPointeeType().isConstQualified())) {
151 CallExpr *TheCall,
unsigned SizeIdx,
152 unsigned DstSizeIdx) {
157 const Expr *SizeArg = TheCall->
getArg(SizeIdx);
158 const Expr *DstSizeArg = TheCall->
getArg(DstSizeIdx);
160 llvm::APSInt Size, DstSize;
167 if (Size.ule(DstSize))
175 S.
Diag(SL, diag::warn_memcpy_chk_overflow) << SR << FnName;
188 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
193 auto CE = cast<CallExpr>(Call);
194 if (CE->getCallee()->getType()->isBlockPointerType()) {
195 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
200 const Decl *TargetDecl = CE->getCalleeDecl();
201 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
202 if (FD->getBuiltinID()) {
203 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
208 if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
209 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
218 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
232 BuiltinCall->
setType(CE->getType());
236 BuiltinCall->
setArg(1, ChainResult.
get());
253 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
256 << DRE->getDecl()->getIdentifier();
272 ArrayRef<QualType> Params =
274 unsigned ArgCounter = 0;
275 bool IllegalParams =
false;
278 for (ArrayRef<QualType>::iterator
I = Params.begin(),
E = Params.end();
279 I !=
E; ++
I, ++ArgCounter) {
280 if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
281 (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
287 if (isa<BlockExpr>(BlockArg)) {
288 BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
290 }
else if (isa<DeclRefExpr>(BlockArg)) {
291 ErrorLoc = cast<DeclRefExpr>(BlockArg)->getLocStart();
294 diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
295 IllegalParams =
true;
299 return IllegalParams;
312 diag::err_opencl_builtin_expected_type)
324 unsigned Start,
unsigned End) {
325 bool IllegalParams =
false;
326 for (
unsigned I = Start;
I <=
End; ++
I)
329 return IllegalParams;
336 unsigned NumNonVarArgs) {
339 unsigned NumBlockParams =
341 unsigned TotalNumArgs = TheCall->
getNumArgs();
345 if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
347 diag::err_opencl_enqueue_kernel_local_size_args);
398 diag::err_opencl_builtin_expected_type)
406 diag::err_opencl_builtin_expected_type)
407 << TheCall->
getDirectCallee() <<
"'kernel_enqueue_flags_t' (i.e. uint)";
414 diag::err_opencl_builtin_expected_type)
433 diag::err_opencl_enqueue_kernel_blocks_no_args);
457 diag::err_opencl_builtin_expected_type)
470 diag::err_opencl_builtin_expected_type)
482 diag::err_opencl_builtin_expected_type)
496 diag::err_opencl_enqueue_kernel_incorrect_args);
502 return D->
getAttr<OpenCLAccessAttr>();
514 OpenCLAccessAttr *AccessQual =
521 case Builtin::BIread_pipe:
522 case Builtin::BIreserve_read_pipe:
523 case Builtin::BIcommit_read_pipe:
524 case Builtin::BIwork_group_reserve_read_pipe:
525 case Builtin::BIsub_group_reserve_read_pipe:
526 case Builtin::BIwork_group_commit_read_pipe:
527 case Builtin::BIsub_group_commit_read_pipe:
528 if (!(!AccessQual || AccessQual->isReadOnly())) {
530 diag::err_opencl_builtin_pipe_invalid_access_modifier)
535 case Builtin::BIwrite_pipe:
536 case Builtin::BIreserve_write_pipe:
537 case Builtin::BIcommit_write_pipe:
538 case Builtin::BIwork_group_reserve_write_pipe:
539 case Builtin::BIsub_group_reserve_write_pipe:
540 case Builtin::BIwork_group_commit_write_pipe:
541 case Builtin::BIsub_group_commit_write_pipe:
542 if (!(AccessQual && AccessQual->isWriteOnly())) {
544 diag::err_opencl_builtin_pipe_invalid_access_modifier)
708 if (!RT->isPointerType() || RT->getPointeeType()
710 S.
Diag(Call->
getLocStart(), diag::err_opencl_builtin_to_addr_invalid_arg)
715 RT = RT->getPointeeType();
716 auto Qual = RT.getQualifiers();
718 case Builtin::BIto_global:
721 case Builtin::BIto_local:
725 Qual.removeAddressSpace();
728 RT.getUnqualifiedType(), Qual)));
734 Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
739 unsigned ICEArguments = 0;
746 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
748 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
751 if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
753 ICEArguments &= ~(1 << ArgNo);
757 case Builtin::BI__builtin___CFStringMakeConstantString:
759 "Wrong # arguments to builtin CFStringMakeConstantString");
760 if (CheckObjCString(TheCall->
getArg(0)))
763 case Builtin::BI__builtin_ms_va_start:
764 case Builtin::BI__builtin_stdarg_start:
765 case Builtin::BI__builtin_va_start:
766 if (SemaBuiltinVAStart(BuiltinID, TheCall))
769 case Builtin::BI__va_start: {
771 case llvm::Triple::arm:
772 case llvm::Triple::thumb:
773 if (SemaBuiltinVAStartARM(TheCall))
777 if (SemaBuiltinVAStart(BuiltinID, TheCall))
783 case Builtin::BI__builtin_isgreater:
784 case Builtin::BI__builtin_isgreaterequal:
785 case Builtin::BI__builtin_isless:
786 case Builtin::BI__builtin_islessequal:
787 case Builtin::BI__builtin_islessgreater:
788 case Builtin::BI__builtin_isunordered:
789 if (SemaBuiltinUnorderedCompare(TheCall))
792 case Builtin::BI__builtin_fpclassify:
793 if (SemaBuiltinFPClassification(TheCall, 6))
796 case Builtin::BI__builtin_isfinite:
797 case Builtin::BI__builtin_isinf:
798 case Builtin::BI__builtin_isinf_sign:
799 case Builtin::BI__builtin_isnan:
800 case Builtin::BI__builtin_isnormal:
801 if (SemaBuiltinFPClassification(TheCall, 1))
804 case Builtin::BI__builtin_shufflevector:
805 return SemaBuiltinShuffleVector(TheCall);
808 case Builtin::BI__builtin_prefetch:
809 if (SemaBuiltinPrefetch(TheCall))
812 case Builtin::BI__builtin_alloca_with_align:
813 if (SemaBuiltinAllocaWithAlign(TheCall))
816 case Builtin::BI__assume:
817 case Builtin::BI__builtin_assume:
818 if (SemaBuiltinAssume(TheCall))
821 case Builtin::BI__builtin_assume_aligned:
822 if (SemaBuiltinAssumeAligned(TheCall))
825 case Builtin::BI__builtin_object_size:
826 if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
829 case Builtin::BI__builtin_longjmp:
830 if (SemaBuiltinLongjmp(TheCall))
833 case Builtin::BI__builtin_setjmp:
834 if (SemaBuiltinSetjmp(TheCall))
837 case Builtin::BI_setjmp:
838 case Builtin::BI_setjmpex:
843 case Builtin::BI__builtin_classify_type:
847 case Builtin::BI__builtin_constant_p:
851 case Builtin::BI__sync_fetch_and_add:
852 case Builtin::BI__sync_fetch_and_add_1:
853 case Builtin::BI__sync_fetch_and_add_2:
854 case Builtin::BI__sync_fetch_and_add_4:
855 case Builtin::BI__sync_fetch_and_add_8:
856 case Builtin::BI__sync_fetch_and_add_16:
857 case Builtin::BI__sync_fetch_and_sub:
858 case Builtin::BI__sync_fetch_and_sub_1:
859 case Builtin::BI__sync_fetch_and_sub_2:
860 case Builtin::BI__sync_fetch_and_sub_4:
861 case Builtin::BI__sync_fetch_and_sub_8:
862 case Builtin::BI__sync_fetch_and_sub_16:
863 case Builtin::BI__sync_fetch_and_or:
864 case Builtin::BI__sync_fetch_and_or_1:
865 case Builtin::BI__sync_fetch_and_or_2:
866 case Builtin::BI__sync_fetch_and_or_4:
867 case Builtin::BI__sync_fetch_and_or_8:
868 case Builtin::BI__sync_fetch_and_or_16:
869 case Builtin::BI__sync_fetch_and_and:
870 case Builtin::BI__sync_fetch_and_and_1:
871 case Builtin::BI__sync_fetch_and_and_2:
872 case Builtin::BI__sync_fetch_and_and_4:
873 case Builtin::BI__sync_fetch_and_and_8:
874 case Builtin::BI__sync_fetch_and_and_16:
875 case Builtin::BI__sync_fetch_and_xor:
876 case Builtin::BI__sync_fetch_and_xor_1:
877 case Builtin::BI__sync_fetch_and_xor_2:
878 case Builtin::BI__sync_fetch_and_xor_4:
879 case Builtin::BI__sync_fetch_and_xor_8:
880 case Builtin::BI__sync_fetch_and_xor_16:
881 case Builtin::BI__sync_fetch_and_nand:
882 case Builtin::BI__sync_fetch_and_nand_1:
883 case Builtin::BI__sync_fetch_and_nand_2:
884 case Builtin::BI__sync_fetch_and_nand_4:
885 case Builtin::BI__sync_fetch_and_nand_8:
886 case Builtin::BI__sync_fetch_and_nand_16:
887 case Builtin::BI__sync_add_and_fetch:
888 case Builtin::BI__sync_add_and_fetch_1:
889 case Builtin::BI__sync_add_and_fetch_2:
890 case Builtin::BI__sync_add_and_fetch_4:
891 case Builtin::BI__sync_add_and_fetch_8:
892 case Builtin::BI__sync_add_and_fetch_16:
893 case Builtin::BI__sync_sub_and_fetch:
894 case Builtin::BI__sync_sub_and_fetch_1:
895 case Builtin::BI__sync_sub_and_fetch_2:
896 case Builtin::BI__sync_sub_and_fetch_4:
897 case Builtin::BI__sync_sub_and_fetch_8:
898 case Builtin::BI__sync_sub_and_fetch_16:
899 case Builtin::BI__sync_and_and_fetch:
900 case Builtin::BI__sync_and_and_fetch_1:
901 case Builtin::BI__sync_and_and_fetch_2:
902 case Builtin::BI__sync_and_and_fetch_4:
903 case Builtin::BI__sync_and_and_fetch_8:
904 case Builtin::BI__sync_and_and_fetch_16:
905 case Builtin::BI__sync_or_and_fetch:
906 case Builtin::BI__sync_or_and_fetch_1:
907 case Builtin::BI__sync_or_and_fetch_2:
908 case Builtin::BI__sync_or_and_fetch_4:
909 case Builtin::BI__sync_or_and_fetch_8:
910 case Builtin::BI__sync_or_and_fetch_16:
911 case Builtin::BI__sync_xor_and_fetch:
912 case Builtin::BI__sync_xor_and_fetch_1:
913 case Builtin::BI__sync_xor_and_fetch_2:
914 case Builtin::BI__sync_xor_and_fetch_4:
915 case Builtin::BI__sync_xor_and_fetch_8:
916 case Builtin::BI__sync_xor_and_fetch_16:
917 case Builtin::BI__sync_nand_and_fetch:
918 case Builtin::BI__sync_nand_and_fetch_1:
919 case Builtin::BI__sync_nand_and_fetch_2:
920 case Builtin::BI__sync_nand_and_fetch_4:
921 case Builtin::BI__sync_nand_and_fetch_8:
922 case Builtin::BI__sync_nand_and_fetch_16:
923 case Builtin::BI__sync_val_compare_and_swap:
924 case Builtin::BI__sync_val_compare_and_swap_1:
925 case Builtin::BI__sync_val_compare_and_swap_2:
926 case Builtin::BI__sync_val_compare_and_swap_4:
927 case Builtin::BI__sync_val_compare_and_swap_8:
928 case Builtin::BI__sync_val_compare_and_swap_16:
929 case Builtin::BI__sync_bool_compare_and_swap:
930 case Builtin::BI__sync_bool_compare_and_swap_1:
931 case Builtin::BI__sync_bool_compare_and_swap_2:
932 case Builtin::BI__sync_bool_compare_and_swap_4:
933 case Builtin::BI__sync_bool_compare_and_swap_8:
934 case Builtin::BI__sync_bool_compare_and_swap_16:
935 case Builtin::BI__sync_lock_test_and_set:
936 case Builtin::BI__sync_lock_test_and_set_1:
937 case Builtin::BI__sync_lock_test_and_set_2:
938 case Builtin::BI__sync_lock_test_and_set_4:
939 case Builtin::BI__sync_lock_test_and_set_8:
940 case Builtin::BI__sync_lock_test_and_set_16:
941 case Builtin::BI__sync_lock_release:
942 case Builtin::BI__sync_lock_release_1:
943 case Builtin::BI__sync_lock_release_2:
944 case Builtin::BI__sync_lock_release_4:
945 case Builtin::BI__sync_lock_release_8:
946 case Builtin::BI__sync_lock_release_16:
947 case Builtin::BI__sync_swap:
948 case Builtin::BI__sync_swap_1:
949 case Builtin::BI__sync_swap_2:
950 case Builtin::BI__sync_swap_4:
951 case Builtin::BI__sync_swap_8:
952 case Builtin::BI__sync_swap_16:
953 return SemaBuiltinAtomicOverloaded(TheCallResult);
954 case Builtin::BI__builtin_nontemporal_load:
955 case Builtin::BI__builtin_nontemporal_store:
956 return SemaBuiltinNontemporalOverloaded(TheCallResult);
957 #define BUILTIN(ID, TYPE, ATTRS)
958 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
959 case Builtin::BI##ID: \
960 return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
961 #include "clang/Basic/Builtins.def"
962 case Builtin::BI__builtin_annotation:
966 case Builtin::BI__builtin_addressof:
970 case Builtin::BI__builtin_add_overflow:
971 case Builtin::BI__builtin_sub_overflow:
972 case Builtin::BI__builtin_mul_overflow:
976 case Builtin::BI__builtin_operator_new:
977 case Builtin::BI__builtin_operator_delete:
980 << (BuiltinID == Builtin::BI__builtin_operator_new
981 ?
"__builtin_operator_new"
982 :
"__builtin_operator_delete")
988 DeclareGlobalNewDelete();
993 case Builtin::BI__builtin___memcpy_chk:
994 case Builtin::BI__builtin___memmove_chk:
995 case Builtin::BI__builtin___memset_chk:
996 case Builtin::BI__builtin___strlcat_chk:
997 case Builtin::BI__builtin___strlcpy_chk:
998 case Builtin::BI__builtin___strncat_chk:
999 case Builtin::BI__builtin___strncpy_chk:
1000 case Builtin::BI__builtin___stpncpy_chk:
1003 case Builtin::BI__builtin___memccpy_chk:
1006 case Builtin::BI__builtin___snprintf_chk:
1007 case Builtin::BI__builtin___vsnprintf_chk:
1010 case Builtin::BI__builtin_call_with_static_chain:
1014 case Builtin::BI__exception_code:
1015 case Builtin::BI_exception_code:
1017 diag::err_seh___except_block))
1020 case Builtin::BI__exception_info:
1021 case Builtin::BI_exception_info:
1023 diag::err_seh___except_filter))
1026 case Builtin::BI__GetExceptionInfo:
1030 if (CheckCXXThrowOperand(
1039 case Builtin::BIread_pipe:
1040 case Builtin::BIwrite_pipe:
1047 case Builtin::BIreserve_read_pipe:
1048 case Builtin::BIreserve_write_pipe:
1049 case Builtin::BIwork_group_reserve_read_pipe:
1050 case Builtin::BIwork_group_reserve_write_pipe:
1051 case Builtin::BIsub_group_reserve_read_pipe:
1052 case Builtin::BIsub_group_reserve_write_pipe:
1060 case Builtin::BIcommit_read_pipe:
1061 case Builtin::BIcommit_write_pipe:
1062 case Builtin::BIwork_group_commit_read_pipe:
1063 case Builtin::BIwork_group_commit_write_pipe:
1064 case Builtin::BIsub_group_commit_read_pipe:
1065 case Builtin::BIsub_group_commit_write_pipe:
1069 case Builtin::BIget_pipe_num_packets:
1070 case Builtin::BIget_pipe_max_packets:
1075 case Builtin::BIto_global:
1076 case Builtin::BIto_local:
1077 case Builtin::BIto_private:
1082 case Builtin::BIenqueue_kernel:
1086 case Builtin::BIget_kernel_work_group_size:
1087 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1091 case Builtin::BI__builtin_os_log_format:
1092 case Builtin::BI__builtin_os_log_format_buffer_size:
1093 if (SemaBuiltinOSLogFormat(TheCall)) {
1103 case llvm::Triple::arm:
1104 case llvm::Triple::armeb:
1105 case llvm::Triple::thumb:
1106 case llvm::Triple::thumbeb:
1107 if (CheckARMBuiltinFunctionCall(BuiltinID, TheCall))
1110 case llvm::Triple::aarch64:
1111 case llvm::Triple::aarch64_be:
1112 if (CheckAArch64BuiltinFunctionCall(BuiltinID, TheCall))
1115 case llvm::Triple::mips:
1116 case llvm::Triple::mipsel:
1117 case llvm::Triple::mips64:
1118 case llvm::Triple::mips64el:
1119 if (CheckMipsBuiltinFunctionCall(BuiltinID, TheCall))
1122 case llvm::Triple::systemz:
1123 if (CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall))
1126 case llvm::Triple::x86:
1127 case llvm::Triple::x86_64:
1128 if (CheckX86BuiltinFunctionCall(BuiltinID, TheCall))
1131 case llvm::Triple::ppc:
1132 case llvm::Triple::ppc64:
1133 case llvm::Triple::ppc64le:
1134 if (CheckPPCBuiltinFunctionCall(BuiltinID, TheCall))
1142 return TheCallResult;
1146 static unsigned RFT(
unsigned t,
bool shift =
false,
bool ForceQuad =
false) {
1148 int IsQuad = ForceQuad ?
true : Type.
isQuad();
1152 return shift ? 7 : (8 << IsQuad) - 1;
1155 return shift ? 15 : (4 << IsQuad) - 1;
1157 return shift ? 31 : (2 << IsQuad) - 1;
1160 return shift ? 63 : (1 << IsQuad) - 1;
1162 return shift ? 127 : (1 << IsQuad) - 1;
1164 assert(!shift &&
"cannot shift float types!");
1165 return (4 << IsQuad) - 1;
1167 assert(!shift &&
"cannot shift float types!");
1168 return (2 << IsQuad) - 1;
1170 assert(!shift &&
"cannot shift float types!");
1171 return (1 << IsQuad) - 1;
1173 llvm_unreachable(
"Invalid NeonTypeFlag!");
1180 bool IsPolyUnsigned,
bool IsInt64Long) {
1212 llvm_unreachable(
"Invalid NeonTypeFlag!");
1215 bool Sema::CheckNeonBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1216 llvm::APSInt Result;
1220 bool HasConstPtr =
false;
1221 switch (BuiltinID) {
1222 #define GET_NEON_OVERLOAD_CHECK
1223 #include "clang/Basic/arm_neon.inc"
1224 #undef GET_NEON_OVERLOAD_CHECK
1231 if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
1234 TV = Result.getLimitedValue(64);
1235 if ((TV > 63) || (mask & (1ULL << TV)) == 0)
1240 if (PtrArgNum >= 0) {
1244 Arg = ICE->getSubExpr();
1245 ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
1249 bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
1250 Arch == llvm::Triple::aarch64_be;
1258 AssignConvertType ConvTy;
1259 ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
1262 if (DiagnoseAssignmentResult(ConvTy, Arg->
getLocStart(), LHSTy, RHSTy,
1263 RHS.
get(), AA_Assigning))
1269 unsigned i = 0, l = 0, u = 0;
1270 switch (BuiltinID) {
1273 #define GET_NEON_IMMEDIATE_CHECK
1274 #include "clang/Basic/arm_neon.inc"
1275 #undef GET_NEON_IMMEDIATE_CHECK
1278 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1281 bool Sema::CheckARMBuiltinExclusiveCall(
unsigned BuiltinID,
CallExpr *TheCall,
1282 unsigned MaxWidth) {
1283 assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
1284 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1285 BuiltinID == ARM::BI__builtin_arm_strex ||
1286 BuiltinID == ARM::BI__builtin_arm_stlex ||
1287 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1288 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1289 BuiltinID == AArch64::BI__builtin_arm_strex ||
1290 BuiltinID == AArch64::BI__builtin_arm_stlex) &&
1291 "unexpected ARM builtin");
1292 bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
1293 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1294 BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1295 BuiltinID == AArch64::BI__builtin_arm_ldaex;
1307 Expr *PointerArg = TheCall->
getArg(IsLdrex ? 0 : 1);
1308 ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
1311 PointerArg = PointerArgRes.
get();
1331 CastNeeded = CK_BitCast;
1332 Diag(DRE->
getLocStart(), diag::ext_typecheck_convert_discards_qualifiers)
1340 PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
1343 PointerArg = PointerArgRes.
get();
1345 TheCall->
setArg(IsLdrex ? 0 : 1, PointerArg);
1350 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
1357 assert(MaxWidth == 64 &&
"Diagnostic unexpectedly inaccurate");
1358 Diag(DRE->
getLocStart(), diag::err_atomic_exclusive_builtin_pointer_size)
1386 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
1397 bool Sema::CheckARMBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1398 if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
1399 BuiltinID == ARM::BI__builtin_arm_ldaex ||
1400 BuiltinID == ARM::BI__builtin_arm_strex ||
1401 BuiltinID == ARM::BI__builtin_arm_stlex) {
1402 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
1405 if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
1406 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1407 SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
1410 if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
1411 BuiltinID == ARM::BI__builtin_arm_wsr64)
1412 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3,
false);
1414 if (BuiltinID == ARM::BI__builtin_arm_rsr ||
1415 BuiltinID == ARM::BI__builtin_arm_rsrp ||
1416 BuiltinID == ARM::BI__builtin_arm_wsr ||
1417 BuiltinID == ARM::BI__builtin_arm_wsrp)
1418 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1420 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1425 unsigned i = 0, l = 0, u = 0;
1426 switch (BuiltinID) {
1427 default:
return false;
1428 case ARM::BI__builtin_arm_ssat: i = 1; l = 1; u = 31;
break;
1429 case ARM::BI__builtin_arm_usat: i = 1; u = 31;
break;
1430 case ARM::BI__builtin_arm_vcvtr_f:
1431 case ARM::BI__builtin_arm_vcvtr_d: i = 1; u = 1;
break;
1432 case ARM::BI__builtin_arm_dmb:
1433 case ARM::BI__builtin_arm_dsb:
1434 case ARM::BI__builtin_arm_isb:
1435 case ARM::BI__builtin_arm_dbg: l = 0; u = 15;
break;
1439 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1442 bool Sema::CheckAArch64BuiltinFunctionCall(
unsigned BuiltinID,
1444 if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
1445 BuiltinID == AArch64::BI__builtin_arm_ldaex ||
1446 BuiltinID == AArch64::BI__builtin_arm_strex ||
1447 BuiltinID == AArch64::BI__builtin_arm_stlex) {
1448 return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
1451 if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
1452 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1453 SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
1454 SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
1455 SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
1458 if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
1459 BuiltinID == AArch64::BI__builtin_arm_wsr64)
1460 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1462 if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
1463 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
1464 BuiltinID == AArch64::BI__builtin_arm_wsr ||
1465 BuiltinID == AArch64::BI__builtin_arm_wsrp)
1466 return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5,
true);
1468 if (CheckNeonBuiltinFunctionCall(BuiltinID, TheCall))
1473 unsigned i = 0, l = 0, u = 0;
1474 switch (BuiltinID) {
1475 default:
return false;
1476 case AArch64::BI__builtin_arm_dmb:
1477 case AArch64::BI__builtin_arm_dsb:
1478 case AArch64::BI__builtin_arm_isb: l = 0; u = 15;
break;
1481 return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
1493 bool Sema::CheckMipsBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1494 unsigned i = 0, l = 0, u = 0, m = 0;
1495 switch (BuiltinID) {
1496 default:
return false;
1497 case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63;
break;
1498 case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63;
break;
1499 case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31;
break;
1500 case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3;
break;
1501 case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31;
break;
1502 case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31;
break;
1503 case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31;
break;
1507 case Mips::BI__builtin_msa_bclri_b:
1508 case Mips::BI__builtin_msa_bnegi_b:
1509 case Mips::BI__builtin_msa_bseti_b:
1510 case Mips::BI__builtin_msa_sat_s_b:
1511 case Mips::BI__builtin_msa_sat_u_b:
1512 case Mips::BI__builtin_msa_slli_b:
1513 case Mips::BI__builtin_msa_srai_b:
1514 case Mips::BI__builtin_msa_srari_b:
1515 case Mips::BI__builtin_msa_srli_b:
1516 case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7;
break;
1517 case Mips::BI__builtin_msa_binsli_b:
1518 case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7;
break;
1520 case Mips::BI__builtin_msa_bclri_h:
1521 case Mips::BI__builtin_msa_bnegi_h:
1522 case Mips::BI__builtin_msa_bseti_h:
1523 case Mips::BI__builtin_msa_sat_s_h:
1524 case Mips::BI__builtin_msa_sat_u_h:
1525 case Mips::BI__builtin_msa_slli_h:
1526 case Mips::BI__builtin_msa_srai_h:
1527 case Mips::BI__builtin_msa_srari_h:
1528 case Mips::BI__builtin_msa_srli_h:
1529 case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15;
break;
1530 case Mips::BI__builtin_msa_binsli_h:
1531 case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15;
break;
1535 case Mips::BI__builtin_msa_clei_u_b:
1536 case Mips::BI__builtin_msa_clei_u_h:
1537 case Mips::BI__builtin_msa_clei_u_w:
1538 case Mips::BI__builtin_msa_clei_u_d:
1539 case Mips::BI__builtin_msa_clti_u_b:
1540 case Mips::BI__builtin_msa_clti_u_h:
1541 case Mips::BI__builtin_msa_clti_u_w:
1542 case Mips::BI__builtin_msa_clti_u_d:
1543 case Mips::BI__builtin_msa_maxi_u_b:
1544 case Mips::BI__builtin_msa_maxi_u_h:
1545 case Mips::BI__builtin_msa_maxi_u_w:
1546 case Mips::BI__builtin_msa_maxi_u_d:
1547 case Mips::BI__builtin_msa_mini_u_b:
1548 case Mips::BI__builtin_msa_mini_u_h:
1549 case Mips::BI__builtin_msa_mini_u_w:
1550 case Mips::BI__builtin_msa_mini_u_d:
1551 case Mips::BI__builtin_msa_addvi_b:
1552 case Mips::BI__builtin_msa_addvi_h:
1553 case Mips::BI__builtin_msa_addvi_w:
1554 case Mips::BI__builtin_msa_addvi_d:
1555 case Mips::BI__builtin_msa_bclri_w:
1556 case Mips::BI__builtin_msa_bnegi_w:
1557 case Mips::BI__builtin_msa_bseti_w:
1558 case Mips::BI__builtin_msa_sat_s_w:
1559 case Mips::BI__builtin_msa_sat_u_w:
1560 case Mips::BI__builtin_msa_slli_w:
1561 case Mips::BI__builtin_msa_srai_w:
1562 case Mips::BI__builtin_msa_srari_w:
1563 case Mips::BI__builtin_msa_srli_w:
1564 case Mips::BI__builtin_msa_srlri_w:
1565 case Mips::BI__builtin_msa_subvi_b:
1566 case Mips::BI__builtin_msa_subvi_h:
1567 case Mips::BI__builtin_msa_subvi_w:
1568 case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31;
break;
1569 case Mips::BI__builtin_msa_binsli_w:
1570 case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31;
break;
1572 case Mips::BI__builtin_msa_bclri_d:
1573 case Mips::BI__builtin_msa_bnegi_d:
1574 case Mips::BI__builtin_msa_bseti_d:
1575 case Mips::BI__builtin_msa_sat_s_d:
1576 case Mips::BI__builtin_msa_sat_u_d:
1577 case Mips::BI__builtin_msa_slli_d:
1578 case Mips::BI__builtin_msa_srai_d:
1579 case Mips::BI__builtin_msa_srari_d:
1580 case Mips::BI__builtin_msa_srli_d:
1581 case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63;
break;
1582 case Mips::BI__builtin_msa_binsli_d:
1583 case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63;
break;
1585 case Mips::BI__builtin_msa_ceqi_b:
1586 case Mips::BI__builtin_msa_ceqi_h:
1587 case Mips::BI__builtin_msa_ceqi_w:
1588 case Mips::BI__builtin_msa_ceqi_d:
1589 case Mips::BI__builtin_msa_clti_s_b:
1590 case Mips::BI__builtin_msa_clti_s_h:
1591 case Mips::BI__builtin_msa_clti_s_w:
1592 case Mips::BI__builtin_msa_clti_s_d:
1593 case Mips::BI__builtin_msa_clei_s_b:
1594 case Mips::BI__builtin_msa_clei_s_h:
1595 case Mips::BI__builtin_msa_clei_s_w:
1596 case Mips::BI__builtin_msa_clei_s_d:
1597 case Mips::BI__builtin_msa_maxi_s_b:
1598 case Mips::BI__builtin_msa_maxi_s_h:
1599 case Mips::BI__builtin_msa_maxi_s_w:
1600 case Mips::BI__builtin_msa_maxi_s_d:
1601 case Mips::BI__builtin_msa_mini_s_b:
1602 case Mips::BI__builtin_msa_mini_s_h:
1603 case Mips::BI__builtin_msa_mini_s_w:
1604 case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15;
break;
1606 case Mips::BI__builtin_msa_andi_b:
1607 case Mips::BI__builtin_msa_nori_b:
1608 case Mips::BI__builtin_msa_ori_b:
1609 case Mips::BI__builtin_msa_shf_b:
1610 case Mips::BI__builtin_msa_shf_h:
1611 case Mips::BI__builtin_msa_shf_w:
1612 case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255;
break;
1613 case Mips::BI__builtin_msa_bseli_b:
1614 case Mips::BI__builtin_msa_bmnzi_b:
1615 case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255;
break;
1618 case Mips::BI__builtin_msa_copy_s_b:
1619 case Mips::BI__builtin_msa_copy_u_b:
1620 case Mips::BI__builtin_msa_insve_b:
1621 case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15;
break;
1622 case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15;
break;
1624 case Mips::BI__builtin_msa_copy_s_h:
1625 case Mips::BI__builtin_msa_copy_u_h:
1626 case Mips::BI__builtin_msa_insve_h:
1627 case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7;
break;
1628 case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7;
break;
1630 case Mips::BI__builtin_msa_copy_s_w:
1631 case Mips::BI__builtin_msa_copy_u_w:
1632 case Mips::BI__builtin_msa_insve_w:
1633 case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3;
break;
1634 case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3;
break;
1636 case Mips::BI__builtin_msa_copy_s_d:
1637 case Mips::BI__builtin_msa_copy_u_d:
1638 case Mips::BI__builtin_msa_insve_d:
1639 case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1;
break;
1640 case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1;
break;
1643 case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255;
break;
1644 case Mips::BI__builtin_msa_ldi_h:
1645 case Mips::BI__builtin_msa_ldi_w:
1646 case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511;
break;
1647 case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 16;
break;
1648 case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 16;
break;
1649 case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 16;
break;
1650 case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 16;
break;
1651 case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 16;
break;
1652 case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 16;
break;
1653 case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 16;
break;
1654 case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 16;
break;
1658 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1660 return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
1661 SemaBuiltinConstantArgMultiple(TheCall, i, m);
1664 bool Sema::CheckPPCBuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
1665 unsigned i = 0, l = 0, u = 0;
1666 bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
1667 BuiltinID == PPC::BI__builtin_divdeu ||
1668 BuiltinID == PPC::BI__builtin_bpermd;
1672 .getIntPtrType()) == 64;
1673 bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
1674 BuiltinID == PPC::BI__builtin_divweu ||
1675 BuiltinID == PPC::BI__builtin_divde ||
1676 BuiltinID == PPC::BI__builtin_divdeu;
1678 if (Is64BitBltin && !IsTarget64Bit)
1679 return Diag(TheCall->
getLocStart(), diag::err_64_bit_builtin_32_bit_tgt)
1683 (BuiltinID == PPC::BI__builtin_bpermd &&
1685 return Diag(TheCall->
getLocStart(), diag::err_ppc_builtin_only_on_pwr7)
1688 switch (BuiltinID) {
1689 default:
return false;
1690 case PPC::BI__builtin_altivec_crypto_vshasigmaw:
1691 case PPC::BI__builtin_altivec_crypto_vshasigmad:
1692 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
1693 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1694 case PPC::BI__builtin_tbegin:
1695 case PPC::BI__builtin_tend: i = 0; l = 0; u = 1;
break;
1696 case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7;
break;
1697 case PPC::BI__builtin_tabortwc:
1698 case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31;
break;
1699 case PPC::BI__builtin_tabortwci:
1700 case PPC::BI__builtin_tabortdci:
1701 return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
1702 SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
1703 case PPC::BI__builtin_vsx_xxpermdi:
1704 case PPC::BI__builtin_vsx_xxsldwi:
1705 return SemaBuiltinVSX(TheCall);
1707 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1710 bool Sema::CheckSystemZBuiltinFunctionCall(
unsigned BuiltinID,
1712 if (BuiltinID == SystemZ::BI__builtin_tabort) {
1714 llvm::APSInt AbortCode(32);
1716 AbortCode.getSExtValue() >= 0 && AbortCode.getSExtValue() < 256)
1717 return Diag(Arg->
getLocStart(), diag::err_systemz_invalid_tabort_code)
1723 unsigned i = 0, l = 0, u = 0;
1724 switch (BuiltinID) {
1725 default:
return false;
1726 case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15;
break;
1727 case SystemZ::BI__builtin_s390_verimb:
1728 case SystemZ::BI__builtin_s390_verimh:
1729 case SystemZ::BI__builtin_s390_verimf:
1730 case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255;
break;
1731 case SystemZ::BI__builtin_s390_vfaeb:
1732 case SystemZ::BI__builtin_s390_vfaeh:
1733 case SystemZ::BI__builtin_s390_vfaef:
1734 case SystemZ::BI__builtin_s390_vfaebs:
1735 case SystemZ::BI__builtin_s390_vfaehs:
1736 case SystemZ::BI__builtin_s390_vfaefs:
1737 case SystemZ::BI__builtin_s390_vfaezb:
1738 case SystemZ::BI__builtin_s390_vfaezh:
1739 case SystemZ::BI__builtin_s390_vfaezf:
1740 case SystemZ::BI__builtin_s390_vfaezbs:
1741 case SystemZ::BI__builtin_s390_vfaezhs:
1742 case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15;
break;
1743 case SystemZ::BI__builtin_s390_vfisb:
1744 case SystemZ::BI__builtin_s390_vfidb:
1745 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
1746 SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
1747 case SystemZ::BI__builtin_s390_vftcisb:
1748 case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095;
break;
1749 case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15;
break;
1750 case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15;
break;
1751 case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15;
break;
1752 case SystemZ::BI__builtin_s390_vstrcb:
1753 case SystemZ::BI__builtin_s390_vstrch:
1754 case SystemZ::BI__builtin_s390_vstrcf:
1755 case SystemZ::BI__builtin_s390_vstrczb:
1756 case SystemZ::BI__builtin_s390_vstrczh:
1757 case SystemZ::BI__builtin_s390_vstrczf:
1758 case SystemZ::BI__builtin_s390_vstrcbs:
1759 case SystemZ::BI__builtin_s390_vstrchs:
1760 case SystemZ::BI__builtin_s390_vstrcfs:
1761 case SystemZ::BI__builtin_s390_vstrczbs:
1762 case SystemZ::BI__builtin_s390_vstrczhs:
1763 case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15;
break;
1764 case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15;
break;
1765 case SystemZ::BI__builtin_s390_vfminsb:
1766 case SystemZ::BI__builtin_s390_vfmaxsb:
1767 case SystemZ::BI__builtin_s390_vfmindb:
1768 case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15;
break;
1770 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
1781 return S.
Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
1794 bool Sema::CheckX86BuiltinRoundingOrSAE(
unsigned BuiltinID,
CallExpr *TheCall) {
1798 unsigned ArgNum = 0;
1799 switch (BuiltinID) {
1802 case X86::BI__builtin_ia32_vcvttsd2si32:
1803 case X86::BI__builtin_ia32_vcvttsd2si64:
1804 case X86::BI__builtin_ia32_vcvttsd2usi32:
1805 case X86::BI__builtin_ia32_vcvttsd2usi64:
1806 case X86::BI__builtin_ia32_vcvttss2si32:
1807 case X86::BI__builtin_ia32_vcvttss2si64:
1808 case X86::BI__builtin_ia32_vcvttss2usi32:
1809 case X86::BI__builtin_ia32_vcvttss2usi64:
1812 case X86::BI__builtin_ia32_cvtps2pd512_mask:
1813 case X86::BI__builtin_ia32_cvttpd2dq512_mask:
1814 case X86::BI__builtin_ia32_cvttpd2qq512_mask:
1815 case X86::BI__builtin_ia32_cvttpd2udq512_mask:
1816 case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
1817 case X86::BI__builtin_ia32_cvttps2dq512_mask:
1818 case X86::BI__builtin_ia32_cvttps2qq512_mask:
1819 case X86::BI__builtin_ia32_cvttps2udq512_mask:
1820 case X86::BI__builtin_ia32_cvttps2uqq512_mask:
1821 case X86::BI__builtin_ia32_exp2pd_mask:
1822 case X86::BI__builtin_ia32_exp2ps_mask:
1823 case X86::BI__builtin_ia32_getexppd512_mask:
1824 case X86::BI__builtin_ia32_getexpps512_mask:
1825 case X86::BI__builtin_ia32_rcp28pd_mask:
1826 case X86::BI__builtin_ia32_rcp28ps_mask:
1827 case X86::BI__builtin_ia32_rsqrt28pd_mask:
1828 case X86::BI__builtin_ia32_rsqrt28ps_mask:
1829 case X86::BI__builtin_ia32_vcomisd:
1830 case X86::BI__builtin_ia32_vcomiss:
1831 case X86::BI__builtin_ia32_vcvtph2ps512_mask:
1834 case X86::BI__builtin_ia32_cmppd512_mask:
1835 case X86::BI__builtin_ia32_cmpps512_mask:
1836 case X86::BI__builtin_ia32_cmpsd_mask:
1837 case X86::BI__builtin_ia32_cmpss_mask:
1838 case X86::BI__builtin_ia32_cvtss2sd_round_mask:
1839 case X86::BI__builtin_ia32_getexpsd128_round_mask:
1840 case X86::BI__builtin_ia32_getexpss128_round_mask:
1841 case X86::BI__builtin_ia32_maxpd512_mask:
1842 case X86::BI__builtin_ia32_maxps512_mask:
1843 case X86::BI__builtin_ia32_maxsd_round_mask:
1844 case X86::BI__builtin_ia32_maxss_round_mask:
1845 case X86::BI__builtin_ia32_minpd512_mask:
1846 case X86::BI__builtin_ia32_minps512_mask:
1847 case X86::BI__builtin_ia32_minsd_round_mask:
1848 case X86::BI__builtin_ia32_minss_round_mask:
1849 case X86::BI__builtin_ia32_rcp28sd_round_mask:
1850 case X86::BI__builtin_ia32_rcp28ss_round_mask:
1851 case X86::BI__builtin_ia32_reducepd512_mask:
1852 case X86::BI__builtin_ia32_reduceps512_mask:
1853 case X86::BI__builtin_ia32_rndscalepd_mask:
1854 case X86::BI__builtin_ia32_rndscaleps_mask:
1855 case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
1856 case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
1859 case X86::BI__builtin_ia32_fixupimmpd512_mask:
1860 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
1861 case X86::BI__builtin_ia32_fixupimmps512_mask:
1862 case X86::BI__builtin_ia32_fixupimmps512_maskz:
1863 case X86::BI__builtin_ia32_fixupimmsd_mask:
1864 case X86::BI__builtin_ia32_fixupimmsd_maskz:
1865 case X86::BI__builtin_ia32_fixupimmss_mask:
1866 case X86::BI__builtin_ia32_fixupimmss_maskz:
1867 case X86::BI__builtin_ia32_rangepd512_mask:
1868 case X86::BI__builtin_ia32_rangeps512_mask:
1869 case X86::BI__builtin_ia32_rangesd128_round_mask:
1870 case X86::BI__builtin_ia32_rangess128_round_mask:
1871 case X86::BI__builtin_ia32_reducesd_mask:
1872 case X86::BI__builtin_ia32_reducess_mask:
1873 case X86::BI__builtin_ia32_rndscalesd_round_mask:
1874 case X86::BI__builtin_ia32_rndscaless_round_mask:
1877 case X86::BI__builtin_ia32_vcvtsd2si64:
1878 case X86::BI__builtin_ia32_vcvtsd2si32:
1879 case X86::BI__builtin_ia32_vcvtsd2usi32:
1880 case X86::BI__builtin_ia32_vcvtsd2usi64:
1881 case X86::BI__builtin_ia32_vcvtss2si32:
1882 case X86::BI__builtin_ia32_vcvtss2si64:
1883 case X86::BI__builtin_ia32_vcvtss2usi32:
1884 case X86::BI__builtin_ia32_vcvtss2usi64:
1888 case X86::BI__builtin_ia32_cvtsi2sd64:
1889 case X86::BI__builtin_ia32_cvtsi2ss32:
1890 case X86::BI__builtin_ia32_cvtsi2ss64:
1891 case X86::BI__builtin_ia32_cvtusi2sd64:
1892 case X86::BI__builtin_ia32_cvtusi2ss32:
1893 case X86::BI__builtin_ia32_cvtusi2ss64:
1897 case X86::BI__builtin_ia32_cvtdq2ps512_mask:
1898 case X86::BI__builtin_ia32_cvtudq2ps512_mask:
1899 case X86::BI__builtin_ia32_cvtpd2ps512_mask:
1900 case X86::BI__builtin_ia32_cvtpd2qq512_mask:
1901 case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
1902 case X86::BI__builtin_ia32_cvtps2qq512_mask:
1903 case X86::BI__builtin_ia32_cvtps2uqq512_mask:
1904 case X86::BI__builtin_ia32_cvtqq2pd512_mask:
1905 case X86::BI__builtin_ia32_cvtqq2ps512_mask:
1906 case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
1907 case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
1908 case X86::BI__builtin_ia32_sqrtpd512_mask:
1909 case X86::BI__builtin_ia32_sqrtps512_mask:
1913 case X86::BI__builtin_ia32_addpd512_mask:
1914 case X86::BI__builtin_ia32_addps512_mask:
1915 case X86::BI__builtin_ia32_divpd512_mask:
1916 case X86::BI__builtin_ia32_divps512_mask:
1917 case X86::BI__builtin_ia32_mulpd512_mask:
1918 case X86::BI__builtin_ia32_mulps512_mask:
1919 case X86::BI__builtin_ia32_subpd512_mask:
1920 case X86::BI__builtin_ia32_subps512_mask:
1921 case X86::BI__builtin_ia32_addss_round_mask:
1922 case X86::BI__builtin_ia32_addsd_round_mask:
1923 case X86::BI__builtin_ia32_divss_round_mask:
1924 case X86::BI__builtin_ia32_divsd_round_mask:
1925 case X86::BI__builtin_ia32_mulss_round_mask:
1926 case X86::BI__builtin_ia32_mulsd_round_mask:
1927 case X86::BI__builtin_ia32_subss_round_mask:
1928 case X86::BI__builtin_ia32_subsd_round_mask:
1929 case X86::BI__builtin_ia32_scalefpd512_mask:
1930 case X86::BI__builtin_ia32_scalefps512_mask:
1931 case X86::BI__builtin_ia32_scalefsd_round_mask:
1932 case X86::BI__builtin_ia32_scalefss_round_mask:
1933 case X86::BI__builtin_ia32_getmantpd512_mask:
1934 case X86::BI__builtin_ia32_getmantps512_mask:
1935 case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
1936 case X86::BI__builtin_ia32_sqrtsd_round_mask:
1937 case X86::BI__builtin_ia32_sqrtss_round_mask:
1938 case X86::BI__builtin_ia32_vfmaddpd512_mask:
1939 case X86::BI__builtin_ia32_vfmaddpd512_mask3:
1940 case X86::BI__builtin_ia32_vfmaddpd512_maskz:
1941 case X86::BI__builtin_ia32_vfmaddps512_mask:
1942 case X86::BI__builtin_ia32_vfmaddps512_mask3:
1943 case X86::BI__builtin_ia32_vfmaddps512_maskz:
1944 case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
1945 case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
1946 case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
1947 case X86::BI__builtin_ia32_vfmaddsubps512_mask:
1948 case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
1949 case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
1950 case X86::BI__builtin_ia32_vfmsubpd512_mask3:
1951 case X86::BI__builtin_ia32_vfmsubps512_mask3:
1952 case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
1953 case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
1954 case X86::BI__builtin_ia32_vfnmaddpd512_mask:
1955 case X86::BI__builtin_ia32_vfnmaddps512_mask:
1956 case X86::BI__builtin_ia32_vfnmsubpd512_mask:
1957 case X86::BI__builtin_ia32_vfnmsubpd512_mask3:
1958 case X86::BI__builtin_ia32_vfnmsubps512_mask:
1959 case X86::BI__builtin_ia32_vfnmsubps512_mask3:
1960 case X86::BI__builtin_ia32_vfmaddsd3_mask:
1961 case X86::BI__builtin_ia32_vfmaddsd3_maskz:
1962 case X86::BI__builtin_ia32_vfmaddsd3_mask3:
1963 case X86::BI__builtin_ia32_vfmaddss3_mask:
1964 case X86::BI__builtin_ia32_vfmaddss3_maskz:
1965 case X86::BI__builtin_ia32_vfmaddss3_mask3:
1969 case X86::BI__builtin_ia32_getmantsd_round_mask:
1970 case X86::BI__builtin_ia32_getmantss_round_mask:
1976 llvm::APSInt Result;
1984 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
1992 (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
1995 return Diag(TheCall->
getLocStart(), diag::err_x86_builtin_invalid_rounding)
2000 bool Sema::CheckX86BuiltinGatherScatterScale(
unsigned BuiltinID,
2002 unsigned ArgNum = 0;
2003 switch (BuiltinID) {
2006 case X86::BI__builtin_ia32_gatherpfdpd:
2007 case X86::BI__builtin_ia32_gatherpfdps:
2008 case X86::BI__builtin_ia32_gatherpfqpd:
2009 case X86::BI__builtin_ia32_gatherpfqps:
2010 case X86::BI__builtin_ia32_scatterpfdpd:
2011 case X86::BI__builtin_ia32_scatterpfdps:
2012 case X86::BI__builtin_ia32_scatterpfqpd:
2013 case X86::BI__builtin_ia32_scatterpfqps:
2016 case X86::BI__builtin_ia32_gatherd_pd:
2017 case X86::BI__builtin_ia32_gatherd_pd256:
2018 case X86::BI__builtin_ia32_gatherq_pd:
2019 case X86::BI__builtin_ia32_gatherq_pd256:
2020 case X86::BI__builtin_ia32_gatherd_ps:
2021 case X86::BI__builtin_ia32_gatherd_ps256:
2022 case X86::BI__builtin_ia32_gatherq_ps:
2023 case X86::BI__builtin_ia32_gatherq_ps256:
2024 case X86::BI__builtin_ia32_gatherd_q:
2025 case X86::BI__builtin_ia32_gatherd_q256:
2026 case X86::BI__builtin_ia32_gatherq_q:
2027 case X86::BI__builtin_ia32_gatherq_q256:
2028 case X86::BI__builtin_ia32_gatherd_d:
2029 case X86::BI__builtin_ia32_gatherd_d256:
2030 case X86::BI__builtin_ia32_gatherq_d:
2031 case X86::BI__builtin_ia32_gatherq_d256:
2032 case X86::BI__builtin_ia32_gather3div2df:
2033 case X86::BI__builtin_ia32_gather3div2di:
2034 case X86::BI__builtin_ia32_gather3div4df:
2035 case X86::BI__builtin_ia32_gather3div4di:
2036 case X86::BI__builtin_ia32_gather3div4sf:
2037 case X86::BI__builtin_ia32_gather3div4si:
2038 case X86::BI__builtin_ia32_gather3div8sf:
2039 case X86::BI__builtin_ia32_gather3div8si:
2040 case X86::BI__builtin_ia32_gather3siv2df:
2041 case X86::BI__builtin_ia32_gather3siv2di:
2042 case X86::BI__builtin_ia32_gather3siv4df:
2043 case X86::BI__builtin_ia32_gather3siv4di:
2044 case X86::BI__builtin_ia32_gather3siv4sf:
2045 case X86::BI__builtin_ia32_gather3siv4si:
2046 case X86::BI__builtin_ia32_gather3siv8sf:
2047 case X86::BI__builtin_ia32_gather3siv8si:
2048 case X86::BI__builtin_ia32_gathersiv8df:
2049 case X86::BI__builtin_ia32_gathersiv16sf:
2050 case X86::BI__builtin_ia32_gatherdiv8df:
2051 case X86::BI__builtin_ia32_gatherdiv16sf:
2052 case X86::BI__builtin_ia32_gathersiv8di:
2053 case X86::BI__builtin_ia32_gathersiv16si:
2054 case X86::BI__builtin_ia32_gatherdiv8di:
2055 case X86::BI__builtin_ia32_gatherdiv16si:
2056 case X86::BI__builtin_ia32_scatterdiv2df:
2057 case X86::BI__builtin_ia32_scatterdiv2di:
2058 case X86::BI__builtin_ia32_scatterdiv4df:
2059 case X86::BI__builtin_ia32_scatterdiv4di:
2060 case X86::BI__builtin_ia32_scatterdiv4sf:
2061 case X86::BI__builtin_ia32_scatterdiv4si:
2062 case X86::BI__builtin_ia32_scatterdiv8sf:
2063 case X86::BI__builtin_ia32_scatterdiv8si:
2064 case X86::BI__builtin_ia32_scattersiv2df:
2065 case X86::BI__builtin_ia32_scattersiv2di:
2066 case X86::BI__builtin_ia32_scattersiv4df:
2067 case X86::BI__builtin_ia32_scattersiv4di:
2068 case X86::BI__builtin_ia32_scattersiv4sf:
2069 case X86::BI__builtin_ia32_scattersiv4si:
2070 case X86::BI__builtin_ia32_scattersiv8sf:
2071 case X86::BI__builtin_ia32_scattersiv8si:
2072 case X86::BI__builtin_ia32_scattersiv8df:
2073 case X86::BI__builtin_ia32_scattersiv16sf:
2074 case X86::BI__builtin_ia32_scatterdiv8df:
2075 case X86::BI__builtin_ia32_scatterdiv16sf:
2076 case X86::BI__builtin_ia32_scattersiv8di:
2077 case X86::BI__builtin_ia32_scattersiv16si:
2078 case X86::BI__builtin_ia32_scatterdiv8di:
2079 case X86::BI__builtin_ia32_scatterdiv16si:
2084 llvm::APSInt Result;
2092 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
2095 if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
2098 return Diag(TheCall->
getLocStart(), diag::err_x86_builtin_invalid_scale)
2102 bool Sema::CheckX86BuiltinFunctionCall(
unsigned BuiltinID,
CallExpr *TheCall) {
2103 if (BuiltinID == X86::BI__builtin_cpu_supports)
2107 if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
2111 if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
2116 int i = 0, l = 0, u = 0;
2117 switch (BuiltinID) {
2120 case X86::BI_mm_prefetch:
2121 i = 1; l = 0; u = 3;
2123 case X86::BI__builtin_ia32_sha1rnds4:
2124 case X86::BI__builtin_ia32_shuf_f32x4_256_mask:
2125 case X86::BI__builtin_ia32_shuf_f64x2_256_mask:
2126 case X86::BI__builtin_ia32_shuf_i32x4_256_mask:
2127 case X86::BI__builtin_ia32_shuf_i64x2_256_mask:
2128 i = 2; l = 0; u = 3;
2130 case X86::BI__builtin_ia32_vpermil2pd:
2131 case X86::BI__builtin_ia32_vpermil2pd256:
2132 case X86::BI__builtin_ia32_vpermil2ps:
2133 case X86::BI__builtin_ia32_vpermil2ps256:
2134 i = 3; l = 0; u = 3;
2136 case X86::BI__builtin_ia32_cmpb128_mask:
2137 case X86::BI__builtin_ia32_cmpw128_mask:
2138 case X86::BI__builtin_ia32_cmpd128_mask:
2139 case X86::BI__builtin_ia32_cmpq128_mask:
2140 case X86::BI__builtin_ia32_cmpb256_mask:
2141 case X86::BI__builtin_ia32_cmpw256_mask:
2142 case X86::BI__builtin_ia32_cmpd256_mask:
2143 case X86::BI__builtin_ia32_cmpq256_mask:
2144 case X86::BI__builtin_ia32_cmpb512_mask:
2145 case X86::BI__builtin_ia32_cmpw512_mask:
2146 case X86::BI__builtin_ia32_cmpd512_mask:
2147 case X86::BI__builtin_ia32_cmpq512_mask:
2148 case X86::BI__builtin_ia32_ucmpb128_mask:
2149 case X86::BI__builtin_ia32_ucmpw128_mask:
2150 case X86::BI__builtin_ia32_ucmpd128_mask:
2151 case X86::BI__builtin_ia32_ucmpq128_mask:
2152 case X86::BI__builtin_ia32_ucmpb256_mask:
2153 case X86::BI__builtin_ia32_ucmpw256_mask:
2154 case X86::BI__builtin_ia32_ucmpd256_mask:
2155 case X86::BI__builtin_ia32_ucmpq256_mask:
2156 case X86::BI__builtin_ia32_ucmpb512_mask:
2157 case X86::BI__builtin_ia32_ucmpw512_mask:
2158 case X86::BI__builtin_ia32_ucmpd512_mask:
2159 case X86::BI__builtin_ia32_ucmpq512_mask:
2160 case X86::BI__builtin_ia32_vpcomub:
2161 case X86::BI__builtin_ia32_vpcomuw:
2162 case X86::BI__builtin_ia32_vpcomud:
2163 case X86::BI__builtin_ia32_vpcomuq:
2164 case X86::BI__builtin_ia32_vpcomb:
2165 case X86::BI__builtin_ia32_vpcomw:
2166 case X86::BI__builtin_ia32_vpcomd:
2167 case X86::BI__builtin_ia32_vpcomq:
2168 i = 2; l = 0; u = 7;
2170 case X86::BI__builtin_ia32_roundps:
2171 case X86::BI__builtin_ia32_roundpd:
2172 case X86::BI__builtin_ia32_roundps256:
2173 case X86::BI__builtin_ia32_roundpd256:
2174 i = 1; l = 0; u = 15;
2176 case X86::BI__builtin_ia32_roundss:
2177 case X86::BI__builtin_ia32_roundsd:
2178 case X86::BI__builtin_ia32_rangepd128_mask:
2179 case X86::BI__builtin_ia32_rangepd256_mask:
2180 case X86::BI__builtin_ia32_rangepd512_mask:
2181 case X86::BI__builtin_ia32_rangeps128_mask:
2182 case X86::BI__builtin_ia32_rangeps256_mask:
2183 case X86::BI__builtin_ia32_rangeps512_mask:
2184 case X86::BI__builtin_ia32_getmantsd_round_mask:
2185 case X86::BI__builtin_ia32_getmantss_round_mask:
2186 i = 2; l = 0; u = 15;
2188 case X86::BI__builtin_ia32_cmpps:
2189 case X86::BI__builtin_ia32_cmpss:
2190 case X86::BI__builtin_ia32_cmppd:
2191 case X86::BI__builtin_ia32_cmpsd:
2192 case X86::BI__builtin_ia32_cmpps256:
2193 case X86::BI__builtin_ia32_cmppd256:
2194 case X86::BI__builtin_ia32_cmpps128_mask:
2195 case X86::BI__builtin_ia32_cmppd128_mask:
2196 case X86::BI__builtin_ia32_cmpps256_mask:
2197 case X86::BI__builtin_ia32_cmppd256_mask:
2198 case X86::BI__builtin_ia32_cmpps512_mask:
2199 case X86::BI__builtin_ia32_cmppd512_mask:
2200 case X86::BI__builtin_ia32_cmpsd_mask:
2201 case X86::BI__builtin_ia32_cmpss_mask:
2202 i = 2; l = 0; u = 31;
2204 case X86::BI__builtin_ia32_xabort:
2205 i = 0; l = -128; u = 255;
2207 case X86::BI__builtin_ia32_pshufw:
2208 case X86::BI__builtin_ia32_aeskeygenassist128:
2209 i = 1; l = -128; u = 255;
2211 case X86::BI__builtin_ia32_vcvtps2ph:
2212 case X86::BI__builtin_ia32_vcvtps2ph256:
2213 case X86::BI__builtin_ia32_rndscaleps_128_mask:
2214 case X86::BI__builtin_ia32_rndscalepd_128_mask:
2215 case X86::BI__builtin_ia32_rndscaleps_256_mask:
2216 case X86::BI__builtin_ia32_rndscalepd_256_mask:
2217 case X86::BI__builtin_ia32_rndscaleps_mask:
2218 case X86::BI__builtin_ia32_rndscalepd_mask:
2219 case X86::BI__builtin_ia32_reducepd128_mask:
2220 case X86::BI__builtin_ia32_reducepd256_mask:
2221 case X86::BI__builtin_ia32_reducepd512_mask:
2222 case X86::BI__builtin_ia32_reduceps128_mask:
2223 case X86::BI__builtin_ia32_reduceps256_mask:
2224 case X86::BI__builtin_ia32_reduceps512_mask:
2225 case X86::BI__builtin_ia32_prold512_mask:
2226 case X86::BI__builtin_ia32_prolq512_mask:
2227 case X86::BI__builtin_ia32_prold128_mask:
2228 case X86::BI__builtin_ia32_prold256_mask:
2229 case X86::BI__builtin_ia32_prolq128_mask:
2230 case X86::BI__builtin_ia32_prolq256_mask:
2231 case X86::BI__builtin_ia32_prord128_mask:
2232 case X86::BI__builtin_ia32_prord256_mask:
2233 case X86::BI__builtin_ia32_prorq128_mask:
2234 case X86::BI__builtin_ia32_prorq256_mask:
2235 case X86::BI__builtin_ia32_fpclasspd128_mask:
2236 case X86::BI__builtin_ia32_fpclasspd256_mask:
2237 case X86::BI__builtin_ia32_fpclassps128_mask:
2238 case X86::BI__builtin_ia32_fpclassps256_mask:
2239 case X86::BI__builtin_ia32_fpclassps512_mask:
2240 case X86::BI__builtin_ia32_fpclasspd512_mask:
2241 case X86::BI__builtin_ia32_fpclasssd_mask:
2242 case X86::BI__builtin_ia32_fpclassss_mask:
2243 i = 1; l = 0; u = 255;
2245 case X86::BI__builtin_ia32_palignr:
2246 case X86::BI__builtin_ia32_insertps128:
2247 case X86::BI__builtin_ia32_dpps:
2248 case X86::BI__builtin_ia32_dppd:
2249 case X86::BI__builtin_ia32_dpps256:
2250 case X86::BI__builtin_ia32_mpsadbw128:
2251 case X86::BI__builtin_ia32_mpsadbw256:
2252 case X86::BI__builtin_ia32_pcmpistrm128:
2253 case X86::BI__builtin_ia32_pcmpistri128:
2254 case X86::BI__builtin_ia32_pcmpistria128:
2255 case X86::BI__builtin_ia32_pcmpistric128:
2256 case X86::BI__builtin_ia32_pcmpistrio128:
2257 case X86::BI__builtin_ia32_pcmpistris128:
2258 case X86::BI__builtin_ia32_pcmpistriz128:
2259 case X86::BI__builtin_ia32_pclmulqdq128:
2260 case X86::BI__builtin_ia32_vperm2f128_pd256:
2261 case X86::BI__builtin_ia32_vperm2f128_ps256:
2262 case X86::BI__builtin_ia32_vperm2f128_si256:
2263 case X86::BI__builtin_ia32_permti256:
2264 i = 2; l = -128; u = 255;
2266 case X86::BI__builtin_ia32_palignr128:
2267 case X86::BI__builtin_ia32_palignr256:
2268 case X86::BI__builtin_ia32_palignr512_mask:
2269 case X86::BI__builtin_ia32_vcomisd:
2270 case X86::BI__builtin_ia32_vcomiss:
2271 case X86::BI__builtin_ia32_shuf_f32x4_mask:
2272 case X86::BI__builtin_ia32_shuf_f64x2_mask:
2273 case X86::BI__builtin_ia32_shuf_i32x4_mask:
2274 case X86::BI__builtin_ia32_shuf_i64x2_mask:
2275 case X86::BI__builtin_ia32_dbpsadbw128_mask:
2276 case X86::BI__builtin_ia32_dbpsadbw256_mask:
2277 case X86::BI__builtin_ia32_dbpsadbw512_mask:
2278 i = 2; l = 0; u = 255;
2280 case X86::BI__builtin_ia32_fixupimmpd512_mask:
2281 case X86::BI__builtin_ia32_fixupimmpd512_maskz:
2282 case X86::BI__builtin_ia32_fixupimmps512_mask:
2283 case X86::BI__builtin_ia32_fixupimmps512_maskz:
2284 case X86::BI__builtin_ia32_fixupimmsd_mask:
2285 case X86::BI__builtin_ia32_fixupimmsd_maskz:
2286 case X86::BI__builtin_ia32_fixupimmss_mask:
2287 case X86::BI__builtin_ia32_fixupimmss_maskz:
2288 case X86::BI__builtin_ia32_fixupimmpd128_mask:
2289 case X86::BI__builtin_ia32_fixupimmpd128_maskz:
2290 case X86::BI__builtin_ia32_fixupimmpd256_mask:
2291 case X86::BI__builtin_ia32_fixupimmpd256_maskz:
2292 case X86::BI__builtin_ia32_fixupimmps128_mask:
2293 case X86::BI__builtin_ia32_fixupimmps128_maskz:
2294 case X86::BI__builtin_ia32_fixupimmps256_mask:
2295 case X86::BI__builtin_ia32_fixupimmps256_maskz:
2296 case X86::BI__builtin_ia32_pternlogd512_mask:
2297 case X86::BI__builtin_ia32_pternlogd512_maskz:
2298 case X86::BI__builtin_ia32_pternlogq512_mask:
2299 case X86::BI__builtin_ia32_pternlogq512_maskz:
2300 case X86::BI__builtin_ia32_pternlogd128_mask:
2301 case X86::BI__builtin_ia32_pternlogd128_maskz:
2302 case X86::BI__builtin_ia32_pternlogd256_mask:
2303 case X86::BI__builtin_ia32_pternlogd256_maskz:
2304 case X86::BI__builtin_ia32_pternlogq128_mask:
2305 case X86::BI__builtin_ia32_pternlogq128_maskz:
2306 case X86::BI__builtin_ia32_pternlogq256_mask:
2307 case X86::BI__builtin_ia32_pternlogq256_maskz:
2308 i = 3; l = 0; u = 255;
2310 case X86::BI__builtin_ia32_gatherpfdpd:
2311 case X86::BI__builtin_ia32_gatherpfdps:
2312 case X86::BI__builtin_ia32_gatherpfqpd:
2313 case X86::BI__builtin_ia32_gatherpfqps:
2314 case X86::BI__builtin_ia32_scatterpfdpd:
2315 case X86::BI__builtin_ia32_scatterpfdps:
2316 case X86::BI__builtin_ia32_scatterpfqpd:
2317 case X86::BI__builtin_ia32_scatterpfqps:
2318 i = 4; l = 2; u = 3;
2320 case X86::BI__builtin_ia32_pcmpestrm128:
2321 case X86::BI__builtin_ia32_pcmpestri128:
2322 case X86::BI__builtin_ia32_pcmpestria128:
2323 case X86::BI__builtin_ia32_pcmpestric128:
2324 case X86::BI__builtin_ia32_pcmpestrio128:
2325 case X86::BI__builtin_ia32_pcmpestris128:
2326 case X86::BI__builtin_ia32_pcmpestriz128:
2327 i = 4; l = -128; u = 255;
2329 case X86::BI__builtin_ia32_rndscalesd_round_mask:
2330 case X86::BI__builtin_ia32_rndscaless_round_mask:
2331 i = 4; l = 0; u = 255;
2334 return SemaBuiltinConstantArgRange(TheCall, i, l, u);
2341 bool Sema::getFormatStringInfo(
const FormatAttr *Format,
bool IsCXXMember,
2342 FormatStringInfo *FSI) {
2343 FSI->HasVAListArg = Format->getFirstArg() == 0;
2344 FSI->FormatIdx = Format->getFormatIdx() - 1;
2345 FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
2351 if(FSI->FormatIdx == 0)
2354 if (FSI->FirstDataArg != 0)
2355 --FSI->FirstDataArg;
2365 if (
auto nullability
2374 if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
2376 dyn_cast<CompoundLiteralExpr>(Expr))
2378 dyn_cast<InitListExpr>(CLE->getInitializer()))
2379 Expr = ILE->getInit(0);
2389 const Expr *ArgExpr,
2397 FormatStringInfo FSI;
2398 if ((GetFormatStringType(Format) == FST_NSString) &&
2399 getFormatStringInfo(Format,
false, &FSI)) {
2400 Idx = FSI.FormatIdx;
2413 bool Format =
false;
2426 if (!Format || NumArgs <= Idx)
2428 const Expr *FormatExpr = Args[Idx];
2429 if (
const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
2430 FormatExpr = CSCE->getSubExpr();
2440 S.
Diag(FormatExpr->
getExprLoc(), diag::warn_objc_cdirective_format_string)
2458 ArrayRef<const Expr *> Args,
2460 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
2463 llvm::SmallBitVector NonNullArgs;
2469 for (
const auto *Arg : Args)
2475 for (
unsigned Val :
NonNull->args()) {
2476 if (Val >= Args.size())
2478 if (NonNullArgs.empty())
2479 NonNullArgs.resize(Args.size());
2480 NonNullArgs.set(Val);
2485 if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
2488 ArrayRef<ParmVarDecl*> parms;
2489 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
2490 parms = FD->parameters();
2492 parms = cast<ObjCMethodDecl>(FDecl)->parameters();
2494 unsigned ParamIndex = 0;
2495 for (ArrayRef<ParmVarDecl*>::iterator
I = parms.begin(),
E = parms.end();
2496 I !=
E; ++
I, ++ParamIndex) {
2498 if (PVD->
hasAttr<NonNullAttr>() ||
2500 if (NonNullArgs.empty())
2501 NonNullArgs.resize(Args.size());
2503 NonNullArgs.set(ParamIndex);
2510 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
2529 if (NonNullArgs.empty())
2530 NonNullArgs.resize(Args.size());
2532 NonNullArgs.set(Index);
2541 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
2542 ArgIndex != ArgIndexEnd; ++ArgIndex) {
2543 if (NonNullArgs[ArgIndex])
2552 const Expr *ThisArg, ArrayRef<const Expr *> Args,
2556 if (CurContext->isDependentContext())
2560 llvm::SmallBitVector CheckedVarArgs;
2564 CheckedVarArgs.resize(Args.size());
2566 CheckFormatArguments(
I, Args, IsMemberFunction, CallType, Loc, Range,
2573 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
2574 if (CallType != VariadicDoesNotApply &&
2575 (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
2577 : FDecl && isa<FunctionDecl>(FDecl)
2578 ? cast<FunctionDecl>(FDecl)->getNumParams()
2579 : FDecl && isa<ObjCMethodDecl>(FDecl)
2580 ? cast<ObjCMethodDecl>(FDecl)->param_size()
2583 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
2585 if (
const Expr *Arg = Args[ArgIdx]) {
2586 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
2587 checkVariadicArgument(Arg, CallType);
2592 if (FDecl || Proto) {
2597 for (
const auto *
I : FDecl->
specific_attrs<ArgumentWithTypeTagAttr>())
2598 CheckArgumentWithTypeTag(
I, Args.data());
2603 diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
2609 ArrayRef<const Expr *> Args,
2612 VariadicCallType CallType =
2613 Proto->
isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
2614 checkCall(FDecl, Proto,
nullptr, Args,
true,
2622 bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
2623 isa<CXXMethodDecl>(FDecl);
2624 bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
2625 IsMemberOperatorCall;
2626 VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
2631 Expr *ImplicitThis =
nullptr;
2632 if (IsMemberOperatorCall) {
2636 ImplicitThis = Args[0];
2639 }
else if (IsMemberFunction)
2641 cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
2643 checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
2653 CheckAbsoluteValueFunction(TheCall, FDecl);
2654 CheckMaxUnsignedZero(TheCall, FDecl);
2656 if (getLangOpts().ObjC1)
2664 if (CMId == Builtin::BIstrlcpy || CMId == Builtin::BIstrlcat)
2665 CheckStrlcpycatArguments(TheCall, FnInfo);
2666 else if (CMId == Builtin::BIstrncat)
2667 CheckStrncatArguments(TheCall, FnInfo);
2669 CheckMemaccessArguments(TheCall, CMId, FnInfo);
2675 ArrayRef<const Expr *> Args) {
2676 VariadicCallType CallType =
2677 Method->
isVariadic() ? VariadicMethod : VariadicDoesNotApply;
2679 checkCall(Method,
nullptr,
nullptr, Args,
2689 if (
const auto *V = dyn_cast<VarDecl>(NDecl))
2690 Ty = V->getType().getNonReferenceType();
2691 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
2692 Ty = F->getType().getNonReferenceType();
2700 VariadicCallType CallType;
2702 CallType = VariadicDoesNotApply;
2704 CallType = VariadicBlock;
2706 CallType = VariadicFunction;
2709 checkCall(NDecl, Proto,
nullptr,
2720 VariadicCallType CallType = getVariadicCallType(
nullptr, Proto,
2722 checkCall(
nullptr, Proto,
nullptr,
2731 if (!llvm::isValidAtomicOrderingCABI(Ordering))
2734 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
2736 case AtomicExpr::AO__c11_atomic_init:
2737 llvm_unreachable(
"There is no ordering argument for an init");
2739 case AtomicExpr::AO__c11_atomic_load:
2740 case AtomicExpr::AO__atomic_load_n:
2741 case AtomicExpr::AO__atomic_load:
2742 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
2743 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2745 case AtomicExpr::AO__c11_atomic_store:
2746 case AtomicExpr::AO__atomic_store:
2747 case AtomicExpr::AO__atomic_store_n:
2748 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
2749 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
2750 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
2759 CallExpr *TheCall = cast<CallExpr>(TheCallResult.
get());
2783 const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
2784 const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
2792 static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
2793 AtomicExpr::AO__c11_atomic_fetch_xor + 1 ==
2794 AtomicExpr::AO__atomic_load,
2795 "need to update code for modified C11 atomics");
2796 bool IsC11 = Op >= AtomicExpr::AO__c11_atomic_init &&
2797 Op <= AtomicExpr::AO__c11_atomic_fetch_xor;
2798 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
2799 Op == AtomicExpr::AO__atomic_store_n ||
2800 Op == AtomicExpr::AO__atomic_exchange_n ||
2801 Op == AtomicExpr::AO__atomic_compare_exchange_n;
2802 bool IsAddSub =
false;
2805 case AtomicExpr::AO__c11_atomic_init:
2809 case AtomicExpr::AO__c11_atomic_load:
2810 case AtomicExpr::AO__atomic_load_n:
2814 case AtomicExpr::AO__atomic_load:
2818 case AtomicExpr::AO__c11_atomic_store:
2819 case AtomicExpr::AO__atomic_store:
2820 case AtomicExpr::AO__atomic_store_n:
2824 case AtomicExpr::AO__c11_atomic_fetch_add:
2825 case AtomicExpr::AO__c11_atomic_fetch_sub:
2826 case AtomicExpr::AO__atomic_fetch_add:
2827 case AtomicExpr::AO__atomic_fetch_sub:
2828 case AtomicExpr::AO__atomic_add_fetch:
2829 case AtomicExpr::AO__atomic_sub_fetch:
2832 case AtomicExpr::AO__c11_atomic_fetch_and:
2833 case AtomicExpr::AO__c11_atomic_fetch_or:
2834 case AtomicExpr::AO__c11_atomic_fetch_xor:
2835 case AtomicExpr::AO__atomic_fetch_and:
2836 case AtomicExpr::AO__atomic_fetch_or:
2837 case AtomicExpr::AO__atomic_fetch_xor:
2838 case AtomicExpr::AO__atomic_fetch_nand:
2839 case AtomicExpr::AO__atomic_and_fetch:
2840 case AtomicExpr::AO__atomic_or_fetch:
2841 case AtomicExpr::AO__atomic_xor_fetch:
2842 case AtomicExpr::AO__atomic_nand_fetch:
2846 case AtomicExpr::AO__c11_atomic_exchange:
2847 case AtomicExpr::AO__atomic_exchange_n:
2851 case AtomicExpr::AO__atomic_exchange:
2855 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
2856 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
2860 case AtomicExpr::AO__atomic_compare_exchange:
2861 case AtomicExpr::AO__atomic_compare_exchange_n:
2868 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
2869 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
2872 }
else if (TheCall->
getNumArgs() > NumArgs[Form]) {
2874 diag::err_typecheck_call_too_many_args)
2875 << 0 << NumArgs[Form] << TheCall->
getNumArgs()
2882 ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
2886 Ptr = ConvertedPtr.
get();
2889 Diag(DRE->getLocStart(), diag::err_atomic_builtin_must_be_pointer)
2899 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic)
2904 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_atomic)
2909 }
else if (Form != Load && Form != LoadCopy) {
2911 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_non_const_pointer)
2918 if (Form == Arithmetic) {
2921 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2926 Diag(DRE->getLocStart(), diag::err_atomic_op_bitwise_needs_atomic_int)
2932 diag::err_incomplete_type)) {
2938 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_atomic_int_or_ptr)
2947 Diag(DRE->getLocStart(), diag::err_atomic_op_needs_trivial_copy)
2963 Diag(DRE->getLocStart(), diag::err_arc_atomic_ownership)
2974 if (Form == Copy || Form == LoadCopy || Form == GNUXchg || Form == Init)
2976 else if (Form == C11CmpXchg || Form == GNUCmpXchg)
2988 for (
unsigned i = 1; i != NumArgs[Form]; ++i) {
2990 if (i < NumVals[Form] + 1) {
2997 assert(Form != Load);
2998 if (Form == Init || (Form == Arithmetic && ValType->
isIntegerType()))
3000 else if (Form == Copy || Form == Xchg)
3002 else if (Form == Arithmetic)
3013 AS = PtrTy->getPointeeType().getAddressSpace();
3045 SubExprs.push_back(Ptr);
3049 SubExprs.push_back(TheCall->
getArg(1));
3052 SubExprs.push_back(TheCall->
getArg(1));
3058 SubExprs.push_back(TheCall->
getArg(2));
3059 SubExprs.push_back(TheCall->
getArg(1));
3063 SubExprs.push_back(TheCall->
getArg(3));
3064 SubExprs.push_back(TheCall->
getArg(1));
3065 SubExprs.push_back(TheCall->
getArg(2));
3068 SubExprs.push_back(TheCall->
getArg(3));
3069 SubExprs.push_back(TheCall->
getArg(1));
3070 SubExprs.push_back(TheCall->
getArg(4));
3071 SubExprs.push_back(TheCall->
getArg(2));
3074 SubExprs.push_back(TheCall->
getArg(4));
3075 SubExprs.push_back(TheCall->
getArg(1));
3076 SubExprs.push_back(TheCall->
getArg(5));
3077 SubExprs.push_back(TheCall->
getArg(2));
3078 SubExprs.push_back(TheCall->
getArg(3));
3082 if (SubExprs.size() >= 2 && Form != Init) {
3083 llvm::APSInt Result(32);
3084 if (SubExprs[1]->isIntegerConstantExpr(Result,
Context) &&
3086 Diag(SubExprs[1]->getLocStart(),
3087 diag::warn_atomic_op_has_invalid_memory_order)
3088 << SubExprs[1]->getSourceRange();
3092 SubExprs, ResultType, Op,
3095 if ((Op == AtomicExpr::AO__c11_atomic_load ||
3096 (Op == AtomicExpr::AO__c11_atomic_store)) &&
3099 ((Op == AtomicExpr::AO__c11_atomic_load) ? 0 : 1);
3113 assert(Fn &&
"builtin call without direct callee!");
3137 Sema::SemaBuiltinAtomicOverloaded(
ExprResult TheCallResult) {
3144 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3156 ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
3159 FirstArg = FirstArgResult.
get();
3160 TheCall->
setArg(0, FirstArg);
3172 Diag(DRE->
getLocStart(), diag::err_atomic_builtin_must_be_pointer_intptr)
3201 #define BUILTIN_ROW(x) \
3202 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
3203 Builtin::BI##x##_8, Builtin::BI##x##_16 }
3205 static const unsigned BuiltinIndices[][5] = {
3231 case 1: SizeIndex = 0;
break;
3232 case 2: SizeIndex = 1;
break;
3233 case 4: SizeIndex = 2;
break;
3234 case 8: SizeIndex = 3;
break;
3235 case 16: SizeIndex = 4;
break;
3246 unsigned BuiltinID = FDecl->getBuiltinID();
3247 unsigned BuiltinIndex, NumFixed = 1;
3248 bool WarnAboutSemanticsChange =
false;
3249 switch (BuiltinID) {
3250 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
3251 case Builtin::BI__sync_fetch_and_add:
3252 case Builtin::BI__sync_fetch_and_add_1:
3253 case Builtin::BI__sync_fetch_and_add_2:
3254 case Builtin::BI__sync_fetch_and_add_4:
3255 case Builtin::BI__sync_fetch_and_add_8:
3256 case Builtin::BI__sync_fetch_and_add_16:
3260 case Builtin::BI__sync_fetch_and_sub:
3261 case Builtin::BI__sync_fetch_and_sub_1:
3262 case Builtin::BI__sync_fetch_and_sub_2:
3263 case Builtin::BI__sync_fetch_and_sub_4:
3264 case Builtin::BI__sync_fetch_and_sub_8:
3265 case Builtin::BI__sync_fetch_and_sub_16:
3269 case Builtin::BI__sync_fetch_and_or:
3270 case Builtin::BI__sync_fetch_and_or_1:
3271 case Builtin::BI__sync_fetch_and_or_2:
3272 case Builtin::BI__sync_fetch_and_or_4:
3273 case Builtin::BI__sync_fetch_and_or_8:
3274 case Builtin::BI__sync_fetch_and_or_16:
3278 case Builtin::BI__sync_fetch_and_and:
3279 case Builtin::BI__sync_fetch_and_and_1:
3280 case Builtin::BI__sync_fetch_and_and_2:
3281 case Builtin::BI__sync_fetch_and_and_4:
3282 case Builtin::BI__sync_fetch_and_and_8:
3283 case Builtin::BI__sync_fetch_and_and_16:
3287 case Builtin::BI__sync_fetch_and_xor:
3288 case Builtin::BI__sync_fetch_and_xor_1:
3289 case Builtin::BI__sync_fetch_and_xor_2:
3290 case Builtin::BI__sync_fetch_and_xor_4:
3291 case Builtin::BI__sync_fetch_and_xor_8:
3292 case Builtin::BI__sync_fetch_and_xor_16:
3296 case Builtin::BI__sync_fetch_and_nand:
3297 case Builtin::BI__sync_fetch_and_nand_1:
3298 case Builtin::BI__sync_fetch_and_nand_2:
3299 case Builtin::BI__sync_fetch_and_nand_4:
3300 case Builtin::BI__sync_fetch_and_nand_8:
3301 case Builtin::BI__sync_fetch_and_nand_16:
3303 WarnAboutSemanticsChange =
true;
3306 case Builtin::BI__sync_add_and_fetch:
3307 case Builtin::BI__sync_add_and_fetch_1:
3308 case Builtin::BI__sync_add_and_fetch_2:
3309 case Builtin::BI__sync_add_and_fetch_4:
3310 case Builtin::BI__sync_add_and_fetch_8:
3311 case Builtin::BI__sync_add_and_fetch_16:
3315 case Builtin::BI__sync_sub_and_fetch:
3316 case Builtin::BI__sync_sub_and_fetch_1:
3317 case Builtin::BI__sync_sub_and_fetch_2:
3318 case Builtin::BI__sync_sub_and_fetch_4:
3319 case Builtin::BI__sync_sub_and_fetch_8:
3320 case Builtin::BI__sync_sub_and_fetch_16:
3324 case Builtin::BI__sync_and_and_fetch:
3325 case Builtin::BI__sync_and_and_fetch_1:
3326 case Builtin::BI__sync_and_and_fetch_2:
3327 case Builtin::BI__sync_and_and_fetch_4:
3328 case Builtin::BI__sync_and_and_fetch_8:
3329 case Builtin::BI__sync_and_and_fetch_16:
3333 case Builtin::BI__sync_or_and_fetch:
3334 case Builtin::BI__sync_or_and_fetch_1:
3335 case Builtin::BI__sync_or_and_fetch_2:
3336 case Builtin::BI__sync_or_and_fetch_4:
3337 case Builtin::BI__sync_or_and_fetch_8:
3338 case Builtin::BI__sync_or_and_fetch_16:
3342 case Builtin::BI__sync_xor_and_fetch:
3343 case Builtin::BI__sync_xor_and_fetch_1:
3344 case Builtin::BI__sync_xor_and_fetch_2:
3345 case Builtin::BI__sync_xor_and_fetch_4:
3346 case Builtin::BI__sync_xor_and_fetch_8:
3347 case Builtin::BI__sync_xor_and_fetch_16:
3351 case Builtin::BI__sync_nand_and_fetch:
3352 case Builtin::BI__sync_nand_and_fetch_1:
3353 case Builtin::BI__sync_nand_and_fetch_2:
3354 case Builtin::BI__sync_nand_and_fetch_4:
3355 case Builtin::BI__sync_nand_and_fetch_8:
3356 case Builtin::BI__sync_nand_and_fetch_16:
3358 WarnAboutSemanticsChange =
true;
3361 case Builtin::BI__sync_val_compare_and_swap:
3362 case Builtin::BI__sync_val_compare_and_swap_1:
3363 case Builtin::BI__sync_val_compare_and_swap_2:
3364 case Builtin::BI__sync_val_compare_and_swap_4:
3365 case Builtin::BI__sync_val_compare_and_swap_8:
3366 case Builtin::BI__sync_val_compare_and_swap_16:
3371 case Builtin::BI__sync_bool_compare_and_swap:
3372 case Builtin::BI__sync_bool_compare_and_swap_1:
3373 case Builtin::BI__sync_bool_compare_and_swap_2:
3374 case Builtin::BI__sync_bool_compare_and_swap_4:
3375 case Builtin::BI__sync_bool_compare_and_swap_8:
3376 case Builtin::BI__sync_bool_compare_and_swap_16:
3382 case Builtin::BI__sync_lock_test_and_set:
3383 case Builtin::BI__sync_lock_test_and_set_1:
3384 case Builtin::BI__sync_lock_test_and_set_2:
3385 case Builtin::BI__sync_lock_test_and_set_4:
3386 case Builtin::BI__sync_lock_test_and_set_8:
3387 case Builtin::BI__sync_lock_test_and_set_16:
3391 case Builtin::BI__sync_lock_release:
3392 case Builtin::BI__sync_lock_release_1:
3393 case Builtin::BI__sync_lock_release_2:
3394 case Builtin::BI__sync_lock_release_4:
3395 case Builtin::BI__sync_lock_release_8:
3396 case Builtin::BI__sync_lock_release_16:
3402 case Builtin::BI__sync_swap:
3403 case Builtin::BI__sync_swap_1:
3404 case Builtin::BI__sync_swap_2:
3405 case Builtin::BI__sync_swap_4:
3406 case Builtin::BI__sync_swap_8:
3407 case Builtin::BI__sync_swap_16:
3415 Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args_at_least)
3421 if (WarnAboutSemanticsChange) {
3422 Diag(TheCall->
getLocEnd(), diag::warn_sync_fetch_and_nand_semantics_change)
3428 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
3431 if (NewBuiltinID == BuiltinID)
3432 NewBuiltinDecl = FDecl;
3437 LookupName(Res, TUScope,
true);
3438 assert(Res.getFoundDecl());
3439 NewBuiltinDecl = dyn_cast<
FunctionDecl>(Res.getFoundDecl());
3440 if (!NewBuiltinDecl)
3447 for (
unsigned i = 0; i != NumFixed; ++i) {
3484 ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
3485 CK_BuiltinFnToFnPtr);
3493 return TheCallResult;
3507 unsigned BuiltinID = FDecl->getBuiltinID();
3508 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
3509 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
3510 "Unexpected nontemporal load/store builtin!");
3511 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
3512 unsigned numArgs = isStore ? 2 : 1;
3522 Expr *PointerArg = TheCall->
getArg(numArgs - 1);
3524 DefaultFunctionArrayLvalueConversion(PointerArg);
3528 PointerArg = PointerArgResult.
get();
3529 TheCall->
setArg(numArgs - 1, PointerArg);
3533 Diag(DRE->
getLocStart(), diag::err_nontemporal_builtin_must_be_pointer)
3546 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
3553 return TheCallResult;
3558 Context, ValType,
false);
3559 ValArg = PerformCopyInitialization(Entity,
SourceLocation(), ValArg);
3565 return TheCallResult;
3572 bool Sema::CheckObjCString(
Expr *Arg) {
3576 if (!Literal || !Literal->
isAscii()) {
3577 Diag(Arg->
getLocStart(), diag::err_cfstring_literal_not_string_constant)
3583 StringRef String = Literal->
getString();
3584 unsigned NumBytes = String.size();
3586 const llvm::UTF8 *FromPtr = (
const llvm::UTF8 *)String.data();
3587 llvm::UTF16 *ToPtr = &ToBuf[0];
3589 llvm::ConversionResult Result =
3590 llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3591 ToPtr + NumBytes, llvm::strictConversion);
3593 if (Result != llvm::conversionOK)
3606 if (
auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
3611 if (!Literal || (!Literal->
isAscii() && !Literal->
isUTF8())) {
3621 Result = PerformCopyInitialization(Entity,
SourceLocation(), Result);
3629 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
3630 bool IsAArch64 = TT.getArch() == llvm::Triple::aarch64;
3631 bool IsWindows = TT.isOSWindows();
3632 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
3633 if (IsX64 || IsAArch64) {
3636 CC = FD->getType()->getAs<
FunctionType>()->getCallConv();
3641 diag::err_ms_va_start_used_in_sysv_function);
3650 diag::err_va_start_used_in_wrong_abi_function)
3665 bool IsVariadic =
false;
3666 ArrayRef<ParmVarDecl *> Params;
3668 if (
auto *Block = dyn_cast<BlockDecl>(Caller)) {
3669 IsVariadic = Block->isVariadic();
3670 Params = Block->parameters();
3671 }
else if (
auto *FD = dyn_cast<FunctionDecl>(Caller)) {
3672 IsVariadic = FD->isVariadic();
3673 Params = FD->parameters();
3674 }
else if (
auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
3675 IsVariadic = MD->isVariadic();
3677 Params = MD->parameters();
3678 }
else if (isa<CapturedDecl>(Caller)) {
3694 *LastParam = Params.empty() ?
nullptr : Params.back();
3702 bool Sema::SemaBuiltinVAStart(
unsigned BuiltinID,
CallExpr *TheCall) {
3710 diag::err_typecheck_call_too_many_args)
3714 (*(TheCall->
arg_end()-1))->getLocEnd());
3720 diag::err_typecheck_call_too_few_args_at_least)
3735 bool SecondArgIsLastNamedArgument =
false;
3742 bool IsCRegister =
false;
3744 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
3745 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
3746 SecondArgIsLastNamedArgument = PV == LastParam;
3748 Type = PV->getType();
3749 ParamLoc = PV->getLocation();
3751 PV->getStorageClass() ==
SC_Register && !getLangOpts().CPlusPlus;
3755 if (!SecondArgIsLastNamedArgument)
3757 diag::warn_second_arg_of_va_start_not_last_named_param);
3770 unsigned Reason = 0;
3772 else if (IsCRegister) Reason = 2;
3773 Diag(Arg->
getLocStart(), diag::warn_va_start_type_is_undefined) << Reason;
3774 Diag(ParamLoc, diag::note_parameter_type) << Type;
3781 bool Sema::SemaBuiltinVAStartARM(
CallExpr *Call) {
3789 diag::err_typecheck_call_too_few_args_at_least)
3803 } ArgumentTypes[] = {
3808 for (
const auto &AT : ArgumentTypes) {
3813 << Arg->
getType() << AT.Type << 1
3815 << AT.ArgNo + 1 << Arg->
getType() << AT.Type;
3823 bool Sema::SemaBuiltinUnorderedCompare(
CallExpr *TheCall) {
3825 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
3829 diag::err_typecheck_call_too_many_args)
3832 (*(TheCall->
arg_end()-1))->getLocEnd());
3839 QualType Res = UsualArithmeticConversions(OrigArg0, OrigArg1,
false);
3840 if (OrigArg0.isInvalid() || OrigArg1.
isInvalid())
3846 TheCall->
setArg(0, OrigArg0.get());
3855 return Diag(OrigArg0.get()->getLocStart(),
3856 diag::err_typecheck_call_invalid_ordered_compare)
3857 << OrigArg0.get()->getType() << OrigArg1.
get()->
getType()
3867 bool Sema::SemaBuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs) {
3869 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
3873 diag::err_typecheck_call_too_many_args)
3876 (*(TheCall->
arg_end()-1))->getLocEnd());
3880 if (OrigArg->isTypeDependent())
3884 if (!OrigArg->getType()->isRealFloatingType())
3885 return Diag(OrigArg->getLocStart(),
3886 diag::err_typecheck_call_invalid_unary_fp)
3887 << OrigArg->getType() << OrigArg->getSourceRange();
3892 if (Cast->getCastKind() == CK_FloatingCast) {
3893 Expr *CastArg = Cast->getSubExpr();
3895 assert((Cast->getType()->isSpecificBuiltinType(BuiltinType::Double) ||
3896 Cast->getType()->isSpecificBuiltinType(BuiltinType::Float)) &&
3897 "promotion from float to either float or double is the only expected cast here");
3898 Cast->setSubExpr(
nullptr);
3899 TheCall->
setArg(NumArgs-1, CastArg);
3914 bool Sema::SemaBuiltinVSX(
CallExpr *TheCall) {
3915 unsigned ExpectedNumArgs = 3;
3918 diag::err_typecheck_call_too_few_args_at_least)
3919 << 0 << ExpectedNumArgs << TheCall->
getNumArgs()
3924 diag::err_typecheck_call_too_many_args_at_most)
3925 << 0 << ExpectedNumArgs << TheCall->
getNumArgs()
3932 diag::err_vsx_builtin_nonconstant_argument)
3942 if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
3944 return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
3952 return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
3971 diag::err_typecheck_call_too_few_args_at_least)
3979 unsigned numElements = 0;
3988 diag::err_vec_builtin_non_vector)
3994 unsigned numResElements = TheCall->
getNumArgs() - 2;
4003 diag::err_vec_builtin_incompatible_vector)
4009 diag::err_vec_builtin_incompatible_vector)
4013 }
else if (numElements != numResElements) {
4020 for (
unsigned i = 2; i < TheCall->
getNumArgs(); i++) {
4025 llvm::APSInt Result(32);
4028 diag::err_shufflevector_nonconstant_argument)
4032 if (Result.isSigned() && Result.isAllOnesValue())
4035 if (Result.getActiveBits() > 64 || Result.getZExtValue() >= numElements*2)
4037 diag::err_shufflevector_argument_too_large)
4043 for (
unsigned i = 0, e = TheCall->
getNumArgs(); i != e; i++) {
4044 exprs.push_back(TheCall->
getArg(i));
4045 TheCall->
setArg(i,
nullptr);
4064 diag::err_convertvector_non_vector)
4068 diag::err_convertvector_non_vector_type));
4073 if (SrcElts != DstElts)
4075 diag::err_convertvector_incompatible_vector)
4086 bool Sema::SemaBuiltinPrefetch(
CallExpr *TheCall) {
4091 diag::err_typecheck_call_too_many_args_at_most)
4092 << 0 << 3 << NumArgs
4097 for (
unsigned i = 1; i != NumArgs; ++i)
4098 if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
4107 bool Sema::SemaBuiltinAssume(
CallExpr *TheCall) {
4122 bool Sema::SemaBuiltinAllocaWithAlign(
CallExpr *TheCall) {
4128 if (
const auto *UE =
4136 if (!Result.isPowerOf2())
4138 diag::err_alignment_not_power_of_two)
4146 if (Result > INT32_MAX)
4157 bool Sema::SemaBuiltinAssumeAligned(
CallExpr *TheCall) {
4162 diag::err_typecheck_call_too_many_args_at_most)
4163 << 0 << 3 << NumArgs
4171 llvm::APSInt Result;
4172 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4175 if (!Result.isPowerOf2())
4177 diag::err_alignment_not_power_of_two)
4186 if (Arg.isInvalid())
return true;
4187 TheCall->
setArg(2, Arg.get());
4193 bool Sema::SemaBuiltinOSLogFormat(
CallExpr *TheCall) {
4194 unsigned BuiltinID =
4195 cast<FunctionDecl>(TheCall->
getCalleeDecl())->getBuiltinID();
4196 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
4199 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
4200 if (NumArgs < NumRequiredArgs) {
4201 return Diag(TheCall->
getLocEnd(), diag::err_typecheck_call_too_few_args)
4202 << 0 << NumRequiredArgs << NumArgs
4205 if (NumArgs >= NumRequiredArgs + 0x100) {
4207 diag::err_typecheck_call_too_many_args_at_most)
4208 << 0 << (NumRequiredArgs + 0xff) << NumArgs
4219 if (Arg.isInvalid())
4221 TheCall->
setArg(i, Arg.get());
4226 unsigned FormatIdx = i;
4236 unsigned FirstDataArg = i;
4237 while (i < NumArgs) {
4238 ExprResult Arg = DefaultVariadicArgumentPromotion(
4239 TheCall->
getArg(i), VariadicFunction,
nullptr);
4245 << i << (
int)ArgSize.getQuantity() << 0xff
4248 TheCall->setArg(i, Arg.get());
4255 llvm::SmallBitVector CheckedVarArgs(NumArgs,
false);
4257 bool Success = CheckFormatArguments(
4258 Args,
false, FormatIdx, FirstDataArg, FST_OSLog,
4275 bool Sema::SemaBuiltinConstantArg(
CallExpr *TheCall,
int ArgNum,
4276 llvm::APSInt &Result) {
4284 return Diag(TheCall->
getLocStart(), diag::err_constant_integer_arg_type)
4292 bool Sema::SemaBuiltinConstantArgRange(
CallExpr *TheCall,
int ArgNum,
4293 int Low,
int High) {
4294 llvm::APSInt Result;
4302 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4305 if (Result.getSExtValue() < Low || Result.getSExtValue() > High)
4314 bool Sema::SemaBuiltinConstantArgMultiple(
CallExpr *TheCall,
int ArgNum,
4316 llvm::APSInt Result;
4324 if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4327 if (Result.getSExtValue() % Num != 0)
4336 bool Sema::SemaBuiltinARMSpecialReg(
unsigned BuiltinID,
CallExpr *TheCall,
4337 int ArgNum,
unsigned ExpectedFieldNum,
4339 bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
4340 BuiltinID == ARM::BI__builtin_arm_wsr64 ||
4341 BuiltinID == ARM::BI__builtin_arm_rsr ||
4342 BuiltinID == ARM::BI__builtin_arm_rsrp ||
4343 BuiltinID == ARM::BI__builtin_arm_wsr ||
4344 BuiltinID == ARM::BI__builtin_arm_wsrp;
4345 bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
4346 BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
4347 BuiltinID == AArch64::BI__builtin_arm_rsr ||
4348 BuiltinID == AArch64::BI__builtin_arm_rsrp ||
4349 BuiltinID == AArch64::BI__builtin_arm_wsr ||
4350 BuiltinID == AArch64::BI__builtin_arm_wsrp;
4351 assert((IsARMBuiltin || IsAArch64Builtin) &&
"Unexpected ARM builtin.");
4360 return Diag(TheCall->
getLocStart(), diag::err_expr_not_string_literal)
4366 Reg.split(Fields,
":");
4368 if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
4376 if (Fields.size() > 1) {
4377 bool FiveFields = Fields.size() == 5;
4379 bool ValidString =
true;
4381 ValidString &= Fields[0].startswith_lower(
"cp") ||
4382 Fields[0].startswith_lower(
"p");
4385 Fields[0].drop_front(Fields[0].startswith_lower(
"cp") ? 2 : 1);
4387 ValidString &= Fields[2].startswith_lower(
"c");
4389 Fields[2] = Fields[2].drop_front(1);
4392 ValidString &= Fields[3].startswith_lower(
"c");
4394 Fields[3] = Fields[3].drop_front(1);
4400 Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
4402 Ranges.append({15, 7, 15});
4404 for (
unsigned i=0; i<Fields.size(); ++i) {
4406 ValidString &= !Fields[i].getAsInteger(10, IntField);
4407 ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
4414 }
else if (IsAArch64Builtin && Fields.size() == 1) {
4424 std::string RegLower = Reg.lower();
4425 if (RegLower !=
"spsel" && RegLower !=
"daifset" && RegLower !=
"daifclr" &&
4426 RegLower !=
"pan" && RegLower !=
"uao")
4429 return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
4438 bool Sema::SemaBuiltinLongjmp(
CallExpr *TheCall) {
4440 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_unsupported)
4444 llvm::APSInt Result;
4447 if (SemaBuiltinConstantArg(TheCall, 1, Result))
4451 return Diag(TheCall->
getLocStart(), diag::err_builtin_longjmp_invalid_val)
4459 bool Sema::SemaBuiltinSetjmp(
CallExpr *TheCall) {
4461 return Diag(TheCall->
getLocStart(), diag::err_builtin_setjmp_unsupported)
4467 class UncoveredArgHandler {
4468 enum {
Unknown = -1, AllCovered = -2 };
4469 signed FirstUncoveredArg;
4473 UncoveredArgHandler() : FirstUncoveredArg(
Unknown) { }
4475 bool hasUncoveredArg()
const {
4476 return (FirstUncoveredArg >= 0);
4479 unsigned getUncoveredArg()
const {
4480 assert(hasUncoveredArg() &&
"no uncovered argument");
4481 return FirstUncoveredArg;
4484 void setAllCovered() {
4487 DiagnosticExprs.clear();
4488 FirstUncoveredArg = AllCovered;
4491 void Update(
signed NewFirstUncoveredArg,
const Expr *StrExpr) {
4492 assert(NewFirstUncoveredArg >= 0 &&
"Outside range");
4495 if (FirstUncoveredArg == AllCovered)
4500 if (NewFirstUncoveredArg == FirstUncoveredArg)
4501 DiagnosticExprs.push_back(StrExpr);
4502 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
4503 DiagnosticExprs.clear();
4504 DiagnosticExprs.push_back(StrExpr);
4505 FirstUncoveredArg = NewFirstUncoveredArg;
4509 void Diagnose(
Sema &
S,
bool IsFunctionCall,
const Expr *ArgExpr);
4514 SLCT_UncheckedLiteral,
4521 bool AddendIsRight) {
4522 unsigned BitWidth = Offset.getBitWidth();
4523 unsigned AddendBitWidth = Addend.getBitWidth();
4525 if (Addend.isUnsigned()) {
4526 Addend = Addend.zext(++AddendBitWidth);
4527 Addend.setIsSigned(
true);
4530 if (AddendBitWidth > BitWidth) {
4531 Offset = Offset.sext(AddendBitWidth);
4532 BitWidth = AddendBitWidth;
4533 }
else if (BitWidth > AddendBitWidth) {
4534 Addend = Addend.sext(BitWidth);
4538 llvm::APSInt ResOffset =
Offset;
4539 if (BinOpKind == BO_Add)
4540 ResOffset = Offset.sadd_ov(Addend, Ov);
4542 assert(AddendIsRight && BinOpKind == BO_Sub &&
4543 "operator must be add or sub with addend on the right");
4544 ResOffset = Offset.ssub_ov(Addend, Ov);
4550 assert(BitWidth <=
UINT_MAX / 2 &&
"index (intermediate) result too big");
4551 Offset = Offset.sext(2 * BitWidth);
4552 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
4563 class FormatStringLiteral {
4571 StringRef getString()
const {
4572 return FExpr->getString().drop_front(
Offset);
4575 unsigned getByteLength()
const {
4576 return FExpr->getByteLength() - getCharByteWidth() *
Offset;
4578 unsigned getLength()
const {
return FExpr->getLength() -
Offset; }
4579 unsigned getCharByteWidth()
const {
return FExpr->getCharByteWidth(); }
4583 QualType getType()
const {
return FExpr->getType(); }
4585 bool isAscii()
const {
return FExpr->isAscii(); }
4586 bool isWide()
const {
return FExpr->isWide(); }
4587 bool isUTF8()
const {
return FExpr->isUTF8(); }
4588 bool isUTF16()
const {
return FExpr->isUTF16(); }
4589 bool isUTF32()
const {
return FExpr->isUTF32(); }
4590 bool isPascal()
const {
return FExpr->isPascal(); }
4594 const TargetInfo &Target,
unsigned *StartToken =
nullptr,
4595 unsigned *StartTokenByteOffset =
nullptr)
const {
4596 return FExpr->getLocationOfByte(ByteNo +
Offset, SM, Features, Target,
4597 StartToken, StartTokenByteOffset);
4603 SourceLocation getLocEnd() const LLVM_READONLY {
return FExpr->getLocEnd(); }
4608 const Expr *OrigFormatExpr,
4609 ArrayRef<const Expr *> Args,
4610 bool HasVAListArg,
unsigned format_idx,
4611 unsigned firstDataArg,
4613 bool inFunctionCall,
4615 llvm::SmallBitVector &CheckedVarArgs,
4616 UncoveredArgHandler &UncoveredArg);
4624 bool HasVAListArg,
unsigned format_idx,
4627 llvm::SmallBitVector &CheckedVarArgs,
4628 UncoveredArgHandler &UncoveredArg,
4631 assert(Offset.isSigned() &&
"invalid offset");
4634 return SLCT_NotALiteral;
4643 return SLCT_UncheckedLiteral;
4646 case Stmt::BinaryConditionalOperatorClass:
4647 case Stmt::ConditionalOperatorClass: {
4651 cast<AbstractConditionalOperator>(
E);
4656 bool CheckLeft =
true, CheckRight =
true;
4672 Left = SLCT_UncheckedLiteral;
4675 HasVAListArg, format_idx, firstDataArg,
4676 Type, CallType, InFunctionCall,
4677 CheckedVarArgs, UncoveredArg,
Offset);
4678 if (Left == SLCT_NotALiteral || !CheckRight) {
4685 HasVAListArg, format_idx, firstDataArg,
4686 Type, CallType, InFunctionCall, CheckedVarArgs,
4689 return (CheckLeft && Left < Right) ? Left : Right;
4692 case Stmt::ImplicitCastExprClass: {
4693 E = cast<ImplicitCastExpr>(
E)->getSubExpr();
4697 case Stmt::OpaqueValueExprClass:
4698 if (
const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
4702 return SLCT_NotALiteral;
4704 case Stmt::PredefinedExprClass:
4708 return SLCT_UncheckedLiteral;
4710 case Stmt::DeclRefExprClass: {
4716 bool isConstant =
false;
4720 isConstant = AT->getElementType().isConstant(S.
Context);
4723 PT->getPointeeType().isConstant(S.
Context);
4731 if (
const Expr *Init = VD->getAnyInitializer()) {
4733 if (
const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4734 if (InitList->isStringLiteralInit())
4735 Init = InitList->getInit(0)->IgnoreParenImpCasts();
4738 HasVAListArg, format_idx,
4739 firstDataArg, Type, CallType,
4740 false, CheckedVarArgs,
4741 UncoveredArg, Offset);
4760 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
4761 if (
const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
4762 int PVIndex = PV->getFunctionScopeIndex() + 1;
4763 for (
const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
4766 if (MD->isInstance())
4770 if (PVIndex == PVFormat->getFormatIdx() &&
4772 return SLCT_UncheckedLiteral;
4779 return SLCT_NotALiteral;
4782 case Stmt::CallExprClass:
4783 case Stmt::CXXMemberCallExprClass: {
4786 if (
const FormatArgAttr *FA = ND->getAttr<FormatArgAttr>()) {
4787 unsigned ArgIndex = FA->getFormatIdx();
4789 if (MD->isInstance())
4794 HasVAListArg, format_idx, firstDataArg,
4795 Type, CallType, InFunctionCall,
4796 CheckedVarArgs, UncoveredArg, Offset);
4797 }
else if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4798 unsigned BuiltinID = FD->getBuiltinID();
4799 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4800 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
4803 HasVAListArg, format_idx,
4804 firstDataArg, Type, CallType,
4805 InFunctionCall, CheckedVarArgs,
4806 UncoveredArg, Offset);
4811 return SLCT_NotALiteral;
4813 case Stmt::ObjCMessageExprClass: {
4814 const auto *ME = cast<ObjCMessageExpr>(
E);
4815 if (
const auto *ND = ME->getMethodDecl()) {
4816 if (
const auto *FA = ND->getAttr<FormatArgAttr>()) {
4817 unsigned ArgIndex = FA->getFormatIdx();
4818 const Expr *Arg = ME->getArg(ArgIndex - 1);
4820 S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
4821 CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset);
4825 return SLCT_NotALiteral;
4827 case Stmt::ObjCStringLiteralClass:
4828 case Stmt::StringLiteralClass: {
4834 StrE = cast<StringLiteral>(
E);
4837 if (Offset.isNegative() || Offset > StrE->
getLength()) {
4840 return SLCT_NotALiteral;
4842 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
4844 firstDataArg, Type, InFunctionCall, CallType,
4845 CheckedVarArgs, UncoveredArg);
4846 return SLCT_CheckedLiteral;
4849 return SLCT_NotALiteral;
4851 case Stmt::BinaryOperatorClass: {
4852 llvm::APSInt LResult;
4853 llvm::APSInt RResult;
4862 if (LIsInt != RIsInt) {
4866 if (BinOpKind == BO_Add) {
4867 sumOffsets(Offset, LResult, BinOpKind, RIsInt);
4872 sumOffsets(Offset, RResult, BinOpKind, RIsInt);
4879 return SLCT_NotALiteral;
4881 case Stmt::UnaryOperatorClass: {
4884 if (UnaOp->
getOpcode() == clang::UO_AddrOf && ASE) {
4885 llvm::APSInt IndexResult;
4886 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.
Context)) {
4887 sumOffsets(Offset, IndexResult, BO_Add,
true);
4893 return SLCT_NotALiteral;
4897 return SLCT_NotALiteral;
4902 return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
4903 .Case(
"scanf", FST_Scanf)
4904 .Cases(
"printf",
"printf0", FST_Printf)
4905 .Cases(
"NSString",
"CFString", FST_NSString)
4906 .Case(
"strftime", FST_Strftime)
4907 .Case(
"strfmon", FST_Strfmon)
4908 .Cases(
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err", FST_Kprintf)
4909 .Case(
"freebsd_kprintf", FST_FreeBSDKPrintf)
4910 .Case(
"os_trace", FST_OSLog)
4911 .Case(
"os_log", FST_OSLog)
4912 .Default(FST_Unknown);
4918 bool Sema::CheckFormatArguments(
const FormatAttr *Format,
4921 VariadicCallType CallType,
4923 llvm::SmallBitVector &CheckedVarArgs) {
4924 FormatStringInfo FSI;
4925 if (getFormatStringInfo(Format, IsCXXMember, &FSI))
4926 return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
4927 FSI.FirstDataArg, GetFormatStringType(Format),
4928 CallType, Loc, Range, CheckedVarArgs);
4932 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
4933 bool HasVAListArg,
unsigned format_idx,
4934 unsigned firstDataArg, FormatStringType Type,
4935 VariadicCallType CallType,
4937 llvm::SmallBitVector &CheckedVarArgs) {
4939 if (format_idx >= Args.size()) {
4940 Diag(Loc, diag::warn_missing_format_string) << Range;
4958 UncoveredArgHandler UncoveredArg;
4961 format_idx, firstDataArg, Type, CallType,
4962 true, CheckedVarArgs,
4964 llvm::APSInt(64,
false) = 0);
4967 if (UncoveredArg.hasUncoveredArg()) {
4968 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
4969 assert(ArgIdx < Args.size() &&
"ArgIdx outside bounds");
4970 UncoveredArg.Diagnose(*
this,
true, Args[ArgIdx]);
4973 if (CT != SLCT_NotALiteral)
4975 return CT == SLCT_CheckedLiteral;
4979 if (Type == FST_Strftime)
4987 if (Type == FST_NSString &&
SourceMgr.isInSystemMacro(FormatLoc))
4992 if (Args.size() == firstDataArg) {
4993 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
4999 case FST_FreeBSDKPrintf:
5001 Diag(FormatLoc, diag::note_format_security_fixit)
5005 Diag(FormatLoc, diag::note_format_security_fixit)
5010 Diag(FormatLoc, diag::warn_format_nonliteral)
5020 const FormatStringLiteral *FExpr;
5021 const Expr *OrigFormatExpr;
5023 const unsigned FirstDataArg;
5024 const unsigned NumDataArgs;
5026 const bool HasVAListArg;
5027 ArrayRef<const Expr *> Args;
5029 llvm::SmallBitVector CoveredArgs;
5030 bool usesPositionalArgs;
5032 bool inFunctionCall;
5034 llvm::SmallBitVector &CheckedVarArgs;
5035 UncoveredArgHandler &UncoveredArg;
5038 CheckFormatHandler(
Sema &s,
const FormatStringLiteral *fexpr,
5039 const Expr *origFormatExpr,
5041 unsigned numDataArgs,
const char *beg,
bool hasVAListArg,
5042 ArrayRef<const Expr *> Args,
unsigned formatIdx,
5044 llvm::SmallBitVector &CheckedVarArgs,
5045 UncoveredArgHandler &UncoveredArg)
5046 :
S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
5047 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
5048 HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
5049 usesPositionalArgs(
false), atFirstArg(
true),
5050 inFunctionCall(inFunctionCall), CallType(callType),
5051 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
5052 CoveredArgs.resize(numDataArgs);
5053 CoveredArgs.reset();
5056 void DoneProcessing();
5058 void HandleIncompleteSpecifier(
const char *startSpecifier,
5059 unsigned specifierLen)
override;
5061 void HandleInvalidLengthModifier(
5064 const char *startSpecifier,
unsigned specifierLen,
5067 void HandleNonStandardLengthModifier(
5069 const char *startSpecifier,
unsigned specifierLen);
5071 void HandleNonStandardConversionSpecifier(
5073 const char *startSpecifier,
unsigned specifierLen);
5075 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
5077 void HandleInvalidPosition(
const char *startSpecifier,
5078 unsigned specifierLen,
5081 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
5083 void HandleNullChar(
const char *nullCharacter)
override;
5085 template <
typename Range>
5087 EmitFormatDiagnostic(
Sema &
S,
bool inFunctionCall,
const Expr *ArgumentExpr,
5089 bool IsStringLocation, Range StringRange,
5090 ArrayRef<FixItHint> Fixit = None);
5093 bool HandleInvalidConversionSpecifier(
unsigned argIndex,
SourceLocation Loc,
5094 const char *startSpec,
5095 unsigned specifierLen,
5096 const char *csStart,
unsigned csLen);
5099 const char *startSpec,
5100 unsigned specifierLen);
5104 unsigned specifierLen);
5107 const Expr *getDataArg(
unsigned i)
const;
5111 const char *startSpecifier,
unsigned specifierLen,
5114 template <
typename Range>
5116 bool IsStringLocation, Range StringRange,
5117 ArrayRef<FixItHint> Fixit = None);
5121 SourceRange CheckFormatHandler::getFormatStringRange() {
5126 getSpecifierRange(
const char *startSpecifier,
unsigned specifierLen) {
5136 SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
5141 void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
5142 unsigned specifierLen){
5143 EmitFormatDiagnostic(
S.
PDiag(diag::warn_printf_incomplete_specifier),
5144 getLocationOfByte(startSpecifier),
5146 getSpecifierRange(startSpecifier, specifierLen));
5149 void CheckFormatHandler::HandleInvalidLengthModifier(
5152 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
5153 using namespace analyze_format_string;
5156 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5161 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
5162 getLocationOfByte(LM.getStart()),
5164 getSpecifierRange(startSpecifier, specifierLen));
5166 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5167 << FixedLM->toString()
5172 if (DiagID == diag::warn_format_nonsensical_length)
5175 EmitFormatDiagnostic(
S.
PDiag(DiagID) << LM.toString() << CS.
toString(),
5176 getLocationOfByte(LM.getStart()),
5178 getSpecifierRange(startSpecifier, specifierLen),
5183 void CheckFormatHandler::HandleNonStandardLengthModifier(
5185 const char *startSpecifier,
unsigned specifierLen) {
5186 using namespace analyze_format_string;
5189 CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
5194 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
5195 << LM.toString() << 0,
5196 getLocationOfByte(LM.getStart()),
5198 getSpecifierRange(startSpecifier, specifierLen));
5200 S.
Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
5201 << FixedLM->toString()
5205 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
5206 << LM.toString() << 0,
5207 getLocationOfByte(LM.getStart()),
5209 getSpecifierRange(startSpecifier, specifierLen));
5213 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
5215 const char *startSpecifier,
unsigned specifierLen) {
5216 using namespace analyze_format_string;
5221 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
5225 getSpecifierRange(startSpecifier, specifierLen));
5228 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
5229 << FixedCS->toString()
5232 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard)
5236 getSpecifierRange(startSpecifier, specifierLen));
5240 void CheckFormatHandler::HandlePosition(
const char *startPos,
5242 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_non_standard_positional_arg),
5243 getLocationOfByte(startPos),
5245 getSpecifierRange(startPos, posLen));
5249 CheckFormatHandler::HandleInvalidPosition(
const char *startPos,
unsigned posLen,
5251 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_invalid_positional_specifier)
5253 getLocationOfByte(startPos),
true,
5254 getSpecifierRange(startPos, posLen));
5257 void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
5259 EmitFormatDiagnostic(
S.
PDiag(diag::warn_format_zero_positional_specifier),
5260 getLocationOfByte(startPos),
5262 getSpecifierRange(startPos, posLen));
5265 void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
5266 if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
5268 EmitFormatDiagnostic(
5269 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
5270 getLocationOfByte(nullCharacter),
true,
5271 getFormatStringRange());
5277 const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
5278 return Args[FirstDataArg + i];
5281 void CheckFormatHandler::DoneProcessing() {
5284 if (!HasVAListArg) {
5287 signed notCoveredArg = CoveredArgs.find_first();
5288 if (notCoveredArg >= 0) {
5289 assert((
unsigned)notCoveredArg < NumDataArgs);
5290 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
5292 UncoveredArg.setAllCovered();
5297 void UncoveredArgHandler::Diagnose(
Sema &
S,
bool IsFunctionCall,
5298 const Expr *ArgExpr) {
5299 assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
5311 for (
auto E : DiagnosticExprs)
5312 PDiag <<
E->getSourceRange();
5314 CheckFormatHandler::EmitFormatDiagnostic(
5315 S, IsFunctionCall, DiagnosticExprs[0],
5321 CheckFormatHandler::HandleInvalidConversionSpecifier(
unsigned argIndex,
5323 const char *startSpec,
5324 unsigned specifierLen,
5325 const char *csStart,
5327 bool keepGoing =
true;
5328 if (argIndex < NumDataArgs) {
5331 CoveredArgs.set(argIndex);
5347 std::string CodePointStr;
5348 if (!llvm::sys::locale::isPrint(*csStart)) {
5349 llvm::UTF32 CodePoint;
5350 const llvm::UTF8 **B =
reinterpret_cast<const llvm::UTF8 **
>(&csStart);
5351 const llvm::UTF8 *
E =
5352 reinterpret_cast<const llvm::UTF8 *
>(csStart + csLen);
5353 llvm::ConversionResult Result =
5354 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
5356 if (Result != llvm::conversionOK) {
5357 unsigned char FirstChar = *csStart;
5358 CodePoint = (llvm::UTF32)FirstChar;
5361 llvm::raw_string_ostream OS(CodePointStr);
5362 if (CodePoint < 256)
5363 OS <<
"\\x" << llvm::format(
"%02x", CodePoint);
5364 else if (CodePoint <= 0xFFFF)
5365 OS <<
"\\u" << llvm::format(
"%04x", CodePoint);
5367 OS <<
"\\U" << llvm::format(
"%08x", CodePoint);
5372 EmitFormatDiagnostic(
5374 true, getSpecifierRange(startSpec, specifierLen));
5380 CheckFormatHandler::HandlePositionalNonpositionalArgs(
SourceLocation Loc,
5381 const char *startSpec,
5382 unsigned specifierLen) {
5383 EmitFormatDiagnostic(
5384 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args),
5385 Loc,
true, getSpecifierRange(startSpec, specifierLen));
5389 CheckFormatHandler::CheckNumArgs(
5392 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
5394 if (argIndex >= NumDataArgs) {
5396 ? (S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
5397 << (argIndex+1) << NumDataArgs)
5398 : S.
PDiag(diag::warn_printf_insufficient_data_args);
5399 EmitFormatDiagnostic(
5400 PDiag, getLocationOfByte(CS.
getStart()),
true,
5401 getSpecifierRange(startSpecifier, specifierLen));
5405 UncoveredArg.setAllCovered();
5411 template<
typename Range>
5414 bool IsStringLocation,
5416 ArrayRef<FixItHint>
FixIt) {
5417 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
5418 Loc, IsStringLocation, StringRange, FixIt);
5448 template <
typename Range>
5449 void CheckFormatHandler::EmitFormatDiagnostic(
5450 Sema &S,
bool InFunctionCall,
const Expr *ArgumentExpr,
5452 Range StringRange, ArrayRef<FixItHint>
FixIt) {
5453 if (InFunctionCall) {
5458 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
5462 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
5463 diag::note_format_string_defined);
5465 Note << StringRange;
5473 class CheckPrintfHandler :
public CheckFormatHandler {
5475 CheckPrintfHandler(
Sema &s,
const FormatStringLiteral *fexpr,
5476 const Expr *origFormatExpr,
5478 unsigned numDataArgs,
bool isObjC,
const char *beg,
5479 bool hasVAListArg, ArrayRef<const Expr *> Args,
5480 unsigned formatIdx,
bool inFunctionCall,
5482 llvm::SmallBitVector &CheckedVarArgs,
5483 UncoveredArgHandler &UncoveredArg)
5484 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
5485 numDataArgs, beg, hasVAListArg, Args, formatIdx,
5486 inFunctionCall, CallType, CheckedVarArgs,
5492 bool allowsObjCArg()
const {
5497 bool HandleInvalidPrintfConversionSpecifier(
5499 const char *startSpecifier,
5500 unsigned specifierLen)
override;
5503 const char *startSpecifier,
5504 unsigned specifierLen)
override;
5506 const char *StartSpecifier,
5507 unsigned SpecifierLen,
5511 const char *startSpecifier,
unsigned specifierLen);
5513 const analyze_printf::OptionalAmount &Amt,
5515 const char *startSpecifier,
unsigned specifierLen);
5517 const analyze_printf::OptionalFlag &flag,
5518 const char *startSpecifier,
unsigned specifierLen);
5520 const analyze_printf::OptionalFlag &ignoredFlag,
5521 const analyze_printf::OptionalFlag &flag,
5522 const char *startSpecifier,
unsigned specifierLen);
5523 bool checkForCStrMembers(
const analyze_printf::ArgType &AT,
5526 void HandleEmptyObjCModifierFlag(
const char *startFlag,
5527 unsigned flagLen)
override;
5529 void HandleInvalidObjCModifierFlag(
const char *startFlag,
5530 unsigned flagLen)
override;
5532 void HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
5533 const char *flagsEnd,
5534 const char *conversionPosition)
5539 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
5541 const char *startSpecifier,
5542 unsigned specifierLen) {
5546 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
5548 startSpecifier, specifierLen,
5552 bool CheckPrintfHandler::HandleAmount(
5554 unsigned k,
const char *startSpecifier,
5555 unsigned specifierLen) {
5557 if (!HasVAListArg) {
5559 if (argIndex >= NumDataArgs) {
5560 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
5564 getSpecifierRange(startSpecifier, specifierLen));
5574 CoveredArgs.set(argIndex);
5575 const Expr *Arg = getDataArg(argIndex);
5582 assert(AT.isValid());
5584 if (!AT.matchesType(S.
Context, T)) {
5585 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_wrong_type)
5586 << k << AT.getRepresentativeTypeName(S.
Context)
5590 getSpecifierRange(startSpecifier, specifierLen));
5600 void CheckPrintfHandler::HandleInvalidAmount(
5602 const analyze_printf::OptionalAmount &Amt,
5604 const char *startSpecifier,
5605 unsigned specifierLen) {
5610 Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
5612 Amt.getConstantLength()))
5615 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
5617 getLocationOfByte(Amt.getStart()),
5619 getSpecifierRange(startSpecifier, specifierLen),
5624 const analyze_printf::OptionalFlag &flag,
5625 const char *startSpecifier,
5626 unsigned specifierLen) {
5630 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_flag)
5631 << flag.toString() << CS.
toString(),
5632 getLocationOfByte(flag.getPosition()),
5634 getSpecifierRange(startSpecifier, specifierLen),
5636 getSpecifierRange(flag.getPosition(), 1)));
5639 void CheckPrintfHandler::HandleIgnoredFlag(
5641 const analyze_printf::OptionalFlag &ignoredFlag,
5642 const analyze_printf::OptionalFlag &flag,
5643 const char *startSpecifier,
5644 unsigned specifierLen) {
5646 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
5647 << ignoredFlag.toString() << flag.toString(),
5648 getLocationOfByte(ignoredFlag.getPosition()),
5650 getSpecifierRange(startSpecifier, specifierLen),
5652 getSpecifierRange(ignoredFlag.getPosition(), 1)));
5659 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
5662 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_empty_objc_flag),
5663 getLocationOfByte(startFlag),
5665 getSpecifierRange(startFlag, flagLen));
5668 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
5671 auto Range = getSpecifierRange(startFlag, flagLen);
5672 StringRef flag(startFlag, flagLen);
5673 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
5674 getLocationOfByte(startFlag),
5679 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
5680 const char *flagsStart,
const char *flagsEnd,
const char *conversionPosition) {
5682 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
5683 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
5684 EmitFormatDiagnostic(S.
PDiag(diag) << StringRef(conversionPosition, 1),
5685 getLocationOfByte(conversionPosition),
5693 template<
typename MemberKind>
5694 static llvm::SmallPtrSet<MemberKind*, 1>
5697 llvm::SmallPtrSet<MemberKind*, 1> Results;
5714 if (MemberKind *FK = dyn_cast<MemberKind>(decl))
5725 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5727 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str", *
this, E->
getType());
5728 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5730 if ((*MI)->getMinRequiredArguments() == 0)
5738 bool CheckPrintfHandler::checkForCStrMembers(
5739 const analyze_printf::ArgType &AT,
const Expr *E) {
5740 typedef llvm::SmallPtrSet<CXXMethodDecl*, 1> MethodSet;
5743 CXXRecordMembersNamed<CXXMethodDecl>(
"c_str",
S, E->
getType());
5745 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
5765 const char *startSpecifier,
5766 unsigned specifierLen) {
5767 using namespace analyze_format_string;
5768 using namespace analyze_printf;
5777 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
5778 startSpecifier, specifierLen);
5786 startSpecifier, specifierLen)) {
5791 startSpecifier, specifierLen)) {
5803 if (argIndex < NumDataArgs) {
5807 CoveredArgs.set(argIndex);
5811 if (CS.
getKind() == ConversionSpecifier::FreeBSDbArg ||
5812 CS.
getKind() == ConversionSpecifier::FreeBSDDArg) {
5814 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
5818 CoveredArgs.set(argIndex + 1);
5821 const Expr *Ex = getDataArg(argIndex);
5822 const analyze_printf::ArgType &AT =
5823 (CS.
getKind() == ConversionSpecifier::FreeBSDbArg) ?
5824 ArgType(S.Context.IntTy) : ArgType::CPointerTy;
5825 if (AT.isValid() && !AT.matchesType(S.Context, Ex->
getType()))
5826 EmitFormatDiagnostic(
5827 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5828 << AT.getRepresentativeTypeName(S.Context) << Ex->
getType()
5831 getSpecifierRange(startSpecifier, specifierLen));
5834 Ex = getDataArg(argIndex + 1);
5835 const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
5836 if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
5837 EmitFormatDiagnostic(
5838 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
5839 << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
5840 <<
false << Ex->getSourceRange(),
5841 Ex->getLocStart(),
false,
5842 getSpecifierRange(startSpecifier, specifierLen));
5849 if (!allowsObjCArg() && CS.
isObjCArg()) {
5850 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5856 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5862 EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
5865 getSpecifierRange(startSpecifier, specifierLen));
5872 (CS.
getKind() == ConversionSpecifier::PArg ||
5873 CS.
getKind() == ConversionSpecifier::sArg ||
5874 CS.
getKind() == ConversionSpecifier::ObjCObjArg)) {
5875 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
5882 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5884 getLocationOfByte(FS.
isPublic().getPosition()),
5886 getSpecifierRange(startSpecifier, specifierLen));
5889 EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
5891 getLocationOfByte(FS.
isPrivate().getPosition()),
5893 getSpecifierRange(startSpecifier, specifierLen));
5900 startSpecifier, specifierLen);
5906 startSpecifier, specifierLen);
5910 if (CS.
getKind() == ConversionSpecifier::PArg &&
5911 FS.
getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
5912 EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
5913 getLocationOfByte(startSpecifier),
5915 getSpecifierRange(startSpecifier, specifierLen));
5924 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
5926 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
5935 startSpecifier, specifierLen);
5938 startSpecifier, specifierLen);
5942 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5943 diag::warn_format_nonsensical_length);
5945 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
5947 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
5948 diag::warn_format_non_standard_conversion_spec);
5951 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
5957 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
5960 const Expr *Arg = getDataArg(argIndex);
5964 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
5976 case Stmt::ArraySubscriptExprClass:
5977 case Stmt::CallExprClass:
5978 case Stmt::CharacterLiteralClass:
5979 case Stmt::CXXBoolLiteralExprClass:
5980 case Stmt::DeclRefExprClass:
5981 case Stmt::FloatingLiteralClass:
5982 case Stmt::IntegerLiteralClass:
5983 case Stmt::MemberExprClass:
5984 case Stmt::ObjCArrayLiteralClass:
5985 case Stmt::ObjCBoolLiteralExprClass:
5986 case Stmt::ObjCBoxedExprClass:
5987 case Stmt::ObjCDictionaryLiteralClass:
5988 case Stmt::ObjCEncodeExprClass:
5989 case Stmt::ObjCIvarRefExprClass:
5990 case Stmt::ObjCMessageExprClass:
5991 case Stmt::ObjCPropertyRefExprClass:
5992 case Stmt::ObjCStringLiteralClass:
5993 case Stmt::ObjCSubscriptRefExprClass:
5994 case Stmt::ParenExprClass:
5995 case Stmt::StringLiteralClass:
5996 case Stmt::UnaryOperatorClass:
6003 static std::pair<QualType, StringRef>
6010 StringRef
Name = UserTy->getDecl()->getName();
6012 .Case(
"CFIndex", Context.
LongTy)
6013 .Case(
"NSInteger", Context.
LongTy)
6015 .Case(
"SInt32", Context.
IntTy)
6020 return std::make_pair(CastTy, Name);
6022 TyTy = UserTy->desugar();
6026 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
6028 PE->getSubExpr()->getType(),
6037 StringRef TrueName, FalseName;
6039 std::tie(TrueTy, TrueName) =
6041 CO->getTrueExpr()->getType(),
6043 std::tie(FalseTy, FalseName) =
6045 CO->getFalseExpr()->getType(),
6046 CO->getFalseExpr());
6048 if (TrueTy == FalseTy)
6049 return std::make_pair(TrueTy, TrueName);
6050 else if (TrueTy.
isNull())
6051 return std::make_pair(FalseTy, FalseName);
6052 else if (FalseTy.
isNull())
6053 return std::make_pair(TrueTy, TrueName);
6056 return std::make_pair(
QualType(), StringRef());
6061 const char *StartSpecifier,
6062 unsigned SpecifierLen,
6064 using namespace analyze_format_string;
6065 using namespace analyze_printf;
6068 const analyze_printf::ArgType &AT = FS.
getArgType(S.Context, isObjCContext());
6073 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
6074 ExprTy = TET->getUnderlyingExpr()->getType();
6077 analyze_printf::ArgType::MatchKind
match = AT.matchesType(S.Context, ExprTy);
6079 if (
match == analyze_printf::ArgType::Match) {
6088 if (ICE->getCastKind() == CK_IntegralCast ||
6089 ICE->getCastKind() == CK_FloatingCast) {
6090 E = ICE->getSubExpr();
6096 if (ICE->getType() == S.Context.IntTy ||
6097 ICE->getType() == S.Context.UnsignedIntTy) {
6099 if (AT.matchesType(S.Context, ExprTy))
6107 if (ExprTy == S.Context.IntTy)
6108 if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
6109 ExprTy = S.Context.CharTy;
6113 bool IsEnum =
false;
6114 if (
auto EnumTy = ExprTy->getAs<
EnumType>()) {
6115 ExprTy = EnumTy->getDecl()->getIntegerType();
6123 if (isObjCContext() &&
6125 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
6126 !ExprTy->isCharType()) {
6129 IntendedTy = S.Context.UnsignedShortTy;
6134 const llvm::APInt &V = IL->getValue();
6135 if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
6141 if (S.LookupName(Result, S.getCurScope())) {
6144 if (TD->getUnderlyingType() == IntendedTy)
6145 IntendedTy = S.Context.getTypedefType(TD);
6152 bool ShouldNotPrintDirectly =
false; StringRef CastTyName;
6153 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
6157 IntendedTy = CastTy;
6158 ShouldNotPrintDirectly =
true;
6163 PrintfSpecifier fixedFS = FS;
6165 fixedFS.
fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
6170 llvm::raw_svector_ostream os(buf);
6171 fixedFS.toString(os);
6173 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
6175 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
6176 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6178 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6182 EmitFormatDiagnostic(S.PDiag(diag)
6183 << AT.getRepresentativeTypeName(S.Context)
6197 llvm::raw_svector_ostream CastFix(CastBuf);
6199 IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
6203 if (!AT.matchesType(S.Context, IntendedTy))
6208 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
6226 if (ShouldNotPrintDirectly) {
6231 if (
const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
6232 Name = TypedefTy->getDecl()->getName();
6235 EmitFormatDiagnostic(S.PDiag(diag::warn_format_argument_needs_cast)
6236 << Name << IntendedTy << IsEnum
6244 EmitFormatDiagnostic(
6245 S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
6246 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
6258 switch (S.isValidVarArgType(ExprTy)) {
6261 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6262 if (
match == analyze_printf::ArgType::NoMatchPedantic) {
6263 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6266 EmitFormatDiagnostic(
6267 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
6274 EmitFormatDiagnostic(
6275 S.PDiag(diag::warn_non_pod_vararg_with_format_string)
6276 << S.getLangOpts().CPlusPlus11
6279 << AT.getRepresentativeTypeName(S.Context)
6283 checkForCStrMembers(AT, E);
6287 if (ExprTy->isObjCObjectType())
6288 EmitFormatDiagnostic(
6289 S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
6290 << S.getLangOpts().CPlusPlus11
6293 << AT.getRepresentativeTypeName(S.Context)
6300 S.Diag(E->
getLocStart(), diag::err_cannot_pass_to_vararg_format)
6301 << isa<InitListExpr>(E) << ExprTy << CallType
6302 << AT.getRepresentativeTypeName(S.Context)
6307 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
6308 "format string specifier index out of range");
6309 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
6318 class CheckScanfHandler :
public CheckFormatHandler {
6320 CheckScanfHandler(
Sema &s,
const FormatStringLiteral *fexpr,
6322 unsigned firstDataArg,
unsigned numDataArgs,
6323 const char *beg,
bool hasVAListArg,
6324 ArrayRef<const Expr *> Args,
unsigned formatIdx,
6326 llvm::SmallBitVector &CheckedVarArgs,
6327 UncoveredArgHandler &UncoveredArg)
6328 : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
6329 numDataArgs, beg, hasVAListArg, Args, formatIdx,
6330 inFunctionCall, CallType, CheckedVarArgs,
6334 const char *startSpecifier,
6335 unsigned specifierLen)
override;
6337 bool HandleInvalidScanfConversionSpecifier(
6339 const char *startSpecifier,
6340 unsigned specifierLen)
override;
6342 void HandleIncompleteScanList(
const char *start,
const char *end)
override;
6346 void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
6348 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
6349 getLocationOfByte(end),
true,
6350 getSpecifierRange(start, end - start));
6353 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
6355 const char *startSpecifier,
6356 unsigned specifierLen) {
6361 return HandleInvalidConversionSpecifier(FS.
getArgIndex(),
6363 startSpecifier, specifierLen,
6367 bool CheckScanfHandler::HandleScanfSpecifier(
6369 const char *startSpecifier,
6370 unsigned specifierLen) {
6371 using namespace analyze_scanf;
6372 using namespace analyze_format_string;
6384 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
6385 startSpecifier, specifierLen);
6392 if (Amt.getHowSpecified() == OptionalAmount::Constant) {
6393 if (Amt.getConstantAmount() == 0) {
6395 Amt.getConstantLength());
6396 EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
6397 getLocationOfByte(Amt.getStart()),
6399 FixItHint::CreateRemoval(R));
6411 if (argIndex < NumDataArgs) {
6415 CoveredArgs.set(argIndex);
6420 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6421 diag::warn_format_nonsensical_length);
6423 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
6425 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
6426 diag::warn_format_non_standard_conversion_spec);
6429 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
6435 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
6439 const Expr *Ex = getDataArg(argIndex);
6445 if (!AT.isValid()) {
6450 AT.matchesType(S.Context, Ex->getType());
6455 ScanfSpecifier fixedFS = FS;
6456 bool success = fixedFS.
fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
6457 S.getLangOpts(), S.Context);
6459 unsigned diag = diag::warn_format_conversion_argument_type_mismatch;
6461 diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
6467 llvm::raw_svector_ostream os(buf);
6468 fixedFS.toString(os);
6470 EmitFormatDiagnostic(
6471 S.PDiag(diag) << AT.getRepresentativeTypeName(S.Context)
6472 << Ex->getType() <<
false << Ex->getSourceRange(),
6475 getSpecifierRange(startSpecifier, specifierLen),
6477 getSpecifierRange(startSpecifier, specifierLen), os.str()));
6479 EmitFormatDiagnostic(S.PDiag(diag)
6480 << AT.getRepresentativeTypeName(S.Context)
6481 << Ex->getType() <<
false << Ex->getSourceRange(),
6484 getSpecifierRange(startSpecifier, specifierLen));
6491 const Expr *OrigFormatExpr,
6492 ArrayRef<const Expr *> Args,
6493 bool HasVAListArg,
unsigned format_idx,
6494 unsigned firstDataArg,
6496 bool inFunctionCall,
6498 llvm::SmallBitVector &CheckedVarArgs,
6499 UncoveredArgHandler &UncoveredArg) {
6501 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
6502 CheckFormatHandler::EmitFormatDiagnostic(
6503 S, inFunctionCall, Args[format_idx],
6504 S.
PDiag(diag::warn_format_string_is_wide_literal), FExpr->getLocStart(),
6510 StringRef StrRef = FExpr->getString();
6511 const char *Str = StrRef.data();
6515 assert(T &&
"String literal not of constant array type!");
6516 size_t TypeSize = T->
getSize().getZExtValue();
6517 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
6518 const unsigned numDataArgs = Args.size() - firstDataArg;
6522 if (TypeSize <= StrRef.size() &&
6523 StrRef.substr(0, TypeSize).find(
'\0') == StringRef::npos) {
6524 CheckFormatHandler::EmitFormatDiagnostic(
6525 S, inFunctionCall, Args[format_idx],
6526 S.
PDiag(diag::warn_printf_format_string_not_null_terminated),
6527 FExpr->getLocStart(),
6533 if (StrLen == 0 && numDataArgs > 0) {
6534 CheckFormatHandler::EmitFormatDiagnostic(
6535 S, inFunctionCall, Args[format_idx],
6536 S.
PDiag(diag::warn_empty_format_string), FExpr->getLocStart(),
6544 CheckPrintfHandler H(
6545 S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
6547 HasVAListArg, Args, format_idx, inFunctionCall, CallType,
6548 CheckedVarArgs, UncoveredArg);
6556 CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
6557 numDataArgs, Str, HasVAListArg, Args, format_idx,
6558 inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
6570 const char *Str = StrRef.data();
6573 assert(T &&
"String literal not of constant array type!");
6574 size_t TypeSize = T->
getSize().getZExtValue();
6575 size_t StrLen =
std::min(
std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
6586 switch (AbsFunction) {
6590 case Builtin::BI__builtin_abs:
6591 return Builtin::BI__builtin_labs;
6592 case Builtin::BI__builtin_labs:
6593 return Builtin::BI__builtin_llabs;
6594 case Builtin::BI__builtin_llabs:
6597 case Builtin::BI__builtin_fabsf:
6598 return Builtin::BI__builtin_fabs;
6599 case Builtin::BI__builtin_fabs:
6600 return Builtin::BI__builtin_fabsl;
6601 case Builtin::BI__builtin_fabsl:
6604 case Builtin::BI__builtin_cabsf:
6605 return Builtin::BI__builtin_cabs;
6606 case Builtin::BI__builtin_cabs:
6607 return Builtin::BI__builtin_cabsl;
6608 case Builtin::BI__builtin_cabsl:
6611 case Builtin::BIabs:
6612 return Builtin::BIlabs;
6613 case Builtin::BIlabs:
6614 return Builtin::BIllabs;
6615 case Builtin::BIllabs:
6618 case Builtin::BIfabsf:
6619 return Builtin::BIfabs;
6620 case Builtin::BIfabs:
6621 return Builtin::BIfabsl;
6622 case Builtin::BIfabsl:
6625 case Builtin::BIcabsf:
6626 return Builtin::BIcabs;
6627 case Builtin::BIcabs:
6628 return Builtin::BIcabsl;
6629 case Builtin::BIcabsl:
6658 unsigned AbsFunctionKind) {
6659 unsigned BestKind = 0;
6661 for (
unsigned Kind = AbsFunctionKind;
Kind != 0;
6667 else if (Context.
hasSameType(ParamType, ArgType)) {
6690 llvm_unreachable(
"Type not integer, floating, or complex");
6697 switch (ValueKind) {
6702 case Builtin::BI__builtin_fabsf:
6703 case Builtin::BI__builtin_fabs:
6704 case Builtin::BI__builtin_fabsl:
6705 case Builtin::BI__builtin_cabsf:
6706 case Builtin::BI__builtin_cabs:
6707 case Builtin::BI__builtin_cabsl:
6708 return Builtin::BI__builtin_abs;
6709 case Builtin::BIfabsf:
6710 case Builtin::BIfabs:
6711 case Builtin::BIfabsl:
6712 case Builtin::BIcabsf:
6713 case Builtin::BIcabs:
6714 case Builtin::BIcabsl:
6715 return Builtin::BIabs;
6721 case Builtin::BI__builtin_abs:
6722 case Builtin::BI__builtin_labs:
6723 case Builtin::BI__builtin_llabs:
6724 case Builtin::BI__builtin_cabsf:
6725 case Builtin::BI__builtin_cabs:
6726 case Builtin::BI__builtin_cabsl:
6727 return Builtin::BI__builtin_fabsf;
6728 case Builtin::BIabs:
6729 case Builtin::BIlabs:
6730 case Builtin::BIllabs:
6731 case Builtin::BIcabsf:
6732 case Builtin::BIcabs:
6733 case Builtin::BIcabsl:
6734 return Builtin::BIfabsf;
6740 case Builtin::BI__builtin_abs:
6741 case Builtin::BI__builtin_labs:
6742 case Builtin::BI__builtin_llabs:
6743 case Builtin::BI__builtin_fabsf:
6744 case Builtin::BI__builtin_fabs:
6745 case Builtin::BI__builtin_fabsl:
6746 return Builtin::BI__builtin_cabsf;
6747 case Builtin::BIabs:
6748 case Builtin::BIlabs:
6749 case Builtin::BIllabs:
6750 case Builtin::BIfabsf:
6751 case Builtin::BIfabs:
6752 case Builtin::BIfabsl:
6753 return Builtin::BIcabsf;
6756 llvm_unreachable(
"Unable to convert function");
6767 case Builtin::BI__builtin_abs:
6768 case Builtin::BI__builtin_fabs:
6769 case Builtin::BI__builtin_fabsf:
6770 case Builtin::BI__builtin_fabsl:
6771 case Builtin::BI__builtin_labs:
6772 case Builtin::BI__builtin_llabs:
6773 case Builtin::BI__builtin_cabs:
6774 case Builtin::BI__builtin_cabsf:
6775 case Builtin::BI__builtin_cabsl:
6776 case Builtin::BIabs:
6777 case Builtin::BIlabs:
6778 case Builtin::BIllabs:
6779 case Builtin::BIfabs:
6780 case Builtin::BIfabsf:
6781 case Builtin::BIfabsl:
6782 case Builtin::BIcabs:
6783 case Builtin::BIcabsf:
6784 case Builtin::BIcabsl:
6787 llvm_unreachable(
"Unknown Builtin type");
6793 unsigned AbsKind,
QualType ArgType) {
6794 bool EmitHeaderHint =
true;
6795 const char *HeaderName =
nullptr;
6796 const char *FunctionName =
nullptr;
6798 FunctionName =
"std::abs";
6800 HeaderName =
"cstdlib";
6802 HeaderName =
"cmath";
6804 llvm_unreachable(
"Invalid Type");
6810 R.suppressDiagnostics();
6813 for (
const auto *
I : R) {
6816 FDecl = dyn_cast<
FunctionDecl>(UsingD->getTargetDecl());
6833 EmitHeaderHint =
false;
6845 R.suppressDiagnostics();
6848 if (R.isSingleResult()) {
6851 EmitHeaderHint =
false;
6855 }
else if (!R.empty()) {
6861 S.
Diag(Loc, diag::note_replace_abs_function)
6867 if (!EmitHeaderHint)
6870 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
6874 template <std::
size_t StrLen>
6876 const char (&Str)[StrLen]) {
6888 void Sema::CheckAbsoluteValueFunction(
const CallExpr *Call,
6895 if (AbsKind == 0 && !IsStdAbs)
6904 const char *FunctionName =
6906 Diag(Call->
getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
6916 unsigned DiagType = 0;
6922 Diag(Call->
getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
6936 if (ArgValueKind == ParamValueKind) {
6942 << FDecl << ArgType << ParamType;
6944 if (NewAbsKind == 0)
6957 if (NewAbsKind == 0)
6961 << FDecl << ParamValueKind << ArgValueKind;
6968 void Sema::CheckMaxUnsignedZero(
const CallExpr *Call,
6970 if (!Call || !FDecl)
return;
6973 if (inTemplateInstantiation())
return;
6980 if (!ArgList)
return;
6981 if (ArgList->size() != 1)
return;
6984 const auto& TA = ArgList->
get(0);
6990 auto IsLiteralZeroArg = [](
const Expr*
E) ->
bool {
6992 if (!MTE)
return false;
6993 const auto *Num = dyn_cast<
IntegerLiteral>(MTE->GetTemporaryExpr());
6994 if (!Num)
return false;
6995 if (Num->getValue() != 0)
return false;
7001 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
7002 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
7005 if (IsFirstArgZero == IsSecondArgZero)
return;
7010 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
7017 if (IsFirstArgZero) {
7027 << FixItHint::CreateRemoval(RemovalRange);
7050 << SizeRange << FnName;
7051 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
7055 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
7066 bool &IsContained) {
7069 IsContained =
false;
7082 for (
auto *FD : RD->
fields()) {
7098 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7108 dyn_cast<UnaryExprOrTypeTraitExpr>(E))
7110 return SizeOf->getTypeOfArgument();
7122 void Sema::CheckMemaccessArguments(
const CallExpr *Call,
7129 unsigned ExpectedNumArgs =
7130 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
7134 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
7135 BId == Builtin::BIstrndup ? 1 : 2);
7137 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
7147 llvm::FoldingSetNodeID SizeOfArgID;
7156 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
7175 !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
7179 if (SizeOfArgID == llvm::FoldingSetNodeID())
7180 SizeOfArg->
Profile(SizeOfArgID, Context,
true);
7181 llvm::FoldingSetNodeID DestID;
7182 Dest->
Profile(DestID, Context,
true);
7183 if (DestID == SizeOfArgID) {
7186 unsigned ActionIdx = 0;
7187 StringRef ReadableName = FnName->
getName();
7189 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
7190 if (UnaryOp->getOpcode() == UO_AddrOf)
7213 DiagRuntimeBehavior(SL, SizeOfArg,
7214 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
7220 DiagRuntimeBehavior(SL, SizeOfArg,
7221 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
7235 DiagRuntimeBehavior(LenExpr->
getExprLoc(), Dest,
7236 PDiag(diag::warn_sizeof_pointer_type_memaccess)
7237 << FnName << SizeOfArgTy << ArgIdx
7255 unsigned OperationType = 0;
7258 if (ArgIdx != 0 || BId == Builtin::BImemcmp) {
7259 if (BId == Builtin::BImemcpy)
7261 else if(BId == Builtin::BImemmove)
7263 else if (BId == Builtin::BImemcmp)
7267 DiagRuntimeBehavior(
7269 PDiag(diag::warn_dyn_class_memaccess)
7270 << (BId == Builtin::BImemcmp ? ArgIdx + 2 : ArgIdx)
7271 << FnName << IsContained << ContainedRD << OperationType
7274 BId != Builtin::BImemset)
7275 DiagRuntimeBehavior(
7277 PDiag(diag::warn_arc_object_memaccess)
7278 << ArgIdx << FnName << PointeeTy
7283 DiagRuntimeBehavior(
7285 PDiag(diag::note_bad_memaccess_silence)
7305 if (isa<IntegerLiteral>(RHS))
7307 else if (isa<IntegerLiteral>(LHS))
7321 if (CAT->getSize().getSExtValue() <= 1)
7331 void Sema::CheckStrlcpycatArguments(
const CallExpr *Call,
7336 if ((NumArgs != 3) && (NumArgs != 4))
7341 const Expr *CompareWithSrc =
nullptr;
7349 CompareWithSrc = Ex;
7352 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
7353 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
7354 SizeCall->getNumArgs() == 1)
7359 if (!CompareWithSrc)
7371 if (!CompareWithSrcDRE ||
7375 const Expr *OriginalSizeArg = Call->
getArg(2);
7376 Diag(CompareWithSrcDRE->
getLocStart(), diag::warn_strlcpycat_wrong_size)
7388 llvm::raw_svector_ostream OS(sizeString);
7390 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7393 Diag(OriginalSizeArg->
getLocStart(), diag::note_strlcpycat_wrong_size)
7400 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
7401 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
7402 return D1->getDecl() == D2->getDecl();
7407 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
7411 return CE->getArg(0)->IgnoreParenCasts();
7419 void Sema::CheckStrncatArguments(
const CallExpr *CE,
7434 unsigned PatternType = 0;
7442 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
7443 if (BE->getOpcode() == BO_Sub) {
7445 const Expr *R = BE->getRHS()->IgnoreParenCasts();
7456 if (PatternType == 0)
7475 if (!isKnownSizeArray) {
7476 if (PatternType == 1)
7477 Diag(SL, diag::warn_strncat_wrong_size) << SR;
7479 Diag(SL, diag::warn_strncat_src_size) << SR;
7483 if (PatternType == 1)
7484 Diag(SL, diag::warn_strncat_large_size) << SR;
7486 Diag(SL, diag::warn_strncat_src_size) << SR;
7489 llvm::raw_svector_ostream OS(sizeString);
7491 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7494 DstArg->
printPretty(OS,
nullptr, getPrintingPolicy());
7497 Diag(SL, diag::note_strncat_wrong_size)
7504 SmallVectorImpl<const DeclRefExpr *> &refVars,
7505 const Decl *ParentDecl);
7507 SmallVectorImpl<const DeclRefExpr *> &refVars,
7508 const Decl *ParentDecl);
7516 const Expr *stackE =
nullptr;
7523 stackE =
EvalAddr(RetValExp, refVars,
nullptr);
7525 stackE =
EvalVal(RetValExp, refVars,
nullptr);
7533 for (
auto *DRE : refVars)
7534 if (isa<ParmVarDecl>(DRE->
getDecl()))
7539 if (refVars.empty()) {
7547 diagLoc = refVars[0]->getLocStart();
7548 diagRange = refVars[0]->getSourceRange();
7551 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(stackE)) {
7554 << DR->getDecl()->getDeclName() << diagRange;
7555 }
else if (isa<BlockExpr>(stackE)) {
7556 S.
Diag(diagLoc, diag::err_ret_local_block) << diagRange;
7557 }
else if (isa<AddrLabelExpr>(stackE)) {
7558 S.
Diag(diagLoc, diag::warn_ret_addr_label) << diagRange;
7562 if (
auto *ICE = dyn_cast<ImplicitCastExpr>(RetValExp)) {
7563 if (ICE->getCastKind() == CK_LValueToRValue) {
7567 S.
Diag(diagLoc, diag::warn_ret_local_temp_addr_ref)
7573 for (
unsigned i = 0, e = refVars.size(); i != e; ++i) {
7574 const VarDecl *VD = cast<VarDecl>(refVars[i]->getDecl());
7612 SmallVectorImpl<const DeclRefExpr *> &refVars,
7613 const Decl *ParentDecl) {
7621 "EvalAddr only works on pointers");
7629 case Stmt::DeclRefExprClass: {
7639 if (V->hasLocalStorage() &&
7640 V->getType()->isReferenceType() && V->hasInit()) {
7642 refVars.push_back(DR);
7643 return EvalAddr(V->getInit(), refVars, ParentDecl);
7649 case Stmt::UnaryOperatorClass: {
7659 case Stmt::BinaryOperatorClass: {
7665 if (op != BO_Add && op != BO_Sub)
7676 return EvalAddr(Base, refVars, ParentDecl);
7681 case Stmt::ConditionalOperatorClass: {
7688 if (!LHSExpr->getType()->isVoidType())
7689 if (
const Expr *LHS =
EvalAddr(LHSExpr, refVars, ParentDecl))
7700 case Stmt::BlockExprClass:
7701 if (cast<BlockExpr>(E)->getBlockDecl()->hasCaptures())
7705 case Stmt::AddrLabelExprClass:
7708 case Stmt::ExprWithCleanupsClass:
7709 return EvalAddr(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7714 case Stmt::ImplicitCastExprClass:
7715 case Stmt::CStyleCastExprClass:
7716 case Stmt::CXXFunctionalCastExprClass:
7717 case Stmt::ObjCBridgedCastExprClass:
7718 case Stmt::CXXStaticCastExprClass:
7719 case Stmt::CXXDynamicCastExprClass:
7720 case Stmt::CXXConstCastExprClass:
7721 case Stmt::CXXReinterpretCastExprClass: {
7722 const Expr* SubExpr = cast<CastExpr>(
E)->getSubExpr();
7723 switch (cast<CastExpr>(E)->getCastKind()) {
7724 case CK_LValueToRValue:
7726 case CK_BaseToDerived:
7727 case CK_DerivedToBase:
7728 case CK_UncheckedDerivedToBase:
7730 case CK_CPointerToObjCPointerCast:
7731 case CK_BlockPointerToObjCPointerCast:
7732 case CK_AnyPointerToBlockPointerCast:
7733 return EvalAddr(SubExpr, refVars, ParentDecl);
7735 case CK_ArrayToPointerDecay:
7736 return EvalVal(SubExpr, refVars, ParentDecl);
7742 return EvalAddr(SubExpr, refVars, ParentDecl);
7751 case Stmt::MaterializeTemporaryExprClass:
7752 if (
const Expr *Result =
7753 EvalAddr(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7754 refVars, ParentDecl))
7767 SmallVectorImpl<const DeclRefExpr *> &refVars,
7768 const Decl *ParentDecl) {
7781 case Stmt::ImplicitCastExprClass: {
7790 case Stmt::ExprWithCleanupsClass:
7791 return EvalVal(cast<ExprWithCleanups>(E)->getSubExpr(), refVars,
7794 case Stmt::DeclRefExprClass: {
7806 if (V == ParentDecl)
7809 if (V->hasLocalStorage()) {
7810 if (!V->getType()->isReferenceType())
7817 refVars.push_back(DR);
7818 return EvalVal(V->getInit(), refVars, V);
7826 case Stmt::UnaryOperatorClass: {
7838 case Stmt::ArraySubscriptExprClass: {
7842 const auto *ASE = cast<ArraySubscriptExpr>(
E);
7843 if (ASE->isTypeDependent())
7845 return EvalAddr(ASE->getBase(), refVars, ParentDecl);
7848 case Stmt::OMPArraySectionExprClass: {
7849 return EvalAddr(cast<OMPArraySectionExpr>(E)->getBase(), refVars,
7853 case Stmt::ConditionalOperatorClass: {
7861 if (!LHSExpr->getType()->isVoidType())
7862 if (
const Expr *LHS =
EvalVal(LHSExpr, refVars, ParentDecl))
7874 case Stmt::MemberExprClass: {
7890 case Stmt::MaterializeTemporaryExprClass:
7891 if (
const Expr *Result =
7892 EvalVal(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr(),
7893 refVars, ParentDecl))
7910 Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
7918 if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
7921 Diag(ReturnLoc, diag::warn_null_ret)
7931 if (Op == OO_New || Op == OO_Array_New) {
7936 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
7937 << FD << getLangOpts().CPlusPlus11;
7953 if (
DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
7954 if (
DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
7955 if (DRL->getDecl() == DRR->getDecl())
7963 if (
FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
7967 if (
FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
7972 if (
CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
7973 if (CL->getBuiltinCallee())
7976 if (
CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
7977 if (CR->getBuiltinCallee())
7981 Diag(Loc, diag::warn_floatingpoint_eq)
7999 IntRange(
unsigned Width,
bool NonNegative)
8000 : Width(Width), NonNegative(NonNegative)
8004 static IntRange forBoolType() {
8005 return IntRange(1,
true);
8010 return forValueOfCanonicalType(C,
8015 static IntRange forValueOfCanonicalType(
ASTContext &C,
const Type *T) {
8018 if (
const VectorType *VT = dyn_cast<VectorType>(T))
8019 T = VT->getElementType().getTypePtr();
8020 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
8021 T = CT->getElementType().getTypePtr();
8022 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
8023 T = AT->getValueType().getTypePtr();
8026 if (
const EnumType *ET = dyn_cast<EnumType>(T)) {
8034 if (NumNegative == 0)
8035 return IntRange(NumPositive,
true);
8037 return IntRange(
std::max(NumPositive + 1, NumNegative),
8052 static IntRange forTargetOfCanonicalType(
ASTContext &C,
const Type *T) {
8055 if (
const VectorType *VT = dyn_cast<VectorType>(T))
8056 T = VT->getElementType().getTypePtr();
8057 if (
const ComplexType *CT = dyn_cast<ComplexType>(T))
8058 T = CT->getElementType().getTypePtr();
8059 if (
const AtomicType *AT = dyn_cast<AtomicType>(T))
8060 T = AT->getValueType().getTypePtr();
8061 if (
const EnumType *ET = dyn_cast<EnumType>(T))
8071 static IntRange join(IntRange L, IntRange R) {
8072 return IntRange(
std::max(L.Width, R.Width),
8073 L.NonNegative && R.NonNegative);
8077 static IntRange meet(IntRange L, IntRange R) {
8078 return IntRange(
std::min(L.Width, R.Width),
8079 L.NonNegative || R.NonNegative);
8083 IntRange GetValueRange(
ASTContext &C, llvm::APSInt &value,
unsigned MaxWidth) {
8084 if (value.isSigned() && value.isNegative())
8085 return IntRange(value.getMinSignedBits(),
false);
8087 if (value.getBitWidth() > MaxWidth)
8088 value = value.trunc(MaxWidth);
8092 return IntRange(value.getActiveBits(),
true);
8096 unsigned MaxWidth) {
8098 return GetValueRange(C, result.
getInt(), MaxWidth);
8101 IntRange R = GetValueRange(C, result.
getVectorElt(0), Ty, MaxWidth);
8103 IntRange El = GetValueRange(C, result.
getVectorElt(i), Ty, MaxWidth);
8104 R = IntRange::join(R, El);
8112 return IntRange::join(R, I);
8127 Ty = AtomicRHS->getValueType();
8135 IntRange GetExprRange(
ASTContext &C,
const Expr *E,
unsigned MaxWidth) {
8141 return GetValueRange(C, result.
Val, GetExprType(E), MaxWidth);
8146 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
8147 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
8148 return GetExprRange(C, CE->getSubExpr(), MaxWidth);
8150 IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
8152 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
8153 CE->getCastKind() == CK_BooleanToSignedIntegral;
8157 return OutputTypeRange;
8160 = GetExprRange(C, CE->getSubExpr(),
8161 std::min(MaxWidth, OutputTypeRange.Width));
8164 if (SubRange.Width >= OutputTypeRange.Width)
8165 return OutputTypeRange;
8169 return IntRange(SubRange.Width,
8170 SubRange.NonNegative || OutputTypeRange.NonNegative);
8173 if (
const auto *CO = dyn_cast<ConditionalOperator>(E)) {
8176 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
8177 return GetExprRange(C, CondResult ? CO->getTrueExpr()
8178 : CO->getFalseExpr(),
8182 IntRange L = GetExprRange(C, CO->getTrueExpr(), MaxWidth);
8183 IntRange R = GetExprRange(C, CO->getFalseExpr(), MaxWidth);
8184 return IntRange::join(L, R);
8187 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
8188 switch (BO->getOpcode()) {
8199 return IntRange::forBoolType();
8211 return IntRange::forValueOfType(C, GetExprType(E));
8217 return GetExprRange(C, BO->getRHS(), MaxWidth);
8222 return IntRange::forValueOfType(C, GetExprType(E));
8227 return IntRange::meet(GetExprRange(C, BO->getLHS(), MaxWidth),
8228 GetExprRange(C, BO->getRHS(), MaxWidth));
8235 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
8236 if (I->getValue() == 1) {
8237 IntRange R = IntRange::forValueOfType(C, GetExprType(E));
8238 return IntRange(R.Width,
true);
8244 return IntRange::forValueOfType(C, GetExprType(E));
8248 case BO_ShrAssign: {
8249 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8254 if (BO->getRHS()->isIntegerConstantExpr(shift, C) &&
8255 shift.isNonNegative()) {
8256 unsigned zext = shift.getZExtValue();
8257 if (zext >= L.Width)
8258 L.Width = (L.NonNegative ? 0 : 1);
8268 return GetExprRange(C, BO->getRHS(), MaxWidth);
8272 if (BO->getLHS()->getType()->isPointerType())
8273 return IntRange::forValueOfType(C, GetExprType(E));
8281 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8284 llvm::APSInt divisor;
8285 if (BO->getRHS()->isIntegerConstantExpr(divisor, C)) {
8286 unsigned log2 = divisor.logBase2();
8287 if (log2 >= L.Width)
8288 L.Width = (L.NonNegative ? 0 : 1);
8290 L.Width =
std::min(L.Width - log2, MaxWidth);
8295 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8296 return IntRange(L.Width, L.NonNegative && R.NonNegative);
8304 IntRange L = GetExprRange(C, BO->getLHS(), opWidth);
8305 IntRange R = GetExprRange(C, BO->getRHS(), opWidth);
8307 IntRange meet = IntRange::meet(L, R);
8308 meet.Width =
std::min(meet.Width, MaxWidth);
8322 IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth);
8323 IntRange R = GetExprRange(C, BO->getRHS(), MaxWidth);
8324 return IntRange::join(L, R);
8327 if (
const auto *UO = dyn_cast<UnaryOperator>(E)) {
8328 switch (UO->getOpcode()) {
8331 return IntRange::forBoolType();
8336 return IntRange::forValueOfType(C, GetExprType(E));
8339 return GetExprRange(C, UO->getSubExpr(), MaxWidth);
8343 if (
const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
8344 return GetExprRange(C, OVE->getSourceExpr(), MaxWidth);
8347 return IntRange(BitField->getBitWidthValue(C),
8348 BitField->getType()->isUnsignedIntegerOrEnumerationType());
8350 return IntRange::forValueOfType(C, GetExprType(E));
8354 return GetExprRange(C, E, C.
getIntWidth(GetExprType(E)));
8360 bool IsSameFloatAfterCast(
const llvm::APFloat &value,
8361 const llvm::fltSemantics &Src,
8362 const llvm::fltSemantics &Tgt) {
8363 llvm::APFloat truncated = value;
8366 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
8367 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
8369 return truncated.bitwiseIsEqual(value);
8377 bool IsSameFloatAfterCast(
const APValue &value,
8378 const llvm::fltSemantics &Src,
8379 const llvm::fltSemantics &Tgt) {
8381 return IsSameFloatAfterCast(value.
getFloat(), Src, Tgt);
8385 if (!IsSameFloatAfterCast(value.
getVectorElt(i), Src, Tgt))
8401 if (isa<EnumConstantDecl>(DR->getDecl()))
8412 bool HasEnumType(
Expr *E) {
8415 if (ICE->getCastKind() != CK_IntegralCast &&
8416 ICE->getCastKind() != CK_NoOp)
8418 E = ICE->getSubExpr();
8433 if (op == BO_LT && IsZero(S, E->
getRHS())) {
8435 <<
"< 0" <<
"false" << HasEnumType(E->
getLHS())
8437 }
else if (op == BO_GE && IsZero(S, E->
getRHS())) {
8439 <<
">= 0" <<
"true" << HasEnumType(E->
getLHS())
8441 }
else if (op == BO_GT && IsZero(S, E->
getLHS())) {
8443 <<
"0 >" <<
"false" << HasEnumType(E->
getRHS())
8445 }
else if (op == BO_LE && IsZero(S, E->
getLHS())) {
8447 <<
"0 <=" <<
"true" << HasEnumType(E->
getRHS())
8453 Expr *Other,
const llvm::APSInt &Value,
8463 OtherT = AT->getValueType();
8464 IntRange OtherRange = IntRange::forValueOfType(S.
Context, OtherT);
8465 unsigned OtherWidth = OtherRange.Width;
8470 if ((Value == 0) && (!OtherIsBooleanType))
8478 LiteralConstant = 0,
8481 } LiteralOrBoolConstant = LiteralConstant;
8483 if (!OtherIsBooleanType) {
8490 "comparison with non-integer type");
8495 bool EqualityOnly =
false;
8499 if (!OtherRange.NonNegative) {
8501 if (ConstantSigned) {
8502 if (OtherWidth >= Value.getMinSignedBits())
8505 if (OtherWidth >= Value.getActiveBits() + 1)
8511 if (ConstantSigned) {
8512 if (Value.isNonNegative() && OtherWidth >= Value.getActiveBits())
8515 if (OtherWidth >= Value.getActiveBits())
8520 if (OtherRange.NonNegative) {
8521 if (OtherWidth >= Value.getActiveBits())
8524 assert(!ConstantSigned &&
8525 "Two signed types converted to unsigned types.");
8527 if (OtherWidth > Value.getActiveBits())
8533 Value.isNegative() && Value.getMinSignedBits() <= OtherWidth)
8538 EqualityOnly =
true;
8542 bool PositiveConstant = !ConstantSigned || Value.isNonNegative();
8544 if (op == BO_EQ || op == BO_NE) {
8545 IsTrue = op == BO_NE;
8546 }
else if (EqualityOnly) {
8548 }
else if (RhsConstant) {
8549 if (op == BO_GT || op == BO_GE)
8550 IsTrue = !PositiveConstant;
8552 IsTrue = PositiveConstant;
8554 if (op == BO_LT || op == BO_LE)
8555 IsTrue = !PositiveConstant;
8557 IsTrue = PositiveConstant;
8561 enum CompareBoolWithConstantResult { AFals, ATrue, Unkwn };
8562 enum ConstantValue { LT_Zero, Zero, One, GT_One, SizeOfConstVal };
8563 enum ConstantSide { Lhs, Rhs, SizeOfConstSides };
8565 static const struct LinkedConditions {
8566 CompareBoolWithConstantResult BO_LT_OP[SizeOfConstSides][SizeOfConstVal];
8567 CompareBoolWithConstantResult BO_GT_OP[SizeOfConstSides][SizeOfConstVal];
8568 CompareBoolWithConstantResult BO_LE_OP[SizeOfConstSides][SizeOfConstVal];
8569 CompareBoolWithConstantResult BO_GE_OP[SizeOfConstSides][SizeOfConstVal];
8570 CompareBoolWithConstantResult BO_EQ_OP[SizeOfConstSides][SizeOfConstVal];
8571 CompareBoolWithConstantResult BO_NE_OP[SizeOfConstSides][SizeOfConstVal];
8576 { { ATrue, Unkwn, AFals, AFals }, { AFals, AFals, Unkwn, ATrue } },
8577 { { AFals, AFals, Unkwn, ATrue }, { ATrue, Unkwn, AFals, AFals } },
8578 { { ATrue, ATrue, Unkwn, AFals }, { AFals, Unkwn, ATrue, ATrue } },
8579 { { AFals, Unkwn, ATrue, ATrue }, { ATrue, ATrue, Unkwn, AFals } },
8580 { { AFals, Unkwn, Unkwn, AFals }, { AFals, Unkwn, Unkwn, AFals } },
8581 { { ATrue, Unkwn, Unkwn, ATrue }, { ATrue, Unkwn, Unkwn, ATrue } }
8584 bool ConstantIsBoolLiteral = isa<CXXBoolLiteralExpr>(Constant);
8586 enum ConstantValue ConstVal = Zero;
8587 if (Value.isUnsigned() || Value.isNonNegative()) {
8589 LiteralOrBoolConstant =
8590 ConstantIsBoolLiteral ? CXXBoolLiteralFalse : LiteralConstant;
8592 }
else if (Value == 1) {
8593 LiteralOrBoolConstant =
8594 ConstantIsBoolLiteral ? CXXBoolLiteralTrue : LiteralConstant;
8597 LiteralOrBoolConstant = LiteralConstant;
8604 CompareBoolWithConstantResult CmpRes;
8608 CmpRes = TruthTable.BO_LT_OP[RhsConstant][ConstVal];
8611 CmpRes = TruthTable.BO_GT_OP[RhsConstant][ConstVal];
8614 CmpRes = TruthTable.BO_LE_OP[RhsConstant][ConstVal];
8617 CmpRes = TruthTable.BO_GE_OP[RhsConstant][ConstVal];
8620 CmpRes = TruthTable.BO_EQ_OP[RhsConstant][ConstVal];
8623 CmpRes = TruthTable.BO_NE_OP[RhsConstant][ConstVal];
8630 if (CmpRes == AFals) {
8632 }
else if (CmpRes == ATrue) {
8642 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
8643 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
8646 llvm::raw_svector_ostream OS(PrettySourceValue);
8648 OS <<
'\'' << *ED <<
"' (" << Value <<
")";
8654 S.
PDiag(diag::warn_out_of_range_compare)
8655 << OS.str() << LiteralOrBoolConstant
8656 << OtherT << (OtherIsBooleanType && !OtherT->
isBooleanType()) << IsTrue
8677 return AnalyzeImpConvsInComparison(S, E);
8681 return AnalyzeImpConvsInComparison(S, E);
8686 bool IsComparisonConstant =
false;
8691 llvm::APSInt RHSValue;
8692 bool IsRHSIntegralLiteral =
8694 llvm::APSInt LHSValue;
8695 bool IsLHSIntegralLiteral =
8697 if (IsRHSIntegralLiteral && !IsLHSIntegralLiteral)
8698 DiagnoseOutOfRangeComparison(S, E, RHS, LHS, RHSValue,
true);
8699 else if (!IsRHSIntegralLiteral && IsLHSIntegralLiteral)
8700 DiagnoseOutOfRangeComparison(S, E, LHS, RHS, LHSValue,
false);
8702 IsComparisonConstant =
8703 (IsRHSIntegralLiteral && IsLHSIntegralLiteral);
8714 return AnalyzeImpConvsInComparison(S, E);
8718 Expr *signedOperand, *unsignedOperand;
8721 "unsigned comparison between two signed integer expressions?");
8722 signedOperand = LHS;
8723 unsignedOperand = RHS;
8725 signedOperand = RHS;
8726 unsignedOperand = LHS;
8728 CheckTrivialUnsignedComparison(S, E);
8729 return AnalyzeImpConvsInComparison(S, E);
8733 IntRange signedRange = GetExprRange(S.
Context, signedOperand);
8743 if (signedRange.NonNegative)
8744 return CheckTrivialUnsignedComparison(S, E);
8752 IntRange unsignedRange = GetExprRange(S.
Context, unsignedOperand);
8756 assert(unsignedRange.NonNegative &&
"unsigned range includes negative?");
8758 if (unsignedRange.Width < comparisonWidth)
8763 S.
PDiag(diag::warn_mixed_sign_comparison)
8791 S.
Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
8829 unsigned DiagID = 0;
8830 if (SignedEnum && !SignedBitfield) {
8831 DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
8832 }
else if (SignedBitfield && !SignedEnum &&
8834 DiagID = diag::warn_signed_bitfield_enum_conversion;
8838 S.
Diag(InitLoc, DiagID) << Bitfield << ED;
8843 << SignedEnum << TypeRange;
8849 unsigned BitsNeeded = SignedEnum ?
std::max(ED->getNumPositiveBits() + 1,
8850 ED->getNumNegativeBits())
8851 : ED->getNumPositiveBits();
8854 if (BitsNeeded > FieldWidth) {
8856 S.
Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
8866 unsigned OriginalWidth = Value.getBitWidth();
8868 if (!Value.isSigned() || Value.isNegative())
8869 if (
UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
8870 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
8871 OriginalWidth = Value.getMinSignedBits();
8873 if (OriginalWidth <= FieldWidth)
8877 llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
8881 TruncatedValue = TruncatedValue.extend(OriginalWidth);
8882 if (llvm::APSInt::isSameValue(Value, TruncatedValue))
8887 if (FieldWidth == 1 && Value == 1)
8890 std::string PrettyValue = Value.toString(10);
8891 std::string PrettyTrunc = TruncatedValue.toString(10);
8893 S.
Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
8894 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
8909 if (AnalyzeBitFieldAssignment(S, Bitfield, E->
getRHS(),
8923 bool pruneControlFlow =
false) {
8924 if (pruneControlFlow) {
8937 unsigned diag,
bool pruneControlFlow =
false) {
8938 DiagnoseImpCast(S, E, E->
getType(), T, CContext, diag, pruneControlFlow);
8952 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
8955 const bool IsLiteral =
8956 isa<FloatingLiteral>(
E) || isa<FloatingLiteral>(InnerE);
8958 llvm::APFloat
Value(0.0);
8962 return DiagnoseImpCast(S, E, T, CContext,
8963 diag::warn_impcast_float_integer, PruneWarnings);
8966 bool isExact =
false;
8970 if (Value.convertToInteger(IntegerValue, llvm::APFloat::rmTowardZero,
8971 &isExact) == llvm::APFloat::opOK &&
8973 if (IsLiteral)
return;
8974 return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
8978 unsigned DiagID = 0;
8981 DiagID = diag::warn_impcast_literal_float_to_integer;
8982 }
else if (IntegerValue == 0) {
8983 if (Value.isZero()) {
8984 return DiagnoseImpCast(S, E, T, CContext,
8985 diag::warn_impcast_float_integer, PruneWarnings);
8988 DiagID = diag::warn_impcast_float_to_integer_zero;
8990 if (IntegerValue.isUnsigned()) {
8991 if (!IntegerValue.isMaxValue()) {
8992 return DiagnoseImpCast(S, E, T, CContext,
8993 diag::warn_impcast_float_integer, PruneWarnings);
8996 if (!IntegerValue.isMaxSignedValue() &&
8997 !IntegerValue.isMinSignedValue()) {
8998 return DiagnoseImpCast(S, E, T, CContext,
8999 diag::warn_impcast_float_integer, PruneWarnings);
9003 DiagID = diag::warn_impcast_float_to_integer;
9012 unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
9013 precision = (precision * 59 + 195) / 196;
9014 Value.toString(PrettySourceValue, precision);
9018 PrettyTargetValue = Value.isZero() ?
"false" :
"true";
9020 IntegerValue.toString(PrettyTargetValue);
9022 if (PruneWarnings) {
9026 << PrettySourceValue << PrettyTargetValue
9035 std::string PrettyPrintInRange(
const llvm::APSInt &Value, IntRange Range) {
9036 if (!Range.Width)
return "0";
9038 llvm::APSInt ValueInRange =
Value;
9039 ValueInRange.setIsSigned(!Range.NonNegative);
9040 ValueInRange = ValueInRange.trunc(Range.Width);
9041 return ValueInRange.toString(10);
9044 bool IsImplicitBoolFloatConversion(
Sema &S,
Expr *Ex,
bool ToBool) {
9045 if (!isa<ImplicitCastExpr>(Ex))
9050 const Type *Source =
9057 const Type *BoolCandidateType = ToBool ? Target : Source;
9059 return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
9063 void CheckImplicitArgumentConversions(
Sema &S,
CallExpr *TheCall,
9066 for (
unsigned i = 0; i < NumArgs; ++i) {
9068 if (!IsImplicitBoolFloatConversion(S, CurrA,
true))
9071 bool IsSwapped = ((i > 0) &&
9072 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i - 1),
false));
9073 IsSwapped |= ((i < (NumArgs - 1)) &&
9074 IsImplicitBoolFloatConversion(S, TheCall->
getArg(i + 1),
false));
9079 diag::warn_impcast_floating_point_to_bool);
9085 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
9090 if (isa<CallExpr>(E))
9119 if (MacroName ==
"NULL")
9127 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
9133 void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
9135 void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
9140 void checkObjCCollectionLiteralElement(
Sema &S,
QualType TargetElementType,
9141 Expr *Element,
unsigned ElementKind) {
9143 if (
auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
9144 if (ICE->getCastKind() == CK_BitCast &&
9146 Element = ICE->getSubExpr();
9157 diag::warn_objc_collection_literal_element)
9158 << ElementType << ElementKind << TargetElementType
9162 if (
auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
9163 checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
9164 else if (
auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
9165 checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
9170 void checkObjCArrayLiteral(
Sema &S,
QualType TargetType,
9179 if (TargetObjCPtr->isUnspecialized() ||
9180 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9185 if (TypeArgs.size() != 1)
9188 QualType TargetElementType = TypeArgs[0];
9189 for (
unsigned I = 0, N = ArrayLiteral->
getNumElements(); I != N; ++
I) {
9190 checkObjCCollectionLiteralElement(S, TargetElementType,
9198 void checkObjCDictionaryLiteral(
Sema &S,
QualType TargetType,
9207 if (TargetObjCPtr->isUnspecialized() ||
9208 TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
9213 if (TypeArgs.size() != 2)
9216 QualType TargetKeyType = TypeArgs[0];
9217 QualType TargetObjectType = TypeArgs[1];
9218 for (
unsigned I = 0, N = DictionaryLiteral->
getNumElements(); I != N; ++
I) {
9220 checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
9221 checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
9233 const char FirstLiteralCharacter =
9235 if (FirstLiteralCharacter ==
'0')
9242 const char FirstContextCharacter =
9244 if (FirstContextCharacter ==
'{')
9257 if (Source == Target)
return;
9270 if (isa<StringLiteral>(E))
9274 return DiagnoseImpCast(S, E, T, CC,
9275 diag::warn_impcast_string_literal_to_bool);
9276 if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(
E) ||
9277 isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(
E)) {
9280 return DiagnoseImpCast(S, E, T, CC,
9281 diag::warn_impcast_objective_c_literal_to_bool);
9292 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
9293 checkObjCArrayLiteral(S,
QualType(Target, 0), ArrayLiteral);
9294 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
9295 checkObjCDictionaryLiteral(S,
QualType(Target, 0), DictionaryLiteral);
9298 if (isa<VectorType>(Source)) {
9299 if (!isa<VectorType>(Target)) {
9302 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
9310 Source = cast<VectorType>(Source)->getElementType().getTypePtr();
9311 Target = cast<VectorType>(Target)->getElementType().getTypePtr();
9313 if (
auto VecTy = dyn_cast<VectorType>(Target))
9314 Target = VecTy->getElementType().getTypePtr();
9317 if (isa<ComplexType>(Source)) {
9318 if (!isa<ComplexType>(Target)) {
9322 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_complex_scalar);
9325 Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
9326 Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
9335 if (TargetBT && TargetBT->isFloatingPoint()) {
9339 if (SourceBT->
getKind() > TargetBT->getKind()) {
9345 if (IsSameFloatAfterCast(result.
Val,
9354 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
9357 else if (TargetBT->getKind() > SourceBT->
getKind()) {
9361 DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
9367 if (TargetBT && TargetBT->isInteger()) {
9371 DiagnoseFloatingImpCast(S, E, T, CC);
9390 if (isa<ImplicitCastExpr>(LastA) &&
9393 DiagnoseImpCast(S, E, T, CC,
9394 diag::warn_impcast_floating_point_to_bool);
9401 DiagnoseNullConversion(S, E, T, CC);
9414 IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.
Context, Target);
9416 if (SourceRange.Width > TargetRange.Width) {
9419 llvm::APSInt
Value(32);
9424 std::string PrettySourceValue = Value.toString(10);
9425 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9428 S.
PDiag(diag::warn_impcast_integer_precision_constant)
9429 << PrettySourceValue << PrettyTargetValue
9440 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
9442 return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
9445 if (TargetRange.Width == SourceRange.Width && !TargetRange.NonNegative &&
9454 if (isSameWidthConstantConversion(S, E, T, CC)) {
9455 std::string PrettySourceValue = Value.toString(10);
9456 std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
9460 S.
PDiag(diag::warn_impcast_integer_precision_constant)
9461 << PrettySourceValue << PrettyTargetValue << E->
getType() << T
9470 if ((TargetRange.NonNegative && !SourceRange.NonNegative) ||
9471 (!TargetRange.NonNegative && SourceRange.NonNegative &&
9472 SourceRange.Width == TargetRange.Width)) {
9476 unsigned DiagID = diag::warn_impcast_integer_sign;
9484 DiagID = diag::warn_impcast_integer_sign_conditional;
9488 return DiagnoseImpCast(S, E, T, CC, DiagID);
9498 EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
9506 if (SourceEnum->getDecl()->hasNameForLinkage() &&
9507 TargetEnum->getDecl()->hasNameForLinkage() &&
9508 SourceEnum != TargetEnum) {
9512 return DiagnoseImpCast(S, E, SourceType, T, CC,
9513 diag::warn_impcast_different_enum_types);
9524 if (isa<ConditionalOperator>(E))
9525 return CheckConditionalOperator(S, cast<ConditionalOperator>(E), CC, T);
9527 AnalyzeImplicitConversions(S, E, CC);
9529 return CheckImplicitConversion(S, E, T, CC, &ICContext);
9536 bool Suspicious =
false;
9537 CheckConditionalOperand(S, E->
getTrueExpr(), T, CC, Suspicious);
9538 CheckConditionalOperand(S, E->
getFalseExpr(), T, CC, Suspicious);
9542 if (!Suspicious)
return;
9545 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
9550 if (E->
getType() == T)
return;
9554 E->
getType(), CC, &Suspicious);
9557 E->
getType(), CC, &Suspicious);
9580 if (isa<ConditionalOperator>(E)) {
9582 CheckConditionalOperator(S, CO, CC, T);
9587 if (
CallExpr *Call = dyn_cast<CallExpr>(E))
9588 CheckImplicitArgumentConversions(S, Call, CC);
9594 CheckImplicitConversion(S, E, T, CC);
9602 for (
auto *SE : POE->semantics())
9603 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
9604 AnalyzeImplicitConversions(S, OVE->getSourceExpr(), CC);
9608 if (isa<ExplicitCastExpr>(E)) {
9610 return AnalyzeImplicitConversions(S, E, CC);
9615 if (BO->isComparisonOp())
9616 return AnalyzeComparison(S, BO);
9619 if (BO->getOpcode() == BO_Assign)
9620 return AnalyzeAssignment(S, BO);
9627 if (isa<StmtExpr>(E))
return;
9630 if (isa<UnaryExprOrTypeTraitExpr>(E))
return;
9635 bool IsLogicalAndOperator = BO && BO->
getOpcode() == BO_LAnd;
9637 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
9641 if (IsLogicalAndOperator &&
9646 AnalyzeImplicitConversions(S, ChildExpr, CC);
9651 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9652 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
9655 if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
9656 ::CheckBoolLikeConversion(S, SubExpr, BO->
getExprLoc());
9660 if (U->getOpcode() == UO_LNot)
9661 ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
9672 diag::err_opencl_enqueue_kernel_invalid_local_size_type);
9677 CheckImplicitConversion(S, E, IntT, E->
getLocStart());
9689 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
9692 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9693 if (!M->getMemberDecl()->getType()->isReferenceType())
9695 }
else if (
const CallExpr *Call = dyn_cast<CallExpr>(E)) {
9707 SemaRef.
Diag(FD->
getLocation(), diag::note_reference_is_return_value) << FD;
9737 bool IsEqual, SourceRange Range) {
9752 if (isa<CXXThisExpr>(E)) {
9753 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
9754 : diag::warn_this_bool_conversion;
9759 bool IsAddressOf =
false;
9762 if (UO->getOpcode() != UO_AddrOf)
9765 E = UO->getSubExpr();
9769 unsigned DiagID = IsCompare
9770 ? diag::warn_address_of_reference_null_compare
9771 : diag::warn_address_of_reference_bool_conversion;
9779 auto ComplainAboutNonnullParamOrCall = [&](
const Attr *NonnullAttr) {
9780 bool IsParam = isa<NonNullAttr>(NonnullAttr);
9782 llvm::raw_string_ostream
S(Str);
9784 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
9785 : diag::warn_cast_nonnull_to_bool;
9788 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
9794 if (
const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
9795 ComplainAboutNonnullParamOrCall(A);
9805 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
9806 D = M->getMemberDecl();
9814 if (
const auto* PV = dyn_cast<ParmVarDecl>(D)) {
9815 if (getCurFunction() &&
9816 !getCurFunction()->ModifiedNonNullParams.count(PV)) {
9817 if (
const Attr *A = PV->getAttr<NonNullAttr>()) {
9818 ComplainAboutNonnullParamOrCall(A);
9822 if (
const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
9823 auto ParamIter = llvm::find(FD->
parameters(), PV);
9829 ComplainAboutNonnullParamOrCall(
NonNull);
9833 for (
unsigned ArgNo :
NonNull->args()) {
9834 if (ArgNo == ParamNo) {
9835 ComplainAboutNonnullParamOrCall(
NonNull);
9849 if (IsAddressOf && IsFunction) {
9854 if (!IsAddressOf && !IsFunction && !IsArray)
9859 llvm::raw_string_ostream
S(Str);
9862 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
9863 : diag::warn_impcast_pointer_to_bool;
9870 DiagType = AddressOf;
9871 else if (IsFunction)
9872 DiagType = FunctionPointer;
9874 DiagType = ArrayPointer;
9876 llvm_unreachable(
"Could not determine diagnostic.");
9878 << Range << IsEqual;
9890 tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
9891 if (ReturnType.isNull())
9898 if (!ReturnType->isPointerType()) {
9901 if (!ReturnType->isIntegerType())
9910 if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
9926 if (isUnevaluatedContext())
9936 CheckArrayAccess(E);
9939 AnalyzeImplicitConversions(*
this, E, CC);
9945 ::CheckBoolLikeConversion(*
this, E, CC);
9950 void Sema::CheckForIntOverflow (
Expr *E) {
9955 Expr *E = Exprs.pop_back_val();
9962 if (
auto InitList = dyn_cast<InitListExpr>(E))
9963 Exprs.append(InitList->inits().begin(), InitList->inits().end());
9965 if (isa<ObjCBoxedExpr>(E))
9967 }
while (!Exprs.empty());
9981 class SequenceTree {
9983 explicit Value(
unsigned Parent) : Parent(Parent), Merged(
false) {}
9984 unsigned Parent : 31;
9985 unsigned Merged : 1;
9993 explicit Seq(
unsigned N) : Index(N) {}
9995 friend class SequenceTree;
10000 SequenceTree() { Values.push_back(
Value(0)); }
10001 Seq root()
const {
return Seq(0); }
10006 Seq allocate(Seq Parent) {
10007 Values.push_back(
Value(Parent.Index));
10008 return Seq(Values.size() - 1);
10012 void merge(Seq S) {
10013 Values[S.Index].Merged =
true;
10019 bool isUnsequenced(Seq Cur, Seq Old) {
10020 unsigned C = representative(Cur.Index);
10021 unsigned Target = representative(Old.Index);
10022 while (C >= Target) {
10025 C = Values[
C].Parent;
10032 unsigned representative(
unsigned K) {
10033 if (Values[K].Merged)
10035 return Values[K].Parent = representative(Values[K].Parent);
10053 UK_ModAsSideEffect,
10055 UK_Count = UK_ModAsSideEffect + 1
10059 Usage() : Use(nullptr), Seq() {}
10061 SequenceTree::Seq Seq;
10065 UsageInfo() : Diagnosed(
false) {}
10066 Usage Uses[UK_Count];
10070 typedef llvm::SmallDenseMap<Object, UsageInfo, 16> UsageInfoMap;
10076 UsageInfoMap UsageMap;
10078 SequenceTree::Seq Region;
10081 SmallVectorImpl<std::pair<Object, Usage> > *ModAsSideEffect;
10084 SmallVectorImpl<Expr *> &WorkList;
10091 struct SequencedSubexpression {
10092 SequencedSubexpression(SequenceChecker &Self)
10093 : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
10094 Self.ModAsSideEffect = &ModAsSideEffect;
10096 ~SequencedSubexpression() {
10097 for (
auto &M : llvm::reverse(ModAsSideEffect)) {
10098 UsageInfo &U = Self.UsageMap[M.first];
10099 auto &SideEffectUsage = U.Uses[UK_ModAsSideEffect];
10100 Self.addUsage(U, M.first, SideEffectUsage.Use, UK_ModAsValue);
10101 SideEffectUsage = M.second;
10103 Self.ModAsSideEffect = OldModAsSideEffect;
10106 SequenceChecker &Self;
10108 SmallVectorImpl<std::pair<Object, Usage> > *OldModAsSideEffect;
10115 class EvaluationTracker {
10117 EvaluationTracker(SequenceChecker &Self)
10118 : Self(Self), Prev(Self.EvalTracker), EvalOK(
true) {
10119 Self.EvalTracker =
this;
10121 ~EvaluationTracker() {
10122 Self.EvalTracker = Prev;
10124 Prev->EvalOK &= EvalOK;
10127 bool evaluate(
const Expr *E,
bool &Result) {
10135 SequenceChecker &Self;
10136 EvaluationTracker *Prev;
10142 Object getObject(
Expr *E,
bool Mod)
const {
10145 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
10146 return getObject(UO->getSubExpr(), Mod);
10149 return getObject(BO->
getRHS(), Mod);
10151 return getObject(BO->
getLHS(), Mod);
10152 }
else if (
MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
10154 if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
10155 return ME->getMemberDecl();
10156 }
else if (
DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
10163 void addUsage(UsageInfo &UI, Object O,
Expr *Ref, UsageKind UK) {
10164 Usage &U = UI.Uses[UK];
10165 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq)) {
10166 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
10167 ModAsSideEffect->push_back(std::make_pair(O, U));
10173 void checkUsage(Object O, UsageInfo &UI,
Expr *Ref, UsageKind OtherKind,
10178 const Usage &U = UI.Uses[OtherKind];
10179 if (!U.Use || !Tree.isUnsequenced(Region, U.Seq))
10183 Expr *ModOrUse = Ref;
10184 if (OtherKind == UK_Use)
10185 std::swap(Mod, ModOrUse);
10188 IsModMod ? diag::warn_unsequenced_mod_mod
10189 : diag::warn_unsequenced_mod_use)
10190 << O << SourceRange(ModOrUse->
getExprLoc());
10191 UI.Diagnosed =
true;
10194 void notePreUse(Object O,
Expr *Use) {
10195 UsageInfo &U = UsageMap[O];
10197 checkUsage(O, U, Use, UK_ModAsValue,
false);
10199 void notePostUse(Object O,
Expr *Use) {
10200 UsageInfo &U = UsageMap[O];
10201 checkUsage(O, U, Use, UK_ModAsSideEffect,
false);
10202 addUsage(U, O, Use, UK_Use);
10205 void notePreMod(Object O,
Expr *Mod) {
10206 UsageInfo &U = UsageMap[O];
10208 checkUsage(O, U, Mod, UK_ModAsValue,
true);
10209 checkUsage(O, U, Mod, UK_Use,
false);
10211 void notePostMod(Object O,
Expr *Use, UsageKind UK) {
10212 UsageInfo &U = UsageMap[O];
10213 checkUsage(O, U, Use, UK_ModAsSideEffect,
true);
10214 addUsage(U, O, Use, UK);
10218 SequenceChecker(
Sema &S,
Expr *E, SmallVectorImpl<Expr *> &WorkList)
10219 :
Base(S.Context), SemaRef(S), Region(Tree.root()),
10220 ModAsSideEffect(nullptr), WorkList(WorkList), EvalTracker(nullptr) {
10224 void VisitStmt(
Stmt *S) {
10228 void VisitExpr(
Expr *E) {
10230 Base::VisitStmt(E);
10234 Object O = Object();
10250 SequenceTree::Seq LHS = Tree.allocate(Region);
10251 SequenceTree::Seq RHS = Tree.allocate(Region);
10252 SequenceTree::Seq OldRegion = Region;
10255 SequencedSubexpression SeqLHS(*
this);
10263 Region = OldRegion;
10275 Object O = getObject(BO->
getLHS(),
true);
10277 return VisitExpr(BO);
10287 if (isa<CompoundAssignOperator>(BO))
10292 if (isa<CompoundAssignOperator>(BO))
10293 notePostUse(O, BO);
10301 notePostMod(O, BO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10302 : UK_ModAsSideEffect);
10306 VisitBinAssign(CAO);
10309 void VisitUnaryPreInc(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10310 void VisitUnaryPreDec(
UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
10312 Object O = getObject(UO->
getSubExpr(),
true);
10314 return VisitExpr(UO);
10320 notePostMod(O, UO, SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
10321 : UK_ModAsSideEffect);
10324 void VisitUnaryPostInc(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10325 void VisitUnaryPostDec(
UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
10327 Object O = getObject(UO->
getSubExpr(),
true);
10329 return VisitExpr(UO);
10333 notePostMod(O, UO, UK_ModAsSideEffect);
10342 EvaluationTracker Eval(*
this);
10344 SequencedSubexpression Sequenced(*
this);
10349 if (Eval.evaluate(BO->
getLHS(), Result)) {
10359 WorkList.push_back(BO->
getRHS());
10363 EvaluationTracker Eval(*
this);
10365 SequencedSubexpression Sequenced(*
this);
10370 if (Eval.evaluate(BO->
getLHS(), Result)) {
10374 WorkList.push_back(BO->
getRHS());
10381 EvaluationTracker Eval(*
this);
10383 SequencedSubexpression Sequenced(*
this);
10388 if (Eval.evaluate(CO->
getCond(), Result))
10396 void VisitCallExpr(
CallExpr *CE) {
10403 SequencedSubexpression Sequenced(*
this);
10404 Base::VisitCallExpr(CE);
10411 SequencedSubexpression Sequenced(*
this);
10414 return VisitExpr(CCE);
10418 SequenceTree::Seq Parent = Region;
10422 Region = Tree.allocate(Parent);
10423 Elts.push_back(Region);
10429 for (
unsigned I = 0; I < Elts.size(); ++
I)
10430 Tree.merge(Elts[I]);
10434 if (!SemaRef.getLangOpts().CPlusPlus11)
10435 return VisitExpr(ILE);
10439 SequenceTree::Seq Parent = Region;
10443 Region = Tree.allocate(Parent);
10444 Elts.push_back(Region);
10450 for (
unsigned I = 0; I < Elts.size(); ++
I)
10451 Tree.merge(Elts[I]);
10456 void Sema::CheckUnsequencedOperations(
Expr *E) {
10458 WorkList.push_back(E);
10459 while (!WorkList.empty()) {
10460 Expr *Item = WorkList.pop_back_val();
10461 SequenceChecker(*
this, Item, WorkList);
10466 bool IsConstexpr) {
10467 CheckImplicitConversions(E, CheckLoc);
10469 CheckUnsequencedOperations(E);
10471 CheckForIntOverflow(E);
10472 DiagnoseMisalignedMembers();
10478 (void) AnalyzeBitFieldAssignment(*
this, BitField, Init, InitLoc);
10485 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
10489 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
10493 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
10507 S.
Diag(Loc, diag::err_array_star_in_function_definition);
10516 bool CheckParameterNames) {
10517 bool HasInvalidParm =
false;
10524 if (!Param->isInvalidDecl() &&
10525 RequireCompleteType(Param->getLocation(), Param->getType(),
10526 diag::err_typecheck_decl_incomplete_type)) {
10527 Param->setInvalidDecl();
10528 HasInvalidParm =
true;
10533 if (CheckParameterNames &&
10534 Param->getIdentifier() ==
nullptr &&
10535 !Param->isImplicit() &&
10536 !getLangOpts().CPlusPlus)
10537 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
10544 QualType PType = Param->getOriginalType();
10556 if (!Param->isInvalidDecl()) {
10558 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
10563 MarkFunctionReferenced(Param->getLocation(), Destructor);
10564 DiagnoseUseOfDecl(Destructor, Param->
getLocation());
10574 if (
const auto *
Attr = Param->getAttr<PassObjectSizeAttr>())
10575 if (!Param->getType().isConstQualified())
10576 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
10580 return HasInvalidParm;
10587 if (
const auto *DRE = dyn_cast<DeclRefExpr>(E))
10590 if (
const auto *ME = dyn_cast<MemberExpr>(E))
10601 if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.
getBegin()))
10610 if (!DestPtr)
return;
10616 if (DestAlign.
isOne())
return;
10620 if (!SrcPtr)
return;
10631 if (
auto *CE = dyn_cast<CastExpr>(Op)) {
10632 if (CE->getCastKind() == CK_ArrayToPointerDecay)
10634 }
else if (
auto *UO = dyn_cast<UnaryOperator>(Op)) {
10639 if (SrcAlign >= DestAlign)
return;
10644 << static_cast<unsigned>(DestAlign.
getQuantity())
10655 if (Size != 1 || !ND)
return false;
10658 if (!FD)
return false;
10681 if (!RD)
return false;
10682 if (RD->
isUnion())
return false;
10683 if (
const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
10684 if (!CRD->isStandardLayout())
return false;
10688 const Decl *D = FD;
10690 if (isa<FieldDecl>(D))
10695 void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
10697 bool AllowOnePastEnd,
bool IndexNegated) {
10702 const Type *EffectiveType =
10710 llvm::APSInt index;
10717 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10718 ND = dyn_cast<NamedDecl>(DRE->
getDecl());
10719 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10720 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10722 if (index.isUnsigned() || !index.isNegative()) {
10723 llvm::APInt size = ArrayTy->
getSize();
10724 if (!size.isStrictlyPositive())
10728 if (BaseType != EffectiveType) {
10730 uint64_t ptrarith_typesize = Context.
getTypeSize(EffectiveType);
10731 uint64_t array_typesize = Context.
getTypeSize(BaseType);
10733 if (!ptrarith_typesize) ptrarith_typesize = 1;
10734 if (ptrarith_typesize != array_typesize) {
10736 uint64_t ratio = array_typesize / ptrarith_typesize;
10739 if (ptrarith_typesize * ratio == array_typesize)
10740 size *= llvm::APInt(size.getBitWidth(), ratio);
10744 if (size.getBitWidth() > index.getBitWidth())
10745 index = index.zext(size.getBitWidth());
10746 else if (size.getBitWidth() < index.getBitWidth())
10747 size = size.zext(index.getBitWidth());
10753 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
10768 if (
SourceMgr.isInSystemHeader(RBracketLoc)) {
10771 if (
SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
10776 unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
10778 DiagID = diag::warn_array_index_exceeds_bounds;
10780 DiagRuntimeBehavior(BaseExpr->
getLocStart(), BaseExpr,
10781 PDiag(DiagID) << index.toString(10,
true)
10782 << size.toString(10,
true)
10783 << (
unsigned)size.getLimitedValue(~0U)
10786 unsigned DiagID = diag::warn_array_index_precedes_bounds;
10788 DiagID = diag::warn_ptr_arith_precedes_bounds;
10789 if (index.isNegative()) index = -index;
10792 DiagRuntimeBehavior(BaseExpr->
getLocStart(), BaseExpr,
10793 PDiag(DiagID) << index.toString(10,
true)
10800 dyn_cast<ArraySubscriptExpr>(BaseExpr))
10802 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
10804 if (
const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
10805 ND = dyn_cast<NamedDecl>(ME->getMemberDecl());
10810 PDiag(diag::note_array_index_out_of_bounds)
10814 void Sema::CheckArrayAccess(
const Expr *
expr) {
10815 int AllowOnePastEnd = 0;
10819 case Stmt::ArraySubscriptExprClass: {
10822 AllowOnePastEnd > 0);
10825 case Stmt::OMPArraySectionExprClass: {
10829 nullptr, AllowOnePastEnd > 0);
10832 case Stmt::UnaryOperatorClass: {
10848 case Stmt::ConditionalOperatorClass: {
10851 CheckArrayAccess(lhs);
10853 CheckArrayAccess(rhs);
10856 case Stmt::CXXOperatorCallExprClass: {
10857 const auto *OCE = cast<CXXOperatorCallExpr>(
expr);
10858 for (
const auto *Arg : OCE->arguments())
10859 CheckArrayAccess(Arg);
10871 struct RetainCycleOwner {
10878 void setLocsFrom(
Expr *e) {
10894 owner.Variable = var;
10896 owner.setLocsFrom(ref);
10904 switch (
cast->getCastKind()) {
10906 case CK_LValueBitCast:
10907 case CK_LValueToRValue:
10908 case CK_ARCReclaimReturnedObject:
10909 e =
cast->getSubExpr();
10926 if (ref->isFreeIvar()) owner.setLocsFrom(ref);
10927 owner.Indirect =
true;
10931 if (
DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
10933 if (!var)
return false;
10937 if (
MemberExpr *member = dyn_cast<MemberExpr>(e)) {
10938 if (member->isArrow())
return false;
10941 e = member->getBase();
10950 if (!pre)
return false;
10953 if (!property->isRetaining() &&
10954 !(
property->getPropertyIvarDecl() &&
10955 property->getPropertyIvarDecl()->getType()
10959 owner.Indirect =
true;
10962 if (!owner.Variable)
10968 e =
const_cast<Expr*
>(cast<OpaqueValueExpr>(pre->
getBase())
10969 ->getSourceExpr());
10983 Context(Context),
Variable(variable), Capturer(nullptr),
10984 VarWillBeReased(
false) {}
10988 bool VarWillBeReased;
10996 if (Capturer)
return;
11002 void VisitBlockExpr(
BlockExpr *block) {
11009 if (Capturer)
return;
11014 if (!Variable || VarWillBeReased || BinOp->
getOpcode() != BO_Assign)
11017 if (
const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
11022 llvm::APSInt
Value;
11024 (RHS && RHS->isIntegerConstantExpr(Value, Context) && Value == 0);
11034 assert(owner.Variable && owner.Loc.isValid());
11042 e = ME->getInstanceReceiver();
11045 e = e->IgnoreParenCasts();
11047 }
else if (
CallExpr *CE = dyn_cast<CallExpr>(e)) {
11052 if (FnI && FnI->
isStr(
"_Block_copy")) {
11063 FindCaptureVisitor visitor(S.
Context, owner.Variable);
11065 return visitor.VarWillBeReased ?
nullptr : visitor.Capturer;
11069 RetainCycleOwner &owner) {
11071 assert(owner.Variable && owner.Loc.isValid());
11075 S.
Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
11076 << owner.Indirect << owner.Range;
11085 while (!str.empty() && str.front() ==
'_') str = str.substr(1);
11086 if (str.startswith(
"set"))
11087 str = str.substr(3);
11088 else if (str.startswith(
"add")) {
11090 if (sel.
getNumArgs() == 1 && str.startswith(
"addOperationWithBlock"))
11092 str = str.substr(3);
11097 if (str.empty())
return true;
11103 bool IsMutableArray = S.
NSAPIObj->isSubclassOfNSClass(
11106 if (!IsMutableArray) {
11112 Optional<NSAPI::NSArrayMethodKind> MKOpt =
11113 S.
NSAPIObj->getNSArrayMethodKind(Sel);
11138 bool IsMutableDictionary = S.
NSAPIObj->isSubclassOfNSClass(
11141 if (!IsMutableDictionary) {
11147 Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
11148 S.
NSAPIObj->getNSDictionaryMethodKind(Sel);
11169 bool IsMutableSet = S.
NSAPIObj->isSubclassOfNSClass(
11173 bool IsMutableOrderedSet = S.
NSAPIObj->isSubclassOfNSClass(
11176 if (!IsMutableSet && !IsMutableOrderedSet) {
11182 Optional<NSAPI::NSSetMethodKind> MKOpt = S.
NSAPIObj->getNSSetMethodKind(Sel);
11207 Optional<int> ArgOpt;
11215 int ArgIndex = *ArgOpt;
11223 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11224 if (ArgRE->isObjCSelfExpr()) {
11226 diag::warn_objc_circular_container)
11227 << ArgRE->getDecl()->getName() << StringRef(
"super");
11237 if (
DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
11238 if (
DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
11239 if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
11242 diag::warn_objc_circular_container)
11244 if (!ArgRE->isObjCSelfExpr()) {
11246 diag::note_objc_circular_container_declared_here)
11251 }
else if (
ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
11253 if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
11256 diag::warn_objc_circular_container)
11259 diag::note_objc_circular_container_declared_here)
11274 RetainCycleOwner owner;
11280 owner.Variable = getCurMethodDecl()->getSelfDecl();
11286 for (
unsigned i = 0, e = msg->
getNumArgs(); i != e; ++i)
11293 RetainCycleOwner owner;
11302 RetainCycleOwner Owner;
11316 Expr *RHS,
bool isProperty) {
11328 S.
Diag(Loc, diag::warn_arc_literal_assign)
11330 << (isProperty ? 0 : 1)
11338 Expr *RHS,
bool isProperty) {
11341 if (
cast->getCastKind() == CK_ARCConsumeObject) {
11342 S.
Diag(Loc, diag::warn_arc_retained_assign)
11344 << (isProperty ? 0 : 1)
11348 RHS =
cast->getSubExpr();
11390 if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
11391 getCurFunction()->markSafeWeakUse(LHS);
11394 if (checkUnsafeAssigns(Loc, LHSType, RHS))
11414 if (!(AsWrittenAttr & ObjCPropertyDecl::OBJC_PR_assign) &&
11419 if (
cast->getCastKind() == CK_ARCConsumeObject) {
11420 Diag(Loc, diag::warn_arc_retained_property_assign)
11424 RHS =
cast->getSubExpr();
11450 bool StmtLineInvalid;
11453 if (StmtLineInvalid)
11456 bool BodyLineInvalid;
11459 if (BodyLineInvalid)
11463 if (StmtLine != BodyLine)
11475 if (CurrentInstantiationScope)
11484 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11488 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
11492 const Stmt *PossibleBody) {
11493 assert(!CurrentInstantiationScope);
11498 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
11499 StmtLoc = FS->getRParenLoc();
11500 Body = FS->getBody();
11501 DiagID = diag::warn_empty_for_body;
11502 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
11503 StmtLoc = WS->getCond()->getSourceRange().getEnd();
11504 Body = WS->getBody();
11505 DiagID = diag::warn_empty_while_body;
11515 if (Diags.isIgnored(DiagID, NBody->
getSemiLoc()))
11519 if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
11533 bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
11534 if (!ProbableTypo) {
11535 bool BodyColInvalid;
11539 if (BodyColInvalid)
11542 bool StmtColInvalid;
11546 if (StmtColInvalid)
11549 if (BodyCol > StmtCol)
11550 ProbableTypo =
true;
11553 if (ProbableTypo) {
11555 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
11564 if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
11567 if (inTemplateInstantiation())
11586 RHSExpr = CE->
getArg(0);
11592 if (LHSDeclRef && RHSDeclRef) {
11593 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
11599 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11609 const Expr *LHSBase = LHSExpr;
11610 const Expr *RHSBase = RHSExpr;
11613 if (!LHSME || !RHSME)
11616 while (LHSME && RHSME) {
11622 RHSBase = RHSME->getBase();
11629 if (LHSDeclRef && RHSDeclRef) {
11630 if (!LHSDeclRef->
getDecl() || !RHSDeclRef->getDecl())
11636 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11642 if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
11643 Diag(OpLoc, diag::warn_self_move) << LHSExpr->
getType()
11665 if (!isLayoutCompatible(C, Field1->
getType(), Field2->
getType()))
11676 if (Bits1 != Bits2)
11685 bool isLayoutCompatibleStruct(
ASTContext &C,
11689 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
11694 if (D1CXX->getNumBases() != D2CXX->
getNumBases())
11699 Base1 = D1CXX->bases_begin(),
11700 BaseEnd1 = D1CXX->bases_end(),
11703 ++Base1, ++Base2) {
11704 if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
11707 }
else if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
11718 for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
11719 if (!isLayoutCompatible(C, *Field1, *Field2))
11722 if (Field1 != Field1End || Field2 != Field2End)
11733 llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
11734 for (
auto *Field2 : RD2->
fields())
11735 UnmatchedFields.insert(Field2);
11737 for (
auto *Field1 : RD1->
fields()) {
11738 llvm::SmallPtrSet<FieldDecl *, 8>::iterator
11739 I = UnmatchedFields.begin(),
11740 E = UnmatchedFields.end();
11742 for ( ; I !=
E; ++
I) {
11743 if (isLayoutCompatible(C, Field1, *I)) {
11744 bool Result = UnmatchedFields.erase(*I);
11754 return UnmatchedFields.empty();
11762 return isLayoutCompatibleUnion(C, RD1, RD2);
11764 return isLayoutCompatibleStruct(C, RD1, RD2);
11787 if (TC1 == Type::Enum) {
11788 return isLayoutCompatible(C,
11789 cast<EnumType>(T1)->getDecl(),
11790 cast<EnumType>(T2)->getDecl());
11791 }
else if (TC1 == Type::Record) {
11795 return isLayoutCompatible(C,
11796 cast<RecordType>(T1)->getDecl(),
11797 cast<RecordType>(T2)->getDecl());
11814 bool FindTypeTagExpr(
const Expr *TypeExpr,
const ASTContext &Ctx,
11815 const ValueDecl **VD, uint64_t *MagicValue) {
11823 case Stmt::UnaryOperatorClass: {
11832 case Stmt::DeclRefExprClass: {
11833 const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
11838 case Stmt::IntegerLiteralClass: {
11840 llvm::APInt MagicValueAPInt = IL->
getValue();
11841 if (MagicValueAPInt.getActiveBits() <= 64) {
11842 *MagicValue = MagicValueAPInt.getZExtValue();
11848 case Stmt::BinaryConditionalOperatorClass:
11849 case Stmt::ConditionalOperatorClass: {
11851 cast<AbstractConditionalOperator>(TypeExpr);
11863 case Stmt::BinaryOperatorClass: {
11866 TypeExpr = BO->
getRHS();
11890 bool GetMatchingCType(
11895 bool &FoundWrongKind,
11897 FoundWrongKind =
false;
11902 uint64_t MagicValue;
11904 if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue))
11908 if (TypeTagForDatatypeAttr *I = VD->
getAttr<TypeTagForDatatypeAttr>()) {
11909 if (I->getArgumentKind() != ArgumentKind) {
11910 FoundWrongKind =
true;
11913 TypeInfo.
Type = I->getMatchingCType();
11926 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
11927 if (I == MagicValues->end())
11930 TypeInfo = I->second;
11936 uint64_t MagicValue,
QualType Type,
11937 bool LayoutCompatible,
11939 if (!TypeTagForDatatypeMagicValues)
11940 TypeTagForDatatypeMagicValues.reset(
11941 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
11944 (*TypeTagForDatatypeMagicValues)[Magic] =
11961 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
11962 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
11963 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
11964 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
11968 void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
11969 const Expr *
const *ExprArgs) {
11971 bool IsPointerAttr = Attr->getIsPointer();
11973 const Expr *TypeTagExpr = ExprArgs[Attr->getTypeTagIdx()];
11974 bool FoundWrongKind;
11975 TypeTagData TypeInfo;
11976 if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
11977 TypeTagForDatatypeMagicValues.get(),
11978 FoundWrongKind, TypeInfo)) {
11979 if (FoundWrongKind)
11981 diag::warn_type_tag_for_datatype_wrong_kind)
11986 const Expr *ArgumentExpr = ExprArgs[Attr->getArgumentIdx()];
11987 if (IsPointerAttr) {
11989 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
11990 if (ICE->getType()->isVoidPointerType() &&
11991 ICE->getCastKind() == CK_BitCast)
11992 ArgumentExpr = ICE->getSubExpr();
12000 if (TypeInfo.MustBeNull) {
12005 diag::warn_type_safety_null_pointer_required)
12013 QualType RequiredType = TypeInfo.Type;
12017 bool mismatch =
false;
12018 if (!TypeInfo.LayoutCompatible) {
12019 mismatch = !Context.
hasSameType(ArgumentType, RequiredType);
12027 if ((IsPointerAttr && IsSameCharType(ArgumentType->
getPointeeType(),
12029 (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
12033 mismatch = !isLayoutCompatible(Context,
12037 mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
12040 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
12041 << ArgumentType << ArgumentKind
12042 << TypeInfo.LayoutCompatible << RequiredType
12049 MisalignedMembers.emplace_back(E, RD, MD, Alignment);
12053 for (MisalignedMember &m : MisalignedMembers) {
12059 Diag(m.E->getLocStart(), diag::warn_taking_address_of_packed_member)
12062 MisalignedMembers.clear();
12069 if (isa<UnaryOperator>(E) &&
12070 cast<UnaryOperator>(
E)->
getOpcode() == UO_AddrOf) {
12071 auto *Op = cast<UnaryOperator>(
E)->getSubExpr()->
IgnoreParens();
12072 if (isa<MemberExpr>(Op)) {
12073 auto MA = std::find(MisalignedMembers.begin(), MisalignedMembers.end(),
12074 MisalignedMember(Op));
12075 if (MA != MisalignedMembers.end() &&
12079 MisalignedMembers.erase(MA);
12100 bool AnyIsPacked =
false;
12102 QualType BaseType = ME->getBase()->getType();
12116 AnyIsPacked || (RD->
hasAttr<PackedAttr>() || MD->
hasAttr<PackedAttr>());
12117 ReverseMemberChain.push_back(FD);
12120 ME = dyn_cast<
MemberExpr>(ME->getBase()->IgnoreParens());
12122 assert(TopME &&
"We did not compute a topmost MemberExpr!");
12129 const auto *DRE = dyn_cast<
DeclRefExpr>(TopBase);
12133 if (!DRE && !isa<CXXThisExpr>(TopBase))
12140 if (ExpectedAlignment.
isOne())
12145 for (
auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
12152 ReverseMemberChain.back()->getParent()->getTypeForDecl());
12156 if (DRE && !TopME->
isArrow()) {
12159 CompleteObjectAlignment =
12164 if (Offset % ExpectedAlignment != 0 ||
12167 CompleteObjectAlignment < ExpectedAlignment) {
12178 for (
FieldDecl *FDI : ReverseMemberChain) {
12179 if (FDI->hasAttr<PackedAttr>() ||
12180 FDI->getParent()->hasAttr<PackedAttr>()) {
12188 assert(FD &&
"We did not find a packed FieldDecl!");
12193 void Sema::CheckAddressOfPackedMember(
Expr *rhs) {
12194 using namespace std::placeholders;
12195 RefersToMemberWithReducedAlignment(
12196 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*
this), _1,
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)
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0) const
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...
StmtClass getStmtClass() const
CastKind getCastKind() const
FunctionDecl - An instance of this class is created to represent a function declaration or definition...
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.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, bool HasVAListArg, unsigned format_idx, unsigned firstDataArg, Sema::FormatStringType Type, bool inFunctionCall, Sema::VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg)
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.
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different overload formats specified ...
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
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 CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
Helpers for dealing with blocks and functions.
bool isOne() const
isOne - Test whether the quantity equals one.
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
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. ...
Stmt - This represents one statement.
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.
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
static InitializedEntity InitializeParameter(ASTContext &Context, const ParmVarDecl *Parm)
Create the initialization entity for a parameter.
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
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer...
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, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset)
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.
std::string getAsString() const
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
const NestedNameSpecifier * Specifier
A container of type source information.
static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call)
Returns true if pipe element type is different from the pointer.
SourceLocation getOperatorLoc() const
TypeSourceInfo * getIntegerTypeSourceInfo() const
Return the type source info for the underlying integer type, if no type source info exists...
bool isBlockPointerType() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Represents a prvalue temporary that is written into memory so that a reference can bind to it...
static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount)
Checks that a call expression's argument count is the desired number.
float __ovld __cnfn distance(float p0, float p1)
Returns the distance between p0 and p1.
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.
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.
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)
static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall, Expr *BlockArg, unsigned NumNonVarArgs)
OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all 'local void*' parameter of passed blo...
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 checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
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.
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
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.
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
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...
CanQualType OCLReserveIDTy
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
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.
static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall, unsigned Start, unsigned End)
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.
Expr * getTrueExpr() const
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
unsigned getLength() const
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 EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
bool hasValidPlusPrefix() const
unsigned getMinRequiredArguments() const
getMinRequiredArguments - Returns the minimum number of arguments needed to call this function...
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...
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
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.
static const Expr * EvalVal(const Expr *E, SmallVectorImpl< const DeclRefExpr * > &refVars, const Decl *ParentDecl)
EvalVal - This function is complements EvalAddr in the mutual recursion.
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)
Check assignment constraints for an assignment of RHS to LHSType.
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)
static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall)
OpenCL C v2.0, s6.13.17.6 - Check the argument to the get_kernel_work_group_size and get_kernel_prefe...
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
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
CanQualType UnsignedCharTy
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Iterator for iterating over Stmt * arrays that contain only Expr *.
This object can be modified without requiring retains or releases.
param_iterator param_begin()
field_iterator field_end() const
APValue & getVectorElt(unsigned I)
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
SourceLocation getLocEnd() const LLVM_READONLY
static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx)
Returns true if pipe element type is different from the pointer.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand...
unsigned getPresumedColumnNumber(SourceLocation Loc, bool *Invalid=nullptr) const
SourceLocation getTypeSpecStartLoc() 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 hasUnaligned() const
bool isRealFloatingType() const
Floating point categories.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
Exposes information about the current target.
bool hasValidAlternativeForm() const
NSArrayMethodKind
Enumerates the NSArray/NSMutableArray methods used to generate literals and to apply some checks...
static void SemaBuiltinMemChkCall(Sema &S, FunctionDecl *FDecl, CallExpr *TheCall, unsigned SizeIdx, unsigned DstSizeIdx)
const Type * getTypeForDecl() const
BlockDecl - This represents a block literal declaration, which is like an unnamed FunctionDecl...
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...
QualType getPointeeType() const
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.
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
static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg)
OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local void*, which is a requirem...
bool isUnsignedInteger() const
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Represents a C++ destructor within a class.
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
void removeLocalVolatile()
char __ovld __cnfn min(char x, char y)
Returns y if y < x, otherwise it returns x.
unsigned getNumElements() const
getNumElements - Return number of elements of objective-c array literal.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
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.
static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call)
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.
Represents a GCC generic vector type.
static OpenCLAccessAttr * getOpenCLArgAccess(const Decl *D)
Returns OpenCL access qual.
DeclarationName getDeclName() const
getDeclName - Get the actual, stored name of the declaration, which may be a special name...
static const Expr * EvalAddr(const Expr *E, SmallVectorImpl< const DeclRefExpr * > &refVars, const Decl *ParentDecl)
EvalAddr - EvalAddr and EvalVal are mutually recursive functions that check if the expression in a re...
unsigned getNumBases() const
Retrieves the number of base classes of this class.
APSInt & getComplexIntImag()
ObjCStringFormatFamily getObjCFStringFormattingFamily() const
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.
static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size, const NamedDecl *ND)
Check whether this array fits the idiom of a size-one tail padded array member of a struct...
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
static StringRef getIdentifier(const Token &Tok)
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.
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
static CharSourceRange getCharRange(SourceRange R)
const ParmVarDecl * getParamDecl(unsigned i) const
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn)
Check that the user is calling the appropriate va_start builtin for the target and calling convention...
static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call)
SourceLocation getLocStart() const LLVM_READONLY
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
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.
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
void RefersToMemberWithReducedAlignment(Expr *E, llvm::function_ref< void(Expr *, RecordDecl *, FieldDecl *, CharUnits)> Action)
This function calls Action when it determines that E designates a misaligned member due to the packed...
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.
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...
Expression is not a Null pointer constant.
bool isConstant(const ASTContext &Ctx) const
unsigned getBitWidthValue(const ASTContext &Ctx) const
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
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 isValid() const
Return true if this is a valid SourceLocation object.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ASTContext & getASTContext() const
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical) const
Produce a unique representation of the given statement.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
QualType withConst() const
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
Represents a static or instance method of a struct/union/class.
ExprResult SemaBuiltinShuffleVector(CallExpr *TheCall)
SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
ArrayRef< ParmVarDecl * > parameters() const
virtual bool hasSjLjLowering() const
Controls if __builtin_longjmp / __builtin_setjmp can be lowered to llvm.eh.sjlj.longjmp / llvm...
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
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...
bool isNothrow(const ASTContext &Ctx, bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
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.
static bool isBlockPointer(Expr *Arg)
EltType getEltType() const
bool FormatStringHasSArg(const StringLiteral *FExpr)
bool isReserveIDT() const
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.
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.
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
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.
static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call)
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
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
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
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.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T-> getSizeExpr()))
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
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
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.
QualType getPromotionType() const
getPromotionType - Return the integer type that enumerators should promote to.
bool isInvalidDecl() const
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
const OptionalFlag & hasThousandsGrouping() const
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
BinaryOperator::Opcode getOpcode(const SymExpr *SE)
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
SourceLocation getLocStart() const LLVM_READONLY
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
EnumDecl - Represents an enum.
Expression is a C++11 nullptr.
detail::InMemoryDirectory::const_iterator E
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
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
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].
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
ArgType getArgType(ASTContext &Ctx) const
static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID, CallExpr *Call)
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.
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...
static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntType)
Diagnose integer type and any valid implicit conversion to it.
CanQualType UnsignedLongTy
static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call)
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
FunctionDecl * getCurFunctionDecl()
getCurFunctionDecl - If inside of a function body, this returns a pointer to the function decl for th...
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
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.
The template argument is a type.
bool hasValidLeftJustified() const
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
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
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
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
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.
void DiscardMisalignedMemberAddress(const Type *T, Expr *E)
This function checks if the expression is in the sef of potentially misaligned members and it is conv...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
const OptionalFlag & isPrivate() const
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
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
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.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
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
static Decl::Kind getKind(const Decl *D)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
Warn if a value is moved to itself.
A reference to a declared variable, function, enum, etc.
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)
QualType getElementType() const
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.
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.
const OptionalFlag & isPublic() const
NamespaceDecl * getStdNamespace() const
SourceLocation getLocStart() const LLVM_READONLY
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)
Represents the canonical version of C arrays with a specified constant size.
This class handles loading and caching of source files into memory.
unsigned getVectorLength() const
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
unsigned getNumElements() const
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...
CanQualType OCLClkEventTy
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const RecordDecl * getParent() const
getParent - Returns the parent of this field declaration, which is the struct in which this field is ...
Helper class that creates diagnostics with optional template instantiation stacks.
Expr * IgnoreParens() LLVM_READONLY
IgnoreParens - Ignore parentheses.
CanQualType UnsignedIntTy
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
static CharUnits getDeclAlign(Expr *E, CharUnits TypeAlign, ASTContext &Context)
A helper function to get the alignment of a Decl referred to by DeclRefExpr or MemberExpr.
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...