83#include "llvm/ADT/APFloat.h"
84#include "llvm/ADT/APInt.h"
85#include "llvm/ADT/APSInt.h"
86#include "llvm/ADT/ArrayRef.h"
87#include "llvm/ADT/DenseMap.h"
88#include "llvm/ADT/FoldingSet.h"
89#include "llvm/ADT/STLExtras.h"
90#include "llvm/ADT/STLForwardCompat.h"
91#include "llvm/ADT/SmallBitVector.h"
92#include "llvm/ADT/SmallPtrSet.h"
93#include "llvm/ADT/SmallString.h"
94#include "llvm/ADT/SmallVector.h"
95#include "llvm/ADT/StringExtras.h"
96#include "llvm/ADT/StringRef.h"
97#include "llvm/ADT/StringSet.h"
98#include "llvm/ADT/StringSwitch.h"
99#include "llvm/Support/AtomicOrdering.h"
100#include "llvm/Support/Compiler.h"
101#include "llvm/Support/ConvertUTF.h"
102#include "llvm/Support/ErrorHandling.h"
103#include "llvm/Support/Format.h"
104#include "llvm/Support/Locale.h"
105#include "llvm/Support/MathExtras.h"
106#include "llvm/Support/SaveAndRestore.h"
107#include "llvm/Support/raw_ostream.h"
108#include "llvm/TargetParser/RISCVTargetParser.h"
109#include "llvm/TargetParser/Triple.h"
122using namespace clang;
126 unsigned ByteNo)
const {
137 unsigned ArgCount =
Call->getNumArgs();
138 if (ArgCount >= MinArgCount)
141 return Diag(
Call->getEndLoc(), diag::err_typecheck_call_too_few_args)
142 << 0 << MinArgCount << ArgCount
143 << 0 <<
Call->getSourceRange();
147 unsigned ArgCount =
Call->getNumArgs();
148 if (ArgCount <= MaxArgCount)
150 return Diag(
Call->getEndLoc(), diag::err_typecheck_call_too_many_args_at_most)
151 << 0 << MaxArgCount << ArgCount
152 << 0 <<
Call->getSourceRange();
156 unsigned MaxArgCount) {
162 unsigned ArgCount =
Call->getNumArgs();
163 if (ArgCount == DesiredArgCount)
168 assert(ArgCount > DesiredArgCount &&
"should have diagnosed this");
172 Call->getArg(ArgCount - 1)->getEndLoc());
174 return Diag(Range.getBegin(), diag::err_typecheck_call_too_many_args)
175 << 0 << DesiredArgCount << ArgCount
180 bool HasError =
false;
182 for (
const Expr *Arg :
Call->arguments()) {
183 if (Arg->isValueDependent())
186 std::optional<std::string> ArgString = Arg->tryEvaluateString(S.
Context);
187 int DiagMsgKind = -1;
189 if (!ArgString.has_value())
191 else if (ArgString->find(
'$') != std::string::npos)
194 if (DiagMsgKind >= 0) {
195 S.
Diag(Arg->getBeginLoc(), diag::err_builtin_verbose_trap_arg)
196 << DiagMsgKind << Arg->getSourceRange();
205 if (
Value->isTypeDependent())
236 if (!Literal || !Literal->isOrdinary()) {
249 S.
Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
257 auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
258 if (!Literal || !Literal->isWide()) {
259 S.
Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
260 << Arg->getSourceRange();
306 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(
337 bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
339 auto IsValidIntegerType = [](
QualType Ty) {
340 return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
347 if ((!SrcTy->
isPointerType() && !IsValidIntegerType(SrcTy)) ||
349 S.
Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
352 S.
Diag(Source->getExprLoc(), diag::note_alignment_invalid_type);
354 S.
Diag(Source->getExprLoc(), diag::note_alignment_invalid_member_pointer);
356 S.
Diag(Source->getExprLoc(),
357 diag::note_alignment_invalid_function_pointer);
362 if (!IsValidIntegerType(AlignOp->
getType())) {
373 llvm::APSInt AlignValue = AlignResult.
Val.
getInt();
374 llvm::APSInt MaxValue(
375 llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
376 if (AlignValue < 1) {
377 S.
Diag(AlignOp->
getExprLoc(), diag::err_alignment_too_small) << 1;
380 if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
385 if (!AlignValue.isPowerOf2()) {
386 S.
Diag(AlignOp->
getExprLoc(), diag::err_alignment_not_power_of_two);
389 if (AlignValue == 1) {
390 S.
Diag(AlignOp->
getExprLoc(), diag::warn_alignment_builtin_useless)
391 << IsBooleanAlignBuiltin;
419 std::pair<unsigned, const char *> Builtins[] = {
420 { Builtin::BI__builtin_add_overflow,
"ckd_add" },
421 { Builtin::BI__builtin_sub_overflow,
"ckd_sub" },
422 { Builtin::BI__builtin_mul_overflow,
"ckd_mul" },
425 bool CkdOperation = llvm::any_of(Builtins, [&](
const std::pair<
unsigned,
432 auto ValidCkdIntType = [](
QualType QT) {
435 if (
const auto *BT = QT.getCanonicalType()->getAs<
BuiltinType>())
436 return (BT->getKind() >= BuiltinType::Short &&
437 BT->getKind() <= BuiltinType::Int128) || (
438 BT->getKind() >= BuiltinType::UShort &&
439 BT->getKind() <= BuiltinType::UInt128) ||
440 BT->getKind() == BuiltinType::UChar ||
441 BT->getKind() == BuiltinType::SChar;
446 for (
unsigned I = 0; I < 2; ++I) {
452 bool IsValid = CkdOperation ? ValidCkdIntType(Ty) : Ty->
isIntegerType();
471 !PtrTy->getPointeeType()->isIntegerType() ||
472 (!ValidCkdIntType(PtrTy->getPointeeType()) && CkdOperation) ||
473 PtrTy->getPointeeType().isConstQualified()) {
475 diag::err_overflow_builtin_must_be_ptr_int)
483 if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
484 for (
unsigned I = 0; I < 3; ++I) {
485 const auto Arg = TheCall->
getArg(I);
488 if (Ty->isBitIntType() && Ty->isSignedIntegerType() &&
490 return S.
Diag(Arg->getBeginLoc(),
491 diag::err_overflow_builtin_bit_int_max_size)
500struct BuiltinDumpStructGenerator {
504 SmallVector<Expr *, 32> Actions;
505 DiagnosticErrorTrap ErrorTracker;
506 PrintingPolicy Policy;
508 BuiltinDumpStructGenerator(Sema &S, CallExpr *TheCall)
509 : S(S), TheCall(TheCall), ErrorTracker(S.getDiagnostics()),
510 Policy(S.Context.getPrintingPolicy()) {
512 llvm::to_underlying(PrintingPolicy::AnonymousTagMode::Plain);
515 Expr *makeOpaqueValueExpr(Expr *Inner) {
519 Actions.push_back(OVE);
523 Expr *getStringLiteral(llvm::StringRef Str) {
526 return new (S.
Context) ParenExpr(Loc, Loc, Lit);
529 bool callPrintFunction(llvm::StringRef Format,
530 llvm::ArrayRef<Expr *> Exprs = {}) {
531 SmallVector<Expr *, 8> Args;
533 Args.reserve((TheCall->
getNumArgs() - 2) + 1 + Exprs.size());
535 Args.push_back(getStringLiteral(Format));
536 llvm::append_range(Args, Exprs);
539 Sema::CodeSynthesisContext Ctx;
552 Actions.push_back(RealCall.
get());
558 Expr *getIndentString(
unsigned Depth) {
562 llvm::SmallString<32>
Indent;
564 return getStringLiteral(
Indent);
568 return getStringLiteral(
T.getAsString(Policy));
571 bool appendFormatSpecifier(QualType
T, llvm::SmallVectorImpl<char> &Str) {
572 llvm::raw_svector_ostream
OS(Str);
576 if (
auto *BT =
T->
getAs<BuiltinType>()) {
577 switch (BT->getKind()) {
578 case BuiltinType::Bool:
581 case BuiltinType::Char_U:
582 case BuiltinType::UChar:
585 case BuiltinType::Char_S:
586 case BuiltinType::SChar:
594 analyze_printf::PrintfSpecifier
Specifier;
597 if (
Specifier.getConversionSpecifier().getKind() ==
598 analyze_printf::PrintfConversionSpecifier::sArg) {
604 Specifier.setPrecision(analyze_printf::OptionalAmount(32u));
624 bool dumpUnnamedRecord(
const RecordDecl *RD, Expr *E,
unsigned Depth) {
625 Expr *IndentLit = getIndentString(Depth);
627 if (IndentLit ? callPrintFunction(
"%s%s", {IndentLit, TypeLit})
628 : callPrintFunction(
"%s", {TypeLit}))
631 return dumpRecordValue(RD, E, IndentLit, Depth);
635 bool dumpRecordValue(
const RecordDecl *RD, Expr *E, Expr *RecordIndent,
644 Expr *RecordArg = makeOpaqueValueExpr(E);
647 if (callPrintFunction(
" {\n"))
651 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
652 for (
const auto &Base : CXXRD->bases()) {
660 dumpUnnamedRecord(
Base.getType()->getAsRecordDecl(), BasePtr.
get(),
666 Expr *FieldIndentArg = getIndentString(Depth + 1);
669 for (
auto *D : RD->
decls()) {
670 auto *IFD = dyn_cast<IndirectFieldDecl>(D);
671 auto *FD = IFD ? IFD->getAnonField() : dyn_cast<FieldDecl>(D);
672 if (!FD || FD->isUnnamedBitField() || FD->isAnonymousStructOrUnion())
675 llvm::SmallString<20> Format = llvm::StringRef(
"%s%s %s ");
676 llvm::SmallVector<Expr *, 5> Args = {FieldIndentArg,
678 getStringLiteral(FD->getName())};
680 if (FD->isBitField()) {
684 FD->getBitWidthValue());
692 CXXScopeSpec(), Loc, IFD,
695 RecordArg, RecordArgIsPtr, Loc, CXXScopeSpec(), FD,
697 DeclarationNameInfo(FD->getDeclName(), Loc));
698 if (
Field.isInvalid())
701 auto *InnerRD = FD->getType()->getAsRecordDecl();
702 auto *InnerCXXRD = dyn_cast_or_null<CXXRecordDecl>(InnerRD);
703 if (InnerRD && (!InnerCXXRD || InnerCXXRD->isAggregate())) {
705 if (callPrintFunction(Format, Args) ||
706 dumpRecordValue(InnerRD,
Field.get(), FieldIndentArg, Depth + 1))
710 if (appendFormatSpecifier(FD->getType(), Format)) {
712 Args.push_back(
Field.get());
722 Args.push_back(FieldAddr.
get());
725 if (callPrintFunction(Format, Args))
730 return RecordIndent ? callPrintFunction(
"%s}\n", RecordIndent)
731 : callPrintFunction(
"}\n");
734 Expr *buildWrapper() {
737 TheCall->
setType(Wrapper->getType());
758 diag::err_expected_struct_pointer_argument)
767 diag::err_incomplete_type))
776 switch (BT ? BT->getKind() : BuiltinType::Void) {
777 case BuiltinType::Dependent:
778 case BuiltinType::Overload:
779 case BuiltinType::BoundMember:
780 case BuiltinType::PseudoObject:
781 case BuiltinType::UnknownAny:
782 case BuiltinType::BuiltinFn:
788 diag::err_expected_callable_argument)
794 BuiltinDumpStructGenerator Generator(S, TheCall);
800 Expr *PtrArg = PtrArgResult.
get();
804 if (Generator.dumpUnnamedRecord(RD, PtrArg, 0))
807 return Generator.buildWrapper();
819 if (
Call->getStmtClass() != Stmt::CallExprClass) {
820 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
821 <<
Call->getSourceRange();
826 if (CE->getCallee()->getType()->isBlockPointerType()) {
827 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
828 <<
Call->getSourceRange();
832 const Decl *TargetDecl = CE->getCalleeDecl();
833 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
834 if (FD->getBuiltinID()) {
835 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
836 <<
Call->getSourceRange();
841 S.
Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
842 <<
Call->getSourceRange();
850 S.
Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
864 BuiltinCall->
setType(CE->getType());
868 BuiltinCall->
setArg(1, ChainResult.
get());
875class ScanfDiagnosticFormatHandler
879 using ComputeSizeFunction =
880 llvm::function_ref<std::optional<llvm::APSInt>(
unsigned)>;
884 using DiagnoseFunction =
885 llvm::function_ref<void(
unsigned,
unsigned,
unsigned)>;
887 ComputeSizeFunction ComputeSizeArgument;
888 DiagnoseFunction Diagnose;
891 ScanfDiagnosticFormatHandler(ComputeSizeFunction ComputeSizeArgument,
892 DiagnoseFunction Diagnose)
893 : ComputeSizeArgument(ComputeSizeArgument), Diagnose(Diagnose) {}
895 bool HandleScanfSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
896 const char *StartSpecifier,
897 unsigned specifierLen)
override {
901 unsigned NulByte = 0;
913 analyze_format_string::OptionalAmount FW = FS.
getFieldWidth();
915 analyze_format_string::OptionalAmount::HowSpecified::Constant)
920 std::optional<llvm::APSInt> DestSizeAPS =
925 unsigned DestSize = DestSizeAPS->getZExtValue();
927 if (DestSize < SourceSize)
934class EstimateSizeFormatHandler
939 bool IsKernelCompatible =
true;
942 EstimateSizeFormatHandler(StringRef Format)
943 :
Size(std::
min(Format.find(0), Format.size()) +
946 bool HandlePrintfSpecifier(
const analyze_printf::PrintfSpecifier &FS,
947 const char *,
unsigned SpecifierLen,
948 const TargetInfo &)
override {
950 const size_t FieldWidth = computeFieldWidth(FS);
951 const size_t Precision = computePrecision(FS);
958 Size += std::max(FieldWidth, (
size_t)1);
970 Size += std::max(FieldWidth, Precision);
986 Size += std::max(FieldWidth, 1 +
987 (Precision ? 1 + Precision
997 (Precision ? 1 + Precision : 0) +
1005 std::max(FieldWidth,
1007 (Precision ? 1 + Precision : 0) +
1022 IsKernelCompatible =
false;
1023 Size += std::max(FieldWidth, 2 + Precision);
1070 Size += (Precision ? 0 : 1);
1077 assert(SpecifierLen <= Size &&
"no underflow");
1078 Size -= SpecifierLen;
1082 size_t getSizeLowerBound()
const {
return Size; }
1083 bool isKernelCompatible()
const {
return IsKernelCompatible; }
1086 static size_t computeFieldWidth(
const analyze_printf::PrintfSpecifier &FS) {
1087 const analyze_format_string::OptionalAmount &FW = FS.
getFieldWidth();
1088 size_t FieldWidth = 0;
1094 static size_t computePrecision(
const analyze_printf::PrintfSpecifier &FS) {
1095 const analyze_format_string::OptionalAmount &FW = FS.
getPrecision();
1096 size_t Precision = 0;
1143 StringRef &FormatStrRef,
size_t &StrLen,
1145 if (
const auto *Format = dyn_cast<StringLiteral>(FormatExpr);
1146 Format && (Format->isOrdinary() || Format->isUTF8())) {
1147 FormatStrRef = Format->getString();
1149 Context.getAsConstantArrayType(Format->getType());
1150 assert(
T &&
"String literal not of constant array type!");
1151 size_t TypeSize =
T->getZExtSize();
1153 StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, FormatStrRef.find(0));
1161class FortifiedBufferChecker {
1163 FortifiedBufferChecker(Sema &S, FunctionDecl *FD, CallExpr *TheCall)
1164 : S(S), TheCall(TheCall), FD(FD),
1165 DABAttr(FD ? FD->getAttr<DiagnoseAsBuiltinAttr>() :
nullptr) {
1170 std::optional<unsigned> TranslateIndex(
unsigned Index) {
1175 unsigned NewIndex = Index;
1177 unsigned DABIndices = DABAttr->argIndices_size();
1178 NewIndex = Index < DABIndices ? DABAttr->argIndices_begin()[Index]
1182 return std::nullopt;
1188 std::optional<llvm::APSInt> EvaluateIntegerArgument(
unsigned Index) {
1189 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1191 return std::nullopt;
1193 Expr *Arg = TheCall->
getArg(*IndexOptional);
1195 return std::nullopt;
1197 return Result.Val.getInt();
1200 std::optional<llvm::APSInt>
1201 ComputeExplicitObjectSizeArgument(
unsigned Index) {
1202 std::optional<llvm::APSInt>
Integer = EvaluateIntegerArgument(Index);
1204 return std::nullopt;
1210 std::optional<llvm::APSInt> ComputeSizeArgument(
unsigned Index) {
1216 if (Index < FD->getNumParams()) {
1217 if (
const auto *POS =
1219 BOSType = POS->getType();
1222 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1224 return std::nullopt;
1226 const Expr *ObjArg = TheCall->
getArg(*IndexOptional);
1227 if (std::optional<uint64_t> ObjSize =
1230 return llvm::APSInt::getUnsigned(*ObjSize).extOrTrunc(SizeTypeWidth);
1232 return std::nullopt;
1235 std::optional<llvm::APSInt>
1236 ComputeExplicitObjectSizeArgumentProduct(
unsigned LIndex,
unsigned RIndex) {
1237 auto L = ComputeExplicitObjectSizeArgument(LIndex);
1238 auto R = ComputeExplicitObjectSizeArgument(RIndex);
1240 return std::nullopt;
1243 2 * std::max({L->getBitWidth(),
R->getBitWidth(), SizeTypeWidth});
1245 llvm::APSInt
LE = L->extOrTrunc(W);
1246 llvm::APSInt RE =
R->extOrTrunc(W);
1251 std::optional<llvm::APSInt> ComputeStrLenArgument(
unsigned Index) {
1252 std::optional<unsigned> IndexOptional = TranslateIndex(Index);
1254 return std::nullopt;
1255 unsigned NewIndex = *IndexOptional;
1257 const Expr *ObjArg = TheCall->
getArg(NewIndex);
1259 if (std::optional<uint64_t>
Result =
1262 return llvm::APSInt::getUnsigned(*
Result + 1).extOrTrunc(SizeTypeWidth);
1264 return std::nullopt;
1267 unsigned getSizeTypeWidth()
const {
return SizeTypeWidth; }
1269 unsigned getBuiltinID()
const {
1270 const FunctionDecl *UseDecl = FD;
1272 UseDecl = DABAttr->getFunction();
1273 assert(UseDecl &&
"Missing FunctionDecl in DiagnoseAsBuiltin attribute!");
1280 unsigned ID = getBuiltinID();
1284 assert(Callee &&
"expected callee");
1285 return Callee->getName().str();
1288 StringRef Ref = Name;
1290 if (!(Ref.consume_front(
"__builtin___") && Ref.consume_back(
"_chk")))
1291 Ref.consume_front(
"__builtin_");
1292 assert(!Ref.empty() &&
"expected non-empty function name");
1297 void checkSourceOverread(
unsigned SrcArgIdx,
unsigned SizeArgIdx) {
1301 const Expr *SrcArg = TheCall->
getArg(SrcArgIdx);
1302 const Expr *SizeArg = TheCall->
getArg(SizeArgIdx);
1307 std::optional<llvm::APSInt> CopyLen =
1308 ComputeExplicitObjectSizeArgument(SizeArgIdx);
1309 std::optional<llvm::APSInt> SrcBufSize = ComputeSizeArgument(SrcArgIdx);
1311 if (!CopyLen || !SrcBufSize)
1315 if (llvm::APSInt::compareValues(*CopyLen, *SrcBufSize) <= 0)
1319 S.
PDiag(diag::warn_stringop_overread)
1321 << SrcBufSize->getZExtValue());
1328 const DiagnoseAsBuiltinAttr *DABAttr;
1329 unsigned SizeTypeWidth;
1333void Sema::checkFortifiedBuiltinMemoryFunction(
FunctionDecl *FD,
1338 FortifiedBufferChecker Checker(*
this, FD, TheCall);
1340 unsigned BuiltinID = Checker.getBuiltinID();
1344 unsigned SizeTypeWidth = Checker.getSizeTypeWidth();
1346 std::optional<llvm::APSInt> AccessSize;
1347 std::optional<llvm::APSInt> BufferSize;
1348 unsigned DiagID = 0;
1350 switch (BuiltinID) {
1353 case Builtin::BI__builtin_strcat:
1354 case Builtin::BIstrcat:
1355 case Builtin::BI__builtin_stpcpy:
1356 case Builtin::BIstpcpy:
1357 case Builtin::BI__builtin_strcpy:
1358 case Builtin::BIstrcpy: {
1359 DiagID = diag::warn_fortify_strlen_overflow;
1360 AccessSize = Checker.ComputeStrLenArgument(1);
1361 BufferSize = Checker.ComputeSizeArgument(0);
1365 case Builtin::BI__builtin___strcat_chk:
1366 case Builtin::BI__builtin___stpcpy_chk:
1367 case Builtin::BI__builtin___strcpy_chk: {
1368 DiagID = diag::warn_fortify_strlen_overflow;
1369 AccessSize = Checker.ComputeStrLenArgument(1);
1370 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1374 case Builtin::BIscanf:
1375 case Builtin::BIfscanf:
1376 case Builtin::BIsscanf: {
1377 unsigned FormatIndex = 1;
1378 unsigned DataIndex = 2;
1379 if (BuiltinID == Builtin::BIscanf) {
1384 const auto *FormatExpr =
1387 StringRef FormatStrRef;
1392 auto Diagnose = [&](
unsigned ArgIndex,
unsigned DestSize,
1393 unsigned SourceSize) {
1394 DiagID = diag::warn_fortify_scanf_overflow;
1395 unsigned Index = ArgIndex + DataIndex;
1396 std::string FunctionName = Checker.getFunctionName();
1398 PDiag(DiagID) << FunctionName << (Index + 1)
1399 << DestSize << SourceSize);
1402 auto ShiftedComputeSizeArgument = [&](
unsigned Index) {
1403 return Checker.ComputeSizeArgument(Index + DataIndex);
1405 ScanfDiagnosticFormatHandler H(ShiftedComputeSizeArgument,
Diagnose);
1406 const char *FormatBytes = FormatStrRef.data();
1417 case Builtin::BIsprintf:
1418 case Builtin::BI__builtin_sprintf:
1419 case Builtin::BI__builtin___sprintf_chk:
1420 case Builtin::BIvsprintf:
1421 case Builtin::BI__builtin_vsprintf:
1422 case Builtin::BI__builtin___vsprintf_chk: {
1423 bool IsChk = BuiltinID == Builtin::BI__builtin___sprintf_chk ||
1424 BuiltinID == Builtin::BI__builtin___vsprintf_chk;
1425 std::optional<unsigned> FormatIndex = Checker.TranslateIndex(IsChk ? 3 : 1);
1428 const auto *FormatExpr =
1431 StringRef FormatStrRef;
1434 EstimateSizeFormatHandler H(FormatStrRef);
1435 const char *FormatBytes = FormatStrRef.data();
1437 H, FormatBytes, FormatBytes + StrLen,
getLangOpts(),
1438 Context.getTargetInfo(),
false)) {
1439 DiagID = H.isKernelCompatible()
1440 ? diag::warn_format_overflow
1441 : diag::warn_format_overflow_non_kprintf;
1442 AccessSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1443 .extOrTrunc(SizeTypeWidth);
1445 BufferSize = Checker.ComputeExplicitObjectSizeArgument(2);
1447 BufferSize = Checker.ComputeSizeArgument(0);
1454 case Builtin::BI__builtin___memcpy_chk:
1455 case Builtin::BI__builtin___memmove_chk:
1456 case Builtin::BI__builtin___memset_chk:
1457 case Builtin::BI__builtin___strlcat_chk:
1458 case Builtin::BI__builtin___strlcpy_chk:
1459 case Builtin::BI__builtin___strncat_chk:
1460 case Builtin::BI__builtin___strncpy_chk:
1461 case Builtin::BI__builtin___stpncpy_chk:
1462 case Builtin::BI__builtin___memccpy_chk:
1463 case Builtin::BI__builtin___mempcpy_chk: {
1464 DiagID = diag::warn_builtin_chk_overflow;
1466 Checker.ComputeExplicitObjectSizeArgument(TheCall->
getNumArgs() - 2);
1468 Checker.ComputeExplicitObjectSizeArgument(TheCall->
getNumArgs() - 1);
1470 if (BuiltinID == Builtin::BI__builtin___memcpy_chk ||
1471 BuiltinID == Builtin::BI__builtin___memmove_chk ||
1472 BuiltinID == Builtin::BI__builtin___mempcpy_chk) {
1473 Checker.checkSourceOverread(1, 2);
1478 case Builtin::BI__builtin___snprintf_chk:
1479 case Builtin::BI__builtin___vsnprintf_chk: {
1480 DiagID = diag::warn_builtin_chk_overflow;
1481 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1482 BufferSize = Checker.ComputeExplicitObjectSizeArgument(3);
1486 case Builtin::BImemccpy: {
1489 DiagID = diag::warn_fortify_source_size_mismatch;
1490 AccessSize = Checker.ComputeExplicitObjectSizeArgument(3);
1491 BufferSize = Checker.ComputeSizeArgument(0);
1495 case Builtin::BIstrncat:
1496 case Builtin::BI__builtin_strncat:
1497 case Builtin::BIstrncpy:
1498 case Builtin::BI__builtin_strncpy:
1499 case Builtin::BIstpncpy:
1500 case Builtin::BI__builtin_stpncpy:
1501 case Builtin::BIstrlcat:
1502 case Builtin::BI__builtin_strlcat:
1503 case Builtin::BIstrlcpy:
1504 case Builtin::BI__builtin_strlcpy: {
1510 DiagID = diag::warn_fortify_source_size_mismatch;
1511 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1512 BufferSize = Checker.ComputeSizeArgument(0);
1516 case Builtin::BIrecv:
1517 case Builtin::BIrecvfrom: {
1518 unsigned ExpectedArgs = BuiltinID == Builtin::BIrecv ? 4 : 6;
1523 DiagID = diag::warn_fortify_source_size_mismatch;
1524 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1525 BufferSize = Checker.ComputeSizeArgument(1);
1529 case Builtin::BIgetlogin_r: {
1530 DiagID = diag::warn_fortify_source_size_mismatch;
1531 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1532 BufferSize = Checker.ComputeSizeArgument(0);
1536 case Builtin::BIttyname_r:
1537 case Builtin::BIptsname_r:
1538 case Builtin::BIconfstr: {
1539 DiagID = diag::warn_fortify_source_size_mismatch;
1540 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1541 BufferSize = Checker.ComputeSizeArgument(1);
1545 case Builtin::BIpoll:
1546 case Builtin::BIppoll:
1547 case Builtin::BIppoll64: {
1548 unsigned ExpectedArgs = BuiltinID == Builtin::BIpoll ? 3 : 4;
1558 if (BuiltinID == Builtin::BIpoll) {
1563 if (TmoPointeeTy.
isNull())
1570 std::optional<CharUnits> ElemSize =
1571 Context.getTypeSizeInCharsIfKnown(PointeeTy);
1574 std::optional<llvm::APSInt> Count =
1575 Checker.ComputeExplicitObjectSizeArgument(1);
1578 DiagID = diag::warn_fortify_source_size_mismatch;
1579 unsigned WideWidth = SizeTypeWidth * 2;
1580 AccessSize = Count->extOrTrunc(WideWidth) *
1581 llvm::APSInt(llvm::APInt(WideWidth, ElemSize->getQuantity()),
1583 BufferSize = Checker.ComputeSizeArgument(0);
1587 case Builtin::BIbzero:
1588 case Builtin::BI__builtin_bzero:
1589 case Builtin::BIexplicit_bzero: {
1590 DiagID = diag::warn_fortify_source_overflow;
1591 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1592 BufferSize = Checker.ComputeSizeArgument(0);
1596 case Builtin::BImemcpy:
1597 case Builtin::BI__builtin_memcpy:
1598 case Builtin::BImemmove:
1599 case Builtin::BI__builtin_memmove:
1600 case Builtin::BImemset:
1601 case Builtin::BI__builtin_memset:
1602 case Builtin::BImemset_explicit:
1603 case Builtin::BImempcpy:
1604 case Builtin::BI__builtin_mempcpy: {
1605 DiagID = diag::warn_fortify_source_overflow;
1606 AccessSize = Checker.ComputeExplicitObjectSizeArgument(2);
1607 BufferSize = Checker.ComputeSizeArgument(0);
1610 if (BuiltinID != Builtin::BImemset &&
1611 BuiltinID != Builtin::BI__builtin_memset &&
1612 BuiltinID != Builtin::BImemset_explicit) {
1613 Checker.checkSourceOverread(1, 2);
1617 case Builtin::BIbcopy:
1618 case Builtin::BI__builtin_bcopy: {
1619 DiagID = diag::warn_fortify_source_overflow;
1621 Checker.ComputeExplicitObjectSizeArgument(TheCall->
getNumArgs() - 1);
1622 BufferSize = Checker.ComputeSizeArgument(1);
1623 Checker.checkSourceOverread(0, 2);
1626 case Builtin::BIfread:
1627 case Builtin::BIfread_unlocked: {
1628 DiagID = diag::warn_fortify_source_overflow;
1629 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1630 BufferSize = Checker.ComputeSizeArgument(0);
1633 case Builtin::BIfwrite:
1634 case Builtin::BIfwrite_unlocked: {
1635 DiagID = diag::warn_fortify_source_overread;
1636 AccessSize = Checker.ComputeExplicitObjectSizeArgumentProduct(1, 2);
1637 BufferSize = Checker.ComputeSizeArgument(0);
1640 case Builtin::BIfgets:
1641 case Builtin::BIfgets_unlocked: {
1642 AccessSize = Checker.EvaluateIntegerArgument(1);
1644 if (AccessSize && AccessSize->isNegative()) {
1646 PDiag(diag::warn_fortify_source_negative_size)
1647 << Checker.getFunctionName());
1651 DiagID = diag::warn_fortify_source_size_mismatch;
1652 BufferSize = Checker.ComputeSizeArgument(0);
1656 case Builtin::BImemchr:
1657 case Builtin::BI__builtin_memchr: {
1658 Checker.checkSourceOverread(0, 2);
1664 case Builtin::BImemcmp:
1665 case Builtin::BI__builtin_memcmp:
1666 case Builtin::BIbcmp:
1667 case Builtin::BI__builtin_bcmp: {
1668 Checker.checkSourceOverread(0, 2);
1669 Checker.checkSourceOverread(1, 2);
1672 case Builtin::BIsnprintf:
1673 case Builtin::BI__builtin_snprintf:
1674 case Builtin::BIvsnprintf:
1675 case Builtin::BI__builtin_vsnprintf: {
1676 DiagID = diag::warn_fortify_source_size_mismatch;
1677 AccessSize = Checker.ComputeExplicitObjectSizeArgument(1);
1679 StringRef FormatStrRef;
1683 EstimateSizeFormatHandler H(FormatStrRef);
1684 const char *FormatBytes = FormatStrRef.data();
1686 H, FormatBytes, FormatBytes + StrLen,
getLangOpts(),
1687 Context.getTargetInfo(),
false)) {
1688 llvm::APSInt FormatSize =
1689 llvm::APSInt::getUnsigned(H.getSizeLowerBound())
1690 .extOrTrunc(SizeTypeWidth);
1691 if (FormatSize > *AccessSize && *AccessSize != 0) {
1692 unsigned TruncationDiagID =
1693 H.isKernelCompatible() ? diag::warn_format_truncation
1694 : diag::warn_format_truncation_non_kprintf;
1695 SmallString<16> SpecifiedSizeStr;
1696 SmallString<16> FormatSizeStr;
1697 AccessSize->toString(SpecifiedSizeStr, 10);
1698 FormatSize.toString(FormatSizeStr, 10);
1700 PDiag(TruncationDiagID)
1701 << Checker.getFunctionName()
1702 << SpecifiedSizeStr << FormatSizeStr);
1706 BufferSize = Checker.ComputeSizeArgument(0);
1710 CheckSizeofMemaccessArgument(LenArg, Dest, FnInfo);
1714 if (!AccessSize || !BufferSize ||
1715 llvm::APSInt::compareValues(*AccessSize, *BufferSize) <= 0)
1718 std::string FunctionName = Checker.getFunctionName();
1720 SmallString<16> BufferSizeStr;
1721 SmallString<16> AccessSizeStr;
1722 BufferSize->toString(BufferSizeStr, 10);
1723 AccessSize->toString(AccessSizeStr, 10);
1726 << FunctionName << BufferSizeStr << AccessSizeStr);
1746 Expr *Arg = TheCall->
getArg(0);
1758 llvm::APInt RawValue =
R.Val.getInt();
1759 llvm::APInt Mask(RawValue.getBitWidth(), 0777);
1760 llvm::APInt
Extra = RawValue & ~Mask;
1763 SmallString<16> ExtraStr;
1764 Extra.toString(ExtraStr, 8,
false);
1781 if (!S || !(S->
getFlags() & NeededScopeFlags)) {
1784 << DRE->getDecl()->getIdentifier();
1796 "__builtin_alloca has invalid address space");
1822enum PointerAuthOpKind {
1838 Diag(Loc, diag::err_ptrauth_disabled) << Range;
1869 if (!
Context.getTargetInfo().validatePointerAuthKey(*KeyValue)) {
1872 llvm::raw_svector_ostream Str(
Value);
1881 Result = KeyValue->getZExtValue();
1900 bool IsAddrDiscArg =
false;
1905 IsAddrDiscArg =
true;
1914 Diag(Arg->
getExprLoc(), diag::err_ptrauth_address_discrimination_invalid)
1915 <<
Result->getExtValue();
1917 Diag(Arg->
getExprLoc(), diag::err_ptrauth_extra_discriminator_invalid)
1923 IntVal =
Result->getZExtValue();
1927static std::pair<const ValueDecl *, CharUnits>
1934 const auto *BaseDecl =
1939 return {BaseDecl,
Result.Val.getLValueOffset()};
1943 bool RequireConstant =
false) {
1951 auto AllowsPointer = [](PointerAuthOpKind OpKind) {
1952 return OpKind != PAO_BlendInteger;
1954 auto AllowsInteger = [](PointerAuthOpKind OpKind) {
1955 return OpKind == PAO_Discriminator || OpKind == PAO_BlendInteger ||
1956 OpKind == PAO_SignGeneric || OpKind == PAO_BlendPC;
1965 }
else if (AllowsInteger(OpKind) &&
1972 <<
unsigned(OpKind == PAO_Discriminator ? 1
1973 : OpKind == PAO_BlendPointer ? 2
1974 : OpKind == PAO_BlendInteger ? 3
1975 : OpKind == PAO_BlendPC ? 4
1977 <<
unsigned(AllowsInteger(OpKind) ? (AllowsPointer(OpKind) ? 2 : 1) : 0)
1987 if (!RequireConstant) {
1989 if ((OpKind == PAO_Sign || OpKind == PAO_Auth) &&
1992 ? diag::warn_ptrauth_sign_null_pointer
1993 : diag::warn_ptrauth_auth_null_pointer)
2003 if (OpKind == PAO_Sign) {
2021 S.
Diag(Arg->
getExprLoc(), diag::err_ptrauth_bad_constant_pointer);
2026 assert(OpKind == PAO_Discriminator);
2032 if (
Call->getBuiltinCallee() ==
2033 Builtin::BI__builtin_ptrauth_blend_discriminator) {
2048 assert(
Pointer->getType()->isPointerType());
2060 assert(
Integer->getType()->isIntegerType());
2066 S.
Diag(Arg->
getExprLoc(), diag::err_ptrauth_bad_constant_discriminator);
2079 Call->setType(
Call->getArgs()[0]->getType());
2110 PointerAuthOpKind OpKind,
2111 bool RequireConstant) {
2122 Call->setType(
Call->getArgs()[0]->getType());
2138 Call->setType(
Call->getArgs()[0]->getType());
2159 unsigned OldKey = 0;
2162 if (OldKey !=
static_cast<unsigned>(AK::ASIA) &&
2163 OldKey !=
static_cast<unsigned>(AK::ASIB)) {
2164 S.
Diag(
Call->getArgs()[1]->getExprLoc(),
2165 diag::err_ptrauth_auth_with_pc_and_resign_invalid_key)
2166 << OldKey <<
Call->getArgs()[1]->getSourceRange();
2171 Call->setType(
Call->getArgs()[0]->getType());
2180 const Expr *AddendExpr =
Call->getArg(5);
2182 if (!AddendIsConstInt) {
2183 const Expr *Arg =
Call->getArg(5)->IgnoreParenImpCasts();
2197 Call->setType(
Call->getArgs()[0]->getType());
2206 const Expr *Arg =
Call->getArg(0)->IgnoreParenImpCasts();
2209 const auto *Literal = dyn_cast<StringLiteral>(Arg);
2210 if (!Literal || Literal->getCharByteWidth() != 1) {
2226 Call->setArg(0, FirstValue.
get());
2232 if (!FirstArgRecord) {
2233 S.
Diag(FirstArg->
getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2234 << 0 << FirstArgType;
2239 diag::err_get_vtable_pointer_requires_complete_type)) {
2244 S.
Diag(FirstArg->
getBeginLoc(), diag::err_get_vtable_pointer_incorrect_type)
2245 << 1 << FirstArgRecord;
2249 Call->setType(ReturnType);
2274 auto DiagSelect = [&]() -> std::optional<unsigned> {
2281 return std::optional<unsigned>{};
2296 diag::err_incomplete_type))
2300 "Unhandled non-object pointer case");
2328 if (PT->getPointeeType()->isFunctionType()) {
2330 diag::err_builtin_is_within_lifetime_invalid_arg)
2336 if (PT->getPointeeType()->isVariableArrayType()) {
2338 << 1 <<
"__builtin_is_within_lifetime";
2343 diag::err_builtin_is_within_lifetime_invalid_arg)
2357 diag::err_builtin_trivially_relocate_invalid_arg_type)
2364 diag::err_incomplete_type))
2368 T->isIncompleteArrayType()) {
2370 diag::err_builtin_trivially_relocate_invalid_arg_type)
2371 << (
T.isConstQualified() ? 1 : 2);
2380 diag::err_builtin_trivially_relocate_invalid_arg_type)
2387 if (Size.isInvalid())
2391 if (Size.isInvalid())
2393 SizeExpr = Size.get();
2394 TheCall->
setArg(2, SizeExpr);
2404 llvm::Triple::ObjectFormatType CurObjFormat =
2406 if (llvm::is_contained(UnsupportedObjectFormatTypes, CurObjFormat)) {
2419 llvm::Triple::ArchType CurArch =
2421 if (llvm::is_contained(SupportedArchs, CurArch))
2431bool Sema::CheckTSBuiltinFunctionCall(
const TargetInfo &TI,
unsigned BuiltinID,
2438 case llvm::Triple::arm:
2439 case llvm::Triple::armeb:
2440 case llvm::Triple::thumb:
2441 case llvm::Triple::thumbeb:
2443 case llvm::Triple::aarch64:
2444 case llvm::Triple::aarch64_32:
2445 case llvm::Triple::aarch64_be:
2447 case llvm::Triple::bpfeb:
2448 case llvm::Triple::bpfel:
2450 case llvm::Triple::dxil:
2452 case llvm::Triple::hexagon:
2454 case llvm::Triple::mips:
2455 case llvm::Triple::mipsel:
2456 case llvm::Triple::mips64:
2457 case llvm::Triple::mips64el:
2459 case llvm::Triple::spirv:
2460 case llvm::Triple::spirv32:
2461 case llvm::Triple::spirv64:
2462 if (TI.
getTriple().getOS() != llvm::Triple::OSType::AMDHSA)
2465 case llvm::Triple::systemz:
2467 case llvm::Triple::x86:
2468 case llvm::Triple::x86_64:
2470 case llvm::Triple::ppc:
2471 case llvm::Triple::ppcle:
2472 case llvm::Triple::ppc64:
2473 case llvm::Triple::ppc64le:
2475 case llvm::Triple::amdgpu:
2477 case llvm::Triple::riscv32:
2478 case llvm::Triple::riscv64:
2479 case llvm::Triple::riscv32be:
2480 case llvm::Triple::riscv64be:
2482 case llvm::Triple::loongarch32:
2483 case llvm::Triple::loongarch64:
2486 case llvm::Triple::wasm32:
2487 case llvm::Triple::wasm64:
2489 case llvm::Triple::nvptx:
2490 case llvm::Triple::nvptx64:
2496 return T->isDependentType() ||
2497 (
T->isRealType() && !
T->isBooleanType() && !
T->isEnumeralType());
2512 switch (ArgTyRestr) {
2516 return S.
Diag(Loc, diag::err_builtin_invalid_arg_type)
2517 << ArgOrdinal << 2 << 1 << 1
2524 return S.
Diag(Loc, diag::err_builtin_invalid_arg_type)
2525 << ArgOrdinal << 5 << 0
2531 return S.
Diag(Loc, diag::err_builtin_invalid_arg_type)
2532 << ArgOrdinal << 5 << 1
2538 return S.
Diag(Loc, diag::err_builtin_invalid_arg_type)
2552 const TargetInfo *AuxTI,
unsigned BuiltinID) {
2553 assert((BuiltinID == Builtin::BI__builtin_cpu_supports ||
2554 BuiltinID == Builtin::BI__builtin_cpu_is) &&
2555 "Expecting __builtin_cpu_...");
2557 bool IsCPUSupports = BuiltinID == Builtin::BI__builtin_cpu_supports;
2559 auto SupportsBI = [=](
const TargetInfo *TInfo) {
2560 return TInfo && ((IsCPUSupports && TInfo->supportsCpuSupports()) ||
2561 (!IsCPUSupports && TInfo->supportsCpuIs()));
2563 if (!SupportsBI(&TI) && SupportsBI(AuxTI))
2570 ? diag::err_builtin_aix_os_unsupported
2571 : diag::err_builtin_target_unsupported)
2577 return S.
Diag(TheCall->
getBeginLoc(), diag::err_expr_not_string_literal)
2615 if (
const auto *BT = dyn_cast<BitIntType>(ArgTy)) {
2616 if (BT->getNumBits() % 16 != 0 && BT->getNumBits() != 8 &&
2617 BT->getNumBits() != 1) {
2619 << ArgTy << BT->getNumBits();
2695 diag::err_builtin_stdc_invalid_arg_type_bool_or_enum)
2698 return S.
Diag(Arg->
getBeginLoc(), diag::err_builtin_stdc_invalid_arg_type)
2707 if (!llvm::isUIntN(ReturnTypeWidth, ArgWidth))
2708 return S.
Diag(Arg->
getBeginLoc(), diag::err_builtin_stdc_result_overflow)
2728 TheCall->
setArg(0, Arg0);
2745 TheCall->
setArg(1, Arg1);
2751 << 2 << 1 << 4 << 0 << Arg1Ty;
2765 return S.
Diag(Loc, diag::err_builtin_invalid_arg_type)
2767 << (OnlyUnsigned ? 3 : 1)
2775 ArgIndex(ArgIndex), OnlyUnsigned(OnlyUnsigned) {}
2778 return OnlyUnsigned ?
T->isUnsignedIntegerType() :
T->isIntegerType();
2783 return emitError(S, Loc,
T);
2788 return emitError(S, Loc,
T);
2794 return emitError(S, Loc,
T);
2799 return S.
Diag(Conv->
getLocation(), diag::note_conv_function_declared_at);
2804 return emitError(S, Loc,
T);
2809 return S.
Diag(Conv->
getLocation(), diag::note_conv_function_declared_at);
2815 llvm_unreachable(
"conversion functions are permitted");
2834 TheCall->
setArg(0, Arg0);
2848 TheCall->
setArg(1, Arg1);
2859 unsigned Pos,
bool AllowConst,
2863 return S.
Diag(MaskArg->
getBeginLoc(), diag::err_builtin_invalid_arg_type)
2868 if (!PtrTy->isPointerType() || PtrTy->getPointeeType()->isVectorType())
2869 return S.
Diag(PtrArg->
getExprLoc(), diag::err_vec_masked_load_store_ptr)
2870 << Pos <<
"scalar pointer";
2879 diag::err_typecheck_convert_incompatible)
2888 bool TypeDependent =
false;
2889 for (
unsigned Arg = 0, E = TheCall->
getNumArgs(); Arg != E; ++Arg) {
2917 Builtin::BI__builtin_masked_load))
2931 return S.
Diag(PtrArg->
getExprLoc(), diag::err_vec_masked_load_store_ptr)
2954 Builtin::BI__builtin_masked_store))
2962 S.
Diag(ValArg->
getExprLoc(), diag::err_vec_masked_load_store_ptr)
2973 << MaskTy << ValTy);
2977 PtrTy->getPointeeType().getUnqualifiedType()))
2979 diag::err_vec_builtin_incompatible_vector)
3008 return S.
Diag(MaskArg->
getBeginLoc(), diag::err_builtin_invalid_arg_type)
3021 << MaskTy << IdxTy);
3030 diag::err_vec_masked_load_store_ptr)
3059 return S.
Diag(MaskArg->
getBeginLoc(), diag::err_builtin_invalid_arg_type)
3074 << MaskTy << IdxTy);
3080 << MaskTy << ValTy);
3083 PtrTy->getPointeeType().getUnqualifiedType()))
3085 diag::err_vec_builtin_incompatible_vector)
3099 if (Args.size() == 0) {
3101 diag::err_typecheck_call_too_few_args_at_least)
3107 QualType FuncT = Args[0]->getType();
3110 if (Args.size() < 2) {
3112 diag::err_typecheck_call_too_few_args_at_least)
3118 const Type *MemPtrClass = MPT->getQualifier().getAsType();
3119 QualType ObjectT = Args[1]->getType();
3121 if (MPT->isMemberDataPointer() && S.
checkArgCount(TheCall, 2))
3170 tok::periodstar, ObjectArg.
get(), Args[0]);
3174 if (MPT->isMemberDataPointer())
3178 auto *MemCall =
new (S.
Context)
3202 return TyA->getElementType();
3210 const llvm::APSInt &
Result,
int Low,
3211 int High,
bool RangeIsError) {
3220 if (
Result.getSExtValue() < Low ||
Result.getSExtValue() > High) {
3222 return S.
Diag(TheCall->
getBeginLoc(), diag::err_argument_invalid_range)
3229 S.
PDiag(diag::warn_argument_invalid_range)
3238Sema::CheckBuiltinFunctionCall(
FunctionDecl *FDecl,
unsigned BuiltinID,
3243 unsigned ICEArguments = 0;
3245 Context.GetBuiltinType(BuiltinID,
Error, &ICEArguments);
3246 SmallVector<Builtin::Context::ArgRange, 2> ArgRanges;
3249 else if (ICEArguments)
3250 Context.BuiltinInfo.getArgRanges(BuiltinID, ArgRanges);
3253 for (
unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
3255 if ((ICEArguments & (1 << ArgNo)) == 0)
continue;
3257 ICEArguments &= ~(1 << ArgNo);
3268 for (
const Builtin::Context::ArgRange &Range : ArgRanges) {
3269 if (
Range.Index == ArgNo &&
3278 switch (BuiltinID) {
3279 case Builtin::BI__builtin___get_unsafe_stack_start:
3280 case Builtin::BI__builtin___get_unsafe_stack_bottom:
3282 <<
Context.BuiltinInfo.getQuotedName(BuiltinID)
3283 <<
"__safestack_get_unsafe_stack_bottom";
3285 case Builtin::BI__builtin___get_unsafe_stack_top:
3287 <<
Context.BuiltinInfo.getQuotedName(BuiltinID)
3288 <<
"__safestack_get_unsafe_stack_top";
3290 case Builtin::BI__builtin___get_unsafe_stack_ptr:
3292 <<
Context.BuiltinInfo.getQuotedName(BuiltinID)
3293 <<
"__safestack_get_unsafe_stack_ptr";
3295 case Builtin::BI__builtin_cpu_supports:
3296 case Builtin::BI__builtin_cpu_is:
3298 Context.getAuxTargetInfo(), BuiltinID))
3301 case Builtin::BI__builtin_cpu_init:
3302 if (!
Context.getTargetInfo().supportsCpuInit()) {
3308 case Builtin::BI__builtin___CFStringMakeConstantString:
3312 *
this, BuiltinID, TheCall,
3313 {llvm::Triple::GOFF, llvm::Triple::XCOFF}))
3316 "Wrong # arguments to builtin CFStringMakeConstantString");
3317 if (
ObjC().CheckObjCString(TheCall->
getArg(0)))
3320 case Builtin::BI__builtin_ms_va_start:
3321 case Builtin::BI__builtin_zos_va_start:
3322 case Builtin::BI__builtin_stdarg_start:
3323 case Builtin::BI__builtin_va_start:
3324 case Builtin::BI__builtin_c23_va_start:
3325 if (BuiltinVAStart(BuiltinID, TheCall))
3328 case Builtin::BI__va_start: {
3329 switch (
Context.getTargetInfo().getTriple().getArch()) {
3330 case llvm::Triple::aarch64:
3331 case llvm::Triple::arm:
3332 case llvm::Triple::thumb:
3333 if (BuiltinVAStartARMMicrosoft(TheCall))
3337 if (BuiltinVAStart(BuiltinID, TheCall))
3345 case Builtin::BI_interlockedbittestandset_acq:
3346 case Builtin::BI_interlockedbittestandset_rel:
3347 case Builtin::BI_interlockedbittestandset_nf:
3348 case Builtin::BI_interlockedbittestandreset_acq:
3349 case Builtin::BI_interlockedbittestandreset_rel:
3350 case Builtin::BI_interlockedbittestandreset_nf:
3353 {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
3358 case Builtin::BI_bittest64:
3359 case Builtin::BI_bittestandcomplement64:
3360 case Builtin::BI_bittestandreset64:
3361 case Builtin::BI_bittestandset64:
3362 case Builtin::BI_interlockedbittestandreset64:
3363 case Builtin::BI_interlockedbittestandset64:
3366 {llvm::Triple::x86_64, llvm::Triple::arm, llvm::Triple::thumb,
3367 llvm::Triple::aarch64, llvm::Triple::amdgpu}))
3372 case Builtin::BI_interlockedbittestandreset64_acq:
3373 case Builtin::BI_interlockedbittestandreset64_rel:
3374 case Builtin::BI_interlockedbittestandreset64_nf:
3375 case Builtin::BI_interlockedbittestandset64_acq:
3376 case Builtin::BI_interlockedbittestandset64_rel:
3377 case Builtin::BI_interlockedbittestandset64_nf:
3382 case Builtin::BI__builtin_set_flt_rounds:
3385 {llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::arm,
3386 llvm::Triple::thumb, llvm::Triple::aarch64, llvm::Triple::amdgpu,
3387 llvm::Triple::ppc, llvm::Triple::ppc64, llvm::Triple::ppcle,
3388 llvm::Triple::ppc64le}))
3392 case Builtin::BI__builtin_isgreater:
3393 case Builtin::BI__builtin_isgreaterequal:
3394 case Builtin::BI__builtin_isless:
3395 case Builtin::BI__builtin_islessequal:
3396 case Builtin::BI__builtin_islessgreater:
3397 case Builtin::BI__builtin_isunordered:
3398 case Builtin::BI__builtin_iseqsig:
3399 if (BuiltinUnorderedCompare(TheCall, BuiltinID))
3402 case Builtin::BI__builtin_fpclassify:
3403 if (BuiltinFPClassification(TheCall, 6, BuiltinID))
3406 case Builtin::BI__builtin_isfpclass:
3407 if (BuiltinFPClassification(TheCall, 2, BuiltinID))
3410 case Builtin::BI__builtin_isfinite:
3411 case Builtin::BI__builtin_isinf:
3412 case Builtin::BI__builtin_isinf_sign:
3413 case Builtin::BI__builtin_isnan:
3414 case Builtin::BI__builtin_issignaling:
3415 case Builtin::BI__builtin_isnormal:
3416 case Builtin::BI__builtin_issubnormal:
3417 case Builtin::BI__builtin_iszero:
3418 case Builtin::BI__builtin_signbit:
3419 case Builtin::BI__builtin_signbitf:
3420 case Builtin::BI__builtin_signbitl:
3421 if (BuiltinFPClassification(TheCall, 1, BuiltinID))
3424 case Builtin::BI__builtin_shufflevector:
3428 case Builtin::BI__builtin_masked_load:
3429 case Builtin::BI__builtin_masked_expand_load:
3431 case Builtin::BI__builtin_masked_store:
3432 case Builtin::BI__builtin_masked_compress_store:
3434 case Builtin::BI__builtin_masked_gather:
3436 case Builtin::BI__builtin_masked_scatter:
3438 case Builtin::BI__builtin_invoke:
3440 case Builtin::BI__builtin_prefetch:
3441 if (BuiltinPrefetch(TheCall))
3444 case Builtin::BI__builtin_alloca_with_align:
3445 case Builtin::BI__builtin_alloca_with_align_uninitialized:
3446 if (BuiltinAllocaWithAlign(TheCall))
3449 case Builtin::BI__builtin_alloca:
3450 case Builtin::BI__builtin_alloca_uninitialized:
3457 case Builtin::BI__builtin_infer_alloc_token:
3461 case Builtin::BI__arithmetic_fence:
3462 if (BuiltinArithmeticFence(TheCall))
3465 case Builtin::BI__assume:
3466 case Builtin::BI__builtin_assume:
3467 if (BuiltinAssume(TheCall))
3470 case Builtin::BI__builtin_assume_aligned:
3471 if (BuiltinAssumeAligned(TheCall))
3474 case Builtin::BI__builtin_dynamic_object_size:
3475 case Builtin::BI__builtin_object_size:
3479 case Builtin::BI__builtin_longjmp:
3480 if (BuiltinLongjmp(TheCall))
3483 case Builtin::BI__builtin_setjmp:
3484 if (BuiltinSetjmp(TheCall))
3487 case Builtin::BI__builtin_complex:
3488 if (BuiltinComplex(TheCall))
3491 case Builtin::BI__builtin_classify_type:
3492 case Builtin::BI__builtin_constant_p: {
3501 case Builtin::BI__builtin_launder:
3503 case Builtin::BI__builtin_is_within_lifetime:
3505 case Builtin::BI__builtin_trivially_relocate:
3507 case Builtin::BI__builtin_clear_padding: {
3511 const Expr *PtrArg = TheCall->
getArg(0);
3512 const QualType PtrArgType = PtrArg->
getType();
3515 << PtrArgType <<
"pointer" << 1 << 0 << 3 << 1 << PtrArgType
3526 diag::err_typecheck_decl_incomplete_type))
3532 auto IsAddrOfDeclExpr = [&]() {
3534 const auto *UnaryOp = dyn_cast<UnaryOperator>(Inner);
3535 if (!UnaryOp || UnaryOp->getOpcode() != UO_AddrOf)
3539 UnaryOp->getSubExpr()->IgnoreParenNoopCasts(
Context);
3540 const auto *DeclRef = dyn_cast<DeclRefExpr>(Operand);
3544 const auto *VarDecl = dyn_cast<::clang::VarDecl>(DeclRef->getDecl());
3545 if (!VarDecl || VarDecl->getType()->isReferenceType())
3550 QualType VarQType = VarDecl->getType();
3552 Context.hasSameUnqualifiedType(PointeeType, VarQType);
3557 && !IsAddrOfDeclExpr()) {
3558 Diag(PtrArg->
getBeginLoc(), diag::err_clear_padding_needs_trivial_copy)
3565 Diag(PtrArg->
getBeginLoc(), diag::err_clear_padding_no_flexible_array)
3572 case Builtin::BI__sync_fetch_and_add:
3573 case Builtin::BI__sync_fetch_and_add_1:
3574 case Builtin::BI__sync_fetch_and_add_2:
3575 case Builtin::BI__sync_fetch_and_add_4:
3576 case Builtin::BI__sync_fetch_and_add_8:
3577 case Builtin::BI__sync_fetch_and_add_16:
3578 case Builtin::BI__sync_fetch_and_sub:
3579 case Builtin::BI__sync_fetch_and_sub_1:
3580 case Builtin::BI__sync_fetch_and_sub_2:
3581 case Builtin::BI__sync_fetch_and_sub_4:
3582 case Builtin::BI__sync_fetch_and_sub_8:
3583 case Builtin::BI__sync_fetch_and_sub_16:
3584 case Builtin::BI__sync_fetch_and_or:
3585 case Builtin::BI__sync_fetch_and_or_1:
3586 case Builtin::BI__sync_fetch_and_or_2:
3587 case Builtin::BI__sync_fetch_and_or_4:
3588 case Builtin::BI__sync_fetch_and_or_8:
3589 case Builtin::BI__sync_fetch_and_or_16:
3590 case Builtin::BI__sync_fetch_and_and:
3591 case Builtin::BI__sync_fetch_and_and_1:
3592 case Builtin::BI__sync_fetch_and_and_2:
3593 case Builtin::BI__sync_fetch_and_and_4:
3594 case Builtin::BI__sync_fetch_and_and_8:
3595 case Builtin::BI__sync_fetch_and_and_16:
3596 case Builtin::BI__sync_fetch_and_xor:
3597 case Builtin::BI__sync_fetch_and_xor_1:
3598 case Builtin::BI__sync_fetch_and_xor_2:
3599 case Builtin::BI__sync_fetch_and_xor_4:
3600 case Builtin::BI__sync_fetch_and_xor_8:
3601 case Builtin::BI__sync_fetch_and_xor_16:
3602 case Builtin::BI__sync_fetch_and_nand:
3603 case Builtin::BI__sync_fetch_and_nand_1:
3604 case Builtin::BI__sync_fetch_and_nand_2:
3605 case Builtin::BI__sync_fetch_and_nand_4:
3606 case Builtin::BI__sync_fetch_and_nand_8:
3607 case Builtin::BI__sync_fetch_and_nand_16:
3608 case Builtin::BI__sync_add_and_fetch:
3609 case Builtin::BI__sync_add_and_fetch_1:
3610 case Builtin::BI__sync_add_and_fetch_2:
3611 case Builtin::BI__sync_add_and_fetch_4:
3612 case Builtin::BI__sync_add_and_fetch_8:
3613 case Builtin::BI__sync_add_and_fetch_16:
3614 case Builtin::BI__sync_sub_and_fetch:
3615 case Builtin::BI__sync_sub_and_fetch_1:
3616 case Builtin::BI__sync_sub_and_fetch_2:
3617 case Builtin::BI__sync_sub_and_fetch_4:
3618 case Builtin::BI__sync_sub_and_fetch_8:
3619 case Builtin::BI__sync_sub_and_fetch_16:
3620 case Builtin::BI__sync_and_and_fetch:
3621 case Builtin::BI__sync_and_and_fetch_1:
3622 case Builtin::BI__sync_and_and_fetch_2:
3623 case Builtin::BI__sync_and_and_fetch_4:
3624 case Builtin::BI__sync_and_and_fetch_8:
3625 case Builtin::BI__sync_and_and_fetch_16:
3626 case Builtin::BI__sync_or_and_fetch:
3627 case Builtin::BI__sync_or_and_fetch_1:
3628 case Builtin::BI__sync_or_and_fetch_2:
3629 case Builtin::BI__sync_or_and_fetch_4:
3630 case Builtin::BI__sync_or_and_fetch_8:
3631 case Builtin::BI__sync_or_and_fetch_16:
3632 case Builtin::BI__sync_xor_and_fetch:
3633 case Builtin::BI__sync_xor_and_fetch_1:
3634 case Builtin::BI__sync_xor_and_fetch_2:
3635 case Builtin::BI__sync_xor_and_fetch_4:
3636 case Builtin::BI__sync_xor_and_fetch_8:
3637 case Builtin::BI__sync_xor_and_fetch_16:
3638 case Builtin::BI__sync_nand_and_fetch:
3639 case Builtin::BI__sync_nand_and_fetch_1:
3640 case Builtin::BI__sync_nand_and_fetch_2:
3641 case Builtin::BI__sync_nand_and_fetch_4:
3642 case Builtin::BI__sync_nand_and_fetch_8:
3643 case Builtin::BI__sync_nand_and_fetch_16:
3644 case Builtin::BI__sync_val_compare_and_swap:
3645 case Builtin::BI__sync_val_compare_and_swap_1:
3646 case Builtin::BI__sync_val_compare_and_swap_2:
3647 case Builtin::BI__sync_val_compare_and_swap_4:
3648 case Builtin::BI__sync_val_compare_and_swap_8:
3649 case Builtin::BI__sync_val_compare_and_swap_16:
3650 case Builtin::BI__sync_bool_compare_and_swap:
3651 case Builtin::BI__sync_bool_compare_and_swap_1:
3652 case Builtin::BI__sync_bool_compare_and_swap_2:
3653 case Builtin::BI__sync_bool_compare_and_swap_4:
3654 case Builtin::BI__sync_bool_compare_and_swap_8:
3655 case Builtin::BI__sync_bool_compare_and_swap_16:
3656 case Builtin::BI__sync_lock_test_and_set:
3657 case Builtin::BI__sync_lock_test_and_set_1:
3658 case Builtin::BI__sync_lock_test_and_set_2:
3659 case Builtin::BI__sync_lock_test_and_set_4:
3660 case Builtin::BI__sync_lock_test_and_set_8:
3661 case Builtin::BI__sync_lock_test_and_set_16:
3662 case Builtin::BI__sync_lock_release:
3663 case Builtin::BI__sync_lock_release_1:
3664 case Builtin::BI__sync_lock_release_2:
3665 case Builtin::BI__sync_lock_release_4:
3666 case Builtin::BI__sync_lock_release_8:
3667 case Builtin::BI__sync_lock_release_16:
3668 case Builtin::BI__sync_swap:
3669 case Builtin::BI__sync_swap_1:
3670 case Builtin::BI__sync_swap_2:
3671 case Builtin::BI__sync_swap_4:
3672 case Builtin::BI__sync_swap_8:
3673 case Builtin::BI__sync_swap_16:
3674 return BuiltinAtomicOverloaded(TheCallResult);
3675 case Builtin::BI__sync_synchronize:
3679 case Builtin::BI__builtin_nontemporal_load:
3680 case Builtin::BI__builtin_nontemporal_store:
3681 return BuiltinNontemporalOverloaded(TheCallResult);
3682 case Builtin::BI__builtin_memcpy_inline: {
3683 clang::Expr *SizeOp = TheCall->
getArg(2);
3695 case Builtin::BI__builtin_memset_inline: {
3696 clang::Expr *SizeOp = TheCall->
getArg(2);
3706#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
3707 case Builtin::BI##ID: \
3708 return AtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
3709#include "clang/Basic/Builtins.inc"
3710 case Builtin::BI__annotation: {
3711 const llvm::Triple &TT =
Context.getTargetInfo().getTriple();
3712 if (!TT.isOSWindows() && !TT.isUEFI()) {
3721 case Builtin::BI__builtin_annotation:
3725 case Builtin::BI__builtin_addressof:
3729 case Builtin::BI__builtin_function_start:
3733 case Builtin::BI__builtin_is_aligned:
3734 case Builtin::BI__builtin_align_up:
3735 case Builtin::BI__builtin_align_down:
3739 case Builtin::BI__builtin_add_overflow:
3740 case Builtin::BI__builtin_sub_overflow:
3741 case Builtin::BI__builtin_mul_overflow:
3745 case Builtin::BI__builtin_operator_new:
3746 case Builtin::BI__builtin_operator_delete: {
3747 bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
3749 BuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
3752 case Builtin::BI__builtin_dump_struct:
3754 case Builtin::BI__builtin_expect_with_probability: {
3759 const Expr *ProbArg = TheCall->
getArg(2);
3760 SmallVector<PartialDiagnosticAt, 8> Notes;
3761 Expr::EvalResult Eval;
3765 Diag(ProbArg->
getBeginLoc(), diag::err_probability_not_constant_float)
3772 bool LoseInfo =
false;
3773 Probability.convert(llvm::APFloat::IEEEdouble(),
3774 llvm::RoundingMode::Dynamic, &LoseInfo);
3775 if (!(Probability >= llvm::APFloat(0.0) &&
3776 Probability <= llvm::APFloat(1.0))) {
3783 case Builtin::BI__builtin_preserve_access_index:
3787 case Builtin::BI__builtin_call_with_static_chain:
3791 case Builtin::BI__exception_code:
3792 case Builtin::BI_exception_code:
3794 diag::err_seh___except_block))
3797 case Builtin::BI__exception_info:
3798 case Builtin::BI_exception_info:
3800 diag::err_seh___except_filter))
3803 case Builtin::BI__GetExceptionInfo:
3815 case Builtin::BIaddressof:
3816 case Builtin::BI__addressof:
3817 case Builtin::BIforward:
3818 case Builtin::BIforward_like:
3819 case Builtin::BImove:
3820 case Builtin::BImove_if_noexcept:
3821 case Builtin::BIas_const: {
3829 bool ReturnsPointer = BuiltinID == Builtin::BIaddressof ||
3830 BuiltinID == Builtin::BI__addressof;
3832 (ReturnsPointer ?
Result->isAnyPointerType()
3833 :
Result->isReferenceType()) &&
3836 Diag(TheCall->
getBeginLoc(), diag::err_builtin_move_forward_unsupported)
3842 case Builtin::BI__builtin_ptrauth_strip:
3844 case Builtin::BI__builtin_ptrauth_blend_discriminator:
3846 case Builtin::BI__builtin_ptrauth_sign_constant:
3849 case Builtin::BI__builtin_ptrauth_sign_unauthenticated:
3852 case Builtin::BI__builtin_ptrauth_auth:
3855 case Builtin::BI__builtin_ptrauth_sign_generic_data:
3857 case Builtin::BI__builtin_ptrauth_auth_and_resign:
3859 case Builtin::BI__builtin_ptrauth_auth_with_pc_and_resign:
3861 case Builtin::BI__builtin_ptrauth_auth_load_relative_and_sign:
3863 case Builtin::BI__builtin_ptrauth_string_discriminator:
3866 case Builtin::BI__builtin_get_vtable_pointer:
3870 case Builtin::BIread_pipe:
3871 case Builtin::BIwrite_pipe:
3874 if (
OpenCL().checkBuiltinRWPipe(TheCall))
3877 case Builtin::BIreserve_read_pipe:
3878 case Builtin::BIreserve_write_pipe:
3879 case Builtin::BIwork_group_reserve_read_pipe:
3880 case Builtin::BIwork_group_reserve_write_pipe:
3881 if (
OpenCL().checkBuiltinReserveRWPipe(TheCall))
3884 case Builtin::BIsub_group_reserve_read_pipe:
3885 case Builtin::BIsub_group_reserve_write_pipe:
3886 if (
OpenCL().checkSubgroupExt(TheCall) ||
3887 OpenCL().checkBuiltinReserveRWPipe(TheCall))
3890 case Builtin::BIcommit_read_pipe:
3891 case Builtin::BIcommit_write_pipe:
3892 case Builtin::BIwork_group_commit_read_pipe:
3893 case Builtin::BIwork_group_commit_write_pipe:
3894 if (
OpenCL().checkBuiltinCommitRWPipe(TheCall))
3897 case Builtin::BIsub_group_commit_read_pipe:
3898 case Builtin::BIsub_group_commit_write_pipe:
3899 if (
OpenCL().checkSubgroupExt(TheCall) ||
3900 OpenCL().checkBuiltinCommitRWPipe(TheCall))
3903 case Builtin::BIget_pipe_num_packets:
3904 case Builtin::BIget_pipe_max_packets:
3905 if (
OpenCL().checkBuiltinPipePackets(TheCall))
3908 case Builtin::BIto_global:
3909 case Builtin::BIto_local:
3910 case Builtin::BIto_private:
3911 if (
OpenCL().checkBuiltinToAddr(BuiltinID, TheCall))
3915 case Builtin::BIenqueue_kernel:
3916 if (
OpenCL().checkBuiltinEnqueueKernel(TheCall))
3919 case Builtin::BIget_kernel_work_group_size:
3920 case Builtin::BIget_kernel_preferred_work_group_size_multiple:
3921 if (
OpenCL().checkBuiltinKernelWorkGroupSize(TheCall))
3924 case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
3925 case Builtin::BIget_kernel_sub_group_count_for_ndrange:
3926 if (
OpenCL().checkBuiltinNDRangeAndBlock(TheCall))
3929 case Builtin::BI__builtin_os_log_format:
3930 Cleanup.setExprNeedsCleanups(
true);
3932 case Builtin::BI__builtin_os_log_format_buffer_size:
3933 if (BuiltinOSLogFormat(TheCall))
3936 case Builtin::BI__builtin_frame_address:
3937 case Builtin::BI__builtin_return_address: {
3946 Result.Val.getInt() != 0)
3948 << ((BuiltinID == Builtin::BI__builtin_return_address)
3949 ?
"__builtin_return_address"
3950 :
"__builtin_frame_address")
3955 case Builtin::BI__builtin_nondeterministic_value: {
3956 if (BuiltinNonDeterministicValue(TheCall))
3963 case Builtin::BI__builtin_elementwise_abs:
3971 case Builtin::BI__builtin_elementwise_acos:
3972 case Builtin::BI__builtin_elementwise_asin:
3973 case Builtin::BI__builtin_elementwise_atan:
3974 case Builtin::BI__builtin_elementwise_ceil:
3975 case Builtin::BI__builtin_elementwise_cos:
3976 case Builtin::BI__builtin_elementwise_cosh:
3977 case Builtin::BI__builtin_elementwise_exp:
3978 case Builtin::BI__builtin_elementwise_exp2:
3979 case Builtin::BI__builtin_elementwise_exp10:
3980 case Builtin::BI__builtin_elementwise_floor:
3981 case Builtin::BI__builtin_elementwise_log:
3982 case Builtin::BI__builtin_elementwise_log2:
3983 case Builtin::BI__builtin_elementwise_log10:
3984 case Builtin::BI__builtin_elementwise_roundeven:
3985 case Builtin::BI__builtin_elementwise_round:
3986 case Builtin::BI__builtin_elementwise_rint:
3987 case Builtin::BI__builtin_elementwise_nearbyint:
3988 case Builtin::BI__builtin_elementwise_sin:
3989 case Builtin::BI__builtin_elementwise_sinh:
3990 case Builtin::BI__builtin_elementwise_sqrt:
3991 case Builtin::BI__builtin_elementwise_tan:
3992 case Builtin::BI__builtin_elementwise_tanh:
3993 case Builtin::BI__builtin_elementwise_trunc:
3994 case Builtin::BI__builtin_elementwise_canonicalize:
3999 case Builtin::BI__builtin_elementwise_fma:
4004 case Builtin::BI__builtin_elementwise_ldexp: {
4026 const auto *Vec0 = TyA->
getAs<VectorType>();
4027 const auto *Vec1 = TyExp->
getAs<VectorType>();
4028 unsigned Arg0Length = Vec0 ? Vec0->getNumElements() : 0;
4030 if (Arg0Length != Arg1Length) {
4032 diag::err_typecheck_vector_lengths_not_equal)
4046 case Builtin::BI__builtin_elementwise_minnum:
4047 case Builtin::BI__builtin_elementwise_maxnum:
4048 case Builtin::BI__builtin_elementwise_minimum:
4049 case Builtin::BI__builtin_elementwise_maximum:
4050 case Builtin::BI__builtin_elementwise_minimumnum:
4051 case Builtin::BI__builtin_elementwise_maximumnum:
4052 case Builtin::BI__builtin_elementwise_atan2:
4053 case Builtin::BI__builtin_elementwise_fmod:
4054 case Builtin::BI__builtin_elementwise_pow:
4055 if (BuiltinElementwiseMath(TheCall,
4061 case Builtin::BI__builtin_elementwise_add_sat:
4062 case Builtin::BI__builtin_elementwise_sub_sat:
4063 case Builtin::BI__builtin_elementwise_clmul:
4064 case Builtin::BI__builtin_elementwise_pext:
4065 case Builtin::BI__builtin_elementwise_pdep:
4066 if (BuiltinElementwiseMath(TheCall,
4070 case Builtin::BI__builtin_elementwise_fshl:
4071 case Builtin::BI__builtin_elementwise_fshr:
4076 case Builtin::BI__builtin_elementwise_min:
4077 case Builtin::BI__builtin_elementwise_max: {
4078 if (BuiltinElementwiseMath(TheCall))
4080 Expr *Arg0 = TheCall->
getArg(0);
4081 Expr *Arg1 = TheCall->
getArg(1);
4082 QualType Ty0 = Arg0->
getType();
4083 QualType Ty1 = Arg1->
getType();
4084 const VectorType *VecTy0 = Ty0->
getAs<VectorType>();
4085 const VectorType *VecTy1 = Ty1->
getAs<VectorType>();
4088 (VecTy1 && VecTy1->getElementType()->isFloatingType()))
4089 Diag(TheCall->
getBeginLoc(), diag::warn_deprecated_builtin_no_suggestion)
4090 <<
Context.BuiltinInfo.getQuotedName(BuiltinID);
4093 case Builtin::BI__builtin_elementwise_popcount:
4094 case Builtin::BI__builtin_elementwise_bitreverse:
4099 case Builtin::BI__builtin_elementwise_copysign: {
4108 QualType MagnitudeTy = Magnitude.
get()->
getType();
4121 diag::err_typecheck_call_different_arg_types)
4122 << MagnitudeTy << SignTy;
4130 case Builtin::BI__builtin_elementwise_clzg:
4131 case Builtin::BI__builtin_elementwise_ctzg:
4139 }
else if (BuiltinElementwiseMath(
4143 case Builtin::BI__builtin_reduce_max:
4144 case Builtin::BI__builtin_reduce_min:
4145 case Builtin::BI__builtin_reduce_maximum:
4146 case Builtin::BI__builtin_reduce_minimum:
4149 case Builtin::BI__builtin_reduce_add:
4150 case Builtin::BI__builtin_reduce_mul:
4151 case Builtin::BI__builtin_reduce_xor:
4152 case Builtin::BI__builtin_reduce_or:
4153 case Builtin::BI__builtin_reduce_and: {
4154 if (PrepareBuiltinReduceMathOneArgCall(TheCall))
4157 const Expr *Arg = TheCall->
getArg(0);
4160 bool FloatOnly = BuiltinID == Builtin::BI__builtin_reduce_maximum ||
4161 BuiltinID == Builtin::BI__builtin_reduce_minimum;
4163 bool IntOnly = BuiltinID == Builtin::BI__builtin_reduce_add ||
4164 BuiltinID == Builtin::BI__builtin_reduce_mul ||
4165 BuiltinID == Builtin::BI__builtin_reduce_xor ||
4166 BuiltinID == Builtin::BI__builtin_reduce_or ||
4167 BuiltinID == Builtin::BI__builtin_reduce_and;
4176 }
else if (IntOnly) {
4183 }
else if (ElTy.
isNull()) {
4194 case Builtin::BI__builtin_reduce_assoc_fadd:
4195 case Builtin::BI__builtin_reduce_in_order_fadd: {
4197 bool InOrder = BuiltinID == Builtin::BI__builtin_reduce_in_order_fadd;
4222 diag::err_builtin_invalid_arg_type)
4234 case Builtin::BI__builtin_matrix_transpose:
4235 return BuiltinMatrixTranspose(TheCall, TheCallResult);
4237 case Builtin::BI__builtin_matrix_column_major_load:
4238 return BuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
4240 case Builtin::BI__builtin_matrix_column_major_store:
4241 return BuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
4243 case Builtin::BI__builtin_verbose_trap:
4248 case Builtin::BI__builtin_get_device_side_mangled_name: {
4249 auto Check = [](CallExpr *TheCall) {
4255 auto *D = DRE->getDecl();
4258 return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
4259 D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
4261 if (!Check(TheCall)) {
4263 diag::err_hip_invalid_args_builtin_mangled_name);
4268 case Builtin::BI__builtin_bswapg:
4272 case Builtin::BI__builtin_bitreverseg:
4276 case Builtin::BI__builtin_popcountg:
4280 case Builtin::BI__builtin_clzg:
4281 case Builtin::BI__builtin_ctzg:
4286 case Builtin::BI__builtin_stdc_rotate_left:
4287 case Builtin::BI__builtin_stdc_rotate_right:
4292 case Builtin::BI__builtin_stdc_memreverse8:
4293 case Builtin::BIstdc_memreverse8:
4294 case Builtin::BIstdc_memreverse8u8:
4295 case Builtin::BIstdc_memreverse8u16:
4296 case Builtin::BIstdc_memreverse8u32:
4297 case Builtin::BIstdc_memreverse8u64:
4298 case Builtin::BIstdc_load8_leu8:
4299 case Builtin::BIstdc_load8_leu16:
4300 case Builtin::BIstdc_load8_leu32:
4301 case Builtin::BIstdc_load8_leu64:
4302 case Builtin::BIstdc_load8_les8:
4303 case Builtin::BIstdc_load8_les16:
4304 case Builtin::BIstdc_load8_les32:
4305 case Builtin::BIstdc_load8_les64:
4306 case Builtin::BIstdc_load8_beu8:
4307 case Builtin::BIstdc_load8_beu16:
4308 case Builtin::BIstdc_load8_beu32:
4309 case Builtin::BIstdc_load8_beu64:
4310 case Builtin::BIstdc_load8_bes8:
4311 case Builtin::BIstdc_load8_bes16:
4312 case Builtin::BIstdc_load8_bes32:
4313 case Builtin::BIstdc_load8_bes64:
4314 case Builtin::BIstdc_load8_aligned_leu8:
4315 case Builtin::BIstdc_load8_aligned_leu16:
4316 case Builtin::BIstdc_load8_aligned_leu32:
4317 case Builtin::BIstdc_load8_aligned_leu64:
4318 case Builtin::BIstdc_load8_aligned_les8:
4319 case Builtin::BIstdc_load8_aligned_les16:
4320 case Builtin::BIstdc_load8_aligned_les32:
4321 case Builtin::BIstdc_load8_aligned_les64:
4322 case Builtin::BIstdc_load8_aligned_beu8:
4323 case Builtin::BIstdc_load8_aligned_beu16:
4324 case Builtin::BIstdc_load8_aligned_beu32:
4325 case Builtin::BIstdc_load8_aligned_beu64:
4326 case Builtin::BIstdc_load8_aligned_bes8:
4327 case Builtin::BIstdc_load8_aligned_bes16:
4328 case Builtin::BIstdc_load8_aligned_bes32:
4329 case Builtin::BIstdc_load8_aligned_bes64:
4330 if (
Context.getTargetInfo().getCharWidth() != 8) {
4337 case Builtin::BI__builtin_stdc_bit_floor:
4338 case Builtin::BI__builtin_stdc_bit_ceil:
4342 case Builtin::BI__builtin_stdc_has_single_bit:
4346 case Builtin::BI__builtin_stdc_leading_zeros:
4347 case Builtin::BI__builtin_stdc_leading_ones:
4348 case Builtin::BI__builtin_stdc_trailing_zeros:
4349 case Builtin::BI__builtin_stdc_trailing_ones:
4350 case Builtin::BI__builtin_stdc_first_leading_zero:
4351 case Builtin::BI__builtin_stdc_first_leading_one:
4352 case Builtin::BI__builtin_stdc_first_trailing_zero:
4353 case Builtin::BI__builtin_stdc_first_trailing_one:
4354 case Builtin::BI__builtin_stdc_count_zeros:
4355 case Builtin::BI__builtin_stdc_count_ones:
4356 case Builtin::BI__builtin_stdc_bit_width:
4361 case Builtin::BI__builtin_allow_runtime_check: {
4362 Expr *Arg = TheCall->
getArg(0);
4372 case Builtin::BI__builtin_allow_sanitize_check: {
4376 Expr *Arg = TheCall->
getArg(0);
4378 const StringLiteral *SanitizerName =
4380 if (!SanitizerName) {
4386 if (!llvm::StringSwitch<bool>(SanitizerName->
getString())
4387 .Cases({
"address",
"thread",
"memory",
"hwaddress",
4388 "kernel-address",
"kernel-memory",
"kernel-hwaddress"},
4392 << SanitizerName->
getString() <<
"__builtin_allow_sanitize_check"
4398 case Builtin::BI__builtin_counted_by_ref:
4399 if (BuiltinCountedByRef(TheCall))
4409 if (
Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
4410 if (
Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
4411 assert(
Context.getAuxTargetInfo() &&
4412 "Aux Target Builtin, but not an aux target?");
4419 diag::err_builtin_target_unsupported)
4422 if (CheckTSBuiltinFunctionCall(
4424 Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
4427 if (CheckTSBuiltinFunctionCall(
Context.getTargetInfo(), BuiltinID,
4433 return TheCallResult;
4448 if (
Result.isShiftedMask() || (~
Result).isShiftedMask())
4452 diag::err_argument_not_contiguous_bit_field)
4459 bool IsVariadic =
false;
4462 else if (
const auto *BD = dyn_cast<BlockDecl>(D))
4463 IsVariadic = BD->isVariadic();
4464 else if (
const auto *OMD = dyn_cast<ObjCMethodDecl>(D))
4465 IsVariadic = OMD->isVariadic();
4472 bool HasImplicitThisParam,
bool IsVariadic,
4476 else if (IsVariadic)
4486 if (HasImplicitThisParam) {
4518 UT->getDecl()->getMostRecentDecl()->hasAttr<TransparentUnionAttr>()) {
4519 if (
const auto *CLE = dyn_cast<CompoundLiteralExpr>(
Expr))
4520 if (
const auto *ILE = dyn_cast<InitListExpr>(CLE->getInitializer()))
4521 Expr = ILE->getInit(0);
4531 const Expr *ArgExpr,
4535 S.
PDiag(diag::warn_null_arg)
4541 if (
auto nullability =
type->getNullability())
4552 assert((FDecl || Proto) &&
"Need a function declaration or prototype");
4558 llvm::SmallBitVector NonNullArgs;
4564 for (
const auto *Arg : Args)
4571 unsigned IdxAST = Idx.getASTIndex();
4572 if (IdxAST >= Args.size())
4574 if (NonNullArgs.empty())
4575 NonNullArgs.resize(Args.size());
4576 NonNullArgs.set(IdxAST);
4585 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4590 unsigned ParamIndex = 0;
4592 I != E; ++I, ++ParamIndex) {
4595 if (NonNullArgs.empty())
4596 NonNullArgs.resize(Args.size());
4598 NonNullArgs.set(ParamIndex);
4605 if (
const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4610 type = blockType->getPointeeType();
4624 if (NonNullArgs.empty())
4625 NonNullArgs.resize(Args.size());
4627 NonNullArgs.set(Index);
4636 for (
unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4637 ArgIndex != ArgIndexEnd; ++ArgIndex) {
4638 if (NonNullArgs[ArgIndex])
4644 StringRef ParamName,
QualType ArgTy,
4667 CharUnits ParamAlign =
Context.getTypeAlignInChars(ParamTy);
4668 CharUnits ArgAlign =
Context.getTypeAlignInChars(ArgTy);
4672 if (ArgAlign < ParamAlign)
4673 Diag(Loc, diag::warn_param_mismatched_alignment)
4675 << ParamName << (FDecl !=
nullptr) << FDecl;
4679 const Expr *ThisArg,
4681 if (!FD || Args.empty())
4683 auto GetArgAt = [&](
int Idx) ->
const Expr * {
4684 if (Idx == LifetimeCaptureByAttr::Global ||
4685 Idx == LifetimeCaptureByAttr::Unknown)
4687 if (IsMemberFunction && Idx == 0)
4689 return Args[Idx - IsMemberFunction];
4691 auto HandleCaptureByAttr = [&](
const LifetimeCaptureByAttr *
Attr,
4696 Expr *Captured =
const_cast<Expr *
>(GetArgAt(ArgIdx));
4697 for (
int CapturingParamIdx :
Attr->params()) {
4698 if (CapturingParamIdx == LifetimeCaptureByAttr::Invalid)
4702 if (CapturingParamIdx == LifetimeCaptureByAttr::This &&
4705 Expr *Capturing =
const_cast<Expr *
>(GetArgAt(CapturingParamIdx));
4712 for (
const auto *A :
4714 HandleCaptureByAttr(A, I + IsMemberFunction);
4716 if (IsMemberFunction) {
4724 HandleCaptureByAttr(ATL.
getAttrAs<LifetimeCaptureByAttr>(), 0);
4734 llvm::any_of(Args, [](
const Expr *E) {
4735 return E && E->isInstantiationDependent();
4740 llvm::SmallBitVector CheckedVarArgs;
4742 for (
const auto *I : FDecl->
specific_attrs<FormatMatchesAttr>()) {
4744 CheckedVarArgs.resize(Args.size());
4745 CheckFormatString(I, Args, IsMemberFunction, CallType, Loc, Range,
4750 CheckedVarArgs.resize(Args.size());
4751 CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4758 auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4762 : isa_and_nonnull<FunctionDecl>(FDecl)
4764 : isa_and_nonnull<ObjCMethodDecl>(FDecl)
4768 for (
unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4770 if (
const Expr *Arg = Args[ArgIdx]) {
4771 if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4778 if (FDecl || Proto) {
4783 for (
const auto *I : FDecl->
specific_attrs<ArgumentWithTypeTagAttr>())
4784 CheckArgumentWithTypeTag(I, Args, Loc);
4790 if (!Proto && FDecl) {
4792 if (isa_and_nonnull<FunctionProtoType>(FT))
4798 const auto N = std::min<unsigned>(Proto->
getNumParams(), Args.size());
4800 bool IsScalableArg =
false;
4801 for (
unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4803 if (
const Expr *Arg = Args[ArgIdx]) {
4807 if (
Context.getTargetInfo().getTriple().isOSAIX() && FDecl && Arg &&
4815 IsScalableArg =
true;
4817 CheckArgAlignment(Arg->
getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4826 if (
auto *CallerFD = dyn_cast<FunctionDecl>(
CurContext)) {
4827 llvm::StringMap<bool> CallerFeatureMap;
4828 Context.getFunctionFeatureMap(CallerFeatureMap, CallerFD);
4829 if (!CallerFeatureMap.contains(
"sme"))
4830 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4831 }
else if (!
Context.getTargetInfo().hasFeature(
"sme")) {
4832 Diag(Loc, diag::err_sme_call_in_non_sme_target);
4841 const auto *CallerFD = dyn_cast<FunctionDecl>(
CurContext);
4843 (IsScalableArg || IsScalableRet)) {
4844 bool IsCalleeStreaming =
4846 bool IsCalleeStreamingCompatible =
4850 if (!IsCalleeStreamingCompatible &&
4854 unsigned VL = LO.VScaleMin * 128;
4855 unsigned SVL = LO.VScaleStreamingMin * 128;
4856 bool IsVLMismatch = VL && SVL && VL != SVL;
4858 auto EmitDiag = [&](
bool IsArg) {
4862 Diag(Loc, diag::warn_sme_streaming_compatible_vl_mismatch)
4863 << IsArg << IsCalleeStreaming << SVL << VL;
4866 Diag(Loc, diag::err_sme_streaming_transition_vl_mismatch)
4867 << IsArg << SVL << VL;
4869 Diag(Loc, diag::warn_sme_streaming_pass_return_vl_to_non_streaming)
4886 bool CallerHasZAState =
false;
4887 bool CallerHasZT0State =
false;
4889 auto *
Attr = CallerFD->getAttr<ArmNewAttr>();
4891 CallerHasZAState =
true;
4893 CallerHasZT0State =
true;
4897 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4899 CallerHasZT0State |=
4901 FPT->getExtProtoInfo().AArch64SMEAttributes) !=
4907 Diag(Loc, diag::err_sme_za_call_no_za_state);
4910 Diag(Loc, diag::err_sme_zt0_call_no_zt0_state);
4914 Diag(Loc, diag::err_sme_unimplemented_za_save_restore);
4915 Diag(Loc, diag::note_sme_use_preserves_za);
4920 if (FDecl && FDecl->
hasAttr<AllocAlignAttr>()) {
4921 auto *AA = FDecl->
getAttr<AllocAlignAttr>();
4922 const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4923 if (!Arg->isValueDependent()) {
4925 if (Arg->EvaluateAsInt(Align,
Context)) {
4926 const llvm::APSInt &I = Align.
Val.
getInt();
4927 if (!I.isPowerOf2())
4928 Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4929 << Arg->getSourceRange();
4932 Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4941 << diag::OffloadLang::SYCL;
4947 if (
Context.getTargetInfo().checkCallingConvention(CC) !=
4960 AutoT->getTypeConstraintConcept().getAsTemplateDecl()) {
4975 Loc, FDecl,
"'this'", Context.getPointerType(ThisType),
4976 Context.getPointerType(Ctor->getFunctionObjectParameterType()));
4978 checkCall(FDecl, Proto,
nullptr, Args,
true,
4987 IsMemberOperatorCall;
4993 Expr *ImplicitThis =
nullptr;
4998 ImplicitThis = Args[0];
5001 }
else if (IsMemberFunction && !FDecl->
isStatic() &&
5012 ThisType =
Context.getPointerType(ThisType);
5018 CheckArgAlignment(TheCall->
getRParenLoc(), FDecl,
"'this'", ThisType,
5036 CheckAbsoluteValueFunction(TheCall, FDecl);
5037 CheckMaxUnsignedZero(TheCall, FDecl);
5038 CheckInfNaNFunction(TheCall, FDecl);
5049 case Builtin::BIstrlcpy:
5050 case Builtin::BIstrlcat:
5051 CheckStrlcpycatArguments(TheCall, FnInfo);
5053 case Builtin::BIstrncat:
5054 CheckStrncatArguments(TheCall, FnInfo);
5056 case Builtin::BIfree:
5057 CheckFreeArguments(TheCall);
5060 CheckMemaccessArguments(TheCall, CMId, FnInfo);
5069 if (
const auto *
V = dyn_cast<VarDecl>(NDecl))
5070 Ty =
V->getType().getNonReferenceType();
5071 else if (
const auto *F = dyn_cast<FieldDecl>(NDecl))
5072 Ty = F->getType().getNonReferenceType();
5109 if (!llvm::isValidAtomicOrderingCABI(Ordering))
5112 auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5114 case AtomicExpr::AO__c11_atomic_init:
5115 case AtomicExpr::AO__opencl_atomic_init:
5116 llvm_unreachable(
"There is no ordering argument for an init");
5118 case AtomicExpr::AO__c11_atomic_load:
5119 case AtomicExpr::AO__opencl_atomic_load:
5120 case AtomicExpr::AO__hip_atomic_load:
5121 case AtomicExpr::AO__atomic_load_n:
5122 case AtomicExpr::AO__atomic_load:
5123 case AtomicExpr::AO__scoped_atomic_load_n:
5124 case AtomicExpr::AO__scoped_atomic_load:
5125 return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5126 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5128 case AtomicExpr::AO__c11_atomic_store:
5129 case AtomicExpr::AO__opencl_atomic_store:
5130 case AtomicExpr::AO__hip_atomic_store:
5131 case AtomicExpr::AO__atomic_store:
5132 case AtomicExpr::AO__atomic_store_n:
5133 case AtomicExpr::AO__scoped_atomic_store:
5134 case AtomicExpr::AO__scoped_atomic_store_n:
5135 case AtomicExpr::AO__atomic_clear:
5136 return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5137 OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5138 OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5168#define HIP_ATOMIC_FIXABLE(hip, scoped) \
5169 case AtomicExpr::AO__hip_atomic_##hip: \
5170 OldName = "__hip_atomic_" #hip; \
5171 NewName = "__scoped_atomic_" #scoped; \
5184#undef HIP_ATOMIC_FIXABLE
5185 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5186 OldName =
"__hip_atomic_compare_exchange_weak";
5187 NewName =
"__scoped_atomic_compare_exchange";
5190 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5191 OldName =
"__hip_atomic_compare_exchange_strong";
5192 NewName =
"__scoped_atomic_compare_exchange";
5196 llvm_unreachable(
"unhandled HIP atomic op");
5199 auto DB = S.
Diag(ExprRange.
getBegin(), diag::warn_hip_deprecated_builtin)
5200 << OldName << NewName;
5207 std::optional<llvm::APSInt> ScopeVal =
5212 StringRef ScopeName;
5213 switch (ScopeVal->getZExtValue()) {
5215 ScopeName =
"__MEMORY_SCOPE_SINGLE";
5218 ScopeName =
"__MEMORY_SCOPE_WVFRNT";
5221 ScopeName =
"__MEMORY_SCOPE_WRKGRP";
5224 ScopeName =
"__MEMORY_SCOPE_DEVICE";
5227 ScopeName =
"__MEMORY_SCOPE_SYSTEM";
5230 ScopeName =
"__MEMORY_SCOPE_CLUSTR";
5282 const unsigned NumForm = ClearByte + 1;
5283 const unsigned NumArgs[] = {2, 2, 3, 3, 3, 3, 4, 5, 6, 2, 2};
5284 const unsigned NumVals[] = {1, 0, 1, 1, 1, 1, 2, 2, 3, 0, 0};
5292 static_assert(
sizeof(NumArgs)/
sizeof(NumArgs[0]) == NumForm
5293 &&
sizeof(NumVals)/
sizeof(NumVals[0]) == NumForm,
5294 "need to update code for modified forms");
5295 static_assert(AtomicExpr::AO__atomic_add_fetch == 0 &&
5296 AtomicExpr::AO__atomic_xor_fetch + 1 ==
5297 AtomicExpr::AO__c11_atomic_compare_exchange_strong,
5298 "need to update code for modified C11 atomics");
5299 bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_compare_exchange_strong &&
5300 Op <= AtomicExpr::AO__opencl_atomic_store;
5301 bool IsHIP = Op >= AtomicExpr::AO__hip_atomic_compare_exchange_strong &&
5302 Op <= AtomicExpr::AO__hip_atomic_store;
5303 bool IsScoped = Op >= AtomicExpr::AO__scoped_atomic_add_fetch &&
5304 Op <= AtomicExpr::AO__scoped_atomic_xor_fetch;
5305 bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_compare_exchange_strong &&
5306 Op <= AtomicExpr::AO__c11_atomic_store) ||
5308 bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5309 Op == AtomicExpr::AO__atomic_store_n ||
5310 Op == AtomicExpr::AO__atomic_exchange_n ||
5311 Op == AtomicExpr::AO__atomic_compare_exchange_n ||
5312 Op == AtomicExpr::AO__scoped_atomic_load_n ||
5313 Op == AtomicExpr::AO__scoped_atomic_store_n ||
5314 Op == AtomicExpr::AO__scoped_atomic_exchange_n ||
5315 Op == AtomicExpr::AO__scoped_atomic_compare_exchange_n;
5319 enum ArithOpExtraValueType {
5325 unsigned ArithAllows = AOEVT_None;
5328 case AtomicExpr::AO__c11_atomic_init:
5329 case AtomicExpr::AO__opencl_atomic_init:
5333 case AtomicExpr::AO__c11_atomic_load:
5334 case AtomicExpr::AO__opencl_atomic_load:
5335 case AtomicExpr::AO__hip_atomic_load:
5336 case AtomicExpr::AO__atomic_load_n:
5337 case AtomicExpr::AO__scoped_atomic_load_n:
5338 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5342 case AtomicExpr::AO__atomic_load:
5343 case AtomicExpr::AO__scoped_atomic_load:
5344 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5348 case AtomicExpr::AO__c11_atomic_store:
5349 case AtomicExpr::AO__opencl_atomic_store:
5350 case AtomicExpr::AO__hip_atomic_store:
5351 case AtomicExpr::AO__atomic_store:
5352 case AtomicExpr::AO__atomic_store_n:
5353 case AtomicExpr::AO__scoped_atomic_store:
5354 case AtomicExpr::AO__scoped_atomic_store_n:
5355 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5358 case AtomicExpr::AO__atomic_fetch_add:
5359 case AtomicExpr::AO__atomic_fetch_sub:
5360 case AtomicExpr::AO__atomic_add_fetch:
5361 case AtomicExpr::AO__atomic_sub_fetch:
5362 case AtomicExpr::AO__scoped_atomic_fetch_add:
5363 case AtomicExpr::AO__scoped_atomic_fetch_sub:
5364 case AtomicExpr::AO__scoped_atomic_add_fetch:
5365 case AtomicExpr::AO__scoped_atomic_sub_fetch:
5366 case AtomicExpr::AO__c11_atomic_fetch_add:
5367 case AtomicExpr::AO__c11_atomic_fetch_sub:
5368 case AtomicExpr::AO__opencl_atomic_fetch_add:
5369 case AtomicExpr::AO__opencl_atomic_fetch_sub:
5370 case AtomicExpr::AO__hip_atomic_fetch_add:
5371 case AtomicExpr::AO__hip_atomic_fetch_sub:
5372 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5375 case AtomicExpr::AO__atomic_fetch_fminimum:
5376 case AtomicExpr::AO__atomic_fetch_fmaximum:
5377 case AtomicExpr::AO__atomic_fetch_fminimum_num:
5378 case AtomicExpr::AO__atomic_fetch_fmaximum_num:
5379 case AtomicExpr::AO__scoped_atomic_fetch_fminimum:
5380 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum:
5381 case AtomicExpr::AO__scoped_atomic_fetch_fminimum_num:
5382 case AtomicExpr::AO__scoped_atomic_fetch_fmaximum_num:
5383 ArithAllows = AOEVT_FP;
5386 case AtomicExpr::AO__atomic_fetch_max:
5387 case AtomicExpr::AO__atomic_fetch_min:
5388 case AtomicExpr::AO__atomic_max_fetch:
5389 case AtomicExpr::AO__atomic_min_fetch:
5390 case AtomicExpr::AO__scoped_atomic_fetch_max:
5391 case AtomicExpr::AO__scoped_atomic_fetch_min:
5392 case AtomicExpr::AO__scoped_atomic_max_fetch:
5393 case AtomicExpr::AO__scoped_atomic_min_fetch:
5394 case AtomicExpr::AO__c11_atomic_fetch_max:
5395 case AtomicExpr::AO__c11_atomic_fetch_min:
5396 case AtomicExpr::AO__opencl_atomic_fetch_max:
5397 case AtomicExpr::AO__opencl_atomic_fetch_min:
5398 case AtomicExpr::AO__hip_atomic_fetch_max:
5399 case AtomicExpr::AO__hip_atomic_fetch_min:
5400 ArithAllows = AOEVT_Int | AOEVT_FP;
5403 case AtomicExpr::AO__c11_atomic_fetch_and:
5404 case AtomicExpr::AO__c11_atomic_fetch_or:
5405 case AtomicExpr::AO__c11_atomic_fetch_xor:
5406 case AtomicExpr::AO__hip_atomic_fetch_and:
5407 case AtomicExpr::AO__hip_atomic_fetch_or:
5408 case AtomicExpr::AO__hip_atomic_fetch_xor:
5409 case AtomicExpr::AO__c11_atomic_fetch_nand:
5410 case AtomicExpr::AO__opencl_atomic_fetch_and:
5411 case AtomicExpr::AO__opencl_atomic_fetch_or:
5412 case AtomicExpr::AO__opencl_atomic_fetch_xor:
5413 case AtomicExpr::AO__atomic_fetch_and:
5414 case AtomicExpr::AO__atomic_fetch_or:
5415 case AtomicExpr::AO__atomic_fetch_xor:
5416 case AtomicExpr::AO__atomic_fetch_nand:
5417 case AtomicExpr::AO__atomic_and_fetch:
5418 case AtomicExpr::AO__atomic_or_fetch:
5419 case AtomicExpr::AO__atomic_xor_fetch:
5420 case AtomicExpr::AO__atomic_nand_fetch:
5421 case AtomicExpr::AO__atomic_fetch_uinc:
5422 case AtomicExpr::AO__atomic_fetch_udec:
5423 case AtomicExpr::AO__scoped_atomic_fetch_and:
5424 case AtomicExpr::AO__scoped_atomic_fetch_or:
5425 case AtomicExpr::AO__scoped_atomic_fetch_xor:
5426 case AtomicExpr::AO__scoped_atomic_fetch_nand:
5427 case AtomicExpr::AO__scoped_atomic_and_fetch:
5428 case AtomicExpr::AO__scoped_atomic_or_fetch:
5429 case AtomicExpr::AO__scoped_atomic_xor_fetch:
5430 case AtomicExpr::AO__scoped_atomic_nand_fetch:
5431 case AtomicExpr::AO__scoped_atomic_fetch_uinc:
5432 case AtomicExpr::AO__scoped_atomic_fetch_udec:
5436 case AtomicExpr::AO__c11_atomic_exchange:
5437 case AtomicExpr::AO__hip_atomic_exchange:
5438 case AtomicExpr::AO__opencl_atomic_exchange:
5439 case AtomicExpr::AO__atomic_exchange_n:
5440 case AtomicExpr::AO__scoped_atomic_exchange_n:
5441 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5445 case AtomicExpr::AO__atomic_exchange:
5446 case AtomicExpr::AO__scoped_atomic_exchange:
5447 ArithAllows = AOEVT_Pointer | AOEVT_FP;
5451 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5452 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5453 case AtomicExpr::AO__hip_atomic_compare_exchange_strong:
5454 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5455 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5456 case AtomicExpr::AO__hip_atomic_compare_exchange_weak:
5460 case AtomicExpr::AO__atomic_compare_exchange:
5461 case AtomicExpr::AO__atomic_compare_exchange_n:
5462 case AtomicExpr::AO__scoped_atomic_compare_exchange:
5463 case AtomicExpr::AO__scoped_atomic_compare_exchange_n:
5464 ArithAllows = AOEVT_Pointer;
5468 case AtomicExpr::AO__atomic_test_and_set:
5469 Form = TestAndSetByte;
5472 case AtomicExpr::AO__atomic_clear:
5477 unsigned AdjustedNumArgs = NumArgs[Form];
5478 if ((IsOpenCL || IsHIP || IsScoped) &&
5479 Op != AtomicExpr::AO__opencl_atomic_init)
5482 if (Args.size() < AdjustedNumArgs) {
5483 Diag(CallRange.
getEnd(), diag::err_typecheck_call_too_few_args)
5484 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5487 }
else if (Args.size() > AdjustedNumArgs) {
5488 Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5489 diag::err_typecheck_call_too_many_args)
5490 << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5496 Expr *Ptr = Args[0];
5501 Ptr = ConvertedPtr.
get();
5504 Diag(ExprRange.
getBegin(), diag::err_atomic_builtin_must_be_pointer)
5505 << Ptr->getType() << 0 << Ptr->getSourceRange();
5514 Diag(ExprRange.
getBegin(), diag::err_atomic_op_needs_atomic)
5515 << Ptr->getType() << Ptr->getSourceRange();
5520 Diag(ExprRange.
getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5522 << Ptr->getSourceRange();
5526 }
else if (Form != Load && Form != LoadCopy) {
5528 Diag(ExprRange.
getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5529 << Ptr->getType() << Ptr->getSourceRange();
5534 if (Form != TestAndSetByte && Form != ClearByte) {
5537 diag::err_incomplete_type))
5540 if (
Context.getTypeInfoInChars(AtomTy).Width.isZero()) {
5541 Diag(ExprRange.
getBegin(), diag::err_atomic_builtin_must_be_pointer)
5542 << Ptr->getType() << 1 << Ptr->getSourceRange();
5551 pointerType->getPointeeType().getCVRQualifiers());
5561 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5562 << 0 << Ptr->getType() << Ptr->getSourceRange();
5571 auto IsAllowedValueType = [&](
QualType ValType,
5572 unsigned AllowedType) ->
bool {
5573 bool IsX87LongDouble =
5575 &
Context.getTargetInfo().getLongDoubleFormat() ==
5576 &llvm::APFloat::x87DoubleExtended();
5580 return (AllowedType & AOEVT_Int) || AllowedType != AOEVT_FP;
5582 return AllowedType & AOEVT_Pointer;
5586 if (IsX87LongDouble)
5590 if (!IsAllowedValueType(ValType, ArithAllows)) {
5592 ArithAllows == AOEVT_FP
5593 ? diag::err_atomic_op_needs_atomic_fp
5594 : (ArithAllows & AOEVT_FP
5595 ? (ArithAllows & AOEVT_Pointer
5596 ? diag::err_atomic_op_needs_atomic_int_ptr_or_fp
5597 : diag::err_atomic_op_needs_atomic_int_or_fp)
5598 : (ArithAllows & AOEVT_Pointer
5599 ? diag::err_atomic_op_needs_atomic_int_or_ptr
5600 : diag::err_atomic_op_needs_atomic_int));
5602 << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5607 diag::err_incomplete_type)) {
5618 Diag(ExprRange.
getBegin(), diag::err_atomic_op_needs_trivial_copy)
5619 << Ptr->getType() << Ptr->getSourceRange();
5634 Diag(ExprRange.
getBegin(), diag::err_arc_atomic_ownership)
5635 << ValType << Ptr->getSourceRange();
5646 if (Form ==
Copy || Form == LoadCopy || Form == GNUXchg || Form ==
Init ||
5649 else if (Form == C11CmpXchg || Form == GNUCmpXchg || Form == TestAndSetByte)
5655 bool IsPassedByAddress =
false;
5656 if (!IsC11 && !IsHIP && !IsN) {
5657 ByValType = Ptr->getType();
5658 IsPassedByAddress =
true;
5663 APIOrderedArgs.push_back(Args[0]);
5667 APIOrderedArgs.push_back(Args[1]);
5673 APIOrderedArgs.push_back(Args[2]);
5674 APIOrderedArgs.push_back(Args[1]);
5677 APIOrderedArgs.push_back(Args[2]);
5678 APIOrderedArgs.push_back(Args[3]);
5679 APIOrderedArgs.push_back(Args[1]);
5682 APIOrderedArgs.push_back(Args[2]);
5683 APIOrderedArgs.push_back(Args[4]);
5684 APIOrderedArgs.push_back(Args[1]);
5685 APIOrderedArgs.push_back(Args[3]);
5688 APIOrderedArgs.push_back(Args[2]);
5689 APIOrderedArgs.push_back(Args[4]);
5690 APIOrderedArgs.push_back(Args[5]);
5691 APIOrderedArgs.push_back(Args[1]);
5692 APIOrderedArgs.push_back(Args[3]);
5694 case TestAndSetByte:
5696 APIOrderedArgs.push_back(Args[1]);
5700 APIOrderedArgs.append(Args.begin(), Args.end());
5707 for (
unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5709 if (i < NumVals[Form] + 1) {
5722 assert(Form != Load);
5724 Ty =
Context.getPointerDiffType();
5727 else if (Form ==
Copy || Form == Xchg) {
5728 if (IsPassedByAddress) {
5735 Expr *ValArg = APIOrderedArgs[i];
5742 AS = PtrTy->getPointeeType().getAddressSpace();
5751 if (IsPassedByAddress)
5771 APIOrderedArgs[i] = Arg.
get();
5776 SubExprs.push_back(Ptr);
5780 SubExprs.push_back(APIOrderedArgs[1]);
5783 case TestAndSetByte:
5785 SubExprs.push_back(APIOrderedArgs[1]);
5791 SubExprs.push_back(APIOrderedArgs[2]);
5792 SubExprs.push_back(APIOrderedArgs[1]);
5796 SubExprs.push_back(APIOrderedArgs[3]);
5797 SubExprs.push_back(APIOrderedArgs[1]);
5798 SubExprs.push_back(APIOrderedArgs[2]);
5801 SubExprs.push_back(APIOrderedArgs[3]);
5802 SubExprs.push_back(APIOrderedArgs[1]);
5803 SubExprs.push_back(APIOrderedArgs[4]);
5804 SubExprs.push_back(APIOrderedArgs[2]);
5807 SubExprs.push_back(APIOrderedArgs[4]);
5808 SubExprs.push_back(APIOrderedArgs[1]);
5809 SubExprs.push_back(APIOrderedArgs[5]);
5810 SubExprs.push_back(APIOrderedArgs[2]);
5811 SubExprs.push_back(APIOrderedArgs[3]);
5816 if (SubExprs.size() >= 2 && Form !=
Init) {
5817 std::optional<llvm::APSInt>
Success =
5818 SubExprs[1]->getIntegerConstantExpr(
Context);
5820 Diag(SubExprs[1]->getBeginLoc(),
5821 diag::warn_atomic_op_has_invalid_memory_order)
5822 << (Form == C11CmpXchg || Form == GNUCmpXchg)
5823 << SubExprs[1]->getSourceRange();
5825 if (SubExprs.size() >= 5) {
5826 if (std::optional<llvm::APSInt>
Failure =
5827 SubExprs[3]->getIntegerConstantExpr(
Context)) {
5828 if (!llvm::is_contained(
5829 {llvm::AtomicOrderingCABI::relaxed,
5830 llvm::AtomicOrderingCABI::consume,
5831 llvm::AtomicOrderingCABI::acquire,
5832 llvm::AtomicOrderingCABI::seq_cst},
5833 (llvm::AtomicOrderingCABI)
Failure->getSExtValue())) {
5834 Diag(SubExprs[3]->getBeginLoc(),
5835 diag::warn_atomic_op_has_invalid_memory_order)
5836 << 2 << SubExprs[3]->getSourceRange();
5843 auto *
Scope = Args[Args.size() - 1];
5844 if (std::optional<llvm::APSInt>
Result =
5846 if (!ScopeModel->isValid(
Result->getZExtValue()))
5847 Diag(
Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_sync_scope)
5848 <<
Scope->getSourceRange();
5850 SubExprs.push_back(
Scope);
5859 if ((Op == AtomicExpr::AO__c11_atomic_load ||
5860 Op == AtomicExpr::AO__c11_atomic_store ||
5861 Op == AtomicExpr::AO__opencl_atomic_load ||
5862 Op == AtomicExpr::AO__hip_atomic_load ||
5863 Op == AtomicExpr::AO__opencl_atomic_store ||
5864 Op == AtomicExpr::AO__hip_atomic_store) &&
5865 Context.AtomicUsesUnsupportedLibcall(AE))
5867 << ((Op == AtomicExpr::AO__c11_atomic_load ||
5868 Op == AtomicExpr::AO__opencl_atomic_load ||
5869 Op == AtomicExpr::AO__hip_atomic_load)
5874 Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_bit_int_prohibit);
5890 assert(Fn &&
"builtin call without direct callee!");
5906 CallExpr *TheCall =
static_cast<CallExpr *
>(TheCallResult.
get());
5913 Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5915 <<
Callee->getSourceRange();
5924 Expr *FirstArg = TheCall->
getArg(0);
5928 FirstArg = FirstArgResult.
get();
5929 TheCall->
setArg(0, FirstArg);
5941 Diag(DRE->
getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5948 diag::err_atomic_op_needs_non_address_discriminated_pointer)
5979 QualType ResultType = ValType;
5984#define BUILTIN_ROW(x) \
5985 { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5986 Builtin::BI##x##_8, Builtin::BI##x##_16 }
5988 static const unsigned BuiltinIndices[][5] = {
6013 switch (
Context.getTypeSizeInChars(ValType).getQuantity()) {
6014 case 1: SizeIndex = 0;
break;
6015 case 2: SizeIndex = 1;
break;
6016 case 4: SizeIndex = 2;
break;
6017 case 8: SizeIndex = 3;
break;
6018 case 16: SizeIndex = 4;
break;
6030 unsigned BuiltinIndex, NumFixed = 1;
6031 bool WarnAboutSemanticsChange =
false;
6032 switch (BuiltinID) {
6033 default: llvm_unreachable(
"Unknown overloaded atomic builtin!");
6034 case Builtin::BI__sync_fetch_and_add:
6035 case Builtin::BI__sync_fetch_and_add_1:
6036 case Builtin::BI__sync_fetch_and_add_2:
6037 case Builtin::BI__sync_fetch_and_add_4:
6038 case Builtin::BI__sync_fetch_and_add_8:
6039 case Builtin::BI__sync_fetch_and_add_16:
6043 case Builtin::BI__sync_fetch_and_sub:
6044 case Builtin::BI__sync_fetch_and_sub_1:
6045 case Builtin::BI__sync_fetch_and_sub_2:
6046 case Builtin::BI__sync_fetch_and_sub_4:
6047 case Builtin::BI__sync_fetch_and_sub_8:
6048 case Builtin::BI__sync_fetch_and_sub_16:
6052 case Builtin::BI__sync_fetch_and_or:
6053 case Builtin::BI__sync_fetch_and_or_1:
6054 case Builtin::BI__sync_fetch_and_or_2:
6055 case Builtin::BI__sync_fetch_and_or_4:
6056 case Builtin::BI__sync_fetch_and_or_8:
6057 case Builtin::BI__sync_fetch_and_or_16:
6061 case Builtin::BI__sync_fetch_and_and:
6062 case Builtin::BI__sync_fetch_and_and_1:
6063 case Builtin::BI__sync_fetch_and_and_2:
6064 case Builtin::BI__sync_fetch_and_and_4:
6065 case Builtin::BI__sync_fetch_and_and_8:
6066 case Builtin::BI__sync_fetch_and_and_16:
6070 case Builtin::BI__sync_fetch_and_xor:
6071 case Builtin::BI__sync_fetch_and_xor_1:
6072 case Builtin::BI__sync_fetch_and_xor_2:
6073 case Builtin::BI__sync_fetch_and_xor_4:
6074 case Builtin::BI__sync_fetch_and_xor_8:
6075 case Builtin::BI__sync_fetch_and_xor_16:
6079 case Builtin::BI__sync_fetch_and_nand:
6080 case Builtin::BI__sync_fetch_and_nand_1:
6081 case Builtin::BI__sync_fetch_and_nand_2:
6082 case Builtin::BI__sync_fetch_and_nand_4:
6083 case Builtin::BI__sync_fetch_and_nand_8:
6084 case Builtin::BI__sync_fetch_and_nand_16:
6086 WarnAboutSemanticsChange =
true;
6089 case Builtin::BI__sync_add_and_fetch:
6090 case Builtin::BI__sync_add_and_fetch_1:
6091 case Builtin::BI__sync_add_and_fetch_2:
6092 case Builtin::BI__sync_add_and_fetch_4:
6093 case Builtin::BI__sync_add_and_fetch_8:
6094 case Builtin::BI__sync_add_and_fetch_16:
6098 case Builtin::BI__sync_sub_and_fetch:
6099 case Builtin::BI__sync_sub_and_fetch_1:
6100 case Builtin::BI__sync_sub_and_fetch_2:
6101 case Builtin::BI__sync_sub_and_fetch_4:
6102 case Builtin::BI__sync_sub_and_fetch_8:
6103 case Builtin::BI__sync_sub_and_fetch_16:
6107 case Builtin::BI__sync_and_and_fetch:
6108 case Builtin::BI__sync_and_and_fetch_1:
6109 case Builtin::BI__sync_and_and_fetch_2:
6110 case Builtin::BI__sync_and_and_fetch_4:
6111 case Builtin::BI__sync_and_and_fetch_8:
6112 case Builtin::BI__sync_and_and_fetch_16:
6116 case Builtin::BI__sync_or_and_fetch:
6117 case Builtin::BI__sync_or_and_fetch_1:
6118 case Builtin::BI__sync_or_and_fetch_2:
6119 case Builtin::BI__sync_or_and_fetch_4:
6120 case Builtin::BI__sync_or_and_fetch_8:
6121 case Builtin::BI__sync_or_and_fetch_16:
6125 case Builtin::BI__sync_xor_and_fetch:
6126 case Builtin::BI__sync_xor_and_fetch_1:
6127 case Builtin::BI__sync_xor_and_fetch_2:
6128 case Builtin::BI__sync_xor_and_fetch_4:
6129 case Builtin::BI__sync_xor_and_fetch_8:
6130 case Builtin::BI__sync_xor_and_fetch_16:
6134 case Builtin::BI__sync_nand_and_fetch:
6135 case Builtin::BI__sync_nand_and_fetch_1:
6136 case Builtin::BI__sync_nand_and_fetch_2:
6137 case Builtin::BI__sync_nand_and_fetch_4:
6138 case Builtin::BI__sync_nand_and_fetch_8:
6139 case Builtin::BI__sync_nand_and_fetch_16:
6141 WarnAboutSemanticsChange =
true;
6144 case Builtin::BI__sync_val_compare_and_swap:
6145 case Builtin::BI__sync_val_compare_and_swap_1:
6146 case Builtin::BI__sync_val_compare_and_swap_2:
6147 case Builtin::BI__sync_val_compare_and_swap_4:
6148 case Builtin::BI__sync_val_compare_and_swap_8:
6149 case Builtin::BI__sync_val_compare_and_swap_16:
6154 case Builtin::BI__sync_bool_compare_and_swap:
6155 case Builtin::BI__sync_bool_compare_and_swap_1:
6156 case Builtin::BI__sync_bool_compare_and_swap_2:
6157 case Builtin::BI__sync_bool_compare_and_swap_4:
6158 case Builtin::BI__sync_bool_compare_and_swap_8:
6159 case Builtin::BI__sync_bool_compare_and_swap_16:
6165 case Builtin::BI__sync_lock_test_and_set:
6166 case Builtin::BI__sync_lock_test_and_set_1:
6167 case Builtin::BI__sync_lock_test_and_set_2:
6168 case Builtin::BI__sync_lock_test_and_set_4:
6169 case Builtin::BI__sync_lock_test_and_set_8:
6170 case Builtin::BI__sync_lock_test_and_set_16:
6174 case Builtin::BI__sync_lock_release:
6175 case Builtin::BI__sync_lock_release_1:
6176 case Builtin::BI__sync_lock_release_2:
6177 case Builtin::BI__sync_lock_release_4:
6178 case Builtin::BI__sync_lock_release_8:
6179 case Builtin::BI__sync_lock_release_16:
6185 case Builtin::BI__sync_swap:
6186 case Builtin::BI__sync_swap_1:
6187 case Builtin::BI__sync_swap_2:
6188 case Builtin::BI__sync_swap_4:
6189 case Builtin::BI__sync_swap_8:
6190 case Builtin::BI__sync_swap_16:
6198 Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6199 << 0 << 1 + NumFixed << TheCall->
getNumArgs() << 0
6200 <<
Callee->getSourceRange();
6204 Diag(TheCall->
getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6205 <<
Callee->getSourceRange();
6207 if (WarnAboutSemanticsChange) {
6208 Diag(TheCall->
getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6209 <<
Callee->getSourceRange();
6214 unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6215 std::string NewBuiltinName =
Context.BuiltinInfo.getName(NewBuiltinID);
6216 FunctionDecl *NewBuiltinDecl;
6217 if (NewBuiltinID == BuiltinID)
6218 NewBuiltinDecl = FDecl;
6221 DeclarationName DN(&
Context.Idents.get(NewBuiltinName));
6224 assert(Res.getFoundDecl());
6225 NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6226 if (!NewBuiltinDecl)
6233 for (
unsigned i = 0; i != NumFixed; ++i) {
6262 QualType CalleePtrTy =
Context.getPointerType(NewBuiltinDecl->
getType());
6264 CK_BuiltinFnToFnPtr);
6275 const auto *BitIntValType = ValType->
getAs<BitIntType>();
6276 if (BitIntValType && !llvm::isPowerOf2_64(BitIntValType->getNumBits())) {
6277 Diag(FirstArg->
getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6281 return TheCallResult;
6285 CallExpr *TheCall = (CallExpr *)TheCallResult.
get();
6290 assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6291 BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6292 "Unexpected nontemporal load/store builtin!");
6293 bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6294 unsigned numArgs = isStore ? 2 : 1;
6304 Expr *PointerArg = TheCall->
getArg(numArgs - 1);
6310 PointerArg = PointerArgResult.
get();
6311 TheCall->
setArg(numArgs - 1, PointerArg);
6315 Diag(DRE->
getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6328 diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6335 return TheCallResult;
6347 return TheCallResult;
6354 auto *
Literal = dyn_cast<StringLiteral>(Arg);
6356 if (
auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6357 Literal = ObjcLiteral->getString();
6361 if (!Literal || (!
Literal->isOrdinary() && !
Literal->isUTF8())) {
6368 QualType ResultTy =
Context.getPointerType(
Context.CharTy.withConst());
6369 InitializedEntity Entity =
6379 bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6380 bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6381 TT.getArch() == llvm::Triple::aarch64_32);
6382 bool IsWindowsOrUEFI = TT.isOSWindows() || TT.isUEFI();
6383 bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6384 if (IsX64 || IsAArch64) {
6391 return S.
Diag(Fn->getBeginLoc(),
6392 diag::err_ms_va_start_used_in_sysv_function);
6399 (!IsWindowsOrUEFI && CC ==
CC_Win64))
6400 return S.
Diag(Fn->getBeginLoc(),
6401 diag::err_va_start_used_in_wrong_abi_function)
6402 << !IsWindowsOrUEFI;
6408 return S.
Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6416 bool IsVariadic =
false;
6420 if (
auto *
Block = dyn_cast<BlockDecl>(Caller)) {
6421 IsVariadic =
Block->isVariadic();
6422 Params =
Block->parameters();
6423 }
else if (
auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6426 }
else if (
auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6427 IsVariadic = MD->isVariadic();
6429 Params = MD->parameters();
6432 S.
Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6436 S.
Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6441 S.
Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6446 *LastParam = Params.empty() ?
nullptr : Params.back();
6451bool Sema::BuiltinVAStart(
unsigned BuiltinID,
CallExpr *TheCall) {
6456 if (BuiltinID == Builtin::BI__builtin_c23_va_start) {
6480 ParmVarDecl *LastParam;
6491 if (BuiltinID == Builtin::BI__builtin_c23_va_start &&
6493 Diag(TheCall->
getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6498 if (std::optional<llvm::APSInt> Val =
6500 Val &&
LangOpts.C23 && *Val == 0 &&
6501 BuiltinID != Builtin::BI__builtin_c23_va_start) {
6502 Diag(TheCall->
getExprLoc(), diag::warn_c17_compat_va_start_one_arg);
6509 SourceLocation ParamLoc;
6510 bool IsCRegister =
false;
6511 bool SecondArgIsLastNonVariadicArgument =
false;
6512 if (
const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6513 if (
const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6514 SecondArgIsLastNonVariadicArgument = PV == LastParam;
6517 ParamLoc = PV->getLocation();
6523 if (!SecondArgIsLastNonVariadicArgument)
6525 diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
6526 else if (IsCRegister ||
Type->isReferenceType() ||
6527 Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6530 if (!Context.isPromotableIntegerType(Type))
6532 const auto *ED = Type->getAsEnumDecl();
6535 return !Context.typesAreCompatible(ED->getPromotionType(), Type);
6537 unsigned Reason = 0;
6538 if (
Type->isReferenceType()) Reason = 1;
6539 else if (IsCRegister) Reason = 2;
6540 Diag(Arg->
getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6541 Diag(ParamLoc, diag::note_parameter_type) <<
Type;
6548 auto IsSuitablyTypedFormatArgument = [
this](
const Expr *Arg) ->
bool {
6568 if (
Call->getNumArgs() < 3)
6570 diag::err_typecheck_call_too_few_args_at_least)
6571 << 0 << 3 <<
Call->getNumArgs()
6587 const Expr *Arg2 =
Call->getArg(2)->IgnoreParens();
6590 const QualType &ConstCharPtrTy =
6592 if (!Arg1Ty->
isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6594 << Arg1->
getType() << ConstCharPtrTy << 1
6597 << 2 << Arg1->
getType() << ConstCharPtrTy;
6599 const QualType SizeTy =
Context.getSizeType();
6604 << Arg2->
getType() << SizeTy << 1
6607 << 3 << Arg2->
getType() << SizeTy;
6612bool Sema::BuiltinUnorderedCompare(
CallExpr *TheCall,
unsigned BuiltinID) {
6616 if (BuiltinID == Builtin::BI__builtin_isunordered &&
6644 diag::err_typecheck_call_invalid_ordered_compare)
6652bool Sema::BuiltinFPClassification(
CallExpr *TheCall,
unsigned NumArgs,
6653 unsigned BuiltinID) {
6658 if (FPO.getNoHonorInfs() && (BuiltinID == Builtin::BI__builtin_isfinite ||
6659 BuiltinID == Builtin::BI__builtin_isinf ||
6660 BuiltinID == Builtin::BI__builtin_isinf_sign))
6664 if (FPO.getNoHonorNaNs() && (BuiltinID == Builtin::BI__builtin_isnan ||
6665 BuiltinID == Builtin::BI__builtin_isunordered))
6669 bool IsFPClass = NumArgs == 2;
6672 unsigned FPArgNo = IsFPClass ? 0 : NumArgs - 1;
6676 for (
unsigned i = 0; i < FPArgNo; ++i) {
6677 Expr *Arg = TheCall->
getArg(i);
6690 Expr *OrigArg = TheCall->
getArg(FPArgNo);
6699 OrigArg = Res.
get();
6701 TheCall->
setArg(FPArgNo, OrigArg);
6703 QualType VectorResultTy;
6704 QualType ElementTy = OrigArg->
getType();
6709 ElementTy = ElementTy->
castAs<VectorType>()->getElementType();
6715 diag::err_typecheck_call_invalid_unary_fp)
6728 TheCall->
setArg(NumArgs - 1, MaskRes.
get());
6734 if (!VectorResultTy.
isNull())
6735 ResultTy = VectorResultTy;
6744bool Sema::BuiltinComplex(
CallExpr *TheCall) {
6749 for (
unsigned I = 0; I != 2; ++I) {
6750 Expr *Arg = TheCall->
getArg(I);
6760 return Diag(Arg->
getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6775 Expr *Real = TheCall->
getArg(0);
6776 Expr *Imag = TheCall->
getArg(1);
6779 diag::err_typecheck_call_different_arg_types)
6794 diag::err_typecheck_call_too_few_args_at_least)
6795 << 0 << 2 << NumArgs
6802 unsigned NumElements = 0;
6817 unsigned NumResElements = NumArgs - 2;
6824 if (RHSVecType->getElementType()->isBooleanType() ||
6825 !RHSVecType->getElementType()->isIntegerType()) {
6834 if (RHSVecType->getNumElements() != NumElements)
6836 diag::err_typecheck_vector_lengths_not_equal)
6837 << LHSType << RHSType <<
false
6840 }
else if (!
Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6842 diag::err_vec_builtin_incompatible_vector)
6847 }
else if (NumElements != NumResElements) {
6850 ?
Context.getExtVectorType(EltType, NumResElements)
6851 :
Context.getVectorType(EltType, NumResElements,
6856 for (
unsigned I = 2; I != NumArgs; ++I) {
6864 diag::err_shufflevector_nonconstant_argument)
6870 else if (
Result->getActiveBits() > 64 ||
6871 Result->getZExtValue() >= NumElements * 2)
6873 diag::err_shufflevector_argument_too_large)
6898 diag::err_convertvector_non_vector)
6901 return ExprError(
Diag(BuiltinLoc, diag::err_builtin_non_vector_type)
6903 <<
"__builtin_convertvector");
6908 if (SrcElts != DstElts)
6910 diag::err_convertvector_incompatible_vector)
6918bool Sema::BuiltinPrefetch(
CallExpr *TheCall) {
6923 diag::err_typecheck_call_too_many_args_at_most)
6924 << 0 << 3 << NumArgs << 0
6929 for (
unsigned i = 1; i != NumArgs; ++i) {
6939bool Sema::BuiltinArithmeticFence(
CallExpr *TheCall) {
6940 if (!
Context.getTargetInfo().checkArithmeticFenceSupported())
6941 return Diag(TheCall->
getBeginLoc(), diag::err_builtin_target_unsupported)
6945 Expr *Arg = TheCall->
getArg(0);
6949 QualType ArgTy = Arg->
getType();
6951 return Diag(TheCall->
getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6961bool Sema::BuiltinAssume(
CallExpr *TheCall) {
6962 Expr *Arg = TheCall->
getArg(0);
6973bool Sema::BuiltinAllocaWithAlign(
CallExpr *TheCall) {
6975 Expr *Arg = TheCall->
getArg(1);
6979 if (
const auto *UE =
6981 if (UE->getKind() == UETT_AlignOf ||
6982 UE->getKind() == UETT_PreferredAlignOf)
6988 if (!
Result.isPowerOf2())
6989 return Diag(TheCall->
getBeginLoc(), diag::err_alignment_not_power_of_two)
6996 if (
Result > std::numeric_limits<int32_t>::max())
7004bool Sema::BuiltinAssumeAligned(
CallExpr *TheCall) {
7009 Expr *FirstArg = TheCall->
getArg(0);
7017 Diag(TheCall->
getBeginLoc(), diag::err_builtin_assume_aligned_invalid_arg)
7021 TheCall->
setArg(0, FirstArgResult.
get());
7025 Expr *SecondArg = TheCall->
getArg(1);
7033 if (!
Result.isPowerOf2())
7034 return Diag(TheCall->
getBeginLoc(), diag::err_alignment_not_power_of_two)
7046 Expr *ThirdArg = TheCall->
getArg(2);
7049 TheCall->
setArg(2, ThirdArg);
7055bool Sema::BuiltinOSLogFormat(
CallExpr *TheCall) {
7056 unsigned BuiltinID =
7058 bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
7061 unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
7062 if (NumArgs < NumRequiredArgs) {
7063 return Diag(TheCall->
getEndLoc(), diag::err_typecheck_call_too_few_args)
7064 << 0 << NumRequiredArgs << NumArgs
7067 if (NumArgs >= NumRequiredArgs + 0x100) {
7069 diag::err_typecheck_call_too_many_args_at_most)
7070 << 0 << (NumRequiredArgs + 0xff) << NumArgs
7081 if (Arg.isInvalid())
7083 TheCall->
setArg(i, Arg.get());
7088 unsigned FormatIdx = i;
7098 unsigned FirstDataArg = i;
7099 while (i < NumArgs) {
7117 llvm::SmallBitVector CheckedVarArgs(NumArgs,
false);
7119 bool Success = CheckFormatArguments(
7122 TheCall->
getBeginLoc(), SourceRange(), CheckedVarArgs);
7157 int High,
bool RangeIsError) {
7205 return Diag(TheCall->
getBeginLoc(), diag::err_argument_not_power_of_2)
7210 if (
Value.isNegative())
7221 if ((
Value & 0xFF) != 0)
7246 Result.setIsUnsigned(
true);
7251 return Diag(TheCall->
getBeginLoc(), diag::err_argument_not_shifted_byte)
7271 Result.setIsUnsigned(
true);
7279 diag::err_argument_not_shifted_byte_or_xxff)
7283bool Sema::BuiltinLongjmp(
CallExpr *TheCall) {
7284 if (!Context.getTargetInfo().hasSjLjLowering())
7285 return Diag(TheCall->
getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7296 return Diag(TheCall->
getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7302bool Sema::BuiltinSetjmp(
CallExpr *TheCall) {
7303 if (!Context.getTargetInfo().hasSjLjLowering())
7304 return Diag(TheCall->
getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7309bool Sema::BuiltinCountedByRef(
CallExpr *TheCall) {
7324 diag::err_builtin_counted_by_ref_invalid_arg)
7329 diag::err_builtin_counted_by_ref_has_side_effects)
7332 if (
const auto *ME = dyn_cast<MemberExpr>(Arg)) {
7334 ME->getMemberDecl()->getType()->getAs<CountAttributedType>();
7339 if (
const FieldDecl *CountFD = MemberDecl->findCountedByField()) {
7340 if (CountFD->isBitField()) {
7341 Diag(ME->getBeginLoc(),
7342 diag::err_builtin_counted_by_ref_counter_field_is_bitfield)
7344 return Diag(CountFD->getBeginLoc(),
7345 diag::note_counted_by_counter_field)
7346 << CountFD << CountFD->getSourceRange();
7355 QualType MemberTy = ME->getMemberDecl()->getType();
7358 diag::err_builtin_counted_by_ref_invalid_arg)
7362 diag::err_builtin_counted_by_ref_invalid_arg)
7372bool Sema::CheckInvalidBuiltinCountedByRef(
const Expr *E,
7374 const CallExpr *CE =
7383 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7388 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7393 diag::err_builtin_counted_by_ref_cannot_leak_reference)
7397 Diag(E->
getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7401 Diag(E->
getExprLoc(), diag::err_builtin_counted_by_ref_invalid_use)
7411class UncoveredArgHandler {
7412 enum {
Unknown = -1, AllCovered = -2 };
7414 signed FirstUncoveredArg =
Unknown;
7415 SmallVector<const Expr *, 4> DiagnosticExprs;
7418 UncoveredArgHandler() =
default;
7420 bool hasUncoveredArg()
const {
7421 return (FirstUncoveredArg >= 0);
7424 unsigned getUncoveredArg()
const {
7425 assert(hasUncoveredArg() &&
"no uncovered argument");
7426 return FirstUncoveredArg;
7429 void setAllCovered() {
7432 DiagnosticExprs.clear();
7433 FirstUncoveredArg = AllCovered;
7436 void Update(
signed NewFirstUncoveredArg,
const Expr *StrExpr) {
7437 assert(NewFirstUncoveredArg >= 0 &&
"Outside range");
7440 if (FirstUncoveredArg == AllCovered)
7445 if (NewFirstUncoveredArg == FirstUncoveredArg)
7446 DiagnosticExprs.push_back(StrExpr);
7447 else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7448 DiagnosticExprs.clear();
7449 DiagnosticExprs.push_back(StrExpr);
7450 FirstUncoveredArg = NewFirstUncoveredArg;
7454 void Diagnose(Sema &S,
bool IsFunctionCall,
const Expr *ArgExpr);
7457enum StringLiteralCheckType {
7459 SLCT_UncheckedLiteral,
7467 bool AddendIsRight) {
7468 unsigned BitWidth = Offset.getBitWidth();
7469 unsigned AddendBitWidth = Addend.getBitWidth();
7471 if (Addend.isUnsigned()) {
7472 Addend = Addend.zext(++AddendBitWidth);
7473 Addend.setIsSigned(
true);
7476 if (AddendBitWidth > BitWidth) {
7477 Offset = Offset.sext(AddendBitWidth);
7478 BitWidth = AddendBitWidth;
7479 }
else if (BitWidth > AddendBitWidth) {
7480 Addend = Addend.sext(BitWidth);
7484 llvm::APSInt ResOffset = Offset;
7485 if (BinOpKind == BO_Add)
7486 ResOffset = Offset.sadd_ov(Addend, Ov);
7488 assert(AddendIsRight && BinOpKind == BO_Sub &&
7489 "operator must be add or sub with addend on the right");
7490 ResOffset = Offset.ssub_ov(Addend, Ov);
7496 assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7497 "index (intermediate) result too big");
7498 Offset = Offset.sext(2 * BitWidth);
7499 sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7503 Offset = std::move(ResOffset);
7511class FormatStringLiteral {
7512 const StringLiteral *FExpr;
7516 FormatStringLiteral(
const StringLiteral *fexpr,
int64_t Offset = 0)
7517 : FExpr(fexpr), Offset(Offset) {}
7519 const StringLiteral *getFormatString()
const {
return FExpr; }
7521 StringRef getString()
const {
return FExpr->
getString().drop_front(Offset); }
7523 unsigned getByteLength()
const {
7524 return FExpr->
getByteLength() - getCharByteWidth() * Offset;
7527 unsigned getLength()
const {
return FExpr->
getLength() - Offset; }
7534 bool isAscii()
const {
return FExpr->
isOrdinary(); }
7535 bool isWide()
const {
return FExpr->
isWide(); }
7536 bool isUTF8()
const {
return FExpr->
isUTF8(); }
7537 bool isUTF16()
const {
return FExpr->
isUTF16(); }
7538 bool isUTF32()
const {
return FExpr->
isUTF32(); }
7539 bool isPascal()
const {
return FExpr->
isPascal(); }
7541 SourceLocation getLocationOfByte(
7542 unsigned ByteNo,
const SourceManager &SM,
const LangOptions &Features,
7543 const TargetInfo &
Target,
unsigned *StartToken =
nullptr,
7544 unsigned *StartTokenByteOffset =
nullptr)
const {
7546 StartToken, StartTokenByteOffset);
7549 SourceLocation getBeginLoc() const LLVM_READONLY {
7553 SourceLocation getEndLoc() const LLVM_READONLY {
return FExpr->
getEndLoc(); }
7559 Sema &S,
const FormatStringLiteral *FExpr,
7564 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
7565 bool IgnoreStringsWithoutSpecifiers);
7574static StringLiteralCheckType
7580 llvm::SmallBitVector &CheckedVarArgs,
7581 UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset,
7582 std::optional<unsigned> *CallerFormatParamIdx =
nullptr,
7583 bool IgnoreStringsWithoutSpecifiers =
false) {
7585 return SLCT_NotALiteral;
7587 assert(Offset.isSigned() &&
"invalid offset");
7590 return SLCT_NotALiteral;
7599 return SLCT_UncheckedLiteral;
7602 case Stmt::InitListExprClass:
7606 format_idx, firstDataArg,
Type, CallType,
7607 false, CheckedVarArgs,
7608 UncoveredArg, Offset, CallerFormatParamIdx,
7609 IgnoreStringsWithoutSpecifiers);
7611 return SLCT_NotALiteral;
7612 case Stmt::BinaryConditionalOperatorClass:
7613 case Stmt::ConditionalOperatorClass: {
7622 bool CheckLeft =
true, CheckRight =
true;
7625 if (
C->getCond()->EvaluateAsBooleanCondition(
7637 StringLiteralCheckType Left;
7639 Left = SLCT_UncheckedLiteral;
7642 Args, APK, format_idx, firstDataArg,
Type,
7643 CallType, InFunctionCall, CheckedVarArgs,
7644 UncoveredArg, Offset, CallerFormatParamIdx,
7645 IgnoreStringsWithoutSpecifiers);
7646 if (Left == SLCT_NotALiteral || !CheckRight) {
7652 S, ReferenceFormatString,
C->getFalseExpr(), Args, APK, format_idx,
7653 firstDataArg,
Type, CallType, InFunctionCall, CheckedVarArgs,
7654 UncoveredArg, Offset, CallerFormatParamIdx,
7655 IgnoreStringsWithoutSpecifiers);
7657 return (CheckLeft && Left < Right) ? Left : Right;
7660 case Stmt::ImplicitCastExprClass:
7664 case Stmt::OpaqueValueExprClass:
7669 return SLCT_NotALiteral;
7671 case Stmt::PredefinedExprClass:
7675 return SLCT_UncheckedLiteral;
7677 case Stmt::DeclRefExprClass: {
7683 bool isConstant =
false;
7687 isConstant = AT->getElementType().isConstant(S.
Context);
7689 isConstant =
T.isConstant(S.
Context) &&
7690 PT->getPointeeType().isConstant(S.
Context);
7691 }
else if (
T->isObjCObjectPointerType()) {
7694 isConstant =
T.isConstant(S.
Context);
7698 if (
const Expr *
Init = VD->getAnyInitializer()) {
7701 if (InitList->isStringLiteralInit())
7702 Init = InitList->getInit(0)->IgnoreParenImpCasts();
7705 S, ReferenceFormatString,
Init, Args, APK, format_idx,
7706 firstDataArg,
Type, CallType,
false,
7707 CheckedVarArgs, UncoveredArg, Offset, CallerFormatParamIdx);
7758 if (
const auto *PV = dyn_cast<ParmVarDecl>(VD)) {
7759 if (CallerFormatParamIdx)
7760 *CallerFormatParamIdx = PV->getFunctionScopeIndex();
7761 if (
const auto *D = dyn_cast<Decl>(PV->getDeclContext())) {
7762 for (
const auto *PVFormatMatches :
7763 D->specific_attrs<FormatMatchesAttr>()) {
7768 if (PV->getFunctionScopeIndex() == CalleeFSI.
FormatIdx) {
7772 S.
Diag(Args[format_idx]->getBeginLoc(),
7773 diag::warn_format_string_type_incompatible)
7774 << PVFormatMatches->getType()->getName()
7776 if (!InFunctionCall) {
7777 S.
Diag(PVFormatMatches->getFormatString()->getBeginLoc(),
7778 diag::note_format_string_defined);
7780 return SLCT_UncheckedLiteral;
7783 S, ReferenceFormatString, PVFormatMatches->getFormatString(),
7784 Args, APK, format_idx, firstDataArg,
Type, CallType,
7785 false, CheckedVarArgs, UncoveredArg,
7786 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7790 for (
const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7793 PVFormat->getFirstArg(), &CallerFSI))
7795 if (PV->getFunctionScopeIndex() == CallerFSI.
FormatIdx) {
7799 S.
Diag(Args[format_idx]->getBeginLoc(),
7800 diag::warn_format_string_type_incompatible)
7801 << PVFormat->getType()->getName()
7803 if (!InFunctionCall) {
7806 return SLCT_UncheckedLiteral;
7819 return SLCT_UncheckedLiteral;
7827 return SLCT_NotALiteral;
7830 case Stmt::CallExprClass:
7831 case Stmt::CXXMemberCallExprClass: {
7835 StringLiteralCheckType CommonResult;
7836 for (
const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7837 const Expr *Arg = CE->
getArg(FA->getFormatIdx().getASTIndex());
7839 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7840 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7841 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7848 return CommonResult;
7850 if (
const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7852 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7853 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7856 S, ReferenceFormatString, Arg, Args, APK, format_idx,
7857 firstDataArg,
Type, CallType, InFunctionCall, CheckedVarArgs,
7858 UncoveredArg, Offset, CallerFormatParamIdx,
7859 IgnoreStringsWithoutSpecifiers);
7865 format_idx, firstDataArg,
Type, CallType,
7866 false, CheckedVarArgs,
7867 UncoveredArg, Offset, CallerFormatParamIdx,
7868 IgnoreStringsWithoutSpecifiers);
7869 return SLCT_NotALiteral;
7871 case Stmt::ObjCMessageExprClass: {
7873 if (
const auto *MD = ME->getMethodDecl()) {
7874 if (
const auto *FA = MD->getAttr<FormatArgAttr>()) {
7883 if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7885 MD->getSelector().isKeywordSelector(
7886 {
"localizedStringForKey",
"value",
"table"})) {
7887 IgnoreStringsWithoutSpecifiers =
true;
7890 const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7892 S, ReferenceFormatString, Arg, Args, APK, format_idx, firstDataArg,
7893 Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg,
7894 Offset, CallerFormatParamIdx, IgnoreStringsWithoutSpecifiers);
7898 return SLCT_NotALiteral;
7900 case Stmt::ObjCStringLiteralClass:
7901 case Stmt::StringLiteralClass: {
7910 if (Offset.isNegative() || Offset > StrE->
getLength()) {
7913 return SLCT_NotALiteral;
7915 FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7917 format_idx, firstDataArg,
Type, InFunctionCall,
7918 CallType, CheckedVarArgs, UncoveredArg,
7919 IgnoreStringsWithoutSpecifiers);
7920 return SLCT_CheckedLiteral;
7923 return SLCT_NotALiteral;
7925 case Stmt::BinaryOperatorClass: {
7939 if (LIsInt != RIsInt) {
7943 if (BinOpKind == BO_Add) {
7956 return SLCT_NotALiteral;
7958 case Stmt::UnaryOperatorClass: {
7960 auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->
getSubExpr());
7961 if (UnaOp->
getOpcode() == UO_AddrOf && ASE) {
7963 if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.
Context,
7973 return SLCT_NotALiteral;
7977 return SLCT_NotALiteral;
7988 const auto *LVE =
Result.Val.getLValueBase().dyn_cast<
const Expr *>();
7989 if (isa_and_nonnull<StringLiteral>(LVE))
8010 return "freebsd_kprintf";
8019 return llvm::StringSwitch<FormatStringType>(Flavor)
8021 .Cases({
"gnu_printf",
"printf",
"printf0",
"syslog"},
8026 .Cases({
"kprintf",
"cmn_err",
"vcmn_err",
"zcmn_err"},
8042bool Sema::CheckFormatArguments(
const FormatAttr *Format,
8046 llvm::SmallBitVector &CheckedVarArgs) {
8047 FormatStringInfo FSI;
8051 return CheckFormatArguments(
8052 Args, FSI.ArgPassingKind,
nullptr, FSI.FormatIdx, FSI.FirstDataArg,
8057bool Sema::CheckFormatString(
const FormatMatchesAttr *Format,
8061 llvm::SmallBitVector &CheckedVarArgs) {
8062 FormatStringInfo FSI;
8066 return CheckFormatArguments(Args, FSI.ArgPassingKind,
8067 Format->getFormatString(), FSI.FormatIdx,
8069 CallType, Loc, Range, CheckedVarArgs);
8077 unsigned FirstDataArg,
FormatStringType FormatType,
unsigned CallerParamIdx,
8090 unsigned CallerArgumentIndexOffset =
8093 unsigned FirstArgumentIndex = -1;
8103 unsigned NumCalleeArgs = Args.size() - FirstDataArg;
8104 if (NumCalleeArgs == 0 || NumCallerParams < NumCalleeArgs) {
8108 for (
unsigned CalleeIdx = Args.size() - 1, CallerIdx = NumCallerParams - 1;
8109 CalleeIdx >= FirstDataArg; --CalleeIdx, --CallerIdx) {
8111 dyn_cast<DeclRefExpr>(Args[CalleeIdx]->IgnoreParenCasts());
8114 const auto *Param = dyn_cast<ParmVarDecl>(Arg->getDecl());
8115 if (!Param || Param->getFunctionScopeIndex() != CallerIdx)
8118 FirstArgumentIndex =
8119 NumCallerParams + CallerArgumentIndexOffset - NumCalleeArgs;
8125 ? (NumCallerParams + CallerArgumentIndexOffset)
8130 if (!ReferenceFormatString)
8136 unsigned FormatStringIndex = CallerParamIdx + CallerArgumentIndexOffset;
8138 NamedDecl *ND = dyn_cast<NamedDecl>(Caller);
8140 std::string
Attr, Fixit;
8141 llvm::raw_string_ostream AttrOS(
Attr);
8143 AttrOS <<
"format(" << FormatTypeName <<
", " << FormatStringIndex <<
", "
8144 << FirstArgumentIndex <<
")";
8146 AttrOS <<
"format_matches(" << FormatTypeName <<
", " << FormatStringIndex
8148 AttrOS.write_escaped(ReferenceFormatString->
getString());
8152 auto DB = S->
Diag(Loc, diag::warn_missing_format_attribute) <<
Attr;
8163 llvm::raw_string_ostream IS(Fixit);
8171 if (LO.C23 || LO.CPlusPlus11)
8172 IS <<
"[[gnu::" <<
Attr <<
"]]";
8173 else if (LO.ObjC || LO.GNUMode)
8174 IS <<
"__attribute__((" <<
Attr <<
"))";
8188 Caller->
addAttr(FormatAttr::CreateImplicit(
8190 FormatStringIndex, FirstArgumentIndex));
8192 Caller->
addAttr(FormatMatchesAttr::CreateImplicit(
8194 FormatStringIndex, ReferenceFormatString));
8198 auto DB = S->
Diag(Caller->
getLocation(), diag::note_entity_declared_at);
8210 unsigned format_idx,
unsigned firstDataArg,
8214 llvm::SmallBitVector &CheckedVarArgs) {
8216 if (format_idx >= Args.size()) {
8217 Diag(Loc, diag::warn_missing_format_string) <<
Range;
8221 const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8235 UncoveredArgHandler UncoveredArg;
8236 std::optional<unsigned> CallerParamIdx;
8238 *
this, ReferenceFormatString, OrigFormatExpr, Args, APK, format_idx,
8239 firstDataArg,
Type, CallType,
8240 true, CheckedVarArgs, UncoveredArg,
8241 llvm::APSInt(64,
false) = 0, &CallerParamIdx);
8244 if (UncoveredArg.hasUncoveredArg()) {
8245 unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8246 assert(ArgIdx < Args.size() &&
"ArgIdx outside bounds");
8247 UncoveredArg.Diagnose(*
this,
true, Args[ArgIdx]);
8250 if (CT != SLCT_NotALiteral)
8252 return CT == SLCT_CheckedLiteral;
8258 SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8264 this, Args, APK, ReferenceFormatString, format_idx,
8265 firstDataArg,
Type, *CallerParamIdx, Loc))
8275 if (Args.size() == firstDataArg) {
8276 Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8284 Diag(FormatLoc, diag::note_format_security_fixit)
8288 Diag(FormatLoc, diag::note_format_security_fixit)
8293 Diag(FormatLoc, diag::warn_format_nonliteral)
8304 const FormatStringLiteral *FExpr;
8305 const Expr *OrigFormatExpr;
8307 const unsigned FirstDataArg;
8308 const unsigned NumDataArgs;
8311 ArrayRef<const Expr *> Args;
8313 llvm::SmallBitVector CoveredArgs;
8314 bool usesPositionalArgs =
false;
8315 bool atFirstArg =
true;
8316 bool inFunctionCall;
8318 llvm::SmallBitVector &CheckedVarArgs;
8319 UncoveredArgHandler &UncoveredArg;
8322 CheckFormatHandler(Sema &s,
const FormatStringLiteral *fexpr,
8324 unsigned firstDataArg,
unsigned numDataArgs,
8326 ArrayRef<const Expr *> Args,
unsigned formatIdx,
8328 llvm::SmallBitVector &CheckedVarArgs,
8329 UncoveredArgHandler &UncoveredArg)
8330 : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(
type),
8331 FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8332 ArgPassingKind(APK), Args(Args), FormatIdx(formatIdx),
8333 inFunctionCall(inFunctionCall), CallType(callType),
8334 CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8335 CoveredArgs.resize(numDataArgs);
8336 CoveredArgs.reset();
8339 bool HasFormatArguments()
const {
8344 void DoneProcessing();
8346 void HandleIncompleteSpecifier(
const char *startSpecifier,
8347 unsigned specifierLen)
override;
8349 void HandleInvalidLengthModifier(
8350 const analyze_format_string::FormatSpecifier &FS,
8351 const analyze_format_string::ConversionSpecifier &CS,
8352 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID);
8354 void HandleNonStandardLengthModifier(
8355 const analyze_format_string::FormatSpecifier &FS,
8356 const char *startSpecifier,
unsigned specifierLen);
8358 void HandleNonStandardConversionSpecifier(
8359 const analyze_format_string::ConversionSpecifier &CS,
8360 const char *startSpecifier,
unsigned specifierLen);
8362 void HandlePosition(
const char *startPos,
unsigned posLen)
override;
8364 void HandleInvalidPosition(
const char *startSpecifier,
unsigned specifierLen,
8367 void HandleZeroPosition(
const char *startPos,
unsigned posLen)
override;
8369 void HandleNullChar(
const char *nullCharacter)
override;
8371 template <
typename Range>
8373 EmitFormatDiagnostic(Sema &S,
bool inFunctionCall,
const Expr *ArgumentExpr,
8374 const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8375 bool IsStringLocation, Range StringRange,
8376 ArrayRef<FixItHint> Fixit = {});
8379 bool HandleInvalidConversionSpecifier(
unsigned argIndex, SourceLocation Loc,
8380 const char *startSpec,
8381 unsigned specifierLen,
8382 const char *csStart,
unsigned csLen);
8384 void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8385 const char *startSpec,
8386 unsigned specifierLen);
8388 SourceRange getFormatStringRange();
8389 CharSourceRange getSpecifierRange(
const char *startSpecifier,
8390 unsigned specifierLen);
8391 SourceLocation getLocationOfByte(
const char *x);
8393 const Expr *getDataArg(
unsigned i)
const;
8395 bool CheckNumArgs(
const analyze_format_string::FormatSpecifier &FS,
8396 const analyze_format_string::ConversionSpecifier &CS,
8397 const char *startSpecifier,
unsigned specifierLen,
8400 bool CheckUnsupportedType(
const analyze_format_string::ArgType &AT,
8401 const Expr *E,
const char *startSpecifier,
8402 unsigned specifierLen);
8404 template <
typename Range>
8405 void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8406 bool IsStringLocation, Range StringRange,
8407 ArrayRef<FixItHint> Fixit = {});
8412SourceRange CheckFormatHandler::getFormatStringRange() {
8417CheckFormatHandler::getSpecifierRange(
const char *startSpecifier,
8418 unsigned specifierLen) {
8420 SourceLocation End = getLocationOfByte(startSpecifier + specifierLen - 1);
8428SourceLocation CheckFormatHandler::getLocationOfByte(
const char *x) {
8433void CheckFormatHandler::HandleIncompleteSpecifier(
const char *startSpecifier,
8434 unsigned specifierLen) {
8435 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_incomplete_specifier),
8436 getLocationOfByte(startSpecifier),
8438 getSpecifierRange(startSpecifier, specifierLen));
8441bool CheckFormatHandler::CheckUnsupportedType(
8443 const char *StartSpecifier,
unsigned SpecifierLen) {
8447 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_unsupported_type)
8450 getSpecifierRange(StartSpecifier, SpecifierLen));
8454void CheckFormatHandler::HandleInvalidLengthModifier(
8457 const char *startSpecifier,
unsigned specifierLen,
unsigned DiagID) {
8469 getSpecifierRange(startSpecifier, specifierLen));
8471 S.
Diag(getLocationOfByte(LM.
getStart()), diag::note_format_fix_specifier)
8472 << FixedLM->toString()
8477 if (DiagID == diag::warn_format_nonsensical_length)
8483 getSpecifierRange(startSpecifier, specifierLen), Hint);
8487void CheckFormatHandler::HandleNonStandardLengthModifier(
8489 const char *startSpecifier,
unsigned specifierLen) {
8498 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
8502 getSpecifierRange(startSpecifier, specifierLen));
8504 S.
Diag(getLocationOfByte(LM.
getStart()), diag::note_format_fix_specifier)
8505 << FixedLM->toString()
8509 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
8513 getSpecifierRange(startSpecifier, specifierLen));
8517void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8519 const char *startSpecifier,
unsigned specifierLen) {
8525 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
8529 getSpecifierRange(startSpecifier, specifierLen));
8532 S.
Diag(getLocationOfByte(CS.
getStart()), diag::note_format_fix_specifier)
8533 << FixedCS->toString()
8536 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard)
8540 getSpecifierRange(startSpecifier, specifierLen));
8544void CheckFormatHandler::HandlePosition(
const char *startPos,
unsigned posLen) {
8546 diag::warn_format_non_standard_positional_arg,
SourceLocation()))
8547 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_non_standard_positional_arg),
8548 getLocationOfByte(startPos),
8550 getSpecifierRange(startPos, posLen));
8553void CheckFormatHandler::HandleInvalidPosition(
8554 const char *startSpecifier,
unsigned specifierLen,
8557 diag::warn_format_invalid_positional_specifier,
SourceLocation()))
8558 EmitFormatDiagnostic(
8559 S.
PDiag(diag::warn_format_invalid_positional_specifier) << (
unsigned)p,
8560 getLocationOfByte(startSpecifier),
true,
8561 getSpecifierRange(startSpecifier, specifierLen));
8564void CheckFormatHandler::HandleZeroPosition(
const char *startPos,
8568 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_zero_positional_specifier),
8569 getLocationOfByte(startPos),
8571 getSpecifierRange(startPos, posLen));
8574void CheckFormatHandler::HandleNullChar(
const char *nullCharacter) {
8577 EmitFormatDiagnostic(
8578 S.
PDiag(diag::warn_printf_format_string_contains_null_char),
8579 getLocationOfByte(nullCharacter),
true,
8580 getFormatStringRange());
8586const Expr *CheckFormatHandler::getDataArg(
unsigned i)
const {
8587 return Args[FirstDataArg + i];
8590void CheckFormatHandler::DoneProcessing() {
8593 if (HasFormatArguments()) {
8596 signed notCoveredArg = CoveredArgs.find_first();
8597 if (notCoveredArg >= 0) {
8598 assert((
unsigned)notCoveredArg < NumDataArgs);
8599 UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8601 UncoveredArg.setAllCovered();
8606void UncoveredArgHandler::Diagnose(
Sema &S,
bool IsFunctionCall,
8607 const Expr *ArgExpr) {
8608 assert(hasUncoveredArg() && !DiagnosticExprs.empty() &&
"Invalid state");
8619 for (
auto E : DiagnosticExprs)
8622 CheckFormatHandler::EmitFormatDiagnostic(
8623 S, IsFunctionCall, DiagnosticExprs[0], PDiag, Loc,
8627bool CheckFormatHandler::HandleInvalidConversionSpecifier(
8629 unsigned specifierLen,
const char *csStart,
unsigned csLen) {
8630 bool keepGoing =
true;
8631 if (argIndex < NumDataArgs) {
8634 CoveredArgs.set(argIndex);
8649 std::string CodePointStr;
8650 if (!llvm::sys::locale::isPrint(*csStart)) {
8651 llvm::UTF32 CodePoint;
8652 const llvm::UTF8 **B =
reinterpret_cast<const llvm::UTF8 **
>(&csStart);
8653 const llvm::UTF8 *E =
reinterpret_cast<const llvm::UTF8 *
>(csStart + csLen);
8654 llvm::ConversionResult
Result =
8655 llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8657 if (
Result != llvm::conversionOK) {
8658 unsigned char FirstChar = *csStart;
8659 CodePoint = (llvm::UTF32)FirstChar;
8662 llvm::raw_string_ostream
OS(CodePointStr);
8663 if (CodePoint < 256)
8664 OS <<
"\\x" << llvm::format(
"%02x", CodePoint);
8665 else if (CodePoint <= 0xFFFF)
8666 OS <<
"\\u" << llvm::format(
"%04x", CodePoint);
8668 OS <<
"\\U" << llvm::format(
"%08x", CodePoint);
8672 EmitFormatDiagnostic(
8673 S.
PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8674 true, getSpecifierRange(startSpec, specifierLen));
8679void CheckFormatHandler::HandlePositionalNonpositionalArgs(
8680 SourceLocation Loc,
const char *startSpec,
unsigned specifierLen) {
8681 EmitFormatDiagnostic(
8682 S.
PDiag(diag::warn_format_mix_positional_nonpositional_args), Loc,
8683 true, getSpecifierRange(startSpec, specifierLen));
8686bool CheckFormatHandler::CheckNumArgs(
8689 const char *startSpecifier,
unsigned specifierLen,
unsigned argIndex) {
8691 if (HasFormatArguments() && argIndex >= NumDataArgs) {
8694 ? (S.
PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8695 << (argIndex + 1) << NumDataArgs)
8696 : S.
PDiag(diag::warn_printf_insufficient_data_args);
8697 EmitFormatDiagnostic(PDiag, getLocationOfByte(CS.
getStart()),
8699 getSpecifierRange(startSpecifier, specifierLen));
8703 UncoveredArg.setAllCovered();
8709template <
typename Range>
8712 bool IsStringLocation,
8715 EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag, Loc,
8716 IsStringLocation, StringRange, FixIt);
8746template <
typename Range>
8747void CheckFormatHandler::EmitFormatDiagnostic(
8748 Sema &S,
bool InFunctionCall,
const Expr *ArgumentExpr,
8751 if (InFunctionCall) {
8756 S.
Diag(IsStringLocation ? ArgumentExpr->
getExprLoc() : Loc, PDiag)
8760 S.
Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8761 diag::note_format_string_defined);
8763 Note << StringRange;
8772class CheckPrintfHandler :
public CheckFormatHandler {
8774 CheckPrintfHandler(Sema &s,
const FormatStringLiteral *fexpr,
8776 unsigned firstDataArg,
unsigned numDataArgs,
bool isObjC,
8778 ArrayRef<const Expr *> Args,
unsigned formatIdx,
8780 llvm::SmallBitVector &CheckedVarArgs,
8781 UncoveredArgHandler &UncoveredArg)
8782 : CheckFormatHandler(s, fexpr, origFormatExpr,
type, firstDataArg,
8783 numDataArgs, beg, APK, Args, formatIdx,
8784 inFunctionCall, CallType, CheckedVarArgs,
8787 bool isObjCContext()
const {
return FSType == FormatStringType::NSString; }
8790 bool allowsObjCArg()
const {
8791 return FSType == FormatStringType::NSString ||
8792 FSType == FormatStringType::OSLog ||
8793 FSType == FormatStringType::OSTrace;
8796 bool HandleInvalidPrintfConversionSpecifier(
8797 const analyze_printf::PrintfSpecifier &FS,
const char *startSpecifier,
8798 unsigned specifierLen)
override;
8800 void handleInvalidMaskType(StringRef MaskType)
override;
8802 bool HandlePrintfSpecifier(
const analyze_printf::PrintfSpecifier &FS,
8803 const char *startSpecifier,
unsigned specifierLen,
8804 const TargetInfo &
Target)
override;
8805 bool checkFormatExpr(
const analyze_printf::PrintfSpecifier &FS,
8806 const char *StartSpecifier,
unsigned SpecifierLen,
8809 bool HandleAmount(
const analyze_format_string::OptionalAmount &Amt,
8810 unsigned k,
const char *startSpecifier,
8811 unsigned specifierLen);
8812 void HandleInvalidAmount(
const analyze_printf::PrintfSpecifier &FS,
8813 const analyze_printf::OptionalAmount &Amt,
8814 unsigned type,
const char *startSpecifier,
8815 unsigned specifierLen);
8816 void HandleFlag(
const analyze_printf::PrintfSpecifier &FS,
8817 const analyze_printf::OptionalFlag &flag,
8818 const char *startSpecifier,
unsigned specifierLen);
8819 void HandleIgnoredFlag(
const analyze_printf::PrintfSpecifier &FS,
8820 const analyze_printf::OptionalFlag &ignoredFlag,
8821 const analyze_printf::OptionalFlag &flag,
8822 const char *startSpecifier,
unsigned specifierLen);
8823 bool checkForCStrMembers(
const analyze_printf::ArgType &AT,
const Expr *E);
8825 void HandleEmptyObjCModifierFlag(
const char *startFlag,
8826 unsigned flagLen)
override;
8828 void HandleInvalidObjCModifierFlag(
const char *startFlag,
8829 unsigned flagLen)
override;
8832 HandleObjCFlagsWithNonObjCConversion(
const char *flagsStart,
8833 const char *flagsEnd,
8834 const char *conversionPosition)
override;
8839class EquatableFormatArgument {
8841 enum SpecifierSensitivity :
unsigned {
8848 enum FormatArgumentRole :
unsigned {
8856 analyze_format_string::ArgType ArgType;
8857 analyze_format_string::LengthModifier LengthMod;
8858 StringRef SpecifierLetter;
8859 CharSourceRange
Range;
8860 SourceLocation ElementLoc;
8861 FormatArgumentRole
Role : 2;
8862 SpecifierSensitivity Sensitivity : 2;
8863 unsigned Position : 14;
8864 unsigned ModifierFor : 14;
8866 void EmitDiagnostic(Sema &S, PartialDiagnostic PDiag,
const Expr *FmtExpr,
8867 bool InFunctionCall)
const;
8870 EquatableFormatArgument(CharSourceRange Range, SourceLocation ElementLoc,
8871 analyze_format_string::LengthModifier LengthMod,
8872 StringRef SpecifierLetter,
8873 analyze_format_string::ArgType ArgType,
8874 FormatArgumentRole
Role,
8875 SpecifierSensitivity Sensitivity,
unsigned Position,
8876 unsigned ModifierFor)
8877 : ArgType(ArgType), LengthMod(LengthMod),
8878 SpecifierLetter(SpecifierLetter),
Range(
Range), ElementLoc(ElementLoc),
8879 Role(
Role), Sensitivity(Sensitivity), Position(Position),
8880 ModifierFor(ModifierFor) {}
8882 unsigned getPosition()
const {
return Position; }
8883 SourceLocation getSourceLocation()
const {
return ElementLoc; }
8885 analyze_format_string::LengthModifier getLengthModifier()
const {
8888 void setModifierFor(
unsigned V) { ModifierFor =
V; }
8890 std::string buildFormatSpecifier()
const {
8892 llvm::raw_string_ostream(result)
8893 << getLengthModifier().
toString() << SpecifierLetter;
8897 bool VerifyCompatible(Sema &S,
const EquatableFormatArgument &
Other,
8898 const Expr *FmtExpr,
bool InFunctionCall)
const;
8902class DecomposePrintfHandler :
public CheckPrintfHandler {
8903 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs;
8906 DecomposePrintfHandler(Sema &s,
const FormatStringLiteral *fexpr,
8907 const Expr *origFormatExpr,
8909 unsigned numDataArgs,
bool isObjC,
const char *beg,
8911 ArrayRef<const Expr *> Args,
unsigned formatIdx,
8913 llvm::SmallBitVector &CheckedVarArgs,
8914 UncoveredArgHandler &UncoveredArg,
8915 llvm::SmallVectorImpl<EquatableFormatArgument> &Specs)
8916 : CheckPrintfHandler(s, fexpr, origFormatExpr,
type, firstDataArg,
8917 numDataArgs,
isObjC, beg, APK, Args, formatIdx,
8918 inFunctionCall, CallType, CheckedVarArgs,
8920 Specs(Specs), HadError(
false) {}
8924 GetSpecifiers(Sema &S,
const FormatStringLiteral *FSL,
const Expr *FmtExpr,
8926 llvm::SmallVectorImpl<EquatableFormatArgument> &Args);
8928 virtual bool HandlePrintfSpecifier(
const analyze_printf::PrintfSpecifier &FS,
8929 const char *startSpecifier,
8930 unsigned specifierLen,
8931 const TargetInfo &
Target)
override;
8936bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8938 unsigned specifierLen) {
8942 return HandleInvalidConversionSpecifier(
8947void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8948 S.
Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8956 return T->isRecordType() ||
T->isComplexType();
8959bool CheckPrintfHandler::HandleAmount(
8961 const char *startSpecifier,
unsigned specifierLen) {
8963 if (HasFormatArguments()) {
8965 if (argIndex >= NumDataArgs) {
8966 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_asterisk_missing_arg)
8970 getSpecifierRange(startSpecifier, specifierLen));
8980 CoveredArgs.set(argIndex);
8981 const Expr *Arg = getDataArg(argIndex);
8992 ? diag::err_printf_asterisk_wrong_type
8993 : diag::warn_printf_asterisk_wrong_type;
8994 EmitFormatDiagnostic(S.
PDiag(DiagID)
8999 getSpecifierRange(startSpecifier, specifierLen));
9009void CheckPrintfHandler::HandleInvalidAmount(
9012 const char *startSpecifier,
unsigned specifierLen) {
9022 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_nonsensical_optional_amount)
9026 getSpecifierRange(startSpecifier, specifierLen), fixit);
9031 const char *startSpecifier,
9032 unsigned specifierLen) {
9036 EmitFormatDiagnostic(
9037 S.
PDiag(diag::warn_printf_nonsensical_flag)
9041 getSpecifierRange(startSpecifier, specifierLen),
9045void CheckPrintfHandler::HandleIgnoredFlag(
9049 unsigned specifierLen) {
9051 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_ignored_flag)
9055 getSpecifierRange(startSpecifier, specifierLen),
9057 getSpecifierRange(ignoredFlag.
getPosition(), 1)));
9060void CheckPrintfHandler::HandleEmptyObjCModifierFlag(
const char *startFlag,
9063 EmitFormatDiagnostic(
9064 S.
PDiag(diag::warn_printf_empty_objc_flag), getLocationOfByte(startFlag),
9065 true, getSpecifierRange(startFlag, flagLen));
9068void CheckPrintfHandler::HandleInvalidObjCModifierFlag(
const char *startFlag,
9071 auto Range = getSpecifierRange(startFlag, flagLen);
9072 StringRef flag(startFlag, flagLen);
9073 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_invalid_objc_flag) << flag,
9074 getLocationOfByte(startFlag),
9079void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
9080 const char *flagsStart,
const char *flagsEnd,
9081 const char *conversionPosition) {
9083 auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
9084 auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
9085 EmitFormatDiagnostic(S.
PDiag(
diag) << StringRef(conversionPosition, 1),
9086 getLocationOfByte(conversionPosition),
9092 const Expr *FmtExpr,
9093 bool InFunctionCall)
const {
9094 CheckFormatHandler::EmitFormatDiagnostic(S, InFunctionCall, FmtExpr, PDiag,
9095 ElementLoc,
true, Range);
9098bool EquatableFormatArgument::VerifyCompatible(
9099 Sema &S,
const EquatableFormatArgument &
Other,
const Expr *FmtExpr,
9100 bool InFunctionCall)
const {
9105 S, S.
PDiag(diag::warn_format_cmp_role_mismatch) <<
Role <<
Other.Role,
9106 FmtExpr, InFunctionCall);
9107 S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with) << 0 <<
Other.Range;
9111 if (
Role != FAR_Data) {
9112 if (ModifierFor !=
Other.ModifierFor) {
9115 S.
PDiag(diag::warn_format_cmp_modifierfor_mismatch)
9116 << (ModifierFor + 1) << (
Other.ModifierFor + 1),
9117 FmtExpr, InFunctionCall);
9118 S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with) << 0 <<
Other.Range;
9124 bool HadError =
false;
9125 if (Sensitivity !=
Other.Sensitivity) {
9128 S.
PDiag(diag::warn_format_cmp_sensitivity_mismatch)
9129 << Sensitivity <<
Other.Sensitivity,
9130 FmtExpr, InFunctionCall);
9131 HadError = S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with)
9132 << 0 <<
Other.Range;
9135 switch (ArgType.matchesArgType(S.
Context,
Other.ArgType)) {
9139 case MK::MatchPromotion:
9143 case MK::NoMatchTypeConfusion:
9144 case MK::NoMatchPromotionTypeConfusion:
9146 S.
PDiag(diag::warn_format_cmp_specifier_mismatch)
9147 << buildFormatSpecifier()
9148 <<
Other.buildFormatSpecifier(),
9149 FmtExpr, InFunctionCall);
9150 HadError = S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with)
9151 << 0 <<
Other.Range;
9154 case MK::NoMatchPedantic:
9156 S.
PDiag(diag::warn_format_cmp_specifier_mismatch_pedantic)
9157 << buildFormatSpecifier()
9158 <<
Other.buildFormatSpecifier(),
9159 FmtExpr, InFunctionCall);
9160 HadError = S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with)
9161 << 0 <<
Other.Range;
9164 case MK::NoMatchSignedness:
9166 S.
PDiag(diag::warn_format_cmp_specifier_sign_mismatch)
9167 << buildFormatSpecifier()
9168 <<
Other.buildFormatSpecifier(),
9169 FmtExpr, InFunctionCall);
9170 HadError = S.
Diag(
Other.ElementLoc, diag::note_format_cmp_with)
9171 << 0 <<
Other.Range;
9177bool DecomposePrintfHandler::GetSpecifiers(
9178 Sema &S,
const FormatStringLiteral *FSL,
const Expr *FmtExpr,
9181 StringRef
Data = FSL->getString();
9182 const char *Str =
Data.data();
9183 llvm::SmallBitVector BV;
9184 UncoveredArgHandler UA;
9185 const Expr *PrintfArgs[] = {FSL->getFormatString()};
9186 DecomposePrintfHandler H(S, FSL, FSL->getFormatString(),
Type, 0, 0, IsObjC,
9198 llvm::stable_sort(Args, [](
const EquatableFormatArgument &A,
9199 const EquatableFormatArgument &B) {
9200 return A.getPosition() < B.getPosition();
9205bool DecomposePrintfHandler::HandlePrintfSpecifier(
9208 if (!CheckPrintfHandler::HandlePrintfSpecifier(FS, startSpecifier,
9223 const unsigned Unset = ~0;
9224 unsigned FieldWidthIndex = Unset;
9225 unsigned PrecisionIndex = Unset;
9229 if (!FieldWidth.isInvalid() && FieldWidth.hasDataArgument()) {
9230 FieldWidthIndex = Specs.size();
9232 getSpecifierRange(startSpecifier, specifierLen),
9233 getLocationOfByte(FieldWidth.getStart()),
9235 FieldWidth.getArgType(S.
Context),
9236 EquatableFormatArgument::FAR_FieldWidth,
9237 EquatableFormatArgument::SS_None,
9238 FieldWidth.usesPositionalArg() ? FieldWidth.getPositionalArgIndex() - 1
9244 if (!Precision.isInvalid() && Precision.hasDataArgument()) {
9245 PrecisionIndex = Specs.size();
9247 getSpecifierRange(startSpecifier, specifierLen),
9248 getLocationOfByte(Precision.getStart()),
9250 Precision.getArgType(S.
Context), EquatableFormatArgument::FAR_Precision,
9251 EquatableFormatArgument::SS_None,
9252 Precision.usesPositionalArg() ? Precision.getPositionalArgIndex() - 1
9258 unsigned SpecIndex =
9260 if (FieldWidthIndex != Unset)
9261 Specs[FieldWidthIndex].setModifierFor(SpecIndex);
9262 if (PrecisionIndex != Unset)
9263 Specs[PrecisionIndex].setModifierFor(SpecIndex);
9265 EquatableFormatArgument::SpecifierSensitivity Sensitivity;
9267 Sensitivity = EquatableFormatArgument::SS_Private;
9269 Sensitivity = EquatableFormatArgument::SS_Public;
9271 Sensitivity = EquatableFormatArgument::SS_Sensitive;
9273 Sensitivity = EquatableFormatArgument::SS_None;
9276 getSpecifierRange(startSpecifier, specifierLen),
9279 EquatableFormatArgument::FAR_Data, Sensitivity, SpecIndex, 0);
9284 Specs.emplace_back(getSpecifierRange(startSpecifier, specifierLen),
9289 EquatableFormatArgument::FAR_Auxiliary, Sensitivity,
9290 SpecIndex + 1, SpecIndex);
9298template<
typename MemberKind>
9309 R.suppressDiagnostics();
9316 if (MemberKind *FK = dyn_cast<MemberKind>(
decl))
9331 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9333 if ((*MI)->getMinRequiredArguments() == 0)
9341bool CheckPrintfHandler::checkForCStrMembers(
9348 for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
9351 if (
Method->getMinRequiredArguments() == 0 &&
9364bool CheckPrintfHandler::HandlePrintfSpecifier(
9377 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9378 startSpecifier, specifierLen);
9390 if (!HandleAmount(FS.
getPrecision(), 1, startSpecifier,
9395 if (!CS.consumesDataArgument()) {
9403 if (argIndex < NumDataArgs) {
9407 CoveredArgs.set(argIndex);
9414 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9417 if (HasFormatArguments()) {
9419 CoveredArgs.set(argIndex + 1);
9422 const Expr *Ex = getDataArg(argIndex);
9426 : ArgType::CPointerTy;
9428 EmitFormatDiagnostic(
9429 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
9433 getSpecifierRange(startSpecifier, specifierLen));
9436 Ex = getDataArg(argIndex + 1);
9439 EmitFormatDiagnostic(
9440 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
9444 getSpecifierRange(startSpecifier, specifierLen));
9451 if (!allowsObjCArg() && CS.isObjCArg()) {
9452 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9459 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9466 EmitFormatDiagnostic(S.
PDiag(diag::warn_os_log_format_narg),
9467 getLocationOfByte(CS.getStart()),
9469 getSpecifierRange(startSpecifier, specifierLen));
9479 return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9486 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_invalid_annotation)
9490 getSpecifierRange(startSpecifier, specifierLen));
9493 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_invalid_annotation)
9497 getSpecifierRange(startSpecifier, specifierLen));
9501 const llvm::Triple &Triple =
Target.getTriple();
9503 (Triple.isAndroid() || Triple.isOSFuchsia())) {
9504 EmitFormatDiagnostic(S.
PDiag(diag::warn_printf_narg_not_supported),
9505 getLocationOfByte(CS.getStart()),
9507 getSpecifierRange(startSpecifier, specifierLen));
9513 startSpecifier, specifierLen);
9519 startSpecifier, specifierLen);
9525 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_P_no_precision),
9526 getLocationOfByte(startSpecifier),
9528 getSpecifierRange(startSpecifier, specifierLen));
9537 HandleFlag(FS, FS.
hasPlusPrefix(), startSpecifier, specifierLen);
9539 HandleFlag(FS, FS.
hasSpacePrefix(), startSpecifier, specifierLen);
9548 startSpecifier, specifierLen);
9551 startSpecifier, specifierLen);
9556 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9557 diag::warn_format_nonsensical_length);
9559 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9561 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9562 diag::warn_format_non_standard_conversion_spec);
9565 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9568 if (!HasFormatArguments())
9571 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9574 const Expr *Arg = getDataArg(argIndex);
9578 return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9590 case Stmt::ArraySubscriptExprClass:
9591 case Stmt::CallExprClass:
9592 case Stmt::CharacterLiteralClass:
9593 case Stmt::CXXBoolLiteralExprClass:
9594 case Stmt::DeclRefExprClass:
9595 case Stmt::FloatingLiteralClass:
9596 case Stmt::IntegerLiteralClass:
9597 case Stmt::MemberExprClass:
9598 case Stmt::ObjCArrayLiteralClass:
9599 case Stmt::ObjCBoolLiteralExprClass:
9600 case Stmt::ObjCBoxedExprClass:
9601 case Stmt::ObjCDictionaryLiteralClass:
9602 case Stmt::ObjCEncodeExprClass:
9603 case Stmt::ObjCIvarRefExprClass:
9604 case Stmt::ObjCMessageExprClass:
9605 case Stmt::ObjCPropertyRefExprClass:
9606 case Stmt::ObjCStringLiteralClass:
9607 case Stmt::ObjCSubscriptRefExprClass:
9608 case Stmt::ParenExprClass:
9609 case Stmt::StringLiteralClass:
9610 case Stmt::UnaryOperatorClass:
9617static std::pair<QualType, StringRef>
9623 StringRef Name = UserTy->getDecl()->getName();
9624 QualType CastTy = llvm::StringSwitch<QualType>(Name)
9625 .Case(
"CFIndex", Context.getNSIntegerType())
9626 .Case(
"NSInteger", Context.getNSIntegerType())
9627 .Case(
"NSUInteger", Context.getNSUIntegerType())
9628 .Case(
"SInt32", Context.IntTy)
9629 .Case(
"UInt32", Context.UnsignedIntTy)
9633 return std::make_pair(CastTy, Name);
9635 TyTy = UserTy->desugar();
9639 if (
const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9649 StringRef TrueName, FalseName;
9652 Context, CO->getTrueExpr()->getType(), CO->getTrueExpr());
9654 Context, CO->getFalseExpr()->getType(), CO->getFalseExpr());
9656 if (TrueTy == FalseTy)
9657 return std::make_pair(TrueTy, TrueName);
9658 else if (TrueTy.
isNull())
9659 return std::make_pair(FalseTy, FalseName);
9660 else if (FalseTy.
isNull())
9661 return std::make_pair(TrueTy, TrueName);
9664 return std::make_pair(
QualType(), StringRef());
9683 From = VecTy->getElementType();
9685 To = VecTy->getElementType();
9696 diag::warn_format_conversion_argument_type_mismatch_signedness,
9700 diag::warn_format_conversion_argument_type_mismatch, Loc)) {
9707bool CheckPrintfHandler::checkFormatExpr(
9709 unsigned SpecifierLen,
const Expr *E) {
9720 while (
const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9724 if (
const OverflowBehaviorType *OBT =
9725 dyn_cast<OverflowBehaviorType>(
ExprTy.getCanonicalType()))
9726 ExprTy = OBT->getUnderlyingType();
9731 if (
ExprTy->canDecayToPointerType())
9740 getSpecifierRange(StartSpecifier, SpecifierLen);
9742 llvm::raw_svector_ostream os(FSString);
9744 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_bool_as_character)
9753 ExprTy->isObjCObjectPointerType()) {
9755 getSpecifierRange(StartSpecifier, SpecifierLen);
9756 EmitFormatDiagnostic(S.
PDiag(diag::warn_format_P_with_objc_pointer),
9761 if (CheckUnsupportedType(AT, E, StartSpecifier, SpecifierLen))
9769 if (
Match == ArgType::Match)
9773 assert(
Match != ArgType::NoMatchPromotionTypeConfusion);
9782 E = ICE->getSubExpr();
9792 if (OrigMatch == ArgType::NoMatchSignedness &&
9793 ImplicitMatch != ArgType::NoMatchSignedness)
9800 if (ImplicitMatch == ArgType::Match)
9818 if (
Match == ArgType::MatchPromotion)
9822 if (
Match == ArgType::MatchPromotion) {
9826 ImplicitMatch != ArgType::NoMatchPromotionTypeConfusion &&
9827 ImplicitMatch != ArgType::NoMatchTypeConfusion)
9831 if (ImplicitMatch == ArgType::NoMatchPedantic ||
9832 ImplicitMatch == ArgType::NoMatchTypeConfusion)
9833 Match = ImplicitMatch;
9834 assert(
Match != ArgType::MatchPromotion);
9837 bool IsEnum =
false;
9838 bool IsScopedEnum =
false;
9840 if (
const auto *ED =
ExprTy->getAsEnumDecl()) {
9841 IntendedTy = ED->getIntegerType();
9842 if (!ED->isScoped()) {
9848 IsScopedEnum =
true;
9855 if (isObjCContext() &&
9857 if (
ExprTy->isIntegralOrUnscopedEnumerationType() &&
9866 const llvm::APInt &
V = IL->getValue();
9876 if (TD->getUnderlyingType() == IntendedTy)
9886 bool ShouldNotPrintDirectly =
false;
9887 StringRef CastTyName;
9890 std::tie(CastTy, CastTyName) =
9896 if (!IsScopedEnum &&
9897 (CastTyName ==
"NSInteger" || CastTyName ==
"NSUInteger") &&
9901 IntendedTy = CastTy;
9902 ShouldNotPrintDirectly =
true;
9907 PrintfSpecifier fixedFS = FS;
9914 llvm::raw_svector_ostream os(buf);
9917 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9919 if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
9925 llvm_unreachable(
"expected non-matching");
9927 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
9930 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9933 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9936 Diag = diag::warn_format_conversion_argument_type_mismatch;
9957 llvm::raw_svector_ostream CastFix(CastBuf);
9958 CastFix << (S.
LangOpts.CPlusPlus ?
"static_cast<" :
"(");
9960 CastFix << (S.
LangOpts.CPlusPlus ?
">" :
")");
9966 if ((IntendedMatch != ArgType::Match) || ShouldNotPrintDirectly)
9971 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9993 if (ShouldNotPrintDirectly && !IsScopedEnum) {
9999 Name = TypedefTy->getDecl()->getName();
10003 ? diag::warn_format_argument_needs_cast_pedantic
10004 : diag::warn_format_argument_needs_cast;
10005 EmitFormatDiagnostic(S.
PDiag(
Diag) << Name << IntendedTy << IsEnum
10016 ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10017 : diag::warn_format_conversion_argument_type_mismatch;
10019 EmitFormatDiagnostic(
10027 getSpecifierRange(StartSpecifier, SpecifierLen);
10031 bool EmitTypeMismatch =
false;
10035 bool EmitOSLogError =
false;
10044 llvm_unreachable(
"expected non-matching");
10046 Diag = diag::warn_format_conversion_argument_type_mismatch_signedness;
10049 Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
10052 Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
10056 Diag = diag::warn_format_conversion_argument_type_mismatch;
10060 if (!EmitOSLogError)
10061 EmitFormatDiagnostic(
10070 EmitTypeMismatch =
true;
10074 EmitOSLogError =
true;
10076 EmitFormatDiagnostic(
10077 S.
PDiag(diag::warn_non_pod_vararg_with_format_string)
10078 << S.
getLangOpts().CPlusPlus11 << ExprTy << CallType
10082 checkForCStrMembers(AT, E);
10088 EmitTypeMismatch =
true;
10089 else if (
ExprTy->isObjCObjectType())
10090 EmitFormatDiagnostic(
10091 S.
PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
10092 << S.
getLangOpts().CPlusPlus11 << ExprTy << CallType
10105 if (EmitOSLogError)
10106 EmitFormatDiagnostic(
10107 S.
PDiag(diag::err_format_conversion_argument_type_mismatch)
10112 if (EmitTypeMismatch) {
10118 EmitFormatDiagnostic(
10119 S.
PDiag(diag::warn_format_conversion_argument_type_mismatch)
10125 assert(FirstDataArg + FS.
getArgIndex() < CheckedVarArgs.size() &&
10126 "format string specifier index out of range");
10127 CheckedVarArgs[FirstDataArg + FS.
getArgIndex()] =
true;
10137class CheckScanfHandler :
public CheckFormatHandler {
10139 CheckScanfHandler(Sema &s,
const FormatStringLiteral *fexpr,
10141 unsigned firstDataArg,
unsigned numDataArgs,
10143 ArrayRef<const Expr *> Args,
unsigned formatIdx,
10145 llvm::SmallBitVector &CheckedVarArgs,
10146 UncoveredArgHandler &UncoveredArg)
10147 : CheckFormatHandler(s, fexpr, origFormatExpr,
type, firstDataArg,
10148 numDataArgs, beg, APK, Args, formatIdx,
10149 inFunctionCall, CallType, CheckedVarArgs,
10152 bool HandleScanfSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
10153 const char *startSpecifier,
10154 unsigned specifierLen)
override;
10157 HandleInvalidScanfConversionSpecifier(
const analyze_scanf::ScanfSpecifier &FS,
10158 const char *startSpecifier,
10159 unsigned specifierLen)
override;
10161 void HandleIncompleteScanList(
const char *start,
const char *end)
override;
10166void CheckScanfHandler::HandleIncompleteScanList(
const char *start,
10168 EmitFormatDiagnostic(S.
PDiag(diag::warn_scanf_scanlist_incomplete),
10169 getLocationOfByte(end),
true,
10170 getSpecifierRange(start, end - start));
10173bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
10175 unsigned specifierLen) {
10179 return HandleInvalidConversionSpecifier(
10184bool CheckScanfHandler::HandleScanfSpecifier(
10186 unsigned specifierLen) {
10196 atFirstArg =
false;
10199 HandlePositionalNonpositionalArgs(getLocationOfByte(CS.
getStart()),
10200 startSpecifier, specifierLen);
10211 EmitFormatDiagnostic(S.
PDiag(diag::warn_scanf_nonzero_width),
10212 getLocationOfByte(Amt.
getStart()),
10226 if (argIndex < NumDataArgs) {
10230 CoveredArgs.set(argIndex);
10236 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10237 diag::warn_format_nonsensical_length);
10239 HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
10241 HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
10242 diag::warn_format_non_standard_conversion_spec);
10245 HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
10248 if (!HasFormatArguments())
10251 if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
10255 const Expr *Ex = getDataArg(argIndex);
10265 if (CheckUnsupportedType(AT, Ex, startSpecifier, specifierLen))
10276 ScanfSpecifier fixedFS = FS;
10281 Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
10283 ? diag::warn_format_conversion_argument_type_mismatch_signedness
10284 : diag::warn_format_conversion_argument_type_mismatch;
10289 llvm::raw_svector_ostream os(buf);
10292 EmitFormatDiagnostic(
10297 getSpecifierRange(startSpecifier, specifierLen),
10299 getSpecifierRange(startSpecifier, specifierLen), os.str()));
10306 getSpecifierRange(startSpecifier, specifierLen));
10316 const Expr *FmtExpr,
bool InFunctionCall) {
10317 bool HadError =
false;
10318 auto FmtIter = FmtArgs.begin(), FmtEnd = FmtArgs.end();
10319 auto RefIter = RefArgs.begin(), RefEnd = RefArgs.end();
10320 while (FmtIter < FmtEnd && RefIter < RefEnd) {
10332 for (; FmtIter < FmtEnd; ++FmtIter) {
10336 if (FmtIter->getPosition() < RefIter->getPosition())
10340 if (FmtIter->getPosition() > RefIter->getPosition())
10344 !FmtIter->VerifyCompatible(S, *RefIter, FmtExpr, InFunctionCall);
10348 RefIter = std::find_if(RefIter + 1, RefEnd, [=](
const auto &Arg) {
10349 return Arg.getPosition() != RefIter->getPosition();
10353 if (FmtIter < FmtEnd) {
10354 CheckFormatHandler::EmitFormatDiagnostic(
10355 S, InFunctionCall, FmtExpr,
10356 S.
PDiag(diag::warn_format_cmp_specifier_arity) << 1,
10357 FmtExpr->
getBeginLoc(),
false, FmtIter->getSourceRange());
10358 HadError = S.
Diag(Ref->
getBeginLoc(), diag::note_format_cmp_with) << 1;
10359 }
else if (RefIter < RefEnd) {
10360 CheckFormatHandler::EmitFormatDiagnostic(
10361 S, InFunctionCall, FmtExpr,
10362 S.
PDiag(diag::warn_format_cmp_specifier_arity) << 0,
10365 << 1 << RefIter->getSourceRange();
10371 Sema &S,
const FormatStringLiteral *FExpr,
10376 llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg,
10377 bool IgnoreStringsWithoutSpecifiers) {
10379 if (!FExpr->isAscii() && !FExpr->isUTF8()) {
10380 CheckFormatHandler::EmitFormatDiagnostic(
10381 S, inFunctionCall, Args[format_idx],
10382 S.
PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
10388 StringRef StrRef = FExpr->getString();
10389 const char *Str = StrRef.data();
10393 assert(
T &&
"String literal not of constant array type!");
10394 size_t TypeSize =
T->getZExtSize();
10395 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
10396 const unsigned numDataArgs = Args.size() - firstDataArg;
10398 if (IgnoreStringsWithoutSpecifiers &&
10405 if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains(
'\0')) {
10406 CheckFormatHandler::EmitFormatDiagnostic(
10407 S, inFunctionCall, Args[format_idx],
10408 S.
PDiag(diag::warn_printf_format_string_not_null_terminated),
10409 FExpr->getBeginLoc(),
10415 if (StrLen == 0 && numDataArgs > 0) {
10416 CheckFormatHandler::EmitFormatDiagnostic(
10417 S, inFunctionCall, Args[format_idx],
10418 S.
PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
10429 if (ReferenceFormatString ==
nullptr) {
10430 CheckPrintfHandler H(S, FExpr, OrigFormatExpr,
Type, firstDataArg,
10431 numDataArgs, IsObjC, Str, APK, Args, format_idx,
10432 inFunctionCall, CallType, CheckedVarArgs,
10439 H.DoneProcessing();
10442 Type, ReferenceFormatString, FExpr->getFormatString(),
10443 inFunctionCall ?
nullptr : Args[format_idx]);
10446 CheckScanfHandler H(S, FExpr, OrigFormatExpr,
Type, firstDataArg,
10447 numDataArgs, Str, APK, Args, format_idx, inFunctionCall,
10448 CallType, CheckedVarArgs, UncoveredArg);
10452 H.DoneProcessing();
10468 FormatStringLiteral RefLit = AuthoritativeFormatString;
10469 FormatStringLiteral TestLit = TestedFormatString;
10471 bool DiagAtStringLiteral;
10472 if (FunctionCallArg) {
10473 Arg = FunctionCallArg;
10474 DiagAtStringLiteral =
false;
10476 Arg = TestedFormatString;
10477 DiagAtStringLiteral =
true;
10479 if (DecomposePrintfHandler::GetSpecifiers(*
this, &RefLit,
10480 AuthoritativeFormatString,
Type,
10481 IsObjC,
true, RefArgs) &&
10482 DecomposePrintfHandler::GetSpecifiers(*
this, &TestLit, Arg,
Type, IsObjC,
10483 DiagAtStringLiteral, FmtArgs)) {
10485 TestedFormatString, FmtArgs, Arg,
10486 DiagAtStringLiteral);
10499 FormatStringLiteral RefLit = Str;
10503 if (!DecomposePrintfHandler::GetSpecifiers(*
this, &RefLit, Str,
Type, IsObjC,
10512 bool HadError =
false;
10513 auto Iter = Args.begin();
10514 auto End = Args.end();
10515 while (Iter != End) {
10516 const auto &FirstInGroup = *Iter;
10518 Iter != End && Iter->getPosition() == FirstInGroup.getPosition();
10520 HadError |= !Iter->VerifyCompatible(*
this, FirstInGroup, Str,
true);
10529 const char *Str = StrRef.data();
10532 assert(
T &&
"String literal not of constant array type!");
10533 size_t TypeSize =
T->getZExtSize();
10534 size_t StrLen = std::min(std::max(TypeSize,
size_t(1)) - 1, StrRef.size());
10544 switch (AbsFunction) {
10548 case Builtin::BI__builtin_abs:
10549 return Builtin::BI__builtin_labs;
10550 case Builtin::BI__builtin_labs:
10551 return Builtin::BI__builtin_llabs;
10552 case Builtin::BI__builtin_llabs:
10555 case Builtin::BI__builtin_fabsf:
10556 return Builtin::BI__builtin_fabs;
10557 case Builtin::BI__builtin_fabs:
10558 return Builtin::BI__builtin_fabsl;
10559 case Builtin::BI__builtin_fabsl:
10562 case Builtin::BI__builtin_cabsf:
10563 return Builtin::BI__builtin_cabs;
10564 case Builtin::BI__builtin_cabs:
10565 return Builtin::BI__builtin_cabsl;
10566 case Builtin::BI__builtin_cabsl:
10569 case Builtin::BIabs:
10570 return Builtin::BIlabs;
10571 case Builtin::BIlabs:
10572 return Builtin::BIllabs;
10573 case Builtin::BIllabs:
10576 case Builtin::BIfabsf:
10577 return Builtin::BIfabs;
10578 case Builtin::BIfabs:
10579 return Builtin::BIfabsl;
10580 case Builtin::BIfabsl:
10583 case Builtin::BIcabsf:
10584 return Builtin::BIcabs;
10585 case Builtin::BIcabs:
10586 return Builtin::BIcabsl;
10587 case Builtin::BIcabsl:
10594 unsigned AbsType) {
10616 unsigned AbsFunctionKind) {
10617 unsigned BestKind = 0;
10618 uint64_t ArgSize = Context.getTypeSize(ArgType);
10619 for (
unsigned Kind = AbsFunctionKind; Kind != 0;
10622 if (Context.getTypeSize(ParamType) >= ArgSize) {
10625 else if (Context.hasSameType(ParamType, ArgType)) {
10641 if (
T->isIntegralOrEnumerationType())
10643 if (
T->isRealFloatingType())
10645 if (
T->isAnyComplexType())
10648 llvm_unreachable(
"Type not integer, floating, or complex");
10655 switch (ValueKind) {
10660 case Builtin::BI__builtin_fabsf:
10661 case Builtin::BI__builtin_fabs:
10662 case Builtin::BI__builtin_fabsl:
10663 case Builtin::BI__builtin_cabsf:
10664 case Builtin::BI__builtin_cabs:
10665 case Builtin::BI__builtin_cabsl:
10666 return Builtin::BI__builtin_abs;
10667 case Builtin::BIfabsf:
10668 case Builtin::BIfabs:
10669 case Builtin::BIfabsl:
10670 case Builtin::BIcabsf:
10671 case Builtin::BIcabs:
10672 case Builtin::BIcabsl:
10673 return Builtin::BIabs;
10679 case Builtin::BI__builtin_abs:
10680 case Builtin::BI__builtin_labs:
10681 case Builtin::BI__builtin_llabs:
10682 case Builtin::BI__builtin_cabsf:
10683 case Builtin::BI__builtin_cabs:
10684 case Builtin::BI__builtin_cabsl:
10685 return Builtin::BI__builtin_fabsf;
10686 case Builtin::BIabs:
10687 case Builtin::BIlabs:
10688 case Builtin::BIllabs:
10689 case Builtin::BIcabsf:
10690 case Builtin::BIcabs:
10691 case Builtin::BIcabsl:
10692 return Builtin::BIfabsf;
10698 case Builtin::BI__builtin_abs:
10699 case Builtin::BI__builtin_labs:
10700 case Builtin::BI__builtin_llabs:
10701 case Builtin::BI__builtin_fabsf:
10702 case Builtin::BI__builtin_fabs:
10703 case Builtin::BI__builtin_fabsl:
10704 return Builtin::BI__builtin_cabsf;
10705 case Builtin::BIabs:
10706 case Builtin::BIlabs:
10707 case Builtin::BIllabs:
10708 case Builtin::BIfabsf:
10709 case Builtin::BIfabs:
10710 case Builtin::BIfabsl:
10711 return Builtin::BIcabsf;
10714 llvm_unreachable(
"Unable to convert function");
10725 case Builtin::BI__builtin_abs:
10726 case Builtin::BI__builtin_fabs:
10727 case Builtin::BI__builtin_fabsf:
10728 case Builtin::BI__builtin_fabsl:
10729 case Builtin::BI__builtin_labs:
10730 case Builtin::BI__builtin_llabs:
10731 case Builtin::BI__builtin_cabs:
10732 case Builtin::BI__builtin_cabsf:
10733 case Builtin::BI__builtin_cabsl:
10734 case Builtin::BIabs:
10735 case Builtin::BIlabs:
10736 case Builtin::BIllabs:
10737 case Builtin::BIfabs:
10738 case Builtin::BIfabsf:
10739 case Builtin::BIfabsl:
10740 case Builtin::BIcabs:
10741 case Builtin::BIcabsf:
10742 case Builtin::BIcabsl:
10745 llvm_unreachable(
"Unknown Builtin type");
10751 unsigned AbsKind,
QualType ArgType) {
10752 bool EmitHeaderHint =
true;
10753 const char *HeaderName =
nullptr;
10754 std::string FunctionName;
10755 if (S.
getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10756 FunctionName =
"std::abs";
10757 if (ArgType->isIntegralOrEnumerationType()) {
10758 HeaderName =
"cstdlib";
10759 }
else if (ArgType->isRealFloatingType()) {
10760 HeaderName =
"cmath";
10762 llvm_unreachable(
"Invalid Type");
10768 R.suppressDiagnostics();
10771 for (
const auto *I : R) {
10774 FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10776 FDecl = dyn_cast<FunctionDecl>(I);
10791 EmitHeaderHint =
false;
10803 R.suppressDiagnostics();
10806 if (R.isSingleResult()) {
10807 FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10809 EmitHeaderHint =
false;
10813 }
else if (!R.empty()) {
10819 S.
Diag(Loc, diag::note_replace_abs_function)
10825 if (!EmitHeaderHint)
10828 S.
Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10832template <std::
size_t StrLen>
10834 const char (&Str)[StrLen]) {
10847 auto MatchesAny = [&](std::initializer_list<llvm::StringRef> names) {
10848 return llvm::is_contained(names, calleeName);
10853 return MatchesAny({
"__builtin_nan",
"__builtin_nanf",
"__builtin_nanl",
10854 "__builtin_nanf16",
"__builtin_nanf128"});
10856 return MatchesAny({
"__builtin_inf",
"__builtin_inff",
"__builtin_infl",
10857 "__builtin_inff16",
"__builtin_inff128"});
10859 llvm_unreachable(
"unknown MathCheck");
10863 if (FDecl->
getName() !=
"infinity")
10866 if (
const CXXMethodDecl *MDecl = dyn_cast<CXXMethodDecl>(FDecl)) {
10868 if (RDecl->
getName() !=
"numeric_limits")
10885 if (FPO.getNoHonorNaNs() &&
10888 Diag(
Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10889 << 1 << 0 <<
Call->getSourceRange();
10893 if (FPO.getNoHonorInfs() &&
10897 Diag(
Call->getBeginLoc(), diag::warn_fp_nan_inf_when_disabled)
10898 << 0 << 0 <<
Call->getSourceRange();
10902void Sema::CheckAbsoluteValueFunction(
const CallExpr *
Call,
10904 if (
Call->getNumArgs() != 1)
10909 if (AbsKind == 0 && !IsStdAbs)
10912 QualType ArgType =
Call->getArg(0)->IgnoreParenImpCasts()->getType();
10913 QualType ParamType =
Call->getArg(0)->getType();
10918 std::string FunctionName =
10919 IsStdAbs ?
"std::abs" :
Context.BuiltinInfo.getName(AbsKind);
10920 Diag(
Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10921 Diag(
Call->getExprLoc(), diag::note_remove_abs)
10956 if (ArgValueKind == ParamValueKind) {
10957 if (
Context.getTypeSize(ArgType) <=
Context.getTypeSize(ParamType))
10961 Diag(
Call->getExprLoc(), diag::warn_abs_too_small)
10962 << FDecl << ArgType << ParamType;
10964 if (NewAbsKind == 0)
10968 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10977 if (NewAbsKind == 0)
10980 Diag(
Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10981 << FDecl << ParamValueKind << ArgValueKind;
10984 Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10990 if (!
Call || !FDecl)
return;
10994 if (
Call->getExprLoc().isMacroID())
return;
10997 if (
Call->getNumArgs() != 2)
return;
11000 if (!ArgList)
return;
11001 if (ArgList->size() != 1)
return;
11004 const auto& TA = ArgList->
get(0);
11006 QualType ArgType = TA.getAsType();
11010 auto IsLiteralZeroArg = [](
const Expr* E) ->
bool {
11011 const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
11012 if (!MTE)
return false;
11013 const auto *
Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
11014 if (!
Num)
return false;
11015 if (
Num->getValue() != 0)
return false;
11019 const Expr *FirstArg =
Call->getArg(0);
11020 const Expr *SecondArg =
Call->getArg(1);
11021 const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
11022 const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
11025 if (IsFirstArgZero == IsSecondArgZero)
return;
11030 SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
11032 Diag(
Call->getExprLoc(), diag::warn_max_unsigned_zero)
11033 << IsFirstArgZero <<
Call->getCallee()->getSourceRange() << ZeroRange;
11036 SourceRange RemovalRange;
11037 if (IsFirstArgZero) {
11038 RemovalRange = SourceRange(FirstRange.
getBegin(),
11045 Diag(
Call->getExprLoc(), diag::note_remove_max_call)
11060 const auto *Size = dyn_cast<BinaryOperator>(E);
11065 if (!Size->isComparisonOp() && !Size->isLogicalOp())
11069 S.
Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
11070 << SizeRange << FnName;
11071 S.
Diag(FnLoc, diag::note_memsize_comparison_paren)
11076 S.
Diag(SizeRange.
getBegin(), diag::note_memsize_comparison_cast_silence)
11087 bool &IsContained) {
11089 const Type *Ty =
T->getBaseElementTypeUnsafe();
11090 IsContained =
false;
11103 for (
auto *FD : RD->
fields()) {
11107 IsContained =
true;
11108 return ContainedRD;
11116 if (
const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
11117 if (Unary->getKind() == UETT_SizeOf)
11126 if (!
SizeOf->isArgumentType())
11127 return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
11134 return SizeOf->getTypeOfArgument();
11140struct SearchNonTrivialToInitializeField
11143 DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
11145 SearchNonTrivialToInitializeField(
const Expr *E, Sema &S) : E(E), S(S) {}
11148 SourceLocation SL) {
11149 if (
const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11150 asDerived().visitArray(PDIK, AT, SL);
11154 Super::visitWithKind(PDIK, FT, SL);
11157 void visitARCStrong(QualType FT, SourceLocation SL) {
11160 void visitARCWeak(QualType FT, SourceLocation SL) {
11163 void visitStruct(QualType FT, SourceLocation SL) {
11168 const ArrayType *AT, SourceLocation SL) {
11169 visit(getContext().getBaseElementType(AT), SL);
11171 void visitTrivial(QualType FT, SourceLocation SL) {}
11173 static void diag(QualType RT,
const Expr *E, Sema &S) {
11174 SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
11183struct SearchNonTrivialToCopyField
11185 using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
11187 SearchNonTrivialToCopyField(
const Expr *E, Sema &S) : E(E), S(S) {}
11190 SourceLocation SL) {
11191 if (
const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
11192 asDerived().visitArray(PCK, AT, SL);
11196 Super::visitWithKind(PCK, FT, SL);
11199 void visitARCStrong(QualType FT, SourceLocation SL) {
11202 void visitARCWeak(QualType FT, SourceLocation SL) {
11205 void visitPtrAuth(QualType FT, SourceLocation SL) {
11208 void visitStruct(QualType FT, SourceLocation SL) {
11213 SourceLocation SL) {
11214 visit(getContext().getBaseElementType(AT), SL);
11217 SourceLocation SL) {}
11218 void visitTrivial(QualType FT, SourceLocation SL) {}
11219 void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
11221 static void diag(QualType RT,
const Expr *E, Sema &S) {
11222 SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
11237 if (
const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
11238 if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
11271 if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
11274 const Expr *SizeArg =
11275 Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
11277 auto isLiteralZero = [](
const Expr *E) {
11287 if (isLiteralZero(SizeArg) &&
11294 if (BId == Builtin::BIbzero ||
11297 S.
Diag(DiagLoc, diag::warn_suspicious_bzero_size);
11298 S.
Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
11299 }
else if (!isLiteralZero(
Call->getArg(1)->IgnoreImpCasts())) {
11300 S.
Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
11301 S.
Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
11309 if (BId == Builtin::BImemset &&
11313 S.
Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
11314 S.
Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
11319void Sema::CheckMemaccessArguments(
const CallExpr *
Call,
11326 unsigned ExpectedNumArgs =
11327 (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
11328 if (
Call->getNumArgs() < ExpectedNumArgs)
11331 unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
11332 BId == Builtin::BIstrndup ? 1 : 2);
11334 (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
11338 Call->getBeginLoc(),
Call->getRParenLoc()))
11350 QualType FirstArgTy =
Call->getArg(0)->IgnoreParenImpCasts()->getType();
11351 if (BId == Builtin::BIbzero && !FirstArgTy->
getAs<PointerType>())
11354 for (
unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
11358 QualType DestTy = Dest->
getType();
11359 QualType PointeeTy;
11360 if (
const PointerType *DestPtrTy = DestTy->
getAs<PointerType>()) {
11372 if (CheckSizeofMemaccessArgument(LenExpr, Dest, FnName))
11378 if (SizeOfArgTy != QualType()) {
11380 Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
11382 PDiag(diag::warn_sizeof_pointer_type_memaccess)
11383 << FnName << SizeOfArgTy << ArgIdx
11390 PointeeTy = DestTy;
11393 if (PointeeTy == QualType())
11398 if (
const CXXRecordDecl *ContainedRD =
11401 unsigned OperationType = 0;
11402 const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
11405 if (ArgIdx != 0 || IsCmp) {
11406 if (BId == Builtin::BImemcpy)
11408 else if(BId == Builtin::BImemmove)
11415 PDiag(diag::warn_dyn_class_memaccess)
11416 << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
11417 << IsContained << ContainedRD << OperationType
11418 <<
Call->getCallee()->getSourceRange());
11420 BId != Builtin::BImemset)
11423 PDiag(diag::warn_arc_object_memaccess)
11424 << ArgIdx << FnName << PointeeTy
11425 <<
Call->getCallee()->getSourceRange());
11432 bool NonTriviallyCopyableCXXRecord =
11436 if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11439 PDiag(diag::warn_cstruct_memaccess)
11440 << ArgIdx << FnName << PointeeTy << 0);
11441 SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *
this);
11442 }
else if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
11443 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11447 PDiag(diag::warn_cxxstruct_memaccess)
11448 << FnName << PointeeTy);
11449 }
else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11452 PDiag(diag::warn_cstruct_memaccess)
11453 << ArgIdx << FnName << PointeeTy << 1);
11454 SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *
this);
11455 }
else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
11456 NonTriviallyCopyableCXXRecord && ArgIdx == 0) {
11460 PDiag(diag::warn_cxxstruct_memaccess)
11461 << FnName << PointeeTy);
11470 PDiag(diag::note_bad_memaccess_silence)
11476bool Sema::CheckSizeofMemaccessArgument(
const Expr *LenExpr,
const Expr *Dest,
11478 llvm::FoldingSetNodeID SizeOfArgID;
11484 if (
Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
11487 QualType DestTy = Dest->
getType();
11488 const PointerType *DestPtrTy = DestTy->
getAs<PointerType>();
11494 if (SizeOfArgID == llvm::FoldingSetNodeID())
11497 llvm::FoldingSetNodeID DestID;
11499 if (DestID == SizeOfArgID) {
11502 unsigned ActionIdx = 0;
11503 StringRef ReadableName = FnName->
getName();
11505 if (
const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest);
11506 UnaryOp && UnaryOp->getOpcode() == UO_AddrOf)
11515 SourceLocation SL = SizeOfArg->
getExprLoc();
11530 PDiag(diag::warn_sizeof_pointer_expr_memaccess)
11531 << ReadableName << PointeeTy << DestTy << DSR
11534 PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
11535 << ActionIdx << SSR);
11571 if (CAT->getZExtSize() <= 1)
11579void Sema::CheckStrlcpycatArguments(
const CallExpr *
Call,
11583 unsigned NumArgs =
Call->getNumArgs();
11584 if ((NumArgs != 3) && (NumArgs != 4))
11589 const Expr *CompareWithSrc =
nullptr;
11592 Call->getBeginLoc(),
Call->getRParenLoc()))
11597 CompareWithSrc = Ex;
11600 if (
const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
11601 if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
11602 SizeCall->getNumArgs() == 1)
11607 if (!CompareWithSrc)
11614 const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
11618 const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
11619 if (!CompareWithSrcDRE ||
11623 const Expr *OriginalSizeArg =
Call->getArg(2);
11624 Diag(CompareWithSrcDRE->
getBeginLoc(), diag::warn_strlcpycat_wrong_size)
11631 const Expr *DstArg =
Call->getArg(0)->IgnoreParenImpCasts();
11635 SmallString<128> sizeString;
11636 llvm::raw_svector_ostream
OS(sizeString);
11641 Diag(OriginalSizeArg->
getBeginLoc(), diag::note_strlcpycat_wrong_size)
11648 if (
const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
11649 if (
const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
11650 return D1->getDecl() == D2->getDecl();
11655 if (
const CallExpr *CE = dyn_cast<CallExpr>(E)) {
11664void Sema::CheckStrncatArguments(
const CallExpr *CE,
11679 unsigned PatternType = 0;
11687 }
else if (
const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
11688 if (BE->getOpcode() == BO_Sub) {
11689 const Expr *L = BE->getLHS()->IgnoreParenCasts();
11690 const Expr *
R = BE->getRHS()->IgnoreParenCasts();
11701 if (PatternType == 0)
11717 QualType DstTy = DstArg->
getType();
11720 if (!isKnownSizeArray) {
11721 if (PatternType == 1)
11722 Diag(SL, diag::warn_strncat_wrong_size) << SR;
11724 Diag(SL, diag::warn_strncat_src_size) << SR;
11728 if (PatternType == 1)
11729 Diag(SL, diag::warn_strncat_large_size) << SR;
11731 Diag(SL, diag::warn_strncat_src_size) << SR;
11733 SmallString<128> sizeString;
11734 llvm::raw_svector_ostream
OS(sizeString);
11742 Diag(SL, diag::note_strncat_wrong_size)
11747void CheckFreeArgumentsOnLvalue(
Sema &S,
const std::string &CalleeName,
11756void CheckFreeArgumentsAddressof(
Sema &S,
const std::string &CalleeName,
11758 if (
const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->
getSubExpr())) {
11759 const Decl *D = Lvalue->getDecl();
11760 if (
const auto *DD = dyn_cast<DeclaratorDecl>(D)) {
11761 if (!DD->getType()->isReferenceType())
11762 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
11766 if (
const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->
getSubExpr()))
11767 return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
11768 Lvalue->getMemberDecl());
11771void CheckFreeArgumentsPlus(
Sema &S,
const std::string &CalleeName,
11773 const auto *Lambda = dyn_cast<LambdaExpr>(
11778 S.
Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11779 << CalleeName << 2 ;
11782void CheckFreeArgumentsStackArray(
Sema &S,
const std::string &CalleeName,
11784 const auto *Var = dyn_cast<VarDecl>(Lvalue->
getDecl());
11785 if (Var ==
nullptr)
11789 << CalleeName << 0 << Var;
11792void CheckFreeArgumentsCast(
Sema &S,
const std::string &CalleeName,
11795 llvm::raw_svector_ostream
OS(SizeString);
11798 if (Kind == clang::CK_BitCast &&
11799 !
Cast->getSubExpr()->getType()->isFunctionPointerType())
11801 if (Kind == clang::CK_IntegralToPointer &&
11803 Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11806 switch (
Cast->getCastKind()) {
11807 case clang::CK_BitCast:
11808 case clang::CK_IntegralToPointer:
11809 case clang::CK_FunctionToPointerDecay:
11818 S.
Diag(
Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11819 << CalleeName << 0 <<
OS.str();
11823void Sema::CheckFreeArguments(
const CallExpr *E) {
11824 const std::string CalleeName =
11829 if (
const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11831 case UnaryOperator::Opcode::UO_AddrOf:
11832 return CheckFreeArgumentsAddressof(*
this, CalleeName, UnaryExpr);
11833 case UnaryOperator::Opcode::UO_Plus:
11834 return CheckFreeArgumentsPlus(*
this, CalleeName, UnaryExpr);
11839 if (
const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11841 return CheckFreeArgumentsStackArray(*
this, CalleeName, Lvalue);
11843 if (
const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11844 Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11845 << CalleeName << 0 << Label->getLabel()->getIdentifier();
11851 << CalleeName << 1 ;
11856 if (
const auto *Cast = dyn_cast<CastExpr>(E->
getArg(0)))
11857 return CheckFreeArgumentsCast(*
this, CalleeName, Cast);
11861Sema::CheckReturnValExpr(
Expr *RetValExp,
QualType lhsType,
11870 Diag(ReturnLoc, diag::warn_null_ret)
11880 if (Op == OO_New || Op == OO_Array_New) {
11881 const FunctionProtoType *Proto
11885 Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11891 Diag(ReturnLoc, diag::err_wasm_table_art) << 1;
11896 if (
Context.getTargetInfo().getTriple().isPPC64())
11908 auto getCastAndLiteral = [&FPLiteral, &FPCast](
const Expr *L,
const Expr *R) {
11909 FPLiteral = dyn_cast<FloatingLiteral>(L->IgnoreParens());
11910 FPCast = dyn_cast<CastExpr>(R->IgnoreParens());
11911 return FPLiteral && FPCast;
11914 if (getCastAndLiteral(LHS, RHS) || getCastAndLiteral(RHS, LHS)) {
11920 llvm::APFloat TargetC = FPLiteral->
getValue();
11921 TargetC.convert(
Context.getFloatTypeSemantics(
QualType(SourceTy, 0)),
11922 llvm::APFloat::rmNearestTiesToEven, &Lossy);
11926 Diag(Loc, diag::warn_float_compare_literal)
11927 << (Opcode == BO_EQ) <<
QualType(SourceTy, 0)
11940 if (
const auto *DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11941 if (
const auto *DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11942 if (DRL->getDecl() == DRR->getDecl())
11950 if (
const auto *FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11951 if (FLL->isExact())
11953 }
else if (
const auto *FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11954 if (FLR->isExact())
11958 if (
const auto *
CL = dyn_cast<CallExpr>(LeftExprSansParen);
11959 CL &&
CL->getBuiltinCallee())
11962 if (
const auto *CR = dyn_cast<CallExpr>(RightExprSansParen);
11963 CR && CR->getBuiltinCallee())
11967 Diag(Loc, diag::warn_floatingpoint_eq)
11988 IntRange(
unsigned Width,
bool NonNegative)
11989 : Width(Width), NonNegative(NonNegative) {}
11992 unsigned valueBits()
const {
11993 return NonNegative ? Width : Width - 1;
11997 static IntRange forBoolType() {
11998 return IntRange(1,
true);
12002 static IntRange forValueOfType(ASTContext &
C, QualType
T) {
12003 return forValueOfCanonicalType(
C,
12008 static IntRange forValueOfCanonicalType(ASTContext &
C,
const Type *
T) {
12011 if (
const auto *VT = dyn_cast<VectorType>(
T))
12012 T = VT->getElementType().getTypePtr();
12013 if (
const auto *MT = dyn_cast<ConstantMatrixType>(
T))
12014 T = MT->getElementType().getTypePtr();
12015 if (
const auto *CT = dyn_cast<ComplexType>(
T))
12016 T = CT->getElementType().getTypePtr();
12017 if (
const auto *AT = dyn_cast<AtomicType>(
T))
12018 T = AT->getValueType().getTypePtr();
12019 if (
const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(
T))
12020 T = OBT->getUnderlyingType().getTypePtr();
12022 if (!
C.getLangOpts().CPlusPlus) {
12025 T = ED->getIntegerType().getDesugaredType(
C).getTypePtr();
12030 if (
Enum->isFixed()) {
12031 return IntRange(
C.getIntWidth(QualType(
T, 0)),
12032 !
Enum->getIntegerType()->isSignedIntegerType());
12035 unsigned NumPositive =
Enum->getNumPositiveBits();
12036 unsigned NumNegative =
Enum->getNumNegativeBits();
12038 if (NumNegative == 0)
12039 return IntRange(NumPositive,
true);
12041 return IntRange(std::max(NumPositive + 1, NumNegative),
12045 if (
const auto *EIT = dyn_cast<BitIntType>(
T))
12046 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12059 static IntRange forTargetOfCanonicalType(ASTContext &
C,
const Type *
T) {
12062 if (
const VectorType *VT = dyn_cast<VectorType>(
T))
12063 T = VT->getElementType().getTypePtr();
12064 if (
const auto *MT = dyn_cast<ConstantMatrixType>(
T))
12065 T = MT->getElementType().getTypePtr();
12066 if (
const ComplexType *CT = dyn_cast<ComplexType>(
T))
12067 T = CT->getElementType().getTypePtr();
12068 if (
const AtomicType *AT = dyn_cast<AtomicType>(
T))
12069 T = AT->getValueType().getTypePtr();
12071 T =
C.getCanonicalType(ED->getIntegerType()).getTypePtr();
12072 if (
const OverflowBehaviorType *OBT = dyn_cast<OverflowBehaviorType>(
T))
12073 T = OBT->getUnderlyingType().getTypePtr();
12075 if (
const auto *EIT = dyn_cast<BitIntType>(
T))
12076 return IntRange(EIT->getNumBits(), EIT->isUnsigned());
12085 static IntRange
join(IntRange L, IntRange R) {
12086 bool Unsigned = L.NonNegative &&
R.NonNegative;
12087 return IntRange(std::max(L.valueBits(),
R.valueBits()) + !
Unsigned,
12088 L.NonNegative &&
R.NonNegative);
12092 static IntRange bit_and(IntRange L, IntRange R) {
12093 unsigned Bits = std::max(L.Width,
R.Width);
12094 bool NonNegative =
false;
12095 if (L.NonNegative) {
12096 Bits = std::min(Bits, L.Width);
12097 NonNegative =
true;
12099 if (
R.NonNegative) {
12100 Bits = std::min(Bits,
R.Width);
12101 NonNegative =
true;
12103 return IntRange(Bits, NonNegative);
12107 static IntRange sum(IntRange L, IntRange R) {
12108 bool Unsigned = L.NonNegative &&
R.NonNegative;
12109 return IntRange(std::max(L.valueBits(),
R.valueBits()) + 1 + !
Unsigned,
12114 static IntRange difference(IntRange L, IntRange R) {
12118 bool CanWiden = !L.NonNegative || !
R.NonNegative;
12119 bool Unsigned = L.NonNegative &&
R.Width == 0;
12120 return IntRange(std::max(L.valueBits(),
R.valueBits()) + CanWiden +
12126 static IntRange product(IntRange L, IntRange R) {
12130 bool CanWiden = !L.NonNegative && !
R.NonNegative;
12131 bool Unsigned = L.NonNegative &&
R.NonNegative;
12132 return IntRange(L.valueBits() +
R.valueBits() + CanWiden + !
Unsigned,
12137 static IntRange rem(IntRange L, IntRange R) {
12141 return IntRange(std::min(L.valueBits(),
R.valueBits()) + !
Unsigned,
12149 if (value.isSigned() && value.isNegative())
12150 return IntRange(value.getSignificantBits(),
false);
12152 if (value.getBitWidth() > MaxWidth)
12153 value = value.trunc(MaxWidth);
12157 return IntRange(value.getActiveBits(),
true);
12161 unsigned MaxWidth) {
12162 if (result.
isInt())
12166 std::optional<IntRange> R =
12169 return std::nullopt;
12171 std::optional<IntRange> El =
12174 return std::nullopt;
12175 R = IntRange::join(*R, *El);
12183 return IntRange::join(R, I);
12195 return std::nullopt;
12201 Ty = AtomicRHS->getValueType();
12220 bool InConstantContext,
12221 bool Approximate) {
12239 if (
const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
12240 if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
12244 IntRange OutputTypeRange = IntRange::forValueOfType(
C,
GetExprType(CE));
12246 bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
12247 CE->getCastKind() == CK_BooleanToSignedIntegral;
12250 if (!isIntegerCast)
12251 return OutputTypeRange;
12254 C, CE->getSubExpr(), std::min(MaxWidth, OutputTypeRange.Width),
12255 InConstantContext, Approximate);
12257 return std::nullopt;
12260 if (SubRange->Width >= OutputTypeRange.Width)
12261 return OutputTypeRange;
12265 return IntRange(SubRange->Width,
12266 SubRange->NonNegative || OutputTypeRange.NonNegative);
12269 if (
const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12272 if (CO->getCond()->EvaluateAsBooleanCondition(CondResult,
C))
12274 C, CondResult ? CO->getTrueExpr() : CO->getFalseExpr(), MaxWidth,
12275 InConstantContext, Approximate);
12280 Expr *TrueExpr = CO->getTrueExpr();
12282 return std::nullopt;
12284 std::optional<IntRange> L =
12287 return std::nullopt;
12289 Expr *FalseExpr = CO->getFalseExpr();
12291 return std::nullopt;
12293 std::optional<IntRange> R =
12296 return std::nullopt;
12298 return IntRange::join(*L, *R);
12301 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
12302 IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
12304 switch (BO->getOpcode()) {
12306 llvm_unreachable(
"builtin <=> should have class type");
12317 return IntRange::forBoolType();
12346 Combine = IntRange::bit_and;
12354 = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
12355 if (I->getValue() == 1) {
12356 IntRange R = IntRange::forValueOfType(
C,
GetExprType(E));
12357 return IntRange(R.Width,
true);
12367 case BO_ShrAssign: {
12369 C, BO->getLHS(), MaxWidth, InConstantContext, Approximate);
12371 return std::nullopt;
12375 if (std::optional<llvm::APSInt> shift =
12376 BO->getRHS()->getIntegerConstantExpr(
C)) {
12377 if (shift->isNonNegative()) {
12378 if (shift->uge(L->Width))
12379 L->Width = (L->NonNegative ? 0 : 1);
12381 L->Width -= shift->getZExtValue();
12395 Combine = IntRange::sum;
12399 if (BO->getLHS()->getType()->isPointerType())
12402 Combine = IntRange::difference;
12407 Combine = IntRange::product;
12416 C, BO->getLHS(), opWidth, InConstantContext, Approximate);
12418 return std::nullopt;
12421 if (std::optional<llvm::APSInt> divisor =
12422 BO->getRHS()->getIntegerConstantExpr(
C)) {
12423 unsigned log2 = divisor->logBase2();
12424 if (
log2 >= L->Width)
12425 L->Width = (L->NonNegative ? 0 : 1);
12427 L->Width = std::min(L->Width -
log2, MaxWidth);
12435 C, BO->getRHS(), opWidth, InConstantContext, Approximate);
12437 return std::nullopt;
12439 return IntRange(L->Width, L->NonNegative && R->NonNegative);
12443 Combine = IntRange::rem;
12455 unsigned opWidth =
C.getIntWidth(
T);
12457 InConstantContext, Approximate);
12459 return std::nullopt;
12462 InConstantContext, Approximate);
12464 return std::nullopt;
12466 IntRange
C = Combine(*L, *R);
12467 C.NonNegative |=
T->isUnsignedIntegerOrEnumerationType();
12468 C.Width = std::min(
C.Width, MaxWidth);
12472 if (
const auto *UO = dyn_cast<UnaryOperator>(E)) {
12473 switch (UO->getOpcode()) {
12476 return IntRange::forBoolType();
12484 if (
GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12490 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12493 return std::nullopt;
12498 return IntRange(std::min(SubRange->Width + 1, MaxWidth),
false);
12502 if (
GetExprType(E)->hasUnsignedIntegerRepresentation()) {
12508 C, UO->getSubExpr(), MaxWidth, InConstantContext, Approximate);
12511 return std::nullopt;
12516 std::min(SubRange->Width + (
int)SubRange->NonNegative, MaxWidth),
12526 if (
const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
12530 if (
const Expr *SourceExpr = OVE->getSourceExpr())
12536 return IntRange(BitField->getBitWidthValue(),
12537 BitField->getType()->isUnsignedIntegerOrEnumerationType());
12540 return std::nullopt;
12546 bool InConstantContext,
12547 bool Approximate) {
12556 const llvm::fltSemantics &Src,
12557 const llvm::fltSemantics &Tgt) {
12558 llvm::APFloat truncated = value;
12561 truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
12562 truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
12564 return truncated.bitwiseIsEqual(value);
12573 const llvm::fltSemantics &Src,
12574 const llvm::fltSemantics &Tgt) {
12598 bool IsListInit =
false);
12613 return MacroName !=
"YES" && MacroName !=
"NO" &&
12614 MacroName !=
"true" && MacroName !=
"false";
12622 (!E->
getType()->isSignedIntegerType() ||
12637struct PromotedRange {
12639 llvm::APSInt PromotedMin;
12641 llvm::APSInt PromotedMax;
12643 PromotedRange(IntRange R,
unsigned BitWidth,
bool Unsigned) {
12645 PromotedMin = PromotedMax = llvm::APSInt(BitWidth,
Unsigned);
12646 else if (
R.Width >= BitWidth && !
Unsigned) {
12650 PromotedMin = llvm::APSInt::getMinValue(BitWidth,
Unsigned);
12651 PromotedMax = llvm::APSInt::getMaxValue(BitWidth,
Unsigned);
12653 PromotedMin = llvm::APSInt::getMinValue(
R.Width,
R.NonNegative)
12654 .extOrTrunc(BitWidth);
12655 PromotedMin.setIsUnsigned(
Unsigned);
12657 PromotedMax = llvm::APSInt::getMaxValue(
R.Width,
R.NonNegative)
12658 .extOrTrunc(BitWidth);
12659 PromotedMax.setIsUnsigned(
Unsigned);
12664 bool isContiguous()
const {
return PromotedMin <= PromotedMax; }
12674 InRangeFlag = 0x40,
12677 Min =
LE | InRangeFlag,
12678 InRange = InRangeFlag,
12679 Max =
GE | InRangeFlag,
12682 OnlyValue =
LE |
GE |
EQ | InRangeFlag,
12687 assert(
Value.getBitWidth() == PromotedMin.getBitWidth() &&
12688 Value.isUnsigned() == PromotedMin.isUnsigned());
12689 if (!isContiguous()) {
12690 assert(
Value.isUnsigned() &&
"discontiguous range for signed compare");
12691 if (
Value.isMinValue())
return Min;
12692 if (
Value.isMaxValue())
return Max;
12693 if (
Value >= PromotedMin)
return InRange;
12694 if (
Value <= PromotedMax)
return InRange;
12698 switch (llvm::APSInt::compareValues(
Value, PromotedMin)) {
12699 case -1:
return Less;
12700 case 0:
return PromotedMin == PromotedMax ? OnlyValue :
Min;
12702 switch (llvm::APSInt::compareValues(
Value, PromotedMax)) {
12703 case -1:
return InRange;
12704 case 0:
return Max;
12709 llvm_unreachable(
"impossible compare result");
12712 static std::optional<StringRef>
12714 if (Op == BO_Cmp) {
12716 if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
12718 if (R & EQ)
return StringRef(
"'std::strong_ordering::equal'");
12719 if (R & LTFlag)
return StringRef(
"'std::strong_ordering::less'");
12720 if (R & GTFlag)
return StringRef(
"'std::strong_ordering::greater'");
12721 return std::nullopt;
12728 }
else if (Op == BO_NE) {
12732 if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
12739 if (Op == BO_GE || Op == BO_LE)
12740 std::swap(TrueFlag, FalseFlag);
12743 return StringRef(
"true");
12745 return StringRef(
"false");
12746 return std::nullopt;
12753 while (
const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
12754 if (ICE->getCastKind() != CK_IntegralCast &&
12755 ICE->getCastKind() != CK_NoOp)
12757 E = ICE->getSubExpr();
12766 enum ConstantValueKind {
12771 if (
auto *BL = dyn_cast<CXXBoolLiteralExpr>(
Constant))
12772 return BL->getValue() ? ConstantValueKind::LiteralTrue
12773 : ConstantValueKind::LiteralFalse;
12774 return ConstantValueKind::Miscellaneous;
12779 const llvm::APSInt &
Value,
12780 bool RhsConstant) {
12796 if (
Constant->getType()->isEnumeralType() &&
12802 if (!OtherValueRange)
12807 OtherT = AT->getValueType();
12808 IntRange OtherTypeRange = IntRange::forValueOfType(S.
Context, OtherT);
12812 bool IsObjCSignedCharBool = S.
getLangOpts().ObjC &&
12818 bool OtherIsBooleanDespiteType =
12820 if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
12821 OtherTypeRange = *OtherValueRange = IntRange::forBoolType();
12825 PromotedRange OtherPromotedValueRange(*OtherValueRange,
Value.getBitWidth(),
12826 Value.isUnsigned());
12827 auto Cmp = OtherPromotedValueRange.compare(
Value);
12834 bool TautologicalTypeCompare =
false;
12836 PromotedRange OtherPromotedTypeRange(OtherTypeRange,
Value.getBitWidth(),
12837 Value.isUnsigned());
12838 auto TypeCmp = OtherPromotedTypeRange.compare(
Value);
12841 TautologicalTypeCompare =
true;
12849 if (!TautologicalTypeCompare && OtherValueRange->Width == 0)
12858 bool InRange =
Cmp & PromotedRange::InRangeFlag;
12864 if (
Other->refersToBitField() && InRange &&
Value == 0 &&
12865 Other->getType()->isUnsignedIntegerOrEnumerationType())
12866 TautologicalTypeCompare =
true;
12871 if (
const auto *DR = dyn_cast<DeclRefExpr>(
Constant))
12872 ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
12876 llvm::raw_svector_ostream OS(PrettySourceValue);
12878 OS <<
'\'' << *ED <<
"' (" <<
Value <<
")";
12879 }
else if (
auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
12880 Constant->IgnoreParenImpCasts())) {
12881 OS << (BL->getValue() ?
"YES" :
"NO");
12886 if (!TautologicalTypeCompare) {
12888 << RhsConstant << OtherValueRange->Width << OtherValueRange->NonNegative
12894 if (IsObjCSignedCharBool) {
12896 S.
PDiag(diag::warn_tautological_compare_objc_bool)
12897 << OS.str() << *
Result);
12904 if (!InRange ||
Other->isKnownToHaveBooleanValue()) {
12908 S.
PDiag(!InRange ? diag::warn_out_of_range_compare
12909 : diag::warn_tautological_bool_compare)
12911 << OtherIsBooleanDespiteType << *
Result
12918 ? diag::warn_unsigned_enum_always_true_comparison
12919 : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12920 : diag::warn_unsigned_always_true_comparison)
12921 : diag::warn_tautological_constant_compare;
12957 if (
T->isIntegralType(S.
Context)) {
12958 std::optional<llvm::APSInt> RHSValue =
12960 std::optional<llvm::APSInt> LHSValue =
12964 if (RHSValue && LHSValue)
12968 if ((
bool)RHSValue ^ (
bool)LHSValue) {
12970 const bool RhsConstant = (
bool)RHSValue;
12971 Expr *Const = RhsConstant ? RHS : LHS;
12973 const llvm::APSInt &
Value = RhsConstant ? *RHSValue : *LHSValue;
12982 if (!
T->hasUnsignedIntegerRepresentation()) {
12996 if (
const auto *TET = dyn_cast<TypeOfExprType>(LHS->
getType()))
12998 if (
const auto *TET = dyn_cast<TypeOfExprType>(RHS->
getType()))
13004 Expr *signedOperand, *unsignedOperand;
13007 "unsigned comparison between two signed integer expressions?");
13008 signedOperand = LHS;
13009 unsignedOperand = RHS;
13011 signedOperand = RHS;
13012 unsignedOperand = LHS;
13018 std::optional<IntRange> signedRange =
13030 if (signedRange->NonNegative)
13042 if (!unsignedRange)
13047 assert(unsignedRange->NonNegative &&
"unsigned range includes negative?");
13049 if (unsignedRange->Width < comparisonWidth)
13054 S.
PDiag(diag::warn_mixed_sign_comparison)
13073 if (
auto *BitfieldEnumDecl = BitfieldType->
getAsEnumDecl()) {
13078 !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
13079 BitfieldEnumDecl->getNumPositiveBits() > 0 &&
13080 BitfieldEnumDecl->getNumNegativeBits() == 0) {
13081 S.
Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
13082 << BitfieldEnumDecl;
13089 Init->isValueDependent() ||
13090 Init->isTypeDependent())
13093 Expr *OriginalInit =
Init->IgnoreParenImpCasts();
13103 const PreferredTypeAttr *PTAttr =
nullptr;
13105 PTAttr = Bitfield->
getAttr<PreferredTypeAttr>();
13107 ED = PTAttr->getType()->getAsEnumDecl();
13115 bool SignedEnum = ED->getNumNegativeBits() > 0;
13122 unsigned DiagID = 0;
13123 if (SignedEnum && !SignedBitfield) {
13126 ? diag::warn_unsigned_bitfield_assigned_signed_enum
13128 warn_preferred_type_unsigned_bitfield_assigned_signed_enum;
13129 }
else if (SignedBitfield && !SignedEnum &&
13130 ED->getNumPositiveBits() == FieldWidth) {
13133 ? diag::warn_signed_bitfield_enum_conversion
13134 : diag::warn_preferred_type_signed_bitfield_enum_conversion;
13137 S.
Diag(InitLoc, DiagID) << Bitfield << ED;
13142 << SignedEnum << TypeRange;
13144 S.
Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13151 unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
13152 ED->getNumNegativeBits())
13153 : ED->getNumPositiveBits();
13156 if (BitsNeeded > FieldWidth) {
13160 ? diag::warn_bitfield_too_small_for_enum
13161 : diag::warn_preferred_type_bitfield_too_small_for_enum;
13162 S.
Diag(InitLoc, DiagID) << Bitfield << ED;
13166 S.
Diag(PTAttr->getLocation(), diag::note_bitfield_preferred_type)
13176 unsigned OriginalWidth =
Value.getBitWidth();
13182 bool OneAssignedToOneBitBitfield = FieldWidth == 1 &&
Value == 1;
13183 if (OneAssignedToOneBitBitfield && !S.
LangOpts.CPlusPlus) {
13190 if (!
Value.isSigned() ||
Value.isNegative())
13191 if (
UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
13192 if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
13193 OriginalWidth =
Value.getSignificantBits();
13195 if (OriginalWidth <= FieldWidth)
13199 llvm::APSInt TruncatedValue =
Value.trunc(FieldWidth);
13203 TruncatedValue = TruncatedValue.extend(OriginalWidth);
13204 if (llvm::APSInt::isSameValue(
Value, TruncatedValue))
13208 std::string PrettyTrunc =
toString(TruncatedValue, 10);
13210 S.
Diag(InitLoc, OneAssignedToOneBitBitfield
13211 ? diag::warn_impcast_single_bit_bitield_precision_constant
13212 : diag::warn_impcast_bitfield_precision_constant)
13213 << PrettyValue << PrettyTrunc << OriginalInit->
getType()
13214 <<
Init->getSourceRange();
13251 bool PruneControlFlow =
false) {
13258 if (
T.hasAddressSpace())
13260 if (PruneControlFlow) {
13274 bool PruneControlFlow =
false) {
13281 bool IsBool =
T->isSpecificBuiltinType(BuiltinType::Bool);
13286 if (
const auto *UOp = dyn_cast<UnaryOperator>(InnerE))
13287 if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
13292 llvm::APFloat
Value(0.0);
13298 E, S.
Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
13303 diag::warn_impcast_float_integer, PruneWarnings);
13306 bool isExact =
false;
13309 T->hasUnsignedIntegerRepresentation());
13310 llvm::APFloat::opStatus
Result =
Value.convertToInteger(
13311 IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
13319 unsigned precision = llvm::APFloat::semanticsPrecision(
Value.getSemantics());
13320 precision = (precision * 59 + 195) / 196;
13321 Value.toString(PrettySourceValue, precision);
13325 E, S.
Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
13326 << PrettySourceValue);
13329 if (
Result == llvm::APFloat::opOK && isExact) {
13330 if (IsLiteral)
return;
13331 return DiagnoseImpCast(S, E,
T, CContext, diag::warn_impcast_float_integer,
13337 if (!IsBool &&
Result == llvm::APFloat::opInvalidOp)
13340 IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
13341 : diag::warn_impcast_float_to_integer_out_of_range,
13344 unsigned DiagID = 0;
13347 DiagID = diag::warn_impcast_literal_float_to_integer;
13348 }
else if (IntegerValue == 0) {
13349 if (
Value.isZero()) {
13351 diag::warn_impcast_float_integer, PruneWarnings);
13354 DiagID = diag::warn_impcast_float_to_integer_zero;
13356 if (IntegerValue.isUnsigned()) {
13357 if (!IntegerValue.isMaxValue()) {
13359 diag::warn_impcast_float_integer, PruneWarnings);
13362 if (!IntegerValue.isMaxSignedValue() &&
13363 !IntegerValue.isMinSignedValue()) {
13365 diag::warn_impcast_float_integer, PruneWarnings);
13369 DiagID = diag::warn_impcast_float_to_integer;
13374 PrettyTargetValue =
Value.isZero() ?
"false" :
"true";
13376 IntegerValue.toString(PrettyTargetValue);
13378 if (PruneWarnings) {
13381 << E->
getType() <<
T.getUnqualifiedType()
13382 << PrettySourceValue << PrettyTargetValue
13386 << E->
getType() <<
T.getUnqualifiedType() << PrettySourceValue
13395 "Must be compound assignment operation");
13406 ->getComputationResultType()
13413 if (ResultBT->isInteger())
13415 E->
getExprLoc(), diag::warn_impcast_float_integer);
13417 if (!ResultBT->isFloatingPoint())
13426 diag::warn_impcast_float_result_precision);
13431 if (!Range.Width)
return "0";
13433 llvm::APSInt ValueInRange =
Value;
13434 ValueInRange.setIsSigned(!Range.NonNegative);
13435 ValueInRange = ValueInRange.trunc(Range.Width);
13436 return toString(ValueInRange, 10);
13446 const Type *Source =
13448 if (
Target->isDependentType())
13451 const auto *FloatCandidateBT =
13452 dyn_cast<BuiltinType>(ToBool ? Source :
Target);
13453 const Type *BoolCandidateType = ToBool ?
Target : Source;
13456 FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
13461 for (
unsigned I = 0, N = TheCall->
getNumArgs(); I < N; ++I) {
13467 S, TheCall->
getArg(I - 1),
false));
13469 S, TheCall->
getArg(I + 1),
false));
13474 diag::warn_impcast_floating_point_to_bool);
13489 if (!IsGNUNullExpr && !HasNullPtrType)
13493 if (
T->isAnyPointerType() ||
T->isBlockPointerType() ||
13494 T->isMemberPointerType() || !
T->isScalarType() ||
T->isNullPtrType())
13497 if (S.
Diags.
isIgnored(diag::warn_impcast_null_pointer_to_integer,
13510 if (IsGNUNullExpr && Loc.
isMacroID()) {
13513 if (MacroName ==
"NULL")
13521 S.
Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
13536 const char FirstLiteralCharacter =
13538 if (FirstLiteralCharacter ==
'0')
13544 if (
T->isCharType() && !
T->isSignedIntegerType() && CC.
isValid()) {
13545 const char FirstContextCharacter =
13547 if (FirstContextCharacter ==
'{')
13555 const auto *IL = dyn_cast<IntegerLiteral>(E);
13557 if (
auto *UO = dyn_cast<UnaryOperator>(E)) {
13558 if (UO->getOpcode() == UO_Minus)
13559 return dyn_cast<IntegerLiteral>(UO->getSubExpr());
13570 if (
const auto *BO = dyn_cast<BinaryOperator>(E)) {
13574 if (Opc == BO_Shl) {
13577 if (LHS && LHS->getValue() == 0)
13578 S.
Diag(ExprLoc, diag::warn_left_shift_always) << 0;
13580 RHS->getValue().isNonNegative() &&
13582 S.
Diag(ExprLoc, diag::warn_left_shift_always)
13583 << (
Result.Val.getInt() != 0);
13585 S.
Diag(ExprLoc, diag::warn_left_shift_in_bool_context)
13592 if (
const auto *CO = dyn_cast<ConditionalOperator>(E)) {
13597 if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
13598 (RHS->getValue() == 0 || RHS->getValue() == 1))
13601 if (LHS->getValue() != 0 && RHS->getValue() != 0)
13602 S.
Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
13610 assert(Source->isUnicodeCharacterType() &&
Target->isUnicodeCharacterType() &&
13616 if (Source->isChar16Type() &&
Target->isChar32Type())
13622 llvm::APSInt
Value(32);
13624 bool IsASCII =
Value <= 0x7F;
13625 bool IsBMP =
Value <= 0xDFFF || (
Value >= 0xE000 &&
Value <= 0xFFFF);
13626 bool ConversionPreservesSemantics =
13627 IsASCII || (!Source->isChar8Type() && !
Target->isChar8Type() && IsBMP);
13629 if (!ConversionPreservesSemantics) {
13630 auto IsSingleCodeUnitCP = [](
const QualType &
T,
13631 const llvm::APSInt &
Value) {
13632 if (
T->isChar8Type())
13633 return llvm::IsSingleCodeUnitUTF8Codepoint(
Value.getExtValue());
13634 if (
T->isChar16Type())
13635 return llvm::IsSingleCodeUnitUTF16Codepoint(
Value.getExtValue());
13636 assert(
T->isChar32Type());
13637 return llvm::IsSingleCodeUnitUTF32Codepoint(
Value.getExtValue());
13640 S.
Diag(CC, diag::warn_impcast_unicode_char_type_constant)
13649 LosesPrecision ? diag::warn_impcast_unicode_precision
13650 : diag::warn_impcast_unicode_char_type);
13655 From =
Context.getCanonicalType(From);
13656 To =
Context.getCanonicalType(To);
13659 From = MaybePointee;
13666 if (FromFn->getCFIUncheckedCalleeAttr() &&
13667 !ToFn->getCFIUncheckedCalleeAttr())
13675 bool *ICContext,
bool IsListInit) {
13680 if (Source ==
Target)
return;
13681 if (
Target->isDependentType())
return;
13691 if (Source->isAtomicType())
13695 if (
Target->isSpecificBuiltinType(BuiltinType::Bool)) {
13701 diag::warn_impcast_string_literal_to_bool);
13707 diag::warn_impcast_objective_c_literal_to_bool);
13709 if (Source->isPointerType() || Source->canDecayToPointerType()) {
13721 if (
ObjC().isSignedCharBool(
T) && Source->isIntegralType(
Context)) {
13724 if (
Result.Val.getInt() != 1 &&
Result.Val.getInt() != 0) {
13726 E,
Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
13735 if (
auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
13737 else if (
auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
13748 diag::err_impcast_incompatible_type);
13753 ? diag::err_impcast_complex_scalar
13754 : diag::warn_impcast_complex_scalar);
13763 if (
Target->isSveVLSBuiltinType() &&
13770 if (
Target->isRVVVLSBuiltinType() &&
13780 return DiagnoseImpCast(*
this, E,
T, CC, diag::warn_impcast_vector_scalar);
13788 diag::warn_hlsl_impcast_vector_truncation);
13800 if (
const auto *VecTy = dyn_cast<VectorType>(
Target))
13801 Target = VecTy->getElementType().getTypePtr();
13805 if (
Target->isScalarType())
13806 return DiagnoseImpCast(*
this, E,
T, CC, diag::warn_impcast_matrix_scalar);
13814 diag::warn_hlsl_impcast_matrix_truncation);
13820 if (
const auto *MatTy = dyn_cast<ConstantMatrixType>(
Target))
13821 Target = MatTy->getElementType().getTypePtr();
13823 const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
13829 const Type *OriginalTarget =
Context.getCanonicalType(
T).getTypePtr();
13832 if (
ARM().areCompatibleSveTypes(
QualType(OriginalTarget, 0),
13834 ARM().areLaxCompatibleSveTypes(
QualType(OriginalTarget, 0),
13881 else if (Order < 0) {
13891 if (TargetBT && TargetBT->
isInteger()) {
13918 diag::warn_impcast_floating_point_to_bool);
13926 if (Source->isFixedPointType()) {
13927 if (
Target->isUnsaturatedFixedPointType()) {
13931 llvm::APFixedPoint
Value =
Result.Val.getFixedPoint();
13932 llvm::APFixedPoint MaxVal =
Context.getFixedPointMax(
T);
13933 llvm::APFixedPoint MinVal =
Context.getFixedPointMin(
T);
13936 PDiag(diag::warn_impcast_fixed_point_range)
13937 <<
Value.toString() <<
T
13943 }
else if (
Target->isIntegerType()) {
13947 llvm::APFixedPoint FXResult =
Result.Val.getFixedPoint();
13950 llvm::APSInt IntResult = FXResult.convertToInt(
13951 Context.getIntWidth(
T),
Target->isSignedIntegerOrEnumerationType(),
13956 PDiag(diag::warn_impcast_fixed_point_range)
13957 << FXResult.toString() <<
T
13964 }
else if (
Target->isUnsaturatedFixedPointType()) {
13965 if (Source->isIntegerType()) {
13972 llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
13977 PDiag(diag::warn_impcast_fixed_point_range)
13998 unsigned int SourcePrecision =
SourceRange->Width;
14002 unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
14005 if (SourcePrecision > 0 && TargetPrecision > 0 &&
14006 SourcePrecision > TargetPrecision) {
14008 if (std::optional<llvm::APSInt> SourceInt =
14013 llvm::APFloat TargetFloatValue(
14015 llvm::APFloat::opStatus ConversionStatus =
14016 TargetFloatValue.convertFromAPInt(
14018 llvm::APFloat::rmNearestTiesToEven);
14020 if (ConversionStatus != llvm::APFloat::opOK) {
14022 SourceInt->toString(PrettySourceValue, 10);
14024 TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
14028 PDiag(diag::warn_impcast_integer_float_precision_constant)
14029 << PrettySourceValue << PrettyTargetValue << E->
getType() <<
T
14035 diag::warn_impcast_integer_float_precision);
14044 if (Source->isUnicodeCharacterType() &&
Target->isUnicodeCharacterType()) {
14049 if (
Target->isBooleanType())
14053 Diag(CC, diag::warn_cast_discards_cfi_unchecked_callee)
14057 if (!Source->isIntegerType() || !
Target->isIntegerType())
14062 if (
Target->isSpecificBuiltinType(BuiltinType::Bool))
14065 if (
ObjC().isSignedCharBool(
T) && !Source->isCharType() &&
14068 E,
Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
14073 if (!LikelySourceRange)
14076 IntRange SourceTypeRange =
14077 IntRange::forTargetOfCanonicalType(
Context, Source);
14078 IntRange TargetRange = IntRange::forTargetOfCanonicalType(
Context,
Target);
14080 if (LikelySourceRange->Width > TargetRange.Width) {
14084 if (
const auto *TargetOBT =
Target->getAs<OverflowBehaviorType>()) {
14085 if (TargetOBT->isWrapKind()) {
14092 if (
const auto *SourceOBT = E->
getType()->
getAs<OverflowBehaviorType>()) {
14093 if (SourceOBT->isWrapKind()) {
14103 llvm::APSInt
Value(32);
14113 PDiag(diag::warn_impcast_integer_precision_constant)
14114 << PrettySourceValue << PrettyTargetValue
14124 if (
const auto *UO = dyn_cast<UnaryOperator>(E)) {
14125 if (UO->getOpcode() == UO_Minus)
14127 *
this, E,
T, CC, diag::warn_impcast_integer_precision_on_negation);
14130 if (TargetRange.Width == 32 &&
Context.getIntWidth(E->
getType()) == 64)
14134 diag::warn_impcast_integer_precision);
14137 if (TargetRange.Width > SourceTypeRange.Width) {
14138 if (
auto *UO = dyn_cast<UnaryOperator>(E))
14139 if (UO->getOpcode() == UO_Minus)
14140 if (Source->isUnsignedIntegerType()) {
14141 if (
Target->isUnsignedIntegerType())
14143 diag::warn_impcast_high_order_zero_bits);
14144 if (
Target->isSignedIntegerType())
14146 diag::warn_impcast_nonnegative_result);
14150 if (TargetRange.Width == LikelySourceRange->Width &&
14151 !TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14152 Source->isSignedIntegerType()) {
14166 PDiag(diag::warn_impcast_integer_precision_constant)
14167 << PrettySourceValue << PrettyTargetValue << E->
getType() <<
T
14177 ((TargetRange.NonNegative && !LikelySourceRange->NonNegative) ||
14178 (!TargetRange.NonNegative && LikelySourceRange->NonNegative &&
14179 LikelySourceRange->Width == TargetRange.Width))) {
14183 if (SourceBT && SourceBT->
isInteger() && TargetBT &&
14185 Source->isSignedIntegerType() ==
Target->isSignedIntegerType()) {
14189 unsigned DiagID = diag::warn_impcast_integer_sign;
14197 DiagID = diag::warn_impcast_integer_sign_conditional;
14214 Source =
Context.getCanonicalType(SourceType).getTypePtr();
14216 if (
const EnumType *SourceEnum = Source->getAsCanonical<EnumType>())
14217 if (
const EnumType *TargetEnum =
Target->getAsCanonical<EnumType>())
14218 if (SourceEnum->getDecl()->hasNameForLinkage() &&
14219 TargetEnum->getDecl()->hasNameForLinkage() &&
14220 SourceEnum != TargetEnum) {
14225 diag::warn_impcast_different_enum_types);
14239 if (
auto *CO = dyn_cast<AbstractConditionalOperator>(E))
14252 if (
auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
14253 TrueExpr = BCO->getCommon();
14255 bool Suspicious =
false;
14259 if (
T->isBooleanType())
14264 if (!Suspicious)
return;
14267 if (!S.
Diags.
isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
14274 Suspicious =
false;
14279 E->
getType(), CC, &Suspicious);
14296struct AnalyzeImplicitConversionsWorkItem {
14305 bool ExtraCheckForImplicitConversion,
14308 WorkList.push_back({E, CC,
false});
14310 if (ExtraCheckForImplicitConversion && E->
getType() !=
T)
14317 Sema &S, AnalyzeImplicitConversionsWorkItem Item,
14319 Expr *OrigE = Item.E;
14338 Expr *SourceExpr = E;
14343 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(E))
14344 if (
auto *Src = OVE->getSourceExpr())
14347 if (
const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
14348 if (UO->getOpcode() == UO_Not &&
14349 UO->getSubExpr()->isKnownToHaveBooleanValue())
14350 S.
Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
14354 if (
auto *BO = dyn_cast<BinaryOperator>(SourceExpr)) {
14355 if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
14356 BO->getLHS()->isKnownToHaveBooleanValue() &&
14357 BO->getRHS()->isKnownToHaveBooleanValue() &&
14358 BO->getLHS()->HasSideEffects(S.
Context) &&
14359 BO->getRHS()->HasSideEffects(S.
Context)) {
14370 if (SR.str() ==
"&" || SR.str() ==
"|") {
14372 S.
Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
14373 << (BO->getOpcode() == BO_And ?
"&" :
"|")
14376 BO->getOperatorLoc(),
14377 (BO->getOpcode() == BO_And ?
"&&" :
"||"));
14378 S.
Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
14380 }
else if (BO->isCommaOp() && !S.
getLangOpts().CPlusPlus) {
14398 if (
auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
14404 if (
const auto *
Call = dyn_cast<CallExpr>(SourceExpr))
14419 for (
auto *SE : POE->semantics())
14420 if (
auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
14421 WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
14425 if (
auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
14426 E = CE->getSubExpr();
14432 if (
auto *InitListE = dyn_cast<InitListExpr>(E)) {
14433 if (InitListE->getNumInits() == 1) {
14434 E = InitListE->getInit(0);
14441 WorkList.push_back({E, CC, IsListInit});
14445 if (
auto *OutArgE = dyn_cast<HLSLOutArgExpr>(E)) {
14446 WorkList.push_back({OutArgE->getArgLValue(), CC, IsListInit});
14450 if (OutArgE->isInOut())
14451 WorkList.push_back(
14452 {OutArgE->getCastedTemporary()->getSourceExpr(), CC, IsListInit});
14453 WorkList.push_back({OutArgE->getWritebackCast(), CC, IsListInit});
14459 if (BO->isComparisonOp())
14463 if (BO->getOpcode() == BO_Assign)
14466 if (BO->isAssignmentOp())
14482 bool IsLogicalAndOperator = BO && BO->
getOpcode() == BO_LAnd;
14484 Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
14488 if (
auto *CSE = dyn_cast<CoroutineSuspendExpr>(E))
14489 if (ChildExpr == CSE->getOperand())
14495 if (IsLogicalAndOperator &&
14500 WorkList.push_back({ChildExpr, CC, IsListInit});
14514 if (
U->getOpcode() == UO_LNot) {
14516 }
else if (
U->getOpcode() != UO_AddrOf) {
14517 if (
U->getSubExpr()->getType()->isAtomicType())
14518 S.
Diag(
U->getSubExpr()->getBeginLoc(),
14519 diag::warn_atomic_implicit_seq_cst);
14530 WorkList.push_back({OrigE, CC, IsListInit});
14531 while (!WorkList.empty())
14543 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
14546 }
else if (
const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14547 if (!M->getMemberDecl()->getType()->isReferenceType())
14549 }
else if (
const CallExpr *
Call = dyn_cast<CallExpr>(E)) {
14550 if (!
Call->getCallReturnType(SemaRef.
Context)->isReferenceType())
14552 FD =
Call->getDirectCallee();
14561 SemaRef.
Diag(FD->
getLocation(), diag::note_reference_is_return_value) << FD;
14601 unsigned DiagID = IsCompare ? diag::warn_this_null_compare
14602 : diag::warn_this_bool_conversion;
14607 bool IsAddressOf =
false;
14609 if (
auto *UO = dyn_cast<UnaryOperator>(E->
IgnoreParens())) {
14610 if (UO->getOpcode() != UO_AddrOf)
14612 IsAddressOf =
true;
14613 E = UO->getSubExpr();
14617 unsigned DiagID = IsCompare
14618 ? diag::warn_address_of_reference_null_compare
14619 : diag::warn_address_of_reference_bool_conversion;
14627 auto ComplainAboutNonnullParamOrCall = [&](
const Attr *NonnullAttr) {
14630 llvm::raw_string_ostream S(Str);
14632 unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
14633 : diag::warn_cast_nonnull_to_bool;
14636 Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
14641 if (
auto *Callee =
Call->getDirectCallee()) {
14642 if (
const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
14643 ComplainAboutNonnullParamOrCall(A);
14652 if (
const auto *MCallExpr = dyn_cast<CXXMemberCallExpr>(E)) {
14653 if (
const auto *MRecordDecl = MCallExpr->getRecordDecl();
14654 MRecordDecl && MRecordDecl->isLambda()) {
14657 << MRecordDecl->getSourceRange() << Range << IsEqual;
14667 }
else if (
MemberExpr *M = dyn_cast<MemberExpr>(E)) {
14668 D = M->getMemberDecl();
14676 if (
const auto* PV = dyn_cast<ParmVarDecl>(D)) {
14679 if (
const Attr *A = PV->getAttr<NonNullAttr>()) {
14680 ComplainAboutNonnullParamOrCall(A);
14684 if (
const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
14688 auto ParamIter = llvm::find(FD->
parameters(), PV);
14690 unsigned ParamNo = std::distance(FD->
param_begin(), ParamIter);
14694 ComplainAboutNonnullParamOrCall(
NonNull);
14699 if (ArgNo.getASTIndex() == ParamNo) {
14700 ComplainAboutNonnullParamOrCall(
NonNull);
14711 const bool IsFunctionReference =
14712 T->isReferenceType() &&
T->getPointeeType()->isFunctionType();
14713 if (IsFunctionReference)
14714 T =
T->getPointeeType();
14715 const bool IsArray =
T->isArrayType();
14716 const bool IsFunction =
T->isFunctionType();
14719 if (IsAddressOf && IsFunction) {
14724 if (!IsAddressOf && !IsFunction && !IsArray)
14729 llvm::raw_string_ostream S(Str);
14732 unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
14733 : diag::warn_impcast_pointer_to_bool;
14740 DiagType = AddressOf;
14741 else if (IsFunction)
14742 DiagType = FunctionPointer;
14744 DiagType = ArrayPointer;
14746 llvm_unreachable(
"Could not determine diagnostic.");
14748 << Range << IsEqual;
14751 if (!IsFunction || IsFunctionReference)
14762 if (ReturnType.
isNull())
14793 if (
const auto *OBT = Source->getAs<OverflowBehaviorType>()) {
14794 if (
Target->isIntegerType() && !
Target->isOverflowBehaviorType()) {
14796 if (OBT->isUnsignedIntegerType() && OBT->isWrapKind() &&
14797 Target->isUnsignedIntegerType()) {
14801 ? diag::warn_impcast_overflow_behavior_assignment_pedantic
14802 : diag::warn_impcast_overflow_behavior_pedantic;
14806 ? diag::warn_impcast_overflow_behavior_assignment
14807 : diag::warn_impcast_overflow_behavior;
14813 if (
const auto *TargetOBT =
Target->getAs<OverflowBehaviorType>()) {
14814 if (TargetOBT->isWrapKind()) {
14834 CheckArrayAccess(E);
14844void Sema::CheckForIntOverflow (
const Expr *E) {
14846 SmallVector<const Expr *, 2> Exprs(1, E);
14849 const Expr *OriginalE = Exprs.pop_back_val();
14858 if (
const auto *InitList = dyn_cast<InitListExpr>(OriginalE))
14859 Exprs.append(InitList->inits().begin(), InitList->inits().end());
14862 else if (
const auto *
Call = dyn_cast<CallExpr>(E))
14863 Exprs.append(
Call->arg_begin(),
Call->arg_end());
14864 else if (
const auto *Message = dyn_cast<ObjCMessageExpr>(E))
14866 else if (
const auto *Construct = dyn_cast<CXXConstructExpr>(E))
14867 Exprs.append(Construct->arg_begin(), Construct->arg_end());
14868 else if (
const auto *Temporary = dyn_cast<CXXBindTemporaryExpr>(E))
14869 Exprs.push_back(Temporary->getSubExpr());
14870 else if (
const auto *
Array = dyn_cast<ArraySubscriptExpr>(E))
14871 Exprs.push_back(
Array->getIdx());
14872 else if (
const auto *Compound = dyn_cast<CompoundLiteralExpr>(E))
14873 Exprs.push_back(Compound->getInitializer());
14874 else if (
const auto *
New = dyn_cast<CXXNewExpr>(E);
14875 New &&
New->isArray()) {
14876 if (
auto ArraySize =
New->getArraySize())
14877 Exprs.push_back(*ArraySize);
14878 }
else if (
const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(OriginalE))
14879 Exprs.push_back(MTE->getSubExpr());
14880 }
while (!Exprs.empty());
14888 using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
14895 class SequenceTree {
14897 explicit Value(
unsigned Parent) : Parent(Parent), Merged(
false) {}
14898 unsigned Parent : 31;
14899 LLVM_PREFERRED_TYPE(
bool)
14900 unsigned Merged : 1;
14902 SmallVector<Value, 8> Values;
14908 friend class SequenceTree;
14912 explicit Seq(
unsigned N) : Index(N) {}
14915 Seq() : Index(0) {}
14918 SequenceTree() { Values.push_back(
Value(0)); }
14919 Seq root()
const {
return Seq(0); }
14924 Seq allocate(
Seq Parent) {
14925 Values.push_back(
Value(Parent.Index));
14926 return Seq(Values.size() - 1);
14931 Values[S.Index].Merged =
true;
14937 bool isUnsequenced(
Seq Cur,
Seq Old) {
14938 unsigned C = representative(Cur.Index);
14939 unsigned Target = representative(Old.Index);
14943 C = Values[
C].Parent;
14950 unsigned representative(
unsigned K) {
14951 if (Values[K].Merged)
14953 return Values[K].Parent = representative(Values[K].Parent);
14959 using Object =
const ValueDecl *;
14973 UK_ModAsSideEffect,
14975 UK_Count = UK_ModAsSideEffect + 1
14986 WK_Volatile_UseAndUse
14992 const Expr *UsageExpr =
nullptr;
14993 SequenceTree::Seq
Seq;
14999 Usage Uses[UK_Count];
15002 bool Diagnosed =
false;
15006 using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
15014 UsageInfoMap UsageMap;
15017 SequenceTree::Seq Region;
15021 SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect =
nullptr;
15025 SmallVectorImpl<const Expr *> &WorkList;
15032 struct SequencedSubexpression {
15033 SequencedSubexpression(SequenceChecker &
Self)
15034 :
Self(
Self), OldModAsSideEffect(
Self.ModAsSideEffect) {
15035 Self.ModAsSideEffect = &ModAsSideEffect;
15038 ~SequencedSubexpression() {
15039 for (
const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
15043 UsageInfo &UI =
Self.UsageMap[M.first];
15044 auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
15045 Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
15046 SideEffectUsage = M.second;
15048 Self.ModAsSideEffect = OldModAsSideEffect;
15051 SequenceChecker &
Self;
15052 SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
15053 SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
15060 class EvaluationTracker {
15062 EvaluationTracker(SequenceChecker &
Self)
15064 Self.EvalTracker =
this;
15067 ~EvaluationTracker() {
15068 Self.EvalTracker = Prev;
15070 Prev->EvalOK &= EvalOK;
15073 bool evaluate(
const Expr *E,
bool &
Result) {
15078 Self.SemaRef.isConstantEvaluatedContext());
15083 SequenceChecker &
Self;
15084 EvaluationTracker *Prev;
15085 bool EvalOK =
true;
15086 } *EvalTracker =
nullptr;
15090 Object getObject(
const Expr *E,
bool Mod)
const {
15092 if (
const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
15093 if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
15094 return getObject(UO->getSubExpr(), Mod);
15095 }
else if (
const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
15096 if (BO->getOpcode() == BO_Comma)
15097 return getObject(BO->getRHS(), Mod);
15098 if (Mod && BO->isAssignmentOp())
15099 return getObject(BO->getLHS(), Mod);
15100 }
else if (
const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
15103 return ME->getMemberDecl();
15104 }
else if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
15113 void addUsage(
Object O, UsageInfo &UI,
const Expr *UsageExpr, UsageKind UK) {
15115 Usage &U = UI.Uses[UK];
15116 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
15120 if (UK == UK_ModAsSideEffect && ModAsSideEffect)
15121 ModAsSideEffect->push_back(std::make_pair(O, U));
15123 U.UsageExpr = UsageExpr;
15132 void checkUsage(
Object O, UsageInfo &UI,
const Expr *UsageExpr,
15133 UsageKind OtherKind, WarningKind WarnKind) {
15137 const Usage &U = UI.Uses[OtherKind];
15138 if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
15141 const Expr *Mod = U.UsageExpr;
15142 const Expr *ModOrUse = UsageExpr;
15143 if (OtherKind == UK_Use)
15144 std::swap(Mod, ModOrUse);
15146 unsigned DiagID = 0;
15147 switch (WarnKind) {
15149 DiagID = diag::warn_unsequenced_mod_use;
15152 DiagID = diag::warn_unsequenced_mod_mod;
15154 case WK_Volatile_UseAndUse:
15155 DiagID = diag::warn_unsequenced_use_use_volatile;
15162 UI.Diagnosed =
true;
15191 void notePreUse(
Object O,
const Expr *UseExpr) {
15192 UsageInfo &UI = UsageMap[O];
15194 checkUsage(O, UI, UseExpr, UK_ModAsValue, WK_UseAndMod);
15196 if (O->getType().isVolatileQualified())
15197 checkUsage(O, UI, UseExpr, UK_Use, WK_Volatile_UseAndUse);
15200 void notePostUse(
Object O,
const Expr *UseExpr) {
15201 UsageInfo &UI = UsageMap[O];
15202 checkUsage(O, UI, UseExpr, UK_ModAsSideEffect, WK_UseAndMod);
15203 addUsage(O, UI, UseExpr, UK_Use);
15206 void notePreMod(
Object O,
const Expr *ModExpr) {
15207 UsageInfo &UI = UsageMap[O];
15209 checkUsage(O, UI, ModExpr, UK_ModAsValue, WK_ModAndMod);
15210 checkUsage(O, UI, ModExpr, UK_Use, WK_UseAndMod);
15213 void notePostMod(
Object O,
const Expr *ModExpr, UsageKind UK) {
15214 UsageInfo &UI = UsageMap[O];
15215 checkUsage(O, UI, ModExpr, UK_ModAsSideEffect, WK_ModAndMod);
15216 addUsage(O, UI, ModExpr, UK);
15220 SequenceChecker(Sema &S,
const Expr *E,
15221 SmallVectorImpl<const Expr *> &WorkList)
15222 :
Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
15226 (void)this->WorkList;
15229 void VisitStmt(
const Stmt *S) {
15233 void VisitExpr(
const Expr *E) {
15235 Base::VisitStmt(E);
15238 void VisitCoroutineSuspendExpr(
const CoroutineSuspendExpr *CSE) {
15239 for (
auto *Sub : CSE->
children()) {
15240 const Expr *ChildExpr = dyn_cast_or_null<Expr>(Sub);
15255 void VisitCastExpr(
const CastExpr *E) {
15267 void VisitSequencedExpressions(
const Expr *SequencedBefore,
15268 const Expr *SequencedAfter) {
15269 SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
15270 SequenceTree::Seq AfterRegion = Tree.allocate(Region);
15271 SequenceTree::Seq OldRegion = Region;
15274 SequencedSubexpression SeqBefore(*
this);
15275 Region = BeforeRegion;
15276 Visit(SequencedBefore);
15279 Region = AfterRegion;
15280 Visit(SequencedAfter);
15282 Region = OldRegion;
15284 Tree.merge(BeforeRegion);
15285 Tree.merge(AfterRegion);
15288 void VisitArraySubscriptExpr(
const ArraySubscriptExpr *ASE) {
15293 VisitSequencedExpressions(ASE->
getLHS(), ASE->
getRHS());
15300 void VisitBinPtrMemD(
const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15301 void VisitBinPtrMemI(
const BinaryOperator *BO) { VisitBinPtrMem(BO); }
15302 void VisitBinPtrMem(
const BinaryOperator *BO) {
15307 VisitSequencedExpressions(BO->
getLHS(), BO->
getRHS());
15314 void VisitBinShl(
const BinaryOperator *BO) { VisitBinShlShr(BO); }
15315 void VisitBinShr(
const BinaryOperator *BO) { VisitBinShlShr(BO); }
15316 void VisitBinShlShr(
const BinaryOperator *BO) {
15320 VisitSequencedExpressions(BO->
getLHS(), BO->
getRHS());
15327 void VisitBinComma(
const BinaryOperator *BO) {
15332 VisitSequencedExpressions(BO->
getLHS(), BO->
getRHS());
15335 void VisitBinAssign(
const BinaryOperator *BO) {
15336 SequenceTree::Seq RHSRegion;
15337 SequenceTree::Seq LHSRegion;
15339 RHSRegion = Tree.allocate(Region);
15340 LHSRegion = Tree.allocate(Region);
15342 RHSRegion = Region;
15343 LHSRegion = Region;
15345 SequenceTree::Seq OldRegion = Region;
15361 SequencedSubexpression SeqBefore(*
this);
15362 Region = RHSRegion;
15366 Region = LHSRegion;
15370 notePostUse(O, BO);
15374 Region = LHSRegion;
15378 notePostUse(O, BO);
15380 Region = RHSRegion;
15388 Region = OldRegion;
15392 : UK_ModAsSideEffect);
15394 Tree.merge(RHSRegion);
15395 Tree.merge(LHSRegion);
15399 void VisitCompoundAssignOperator(
const CompoundAssignOperator *CAO) {
15400 VisitBinAssign(CAO);
15403 void VisitUnaryPreInc(
const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15404 void VisitUnaryPreDec(
const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
15405 void VisitUnaryPreIncDec(
const UnaryOperator *UO) {
15408 return VisitExpr(UO);
15416 : UK_ModAsSideEffect);
15419 void VisitUnaryPostInc(
const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15420 void VisitUnaryPostDec(
const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
15421 void VisitUnaryPostIncDec(
const UnaryOperator *UO) {
15424 return VisitExpr(UO);
15428 notePostMod(O, UO, UK_ModAsSideEffect);
15431 void VisitBinLOr(
const BinaryOperator *BO) {
15437 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15438 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15439 SequenceTree::Seq OldRegion = Region;
15441 EvaluationTracker Eval(*
this);
15443 SequencedSubexpression Sequenced(*
this);
15444 Region = LHSRegion;
15451 bool EvalResult =
false;
15452 bool EvalOK = Eval.evaluate(BO->
getLHS(), EvalResult);
15453 bool ShouldVisitRHS = !EvalOK || !EvalResult;
15454 if (ShouldVisitRHS) {
15455 Region = RHSRegion;
15459 Region = OldRegion;
15460 Tree.merge(LHSRegion);
15461 Tree.merge(RHSRegion);
15464 void VisitBinLAnd(
const BinaryOperator *BO) {
15470 SequenceTree::Seq LHSRegion = Tree.allocate(Region);
15471 SequenceTree::Seq RHSRegion = Tree.allocate(Region);
15472 SequenceTree::Seq OldRegion = Region;
15474 EvaluationTracker Eval(*
this);
15476 SequencedSubexpression Sequenced(*
this);
15477 Region = LHSRegion;
15483 bool EvalResult =
false;
15484 bool EvalOK = Eval.evaluate(BO->
getLHS(), EvalResult);
15485 bool ShouldVisitRHS = !EvalOK || EvalResult;
15486 if (ShouldVisitRHS) {
15487 Region = RHSRegion;
15491 Region = OldRegion;
15492 Tree.merge(LHSRegion);
15493 Tree.merge(RHSRegion);
15496 void VisitAbstractConditionalOperator(
const AbstractConditionalOperator *CO) {
15501 SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
15517 SequenceTree::Seq TrueRegion = Tree.allocate(Region);
15518 SequenceTree::Seq FalseRegion = Tree.allocate(Region);
15519 SequenceTree::Seq OldRegion = Region;
15521 EvaluationTracker Eval(*
this);
15523 SequencedSubexpression Sequenced(*
this);
15524 Region = ConditionRegion;
15534 bool EvalResult =
false;
15535 bool EvalOK = Eval.evaluate(CO->
getCond(), EvalResult);
15536 bool ShouldVisitTrueExpr = !EvalOK || EvalResult;
15537 bool ShouldVisitFalseExpr = !EvalOK || !EvalResult;
15538 if (ShouldVisitTrueExpr) {
15539 Region = TrueRegion;
15542 if (ShouldVisitFalseExpr) {
15543 Region = FalseRegion;
15547 Region = OldRegion;
15548 Tree.merge(ConditionRegion);
15549 Tree.merge(TrueRegion);
15550 Tree.merge(FalseRegion);
15553 void VisitCallExpr(
const CallExpr *CE) {
15565 SequencedSubexpression Sequenced(*
this);
15570 SequenceTree::Seq CalleeRegion;
15571 SequenceTree::Seq OtherRegion;
15572 if (SemaRef.getLangOpts().CPlusPlus17) {
15573 CalleeRegion = Tree.allocate(Region);
15574 OtherRegion = Tree.allocate(Region);
15576 CalleeRegion = Region;
15577 OtherRegion = Region;
15579 SequenceTree::Seq OldRegion = Region;
15582 Region = CalleeRegion;
15584 SequencedSubexpression Sequenced(*this);
15585 Visit(CE->getCallee());
15587 Visit(CE->getCallee());
15591 Region = OtherRegion;
15595 Region = OldRegion;
15597 Tree.merge(CalleeRegion);
15598 Tree.merge(OtherRegion);
15616 return VisitCallExpr(CXXOCE);
15627 case OO_MinusEqual:
15629 case OO_SlashEqual:
15630 case OO_PercentEqual:
15631 case OO_CaretEqual:
15634 case OO_LessLessEqual:
15635 case OO_GreaterGreaterEqual:
15636 SequencingKind = RHSBeforeLHS;
15640 case OO_GreaterGreater:
15646 SequencingKind = LHSBeforeRHS;
15650 SequencingKind = LHSBeforeRest;
15654 SequencingKind = NoSequencing;
15658 if (SequencingKind == NoSequencing)
15659 return VisitCallExpr(CXXOCE);
15662 SequencedSubexpression Sequenced(*
this);
15665 assert(SemaRef.getLangOpts().CPlusPlus17 &&
15666 "Should only get there with C++17 and above!");
15667 assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
15668 "Should only get there with an overloaded binary operator"
15669 " or an overloaded call operator!");
15671 if (SequencingKind == LHSBeforeRest) {
15672 assert(CXXOCE->getOperator() == OO_Call &&
15673 "We should only have an overloaded call operator here!");
15682 SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
15683 SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
15684 SequenceTree::Seq OldRegion = Region;
15686 assert(CXXOCE->getNumArgs() >= 1 &&
15687 "An overloaded call operator must have at least one argument"
15688 " for the postfix-expression!");
15689 const Expr *PostfixExpr = CXXOCE->getArgs()[0];
15690 llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
15691 CXXOCE->getNumArgs() - 1);
15695 Region = PostfixExprRegion;
15696 SequencedSubexpression Sequenced(*this);
15697 Visit(PostfixExpr);
15701 Region = ArgsRegion;
15702 for (const Expr *Arg : Args)
15705 Region = OldRegion;
15706 Tree.merge(PostfixExprRegion);
15707 Tree.merge(ArgsRegion);
15709 assert(CXXOCE->getNumArgs() == 2 &&
15710 "Should only have two arguments here!");
15711 assert((SequencingKind == LHSBeforeRHS ||
15712 SequencingKind == RHSBeforeLHS) &&
15713 "Unexpected sequencing kind!");
15717 const Expr *E1 = CXXOCE->getArg(0);
15718 const Expr *E2 = CXXOCE->getArg(1);
15719 if (SequencingKind == RHSBeforeLHS)
15722 return VisitSequencedExpressions(E1, E2);
15729 SequencedSubexpression Sequenced(*
this);
15732 return VisitExpr(CCE);
15735 SequenceExpressionsInOrder(
15741 return VisitExpr(ILE);
15744 SequenceExpressionsInOrder(ILE->
inits());
15756 SequenceTree::Seq Parent = Region;
15757 for (
const Expr *E : ExpressionList) {
15760 Region = Tree.allocate(Parent);
15761 Elts.push_back(Region);
15767 for (
unsigned I = 0; I < Elts.size(); ++I)
15768 Tree.merge(Elts[I]);
15772SequenceChecker::UsageInfo::UsageInfo() =
default;
15776void Sema::CheckUnsequencedOperations(
const Expr *E) {
15777 SmallVector<const Expr *, 8> WorkList;
15778 WorkList.push_back(E);
15779 while (!WorkList.empty()) {
15780 const Expr *Item = WorkList.pop_back_val();
15781 SequenceChecker(*
this, Item, WorkList);
15786 bool IsConstexpr) {
15789 CheckImplicitConversions(E, CheckLoc);
15791 CheckUnsequencedOperations(E);
15793 CheckForIntOverflow(E);
15806 if (
const auto *PointerTy = dyn_cast<PointerType>(PType)) {
15810 if (
const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
15814 if (
const auto *ParenTy = dyn_cast<ParenType>(PType)) {
15828 S.
Diag(Loc, diag::err_array_star_in_function_definition);
15832 bool CheckParameterNames) {
15833 bool HasInvalidParm =
false;
15835 assert(Param &&
"null in a parameter list");
15844 if (!Param->isInvalidDecl() &&
15846 diag::err_typecheck_decl_incomplete_type) ||
15848 diag::err_abstract_type_in_decl,
15850 Param->setInvalidDecl();
15851 HasInvalidParm =
true;
15856 if (CheckParameterNames && Param->getIdentifier() ==
nullptr &&
15860 Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c23);
15868 QualType PType = Param->getOriginalType();
15876 if (!Param->isInvalidDecl()) {
15877 if (
CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
15878 if (!ClassDecl->isInvalidDecl() &&
15879 !ClassDecl->hasIrrelevantDestructor() &&
15880 !ClassDecl->isDependentContext() &&
15881 ClassDecl->isParamDestroyedInCallee()) {
15893 if (
const auto *
Attr = Param->getAttr<PassObjectSizeAttr>())
15894 if (!Param->getType().isConstQualified())
15895 Diag(Param->getLocation(), diag::err_attribute_pointers_only)
15899 if (
LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
15904 if (
auto *RD = dyn_cast<CXXRecordDecl>(DC->
getParent()))
15905 CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
15910 if (!Param->isInvalidDecl() &&
15911 Param->getOriginalType()->isWebAssemblyTableType()) {
15912 Param->setInvalidDecl();
15913 HasInvalidParm =
true;
15914 Diag(Param->getLocation(), diag::err_wasm_table_as_function_parameter);
15918 return HasInvalidParm;
15921std::optional<std::pair<
15930static std::pair<CharUnits, CharUnits>
15938 if (
Base->isVirtual()) {
15945 BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
15952 DerivedType =
Base->getType();
15955 return std::make_pair(BaseAlignment, Offset);
15959static std::optional<std::pair<CharUnits, CharUnits>>
15965 return std::nullopt;
15970 return std::nullopt;
15974 CharUnits Offset = EltSize * IdxRes->getExtValue();
15977 return std::make_pair(P->first, P->second + Offset);
15983 return std::make_pair(
15984 P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
15990std::optional<std::pair<
15998 case Stmt::CStyleCastExprClass:
15999 case Stmt::CXXStaticCastExprClass:
16000 case Stmt::ImplicitCastExprClass: {
16002 const Expr *From = CE->getSubExpr();
16003 switch (CE->getCastKind()) {
16008 case CK_UncheckedDerivedToBase:
16009 case CK_DerivedToBase: {
16019 case Stmt::ArraySubscriptExprClass: {
16024 case Stmt::DeclRefExprClass: {
16028 if (!VD->getType()->isReferenceType()) {
16030 if (VD->hasDependentAlignment())
16039 case Stmt::MemberExprClass: {
16041 auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
16045 std::optional<std::pair<CharUnits, CharUnits>> P;
16054 return std::make_pair(P->first,
16057 case Stmt::UnaryOperatorClass: {
16067 case Stmt::BinaryOperatorClass: {
16079 return std::nullopt;
16084std::optional<std::pair<
16093 case Stmt::CStyleCastExprClass:
16094 case Stmt::CXXStaticCastExprClass:
16095 case Stmt::ImplicitCastExprClass: {
16097 const Expr *From = CE->getSubExpr();
16098 switch (CE->getCastKind()) {
16103 case CK_ArrayToPointerDecay:
16105 case CK_UncheckedDerivedToBase:
16106 case CK_DerivedToBase: {
16116 case Stmt::CXXThisExprClass: {
16121 case Stmt::UnaryOperatorClass: {
16127 case Stmt::BinaryOperatorClass: {
16136 if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
16137 std::swap(LHS, RHS);
16147 return std::nullopt;
16152 std::optional<std::pair<CharUnits, CharUnits>> P =
16156 return P->first.alignmentAtOffset(P->second);
16174 if (!DestPtr)
return;
16180 if (DestAlign.
isOne())
return;
16184 if (!SrcPtr)
return;
16195 if (SrcAlign >= DestAlign)
return;
16200 <<
static_cast<unsigned>(DestAlign.
getQuantity())
16204void Sema::CheckArrayAccess(
const Expr *BaseExpr,
const Expr *IndexExpr,
16206 bool AllowOnePastEnd,
bool IndexNegated) {
16215 const Type *EffectiveType =
16219 Context.getAsConstantArrayType(BaseExpr->
getType());
16222 StrictFlexArraysLevel =
getLangOpts().getStrictFlexArraysLevel();
16224 const Type *BaseType =
16226 bool IsUnboundedArray =
16228 Context, StrictFlexArraysLevel,
16231 (!IsUnboundedArray && BaseType->isDependentType()))
16239 if (IndexNegated) {
16240 index.setIsUnsigned(
false);
16244 if (IsUnboundedArray) {
16247 if (
index.isUnsigned() || !
index.isNegative()) {
16249 unsigned AddrBits = ASTC.getTargetInfo().getPointerWidth(
16251 if (
index.getBitWidth() < AddrBits)
16253 std::optional<CharUnits> ElemCharUnits =
16254 ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
16257 if (!ElemCharUnits || ElemCharUnits->isZero())
16259 llvm::APInt ElemBytes(
index.getBitWidth(), ElemCharUnits->getQuantity());
16264 if (
index.getActiveBits() <= AddrBits) {
16266 llvm::APInt Product(
index);
16268 Product = Product.umul_ov(ElemBytes, Overflow);
16269 if (!Overflow && Product.getActiveBits() <= AddrBits)
16275 llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
16276 MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
16278 ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
16279 MaxElems = MaxElems.udiv(ElemBytes);
16282 ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
16283 : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
16288 PDiag(DiagID) << index << AddrBits
16289 << (
unsigned)ASTC.toBits(*ElemCharUnits)
16290 << ElemBytes << MaxElems
16291 << MaxElems.getZExtValue()
16294 const NamedDecl *ND =
nullptr;
16296 while (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16298 if (
const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16300 if (
const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16301 ND = ME->getMemberDecl();
16305 PDiag(diag::note_array_declared_here) << ND);
16310 if (index.isUnsigned() || !index.isNegative()) {
16320 llvm::APInt size = ArrayTy->
getSize();
16322 if (BaseType != EffectiveType) {
16330 if (!ptrarith_typesize)
16331 ptrarith_typesize =
Context.getCharWidth();
16333 if (ptrarith_typesize != array_typesize) {
16335 uint64_t ratio = array_typesize / ptrarith_typesize;
16339 if (ptrarith_typesize * ratio == array_typesize)
16340 size *= llvm::APInt(size.getBitWidth(), ratio);
16344 if (size.getBitWidth() > index.getBitWidth())
16345 index = index.zext(size.getBitWidth());
16346 else if (size.getBitWidth() < index.getBitWidth())
16347 size = size.zext(index.getBitWidth());
16353 if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
16360 SourceLocation RBracketLoc =
SourceMgr.getSpellingLoc(
16362 if (
SourceMgr.isInSystemHeader(RBracketLoc)) {
16363 SourceLocation IndexLoc =
16365 if (
SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
16370 unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
16371 : diag::warn_ptr_arith_exceeds_bounds;
16372 unsigned CastMsg = (!ASE || BaseType == EffectiveType) ? 0 : 1;
16373 QualType CastMsgTy = ASE ? ASE->
getLHS()->
getType() : QualType();
16377 << index << ArrayTy->
desugar() << CastMsg
16380 unsigned DiagID = diag::warn_array_index_precedes_bounds;
16382 DiagID = diag::warn_ptr_arith_precedes_bounds;
16383 if (index.isNegative()) index = -index;
16390 const NamedDecl *ND =
nullptr;
16392 while (
const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
16394 if (
const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
16396 if (
const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
16397 ND = ME->getMemberDecl();
16401 PDiag(diag::note_array_declared_here) << ND);
16404void Sema::CheckArrayAccess(
const Expr *
expr) {
16405 int AllowOnePastEnd = 0;
16407 expr =
expr->IgnoreParenImpCasts();
16408 switch (
expr->getStmtClass()) {
16409 case Stmt::ArraySubscriptExprClass: {
16412 AllowOnePastEnd > 0);
16416 case Stmt::MemberExprClass: {
16420 case Stmt::CXXMemberCallExprClass: {
16424 case Stmt::ArraySectionExprClass: {
16430 nullptr, AllowOnePastEnd > 0);
16433 case Stmt::UnaryOperatorClass: {
16449 case Stmt::ConditionalOperatorClass: {
16451 if (
const Expr *lhs = cond->
getLHS())
16452 CheckArrayAccess(lhs);
16453 if (
const Expr *rhs = cond->
getRHS())
16454 CheckArrayAccess(rhs);
16457 case Stmt::CXXOperatorCallExprClass: {
16459 for (
const auto *Arg : OCE->arguments())
16460 CheckArrayAccess(Arg);
16470 Expr *RHS,
bool isProperty) {
16482 S.
Diag(Loc, diag::warn_arc_literal_assign)
16484 << (isProperty ? 0 : 1)
16492 Expr *RHS,
bool isProperty) {
16495 if (
cast->getCastKind() == CK_ARCConsumeObject) {
16496 S.
Diag(Loc, diag::warn_arc_retained_assign)
16498 << (isProperty ? 0 : 1)
16502 RHS =
cast->getSubExpr();
16544 if (!
Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
16573 if (
cast->getCastKind() == CK_ARCConsumeObject) {
16574 Diag(Loc, diag::warn_arc_retained_property_assign)
16578 RHS =
cast->getSubExpr();
16601 bool StmtLineInvalid;
16602 unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
16604 if (StmtLineInvalid)
16607 bool BodyLineInvalid;
16608 unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->
getSemiLoc(),
16610 if (BodyLineInvalid)
16614 if (StmtLine != BodyLine)
16629 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16638 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
16642 const Stmt *PossibleBody) {
16648 if (
const ForStmt *FS = dyn_cast<ForStmt>(S)) {
16649 StmtLoc = FS->getRParenLoc();
16650 Body = FS->getBody();
16651 DiagID = diag::warn_empty_for_body;
16652 }
else if (
const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
16653 StmtLoc = WS->getRParenLoc();
16654 Body = WS->getBody();
16655 DiagID = diag::warn_empty_while_body;
16660 const NullStmt *NBody = dyn_cast<NullStmt>(Body);
16684 if (!ProbableTypo) {
16685 bool BodyColInvalid;
16686 unsigned BodyCol =
SourceMgr.getPresumedColumnNumber(
16688 if (BodyColInvalid)
16691 bool StmtColInvalid;
16694 if (StmtColInvalid)
16697 if (BodyCol > StmtCol)
16698 ProbableTypo =
true;
16701 if (ProbableTypo) {
16703 Diag(NBody->
getSemiLoc(), diag::note_empty_body_on_separate_line);
16711 if (
Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16723 if (
const auto *CE = dyn_cast<CallExpr>(RHSExpr);
16725 RHSExpr = CE->
getArg(0);
16726 else if (
const auto *CXXSCE = dyn_cast<CXXStaticCastExpr>(RHSExpr);
16727 CXXSCE && CXXSCE->isXValue())
16728 RHSExpr = CXXSCE->getSubExpr();
16732 const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16733 const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16736 if (LHSDeclRef && RHSDeclRef) {
16743 auto D =
Diag(OpLoc, diag::warn_self_move)
16759 const Expr *LHSBase = LHSExpr;
16760 const Expr *RHSBase = RHSExpr;
16761 const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16762 const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16763 if (!LHSME || !RHSME)
16766 while (LHSME && RHSME) {
16773 LHSME = dyn_cast<MemberExpr>(LHSBase);
16774 RHSME = dyn_cast<MemberExpr>(RHSBase);
16777 LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16778 RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16779 if (LHSDeclRef && RHSDeclRef) {
16786 Diag(OpLoc, diag::warn_self_move)
16793 Diag(OpLoc, diag::warn_self_move)
16817 bool AreUnionMembers =
false) {
16821 assert(((Field1Parent->isStructureOrClassType() &&
16822 Field2Parent->isStructureOrClassType()) ||
16823 (Field1Parent->isUnionType() && Field2Parent->isUnionType())) &&
16824 "Can't evaluate layout compatibility between a struct field and a "
16826 assert(((!AreUnionMembers && Field1Parent->isStructureOrClassType()) ||
16827 (AreUnionMembers && Field1Parent->isUnionType())) &&
16828 "AreUnionMembers should be 'true' for union fields (only).");
16842 if (Bits1 != Bits2)
16846 if (Field1->
hasAttr<clang::NoUniqueAddressAttr>() ||
16847 Field2->
hasAttr<clang::NoUniqueAddressAttr>())
16850 if (!AreUnionMembers &&
16862 if (
const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1))
16863 RD1 = D1CXX->getStandardLayoutBaseWithFields();
16865 if (
const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2))
16866 RD2 = D2CXX->getStandardLayoutBaseWithFields();
16871 return isLayoutCompatible(C, F1, F2);
16882 for (
auto *Field1 : RD1->
fields()) {
16883 auto It = llvm::find_if(UnmatchedFields, [&](
const FieldDecl *Field2) {
16886 if (It == UnmatchedFields.end())
16888 [[maybe_unused]]
bool Result = UnmatchedFields.erase(*It);
16892 return UnmatchedFields.empty();
16918 if (
C.hasSameType(T1, T2))
16927 if (TC1 == Type::Enum)
16929 if (TC1 == Type::Record) {
16948 QualType BaseT =
Base->getType()->getCanonicalTypeUnqualified();
16980 bool isConstantEvaluated) {
16988 case Stmt::UnaryOperatorClass: {
16997 case Stmt::DeclRefExprClass: {
17003 case Stmt::IntegerLiteralClass: {
17005 llvm::APInt MagicValueAPInt = IL->
getValue();
17006 if (MagicValueAPInt.getActiveBits() <= 64) {
17007 *MagicValue = MagicValueAPInt.getZExtValue();
17013 case Stmt::BinaryConditionalOperatorClass:
17014 case Stmt::ConditionalOperatorClass: {
17019 isConstantEvaluated)) {
17029 case Stmt::BinaryOperatorClass: {
17032 TypeExpr = BO->
getRHS();
17062 const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
17065 bool isConstantEvaluated) {
17066 FoundWrongKind =
false;
17073 if (!
FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
17077 if (TypeTagForDatatypeAttr *I = VD->
getAttr<TypeTagForDatatypeAttr>()) {
17078 if (I->getArgumentKind() != ArgumentKind) {
17079 FoundWrongKind =
true;
17082 TypeInfo.Type = I->getMatchingCType();
17083 TypeInfo.LayoutCompatible = I->getLayoutCompatible();
17084 TypeInfo.MustBeNull = I->getMustBeNull();
17095 MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
17096 if (I == MagicValues->end())
17105 bool LayoutCompatible,
17107 if (!TypeTagForDatatypeMagicValues)
17108 TypeTagForDatatypeMagicValues.reset(
17109 new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
17112 (*TypeTagForDatatypeMagicValues)[Magic] =
17128 return (T1Kind == BuiltinType::SChar && T2Kind == BuiltinType::Char_S) ||
17129 (T1Kind == BuiltinType::UChar && T2Kind == BuiltinType::Char_U) ||
17130 (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
17131 (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
17134void Sema::CheckArgumentWithTypeTag(
const ArgumentWithTypeTagAttr *
Attr,
17137 const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
17138 bool IsPointerAttr = Attr->getIsPointer();
17141 unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
17142 if (TypeTagIdxAST >= ExprArgs.size()) {
17143 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17144 << 0 << Attr->getTypeTagIdx().getSourceIndex();
17147 const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
17148 bool FoundWrongKind;
17151 TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
17153 if (FoundWrongKind)
17155 diag::warn_type_tag_for_datatype_wrong_kind)
17161 unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
17162 if (ArgumentIdxAST >= ExprArgs.size()) {
17163 Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
17164 << 1 << Attr->getArgumentIdx().getSourceIndex();
17167 const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
17168 if (IsPointerAttr) {
17170 if (
const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
17171 if (ICE->getType()->isVoidPointerType() &&
17172 ICE->getCastKind() == CK_BitCast)
17173 ArgumentExpr = ICE->getSubExpr();
17175 QualType ArgumentType = ArgumentExpr->
getType();
17181 if (TypeInfo.MustBeNull) {
17186 diag::warn_type_safety_null_pointer_required)
17194 QualType RequiredType = TypeInfo.Type;
17196 RequiredType =
Context.getPointerType(RequiredType);
17198 bool mismatch =
false;
17199 if (!TypeInfo.LayoutCompatible) {
17200 mismatch = !
Context.hasSameType(ArgumentType, RequiredType);
17221 Diag(ArgumentExpr->
getExprLoc(), diag::warn_type_safety_type_mismatch)
17222 << ArgumentType << ArgumentKind
17223 << TypeInfo.LayoutCompatible << RequiredType
17241 Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
17249 if (!
T->isPointerType() && !
T->isIntegerType() && !
T->isDependentType())
17255 auto &MisalignedMembersForExpr =
17257 auto *MA = llvm::find(MisalignedMembersForExpr, MisalignedMember(Op));
17258 if (MA != MisalignedMembersForExpr.end() &&
17259 (
T->isDependentType() ||
T->isIntegerType() ||
17260 (
T->isPointerType() && (
T->getPointeeType()->isIncompleteType() ||
17262 T->getPointeeType()) <= MA->Alignment))))
17263 MisalignedMembersForExpr.erase(MA);
17272 const auto *ME = dyn_cast<MemberExpr>(E);
17284 bool AnyIsPacked =
false;
17286 QualType BaseType = ME->getBase()->getType();
17287 if (BaseType->isDependentType())
17291 auto *RD = BaseType->castAsRecordDecl();
17296 auto *FD = dyn_cast<FieldDecl>(MD);
17302 AnyIsPacked || (RD->
hasAttr<PackedAttr>() || MD->
hasAttr<PackedAttr>());
17303 ReverseMemberChain.push_back(FD);
17306 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
17308 assert(TopME &&
"We did not compute a topmost MemberExpr!");
17315 const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
17326 if (ExpectedAlignment.
isOne())
17331 for (
const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
17332 Offset +=
Context.toCharUnitsFromBits(
Context.getFieldOffset(FD));
17336 Context.getCanonicalTagType(ReverseMemberChain.back()->getParent()));
17340 if (DRE && !TopME->
isArrow()) {
17343 CompleteObjectAlignment =
17344 std::max(CompleteObjectAlignment,
Context.getDeclAlign(VD));
17348 if (!Offset.isMultipleOf(ExpectedAlignment) ||
17351 CompleteObjectAlignment < ExpectedAlignment) {
17362 for (
FieldDecl *FDI : ReverseMemberChain) {
17363 if (FDI->hasAttr<PackedAttr>() ||
17364 FDI->getParent()->hasAttr<PackedAttr>()) {
17366 Alignment = std::min(
Context.getTypeAlignInChars(FD->
getType()),
17372 assert(FD &&
"We did not find a packed FieldDecl!");
17373 Action(E, FD->
getParent(), FD, Alignment);
17377void Sema::CheckAddressOfPackedMember(
Expr *rhs) {
17378 using namespace std::placeholders;
17381 rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*
this), _1,
17405bool Sema::BuiltinElementwiseMath(
CallExpr *TheCall,
17406 EltwiseBuiltinArgTyRestriction ArgTyRestr) {
17433 return S.
Diag(Loc, diag::err_conv_mixed_enum_types)
17450 assert(!Args.empty() &&
"Should have at least one argument.");
17452 Expr *Arg0 = Args.front();
17455 auto EmitError = [&](
Expr *ArgI) {
17457 diag::err_typecheck_call_different_arg_types)
17458 << Arg0->
getType() << ArgI->getType();
17463 for (
Expr *ArgI : Args.drop_front())
17474 for (
Expr *ArgI : Args.drop_front()) {
17475 const auto *VecI = ArgI->getType()->getAs<
VectorType>();
17478 VecI->getElementType()) ||
17479 Vec0->getNumElements() != VecI->getNumElements()) {
17488std::optional<QualType>
17492 return std::nullopt;
17496 return std::nullopt;
17499 for (
int I = 0; I < 2; ++I) {
17503 return std::nullopt;
17504 Args[I] = Converted.
get();
17511 return std::nullopt;
17514 return std::nullopt;
17516 TheCall->
setArg(0, Args[0]);
17517 TheCall->
setArg(1, Args[1]);
17528 TheCall->
getArg(1), Loc) ||
17530 TheCall->
getArg(2), Loc))
17534 for (
int I = 0; I < 3; ++I) {
17539 Args[I] = Converted.
get();
17542 int ArgOrdinal = 1;
17543 for (
Expr *Arg : Args) {
17545 ArgTyRestr, ArgOrdinal++))
17552 for (
int I = 0; I < 3; ++I)
17553 TheCall->
setArg(I, Args[I]);
17559bool Sema::PrepareBuiltinReduceMathOneArgCall(
CallExpr *TheCall) {
17571bool Sema::BuiltinNonDeterministicValue(
CallExpr *TheCall) {
17580 diag::err_builtin_invalid_arg_type)
17581 << 1 << 2 << 1 << 1 << TyArg;
17595 Expr *Matrix = MatrixArg.
get();
17597 auto *MType = Matrix->
getType()->
getAs<ConstantMatrixType>();
17600 << 1 << 3 << 0 << 0
17607 QualType ResultType =
Context.getConstantMatrixType(
17608 MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
17611 TheCall->
setType(ResultType);
17614 TheCall->
setArg(0, Matrix);
17619static std::optional<unsigned>
17643 if (
getLangOpts().getDefaultMatrixMemoryLayout() !=
17645 Diag(TheCall->
getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17653 unsigned PtrArgIdx = 0;
17654 Expr *PtrExpr = TheCall->
getArg(PtrArgIdx);
17655 Expr *RowsExpr = TheCall->
getArg(1);
17656 Expr *ColumnsExpr = TheCall->
getArg(2);
17657 Expr *StrideExpr = TheCall->
getArg(3);
17659 bool ArgError =
false;
17666 PtrExpr = PtrConv.
get();
17667 TheCall->
setArg(0, PtrExpr);
17674 auto *PtrTy = PtrExpr->
getType()->
getAs<PointerType>();
17675 QualType ElementTy;
17678 << PtrArgIdx + 1 << 0 << 5 << 0
17682 ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
17686 << PtrArgIdx + 1 << 0 << 5
17693 auto ApplyArgumentConversions = [
this](Expr *E) {
17702 ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
17704 RowsExpr = RowsConv.
get();
17705 TheCall->
setArg(1, RowsExpr);
17707 RowsExpr =
nullptr;
17709 ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
17711 ColumnsExpr = ColumnsConv.
get();
17712 TheCall->
setArg(2, ColumnsExpr);
17714 ColumnsExpr =
nullptr;
17725 std::optional<unsigned> MaybeRows;
17729 std::optional<unsigned> MaybeColumns;
17734 ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
17737 StrideExpr = StrideConv.
get();
17738 TheCall->
setArg(3, StrideExpr);
17741 if (std::optional<llvm::APSInt>
Value =
17744 if (Stride < *MaybeRows) {
17746 diag::err_builtin_matrix_stride_too_small);
17752 if (ArgError || !MaybeRows || !MaybeColumns)
17756 Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
17767 if (
getLangOpts().getDefaultMatrixMemoryLayout() !=
17769 Diag(TheCall->
getBeginLoc(), diag::err_builtin_matrix_major_order_disabled)
17777 unsigned PtrArgIdx = 1;
17778 Expr *MatrixExpr = TheCall->
getArg(0);
17779 Expr *PtrExpr = TheCall->
getArg(PtrArgIdx);
17780 Expr *StrideExpr = TheCall->
getArg(2);
17782 bool ArgError =
false;
17788 MatrixExpr = MatrixConv.
get();
17789 TheCall->
setArg(0, MatrixExpr);
17796 auto *MatrixTy = MatrixExpr->
getType()->
getAs<ConstantMatrixType>();
17799 << 1 << 3 << 0 << 0 << MatrixExpr->
getType();
17807 PtrExpr = PtrConv.
get();
17808 TheCall->
setArg(1, PtrExpr);
17816 auto *PtrTy = PtrExpr->
getType()->
getAs<PointerType>();
17819 << PtrArgIdx + 1 << 0 << 5 << 0
17823 QualType ElementTy = PtrTy->getPointeeType();
17825 Diag(PtrExpr->
getBeginLoc(), diag::err_builtin_matrix_store_to_const);
17830 !
Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
17832 diag::err_builtin_matrix_pointer_arg_mismatch)
17833 << ElementTy << MatrixTy->getElementType();
17848 StrideExpr = StrideConv.
get();
17849 TheCall->
setArg(2, StrideExpr);
17854 if (std::optional<llvm::APSInt>
Value =
17857 if (Stride < MatrixTy->getNumRows()) {
17859 diag::err_builtin_matrix_stride_too_small);
17879 if (!Caller || !Caller->
hasAttr<EnforceTCBAttr>())
17884 llvm::StringSet<> CalleeTCBs;
17885 for (
const auto *A : Callee->specific_attrs<EnforceTCBAttr>())
17886 CalleeTCBs.insert(A->getTCBName());
17887 for (
const auto *A : Callee->specific_attrs<EnforceTCBLeafAttr>())
17888 CalleeTCBs.insert(A->getTCBName());
17892 for (
const auto *A : Caller->
specific_attrs<EnforceTCBAttr>()) {
17893 StringRef CallerTCB = A->getTCBName();
17894 if (CalleeTCBs.count(CallerTCB) == 0) {
17895 this->
Diag(CallExprLoc, diag::warn_tcb_enforcement_violation)
17896 << Callee << CallerTCB;
Defines the clang::ASTContext interface.
Provides definitions for the various language-specific address spaces.
Defines the Diagnostic-related interfaces.
Defines enumerations for traits support.
static bool getTypeString(SmallStringEnc &Enc, const Decl *D, const CodeGen::CodeGenModule &CGM, TypeStringCache &TSC)
The XCore ABI includes a type information section that communicates symbol type information to the li...
static Decl::Kind getKind(const Decl *D)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Result
Implement __builtin_bit_cast and related operations.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
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.
llvm::MachO::Target Target
llvm::MachO::Record Record
Defines the clang::OpenCLOptions class.
Defines an enumeration for C++ overloaded operators.
Implements a partial diagnostic that can be emitted anwyhere in a DiagnosticBuilder stream.
static bool compare(const PathDiagnostic &X, const PathDiagnostic &Y)
static std::string getFunctionName(const CallEvent &Call)
static std::string toString(const clang::SanitizerSet &Sanitizers)
Produce a string containing comma-separated names of sanitizers in Sanitizers set.
This file declares semantic analysis functions specific to AMDGPU.
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis functions specific to BPF.
static bool isLayoutCompatibleUnion(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout unions are layout-compatible.
static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx, const ValueDecl **VD, uint64_t *MagicValue, bool isConstantEvaluated)
Given a type tag expression find the type tag itself.
static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E, SourceLocation CC, QualType T)
static QualType getSizeOfArgType(const Expr *E)
If E is a sizeof expression, returns its argument type.
static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr, SourceLocation CallSiteLoc)
static bool checkPointerAuthValue(Sema &S, Expr *&Arg, PointerAuthOpKind OpKind, bool RequireConstant=false)
static bool checkBuiltinInferAllocToken(Sema &S, CallExpr *TheCall)
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).
static ExprResult PointerAuthSignGenericData(Sema &S, CallExpr *Call)
static void builtinAllocaAddrSpace(Sema &S, CallExpr *TheCall)
static ExprResult PointerAuthStrip(Sema &S, CallExpr *Call)
static bool isInvalidOSLogArgTypeForCodeGen(FormatStringType FSType, QualType T)
static bool IsSameFloatAfterCast(const llvm::APFloat &value, const llvm::fltSemantics &Src, const llvm::fltSemantics &Tgt)
Checks whether the given value, which currently has the given source semantics, has the same value wh...
static void AnalyzeComparison(Sema &S, BinaryOperator *E)
Implements -Wsign-compare.
static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend, BinaryOperatorKind BinOpKind, bool AddendIsRight)
static std::pair< QualType, StringRef > shouldNotPrintDirectly(const ASTContext &Context, QualType IntendedTy, const Expr *E)
static QualType GetExprType(const Expr *E)
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx)
This helper function takes an lvalue expression and returns the alignment of a VarDecl and a constant...
static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E, Expr *Constant, Expr *Other, const llvm::APSInt &Value, bool RhsConstant)
static bool IsImplicitBoolFloatConversion(Sema &S, const Expr *Ex, bool ToBool)
static AbsoluteValueKind getAbsoluteValueKind(QualType T)
static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E, const IdentifierInfo *FnName, SourceLocation FnLoc, SourceLocation RParenLoc)
Takes the expression passed to the size_t parameter of functions such as memcmp, strncat,...
static ExprResult BuiltinDumpStruct(Sema &S, CallExpr *TheCall)
static bool BuiltinRotateGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_stdc_rotate_{left,right} was called with two arguments, that the first argument...
static bool CompareFormatSpecifiers(Sema &S, const StringLiteral *Ref, ArrayRef< EquatableFormatArgument > RefArgs, const StringLiteral *Fmt, ArrayRef< EquatableFormatArgument > FmtArgs, const Expr *FmtExpr, bool InFunctionCall)
static bool BuiltinBswapg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bswapg was called with a single argument, which is an unsigned integer,...
static ExprResult BuiltinTriviallyRelocate(Sema &S, CallExpr *TheCall)
static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op)
static bool BuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall, Scope::ScopeFlags NeededScopeFlags, unsigned DiagID)
static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E)
Analyze the given compound assignment for the possible losing of floating-point precision.
static bool doesExprLikelyComputeSize(const Expr *SizeofExpr)
Detect if SizeofExpr is likely to calculate the sizeof an object.
static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr, const StringLiteral *ReferenceFormatString, const Expr *OrigFormatExpr, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, bool inFunctionCall, VariadicCallType CallType, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, bool IgnoreStringsWithoutSpecifiers)
static bool BuiltinPreserveAI(Sema &S, CallExpr *TheCall)
Check the number of arguments and set the result type to the argument type.
static bool CheckForReference(Sema &SemaRef, const Expr *E, const PartialDiagnostic &PD)
static const UnaryExprOrTypeTraitExpr * getAsSizeOfExpr(const Expr *E)
static bool BuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID)
Check that the value argument for __builtin_is_aligned(value, alignment) and __builtin_aligned_{up,...
static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC)
Check conversion of given expression to boolean.
static bool isKnownToHaveUnsignedValue(const Expr *E)
static bool checkBuiltinVectorMathArgTypes(Sema &SemaRef, ArrayRef< Expr * > Args)
Check if all arguments have the same type.
static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call)
Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the last two arguments transpose...
static bool checkPointerAuthEnabled(Sema &S, Expr *E)
static std::string PrettyPrintInRange(const llvm::APSInt &Value, IntRange Range)
static ExprResult BuiltinMaskedStore(Sema &S, CallExpr *TheCall)
static const Expr * getStrlenExprArg(const Expr *E)
static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty, ASTContext &Context)
static bool IsInfOrNanFunction(StringRef calleeName, MathCheck Check)
static bool BuiltinCpu(Sema &S, const TargetInfo &TI, CallExpr *TheCall, const TargetInfo *AuxTI, unsigned BuiltinID)
BuiltinCpu{Supports|Is} - Handle __builtin_cpu_{supports|is}(char *).
static bool isValidMathElementType(QualType T)
static void DiagnoseDeprecatedHIPAtomic(Sema &S, SourceRange ExprRange, MultiExprArg Args, AtomicExpr::AtomicOp Op)
Deprecate __hip_atomic_* builtins in favour of __scoped_atomic_* equivalents.
static bool IsSameCharType(QualType T1, QualType T2)
static ExprResult BuiltinVectorMathConversions(Sema &S, Expr *E)
static bool CheckNonNullExpr(Sema &S, const Expr *Expr)
Checks if a the given expression evaluates to null.
static ExprResult BuiltinIsWithinLifetime(Sema &S, CallExpr *TheCall)
static bool isArgumentExpandedFromMacro(SourceManager &SM, SourceLocation CallLoc, SourceLocation ArgLoc)
Check if the ArgLoc originated from a macro passed to the call at CallLoc.
static IntRange GetValueRange(llvm::APSInt &value, unsigned MaxWidth)
static const IntegerLiteral * getIntegerLiteral(Expr *E)
#define HIP_ATOMIC_FIXABLE(hip, scoped)
static bool CheckBuiltinTargetInSupported(Sema &S, CallExpr *TheCall, ArrayRef< llvm::Triple::ArchType > SupportedArchs)
static const Expr * maybeConstEvalStringLiteral(ASTContext &Context, const Expr *E)
static bool IsStdFunction(const FunctionDecl *FDecl, const char(&Str)[StrLen])
static void AnalyzeAssignment(Sema &S, BinaryOperator *E)
Analyze the given simple or compound assignment for warning-worthy operations.
static bool BuiltinFunctionStart(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_function_start is a function.
static bool BuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall)
static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr, SourceLocation StmtLoc, const NullStmt *Body)
static std::pair< CharUnits, CharUnits > getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType, CharUnits BaseAlignment, CharUnits Offset, ASTContext &Ctx)
Compute the alignment and offset of the base class object given the derived-to-base cast expression a...
static std::pair< const ValueDecl *, CharUnits > findConstantBaseAndOffset(Sema &S, Expr *E)
static QualType getVectorElementType(ASTContext &Context, QualType VecTy)
static bool IsEnumConstOrFromMacro(Sema &S, const Expr *E)
static void diagnoseArrayStarInParamType(Sema &S, QualType PType, SourceLocation Loc)
static std::optional< IntRange > TryGetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth, bool InConstantContext, bool Approximate)
Attempts to estimate an approximate range for the given integer expression.
static unsigned changeAbsFunction(unsigned AbsKind, AbsoluteValueKind ValueKind)
static ExprResult BuiltinMaskedLoad(Sema &S, CallExpr *TheCall)
static void CheckImplicitArgumentConversions(Sema &S, const CallExpr *TheCall, SourceLocation CC)
static bool BuiltinBitreverseg(Sema &S, CallExpr *TheCall)
Checks that __builtin_bitreverseg was called with a single argument, which is an integer.
static void CheckConditionalOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool &ICContext)
static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc, Expr *RHS, bool isProperty)
static ExprResult BuiltinLaunder(Sema &S, CallExpr *TheCall)
static bool CheckMissingFormatAttribute(Sema *S, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, StringLiteral *ReferenceFormatString, unsigned FormatIdx, unsigned FirstDataArg, FormatStringType FormatType, unsigned CallerParamIdx, SourceLocation Loc)
static ExprResult PointerAuthBlendDiscriminator(Sema &S, CallExpr *Call)
static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init, SourceLocation InitLoc)
Analyzes an attempt to assign the given value to a bitfield.
static void CheckCommaOperand(Sema &S, Expr *E, QualType T, SourceLocation CC, bool ExtraCheckForImplicitConversion, llvm::SmallVectorImpl< AnalyzeImplicitConversionsWorkItem > &WorkList)
static void DiagnoseFloatingImpCast(Sema &S, const Expr *E, QualType T, SourceLocation CContext)
Diagnose an implicit cast from a floating point value to an integer value.
static int classifyConstantValue(Expr *Constant)
static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc)
static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range, unsigned AbsKind, QualType ArgType)
static bool isLayoutCompatible(const ASTContext &C, QualType T1, QualType T2)
Check if two types are layout-compatible in C++11 sense.
static ExprResult PointerAuthAuthWithPCAndResign(Sema &S, CallExpr *Call)
static bool checkPointerAuthKey(Sema &S, Expr *&Arg)
static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc, Qualifiers::ObjCLifetime LT, Expr *RHS, bool isProperty)
static bool BuiltinOverflow(Sema &S, CallExpr *TheCall, unsigned BuiltinID)
static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl)
static llvm::SmallPtrSet< MemberKind *, 1 > CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty)
static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T, SourceLocation CC)
static bool IsInfinityFunction(const FunctionDecl *FDecl)
static void DiagnoseImpCast(Sema &S, const Expr *E, QualType SourceType, QualType T, SourceLocation CContext, unsigned diag, bool PruneControlFlow=false)
Diagnose an implicit cast; purely a helper for CheckImplicitConversion.
static void CheckNonNullArguments(Sema &S, const NamedDecl *FDecl, const FunctionProtoType *Proto, ArrayRef< const Expr * > Args, SourceLocation CallSiteLoc)
static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction)
static analyze_format_string::ArgType::MatchKind handleFormatSignedness(analyze_format_string::ArgType::MatchKind Match, DiagnosticsEngine &Diags, SourceLocation Loc)
static bool referToTheSameDecl(const Expr *E1, const Expr *E2)
Check if two expressions refer to the same declaration.
static ExprResult BuiltinMaskedScatter(Sema &S, CallExpr *TheCall)
static bool BuiltinCountZeroBitsGeneric(Sema &S, CallExpr *TheCall)
Checks that __builtin_{clzg,ctzg} was called with a first argument, which is an unsigned integer,...
static ExprResult GetVTablePointer(Sema &S, CallExpr *Call)
static bool requiresParensToAddCast(const Expr *E)
static bool HasEnumType(const Expr *E)
static ExprResult PointerAuthAuthAndResign(Sema &S, CallExpr *Call)
static ExprResult BuiltinInvoke(Sema &S, CallExpr *TheCall)
static const Expr * ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx)
static StringLiteralCheckType checkFormatStringExpr(Sema &S, const StringLiteral *ReferenceFormatString, const Expr *E, ArrayRef< const Expr * > Args, Sema::FormatArgumentPassingKind APK, unsigned format_idx, unsigned firstDataArg, FormatStringType Type, VariadicCallType CallType, bool InFunctionCall, llvm::SmallBitVector &CheckedVarArgs, UncoveredArgHandler &UncoveredArg, llvm::APSInt Offset, std::optional< unsigned > *CallerFormatParamIdx=nullptr, bool IgnoreStringsWithoutSpecifiers=false)
static std::optional< unsigned > getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S)
static ExprResult PointerAuthStringDiscriminator(Sema &S, CallExpr *Call)
static bool ProcessFormatStringLiteral(const Expr *FormatExpr, StringRef &FormatStrRef, size_t &StrLen, ASTContext &Context)
static bool isLayoutCompatibleStruct(const ASTContext &C, const RecordDecl *RD1, const RecordDecl *RD2)
Check if two standard-layout structs are layout-compatible.
static bool BuiltinPopcountg(Sema &S, CallExpr *TheCall)
Checks that __builtin_popcountg was called with a single argument, which is an unsigned integer.
static const Expr * getSizeOfExprArg(const Expr *E)
If E is a sizeof expression, returns its argument expression, otherwise returns NULL.
static void DiagnoseIntInBoolContext(Sema &S, Expr *E)
static bool CheckBuiltinTargetNotInUnsupported(Sema &S, unsigned BuiltinID, CallExpr *TheCall, ArrayRef< llvm::Triple::ObjectFormatType > UnsupportedObjectFormatTypes)
static void DiagnoseMixedUnicodeImplicitConversion(Sema &S, const Type *Source, const Type *Target, Expr *E, QualType T, SourceLocation CC)
static bool BuiltinAddressof(Sema &S, CallExpr *TheCall)
Check that the argument to __builtin_addressof is a glvalue, and set the result type to the correspon...
static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S)
static bool CheckMaskedBuiltinArgs(Sema &S, Expr *MaskArg, Expr *PtrArg, unsigned Pos, bool AllowConst, bool AllowAS)
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 ExprResult PointerAuthSignOrAuth(Sema &S, CallExpr *Call, PointerAuthOpKind OpKind, bool RequireConstant)
static bool checkBuiltinVerboseTrap(CallExpr *Call, Sema &S)
static bool checkConstantArgValueRange(Sema &S, CallExpr *TheCall, unsigned ArgNum, const llvm::APSInt &Result, int Low, int High, bool RangeIsError)
static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc, QualType ArgTy, Sema::EltwiseBuiltinArgTyRestriction ArgTyRestr, int ArgOrdinal)
static bool GetMatchingCType(const IdentifierInfo *ArgumentKind, const Expr *TypeExpr, const ASTContext &Ctx, const llvm::DenseMap< Sema::TypeTagMagicValue, Sema::TypeTagData > *MagicValues, bool &FoundWrongKind, Sema::TypeTagData &TypeInfo, bool isConstantEvaluated)
Retrieve the C type corresponding to type tag TypeExpr.
static QualType getAbsoluteValueArgumentType(ASTContext &Context, unsigned AbsType)
static ExprResult BuiltinMaskedGather(Sema &S, CallExpr *TheCall)
static bool ConvertMaskedBuiltinArgs(Sema &S, CallExpr *TheCall)
static bool isNonNullType(QualType type)
Determine whether the given type has a non-null nullability annotation.
static constexpr unsigned short combineFAPK(Sema::FormatArgumentPassingKind A, Sema::FormatArgumentPassingKind B)
static bool BuiltinAnnotation(Sema &S, CallExpr *TheCall)
Check that the first argument to __builtin_annotation is an integer and the second argument is a non-...
static std::optional< std::pair< CharUnits, CharUnits > > getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx)
This helper function takes a pointer expression and returns the alignment of a VarDecl and a constant...
static bool IsShiftedByte(llvm::APSInt Value)
static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType, unsigned AbsFunctionKind)
static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex)
checkBuiltinArgument - Given a call to a builtin function, perform normal type-checking on the given ...
static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E)
Analyze the operands of the given comparison.
static ExprResult PointerAuthAuthLoadRelativeAndSign(Sema &S, CallExpr *Call)
static bool BuiltinStdCBuiltin(Sema &S, CallExpr *TheCall, QualType ReturnType)
Checks the __builtin_stdc_* builtins that take a single unsigned integer argument and return either i...
static bool checkBuiltinVectorMathMixedEnums(Sema &S, Expr *LHS, Expr *RHS, SourceLocation Loc)
static bool isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE)
Return true if ICE is an implicit argument promotion of an arithmetic type.
static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC, bool IsListInit=false)
AnalyzeImplicitConversions - Find and report any interesting implicit conversions in the given expres...
static std::optional< std::pair< CharUnits, CharUnits > > getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE, bool IsSub, ASTContext &Ctx)
Compute the alignment and offset of a binary additive operator.
static bool BuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall)
static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn, ParmVarDecl **LastParam=nullptr)
This file declares semantic analysis for DirectX constructs.
This file declares semantic analysis for HLSL constructs.
This file declares semantic analysis functions specific to Hexagon.
This file declares semantic analysis functions specific to LoongArch.
This file declares semantic analysis functions specific to MIPS.
This file declares semantic analysis functions specific to NVPTX.
This file declares semantic analysis for Objective-C.
This file declares semantic analysis routines for OpenCL.
This file declares semantic analysis functions specific to PowerPC.
This file declares semantic analysis functions specific to RISC-V.
This file declares semantic analysis for SPIRV constructs.
This file declares semantic analysis for SYCL constructs.
This file declares semantic analysis functions specific to SystemZ.
This file declares semantic analysis functions specific to Wasm.
This file declares semantic analysis functions specific to X86.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines various enumerations that describe declaration and type specifiers.
Provides definitions for the atomic synchronization scopes.
C Language Family Type Representation.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__DEVICE__ int min(int __a, int __b)
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
MatchKind
How well a given conversion specifier matches its argument.
@ NoMatch
The conversion specifier and the argument types are incompatible.
@ NoMatchPedantic
The conversion specifier and the argument type are disallowed by the C standard, but are in practice ...
@ Match
The conversion specifier and the argument type are compatible.
@ MatchPromotion
The conversion specifier and the argument type are compatible because of default argument promotions.
@ NoMatchSignedness
The conversion specifier and the argument type have different sign.
@ NoMatchTypeConfusion
The conversion specifier and the argument type are compatible, but still seems likely to be an error.
@ NoMatchPromotionTypeConfusion
The conversion specifier and the argument type are compatible but still seems likely to be an error.
unsigned getLength() const
const char * getStart() const
StringRef toString() const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantAmount() const
unsigned getConstantLength() const
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.
void toString(raw_ostream &os) const
Sema::SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when the only matching conversion function is explicit.
Sema::SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when the expression has incomplete class type.
Sema::SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for one of the candidate conversions.
Sema::SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic when there are multiple possible conversion functions.
Sema::SemaDiagnosticBuilder diagnoseNoMatch(Sema &S, SourceLocation Loc, QualType T) override
Emits a diagnostic complaining that the expression does not have integral or enumeration type.
RotateIntegerConverter(unsigned ArgIndex, bool OnlyUnsigned)
Sema::SemaDiagnosticBuilder diagnoseConversion(Sema &S, SourceLocation Loc, QualType T, QualType ConvTy) override
Emits a diagnostic when we picked a conversion function (for cases when we are not allowed to pick a ...
Sema::SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, QualType ConvTy) override
Emits a note for the explicit conversion function.
bool match(QualType T) override
Determine whether the specified type is a valid destination type for this conversion.
bool fixType(QualType QT, QualType RawQT, const LangOptions &LangOpt, ASTContext &Ctx)
void toString(raw_ostream &os) const
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
APSInt & getComplexIntImag()
bool isComplexInt() const
bool isComplexFloat() const
APValue & getVectorElt(unsigned I)
unsigned getVectorLength() const
APValue & getMatrixElt(unsigned Idx)
APSInt & getComplexIntReal()
APFloat & getComplexFloatImag()
APFloat & getComplexFloatReal()
unsigned getMatrixNumElements() const
bool isAddrLabelDiff() const
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
const ConstantArrayType * getAsConstantArrayType(QualType T) const
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
Builtin::Context & BuiltinInfo
const LangOptions & getLangOpts() const
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
int getFloatingTypeSemanticOrder(QualType LHS, QualType RHS) const
Compare the rank of two floating point types as above, but compare equal if both types have the same ...
QualType getUIntPtrType() const
Return a type compatible with "uintptr_t" (C99 7.18.1.4), as defined by the target.
int getFloatingTypeOrder(QualType LHS, QualType RHS) const
Compare the rank of the two specified floating point types, ignoring the domain of the type (i....
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
QualType removeAddrSpaceQualType(QualType T) const
Remove any existing address space on the type and returns the type with qualifiers intact (or that's ...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
const clang::PrintingPolicy & getPrintingPolicy() const
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CanQualType UnsignedIntTy
QualType getTypedefType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier Qualifier, const TypedefNameDecl *Decl, QualType UnderlyingType=QualType(), std::optional< bool > TypeMatchesDeclOrNone=std::nullopt) const
Return the unique reference to the type for the specified typedef-name decl.
CanQualType UnsignedShortTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
StringLiteral * getPredefinedStringLiteralFromCache(StringRef Key) const
Return a string representing the human readable name for the specified function declaration or file n...
QualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
QualType getExtVectorType(QualType VectorType, unsigned NumElts) const
Return the unique reference to an extended vector type of the specified element type and size.
const TargetInfo & getTargetInfo() const
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
CanQualType getCanonicalTagType(const TagDecl *TD) const
bool isPromotableIntegerType(QualType T) const
More type predicates useful for type checking/promotion.
static bool hasSameUnqualifiedType(QualType T1, QualType T2)
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
CharUnits getNonVirtualAlignment() const
getNonVirtualAlignment - Get the non-virtual alignment (in chars) of an object, which is the alignmen...
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
SourceLocation getQuestionLoc() const
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Expr * getBase()
Get base of the array section.
Expr * getLowerBound()
Get lower bound of array section.
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
SourceLocation getRBracketLoc() const
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Represents an array type, per C99 6.7.5.2 - Array Declarators.
ArraySizeModifier getSizeModifier() const
QualType getElementType() const
AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*, __atomic_load,...
static std::unique_ptr< AtomicScopeModel > getScopeModel(AtomicOp Op)
Get atomic scope model for the atomic op code.
SourceLocation getBeginLoc() const LLVM_READONLY
Attr - This represents one attribute.
const char * getSpelling() const
Type source information for an attributed type.
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
A builtin binary operation expression such as "x + y" or "x <= y".
static bool isLogicalOp(Opcode Opc)
SourceLocation getOperatorLoc() const
SourceLocation getExprLoc() const
static StringRef getOpcodeStr(Opcode Op)
getOpcodeStr - Turn an Opcode enum value into the punctuation char it corresponds to,...
static bool isAdditiveOp(Opcode Opc)
static bool isEqualityOp(Opcode Opc)
BinaryOperatorKind Opcode
This class is used for builtin types like 'int'.
bool isFloatingPoint() const
bool isSignedInteger() const
bool isUnsignedInteger() const
llvm::SmallString< 64 > getQuotedName(unsigned ID) const
Return the identifier name for the specified builtin inside single quotes for a diagnostic,...
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
std::string getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
Represents a base class of a C++ class.
Represents a call to a C++ constructor.
bool isListInitialization() const
Whether this constructor call was written as list-initialization.
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Represents a C++ conversion function within a class.
Represents a C++ destructor within a class.
Represents a static or instance method of a struct/union/class.
A call to an overloaded operator written using operator syntax.
SourceLocation getExprLoc() const LLVM_READONLY
OverloadedOperatorKind getOperator() const
Returns the kind of overloaded operator that this expression refers to.
Represents a list-initialization with parenthesis.
MutableArrayRef< Expr * > getInitExprs()
Represents a C++ struct/union/class.
bool isStandardLayout() const
Determine whether this class is standard-layout per C++ [class]p7.
CXXRecordDecl * getDefinition() const
bool isPolymorphic() const
Whether this class is polymorphic (C++ [class.virtual]), which means that the class contains or inher...
bool isDynamicClass() const
Represents a C++ nested-name-specifier or a global scope specifier.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
SourceLocation getBeginLoc() const
void setArg(unsigned Arg, Expr *ArgExpr)
setArg - Set the specified argument.
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
bool isCallToStdMove() const
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
FPOptions getFPFeaturesInEffect(const LangOptions &LO) const
Get the FP features status of this operator.
Expr ** getArgs()
Retrieve the call arguments.
SourceLocation getEndLoc() const
SourceLocation getRParenLoc() const
bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const
Returns true if this is a call to a builtin which does not evaluate side-effects within its arguments...
void shrinkNumArgs(unsigned NewNumArgs)
Reduce the number of arguments in this call expression.
QualType withConst() const
Retrieves a version of this type with const applied.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
path_iterator path_begin()
CastKind getCastKind() const
Represents a byte-granular source range.
static CharSourceRange getCharRange(SourceRange R)
static CharSourceRange getTokenRange(SourceRange R)
SourceLocation getBegin() const
This is an opaque type for sizes expressed in character units.
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
bool isOne() const
Test whether the quantity equals one.
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Construct a CharUnits quantity of zero.
ConditionalOperator - The ?
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Represents the canonical version of C arrays with a specified constant size.
llvm::APInt getSize() const
Return the constant array size as an APInt.
static ConstantExpr * Create(const ASTContext &Context, Expr *E, const APValue &Result)
Represents a concrete matrix type with constant number of rows and columns.
unsigned getNumElementsFlattened() const
Returns the number of elements required to embed the matrix into a vector.
static ConvertVectorExpr * Create(const ASTContext &C, Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType, ExprValueKind VK, ExprObjectKind OK, SourceLocation BuiltinLoc, SourceLocation RParenLoc, FPOptionsOverride FPFeatures)
Expr * getOperand() const
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
DeclContext * getParent()
getParent - Returns the containing DeclContext.
bool isStdNamespace() const
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
A reference to a declared variable, function, enum, etc.
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, NonOdrUseReason NOUR=NOUR_None)
NestedNameSpecifierLoc getQualifierLoc() const
If the name was qualified, retrieves the nested-name-specifier that precedes the name,...
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
SourceLocation getBeginLoc() const
SourceLocation getLocation() const
Decl - This represents one declaration (or definition), e.g.
bool isInStdNamespace() const
SourceLocation getEndLoc() const LLVM_READONLY
unsigned getMaxAlignment() const
getMaxAlignment - return the maximum alignment specified by attributes on this decl,...
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
bool isInvalidDecl() const
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
SourceLocation getLocation() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
The name of a declaration.
std::string getAsString() const
Retrieve the human-readable string for this name.
SourceLocation getTypeSpecStartLoc() const
TypeSourceInfo * getTypeSourceInfo() const
bool hasUnrecoverableErrorOccurred() const
Determine whether any unrecoverable errors have occurred since this object instance was created.
Concrete class used by the front-end to report problems and issues.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
An instance of this object exists for each enum constant that is defined.
bool isComplete() const
Returns true if this can be considered a complete type.
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
This represents one expression.
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
bool isIntegerConstantExpr(const ASTContext &Ctx) const
Expr * IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY
Skip past any parentheses and casts which do not change the value (including ptr->int casts of the sa...
@ SE_AllowSideEffects
Allow any unmodeled side effect.
@ SE_NoSideEffects
Strictly evaluate the expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
bool isValueDependent() const
Determines whether the value of this expression depends on.
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
bool isTypeDependent() const
Determines whether the type of this expression depends on.
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFloat - Return true if this is a constant which we can fold and convert to a floating point...
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
bool isFlexibleArrayMemberLike(const ASTContext &Context, LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel, bool IgnoreTemplateOrMacroSubstitution=false) const
Check whether this array fits the idiom of a flexible array member, depending on the value of -fstric...
bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsFixedPoint - Return true if this is a constant which we can fold and convert to a fixed poi...
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
FieldDecl * getSourceBitField()
If this expression refers to a bit-field, retrieve the declaration of that bit-field.
@ NPC_ValueDependentIsNull
Specifies that a value-dependent expression of integral or dependent type should be considered a null...
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreCasts() LLVM_READONLY
Skip past any casts which might surround this expression until reaching a fixed point.
Expr * IgnoreImplicitAsWritten() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
std::optional< uint64_t > tryEvaluateStrLen(const ASTContext &Ctx) const
If the current Expr is a pointer, this will try to statically determine the strlen of the string poin...
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
bool EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx, ConstantExprKind Kind=ConstantExprKind::Normal) const
Evaluate an expression that is required to be a constant expression.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
std::optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, bool AllowRelaxedEval=false) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
NullPointerConstantKind
Enumeration used to describe the kind of Null pointer constant returned from isNullPointerConstant().
@ NPCK_ZeroExpression
Expression is a Null pointer constant built from a zero integer expression that is not a simple,...
@ NPCK_ZeroLiteral
Expression is a Null pointer constant built from a literal zero.
@ NPCK_NotNull
Expression is not a Null pointer constant.
bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsBooleanCondition - Return true if this is a constant which we can fold and convert to a boo...
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
QualType getEnumCoercedType(const ASTContext &Ctx) const
If this expression is an enumeration constant, return the enumeration type under which said constant ...
std::optional< uint64_t > tryEvaluateObjectSize(const ASTContext &Ctx, unsigned Type) const
If the current Expr is a pointer, this will try to statically determine the number of bytes available...
void setValueKind(ExprValueKind Cat)
setValueKind - Set the value kind produced by this expression.
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
void setObjectKind(ExprObjectKind Cat)
setObjectKind - Set the object kind produced by this expression.
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
const ValueDecl * getAsBuiltinConstantDeclRef(const ASTContext &Context) const
If this expression is an unambiguous reference to a single declaration, in the style of __builtin_fun...
bool isKnownToHaveBooleanValue(bool Semantic=true) const
isKnownToHaveBooleanValue - Return true if this is an integer expression that is known to return 0 or...
void EvaluateForOverflow(const ASTContext &Ctx) const
ExtVectorType - Extended vector type.
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
unsigned getBitWidthValue() const
Computes the bit width of this field, if this is a bit field.
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
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.
llvm::APFloat getValue() const
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Represents a function declaration or definition.
unsigned getMemoryFunctionKind() const
Identify a memory copying or setting function.
const ParmVarDecl * getParamDecl(unsigned i) const
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
param_iterator param_end()
bool hasCXXExplicitFunctionObjectParameter() const
QualType getReturnType() const
ArrayRef< ParmVarDecl * > parameters() const
param_iterator param_begin()
bool isVariadic() const
Whether this function is variadic.
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Represents a prototype with parameter type info, e.g.
unsigned getNumParams() const
QualType getParamType(unsigned i) const
bool isVariadic() const
Whether this function prototype is variadic.
ExtProtoInfo getExtProtoInfo() const
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
ArrayRef< QualType > getParamTypes() const
FunctionType - C99 6.7.5.3 - Function Declarators.
static StringRef getNameForCallConv(CallingConv CC)
@ SME_PStateSMEnabledMask
@ SME_PStateSMCompatibleMask
static ArmStateValue getArmZT0State(unsigned AttrBits)
static ArmStateValue getArmZAState(unsigned AttrBits)
CallingConv getCallConv() const
QualType getReturnType() const
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Describes an C or C++ initializer list.
ArrayRef< Expr * > inits() const
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
StrictFlexArraysLevelKind
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Represents the results of name lookup.
UnresolvedSetImpl::iterator iterator
Represents a matrix type, as defined in the Matrix Types clang extensions.
static bool isValidElementType(QualType T, const LangOptions &LangOpts)
Valid elements types are the following:
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
A pointer to member type per C++ 8.3.3 - Pointers to members.
This represents a decl that may have a name.
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
bool hasLinkage() const
Determine whether this declaration has linkage.
Represent a C++ namespace.
NullStmt - This is the null statement ";": C99 6.8.3p3.
bool hasLeadingEmptyMacro() const
SourceLocation getSemiLoc() const
Represents an ObjC class declaration.
Represents one property declaration in an Objective-C interface.
ObjCPropertyAttribute::Kind getPropertyAttributesAsWritten() const
ObjCPropertyAttribute::Kind getPropertyAttributes() const
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
ObjCPropertyDecl * getExplicitProperty() const
bool isImplicitProperty() const
ObjCStringLiteral, used for Objective-C string literals i.e.
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
ParenExpr - This represents a parenthesized expression, e.g.
Represents a parameter to a function.
Pointer-authentication qualifiers.
@ MaxDiscriminator
The maximum supported pointer-authentication discriminator.
bool isAddressDiscriminated() const
ARM8_3Key
Hardware pointer-signing keys in ARM8.3.
PointerType - C99 6.7.5.1 - Pointer Declarators.
QualType getPointeeType() const
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
static PseudoObjectExpr * Create(const ASTContext &Context, Expr *syntactic, ArrayRef< Expr * > semantic, unsigned resultIndex)
A (possibly-)qualified type.
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
PointerAuthQualifier getPointerAuth() const
PrimitiveDefaultInitializeKind
QualType withoutLocalFastQualifiers() const
bool isNull() const
Return true if this QualType doesn't point to a type yet.
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
void removeLocalVolatile()
QualType withCVRQualifiers(unsigned CVR) const
bool isConstQualified() const
Determine whether this type is const-qualified.
bool hasAddressSpace() const
Check if this type has any address space qualifier.
QualType getAtomicUnqualifiedType() const
Remove all qualifiers including _Atomic.
unsigned getCVRQualifiers() const
Retrieve the set of CVR (const-volatile-restrict) qualifiers applied to this type.
bool hasNonTrivialObjCLifetime() const
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
@ OCL_None
There is no lifetime qualification on this type.
@ OCL_Weak
Reading or writing from this object requires a barrier call.
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
bool hasUnaligned() const
Represents a struct/union/class.
bool hasFlexibleArrayMember() const
bool isNonTrivialToPrimitiveCopy() const
field_range fields() const
bool isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C structs.
Scope - A scope is a transient data structure that is used while parsing the program.
bool isSEHExceptScope() const
Determine whether this scope is a SEH '__except' block.
unsigned getFlags() const
getFlags - Return the flags for this scope.
const Scope * getParent() const
getParent - Return the scope that this is nested in.
ScopeFlags
ScopeFlags - These are bitfields that are or'd together when creating a scope, which defines the sort...
@ SEHFilterScope
We are currently in the filter expression of an SEH except block.
@ SEHExceptScope
This scope corresponds to an SEH except.
bool CheckAMDGCNBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
@ ArmStreaming
Intrinsic is only available in normal mode.
@ ArmStreamingCompatible
Intrinsic is only available in Streaming-SVE mode.
bool CheckAArch64BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
void notePreserveAIEnumerator(const Expr *E)
static bool isPreserveAIEnumeratorRef(const Expr *E)
bool CheckBPFBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
A generic diagnostic builder for errors which may or may not be deferred.
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
bool CheckDirectXBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckHexagonBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckLoongArchBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckMipsBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckNVPTXBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
void checkArrayLiteral(QualType TargetType, ObjCArrayLiteral *ArrayLiteral)
Check an Objective-C array literal being converted to the given target type.
ObjCLiteralKind CheckLiteralKind(Expr *FromE)
void adornBoolConversionDiagWithTernaryFixit(const Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder)
bool isSignedCharBool(QualType Ty)
void DiagnoseCStringFormatDirectiveInCFAPI(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...
void checkDictionaryLiteral(QualType TargetType, ObjCDictionaryLiteral *DictionaryLiteral)
Check an Objective-C dictionary literal being converted to the given target type.
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
bool CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
void checkAIXMemberAlignment(SourceLocation Loc, const Expr *Arg)
bool CheckPPCMMAType(QualType Type, SourceLocation TypeLoc)
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckSPIRVBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
SemaDiagnosticBuilder DiagIfDeviceCode(SourceLocation Loc, unsigned DiagID)
Creates a SemaDiagnosticBuilder that emits the diagnostic if the current context is "used as device c...
bool CheckSystemZBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall)
bool CheckWebAssemblyBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
bool CheckBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID, CallExpr *TheCall)
Abstract base class used to perform a contextual implicit conversion from an expression to any type p...
ContextualImplicitConverter(bool Suppress=false, bool SuppressConversion=false)
Sema - This implements semantic analysis and AST building for C.
const FieldDecl * getSelfAssignmentClassMemberCandidate(const ValueDecl *SelfAssigned)
Returns a field in a CXXRecordDecl that has the same name as the decl SelfAssigned when inside a CXXM...
bool DiscardingCFIUncheckedCallee(QualType From, QualType To) const
Returns true if From is a function or pointer to a function with the cfi_unchecked_callee attribute b...
bool BuiltinConstantArgShiftedByte(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is a constant expression represen...
bool IsPointerInterconvertibleBaseOf(const TypeSourceInfo *Base, const TypeSourceInfo *Derived)
bool diagnoseArgDependentDiagnoseIfAttrs(const FunctionDecl *Function, const Expr *ThisArg, ArrayRef< const Expr * > Args, SourceLocation Loc)
Emit diagnostics for the diagnose_if attributes on Function, ignoring any non-ArgDependent DiagnoseIf...
bool BuiltinConstantArgMultiple(CallExpr *TheCall, unsigned ArgNum, unsigned Multiple)
BuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr TheCall is a constant expr...
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Scope * getCurScope() const
Retrieve the parser's current scope.
std::optional< QualType > BuiltinVectorMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
ExprResult ActOnUnaryOp(Scope *S, SourceLocation OpLoc, tok::TokenKind Op, Expr *Input, bool IsAfterAmp=false)
Unary Operators. 'Tok' is the token for the operator.
bool tryExprAsCall(Expr &E, QualType &ZeroArgCallReturnTy, UnresolvedSetImpl &NonTemplateOverloads)
Figure out if an expression could be turned into a call.
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
@ LookupAnyName
Look up any declaration with any name.
bool checkArgCountAtMost(CallExpr *Call, unsigned MaxArgCount)
Checks that a call expression's argument count is at most the desired number.
bool checkPointerAuthDiscriminatorArg(Expr *Arg, PointerAuthDiscArgKind Kind, unsigned &IntVal)
bool ValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum)
Returns true if the argument consists of one contiguous run of 1s with any number of 0s on either sid...
void RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind, uint64_t MagicValue, QualType Type, bool LayoutCompatible, bool MustBeNull)
Register a magic integral constant to be used as a type tag.
bool isValidPointerAttrType(QualType T, bool RefOkay=false)
Determine if type T is a valid subject for a nonnull and similar attributes.
void DiagnoseAlwaysNonNullPointer(Expr *E, Expr::NullPointerConstantKind NullType, bool IsEqual, SourceRange Range)
Diagnose pointers that are always non-null.
VariadicCallType getVariadicCallType(FunctionDecl *FDecl, const FunctionProtoType *Proto, Expr *Fn)
bool FormatStringHasSArg(const StringLiteral *FExpr)
QualType UsualArithmeticConversions(ExprResult &LHS, ExprResult &RHS, SourceLocation Loc, ArithConvKind ACK)
UsualArithmeticConversions - Performs various conversions that are common to binary operators (C99 6....
void CheckFloatComparison(SourceLocation Loc, const Expr *LHS, const Expr *RHS, BinaryOperatorKind Opcode)
Check for comparisons of floating-point values using == and !=.
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...
const ExpressionEvaluationContextRecord & currentEvaluationContext() const
bool CheckFormatStringsCompatible(FormatStringType FST, const StringLiteral *AuthoritativeFormatString, const StringLiteral *TestedFormatString, const Expr *FunctionCallArg=nullptr)
Verify that two format strings (as understood by attribute(format) and attribute(format_matches) are ...
bool IsCXXTriviallyRelocatableType(QualType T)
Determines if a type is trivially relocatable according to the C++26 rules.
bool CheckOverflowBehaviorTypeConversion(Expr *E, QualType T, SourceLocation CC)
Check for overflow behavior type related implicit conversion diagnostics.
FPOptionsOverride CurFPFeatureOverrides()
FunctionDecl * getCurFunctionDecl(bool AllowLambda=false) const
Returns a pointer to the innermost enclosing function, or nullptr if the current context is not insid...
ExprResult PerformContextualImplicitConversion(SourceLocation Loc, Expr *FromE, ContextualImplicitConverter &Converter)
Perform a contextual implicit conversion.
ExprResult UsualUnaryConversions(Expr *E)
UsualUnaryConversions - Performs various conversions that are common to most operators (C99 6....
bool checkPointerAuthEnabled(SourceLocation Loc, SourceRange Range)
bool BuiltinIsBaseOf(SourceLocation RhsTLoc, QualType LhsT, QualType RhsT)
ExprResult DefaultVariadicArgumentPromotion(Expr *E, VariadicCallType CT, FunctionDecl *FDecl)
ExprResult tryConvertExprToType(Expr *E, QualType Ty)
Try to convert an expression E to type Ty.
QualType CheckAddressOfOperand(ExprResult &Operand, SourceLocation OpLoc)
CheckAddressOfOperand - The operand of & must be either a function designator or an lvalue designatin...
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
DiagnosticsEngine & getDiagnostics() const
bool checkAddressOfFunctionIsAvailable(const FunctionDecl *Function, bool Complain=false, SourceLocation Loc=SourceLocation())
Returns whether the given function's address can be taken or not, optionally emitting a diagnostic if...
void CheckImplicitConversion(Expr *E, QualType T, SourceLocation CC, bool *ICContext=nullptr, bool IsListInit=false)
bool InOverflowBehaviorAssignmentContext
Track if we're currently analyzing overflow behavior types in assignment context.
std::string getFixItZeroLiteralForType(QualType T, SourceLocation Loc) const
ExprResult DefaultFunctionArrayLvalueConversion(Expr *E, bool Diagnose=true)
ASTContext & getASTContext() const
CXXDestructorDecl * LookupDestructor(CXXRecordDecl *Class)
Look for the destructor of the given class.
ExprResult BuildUnaryOp(Scope *S, SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *Input, bool IsAfterAmp=false)
ExprResult ImpCastExprToType(Expr *E, QualType Type, CastKind CK, ExprValueKind VK=VK_PRValue, const CXXCastPath *BasePath=nullptr, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
ImpCastExprToType - If Expr is not of type 'Type', insert an implicit cast.
bool isConstantEvaluatedOverride
Used to change context to isConstantEvaluated without pushing a heavy ExpressionEvaluationContextReco...
bool BuiltinVectorToScalarMath(CallExpr *TheCall)
bool BuiltinConstantArg(CallExpr *TheCall, unsigned ArgNum, llvm::APSInt &Result)
BuiltinConstantArg - Handle a check if argument ArgNum of CallExpr TheCall is a constant expression.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
void DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr, SourceLocation OpLoc)
DiagnoseSelfMove - Emits a warning if a value is moved to itself.
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
bool BuiltinConstantArgRange(CallExpr *TheCall, unsigned ArgNum, int Low, int High, bool RangeIsError=true)
BuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr TheCall is a constant express...
bool IsLayoutCompatible(QualType T1, QualType T2) const
const LangOptions & getLangOpts() const
bool RequireCompleteExprType(Expr *E, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type of the given expression is complete.
void CheckCastAlign(Expr *Op, QualType T, SourceRange TRange)
CheckCastAlign - Implements -Wcast-align, which warns when a pointer cast increases the alignment req...
ExprResult BuildCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr, bool IsExecConfig=false, bool AllowRecovery=false)
BuildCallExpr - Handle a call to Fn with the specified array of arguments.
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
bool hasCStrMethod(const Expr *E)
Check to see if a given expression could have '.c_str()' called on it.
const LangOptions & LangOpts
static const uint64_t MaximumAlignment
VarArgKind isValidVarArgType(const QualType &Ty)
Determine the degree of POD-ness for an expression.
ExprResult ConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo, SourceLocation BuiltinLoc, SourceLocation RParenLoc)
ConvertVectorExpr - Handle __builtin_convertvector.
static StringRef GetFormatStringTypeName(FormatStringType FST)
bool checkConstantPointerAuthKey(Expr *keyExpr, unsigned &key)
bool convertArgumentToType(Expr *&Value, QualType Ty)
bool checkUnsafeAssigns(SourceLocation Loc, QualType LHS, Expr *RHS)
checkUnsafeAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained type.
EltwiseBuiltinArgTyRestriction
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
NamedDecl * getCurFunctionOrMethodDecl() const
getCurFunctionOrMethodDecl - Return the Decl for the current ObjC method or C function we're in,...
ExprResult BuildCStyleCastExpr(SourceLocation LParenLoc, TypeSourceInfo *Ty, SourceLocation RParenLoc, Expr *Op)
void popCodeSynthesisContext()
void DiagnoseMisalignedMembers()
Diagnoses the current set of gathered accesses.
sema::FunctionScopeInfo * getCurFunction() const
void checkUnsafeExprAssigns(SourceLocation Loc, Expr *LHS, Expr *RHS)
checkUnsafeExprAssigns - Check whether +1 expr is being assigned to weak/__unsafe_unretained expressi...
std::pair< const IdentifierInfo *, uint64_t > TypeTagMagicValue
A pair of ArgumentKind identifier and magic value.
QualType BuiltinRemoveCVRef(QualType BaseType, SourceLocation Loc)
bool findMacroSpelling(SourceLocation &loc, StringRef name)
Looks through the macro-expansion chain for the given location, looking for a macro expansion with th...
ExprResult ActOnMemberAccessExpr(Scope *S, Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &Member, Decl *ObjCImpDecl)
The main callback when the parser finds something like expression .
void DiagnoseEmptyStmtBody(SourceLocation StmtLoc, const Stmt *Body, unsigned DiagID)
Emit DiagID if statement located on StmtLoc has a suspicious null statement as a Body,...
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...
ExprResult DefaultLvalueConversion(Expr *E)
SourceLocation getLocationOfStringLiteralByte(const StringLiteral *SL, unsigned ByteNo) const
void CheckTCBEnforcement(const SourceLocation CallExprLoc, const NamedDecl *Callee)
Enforce the bounds of a TCB CheckTCBEnforcement - Enforces that every function in a named TCB only di...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
bool checkArgCountAtLeast(CallExpr *Call, unsigned MinArgCount)
Checks that a call expression's argument count is at least the desired number.
FormatArgumentPassingKind
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool isUnevaluatedContext() const
Determines whether we are currently in a context that is not evaluated as per C++ [expr] p5.
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
SourceManager & getSourceManager() const
static FormatStringType GetFormatStringType(StringRef FormatFlavor)
ExprResult BuildFieldReferenceExpr(Expr *BaseExpr, bool IsArrow, SourceLocation OpLoc, const CXXScopeSpec &SS, FieldDecl *Field, DeclAccessPair FoundDecl, const DeclarationNameInfo &MemberNameInfo)
bool checkArgCountRange(CallExpr *Call, unsigned MinArgCount, unsigned MaxArgCount)
Checks that a call expression's argument count is in the desired range.
bool ValidateFormatString(FormatStringType FST, const StringLiteral *Str)
Verify that one format string (as understood by attribute(format)) is self-consistent; for instance,...
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 PrepareBuiltinElementwiseMathOneArgCall(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::None)
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
ExprResult BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, SourceLocation nameLoc, IndirectFieldDecl *indirectField, DeclAccessPair FoundDecl=DeclAccessPair::make(nullptr, AS_none), Expr *baseObjectExpr=nullptr, SourceLocation opLoc=SourceLocation())
ExprResult PerformImplicitConversion(Expr *From, QualType ToType, const ImplicitConversionSequence &ICS, AssignmentAction Action, CheckedConversionKind CCK=CheckedConversionKind::Implicit)
PerformImplicitConversion - Perform an implicit conversion of the expression From to the type ToType ...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
ExprResult ActOnBinOp(Scope *S, SourceLocation TokLoc, tok::TokenKind Kind, Expr *LHSExpr, Expr *RHSExpr)
Binary Operators. 'Tok' is the token for the operator.
bool isConstantEvaluatedContext() const
bool BuiltinElementwiseTernaryMath(CallExpr *TheCall, EltwiseBuiltinArgTyRestriction ArgTyRestr=EltwiseBuiltinArgTyRestriction::FloatTy)
bool checkArgCount(CallExpr *Call, unsigned DesiredArgCount)
Checks that a call expression's argument count is the desired number.
ExprResult BuiltinShuffleVector(CallExpr *TheCall)
BuiltinShuffleVector - Handle __builtin_shufflevector.
QualType GetSignedVectorType(QualType V)
Return a signed ext_vector_type that is of identical size and number of elements.
void CheckConstrainedAuto(const AutoType *AutoT, SourceLocation Loc)
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
static bool getFormatStringInfo(const Decl *Function, unsigned FormatIdx, unsigned FirstArg, FormatStringInfo *FSI)
Given a function and its FormatAttr or FormatMatchesAttr info, attempts to populate the FormatStringI...
bool BuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall, unsigned ArgNum, unsigned ArgBits)
BuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of TheCall is a constant expression re...
SourceManager & SourceMgr
ExprResult UsualUnaryFPConversions(Expr *E)
UsualUnaryFPConversions - Promotes floating-point types according to the current language semantics.
DiagnosticsEngine & Diags
NamespaceDecl * getStdNamespace() const
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
void checkVariadicArgument(const Expr *E, VariadicCallType CT)
Check to see if the given expression is a valid argument to a variadic function, issuing a diagnostic...
void checkLifetimeCaptureBy(FunctionDecl *FDecl, bool IsMemberFunction, const Expr *ThisArg, ArrayRef< const Expr * > Args)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
bool BuiltinConstantArgPower2(CallExpr *TheCall, unsigned ArgNum)
BuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a constant expression representing ...
void MarkFunctionReferenced(SourceLocation Loc, FunctionDecl *Func, bool MightBeOdrUse=true)
Mark a function referenced, and check whether it is odr-used (C++ [basic.def.odr]p2,...
ExprResult BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange, SourceLocation RParenLoc, MultiExprArg Args, AtomicExpr::AtomicOp Op, AtomicArgumentOrder ArgOrder=AtomicArgumentOrder::API)
ExprResult ActOnCallExpr(Scope *S, Expr *Fn, SourceLocation LParenLoc, MultiExprArg ArgExprs, SourceLocation RParenLoc, Expr *ExecConfig=nullptr)
ActOnCallExpr - Handle a call to Fn with the specified array of arguments.
SemaLoongArch & LoongArch()
@ Diagnose
Diagnose issues that are non-constant or that are extensions.
bool CheckCXXThrowOperand(SourceLocation ThrowLoc, QualType ThrowTy, Expr *E)
CheckCXXThrowOperand - Validate the operand of a throw.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
bool CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall, const FunctionProtoType *Proto)
CheckFunctionCall - Check a direct function call for various correctness and safety properties not st...
void checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto, const Expr *ThisArg, ArrayRef< const Expr * > Args, bool IsMemberFunction, SourceLocation Loc, SourceRange Range, VariadicCallType CallType)
Handles the checks for format strings, non-POD arguments to vararg functions, NULL arguments passed t...
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
This class handles loading and caching of source files into memory.
bool isMacroBodyExpansion(SourceLocation Loc) const
Tests whether the given source location represents the expansion of a macro body.
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
SourceLocation getTopMacroCallerLoc(SourceLocation Loc) 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...
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
SourceLocation getImmediateMacroCallerLoc(SourceLocation Loc) const
Gets the location of the immediate macro caller, one level up the stack toward the initial macro type...
const char * getCharacterData(SourceLocation SL, bool *Invalid=nullptr) const
Return a pointer to the start of the specified location in the appropriate spelling MemoryBuffer.
bool isInSystemMacro(SourceLocation loc) const
Returns whether Loc is expanded from a macro in a system header.
CharSourceRange getImmediateExpansionRange(SourceLocation Loc) const
Return the start/end of the expansion information for an expansion location.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
Stmt - This represents one statement.
SourceLocation getEndLoc() const LLVM_READONLY
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
StmtClass getStmtClass() const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
void Profile(llvm::FoldingSetNodeID &ID, const ASTContext &Context, bool Canonical, bool ProfileLambdaExpr=false) const
Produce a unique representation of the given statement.
SourceLocation getBeginLoc() const LLVM_READONLY
StringLiteral - This represents a string literal expression, e.g.
SourceLocation getBeginLoc() const LLVM_READONLY
unsigned getLength() const
StringLiteralKind getKind() const
SourceLocation getLocationOfByte(unsigned ByteNo, const SourceManager &SM, const LangOptions &Features, const TargetInfo &Target, unsigned *StartToken=nullptr, unsigned *StartTokenByteOffset=nullptr) const
Return a source location that points to the specified byte of this string literal.
unsigned getByteLength() const
StringRef getString() const
SourceLocation getEndLoc() const LLVM_READONLY
unsigned getCharByteWidth() const
bool isBeingDefined() const
Return true if this decl is currently being defined.
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Exposes information about the current target.
virtual bool supportsCpuSupports() const
virtual bool validateCpuIs(StringRef Name) const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
unsigned getTypeWidth(IntType T) const
Return the width (in bits) of the specified integer type enum.
IntType getSizeType() const
virtual bool validateCpuSupports(StringRef Name) const
virtual bool supportsCpuIs() const
const TemplateArgument & get(unsigned Idx) const
Retrieve the template argument at a given index.
@ Type
The template argument is a type.
The base class of all kinds of template declarations (e.g., class, function, etc.).
Base wrapper for a particular "section" of type source info.
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
SourceLocation getBeginLoc() const
Get the begin source location.
Represents a typeof (or typeof) expression (a C23 feature and GCC extension) or a typeof_unqual expre...
A container of type source information.
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
QualType getType() const
Return the type wrapped by this type source info.
The base class of the type hierarchy.
bool isBlockPointerType() const
bool isBooleanType() const
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
bool isSignedIntegerType() const
Return true if this is an integer type that is signed, according to C99 6.2.5p4 [char,...
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isVoidPointerType() const
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
bool isFunctionPointerType() const
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isEnumeralType() const
bool isScalarType() const
const CXXRecordDecl * getPointeeCXXRecordDecl() const
If this is a pointer or reference to a RecordType, return the CXXRecordDecl that the type refers to.
bool isVariableArrayType() const
bool isSveVLSBuiltinType() const
Determines if this is a sizeless type supported by the 'arm_sve_vector_bits' type attribute,...
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
bool isExtVectorType() const
bool isExtVectorBoolType() const
QualType getSveEltType(const ASTContext &Ctx) const
Returns the representative type for the element of an SVE builtin type.
bool isBitIntType() const
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
bool isBuiltinType() const
Helper methods to distinguish type categories.
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
RecordDecl * castAsRecordDecl() const
bool isAnyComplexType() const
bool hasSignedIntegerRepresentation() const
Determine whether this type has an signed integer representation of some sort, e.g....
QualType getCanonicalTypeInternal() const
bool isWebAssemblyTableType() const
Returns true if this is a WebAssembly table type: either an array of reference types,...
bool isMemberPointerType() const
bool isAtomicType() const
bool isFunctionProtoType() const
bool isMatrixType() const
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
EnumDecl * castAsEnumDecl() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool isUnscopedEnumerationType() const
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
bool isObjectType() const
Determine whether this type is an object type.
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool isFunctionType() const
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
bool isStructureOrClassType() const
bool isVectorType() const
bool isRealFloatingType() const
Floating point categories.
bool isFloatingType() const
bool isUnsignedIntegerType() const
Return true if this is an integer type that is unsigned, according to C99 6.2.5p6 [which returns true...
bool isAnyPointerType() const
TypeClass getTypeClass() const
bool isCanonicalUnqualified() const
Determines if this type would be canonical if it had no further qualification.
const T * getAs() const
Member-template getAs<specific type>'.
bool isNullPtrType() const
bool isRecordType() const
bool isObjCRetainableType() const
bool isSizelessVectorType() const
Returns true for all scalable vector types.
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
QualType getSizelessVectorEltType(const ASTContext &Ctx) const
Returns the representative type for the element of a sizeless vector builtin type.
Base class for declarations which introduce a typedef-name.
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
SourceLocation getBeginLoc() const LLVM_READONLY
Represents a C++ unqualified-id that has been parsed.
void setIdentifier(const IdentifierInfo *Id, SourceLocation IdLoc)
Specify that this unqualified-id was parsed as an identifier.
A set of unresolved declarations.
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Represents a variable declaration or definition.
Represents a GCC generic vector type.
unsigned getNumElements() const
QualType getElementType() const
WhileStmt - This represents a 'while' stmt.
std::string getRepresentativeTypeName(ASTContext &C) const
MatchKind matchesType(ASTContext &C, QualType argTy) const
const char * getStart() const
HowSpecified getHowSpecified() const
unsigned getConstantLength() const
const char * toString() const
const char * getPosition() const
const OptionalFlag & isPrivate() const
bool hasValidLeftJustified() const
bool hasValidFieldWidth() const
bool hasValidSpacePrefix() const
const OptionalAmount & getPrecision() const
const OptionalFlag & hasSpacePrefix() const
bool usesPositionalArg() const
const OptionalFlag & isSensitive() const
const OptionalFlag & isLeftJustified() const
bool hasValidPrecision() const
const OptionalFlag & hasLeadingZeros() const
const OptionalFlag & hasAlternativeForm() const
bool hasValidLeadingZeros() const
void toString(raw_ostream &os) const
const PrintfConversionSpecifier & getConversionSpecifier() const
const OptionalFlag & hasPlusPrefix() const
const OptionalFlag & hasThousandsGrouping() const
bool hasValidThousandsGroupingPrefix() const
ArgType getArgType(ASTContext &Ctx, bool IsObjCLiteral) const
Returns the builtin type that a data argument paired with this format specifier should have.
const OptionalFlag & isPublic() const
bool consumesDataArgument() const
bool hasValidPlusPrefix() const
bool hasValidAlternativeForm() const
bool consumesDataArgument() const
const ScanfConversionSpecifier & getConversionSpecifier() const
ArgType getArgType(ASTContext &Ctx) const
void markSafeWeakUse(const Expr *E)
Record that a given expression is a "safe" access of a weak object (e.g.
Defines the clang::TargetInfo interface.
__inline void unsigned int _2
const clang::Expr * ExprTy
Pieces specific to fprintf format strings.
Pieces specific to fscanf format strings.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< PointerType > pointerType
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
uint32_t Literal
Literals are represented as positive integers.
ComparisonResult
Indicates the result of a tentative comparison.
bool isObjC(ID Id)
isObjC - Is this an "ObjC" input (Obj-C and Obj-C++ sources and headers).
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
@ After
Like System, but searched after the system directories.
@ FixIt
Parse and apply any fixits to the source.
bool GT(InterpState &S, CodePtr OpPC)
bool LT(InterpState &S, CodePtr OpPC)
bool NE(InterpState &S, CodePtr OpPC)
bool LE(InterpState &S, CodePtr OpPC)
bool Cast(InterpState &S, CodePtr OpPC)
bool EQ(InterpState &S, CodePtr OpPC)
bool GE(InterpState &S, CodePtr OpPC)
SetTy< T > join(SetTy< T > A, SetTy< T > B, typename SetTy< T >::Factory &F)
Computes the union of two ImmutableSets.
void checkCaptureByLifetime(Sema &SemaRef, const CapturingEntity &Entity, Expr *Init)
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
OverloadedOperatorKind
Enumeration specifying the different kinds of C++ overloaded operators.
@ Match
This is not an overload because the signature exactly matches an existing declaration.
bool isa(CodeGen::Address addr)
Expr * IgnoreElidableImplicitConstructorSingleStep(Expr *E)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
bool hasSpecificAttr(const Container &container)
@ Arithmetic
An arithmetic operation.
@ Comparison
A comparison.
@ NonNull
Values of this type can never be null.
Expr * IgnoreExprNodes(Expr *E, FnTys &&... Fns)
Given an expression E and functions Fn_1,...,Fn_n : Expr * -> Expr *, Recursively apply each of the f...
@ Success
Annotation was successful.
ExprObjectKind
A further classification of the kind of object referenced by an l-value or x-value.
@ OK_Ordinary
An ordinary object is located at an address in memory.
std::string FormatUTFCodeUnitAsCodepoint(unsigned Value, QualType T)
@ Self
'self' clause, allowed on Compute and Combined Constructs, plus 'update'.
@ Seq
'seq' clause, allowed on 'loop' and 'routine' directives.
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Dependent
Parse the block as a dependent block, which may be used in some template instantiations but not other...
raw_ostream & Indent(raw_ostream &Out, const unsigned int Space, bool IsDot)
SemaARM::ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD)
MutableArrayRef< Expr * > MultiExprArg
@ Internal
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
@ Result
The result type of a method or function.
ActionResult< ParsedType > TypeResult
const FunctionProtoType * T
bool isFunctionOrMethodVariadic(const Decl *D)
LangAS
Defines the address space values used by the address space qualifier of QualType.
CastKind
CastKind - The kind of operation required for a conversion.
unsigned getFunctionOrMethodNumParams(const Decl *D, bool IncludeThis=false)
getFunctionOrMethodNumParams - Return number of function or method parameters, optionally including t...
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
bool hasImplicitObjectParameter(const Decl *D)
ExprValueKind
The categorization of expression values, currently following the C++11 scheme.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
for(const auto &A :T->param_types())
Expr * IgnoreImplicitAsWrittenSingleStep(Expr *E)
CallingConv
CallingConv - Specifies the calling convention that a function uses.
@ Generic
not a target-specific vector type
U cast(CodeGen::Address addr)
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
ActionResult< Expr * > ExprResult
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 unsigned
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t int64_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
EvalResult is a struct with detailed info about an evaluated expression.
APValue Val
Val - This is the value the expression can be folded to.
SmallVectorImpl< PartialDiagnosticAt > * Diag
Diag - If this is non-null, it will be filled in with a stack of notes indicating why evaluation fail...
Extra information about a function prototype.
unsigned AArch64SMEAttributes
unsigned Indentation
The number of spaces to use to indent each line.
unsigned AnonymousTagNameStyle
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
unsigned NumCallArgs
The number of expressions in CallArgs.
const Expr *const * CallArgs
The list of argument expressions in a synthesized call.
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
SmallVector< MisalignedMember, 4 > MisalignedMembers
Small set of gathered accesses to potentially misaligned members due to the packed attribute.