[clang] [clang][CodeGen][OpenCL] Fix `alloca` handling when compiling for (PR #113930)
https://github.com/AlexVlx edited https://github.com/llvm/llvm-project/pull/113930 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen][OpenCL] Fix `alloca` handling (PR #113930)
https://github.com/AlexVlx edited https://github.com/llvm/llvm-project/pull/113930 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][CodeGen][OpenCL] Fix `alloca` handling (PR #113930)
https://github.com/AlexVlx edited https://github.com/llvm/llvm-project/pull/113930 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Contributing.rst update snippet and docs (PR #129209)
https://github.com/carlosgalvezp closed https://github.com/llvm/llvm-project/pull/129209 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [Clang][LLVM] Implement single-single vectors MOP4{A/S} (PR #127797)
@@ -387,6 +405,25 @@ let SMETargetGuard = "sme2" in { def SVBMOPS : Inst<"svbmops_za32[_{d}]_m", "viPPdd", "iUi", MergeNone, "aarch64_sme_bmops_za32", [IsInOutZA, IsStreaming], [ImmCheck<0, ImmCheck0_3>]>; Lukacma wrote: Looking at rest of arm_sme.td file we tend to group instructions together, based on their functionality rather than their feature requirements. I think it would be better if all mop4 instruction were grouped together in their own section instead of scattering them across the file https://github.com/llvm/llvm-project/pull/127797 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Revert "[clang][HIP] Make some math not not work with AMDGCN SPIR-V" (PR #129280)
llvmbot wrote: @llvm/pr-subscribers-backend-x86 Author: Alex Voicu (AlexVlx) Changes Reverts llvm/llvm-project#128360 pending resolution of odd test break. --- Patch is 183.19 KiB, truncated to 20.00 KiB below, full version: https://github.com/llvm/llvm-project/pull/129280.diff 3 Files Affected: - (modified) clang/lib/Headers/__clang_hip_libdevice_declares.h (+20-12) - (modified) clang/lib/Headers/__clang_hip_math.h (+16-12) - (modified) clang/test/Headers/__clang_hip_math.hip (-1655) ``diff diff --git a/clang/lib/Headers/__clang_hip_libdevice_declares.h b/clang/lib/Headers/__clang_hip_libdevice_declares.h index fa8d918248dd0..f15198b3d9f93 100644 --- a/clang/lib/Headers/__clang_hip_libdevice_declares.h +++ b/clang/lib/Headers/__clang_hip_libdevice_declares.h @@ -14,8 +14,6 @@ #include "hip/hip_version.h" #endif // __has_include("hip/hip_version.h") -#define __PRIVATE_AS __attribute__((opencl_private)) - #ifdef __cplusplus extern "C" { #endif @@ -57,7 +55,8 @@ __device__ __attribute__((const)) float __ocml_fmax_f32(float, float); __device__ __attribute__((const)) float __ocml_fmin_f32(float, float); __device__ __attribute__((const)) __device__ float __ocml_fmod_f32(float, float); -__device__ float __ocml_frexp_f32(float, __PRIVATE_AS int *); +__device__ float __ocml_frexp_f32(float, + __attribute__((address_space(5))) int *); __device__ __attribute__((const)) float __ocml_hypot_f32(float, float); __device__ __attribute__((const)) int __ocml_ilogb_f32(float); __device__ __attribute__((const)) int __ocml_isfinite_f32(float); @@ -75,7 +74,8 @@ __device__ __attribute__((pure)) float __ocml_native_log2_f32(float); __device__ __attribute__((const)) float __ocml_logb_f32(float); __device__ __attribute__((pure)) float __ocml_log_f32(float); __device__ __attribute__((pure)) float __ocml_native_log_f32(float); -__device__ float __ocml_modf_f32(float, __PRIVATE_AS float *); +__device__ float __ocml_modf_f32(float, + __attribute__((address_space(5))) float *); __device__ __attribute__((const)) float __ocml_nearbyint_f32(float); __device__ __attribute__((const)) float __ocml_nextafter_f32(float, float); __device__ __attribute__((const)) float __ocml_len3_f32(float, float, float); @@ -87,7 +87,8 @@ __device__ __attribute__((pure)) float __ocml_pow_f32(float, float); __device__ __attribute__((pure)) float __ocml_pown_f32(float, int); __device__ __attribute__((pure)) float __ocml_rcbrt_f32(float); __device__ __attribute__((const)) float __ocml_remainder_f32(float, float); -__device__ float __ocml_remquo_f32(float, float, __PRIVATE_AS int *); +__device__ float __ocml_remquo_f32(float, float, + __attribute__((address_space(5))) int *); __device__ __attribute__((const)) float __ocml_rhypot_f32(float, float); __device__ __attribute__((const)) float __ocml_rint_f32(float); __device__ __attribute__((const)) float __ocml_rlen3_f32(float, float, float); @@ -98,8 +99,10 @@ __device__ __attribute__((pure)) float __ocml_rsqrt_f32(float); __device__ __attribute__((const)) float __ocml_scalb_f32(float, float); __device__ __attribute__((const)) float __ocml_scalbn_f32(float, int); __device__ __attribute__((const)) int __ocml_signbit_f32(float); -__device__ float __ocml_sincos_f32(float, __PRIVATE_AS float *); -__device__ float __ocml_sincospi_f32(float, __PRIVATE_AS float *); +__device__ float __ocml_sincos_f32(float, + __attribute__((address_space(5))) float *); +__device__ float __ocml_sincospi_f32(float, + __attribute__((address_space(5))) float *); __device__ float __ocml_sin_f32(float); __device__ float __ocml_native_sin_f32(float); __device__ __attribute__((pure)) float __ocml_sinh_f32(float); @@ -173,7 +176,8 @@ __device__ __attribute__((const)) double __ocml_fma_f64(double, double, double); __device__ __attribute__((const)) double __ocml_fmax_f64(double, double); __device__ __attribute__((const)) double __ocml_fmin_f64(double, double); __device__ __attribute__((const)) double __ocml_fmod_f64(double, double); -__device__ double __ocml_frexp_f64(double, __PRIVATE_AS int *); +__device__ double __ocml_frexp_f64(double, + __attribute__((address_space(5))) int *); __device__ __attribute__((const)) double __ocml_hypot_f64(double, double); __device__ __attribute__((const)) int __ocml_ilogb_f64(double); __device__ __attribute__((const)) int __ocml_isfinite_f64(double); @@ -188,7 +192,8 @@ __device__ __attribute__((pure)) double __ocml_log1p_f64(double); __device__ __attribute__((pure)) double __ocml_log2_f64(double); __device__ __attribute__((const)) double __ocml_logb_f64(double); __device__ __attribute__((pure)) double __ocml_log_f64(double); -__device__ double __ocml_modf_f64(double, __PRIVATE_
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
https://github.com/isuckatcs edited https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
https://github.com/isuckatcs updated https://github.com/llvm/llvm-project/pull/128265 >From 3a528edbf5c63ac0e47530feffe309a1a51e9c93 Mon Sep 17 00:00:00 2001 From: isuckatcs <65320245+isucka...@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:06:34 +0100 Subject: [PATCH] [clang][diagnostics] add '-Wundef-true' warning option --- .../include/clang/Basic/DiagnosticLexKinds.td | 3 + clang/lib/Lex/PPExpressions.cpp | 5 +- .../test/Preprocessor/warn-macro-undef-true.c | 78 +++ 3 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 clang/test/Preprocessor/warn-macro-undef-true.c diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 4bcef23ccce16..f7c0b2da4a389 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -393,6 +393,9 @@ def pp_macro_not_used : Warning<"macro is not used">, DefaultIgnore, def warn_pp_undef_identifier : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; +def warn_pp_undef_true_identifier : Warning< + "'true' is not defined, evaluates to 0">, + InGroup>; def warn_pp_undef_prefix : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; diff --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp index a3b1384f0fa1d..dd14a1b9eff80 100644 --- a/clang/lib/Lex/PPExpressions.cpp +++ b/clang/lib/Lex/PPExpressions.cpp @@ -260,7 +260,8 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; const DiagnosticsEngine &DiagEngine = PP.getDiagnostics(); - // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics. + // If 'Wundef' is enabled, do not emit 'undef-prefix' or 'undef-true' + // diagnostics. if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier, PeekTok.getLocation())) { const std::vector UndefPrefixes = @@ -272,6 +273,8 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, })) PP.Diag(PeekTok, diag::warn_pp_undef_prefix) << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II; +else if (II->getName() == "true") + PP.Diag(PeekTok, diag::warn_pp_undef_true_identifier); } } Result.Val = 0; diff --git a/clang/test/Preprocessor/warn-macro-undef-true.c b/clang/test/Preprocessor/warn-macro-undef-true.c new file mode 100644 index 0..cb4b206378c0e --- /dev/null +++ b/clang/test/Preprocessor/warn-macro-undef-true.c @@ -0,0 +1,78 @@ +// RUN: %clang_cc1 %s -Eonly -std=c89 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c99 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c11 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c17 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c23 -verify=undef-true -verify=undef + +#if __STDC_VERSION__ >= 202311L +/* undef-no-diagnostics */ +#endif + +#define FOO true +#if FOO /* #1 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#1 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #2 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#2 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #3 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#3 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true 1 + +#define FOO true +#if FOO +#endif + +#if true +#endif + +#if false || true +#endif + +#undef true + +#define FOO true +#if FOO /* #4 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#4 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #5 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#5 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #6 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#6 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true true +#if true /* #7 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#7 {{'true' is not defined, evaluates to 0}} */ +#endif +#undef true + +/* Test that #pragma-enabled 'Wundef' can override 'Wundef-true' */ +#pragma clang diagnostic warning "-Wundef" +#if true /* #8 */ +#endif +#pragma clang diagnostic ignored "-Wundef" +#if __STDC_VERSION__ < 202311L +/* undef-warning@#8 {{'true' is not defined, evaluates to 0}} */ +#endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tidy] warn when `true` is used as a preprocessor keyword in C (PR #128265)
https://github.com/isuckatcs updated https://github.com/llvm/llvm-project/pull/128265 >From 794e45b99711ebb72be1e4e6263f7f67f5da8545 Mon Sep 17 00:00:00 2001 From: isuckatcs <65320245+isucka...@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:06:34 +0100 Subject: [PATCH] [clang][diagnostics] add '-Wundef-true' warning option --- .../include/clang/Basic/DiagnosticLexKinds.td | 3 + clang/lib/Lex/PPExpressions.cpp | 5 +- .../test/Preprocessor/warn-macro-undef-true.c | 78 +++ 3 files changed, 85 insertions(+), 1 deletion(-) create mode 100644 clang/test/Preprocessor/warn-macro-undef-true.c diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 4bcef23ccce16..f7c0b2da4a389 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -393,6 +393,9 @@ def pp_macro_not_used : Warning<"macro is not used">, DefaultIgnore, def warn_pp_undef_identifier : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; +def warn_pp_undef_true_identifier : Warning< + "'true' is not defined, evaluates to 0">, + InGroup>; def warn_pp_undef_prefix : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; diff --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp index a3b1384f0fa1d..831cb01d7387c 100644 --- a/clang/lib/Lex/PPExpressions.cpp +++ b/clang/lib/Lex/PPExpressions.cpp @@ -260,7 +260,8 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; const DiagnosticsEngine &DiagEngine = PP.getDiagnostics(); - // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics. + // If 'Wundef' is enabled, do not emit 'undef-prefix' or 'undef-true' + // diagnostics. if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier, PeekTok.getLocation())) { const std::vector UndefPrefixes = @@ -272,6 +273,8 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, })) PP.Diag(PeekTok, diag::warn_pp_undef_prefix) << AddFlagValue{llvm::join(UndefPrefixes, ",")} << II; +else if(II->getName() == "true") + PP.Diag(PeekTok, diag::warn_pp_undef_true_identifier); } } Result.Val = 0; diff --git a/clang/test/Preprocessor/warn-macro-undef-true.c b/clang/test/Preprocessor/warn-macro-undef-true.c new file mode 100644 index 0..cb4b206378c0e --- /dev/null +++ b/clang/test/Preprocessor/warn-macro-undef-true.c @@ -0,0 +1,78 @@ +// RUN: %clang_cc1 %s -Eonly -std=c89 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c99 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c11 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c17 -verify=undef-true -verify=undef +// RUN: %clang_cc1 %s -Eonly -std=c23 -verify=undef-true -verify=undef + +#if __STDC_VERSION__ >= 202311L +/* undef-no-diagnostics */ +#endif + +#define FOO true +#if FOO /* #1 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#1 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #2 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#2 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #3 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#3 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true 1 + +#define FOO true +#if FOO +#endif + +#if true +#endif + +#if false || true +#endif + +#undef true + +#define FOO true +#if FOO /* #4 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#4 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #5 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#5 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #6 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#6 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true true +#if true /* #7 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#7 {{'true' is not defined, evaluates to 0}} */ +#endif +#undef true + +/* Test that #pragma-enabled 'Wundef' can override 'Wundef-true' */ +#pragma clang diagnostic warning "-Wundef" +#if true /* #8 */ +#endif +#pragma clang diagnostic ignored "-Wundef" +#if __STDC_VERSION__ < 202311L +/* undef-warning@#8 {{'true' is not defined, evaluates to 0}} */ +#endif ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tidy] warn when `true` is used as a preprocessor keyword in C (PR #128265)
@@ -0,0 +1,45 @@ +// RUN: %check_clang_tidy -std=c99 %s bugprone-true-macro %t +// RUN: %check_clang_tidy -std=c11 %s bugprone-true-macro %t +// RUN: %check_clang_tidy -std=c17 %s bugprone-true-macro %t isuckatcs wrote: I added such option in the new, clang diagnostic test. https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [libcxx] [llvm] [libc++][ranges] P2542R8: Implement `views::concat` (PR #120920)
@@ -0,0 +1,646 @@ +// -*- C++ -*- +//===--===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef _LIBCPP___RANGES_CONCAT_VIEW_H +#define _LIBCPP___RANGES_CONCAT_VIEW_H + +#include <__algorithm/ranges_find_if.h> +#include <__assert> +#include <__concepts/common_reference_with.h> +#include <__concepts/constructible.h> +#include <__concepts/convertible_to.h> +#include <__concepts/copyable.h> +#include <__concepts/derived_from.h> +#include <__concepts/equality_comparable.h> +#include <__concepts/swappable.h> +#include <__config> +#include <__functional/bind_back.h> +#include <__functional/invoke.h> +#include <__functional/reference_wrapper.h> +#include <__iterator/concepts.h> +#include <__iterator/default_sentinel.h> +#include <__iterator/distance.h> +#include <__iterator/incrementable_traits.h> +#include <__iterator/iter_move.h> +#include <__iterator/iter_swap.h> +#include <__iterator/iterator_traits.h> +#include <__iterator/next.h> +#include <__memory/addressof.h> +#include <__ranges/access.h> +#include <__ranges/all.h> +#include <__ranges/concepts.h> +#include <__ranges/movable_box.h> +#include <__ranges/non_propagating_cache.h> +#include <__ranges/range_adaptor.h> +#include <__ranges/size.h> +#include <__ranges/view_interface.h> +#include <__ranges/zip_view.h> +#include <__type_traits/conditional.h> +#include <__type_traits/decay.h> +#include <__type_traits/is_nothrow_constructible.h> +#include <__type_traits/is_nothrow_convertible.h> +#include <__type_traits/is_object.h> +#include <__type_traits/make_unsigned.h> +#include <__type_traits/maybe_const.h> +#include <__utility/forward.h> +#include <__utility/in_place.h> +#include <__utility/move.h> +#include +#include + +#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER) +# pragma GCC system_header +#endif + +_LIBCPP_PUSH_MACROS +#include <__undef_macros> + +_LIBCPP_BEGIN_NAMESPACE_STD + +#if _LIBCPP_STD_VER >= 26 + +namespace ranges { + +# ifdef __cpp_pack_indexing +template +using __extract_last _LIBCPP_NODEBUG = _Tp...[sizeof...(_Tp) - 1]; +# else +template +struct __extract_last_impl : __extract_last_impl<_Tail...> {}; +template +struct __extract_last_impl<_Tp> { + using type _LIBCPP_NODEBUG = _Tp; +}; + +template +using __extract_last _LIBCPP_NODEBUG = __extract_last_impl<_Tp...>::type; +# endif + +template +constexpr bool __derived_from_pack = +__derived_from_pack<_Tp, __extract_last<_Tail...>> && __derived_from_pack<_Tail...>; + +template +constexpr bool __derived_from_pack<_Tp, _IterCategory> = derived_from<_Tp, _IterCategory>; + +template +struct __last_view : __last_view<_Views...> {}; + +template +struct __last_view<_View> { + using type = _View; +}; + +template +concept __concat_indirectly_readable_impl = requires(const _It __it) { + { *__it } -> convertible_to<_Ref>; + { ranges::iter_move(__it) } -> convertible_to<_RRef>; +}; + +template +using __concat_reference_t _LIBCPP_NODEBUG = common_reference_t...>; + +template +using __concat_value_t _LIBCPP_NODEBUG = common_type_t...>; + +template +using __concat_rvalue_reference_t _LIBCPP_NODEBUG = common_reference_t...>; + +template +concept __concat_indirectly_readable = +common_reference_with<__concat_reference_t<_Rs...>&&, __concat_value_t<_Rs...>&> && +common_reference_with<__concat_reference_t<_Rs...>&&, __concat_rvalue_reference_t<_Rs...>&&> && +common_reference_with<__concat_rvalue_reference_t<_Rs...>&&, __concat_value_t<_Rs...> const&> && +(__concat_indirectly_readable_impl<__concat_reference_t<_Rs...>, + __concat_rvalue_reference_t<_Rs...>, + iterator_t<_Rs>> && + ...); + +template +concept __concatable = requires { + typename __concat_reference_t<_Rs...>; + typename __concat_value_t<_Rs...>; + typename __concat_rvalue_reference_t<_Rs...>; +} && __concat_indirectly_readable<_Rs...>; + +template +concept __concat_is_random_access = +(random_access_range<__maybe_const<_Const, _Rs>> && ...) && (sized_range<__maybe_const<_Const, _Rs>> && ...); + +template +concept __concat_is_bidirectional = +((bidirectional_range<__maybe_const<_Const, _Rs>> && ...) && (common_range<__maybe_const<_Const, _Rs>> && ...)); + +template +concept __all_forward = (forward_range<__maybe_const<_Const, _Views>> && ...); + +template +struct __apply_drop_first; + +template +struct __apply_drop_first<_Const, _Head, _Tail...> { + static constexpr bool value = (sized_range<__maybe_const<_Const, _Tail>> && ...); +}; + +template + requires(view<_Views> && ...) && (sizeof...(_Views) > 0) && __concatable<_Views...> +class concat_view : public view
[clang] [clang-tidy] warn when `true` is used as a preprocessor keyword in C (PR #128265)
isuckatcs wrote: As per the discussion above, I move the check from `clang-tidy` into `clang` itself. https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)
https://github.com/vbvictor updated https://github.com/llvm/llvm-project/pull/121291 >From 099aacc263f70301efefa722d49874a47b0054a9 Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Sat, 1 Mar 2025 18:05:54 +0300 Subject: [PATCH] add ambigous-smartptr-reset-call check --- .../AmbiguousSmartptrResetCallCheck.cpp | 126 ++ .../AmbiguousSmartptrResetCallCheck.h | 37 ++ .../clang-tidy/readability/CMakeLists.txt | 1 + .../readability/ReadabilityTidyModule.cpp | 3 + clang-tools-extra/docs/ReleaseNotes.rst | 6 + .../docs/clang-tidy/checks/list.rst | 1 + .../ambiguous-smartptr-reset-call.rst | 62 +++ ...us-smartptr-reset-call-custom-pointers.cpp | 52 +++ .../ambiguous-smartptr-reset-call.cpp | 397 ++ 9 files changed, 685 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/readability/ambiguous-smartptr-reset-call.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/ambiguous-smartptr-reset-call-custom-pointers.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/readability/ambiguous-smartptr-reset-call.cpp diff --git a/clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp b/clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp new file mode 100644 index 0..5f36c3976fc69 --- /dev/null +++ b/clang-tools-extra/clang-tidy/readability/AmbiguousSmartptrResetCallCheck.cpp @@ -0,0 +1,126 @@ +//===--- AmbiguousSmartptrResetCallCheck.cpp - clang-tidy -===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "AmbiguousSmartptrResetCallCheck.h" +#include "../utils/OptionsUtils.h" +#include "clang/AST/ASTContext.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Lex/Lexer.h" + +using namespace clang::ast_matchers; + +namespace clang::tidy::readability { + +namespace { + +AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) { + for (const auto *Param : Node.parameters()) { +if (!Param->hasDefaultArg()) + return false; + } + + return true; +} + +const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr;" + "::boost::shared_ptr"; +} // namespace + +AmbiguousSmartptrResetCallCheck::AmbiguousSmartptrResetCallCheck( +StringRef Name, ClangTidyContext *Context) +: ClangTidyCheck(Name, Context), + SmartPointers(utils::options::parseStringList( + Options.get("SmartPointers", DefaultSmartPointers))) {} + +void AmbiguousSmartptrResetCallCheck::storeOptions( +ClangTidyOptions::OptionMap &Opts) { + Options.store(Opts, "SmartPointers", +utils::options::serializeStringList(SmartPointers)); +} + +void AmbiguousSmartptrResetCallCheck::registerMatchers(MatchFinder *Finder) { + const auto IsSmartptr = hasAnyName(SmartPointers); + + const auto ResetMethod = + cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters()); + + const auto TypeWithReset = + anyOf(cxxRecordDecl( +anyOf(hasMethod(ResetMethod), + isDerivedFrom(cxxRecordDecl(hasMethod(ResetMethod), +classTemplateSpecializationDecl( +hasSpecializedTemplate(classTemplateDecl(has(ResetMethod); + + const auto SmartptrWithReset = expr(hasType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(classTemplateSpecializationDecl( + IsSmartptr, + hasTemplateArgument( + 0, templateArgument(refersToType(hasUnqualifiedDesugaredType( + recordType(hasDeclaration(TypeWithReset; + + Finder->addMatcher( + cxxMemberCallExpr( + callee(ResetMethod), + unless(hasAnyArgument(expr(unless(cxxDefaultArgExpr(), + anyOf(on(cxxOperatorCallExpr(hasOverloadedOperatorName("->"), + hasArgument(0, SmartptrWithReset)) + .bind("ArrowOp")), +on(SmartptrWithReset))) + .bind("MemberCall"), + this); +} + +void AmbiguousSmartptrResetCallCheck::check( +const MatchFinder::MatchResult &Result) { + const auto *MemberCall = + Result.Nodes.getNodeAs("MemberCall"); + assert(MemberCall); + + if (const auto *Arrow = + Result.Nodes.getNodeAs("ArrowOp")) { +const CharSourceRange SmartptrSourceRange = +Lexer::getAsCharRange(Arrow->getArg(0)->getSourceRange(), +
[clang] [cindex] Add API to query the class methods of a type (PR #123539)
https://github.com/trelau updated https://github.com/llvm/llvm-project/pull/123539 >From bb0542e8f2ad50892ee9d2c1f76ec1def85c3e56 Mon Sep 17 00:00:00 2001 From: Trevor Laughlin Date: Sun, 19 Jan 2025 19:21:10 -0500 Subject: [PATCH 1/6] [cindex] Add API to query the class methods of a type --- clang/bindings/python/clang/cindex.py | 16 +++ .../bindings/python/tests/cindex/test_type.py | 18 + clang/docs/ReleaseNotes.rst | 4 +++ clang/include/clang-c/Index.h | 23 clang/tools/libclang/CIndexCXX.cpp| 27 +++ clang/tools/libclang/libclang.map | 1 + 6 files changed, 89 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 806e1b40f3c9e..9e65ea2942d16 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -2710,6 +2710,21 @@ def visitor(base, children): conf.lib.clang_visitCXXBaseClasses(self, fields_visit_callback(visitor), bases) return iter(bases) +def get_methods(self): +"""Return an iterator for accessing the methods of this type.""" + +def visitor(method, children): +assert method != conf.lib.clang_getNullCursor() + +# Create reference to TU so it isn't GC'd before Cursor. +method._tu = self._tu +methods.append(method) +return 1 # continue + +methods: list[Cursor] = [] +conf.lib.clang_visitCXXMethods(self, fields_visit_callback(visitor), methods) +return iter(methods) + def get_exception_specification_kind(self): """ Return the kind of the exception specification; a value from @@ -4017,6 +4032,7 @@ def set_property(self, property, value): ), ("clang_visitChildren", [Cursor, cursor_visit_callback, py_object], c_uint), ("clang_visitCXXBaseClasses", [Type, fields_visit_callback, py_object], c_uint), +("clang_visitCXXMethods", [Type, fields_visit_callback, py_object], c_uint), ("clang_Cursor_getNumArguments", [Cursor], c_int), ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor), ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int), diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py index 9bac33f3041f4..bc893d509524e 100644 --- a/clang/bindings/python/tests/cindex/test_type.py +++ b/clang/bindings/python/tests/cindex/test_type.py @@ -559,3 +559,21 @@ class Template : public A, public B, virtual C { self.assertEqual(bases[1].get_base_offsetof(cursor_type_decl), 96) self.assertTrue(bases[2].is_virtual_base()) self.assertEqual(bases[2].get_base_offsetof(cursor_type_decl), 128) + +def test_class_methods(self): +source = """ +template +class Template { void Foo(); }; +typedef Template instance; +instance bar; +""" +tu = get_tu(source, lang="cpp", flags=["--target=x86_64-linux-gnu"]) +cursor = get_cursor(tu, "instance") +cursor_type = cursor.underlying_typedef_type +self.assertEqual(cursor.kind, CursorKind.TYPEDEF_DECL) +methods = list(cursor_type.get_methods()) +self.assertEqual(len(methods), 4) +self.assertEqual(methods[0].kind, CursorKind.CXX_METHOD) +self.assertEqual(methods[1].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[2].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[3].kind, CursorKind.CONSTRUCTOR) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b02ac467cd3a2..dd9f722a6a08c 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -1241,6 +1241,8 @@ libclang of a class. - Added ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``clang_visitCXXMethods``, which allows visiting the methods + of a class. Static Analyzer --- @@ -1394,6 +1396,8 @@ Python Binding Changes allows visiting the base classes of a class. - Added ``Cursor.get_base_offsetof``, a binding for ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which + allows visiting the methods of a class. OpenMP Support -- diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h index aac5d1fa8aa2e..5d961ca0cdd7f 100644 --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -6680,6 +6680,29 @@ CINDEX_LINKAGE unsigned clang_visitCXXBaseClasses(CXType T, CXFieldVisitor visitor, CXClientData client_data); +/** + * Visit the class methods of a type. + * + * This function visits all the methods of t
[clang] [Clang] Check for uninitialized use in lambda within CXXOperatorCallExpr (PR #129198)
@@ -12806,6 +12810,19 @@ namespace { HandleValue(Arg->IgnoreParenImpCasts()); } +void VisitLambdaExpr(LambdaExpr *E) { + if (!isInCXXOperatorCall) { +Inherited::VisitLambdaExpr(E); +return; + } + + for (const auto &init : E->capture_inits()) +if (DeclRefExpr *DRE = dyn_cast(init)) + HandleDeclRefExpr(DRE); +else erichkeane wrote: ```suggestion else if (Init) ``` According to the base implementation of this, we end up expecting this could be null sometimes. https://github.com/llvm/llvm-project/pull/129198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 038731c - [ubsan] Remove -fsanitizer=vptr from -fsanitizer=undefined (#121115)
Author: Vitaly Buka Date: 2025-03-01T13:21:47-08:00 New Revision: 038731c709c665634714275996559c21f36372f2 URL: https://github.com/llvm/llvm-project/commit/038731c709c665634714275996559c21f36372f2 DIFF: https://github.com/llvm/llvm-project/commit/038731c709c665634714275996559c21f36372f2.diff LOG: [ubsan] Remove -fsanitizer=vptr from -fsanitizer=undefined (#121115) This makes `undefined` more consistent. `vptr` check adds additional constraints: 1. trap is off, or silently disabled 2. rtti is no, or compilation error 3. c++abi, or linking error So it's not obvious if `-fsanitizer=undefined` will have it on. https://discourse.llvm.org/t/rfc-remove-vptr-from-undefined/83830 Added: Modified: clang/docs/ReleaseNotes.rst clang/docs/UndefinedBehaviorSanitizer.rst clang/include/clang/Basic/Sanitizers.def clang/lib/Driver/SanitizerArgs.cpp clang/test/Driver/fsanitize.c clang/test/Driver/sanitizer-ld.c Removed: diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index c4377c842cd96..c97bbc372fcb7 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -388,6 +388,8 @@ Moved checkers Sanitizers -- +- ``-fsanitize=vptr`` is no longer a part of ``-fsanitize=undefined``. + Python Binding Changes -- - Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which diff --git a/clang/docs/UndefinedBehaviorSanitizer.rst b/clang/docs/UndefinedBehaviorSanitizer.rst index c4895fb9722bf..0a2d833783e57 100644 --- a/clang/docs/UndefinedBehaviorSanitizer.rst +++ b/clang/docs/UndefinedBehaviorSanitizer.rst @@ -214,13 +214,14 @@ Available checks are: the wrong dynamic type, or that its lifetime has not begun or has ended. Incompatible with ``-fno-rtti``. Link must be performed by ``clang++``, not ``clang``, to make sure C++-specific parts of the runtime library and C++ - standard libraries are present. + standard libraries are present. The check is not a part of the ``undefined`` + group. Also it does not support ``-fsanitize-trap=vptr``. You can also use the following check groups: - ``-fsanitize=undefined``: All of the checks listed above other than ``float-divide-by-zero``, ``unsigned-integer-overflow``, - ``implicit-conversion``, ``local-bounds`` and the ``nullability-*`` group - of checks. + ``implicit-conversion``, ``local-bounds``, ``vptr`` and the + ``nullability-*`` group of checks. - ``-fsanitize=undefined-trap``: Deprecated alias of ``-fsanitize=undefined``. - ``-fsanitize=implicit-integer-truncation``: Catches lossy integral diff --git a/clang/include/clang/Basic/Sanitizers.def b/clang/include/clang/Basic/Sanitizers.def index f234488eaa80c..1d0e97cc7fb4c 100644 --- a/clang/include/clang/Basic/Sanitizers.def +++ b/clang/include/clang/Basic/Sanitizers.def @@ -152,8 +152,7 @@ SANITIZER_GROUP("undefined", Undefined, FloatCastOverflow | IntegerDivideByZero | NonnullAttribute | Null | ObjectSize | PointerOverflow | Return | ReturnsNonnullAttribute | Shift | -SignedIntegerOverflow | Unreachable | VLABound | Function | -Vptr) +SignedIntegerOverflow | Unreachable | VLABound | Function) // -fsanitize=undefined-trap is an alias for -fsanitize=undefined. SANITIZER_GROUP("undefined-trap", UndefinedTrap, Undefined) diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp index 294f637ef6515..6e75001585c61 100644 --- a/clang/lib/Driver/SanitizerArgs.cpp +++ b/clang/lib/Driver/SanitizerArgs.cpp @@ -30,7 +30,8 @@ static const SanitizerMask NeedsUbsanRt = SanitizerKind::Undefined | SanitizerKind::Integer | SanitizerKind::LocalBounds | SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | SanitizerKind::CFI | -SanitizerKind::FloatDivideByZero | SanitizerKind::ObjCCast; +SanitizerKind::FloatDivideByZero | SanitizerKind::ObjCCast | +SanitizerKind::Vptr; static const SanitizerMask NeedsUbsanCxxRt = SanitizerKind::Vptr | SanitizerKind::CFI; static const SanitizerMask NotAllowedWithTrap = SanitizerKind::Vptr; @@ -53,11 +54,12 @@ static const SanitizerMask SupportsCoverage = SanitizerKind::FuzzerNoLink | SanitizerKind::FloatDivideByZero | SanitizerKind::SafeStack | SanitizerKind::ShadowCallStack | SanitizerKind::Thread | SanitizerKind::ObjCCast | SanitizerKind::KCFI | -SanitizerKind::NumericalStability; +SanitizerKind::NumericalStability | SanitizerKind::Vptr; static const SanitizerMask RecoverableByDefault = SanitizerKind::Undefined | SanitizerKind::Integer | SanitizerKind::ImplicitConversion | SanitizerKind::Nullability | -SanitizerKind::FloatDivideByZero | SanitizerKind::ObjCCast; +SanitizerKind::FloatD
[clang] [ubsan] Remove -fsanitizer=vptr from -fsanitizer=undefined (PR #121115)
https://github.com/vitalybuka closed https://github.com/llvm/llvm-project/pull/121115 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [libcxx] [llvm] [libc++][ranges] P2542R8: Implement `views::concat` (PR #120920)
https://github.com/changkhothuychung updated https://github.com/llvm/llvm-project/pull/120920 error: too big or took too long to generate ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add support for dynamic libraries in CLANG_BOLT (PR #127020)
https://github.com/tstellar approved this pull request. LGTM. https://github.com/llvm/llvm-project/pull/127020 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [sanitizer] Apply AlwaysIn/Out in parseSanitizeArgs (PR #129405)
https://github.com/thurstond created https://github.com/llvm/llvm-project/pull/129405 For backwards compatibility, `parseSanitizeArgs`/`parseSanitizeTrapArgs` had an incomplete refactoring in https://github.com/llvm/llvm-project/pull/119819, in order to accommodate the special case of vptr in -fsanitize=undefined and its interaction with -fsanitize-trap=undefined. Now that vptr is no longer part of -fsanitize=undefined (https://github.com/llvm/llvm-project/pull/121115), this patch changes parseSanitizeArgs to apply the AlwaysIn/Out invariants in parseSanitizeArgs, which allows simplifying calls to parseSanitizeArgs. This is not quite NFC: it changes the error message of -fsanitize-trap=vptr. >From 69476cfd0ba3444566b4116a01bb06b73da26e3c Mon Sep 17 00:00:00 2001 From: Thurston Dang Date: Sat, 1 Mar 2025 21:59:06 + Subject: [PATCH] [sanitizer] Apply AlwaysIn/Out in parseSanitizeArgs For backwards compatibility, parseSanitizeArgs had an incomplete refactoring in https://github.com/llvm/llvm-project/pull/119819, in order to accommodate the special case of vptr in -fsanitize=undefined and its interaction with -fsanitize-trap=undefined. Now that vptr is no longer part of UBSan (https://github.com/llvm/llvm-project/pull/121115), this patch changes parseSanitizeArgs to apply the AlwaysIn/Out invariants in parseSanitizeArgs, which allows simplifying calls to parseSanitizeArgs. Note that this does change the error message of -fsanitize-trap=vptr. --- clang/lib/Driver/SanitizerArgs.cpp | 14 -- clang/test/Driver/fsanitize.c | 2 +- 2 files changed, 5 insertions(+), 11 deletions(-) diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp index 6e75001585c61..f5b0bc5ce720f 100644 --- a/clang/lib/Driver/SanitizerArgs.cpp +++ b/clang/lib/Driver/SanitizerArgs.cpp @@ -261,11 +261,8 @@ static SanitizerMask setGroupBits(SanitizerMask Kinds) { } // Computes the sanitizer mask as: -// Default + Arguments (in or out) +// Default + Arguments (in or out) + AlwaysIn - AlwaysOut // with arguments parsed from left to right. -// -// Error messages are printed if the AlwaysIn or AlwaysOut invariants are -// violated, but the caller must enforce these invariants themselves. static SanitizerMask parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, bool DiagnoseErrors, SanitizerMask Default, @@ -315,6 +312,9 @@ parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, } } + Output |= AlwaysIn; + Output &= ~AlwaysOut; + return Output; } @@ -324,10 +324,6 @@ static SanitizerMask parseSanitizeTrapArgs(const Driver &D, SanitizerMask AlwaysTrap; // Empty SanitizerMask NeverTrap = ~(setGroupBits(TrappingSupported)); - // N.B. We do *not* enforce NeverTrap. This maintains the behavior of - // '-fsanitize=undefined -fsanitize-trap=undefined' - // (clang/test/Driver/fsanitize.c ), which is that vptr is not enabled at all - // (not even in recover mode) in order to avoid the need for a ubsan runtime. return parseSanitizeArgs(D, Args, DiagnoseErrors, TrappingDefault, AlwaysTrap, NeverTrap, options::OPT_fsanitize_trap_EQ, options::OPT_fno_sanitize_trap_EQ); @@ -725,8 +721,6 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, D, Args, DiagnoseErrors, RecoverableByDefault, AlwaysRecoverable, Unrecoverable, options::OPT_fsanitize_recover_EQ, options::OPT_fno_sanitize_recover_EQ); - RecoverableKinds |= AlwaysRecoverable; - RecoverableKinds &= ~Unrecoverable; RecoverableKinds &= Kinds; TrappingKinds &= Kinds; diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c index 79c936a79ffd2..9eb6579ce30ab 100644 --- a/clang/test/Driver/fsanitize.c +++ b/clang/test/Driver/fsanitize.c @@ -149,7 +149,7 @@ // CHECK-FSANITIZE-SHIFT-PARTIAL: "-fsanitize=shift-exponent" // RUN: not %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-trap=vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-TRAP-UNDEF -// CHECK-VPTR-TRAP-UNDEF: error: invalid argument '-fsanitize=vptr' not allowed with '-fsanitize-trap=undefined' +// CHECK-VPTR-TRAP-UNDEF: error: unsupported argument 'vptr' to option '-fsanitize-trap=' // RUN: %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-undefined-trap-on-error %s -### ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [sanitizer] Apply AlwaysIn/Out in parseSanitizeArgs (PR #129405)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Thurston Dang (thurstond) Changes For backwards compatibility, `parseSanitizeArgs`/`parseSanitizeTrapArgs` had an incomplete refactoring in https://github.com/llvm/llvm-project/pull/119819, in order to accommodate the special case of vptr in -fsanitize=undefined and its interaction with -fsanitize-trap=undefined. Now that vptr is no longer part of -fsanitize=undefined (https://github.com/llvm/llvm-project/pull/121115), this patch changes parseSanitizeArgs to apply the AlwaysIn/Out invariants in parseSanitizeArgs, which allows simplifying calls to parseSanitizeArgs. This is not quite NFC: it changes the error message of -fsanitize-trap=vptr. --- Full diff: https://github.com/llvm/llvm-project/pull/129405.diff 2 Files Affected: - (modified) clang/lib/Driver/SanitizerArgs.cpp (+4-10) - (modified) clang/test/Driver/fsanitize.c (+1-1) ``diff diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp index 6e75001585c61..f5b0bc5ce720f 100644 --- a/clang/lib/Driver/SanitizerArgs.cpp +++ b/clang/lib/Driver/SanitizerArgs.cpp @@ -261,11 +261,8 @@ static SanitizerMask setGroupBits(SanitizerMask Kinds) { } // Computes the sanitizer mask as: -// Default + Arguments (in or out) +// Default + Arguments (in or out) + AlwaysIn - AlwaysOut // with arguments parsed from left to right. -// -// Error messages are printed if the AlwaysIn or AlwaysOut invariants are -// violated, but the caller must enforce these invariants themselves. static SanitizerMask parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, bool DiagnoseErrors, SanitizerMask Default, @@ -315,6 +312,9 @@ parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, } } + Output |= AlwaysIn; + Output &= ~AlwaysOut; + return Output; } @@ -324,10 +324,6 @@ static SanitizerMask parseSanitizeTrapArgs(const Driver &D, SanitizerMask AlwaysTrap; // Empty SanitizerMask NeverTrap = ~(setGroupBits(TrappingSupported)); - // N.B. We do *not* enforce NeverTrap. This maintains the behavior of - // '-fsanitize=undefined -fsanitize-trap=undefined' - // (clang/test/Driver/fsanitize.c ), which is that vptr is not enabled at all - // (not even in recover mode) in order to avoid the need for a ubsan runtime. return parseSanitizeArgs(D, Args, DiagnoseErrors, TrappingDefault, AlwaysTrap, NeverTrap, options::OPT_fsanitize_trap_EQ, options::OPT_fno_sanitize_trap_EQ); @@ -725,8 +721,6 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, D, Args, DiagnoseErrors, RecoverableByDefault, AlwaysRecoverable, Unrecoverable, options::OPT_fsanitize_recover_EQ, options::OPT_fno_sanitize_recover_EQ); - RecoverableKinds |= AlwaysRecoverable; - RecoverableKinds &= ~Unrecoverable; RecoverableKinds &= Kinds; TrappingKinds &= Kinds; diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c index 79c936a79ffd2..9eb6579ce30ab 100644 --- a/clang/test/Driver/fsanitize.c +++ b/clang/test/Driver/fsanitize.c @@ -149,7 +149,7 @@ // CHECK-FSANITIZE-SHIFT-PARTIAL: "-fsanitize=shift-exponent" // RUN: not %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-trap=vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-TRAP-UNDEF -// CHECK-VPTR-TRAP-UNDEF: error: invalid argument '-fsanitize=vptr' not allowed with '-fsanitize-trap=undefined' +// CHECK-VPTR-TRAP-UNDEF: error: unsupported argument 'vptr' to option '-fsanitize-trap=' // RUN: %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-undefined-trap-on-error %s -### `` https://github.com/llvm/llvm-project/pull/129405 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [sanitizer] Apply AlwaysIn/Out in parseSanitizeArgs (PR #129405)
llvmbot wrote: @llvm/pr-subscribers-clang-driver Author: Thurston Dang (thurstond) Changes For backwards compatibility, `parseSanitizeArgs`/`parseSanitizeTrapArgs` had an incomplete refactoring in https://github.com/llvm/llvm-project/pull/119819, in order to accommodate the special case of vptr in -fsanitize=undefined and its interaction with -fsanitize-trap=undefined. Now that vptr is no longer part of -fsanitize=undefined (https://github.com/llvm/llvm-project/pull/121115), this patch changes parseSanitizeArgs to apply the AlwaysIn/Out invariants in parseSanitizeArgs, which allows simplifying calls to parseSanitizeArgs. This is not quite NFC: it changes the error message of -fsanitize-trap=vptr. --- Full diff: https://github.com/llvm/llvm-project/pull/129405.diff 2 Files Affected: - (modified) clang/lib/Driver/SanitizerArgs.cpp (+4-10) - (modified) clang/test/Driver/fsanitize.c (+1-1) ``diff diff --git a/clang/lib/Driver/SanitizerArgs.cpp b/clang/lib/Driver/SanitizerArgs.cpp index 6e75001585c61..f5b0bc5ce720f 100644 --- a/clang/lib/Driver/SanitizerArgs.cpp +++ b/clang/lib/Driver/SanitizerArgs.cpp @@ -261,11 +261,8 @@ static SanitizerMask setGroupBits(SanitizerMask Kinds) { } // Computes the sanitizer mask as: -// Default + Arguments (in or out) +// Default + Arguments (in or out) + AlwaysIn - AlwaysOut // with arguments parsed from left to right. -// -// Error messages are printed if the AlwaysIn or AlwaysOut invariants are -// violated, but the caller must enforce these invariants themselves. static SanitizerMask parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, bool DiagnoseErrors, SanitizerMask Default, @@ -315,6 +312,9 @@ parseSanitizeArgs(const Driver &D, const llvm::opt::ArgList &Args, } } + Output |= AlwaysIn; + Output &= ~AlwaysOut; + return Output; } @@ -324,10 +324,6 @@ static SanitizerMask parseSanitizeTrapArgs(const Driver &D, SanitizerMask AlwaysTrap; // Empty SanitizerMask NeverTrap = ~(setGroupBits(TrappingSupported)); - // N.B. We do *not* enforce NeverTrap. This maintains the behavior of - // '-fsanitize=undefined -fsanitize-trap=undefined' - // (clang/test/Driver/fsanitize.c ), which is that vptr is not enabled at all - // (not even in recover mode) in order to avoid the need for a ubsan runtime. return parseSanitizeArgs(D, Args, DiagnoseErrors, TrappingDefault, AlwaysTrap, NeverTrap, options::OPT_fsanitize_trap_EQ, options::OPT_fno_sanitize_trap_EQ); @@ -725,8 +721,6 @@ SanitizerArgs::SanitizerArgs(const ToolChain &TC, D, Args, DiagnoseErrors, RecoverableByDefault, AlwaysRecoverable, Unrecoverable, options::OPT_fsanitize_recover_EQ, options::OPT_fno_sanitize_recover_EQ); - RecoverableKinds |= AlwaysRecoverable; - RecoverableKinds &= ~Unrecoverable; RecoverableKinds &= Kinds; TrappingKinds &= Kinds; diff --git a/clang/test/Driver/fsanitize.c b/clang/test/Driver/fsanitize.c index 79c936a79ffd2..9eb6579ce30ab 100644 --- a/clang/test/Driver/fsanitize.c +++ b/clang/test/Driver/fsanitize.c @@ -149,7 +149,7 @@ // CHECK-FSANITIZE-SHIFT-PARTIAL: "-fsanitize=shift-exponent" // RUN: not %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-trap=vptr %s -### 2>&1 | FileCheck %s --check-prefix=CHECK-VPTR-TRAP-UNDEF -// CHECK-VPTR-TRAP-UNDEF: error: invalid argument '-fsanitize=vptr' not allowed with '-fsanitize-trap=undefined' +// CHECK-VPTR-TRAP-UNDEF: error: unsupported argument 'vptr' to option '-fsanitize-trap=' // RUN: %clang --target=x86_64-linux-gnu -fsanitize=vptr -fsanitize-undefined-trap-on-error %s -### `` https://github.com/llvm/llvm-project/pull/129405 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
https://github.com/isuckatcs updated https://github.com/llvm/llvm-project/pull/128265 >From dc4d30261101f6fc186b828b9230752316ffdd76 Mon Sep 17 00:00:00 2001 From: isuckatcs <65320245+isucka...@users.noreply.github.com> Date: Sat, 1 Mar 2025 17:06:34 +0100 Subject: [PATCH] [clang][diagnostics] add '-Wundef-true' warning option --- clang/include/clang/Basic/DiagnosticGroups.td | 2 + .../include/clang/Basic/DiagnosticLexKinds.td | 5 +- clang/lib/Lex/PPExpressions.cpp | 5 +- .../test/Preprocessor/warn-macro-undef-true.c | 78 +++ 4 files changed, 87 insertions(+), 3 deletions(-) create mode 100644 clang/test/Preprocessor/warn-macro-undef-true.c diff --git a/clang/include/clang/Basic/DiagnosticGroups.td b/clang/include/clang/Basic/DiagnosticGroups.td index 05e39899e6f25..f14bcfc15039e 100644 --- a/clang/include/clang/Basic/DiagnosticGroups.td +++ b/clang/include/clang/Basic/DiagnosticGroups.td @@ -791,6 +791,8 @@ def ReservedIdAsMacroAlias : DiagGroup<"reserved-id-macro", [ReservedIdAsMacro]> def ReservedAttributeIdentifier : DiagGroup<"reserved-attribute-identifier">; def RestrictExpansionMacro : DiagGroup<"restrict-expansion">; def FinalMacro : DiagGroup<"final-macro">; +def UndefinedTrueIdentifier : DiagGroup<"undef-true">; +def UndefinedIdentifier : DiagGroup<"undef", [UndefinedTrueIdentifier]>; // Just silence warnings about -Wstrict-aliasing for now. def : DiagGroup<"strict-aliasing=0">; diff --git a/clang/include/clang/Basic/DiagnosticLexKinds.td b/clang/include/clang/Basic/DiagnosticLexKinds.td index 4bcef23ccce16..c2552565fb96c 100644 --- a/clang/include/clang/Basic/DiagnosticLexKinds.td +++ b/clang/include/clang/Basic/DiagnosticLexKinds.td @@ -392,7 +392,10 @@ def pp_macro_not_used : Warning<"macro is not used">, DefaultIgnore, InGroup>; def warn_pp_undef_identifier : Warning< "%0 is not defined, evaluates to 0">, - InGroup>, DefaultIgnore; + InGroup, DefaultIgnore; +def warn_pp_undef_true_identifier : Warning< + "'true' is not defined, evaluates to 0">, + InGroup; def warn_pp_undef_prefix : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; diff --git a/clang/lib/Lex/PPExpressions.cpp b/clang/lib/Lex/PPExpressions.cpp index a3b1384f0fa1d..6f344fbb80468 100644 --- a/clang/lib/Lex/PPExpressions.cpp +++ b/clang/lib/Lex/PPExpressions.cpp @@ -257,11 +257,12 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, // preprocessor keywords and it wasn't macro expanded, it turns // into a simple 0 if (ValueLive) { - PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; + unsigned DiagID = II->getName() == "true" ? diag::warn_pp_undef_true_identifier : diag::warn_pp_undef_identifier; + PP.Diag(PeekTok, DiagID) << II; const DiagnosticsEngine &DiagEngine = PP.getDiagnostics(); // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics. - if (DiagEngine.isIgnored(diag::warn_pp_undef_identifier, + if (DiagEngine.isIgnored(DiagID, PeekTok.getLocation())) { const std::vector UndefPrefixes = DiagEngine.getDiagnosticOptions().UndefPrefixes; diff --git a/clang/test/Preprocessor/warn-macro-undef-true.c b/clang/test/Preprocessor/warn-macro-undef-true.c new file mode 100644 index 0..9a64d577a96ed --- /dev/null +++ b/clang/test/Preprocessor/warn-macro-undef-true.c @@ -0,0 +1,78 @@ +// RUN: %clang_cc1 %s -Eonly -std=c89 -verify=undef-true +// RUN: %clang_cc1 %s -Eonly -std=c99 -verify=undef-true +// RUN: %clang_cc1 %s -Eonly -std=c11 -verify=undef-true +// RUN: %clang_cc1 %s -Eonly -std=c17 -verify=undef-true +// RUN: %clang_cc1 %s -Eonly -std=c23 -verify=undef-true + +#if __STDC_VERSION__ >= 202311L +/* undef-true-no-diagnostics */ +#endif + +#define FOO true +#if FOO /* #1 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#1 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #2 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#2 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #3 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#3 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true 1 + +#define FOO true +#if FOO +#endif + +#if true +#endif + +#if false || true +#endif + +#undef true + +#define FOO true +#if FOO /* #4 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#4 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if true /* #5 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#5 {{'true' is not defined, evaluates to 0}} */ +#endif + +#if false || true /* #6 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-true-warning@#6 {{'true' is not defined, evaluates to 0}} */ +#endif + +#define true true +#if true /* #7 */ +#endif +#if __STDC_VERSION__ < 202311L +/* undef-tru
[clang-tools-extra] [clang-tidy] `modernize-use-trailing-return-type`: add an option to apply to `void`-returning functions as well (PR #129406)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: None (khuldraeseth) Changes Adds an option `modernize-use-trailing-return-type.EvenWhenVoid` that when `true` enforces this check for declarations like `void foo();`. Default is `false` to preserve existing behavior. --- Full diff: https://github.com/llvm/llvm-project/pull/129406.diff 5 Files Affected: - (modified) clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp (+11-5) - (modified) clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h (+7-1) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+5) - (modified) clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst (+8) - (modified) clang-tools-extra/test/clang-tidy/checkers/modernize/use-trailing-return-type.cpp (+27-5) ``diff diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index 9774e988d71e2..12448303fdcd8 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -8,8 +8,10 @@ #include "UseTrailingReturnTypeCheck.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/DeclCXX.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Preprocessor.h" #include "clang/Tooling/FixIt.h" #include "llvm/ADT/StringExtras.h" @@ -287,7 +289,6 @@ SourceRange UseTrailingReturnTypeCheck::findReturnTypeAndCVSourceRange( return {}; } - // If the return type has no local qualifiers, it's source range is accurate. if (!hasAnyNestedLocalQualifiers(F.getReturnType())) return ReturnTypeRange; @@ -384,10 +385,15 @@ void UseTrailingReturnTypeCheck::keepSpecifiers( } void UseTrailingReturnTypeCheck::registerMatchers(MatchFinder *Finder) { - auto F = functionDecl( - unless(anyOf(hasTrailingReturn(), returns(voidType()), -cxxConversionDecl(), cxxMethodDecl(isImplicit() - .bind("Func"); + const auto hasNoWrittenReturnType = + anyOf(cxxConversionDecl(), cxxConstructorDecl(), cxxDestructorDecl(), +cxxMethodDecl(isImplicit())); + + const auto where = functionDecl( + unless(anyOf(hasTrailingReturn(), hasNoWrittenReturnType, + EvenWhenVoid ? unless(anything()) : returns(voidType(); + + auto F = where.bind("Func"); Finder->addMatcher(F, this); Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this); diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h index 5fb6ae945f466..fdd8be285c03b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h @@ -28,7 +28,8 @@ struct ClassifiedToken { class UseTrailingReturnTypeCheck : public ClangTidyCheck { public: UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + : ClangTidyCheck(Name, Context), +EvenWhenVoid(Options.get("EvenWhenVoid", false)) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus11; } @@ -39,6 +40,7 @@ class UseTrailingReturnTypeCheck : public ClangTidyCheck { private: Preprocessor *PP = nullptr; + bool const EvenWhenVoid; SourceLocation findTrailingReturnTypeSourceLocation( const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx, @@ -56,6 +58,10 @@ class UseTrailingReturnTypeCheck : public ClangTidyCheck { SourceRange ReturnTypeCVRange, const FunctionDecl &F, const FriendDecl *Fr, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts); + + auto storeOptions(ClangTidyOptions::OptionMap &Opts) -> void override { +Options.store(Opts, "EvenWhenVoid", EvenWhenVoid); + } }; } // namespace clang::tidy::modernize diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 2dcefa2ddec83..93b2202ce8635 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -120,6 +120,11 @@ Changes in existing checks tolerating fix-it breaking compilation when functions is used as pointers to avoid matching usage of functions within the current compilation unit. +- Improved :doc:`modernize/use-trailing-return-type + ` check by adding the + option ``EvenWhenVoid`` that applies the check to ``void``-returning functions + that by default are excluded from this check. + Removed checks ^^ diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
https://github.com/zygoloid edited https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream func args alloca handling (PR #129167)
@@ -52,6 +52,14 @@ class Address { elementType); } + Address(mlir::Value pointer, clang::CharUnits alignment) + : Address(pointer, +mlir::cast(pointer.getType()).getPointee(), erichkeane wrote: Got it, thanks for the clarification! NVM then. https://github.com/llvm/llvm-project/pull/129167 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave updated https://github.com/llvm/llvm-project/pull/129370 >From 39900908f047c2c067eea93855a5e6f644d13830 Mon Sep 17 00:00:00 2001 From: David Rivera Date: Sat, 1 Mar 2025 02:09:02 -0500 Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init --- .../modernize/UseDefaultMemberInitCheck.cpp | 26 +-- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/use-default-member-init.cpp | 26 +++ 3 files changed, 48 insertions(+), 8 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 6c06b0af342f6..3afc047a02b7b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) { case Stmt::UnaryOperatorClass: return sameValue(cast(E1)->getSubExpr(), cast(E2)->getSubExpr()); + case Stmt::BinaryOperatorClass: { +const auto *BinOp1 = cast(E1); +const auto *BinOp2 = cast(E2); +return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == cast(E2)->getValue(); @@ -194,15 +200,19 @@ void UseDefaultMemberInitCheck::storeOptions( } void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { + auto NumericLiteral = anyOf(integerLiteral(), floatLiteral()); + auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"), + hasUnaryOperand(NumericLiteral)); + auto EnumRef = declRefExpr(to(enumConstantDecl())); + + auto BinaryNumericExpr = binaryOperator( + hasOperands(anyOf(NumericLiteral, EnumRef, binaryOperator()), + anyOf(NumericLiteral, EnumRef, binaryOperator(; + auto InitBase = - anyOf(stringLiteral(), characterLiteral(), integerLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(integerLiteral())), -floatLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(floatLiteral())), -cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; + anyOf(stringLiteral(), characterLiteral(), NumericLiteral, +UnaryNumericLiteral, cxxBoolLiteral(), cxxNullPtrLiteralExpr(), +implicitValueInitExpr(), EnumRef, BinaryNumericExpr); auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..01892f4cde648 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -128,6 +128,10 @@ Changes in existing checks ` check by providing additional examples and fixing some macro related false positives. +- Improved :doc:`modernize-use-default-member-init + ` check by matching arithmetic + operations within member list initialization. + - Improved :doc:`performance/unnecessary-value-param ` check performance by tolerating fix-it breaking compilation when functions is used as pointers diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp index 81c980e0217e6..ff8c80b682bdb 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp @@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues { }; } // namespace PR63285 + +namespace PR122480 { + +#define ARITHMETIC_MACRO (44 - 2) + +class DefaultMemberInitWithArithmetic { + DefaultMemberInitWithArithmetic() : a{1 + 1}, b{1 + 11 + 123 + 1234}, c{2 + (4 / 2) + 3 + (7 / 11)}, d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {} + // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is redundant [modernize-use-default-member-init] + // CHECK-FIXES: DefaultMemberInitWithArithmetic() {} + + int a{1 + 1}; + int b; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'b' [modernize-use-default-member-init] + // CHECK-FIXES: int b{1 + 11 + 123 + 1234}; + int c; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'c' [modernize-use-default-member-init] + // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)} + int d; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'd' [modernize-use-default-member-
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave deleted https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] `modernize-use-trailing-return-type`: add an option to apply to `void`-returning functions as well (PR #129406)
https://github.com/khuldraeseth created https://github.com/llvm/llvm-project/pull/129406 Adds an option `modernize-use-trailing-return-type.EvenWhenVoid` that when `true` enforces this check for declarations like `void foo();`. Default is `false` to preserve existing behavior. >From cd7e8c60fb3d5d571b6f3398aa7b1fa0af88667c Mon Sep 17 00:00:00 2001 From: khuldraeseth <28711596+khuldraes...@users.noreply.github.com> Date: Wed, 26 Feb 2025 11:28:37 -0600 Subject: [PATCH 1/5] add EvenWhenVoid option to modernize-use-trailing-return-type check --- .../modernize/UseTrailingReturnTypeCheck.cpp | 16 +++- .../modernize/UseTrailingReturnTypeCheck.h | 8 +++- 2 files changed, 18 insertions(+), 6 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp index 9774e988d71e2..140d51e77fc70 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.cpp @@ -8,8 +8,10 @@ #include "UseTrailingReturnTypeCheck.h" #include "clang/AST/ASTContext.h" +#include "clang/AST/DeclCXX.h" #include "clang/AST/RecursiveASTVisitor.h" #include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" #include "clang/Lex/Preprocessor.h" #include "clang/Tooling/FixIt.h" #include "llvm/ADT/StringExtras.h" @@ -287,7 +289,6 @@ SourceRange UseTrailingReturnTypeCheck::findReturnTypeAndCVSourceRange( return {}; } - // If the return type has no local qualifiers, it's source range is accurate. if (!hasAnyNestedLocalQualifiers(F.getReturnType())) return ReturnTypeRange; @@ -384,10 +385,15 @@ void UseTrailingReturnTypeCheck::keepSpecifiers( } void UseTrailingReturnTypeCheck::registerMatchers(MatchFinder *Finder) { - auto F = functionDecl( - unless(anyOf(hasTrailingReturn(), returns(voidType()), -cxxConversionDecl(), cxxMethodDecl(isImplicit() - .bind("Func"); + auto const where = + EvenWhenVoid + ? functionDecl(unless(anyOf(hasTrailingReturn(), cxxConversionDecl(), + cxxMethodDecl(isImplicit() + : functionDecl(unless(anyOf(hasTrailingReturn(), returns(voidType()), + cxxConversionDecl(), + cxxMethodDecl(isImplicit(); + + auto F = where.bind("Func"); Finder->addMatcher(F, this); Finder->addMatcher(friendDecl(hasDescendant(F)).bind("Friend"), this); diff --git a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h index 5fb6ae945f466..fdd8be285c03b 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h +++ b/clang-tools-extra/clang-tidy/modernize/UseTrailingReturnTypeCheck.h @@ -28,7 +28,8 @@ struct ClassifiedToken { class UseTrailingReturnTypeCheck : public ClangTidyCheck { public: UseTrailingReturnTypeCheck(StringRef Name, ClangTidyContext *Context) - : ClangTidyCheck(Name, Context) {} + : ClangTidyCheck(Name, Context), +EvenWhenVoid(Options.get("EvenWhenVoid", false)) {} bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { return LangOpts.CPlusPlus11; } @@ -39,6 +40,7 @@ class UseTrailingReturnTypeCheck : public ClangTidyCheck { private: Preprocessor *PP = nullptr; + bool const EvenWhenVoid; SourceLocation findTrailingReturnTypeSourceLocation( const FunctionDecl &F, const FunctionTypeLoc &FTL, const ASTContext &Ctx, @@ -56,6 +58,10 @@ class UseTrailingReturnTypeCheck : public ClangTidyCheck { SourceRange ReturnTypeCVRange, const FunctionDecl &F, const FriendDecl *Fr, const ASTContext &Ctx, const SourceManager &SM, const LangOptions &LangOpts); + + auto storeOptions(ClangTidyOptions::OptionMap &Opts) -> void override { +Options.store(Opts, "EvenWhenVoid", EvenWhenVoid); + } }; } // namespace clang::tidy::modernize >From 305cbb6b44a4d16e8d4bd349548c98880b870480 Mon Sep 17 00:00:00 2001 From: khuldraeseth <28711596+khuldraes...@users.noreply.github.com> Date: Sat, 1 Mar 2025 15:47:01 -0600 Subject: [PATCH 2/5] document EvenWhenVoid check option --- .../checks/modernize/use-trailing-return-type.rst | 8 1 file changed, 8 insertions(+) diff --git a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst index 0593a35326aaa..1187c931fca43 100644 --- a/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst +++ b/clang-tools-extra/docs/clang-tidy/checks/modernize/use-trailing-return-type.rst @@ -25,6 +25,14 @@ transforms to: inline
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
https://github.com/zygoloid commented: Thanks! https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
@@ -202,7 +208,13 @@ void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(floatLiteral())), cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; +declRefExpr(to(enumConstantDecl())), +binaryOperator(hasLHS(anyOf(integerLiteral(), floatLiteral(), RiverDave wrote: Done. I've improved not only my part but think I got rid of some redundancies to make it more readable. There's still some duplicate code like: ```cpp hasOperands(anyOf(NumericLiteral, EnumRef, binaryOperator()), anyOf(NumericLiteral, EnumRef, binaryOperator(; ``` I'm not really sure if there's another way of avoiding that. for the rest let me know if this is the right direction. https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
@@ -791,6 +791,8 @@ def ReservedIdAsMacroAlias : DiagGroup<"reserved-id-macro", [ReservedIdAsMacro]> def ReservedAttributeIdentifier : DiagGroup<"reserved-attribute-identifier">; def RestrictExpansionMacro : DiagGroup<"restrict-expansion">; def FinalMacro : DiagGroup<"final-macro">; +def UndefinedIdentifier : DiagGroup<"undef">; +def UndefinedTrueIdentifier : DiagGroup<"undef-true", [UndefinedIdentifier]>; zygoloid wrote: This looks reversed to me: I think we want `UndefinedTrueIdentifier` to be listed as a child of `UndefinedIdentifier`, not the other way around, so that (eg) `-Wundef` implies `-Wundef-true` (not vice versa). https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
@@ -257,7 +257,10 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, // preprocessor keywords and it wasn't macro expanded, it turns // into a simple 0 if (ValueLive) { - PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; + if (II->getName() == "true") +PP.Diag(PeekTok, diag::warn_pp_undef_true_identifier); + else +PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; const DiagnosticsEngine &DiagEngine = PP.getDiagnostics(); // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics. zygoloid wrote: We should check the same DiagID we used above in the `isIgnored` check too; the logic is meant to be "if we just issued a diagnostic then don't produce another". https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] `modernize-use-trailing-return-type`: add an option to apply to `void`-returning functions as well (PR #129406)
github-actions[bot] wrote: Thank you for submitting a Pull Request (PR) to the LLVM Project! This PR will be automatically labeled and the relevant teams will be notified. If you wish to, you can add reviewers by using the "Reviewers" section on this page. If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using `@` followed by their GitHub username. If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers. If you have further questions, they may be answered by the [LLVM GitHub User Guide](https://llvm.org/docs/GitHub.html). You can also ask questions in a comment on this PR, on the [LLVM Discord](https://discord.com/invite/xS7Z362) or on the [forums](https://discourse.llvm.org/). https://github.com/llvm/llvm-project/pull/129406 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Check for uninitialized use in lambda within CXXOperatorCallExpr (PR #129198)
@@ -12796,6 +12799,7 @@ namespace { } void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) { + llvm::SaveAndRestore cxxOpCallScope(isInCXXOperatorCall, true); zhaohuiw42 wrote: Fixed. https://github.com/llvm/llvm-project/pull/129198 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in wrapping function return type (PR #129374)
https://github.com/owenca created https://github.com/llvm/llvm-project/pull/129374 Fixes #113766 >From 5bfc03509419452a22f2c9c663e53152390a310a Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 1 Mar 2025 01:53:01 -0800 Subject: [PATCH] [clang-format] Fix a bug in wrapping function return type Fixes #113766 --- clang/lib/Format/ContinuationIndenter.cpp | 4 clang/lib/Format/FormatToken.h| 3 +++ clang/lib/Format/UnwrappedLineParser.cpp | 6 -- clang/unittests/Format/FormatTest.cpp | 5 + 4 files changed, 16 insertions(+), 2 deletions(-) diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index d49128c2b40f8..fb4bcf965ac33 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -628,6 +628,10 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { // name. !Style.isJavaScript() && Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) { +for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous) + if (Tok->FirstAfterPPDirectiveLine || Tok->is(TT_LineComment)) +return false; + return true; } diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 02429970599c0..2cace7c3f060e 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -594,6 +594,9 @@ struct FormatToken { /// Has "\n\f\n" or "\n\f\r\n" before TokenText. bool HasFormFeedBefore = false; + /// Is the first token after a PPDirective line. + bool FirstAfterPPDirectiveLine = false; + /// Number of optional braces to be inserted after this token: /// -1: a single left brace ///0: no braces diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 16f19e955bf55..2da0432816df7 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -5091,8 +5091,10 @@ UnwrappedLineParser::parseMacroCall() { void UnwrappedLineParser::pushToken(FormatToken *Tok) { Line->Tokens.push_back(UnwrappedLineNode(Tok)); if (MustBreakBeforeNextToken) { -Line->Tokens.back().Tok->MustBreakBefore = true; -Line->Tokens.back().Tok->MustBreakBeforeFinalized = true; +auto &Tok = *Line->Tokens.back().Tok; +Tok.MustBreakBefore = true; +Tok.MustBreakBeforeFinalized = true; +Tok.FirstAfterPPDirectiveLine = true; MustBreakBeforeNextToken = false; } } diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 537be3632f439..15b58fc584997 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -6832,6 +6832,11 @@ TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { " param3) {\n" " f();\n" "}"); + + verifyFormat("#ifdef __cplusplus\n" + "extern \"C\"\n" + "#endif\n" + "void f();"); } TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] more useful error message for decomposition declaration missing initializer (PR #127924)
https://github.com/kbrav updated https://github.com/llvm/llvm-project/pull/127924 >From 7f7b9b3f2e7324bd290decb7151c9432875b1dd6 Mon Sep 17 00:00:00 2001 From: kbrav Date: Wed, 19 Feb 2025 19:05:05 -0500 Subject: [PATCH 1/4] [clang] more useful error message for decomposition declaration missing initializer (#90107) --- clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 +- clang/lib/Sema/SemaDecl.cpp | 12 +++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index feef50812eca9..ad36ae898b147 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -555,7 +555,7 @@ def err_decomp_decl_template : Error< def err_decomp_decl_not_alone : Error< "decomposition declaration must be the only declaration in its group">; def err_decomp_decl_requires_init : Error< - "decomposition declaration %0 requires an initializer">; + "decomposition declaration %0 requires an initializer, but got %1 instead">; def err_decomp_decl_wrong_number_bindings : Error< "type %0 decomposes into %3 %plural{1:element|:elements}2, but " "%select{%plural{0:no|:only %1}1|%1}4 " diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index 362df485a025c..c62041c8c5e93 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -14058,7 +14058,17 @@ void Sema::ActOnUninitializedDecl(Decl *RealDecl) { // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. if (isa(RealDecl)) { - Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var; + Preprocessor &PP = getPreprocessor(); + SourceManager &SM = Context.getSourceManager(); + LangOptionsLO = Context.getLangOpts(); + + // Lexer previously checked for '=' and didn't find it + // Highlight the token found in its place in the error message + Token Tok; + Lexer::getRawToken(PP.getLastCachedTokenLocation(), Tok, SM, LO); + + Diag(Tok.getLocation(), diag::err_decomp_decl_requires_init) +<< Var << Lexer::getSpelling(Tok, SM, LO); Var->setInvalidDecl(); return; } >From cd657462ec40663896fa60fdabf565625188958f Mon Sep 17 00:00:00 2001 From: kbrav Date: Wed, 19 Feb 2025 19:51:19 -0500 Subject: [PATCH 2/4] run clang-format --- clang/lib/Sema/SemaDecl.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp index c62041c8c5e93..724da72b8115e 100644 --- a/clang/lib/Sema/SemaDecl.cpp +++ b/clang/lib/Sema/SemaDecl.cpp @@ -14058,9 +14058,9 @@ void Sema::ActOnUninitializedDecl(Decl *RealDecl) { // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory. if (isa(RealDecl)) { - Preprocessor &PP = getPreprocessor(); + Preprocessor &PP = getPreprocessor(); SourceManager &SM = Context.getSourceManager(); - LangOptionsLO = Context.getLangOpts(); + LangOptions LO = Context.getLangOpts(); // Lexer previously checked for '=' and didn't find it // Highlight the token found in its place in the error message @@ -14068,7 +14068,7 @@ void Sema::ActOnUninitializedDecl(Decl *RealDecl) { Lexer::getRawToken(PP.getLastCachedTokenLocation(), Tok, SM, LO); Diag(Tok.getLocation(), diag::err_decomp_decl_requires_init) -<< Var << Lexer::getSpelling(Tok, SM, LO); + << Var << Lexer::getSpelling(Tok, SM, LO); Var->setInvalidDecl(); return; } >From feac0003628dd18a54a8c1f101bd21be4e714534 Mon Sep 17 00:00:00 2001 From: kbrav Date: Tue, 25 Feb 2025 02:01:22 -0500 Subject: [PATCH 3/4] highlight token after decomposition decl in parser --- clang/docs/ReleaseNotes.rst | 1 + clang/include/clang/Basic/DiagnosticParseKinds.td | 1 + clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 +- clang/lib/Parse/ParseDecl.cpp | 2 ++ clang/lib/Sema/SemaDecl.cpp | 12 +--- clang/test/PCH/cxx1z-decomposition.cpp| 2 +- clang/test/Parser/cxx1z-decomposition.cpp | 9 + clang/test/SemaCXX/cxx1z-decomposition.cpp| 2 +- 8 files changed, 13 insertions(+), 18 deletions(-) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 657340c170503..109abdef4ad01 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -193,6 +193,7 @@ Improvements to Clang's diagnostics under the subgroup ``-Wunsafe-buffer-usage-in-libc-call``. - Diagnostics on chained comparisons (``a < b < c``) are now an error by default. This can be disabled with ``-Wno-error=parentheses``. +- Added a clearer diagnostic for uninitialized decomposition declarations. Improvements to Clang's time-trace -- diff --git a/cl
[clang] [llvm] [libclang/python] Enable packaging libclang bindings (PR #125806)
https://github.com/LecrisUT approved this pull request. My review is that it looks good to go for the scope that it serves. Follow up changes I would recommend is to align the CI and `pyproject.toml` across the other python projects, but it seems that it has been broken for a while, so it's a bigger issue to address. https://github.com/llvm/llvm-project/pull/125806 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [libclang/python] Enable packaging libclang bindings (PR #125806)
https://github.com/LecrisUT edited https://github.com/llvm/llvm-project/pull/125806 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Add `pragma clang scope [push|pop]` (PR #121025)
vgvassilev wrote: I wonder if we had an rfc for this. Maybe we should solicit some feedback before moving forward with this extension. https://github.com/llvm/llvm-project/pull/121025 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/vbvictor edited https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
@@ -202,7 +208,13 @@ void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(floatLiteral())), cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; +declRefExpr(to(enumConstantDecl())), +binaryOperator(hasLHS(anyOf(integerLiteral(), floatLiteral(), vbvictor wrote: Consider moving duplicate code to helper-mather like `auto Init` https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Realign CIR-to-LLVM IR lowering code with incubator (PR #129293)
https://github.com/erichkeane approved this pull request. https://github.com/llvm/llvm-project/pull/129293 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] Reland #90786 ([BoundsSafety] Allow 'counted_by' attribute on pointers in structs in C) (PR #93121)
@@ -8663,31 +8663,95 @@ static const RecordDecl *GetEnclosingNamedOrTopAnonRecord(const FieldDecl *FD) { return RD; } -static bool -CheckCountExpr(Sema &S, FieldDecl *FD, Expr *E, - llvm::SmallVectorImpl &Decls) { +enum class CountedByInvalidPointeeTypeKind { + INCOMPLETE, + SIZELESS, + FUNCTION, + FLEXIBLE_ARRAY_MEMBER, + VALID, +}; + +static bool CheckCountedByAttrOnField( +Sema &S, FieldDecl *FD, Expr *E, +llvm::SmallVectorImpl &Decls) { + // Check the context the attribute is used in + if (FD->getParent()->isUnion()) { S.Diag(FD->getBeginLoc(), diag::err_counted_by_attr_in_union) << FD->getSourceRange(); return true; } - if (!E->getType()->isIntegerType() || E->getType()->isBooleanType()) { -S.Diag(E->getBeginLoc(), diag::err_counted_by_attr_argument_not_integer) -<< E->getSourceRange(); + const auto FieldTy = FD->getType(); + if (!FieldTy->isArrayType() && !FieldTy->isPointerType()) { +S.Diag(FD->getBeginLoc(), + diag::err_counted_by_attr_not_on_ptr_or_flexible_array_member) +<< FD->getLocation(); return true; } LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel = LangOptions::StrictFlexArraysLevelKind::IncompleteOnly; - - if (!Decl::isFlexibleArrayMemberLike(S.getASTContext(), FD, FD->getType(), + if (FieldTy->isArrayType() && + !Decl::isFlexibleArrayMemberLike(S.getASTContext(), FD, FieldTy, StrictFlexArraysLevel, true)) { -// The "counted_by" attribute must be on a flexible array member. -SourceRange SR = FD->getLocation(); -S.Diag(SR.getBegin(), - diag::err_counted_by_attr_not_on_flexible_array_member) -<< SR; +S.Diag(FD->getBeginLoc(), + diag::err_counted_by_attr_on_array_not_flexible_array_member) kees wrote: Yes, `=1` and `=2` were introduced by GCC against my recommendation even though they could not justify it beyond theoretical concerns. IMO, our experience purging the Linux kernel of fake flexible arrays supports the "all or nothing" case for dealing with flexible arrays. But, whatever the case, at the end of the day, `=3` needs to stick to the "strict" part of the option name. :) Anything else allows for ambiguous bounds calculations, and ambiguity is what breeds bugs and security flaws. https://github.com/llvm/llvm-project/pull/93121 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang] Pass fp128 indirectly and return in xmm0 on Windows (PR #115052)
https://github.com/tgross35 edited https://github.com/llvm/llvm-project/pull/115052 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in wrapping function return type (PR #129374)
llvmbot wrote: @llvm/pr-subscribers-clang-format Author: Owen Pan (owenca) Changes Fixes #113766 --- Full diff: https://github.com/llvm/llvm-project/pull/129374.diff 4 Files Affected: - (modified) clang/lib/Format/ContinuationIndenter.cpp (+4) - (modified) clang/lib/Format/FormatToken.h (+3) - (modified) clang/lib/Format/UnwrappedLineParser.cpp (+4-2) - (modified) clang/unittests/Format/FormatTest.cpp (+5) ``diff diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index d49128c2b40f8..fb4bcf965ac33 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -628,6 +628,10 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { // name. !Style.isJavaScript() && Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) { +for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous) + if (Tok->FirstAfterPPDirectiveLine || Tok->is(TT_LineComment)) +return false; + return true; } diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 02429970599c0..2cace7c3f060e 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -594,6 +594,9 @@ struct FormatToken { /// Has "\n\f\n" or "\n\f\r\n" before TokenText. bool HasFormFeedBefore = false; + /// Is the first token after a PPDirective line. + bool FirstAfterPPDirectiveLine = false; + /// Number of optional braces to be inserted after this token: /// -1: a single left brace ///0: no braces diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 16f19e955bf55..2da0432816df7 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -5091,8 +5091,10 @@ UnwrappedLineParser::parseMacroCall() { void UnwrappedLineParser::pushToken(FormatToken *Tok) { Line->Tokens.push_back(UnwrappedLineNode(Tok)); if (MustBreakBeforeNextToken) { -Line->Tokens.back().Tok->MustBreakBefore = true; -Line->Tokens.back().Tok->MustBreakBeforeFinalized = true; +auto &Tok = *Line->Tokens.back().Tok; +Tok.MustBreakBefore = true; +Tok.MustBreakBeforeFinalized = true; +Tok.FirstAfterPPDirectiveLine = true; MustBreakBeforeNextToken = false; } } diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 537be3632f439..15b58fc584997 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -6832,6 +6832,11 @@ TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { " param3) {\n" " f();\n" "}"); + + verifyFormat("#ifdef __cplusplus\n" + "extern \"C\"\n" + "#endif\n" + "void f();"); } TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { `` https://github.com/llvm/llvm-project/pull/129374 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff 83d2c68fc151ab50e005ecd36edb53a2af89e71c 60856b908e2b52cc512445d7d31e7fc72cd124cb --extensions cpp -- clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp `` View the diff from clang-format here. ``diff diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index a9d9e8b66e..d155207d2a 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -163,7 +163,7 @@ static bool sameValue(const Expr *E1, const Expr *E2) { const auto *BinOp1 = cast(E1); const auto *BinOp2 = cast(E2); return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && -sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == @@ -209,11 +209,12 @@ void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { hasUnaryOperand(floatLiteral())), cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), declRefExpr(to(enumConstantDecl())), -binaryOperator( -hasLHS(anyOf(integerLiteral(), floatLiteral(), - declRefExpr(to(enumConstantDecl())), binaryOperator())), -hasRHS(anyOf(integerLiteral(), floatLiteral(), - declRefExpr(to(enumConstantDecl())), binaryOperator(); +binaryOperator(hasLHS(anyOf(integerLiteral(), floatLiteral(), +declRefExpr(to(enumConstantDecl())), +binaryOperator())), + hasRHS(anyOf(integerLiteral(), floatLiteral(), +declRefExpr(to(enumConstantDecl())), +binaryOperator(); auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), `` https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave updated https://github.com/llvm/llvm-project/pull/129370 >From 68c371939323c9be13dba2e8e80ac4138859d845 Mon Sep 17 00:00:00 2001 From: David Rivera Date: Sat, 1 Mar 2025 02:09:02 -0500 Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init --- .../modernize/UseDefaultMemberInitCheck.cpp | 14 +- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/use-default-member-init.cpp | 26 +++ 3 files changed, 43 insertions(+), 1 deletion(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 6c06b0af342f6..d155207d2a3ea 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) { case Stmt::UnaryOperatorClass: return sameValue(cast(E1)->getSubExpr(), cast(E2)->getSubExpr()); + case Stmt::BinaryOperatorClass: { +const auto *BinOp1 = cast(E1); +const auto *BinOp2 = cast(E2); +return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == cast(E2)->getValue(); @@ -202,7 +208,13 @@ void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(floatLiteral())), cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; +declRefExpr(to(enumConstantDecl())), +binaryOperator(hasLHS(anyOf(integerLiteral(), floatLiteral(), +declRefExpr(to(enumConstantDecl())), +binaryOperator())), + hasRHS(anyOf(integerLiteral(), floatLiteral(), +declRefExpr(to(enumConstantDecl())), +binaryOperator(); auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..6d909f9d7c6bd 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`modernize-use-default-member-init + ` check by matching arithmetic + operations within member list initialization. + Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp index 81c980e0217e6..ff8c80b682bdb 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp @@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues { }; } // namespace PR63285 + +namespace PR122480 { + +#define ARITHMETIC_MACRO (44 - 2) + +class DefaultMemberInitWithArithmetic { + DefaultMemberInitWithArithmetic() : a{1 + 1}, b{1 + 11 + 123 + 1234}, c{2 + (4 / 2) + 3 + (7 / 11)}, d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {} + // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is redundant [modernize-use-default-member-init] + // CHECK-FIXES: DefaultMemberInitWithArithmetic() {} + + int a{1 + 1}; + int b; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'b' [modernize-use-default-member-init] + // CHECK-FIXES: int b{1 + 11 + 123 + 1234}; + int c; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'c' [modernize-use-default-member-init] + // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)} + int d; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'd' [modernize-use-default-member-init] + // CHECK-FIXES: int d{ARITHMETIC_MACRO * 2}; + double e; + // CHECK-MESSAGES: :[[@LINE-1]]:10: warning: use default member initializer for 'e' [modernize-use-default-member-init] + // CHECK-FIXES: double e{1.2 + 3.4}; + +}; +} // namespace PR122480 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [libcxx] [llvm] [libc++] constexpr deque (PR #129367)
https://github.com/changkhothuychung created https://github.com/llvm/llvm-project/pull/129367 None error: too big or took too long to generate ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [MC/DC] Refactor MCDC::State::Decision. NFC. (PR #125408)
@@ -30,8 +32,20 @@ struct State { unsigned BitmapBits = 0; struct Decision { +using IndicesTy = llvm::SmallVector>; +static constexpr auto InvalidID = std::numeric_limits::max(); + unsigned BitmapIdx; -llvm::SmallVector> Indices; +IndicesTy Indices; +unsigned ID = InvalidID; + +bool isValid() const { return ID != InvalidID; } + +void update(unsigned I, IndicesTy &&X) { + assert(ID != InvalidID); chapuni wrote: Done. https://github.com/llvm/llvm-project/pull/125408 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-format] Fix a bug in wrapping function return type (PR #129374)
https://github.com/owenca updated https://github.com/llvm/llvm-project/pull/129374 >From 24b77153d8f65bdf3282a8f25fbc87b619a736f6 Mon Sep 17 00:00:00 2001 From: Owen Pan Date: Sat, 1 Mar 2025 01:53:01 -0800 Subject: [PATCH] [clang-format] Fix a bug in wrapping function return type Fixes #113766 --- clang/lib/Format/ContinuationIndenter.cpp | 4 clang/lib/Format/FormatToken.h| 3 +++ clang/lib/Format/UnwrappedLineParser.cpp | 6 -- clang/unittests/Format/FormatTest.cpp | 9 + 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/clang/lib/Format/ContinuationIndenter.cpp b/clang/lib/Format/ContinuationIndenter.cpp index d49128c2b40f8..fb4bcf965ac33 100644 --- a/clang/lib/Format/ContinuationIndenter.cpp +++ b/clang/lib/Format/ContinuationIndenter.cpp @@ -628,6 +628,10 @@ bool ContinuationIndenter::mustBreak(const LineState &State) { // name. !Style.isJavaScript() && Previous.isNot(tok::kw_template) && CurrentState.BreakBeforeParameter) { +for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous) + if (Tok->FirstAfterPPDirectiveLine || Tok->is(TT_LineComment)) +return false; + return true; } diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h index 02429970599c0..2cace7c3f060e 100644 --- a/clang/lib/Format/FormatToken.h +++ b/clang/lib/Format/FormatToken.h @@ -594,6 +594,9 @@ struct FormatToken { /// Has "\n\f\n" or "\n\f\r\n" before TokenText. bool HasFormFeedBefore = false; + /// Is the first token after a PPDirective line. + bool FirstAfterPPDirectiveLine = false; + /// Number of optional braces to be inserted after this token: /// -1: a single left brace ///0: no braces diff --git a/clang/lib/Format/UnwrappedLineParser.cpp b/clang/lib/Format/UnwrappedLineParser.cpp index 16f19e955bf55..2da0432816df7 100644 --- a/clang/lib/Format/UnwrappedLineParser.cpp +++ b/clang/lib/Format/UnwrappedLineParser.cpp @@ -5091,8 +5091,10 @@ UnwrappedLineParser::parseMacroCall() { void UnwrappedLineParser::pushToken(FormatToken *Tok) { Line->Tokens.push_back(UnwrappedLineNode(Tok)); if (MustBreakBeforeNextToken) { -Line->Tokens.back().Tok->MustBreakBefore = true; -Line->Tokens.back().Tok->MustBreakBeforeFinalized = true; +auto &Tok = *Line->Tokens.back().Tok; +Tok.MustBreakBefore = true; +Tok.MustBreakBeforeFinalized = true; +Tok.FirstAfterPPDirectiveLine = true; MustBreakBeforeNextToken = false; } } diff --git a/clang/unittests/Format/FormatTest.cpp b/clang/unittests/Format/FormatTest.cpp index 537be3632f439..f3948142da0c9 100644 --- a/clang/unittests/Format/FormatTest.cpp +++ b/clang/unittests/Format/FormatTest.cpp @@ -6832,6 +6832,11 @@ TEST_F(FormatTest, LayoutStatementsAroundPreprocessorDirectives) { " param3) {\n" " f();\n" "}"); + + verifyFormat("#ifdef __cplusplus\n" + "extern \"C\"\n" + "#endif\n" + "void f();"); } TEST_F(FormatTest, GraciouslyHandleIncorrectPreprocessorConditions) { @@ -8539,6 +8544,7 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) { verifyGoogleFormat( "SomeLoogType operator<<(\n" "const SomeLogType &a, const SomeLogType &b);"); + verifyFormat("void (\n" "int aaa = 1);"); verifyFormat("aa\n" @@ -8552,6 +8558,9 @@ TEST_F(FormatTest, BreaksFunctionDeclarations) { "aaa::a(\n" "aaa aaa);"); + verifyFormat("extern \"C\" //\n" + "void f();"); + FormatStyle Style = getLLVMStyle(); Style.PointerAlignment = FormatStyle::PAS_Left; verifyFormat("void aa(\n" ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Add a few things to the python api (PR #120590)
DeinAlptraum wrote: @Endilll since there hasn't been a reply in months, do you think it's appropriate to close this? https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][bytecode] Explicitly composite array descriptor types (PR #129376)
https://github.com/tbaederr created https://github.com/llvm/llvm-project/pull/129376 When creating descriptor for array element types, we only save the original source, e.g. int[2][2][2]. So later calls to getType() of the element descriptors will also return int[2][2][2], instead of e.g. int[2][2] for the second dimension. Fix this by explicitly tracking the array types. The last attached test case used to have an lvalue offset of 32 instead of 24. We should do this for more desriptor types though and not just composite array, but I'm leaving that to a later patch. >From 82c307fd468a481096d64f7270e1eea4a7f503ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timm=20B=C3=A4der?= Date: Sat, 1 Mar 2025 11:38:08 +0100 Subject: [PATCH] [clang][bytecode] Explicitly composite array descriptor types When creating descriptor for array element types, we only save the original source, e.g. int[2][2][2]. So later calls to getType() of the element descriptors will also return int[2][2][2], instead of e.g. int[2][2] for the second dimension. Fix this by explicitly tracking the array types. The last attached test case used to have an lvalue offset of 32 instead of 24. We should do this for more desriptor types though and not just composite array, but I'm leaving that to a later patch. --- clang/lib/AST/ByteCode/Descriptor.cpp | 8 ++- clang/lib/AST/ByteCode/Descriptor.h | 6 +- clang/lib/AST/ByteCode/DynamicAllocator.cpp | 4 +- clang/lib/AST/ByteCode/Program.cpp | 2 +- clang/unittests/AST/ByteCode/toAPValue.cpp | 67 + 5 files changed, 81 insertions(+), 6 deletions(-) diff --git a/clang/lib/AST/ByteCode/Descriptor.cpp b/clang/lib/AST/ByteCode/Descriptor.cpp index 6017f6dd61cb3..bcd9f6f3d078a 100644 --- a/clang/lib/AST/ByteCode/Descriptor.cpp +++ b/clang/lib/AST/ByteCode/Descriptor.cpp @@ -367,10 +367,12 @@ Descriptor::Descriptor(const DeclTy &D, PrimType Type, MetadataSize MD, } /// Arrays of composite elements. -Descriptor::Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, +Descriptor::Descriptor(const DeclTy &D, const Type *SourceTy, + const Descriptor *Elem, MetadataSize MD, unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable) -: Source(D), ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)), +: Source(D), SourceType(SourceTy), + ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)), Size(ElemSize * NumElems), MDSize(MD.value_or(0)), AllocSize(std::max(alignof(void *), Size) + MDSize), ElemDesc(Elem), IsConst(IsConst), IsMutable(IsMutable), @@ -410,6 +412,8 @@ Descriptor::Descriptor(const DeclTy &D) } QualType Descriptor::getType() const { + if (SourceType) +return QualType(SourceType, 0); if (const auto *D = asValueDecl()) return D->getType(); if (const auto *T = dyn_cast_if_present(asDecl())) diff --git a/clang/lib/AST/ByteCode/Descriptor.h b/clang/lib/AST/ByteCode/Descriptor.h index 01fa4b198de67..b2e9f1b6bded4 100644 --- a/clang/lib/AST/ByteCode/Descriptor.h +++ b/clang/lib/AST/ByteCode/Descriptor.h @@ -124,6 +124,7 @@ struct Descriptor final { private: /// Original declaration, used to emit the error message. const DeclTy Source; + const Type *SourceType = nullptr; /// Size of an element, in host bytes. const unsigned ElemSize; /// Size of the storage, in host bytes. @@ -186,8 +187,9 @@ struct Descriptor final { bool IsTemporary, UnknownSize); /// Allocates a descriptor for an array of composites. - Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, - unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable); + Descriptor(const DeclTy &D, const Type *SourceTy, const Descriptor *Elem, + MetadataSize MD, unsigned NumElems, bool IsConst, bool IsTemporary, + bool IsMutable); /// Allocates a descriptor for an array of composites of unknown size. Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp b/clang/lib/AST/ByteCode/DynamicAllocator.cpp index 3ef8c2e1f3e7c..728bd75d7d141 100644 --- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp +++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp @@ -57,8 +57,10 @@ Block *DynamicAllocator::allocate(const Descriptor *ElementDesc, assert(ElementDesc->getMetadataSize() == 0); // Create a new descriptor for an array of the specified size and // element type. + // FIXME: Pass proper element type. const Descriptor *D = allocateDescriptor( - ElementDesc->asExpr(), ElementDesc, Descriptor::InlineDescMD, NumElements, + ElementDesc->asExpr(), nullptr, ElementDesc, Descriptor::InlineDescMD, + NumElements, /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false); return allocate(D, EvalID, AllocForm); } diff --git a/clang/lib/AST/ByteCode
[clang] [clang][bytecode] Explicitly composite array descriptor types (PR #129376)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Timm Baeder (tbaederr) Changes When creating descriptor for array element types, we only save the original source, e.g. int[2][2][2]. So later calls to getType() of the element descriptors will also return int[2][2][2], instead of e.g. int[2][2] for the second dimension. Fix this by explicitly tracking the array types. The last attached test case used to have an lvalue offset of 32 instead of 24. We should do this for more desriptor types though and not just composite array, but I'm leaving that to a later patch. --- Full diff: https://github.com/llvm/llvm-project/pull/129376.diff 5 Files Affected: - (modified) clang/lib/AST/ByteCode/Descriptor.cpp (+6-2) - (modified) clang/lib/AST/ByteCode/Descriptor.h (+4-2) - (modified) clang/lib/AST/ByteCode/DynamicAllocator.cpp (+3-1) - (modified) clang/lib/AST/ByteCode/Program.cpp (+1-1) - (modified) clang/unittests/AST/ByteCode/toAPValue.cpp (+67) ``diff diff --git a/clang/lib/AST/ByteCode/Descriptor.cpp b/clang/lib/AST/ByteCode/Descriptor.cpp index 6017f6dd61cb3..bcd9f6f3d078a 100644 --- a/clang/lib/AST/ByteCode/Descriptor.cpp +++ b/clang/lib/AST/ByteCode/Descriptor.cpp @@ -367,10 +367,12 @@ Descriptor::Descriptor(const DeclTy &D, PrimType Type, MetadataSize MD, } /// Arrays of composite elements. -Descriptor::Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, +Descriptor::Descriptor(const DeclTy &D, const Type *SourceTy, + const Descriptor *Elem, MetadataSize MD, unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable) -: Source(D), ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)), +: Source(D), SourceType(SourceTy), + ElemSize(Elem->getAllocSize() + sizeof(InlineDescriptor)), Size(ElemSize * NumElems), MDSize(MD.value_or(0)), AllocSize(std::max(alignof(void *), Size) + MDSize), ElemDesc(Elem), IsConst(IsConst), IsMutable(IsMutable), @@ -410,6 +412,8 @@ Descriptor::Descriptor(const DeclTy &D) } QualType Descriptor::getType() const { + if (SourceType) +return QualType(SourceType, 0); if (const auto *D = asValueDecl()) return D->getType(); if (const auto *T = dyn_cast_if_present(asDecl())) diff --git a/clang/lib/AST/ByteCode/Descriptor.h b/clang/lib/AST/ByteCode/Descriptor.h index 01fa4b198de67..b2e9f1b6bded4 100644 --- a/clang/lib/AST/ByteCode/Descriptor.h +++ b/clang/lib/AST/ByteCode/Descriptor.h @@ -124,6 +124,7 @@ struct Descriptor final { private: /// Original declaration, used to emit the error message. const DeclTy Source; + const Type *SourceType = nullptr; /// Size of an element, in host bytes. const unsigned ElemSize; /// Size of the storage, in host bytes. @@ -186,8 +187,9 @@ struct Descriptor final { bool IsTemporary, UnknownSize); /// Allocates a descriptor for an array of composites. - Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, - unsigned NumElems, bool IsConst, bool IsTemporary, bool IsMutable); + Descriptor(const DeclTy &D, const Type *SourceTy, const Descriptor *Elem, + MetadataSize MD, unsigned NumElems, bool IsConst, bool IsTemporary, + bool IsMutable); /// Allocates a descriptor for an array of composites of unknown size. Descriptor(const DeclTy &D, const Descriptor *Elem, MetadataSize MD, diff --git a/clang/lib/AST/ByteCode/DynamicAllocator.cpp b/clang/lib/AST/ByteCode/DynamicAllocator.cpp index 3ef8c2e1f3e7c..728bd75d7d141 100644 --- a/clang/lib/AST/ByteCode/DynamicAllocator.cpp +++ b/clang/lib/AST/ByteCode/DynamicAllocator.cpp @@ -57,8 +57,10 @@ Block *DynamicAllocator::allocate(const Descriptor *ElementDesc, assert(ElementDesc->getMetadataSize() == 0); // Create a new descriptor for an array of the specified size and // element type. + // FIXME: Pass proper element type. const Descriptor *D = allocateDescriptor( - ElementDesc->asExpr(), ElementDesc, Descriptor::InlineDescMD, NumElements, + ElementDesc->asExpr(), nullptr, ElementDesc, Descriptor::InlineDescMD, + NumElements, /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false); return allocate(D, EvalID, AllocForm); } diff --git a/clang/lib/AST/ByteCode/Program.cpp b/clang/lib/AST/ByteCode/Program.cpp index 0754e259b7cb3..cc2cfc9b03b41 100644 --- a/clang/lib/AST/ByteCode/Program.cpp +++ b/clang/lib/AST/ByteCode/Program.cpp @@ -419,7 +419,7 @@ Descriptor *Program::createDescriptor(const DeclTy &D, const Type *Ty, unsigned ElemSize = ElemDesc->getAllocSize() + sizeof(InlineDescriptor); if (std::numeric_limits::max() / ElemSize <= NumElems) return {}; -return allocateDescriptor(D, ElemDesc, MDSize, NumElems, IsConst, +return allocateDescriptor(D, Ty, ElemDesc, MDSize, NumElems, IsConst, IsTemporary, IsMutable
[clang] [CIR] Upstream floating point literal expressions (PR #129304)
@@ -57,3 +57,15 @@ bool boolfunc() { return true; } // CHECK: %0 = cir.const #true // CHECK: cir.return %0 : !cir.bool // CHECK: } + +float floatfunc() { return 42.42f; } +// CHECK: cir.func @floatfunc() -> !cir.float { +// CHECK: %0 = cir.const #cir.fp<4.242000e+01> : !cir.float AmrDeveloper wrote: As far as I understand both MLIR LLVM dialect and LLVM IR use the same format, I will update the test to just check this part `%0 = cir.const #cir.fp<4.242` https://github.com/llvm/llvm-project/pull/129304 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [CIR] Upstream floating point literal expressions (PR #129304)
https://github.com/AmrDeveloper updated https://github.com/llvm/llvm-project/pull/129304 >From d13f2d0d40987302243efad7304a1a006fdb2dde Mon Sep 17 00:00:00 2001 From: AmrDeveloper Date: Fri, 28 Feb 2025 21:42:36 +0100 Subject: [PATCH 1/2] [CIR] Upstream floating point literal expressions --- clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp | 9 + clang/test/CIR/func-simple.cpp | 12 2 files changed, 21 insertions(+) diff --git a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp index 24a959108f73b..1b2861ddcedb5 100644 --- a/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp +++ b/clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp @@ -59,6 +59,15 @@ class ScalarExprEmitter : public StmtVisitor { builder.getAttr(type, e->getValue())); } + mlir::Value VisitFloatingLiteral(const FloatingLiteral *e) { +mlir::Type type = cgf.convertType(e->getType()); +assert(mlir::isa(type) && + "expect floating-point type"); +return builder.create( +cgf.getLoc(e->getExprLoc()), type, +builder.getAttr(type, e->getValue())); + } + mlir::Value VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *e) { mlir::Type type = cgf.convertType(e->getType()); return builder.create( diff --git a/clang/test/CIR/func-simple.cpp b/clang/test/CIR/func-simple.cpp index 3947055e300a0..5927d90a2e548 100644 --- a/clang/test/CIR/func-simple.cpp +++ b/clang/test/CIR/func-simple.cpp @@ -57,3 +57,15 @@ bool boolfunc() { return true; } // CHECK: %0 = cir.const #true // CHECK: cir.return %0 : !cir.bool // CHECK: } + +float floatfunc() { return 42.42f; } +// CHECK: cir.func @floatfunc() -> !cir.float { +// CHECK: %0 = cir.const #cir.fp<4.242000e+01> : !cir.float +// CHECK: cir.return %0 : !cir.float +// CHECK: } + +double doublefunc() { return 42.42; } +// CHECK: cir.func @doublefunc() -> !cir.double { +// CHECK: %0 = cir.const #cir.fp<4.242000e+01> : !cir.double +// CHECK: cir.return %0 : !cir.double +// CHECK: } >From a1409b1b1b73249a4baa98435f0c6fd7d15be5c8 Mon Sep 17 00:00:00 2001 From: AmrDeveloper Date: Sat, 1 Mar 2025 11:56:56 +0100 Subject: [PATCH 2/2] Simplify the test to check the first part of the floating point only --- clang/test/CIR/func-simple.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clang/test/CIR/func-simple.cpp b/clang/test/CIR/func-simple.cpp index 5927d90a2e548..d37ccc7229f22 100644 --- a/clang/test/CIR/func-simple.cpp +++ b/clang/test/CIR/func-simple.cpp @@ -60,12 +60,12 @@ bool boolfunc() { return true; } float floatfunc() { return 42.42f; } // CHECK: cir.func @floatfunc() -> !cir.float { -// CHECK: %0 = cir.const #cir.fp<4.242000e+01> : !cir.float +// CHECK: %0 = cir.const #cir.fp<4.242 // CHECK: cir.return %0 : !cir.float // CHECK: } double doublefunc() { return 42.42; } // CHECK: cir.func @doublefunc() -> !cir.double { -// CHECK: %0 = cir.const #cir.fp<4.242000e+01> : !cir.double +// CHECK: %0 = cir.const #cir.fp<4.242 // CHECK: cir.return %0 : !cir.double // CHECK: } ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang][diagnostics] Improve the diagnostics for chained comparisons (PR #129285)
@@ -85,7 +85,7 @@ void f(int x, int y, int z) { if ((ayy y < z' don't have their mathematical meaning}} AmrDeveloper wrote: Yes, I got your point also it will not be great with large expressions :D, I am thinking should we change the message to be different or just the old one with actual operators 🤔 https://github.com/llvm/llvm-project/pull/129285 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [MC/DC] Update CoverageMapping tests (PR #125404)
@@ -0,0 +1,34 @@ +// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 -fcoverage-mcdc -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only %s 2> %t.stderr.txt | FileCheck %s chapuni wrote: Nah, wrong. I've removed another. https://github.com/llvm/llvm-project/pull/125404 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [WebAssembly] Make WASI -threads environment behave as -pthread (PR #129164)
https://github.com/ArcaneNibble closed https://github.com/llvm/llvm-project/pull/129164 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 39edcf9 - [WebAssembly] Make WASI -threads environment behave as -pthread (#129164)
Author: R Date: 2025-03-01T12:53:57Z New Revision: 39edcf9126ee1709753728205d2ed211aac4f7b3 URL: https://github.com/llvm/llvm-project/commit/39edcf9126ee1709753728205d2ed211aac4f7b3 DIFF: https://github.com/llvm/llvm-project/commit/39edcf9126ee1709753728205d2ed211aac4f7b3.diff LOG: [WebAssembly] Make WASI -threads environment behave as -pthread (#129164) If the user specifies a target triple of wasm32-wasi-threads, then enable all of the same flags as if `-pthread` were passed. This helps prevent user error, as the whole point of selecting this target is to gain pthread support. The reverse does not happen (passing `-pthread` does not alter the target triple) so as to not interfere with custom environments and/or custom multilib setups. Added: Modified: clang/lib/Driver/ToolChains/WebAssembly.cpp clang/test/Driver/wasm-toolchain.c Removed: diff --git a/clang/lib/Driver/ToolChains/WebAssembly.cpp b/clang/lib/Driver/ToolChains/WebAssembly.cpp index 93f17a03c580f..cd12f2ae5a6de 100644 --- a/clang/lib/Driver/ToolChains/WebAssembly.cpp +++ b/clang/lib/Driver/ToolChains/WebAssembly.cpp @@ -69,6 +69,18 @@ static bool TargetBuildsComponents(const llvm::Triple &TargetTriple) { TargetTriple.getOSName() != "wasi"; } +static bool WantsPthread(const llvm::Triple &Triple, const ArgList &Args) { + bool WantsPthread = + Args.hasFlag(options::OPT_pthread, options::OPT_no_pthread, false); + + // If the WASI environment is "threads" then enable pthreads support + // without requiring -pthread, in order to prevent user error + if (Triple.isOSWASI() && Triple.getEnvironmentName() == "threads") +WantsPthread = true; + + return WantsPthread; +} + void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA, const InputInfo &Output, const InputInfoList &Inputs, @@ -150,14 +162,14 @@ void wasm::Linker::ConstructJob(Compilation &C, const JobAction &JA, AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs, JA); - if (Args.hasArg(options::OPT_pthread)) + if (WantsPthread(ToolChain.getTriple(), Args)) CmdArgs.push_back("--shared-memory"); if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) { if (ToolChain.ShouldLinkCXXStdlib(Args)) ToolChain.AddCXXStdlibLibArgs(Args, CmdArgs); -if (Args.hasArg(options::OPT_pthread)) +if (WantsPthread(ToolChain.getTriple(), Args)) CmdArgs.push_back("-lpthread"); CmdArgs.push_back("-lc"); @@ -292,8 +304,7 @@ void WebAssembly::addClangTargetOptions(const ArgList &DriverArgs, CC1Args.push_back("-fno-use-init-array"); // '-pthread' implies atomics, bulk-memory, mutable-globals, and sign-ext - if (DriverArgs.hasFlag(options::OPT_pthread, options::OPT_no_pthread, - false)) { + if (WantsPthread(getTriple(), DriverArgs)) { if (DriverArgs.hasFlag(options::OPT_mno_atomics, options::OPT_matomics, false)) getDriver().Diag(diag::err_drv_argument_not_allowed_with) diff --git a/clang/test/Driver/wasm-toolchain.c b/clang/test/Driver/wasm-toolchain.c index 1ad219338ac28..91803fe6bc1f2 100644 --- a/clang/test/Driver/wasm-toolchain.c +++ b/clang/test/Driver/wasm-toolchain.c @@ -110,6 +110,12 @@ // RUN: | FileCheck -check-prefix=PTHREAD_NO_SIGN_EXT %s // PTHREAD_NO_SIGN_EXT: invalid argument '-pthread' not allowed with '-mno-sign-ext' +// 'wasm32-wasi-threads' does the same thing as '-pthread' +// RUN: %clang -### --target=wasm32-wasi-threads --sysroot=/foo %s 2>&1 \ +// RUN: | FileCheck -check-prefix=WASI_THREADS %s +// WASI_THREADS: "-cc1" {{.*}} "-target-feature" "+atomics" "-target-feature" "+bulk-memory" "-target-feature" "+mutable-globals" "-target-feature" "+sign-ext" +// WASI_THREADS: wasm-ld{{.*}}" "--shared-memory" "-lpthread" + // '-mllvm -emscripten-cxx-exceptions-allowed=foo,bar' sets // '-mllvm --force-attribute=foo:noinline -mllvm --force-attribute=bar:noinline' // RUN: %clang -### --target=wasm32-unknown-unknown \ ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [Clang] Treat constexpr-unknown value as invalid in `EvaluateAsInitializer` (PR #128409)
dtcxzyw wrote: > If I am reading the code correctly there should be some constexpr cases that > generate a diagnostic, can we verify that with a test? It has been tested by the following case: ``` extern int &Recurse1; int &Recurse2 = Recurse1; int &Recurse1 = Recurse2; constexpr int &Recurse3 = Recurse2; ``` Without diagnostic-related code in this patch, we will lose some notes on `Recurse2`. https://github.com/llvm/llvm-project/pull/128409 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Add a few things to the python api (PR #120590)
@@ -2022,6 +2025,14 @@ def lexical_parent(self): return self._lexical_parent +@property +def specialized_template(self): +"""Return the base template that this cursor is a specialization of, if any.""" Endilll wrote: I wonder if "base template" should be replaced with the Standard term "primary template". https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Add a few things to the python api (PR #120590)
https://github.com/Endilll commented: Even though this PR is rather small, it is still a bunch of changes here and there. I'd prefer it to be split up into multiple focused PRs. https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Add a few things to the python api (PR #120590)
https://github.com/Endilll edited https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [libclang/python] Add a few things to the python api (PR #120590)
DeinAlptraum wrote: Okay, thanks for the explanation & review :D I guess I might take this over if I have time then, which might be some time late in April (work is extremely busy) https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [cindex] Add API to query the class methods of a type (PR #123539)
https://github.com/trelau updated https://github.com/llvm/llvm-project/pull/123539 >From bb0542e8f2ad50892ee9d2c1f76ec1def85c3e56 Mon Sep 17 00:00:00 2001 From: Trevor Laughlin Date: Sun, 19 Jan 2025 19:21:10 -0500 Subject: [PATCH 1/4] [cindex] Add API to query the class methods of a type --- clang/bindings/python/clang/cindex.py | 16 +++ .../bindings/python/tests/cindex/test_type.py | 18 + clang/docs/ReleaseNotes.rst | 4 +++ clang/include/clang-c/Index.h | 23 clang/tools/libclang/CIndexCXX.cpp| 27 +++ clang/tools/libclang/libclang.map | 1 + 6 files changed, 89 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 806e1b40f3c9e..9e65ea2942d16 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -2710,6 +2710,21 @@ def visitor(base, children): conf.lib.clang_visitCXXBaseClasses(self, fields_visit_callback(visitor), bases) return iter(bases) +def get_methods(self): +"""Return an iterator for accessing the methods of this type.""" + +def visitor(method, children): +assert method != conf.lib.clang_getNullCursor() + +# Create reference to TU so it isn't GC'd before Cursor. +method._tu = self._tu +methods.append(method) +return 1 # continue + +methods: list[Cursor] = [] +conf.lib.clang_visitCXXMethods(self, fields_visit_callback(visitor), methods) +return iter(methods) + def get_exception_specification_kind(self): """ Return the kind of the exception specification; a value from @@ -4017,6 +4032,7 @@ def set_property(self, property, value): ), ("clang_visitChildren", [Cursor, cursor_visit_callback, py_object], c_uint), ("clang_visitCXXBaseClasses", [Type, fields_visit_callback, py_object], c_uint), +("clang_visitCXXMethods", [Type, fields_visit_callback, py_object], c_uint), ("clang_Cursor_getNumArguments", [Cursor], c_int), ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor), ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int), diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py index 9bac33f3041f4..bc893d509524e 100644 --- a/clang/bindings/python/tests/cindex/test_type.py +++ b/clang/bindings/python/tests/cindex/test_type.py @@ -559,3 +559,21 @@ class Template : public A, public B, virtual C { self.assertEqual(bases[1].get_base_offsetof(cursor_type_decl), 96) self.assertTrue(bases[2].is_virtual_base()) self.assertEqual(bases[2].get_base_offsetof(cursor_type_decl), 128) + +def test_class_methods(self): +source = """ +template +class Template { void Foo(); }; +typedef Template instance; +instance bar; +""" +tu = get_tu(source, lang="cpp", flags=["--target=x86_64-linux-gnu"]) +cursor = get_cursor(tu, "instance") +cursor_type = cursor.underlying_typedef_type +self.assertEqual(cursor.kind, CursorKind.TYPEDEF_DECL) +methods = list(cursor_type.get_methods()) +self.assertEqual(len(methods), 4) +self.assertEqual(methods[0].kind, CursorKind.CXX_METHOD) +self.assertEqual(methods[1].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[2].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[3].kind, CursorKind.CONSTRUCTOR) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b02ac467cd3a2..dd9f722a6a08c 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -1241,6 +1241,8 @@ libclang of a class. - Added ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``clang_visitCXXMethods``, which allows visiting the methods + of a class. Static Analyzer --- @@ -1394,6 +1396,8 @@ Python Binding Changes allows visiting the base classes of a class. - Added ``Cursor.get_base_offsetof``, a binding for ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which + allows visiting the methods of a class. OpenMP Support -- diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h index aac5d1fa8aa2e..5d961ca0cdd7f 100644 --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -6680,6 +6680,29 @@ CINDEX_LINKAGE unsigned clang_visitCXXBaseClasses(CXType T, CXFieldVisitor visitor, CXClientData client_data); +/** + * Visit the class methods of a type. + * + * This function visits all the methods of t
[clang] [llvm] [RISCV] Xqccmp Code Generation (PR #128815)
@@ -974,17 +974,20 @@ void RISCVFrameLowering::emitPrologue(MachineFunction &MF, emitCFIForCSI(MBB, MBBI, getUnmanagedCSI(MF, CSI)); // Generate new FP. - if (hasFP(MF) && RVFI->getPushPopKind(MF) != - RISCVMachineFunctionInfo::PushPopKind::VendorXqccmp) { + if (hasFP(MF)) { if (STI.isRegisterReservedByUser(FPReg)) MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{ MF.getFunction(), "Frame pointer required, but has been reserved."}); // The frame pointer does need to be reserved from register allocation. assert(MF.getRegInfo().isReserved(FPReg) && "FP not reserved"); -RI->adjustReg(MBB, MBBI, DL, FPReg, SPReg, - StackOffset::getFixed(RealStackSize - RVFI->getVarArgsSaveSize()), - MachineInstr::FrameSetup, getStackAlign()); +// Xqxxmp with hasFP will update FP using `qc.cm.pushfp`, so we don't need lenary wrote: Thanks, sorted. https://github.com/llvm/llvm-project/pull/128815 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [cindex] Add API to query the class methods of a type (PR #123539)
https://github.com/trelau updated https://github.com/llvm/llvm-project/pull/123539 >From bb0542e8f2ad50892ee9d2c1f76ec1def85c3e56 Mon Sep 17 00:00:00 2001 From: Trevor Laughlin Date: Sun, 19 Jan 2025 19:21:10 -0500 Subject: [PATCH 1/5] [cindex] Add API to query the class methods of a type --- clang/bindings/python/clang/cindex.py | 16 +++ .../bindings/python/tests/cindex/test_type.py | 18 + clang/docs/ReleaseNotes.rst | 4 +++ clang/include/clang-c/Index.h | 23 clang/tools/libclang/CIndexCXX.cpp| 27 +++ clang/tools/libclang/libclang.map | 1 + 6 files changed, 89 insertions(+) diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 806e1b40f3c9e..9e65ea2942d16 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -2710,6 +2710,21 @@ def visitor(base, children): conf.lib.clang_visitCXXBaseClasses(self, fields_visit_callback(visitor), bases) return iter(bases) +def get_methods(self): +"""Return an iterator for accessing the methods of this type.""" + +def visitor(method, children): +assert method != conf.lib.clang_getNullCursor() + +# Create reference to TU so it isn't GC'd before Cursor. +method._tu = self._tu +methods.append(method) +return 1 # continue + +methods: list[Cursor] = [] +conf.lib.clang_visitCXXMethods(self, fields_visit_callback(visitor), methods) +return iter(methods) + def get_exception_specification_kind(self): """ Return the kind of the exception specification; a value from @@ -4017,6 +4032,7 @@ def set_property(self, property, value): ), ("clang_visitChildren", [Cursor, cursor_visit_callback, py_object], c_uint), ("clang_visitCXXBaseClasses", [Type, fields_visit_callback, py_object], c_uint), +("clang_visitCXXMethods", [Type, fields_visit_callback, py_object], c_uint), ("clang_Cursor_getNumArguments", [Cursor], c_int), ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor), ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int), diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py index 9bac33f3041f4..bc893d509524e 100644 --- a/clang/bindings/python/tests/cindex/test_type.py +++ b/clang/bindings/python/tests/cindex/test_type.py @@ -559,3 +559,21 @@ class Template : public A, public B, virtual C { self.assertEqual(bases[1].get_base_offsetof(cursor_type_decl), 96) self.assertTrue(bases[2].is_virtual_base()) self.assertEqual(bases[2].get_base_offsetof(cursor_type_decl), 128) + +def test_class_methods(self): +source = """ +template +class Template { void Foo(); }; +typedef Template instance; +instance bar; +""" +tu = get_tu(source, lang="cpp", flags=["--target=x86_64-linux-gnu"]) +cursor = get_cursor(tu, "instance") +cursor_type = cursor.underlying_typedef_type +self.assertEqual(cursor.kind, CursorKind.TYPEDEF_DECL) +methods = list(cursor_type.get_methods()) +self.assertEqual(len(methods), 4) +self.assertEqual(methods[0].kind, CursorKind.CXX_METHOD) +self.assertEqual(methods[1].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[2].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[3].kind, CursorKind.CONSTRUCTOR) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index b02ac467cd3a2..dd9f722a6a08c 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -1241,6 +1241,8 @@ libclang of a class. - Added ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``clang_visitCXXMethods``, which allows visiting the methods + of a class. Static Analyzer --- @@ -1394,6 +1396,8 @@ Python Binding Changes allows visiting the base classes of a class. - Added ``Cursor.get_base_offsetof``, a binding for ``clang_getOffsetOfBase``, which allows computing the offset of a base class in a class's layout. +- Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which + allows visiting the methods of a class. OpenMP Support -- diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h index aac5d1fa8aa2e..5d961ca0cdd7f 100644 --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -6680,6 +6680,29 @@ CINDEX_LINKAGE unsigned clang_visitCXXBaseClasses(CXType T, CXFieldVisitor visitor, CXClientData client_data); +/** + * Visit the class methods of a type. + * + * This function visits all the methods of t
[clang] [clang-tidy] warn when `true` is used as a preprocessor keyword in C (PR #128265)
@@ -0,0 +1,38 @@ +//===--- TrueMacroCheck.h - clang-tidy --*- C++ -*-===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_TRUEMACROCHECK_H +#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_BUGPRONE_TRUEMACROCHECK_H + +#include "../ClangTidyCheck.h" + +namespace clang::tidy::bugprone { + +/// In C++, `true` is considered a keyword by the preprocessor so an `#if +/// true` enters the true branch, while in C, `true` is not treated as a +/// special keyword by the preprocessor, so the false branch is entered. +/// +/// The check identifies such cases, when `true` is used without being +/// defined first and also offers fix-its in some cases. +/// +/// For the user-facing documentation see: +/// http://clang.llvm.org/extra/clang-tidy/checks/bugprone/true-macro.html +class TrueMacroCheck : public ClangTidyCheck { +public: + TrueMacroCheck(StringRef Name, ClangTidyContext *Context) + : ClangTidyCheck(Name, Context) {} + void registerPPCallbacks(const SourceManager &SM, Preprocessor *PP, + Preprocessor *ModuleExpanderPP) override; + bool isLanguageVersionSupported(const LangOptions &LangOpts) const override { +return LangOpts.C99 || LangOpts.C11 || LangOpts.C17; isuckatcs wrote: It is tested in the new clang diagnostic test. https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]: `misc-unused-using-decls`: add correct handling of `operator""` with template parametes (PR #129392)
llvmbot wrote: @llvm/pr-subscribers-clang-tidy Author: Baranov Victor (vbvictor) Changes Fixes false-positives when operator"" has template paremetes, e.g. ```cpp templateint operator""_r() { return {}; } ``` --- Full diff: https://github.com/llvm/llvm-project/pull/129392.diff 3 Files Affected: - (modified) clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp (+10-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp (+16) ``diff diff --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp index 5d74907aa9fab..0b501b9c9d6a3 100644 --- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp @@ -184,8 +184,16 @@ void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) { return; } // Check user-defined literals - if (const auto *UDL = Result.Nodes.getNodeAs("used")) -removeFromFoundDecls(UDL->getCalleeDecl()); + if (const auto *UDL = Result.Nodes.getNodeAs("used")) { +const Decl *CalleeDecl = UDL->getCalleeDecl(); +if (const auto *FD = dyn_cast(UDL->getCalleeDecl())) { + if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) { +removeFromFoundDecls(FPT); +return; + } +} +removeFromFoundDecls(CalleeDecl); + } } void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) { diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..ccdb741ef5879 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`misc-unused-using-decls + ` check by fixing false positives + on ``operator""`` with template parameters. + Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp index 12fc18f340f21..62aa17b0b1c22 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp @@ -222,3 +222,19 @@ using gh69714::StructGH69714_1; using gh69714::StructGH69714_2; struct StructGH69714_1 a; struct StructGH69714_2 *b; + +namespace gh53444 { +namespace my_literals { + template + int operator""_r() { +return {}; + } +} + +using my_literals::operator"" _r; + +int foo() { + auto x2 = 123_r; +} + +} `` https://github.com/llvm/llvm-project/pull/129392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]: `misc-unused-using-decls`: add correct handling of `operator""` with template parametes (PR #129392)
https://github.com/vbvictor created https://github.com/llvm/llvm-project/pull/129392 Fixes false-positives when operator"" has template paremetes, e.g. ```cpp template int operator""_r() { return {}; } ``` >From eac5105574e6144eb702e75b21d00203706c6ada Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Sat, 1 Mar 2025 19:38:43 +0300 Subject: [PATCH] add correct handling of template operator"" --- .../clang-tidy/misc/UnusedUsingDeclsCheck.cpp| 12 ++-- clang-tools-extra/docs/ReleaseNotes.rst | 4 .../checkers/misc/unused-using-decls.cpp | 16 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp index 5d74907aa9fab..0b501b9c9d6a3 100644 --- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp @@ -184,8 +184,16 @@ void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) { return; } // Check user-defined literals - if (const auto *UDL = Result.Nodes.getNodeAs("used")) -removeFromFoundDecls(UDL->getCalleeDecl()); + if (const auto *UDL = Result.Nodes.getNodeAs("used")) { +const Decl *CalleeDecl = UDL->getCalleeDecl(); +if (const auto *FD = dyn_cast(UDL->getCalleeDecl())) { + if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) { +removeFromFoundDecls(FPT); +return; + } +} +removeFromFoundDecls(CalleeDecl); + } } void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) { diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..ccdb741ef5879 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`misc-unused-using-decls + ` check by fixing false positives + on ``operator""`` with template parameters. + Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp index 12fc18f340f21..62aa17b0b1c22 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp @@ -222,3 +222,19 @@ using gh69714::StructGH69714_1; using gh69714::StructGH69714_2; struct StructGH69714_1 a; struct StructGH69714_2 *b; + +namespace gh53444 { +namespace my_literals { + template + int operator""_r() { +return {}; + } +} + +using my_literals::operator"" _r; + +int foo() { + auto x2 = 123_r; +} + +} ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] `misc-unused-using-decls`: add correct handling of `operator""` with template parametes (PR #129392)
https://github.com/vbvictor edited https://github.com/llvm/llvm-project/pull/129392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]: `misc-unused-using-decls`: add correct handling of `operator""` with template parametes (PR #129392)
https://github.com/vbvictor edited https://github.com/llvm/llvm-project/pull/129392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [cindex] Add API to query the class methods of a type (PR #123539)
trelau wrote: @DeinAlptraum ok now i think it's ready https://github.com/llvm/llvm-project/pull/123539 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]improve performance-unnecessary-value-param performance (PR #128383)
@@ -110,6 +110,11 @@ Changes in existing checks ` check by providing additional examples and fixing some macro related false positives. +- Improved :doc:`performance/unnecessary-value-param vbvictor wrote: nit: `performance/unnecessary-value-param` should be `performance-unnecessary-value-param`, may be fixed later before 21 release https://github.com/llvm/llvm-project/pull/128383 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy]: `misc-unused-using-decls`: add correct handling of `operator""` with template parametes (PR #129392)
llvmbot wrote: @llvm/pr-subscribers-clang-tools-extra Author: Baranov Victor (vbvictor) Changes Fixes false-positives when operator"" has template paremetes, e.g. ```cpp templateint operator""_r() { return {}; } ``` --- Full diff: https://github.com/llvm/llvm-project/pull/129392.diff 3 Files Affected: - (modified) clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp (+10-2) - (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) - (modified) clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp (+16) ``diff diff --git a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp index 5d74907aa9fab..0b501b9c9d6a3 100644 --- a/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp +++ b/clang-tools-extra/clang-tidy/misc/UnusedUsingDeclsCheck.cpp @@ -184,8 +184,16 @@ void UnusedUsingDeclsCheck::check(const MatchFinder::MatchResult &Result) { return; } // Check user-defined literals - if (const auto *UDL = Result.Nodes.getNodeAs("used")) -removeFromFoundDecls(UDL->getCalleeDecl()); + if (const auto *UDL = Result.Nodes.getNodeAs("used")) { +const Decl *CalleeDecl = UDL->getCalleeDecl(); +if (const auto *FD = dyn_cast(UDL->getCalleeDecl())) { + if (const FunctionTemplateDecl *FPT = FD->getPrimaryTemplate()) { +removeFromFoundDecls(FPT); +return; + } +} +removeFromFoundDecls(CalleeDecl); + } } void UnusedUsingDeclsCheck::removeFromFoundDecls(const Decl *D) { diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..ccdb741ef5879 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`misc-unused-using-decls + ` check by fixing false positives + on ``operator""`` with template parameters. + Removed checks ^^ diff --git a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp index 12fc18f340f21..62aa17b0b1c22 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/misc/unused-using-decls.cpp @@ -222,3 +222,19 @@ using gh69714::StructGH69714_1; using gh69714::StructGH69714_2; struct StructGH69714_1 a; struct StructGH69714_2 *b; + +namespace gh53444 { +namespace my_literals { + template + int operator""_r() { +return {}; + } +} + +using my_literals::operator"" _r; + +int foo() { + auto x2 = 123_r; +} + +} `` https://github.com/llvm/llvm-project/pull/129392 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [cindex] Add API to query the class methods of a type (PR #123539)
DeinAlptraum wrote: Is this ready to be merged? @trelau https://github.com/llvm/llvm-project/pull/123539 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave updated https://github.com/llvm/llvm-project/pull/129370 >From 6dff411516cb4c0e807307fd36d15955e805d5c4 Mon Sep 17 00:00:00 2001 From: David Rivera Date: Sat, 1 Mar 2025 02:09:02 -0500 Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init --- .../modernize/UseDefaultMemberInitCheck.cpp | 23 ++-- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/use-default-member-init.cpp | 26 +++ 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 6c06b0af342f6..d01f440fe7e16 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) { case Stmt::UnaryOperatorClass: return sameValue(cast(E1)->getSubExpr(), cast(E2)->getSubExpr()); + case Stmt::BinaryOperatorClass: { +const auto *BinOp1 = cast(E1); +const auto *BinOp2 = cast(E2); +return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == cast(E2)->getValue(); @@ -194,15 +200,16 @@ void UseDefaultMemberInitCheck::storeOptions( } void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { + auto NumericLiteral = anyOf(integerLiteral(), floatLiteral()); + auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(NumericLiteral)); + auto EnumRef = declRefExpr(to(enumConstantDecl())); + auto InitBase = - anyOf(stringLiteral(), characterLiteral(), integerLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(integerLiteral())), -floatLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(floatLiteral())), -cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; + anyOf(stringLiteral(), characterLiteral(), NumericLiteral, UnaryNumericLiteral, +cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), EnumRef, +binaryOperator(hasLHS(anyOf(NumericLiteral, EnumRef, binaryOperator())), + hasRHS(anyOf(NumericLiteral, EnumRef, binaryOperator(); + auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..01892f4cde648 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -128,6 +128,10 @@ Changes in existing checks ` check by providing additional examples and fixing some macro related false positives. +- Improved :doc:`modernize-use-default-member-init + ` check by matching arithmetic + operations within member list initialization. + - Improved :doc:`performance/unnecessary-value-param ` check performance by tolerating fix-it breaking compilation when functions is used as pointers diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp index 81c980e0217e6..ff8c80b682bdb 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp @@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues { }; } // namespace PR63285 + +namespace PR122480 { + +#define ARITHMETIC_MACRO (44 - 2) + +class DefaultMemberInitWithArithmetic { + DefaultMemberInitWithArithmetic() : a{1 + 1}, b{1 + 11 + 123 + 1234}, c{2 + (4 / 2) + 3 + (7 / 11)}, d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {} + // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is redundant [modernize-use-default-member-init] + // CHECK-FIXES: DefaultMemberInitWithArithmetic() {} + + int a{1 + 1}; + int b; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'b' [modernize-use-default-member-init] + // CHECK-FIXES: int b{1 + 11 + 123 + 1234}; + int c; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'c' [modernize-use-default-member-init] + // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)} + int d; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'd' [modernize-use-default-member-init] + // CHECK-FIXES: int d{ARITHMETIC_MACRO * 2}; + double e; + // CHECK-MESSAG
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
@@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`modernize-use-default-member-init RiverDave wrote: Thx for pointing out, It's fixed now. https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave updated https://github.com/llvm/llvm-project/pull/129370 >From be9f035f738c8ea2771c9e79d4c22ff0fa82542e Mon Sep 17 00:00:00 2001 From: David Rivera Date: Sat, 1 Mar 2025 02:09:02 -0500 Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init --- .../modernize/UseDefaultMemberInitCheck.cpp | 26 --- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/use-default-member-init.cpp | 26 +++ 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 6c06b0af342f6..639b594abaf30 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) { case Stmt::UnaryOperatorClass: return sameValue(cast(E1)->getSubExpr(), cast(E2)->getSubExpr()); + case Stmt::BinaryOperatorClass: { +const auto *BinOp1 = cast(E1); +const auto *BinOp2 = cast(E2); +return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == cast(E2)->getValue(); @@ -194,15 +200,17 @@ void UseDefaultMemberInitCheck::storeOptions( } void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { - auto InitBase = - anyOf(stringLiteral(), characterLiteral(), integerLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(integerLiteral())), -floatLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(floatLiteral())), -cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; + auto NumericLiteral = anyOf(integerLiteral(), floatLiteral()); + auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(NumericLiteral)); + auto EnumRef = declRefExpr(to(enumConstantDecl())); + + auto InitBase = anyOf( + stringLiteral(), characterLiteral(), NumericLiteral, UnaryNumericLiteral, + cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), + EnumRef, + binaryOperator(hasLHS(anyOf(NumericLiteral, EnumRef, binaryOperator())), + hasRHS(anyOf(NumericLiteral, EnumRef, binaryOperator(); + auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..01892f4cde648 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -128,6 +128,10 @@ Changes in existing checks ` check by providing additional examples and fixing some macro related false positives. +- Improved :doc:`modernize-use-default-member-init + ` check by matching arithmetic + operations within member list initialization. + - Improved :doc:`performance/unnecessary-value-param ` check performance by tolerating fix-it breaking compilation when functions is used as pointers diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp index 81c980e0217e6..ff8c80b682bdb 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp @@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues { }; } // namespace PR63285 + +namespace PR122480 { + +#define ARITHMETIC_MACRO (44 - 2) + +class DefaultMemberInitWithArithmetic { + DefaultMemberInitWithArithmetic() : a{1 + 1}, b{1 + 11 + 123 + 1234}, c{2 + (4 / 2) + 3 + (7 / 11)}, d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {} + // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is redundant [modernize-use-default-member-init] + // CHECK-FIXES: DefaultMemberInitWithArithmetic() {} + + int a{1 + 1}; + int b; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'b' [modernize-use-default-member-init] + // CHECK-FIXES: int b{1 + 11 + 123 + 1234}; + int c; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'c' [modernize-use-default-member-init] + // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)} + int d; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'd' [modernize-use-default-member-init] + // CHECK-FIXES: int d{ARITHMETIC_MACRO * 2}; + double e; + // CHE
[clang] [libclang/python] Add a few things to the python api (PR #120590)
Endilll wrote: > @Endilll since there hasn't been a reply in months, do you think it's > appropriate to close this? Our existing practice is that PRs remain to linger like this until someone picks them up. Closing it would be "we don't want this" answer, and it wouldn't be correct. That's how we end up with ever-growing number of opened PRs, yeah. https://github.com/llvm/llvm-project/pull/120590 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [libclang/python] Enable packaging libclang bindings (PR #125806)
Endilll wrote: > @Endilll @LecrisUT what else do you think needs to be done here to get this > approved? I still would like to hear from @sighingnow. One of the reasons is that I think I've seen them attending one of the open meetings we have, so they might be around somewhere. Also I barely know anything about how to package this stuff correctly, and what the consequences would be if we get it wrong. https://github.com/llvm/llvm-project/pull/125806 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] add new check: modernize-use-scoped-lock (PR #126434)
https://github.com/vbvictor updated https://github.com/llvm/llvm-project/pull/126434 >From 2c2738704e5fd2e402b75021341a47413e6bfe39 Mon Sep 17 00:00:00 2001 From: Victor Baranov Date: Sat, 1 Mar 2025 18:11:30 +0300 Subject: [PATCH] add scoped-lock-check --- .../clang-tidy/modernize/CMakeLists.txt | 1 + .../modernize/ModernizeTidyModule.cpp | 3 + .../modernize/UseScopedLockCheck.cpp | 319 ++ .../clang-tidy/modernize/UseScopedLockCheck.h | 54 +++ clang-tools-extra/docs/ReleaseNotes.rst | 6 + .../docs/clang-tidy/checks/list.rst | 1 + .../checks/modernize/use-scoped-lock.rst | 102 + ...e-lock-warn-on-using-and-typedef-false.cpp | 57 +++ ...scoped-lock-warn-on-single-locks-false.cpp | 123 ++ .../checkers/modernize/use-scoped-lock.cpp| 399 ++ 10 files changed, 1065 insertions(+) create mode 100644 clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp create mode 100644 clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.h create mode 100644 clang-tools-extra/docs/clang-tidy/checks/modernize/use-scoped-lock.rst create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-scope-lock-warn-on-using-and-typedef-false.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock-warn-on-single-locks-false.cpp create mode 100644 clang-tools-extra/test/clang-tidy/checkers/modernize/use-scoped-lock.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt index bab1167fb15ff..619a27b2f9bb6 100644 --- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt +++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt @@ -42,6 +42,7 @@ add_clang_library(clangTidyModernizeModule STATIC UseNullptrCheck.cpp UseOverrideCheck.cpp UseRangesCheck.cpp + UseScopedLockCheck.cpp UseStartsEndsWithCheck.cpp UseStdFormatCheck.cpp UseStdNumbersCheck.cpp diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp index fc46c72982fdc..b2d4ddd667502 100644 --- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp +++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp @@ -43,6 +43,7 @@ #include "UseNullptrCheck.h" #include "UseOverrideCheck.h" #include "UseRangesCheck.h" +#include "UseScopedLockCheck.h" #include "UseStartsEndsWithCheck.h" #include "UseStdFormatCheck.h" #include "UseStdNumbersCheck.h" @@ -80,6 +81,8 @@ class ModernizeModule : public ClangTidyModule { CheckFactories.registerCheck( "modernize-use-integer-sign-comparison"); CheckFactories.registerCheck("modernize-use-ranges"); +CheckFactories.registerCheck( +"modernize-use-scoped-lock"); CheckFactories.registerCheck( "modernize-use-starts-ends-with"); CheckFactories.registerCheck("modernize-use-std-format"); diff --git a/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp new file mode 100644 index 0..5dbb3a2f671e6 --- /dev/null +++ b/clang-tools-extra/clang-tidy/modernize/UseScopedLockCheck.cpp @@ -0,0 +1,319 @@ +//===--- UseScopedLockCheck.cpp - clang-tidy --===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===--===// + +#include "UseScopedLockCheck.h" +#include "clang/AST/ASTContext.h" +#include "clang/AST/Decl.h" +#include "clang/AST/Stmt.h" +#include "clang/AST/Type.h" +#include "clang/ASTMatchers/ASTMatchFinder.h" +#include "clang/ASTMatchers/ASTMatchers.h" +#include "clang/Basic/SourceLocation.h" +#include "clang/Lex/Lexer.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/Twine.h" +#include + +using namespace clang::ast_matchers; + +namespace clang::tidy::modernize { + +namespace { + +bool isLockGuard(const QualType &Type) { + if (const auto *Record = Type->getAs()) { +if (const RecordDecl *Decl = Record->getDecl()) { + return Decl->getName() == "lock_guard" && Decl->isInStdNamespace(); +} + } + + if (const auto *TemplateSpecType = + Type->getAs()) { +if (const TemplateDecl *Decl = +TemplateSpecType->getTemplateName().getAsTemplateDecl()) { + return Decl->getName() == "lock_guard" && Decl->isInStdNamespace(); +} + } + + return false; +} + +llvm::SmallVector getLockGuardsFromDecl(const DeclStmt *DS) { + llvm::SmallVector LockGuards; + + for (const Decl *Decl : DS->decls()) { +if (const auto *VD = dyn_cast(Decl)) { + const QualType Type = VD->getType().getCanonicalType(); + if (isLockGuard(Type)) { +LockGuards.push_ba
[clang] [clang] more useful error message for decomposition declaration missing initializer (PR #127924)
@@ -140,18 +140,23 @@ namespace Template { template auto [a, b, c] = n; // expected-error {{decomposition declaration template not supported}} } +#define MYC C + namespace Init { - void f() { + template T f(T t) { int arr[1]; struct S { int n; }; -auto &[bad1]; // expected-error {{decomposition declaration '[bad1]' requires an initializer}} +auto &[bad1]; // expected-error {{decomposition declaration '[bad1]' requires an initializer}} expected-error {{expected initializer before ';'}} zyn0217 wrote: They look duplicate and are not great https://github.com/llvm/llvm-project/pull/127924 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
@@ -137,6 +137,10 @@ Changes in existing checks ` check by fixing false negatives on ternary operators calling ``std::move``. +- Improved :doc:`modernize-use-default-member-init EugeneZelenko wrote: Please keep alphabetical order (by check name) in this list. https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
@@ -202,7 +208,13 @@ void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { unaryOperator(hasAnyOperatorName("+", "-"), hasUnaryOperand(floatLiteral())), cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; +declRefExpr(to(enumConstantDecl())), +binaryOperator(hasLHS(anyOf(integerLiteral(), floatLiteral(), RiverDave wrote: I've improved it a bit, not only my changes but the rest as well as I think is way more readable now, there's still some duplicate code like: ```cpp binaryOperator(hasLHS(anyOf(NumericLiteral, EnumRef, binaryOperator())), hasRHS(anyOf(NumericLiteral, EnumRef, binaryOperator(); ``` But I still didn't wanted to change it as I think It's better for readability. let me know if this is the right call. https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave edited https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave updated https://github.com/llvm/llvm-project/pull/129370 >From b46375a39104f967bdb3b6a9bd3214545a5965cf Mon Sep 17 00:00:00 2001 From: David Rivera Date: Sat, 1 Mar 2025 02:09:02 -0500 Subject: [PATCH] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init --- .../modernize/UseDefaultMemberInitCheck.cpp | 26 --- clang-tools-extra/docs/ReleaseNotes.rst | 4 +++ .../modernize/use-default-member-init.cpp | 26 +++ 3 files changed, 47 insertions(+), 9 deletions(-) diff --git a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp index 6c06b0af342f6..16f04b5f555e1 100644 --- a/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp +++ b/clang-tools-extra/clang-tidy/modernize/UseDefaultMemberInitCheck.cpp @@ -159,6 +159,12 @@ static bool sameValue(const Expr *E1, const Expr *E2) { case Stmt::UnaryOperatorClass: return sameValue(cast(E1)->getSubExpr(), cast(E2)->getSubExpr()); + case Stmt::BinaryOperatorClass: { +const auto *BinOp1 = cast(E1); +const auto *BinOp2 = cast(E2); +return sameValue(BinOp1->getLHS(), BinOp2->getLHS()) && + sameValue(BinOp1->getRHS(), BinOp2->getRHS()); + } case Stmt::CharacterLiteralClass: return cast(E1)->getValue() == cast(E2)->getValue(); @@ -194,15 +200,17 @@ void UseDefaultMemberInitCheck::storeOptions( } void UseDefaultMemberInitCheck::registerMatchers(MatchFinder *Finder) { - auto InitBase = - anyOf(stringLiteral(), characterLiteral(), integerLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(integerLiteral())), -floatLiteral(), -unaryOperator(hasAnyOperatorName("+", "-"), - hasUnaryOperand(floatLiteral())), -cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), -declRefExpr(to(enumConstantDecl(; + auto NumericLiteral = anyOf(integerLiteral(), floatLiteral()); + auto UnaryNumericLiteral = unaryOperator(hasAnyOperatorName("+", "-"), + hasUnaryOperand(NumericLiteral)); + auto EnumRef = declRefExpr(to(enumConstantDecl())); + + auto InitBase = anyOf( + stringLiteral(), characterLiteral(), NumericLiteral, UnaryNumericLiteral, + cxxBoolLiteral(), cxxNullPtrLiteralExpr(), implicitValueInitExpr(), + EnumRef, + binaryOperator(hasLHS(anyOf(NumericLiteral, EnumRef, binaryOperator())), + hasRHS(anyOf(NumericLiteral, EnumRef, binaryOperator(); auto Init = anyOf(initListExpr(anyOf(allOf(initCountIs(1), hasInit(0, InitBase)), diff --git a/clang-tools-extra/docs/ReleaseNotes.rst b/clang-tools-extra/docs/ReleaseNotes.rst index 07a79d6bbe807..01892f4cde648 100644 --- a/clang-tools-extra/docs/ReleaseNotes.rst +++ b/clang-tools-extra/docs/ReleaseNotes.rst @@ -128,6 +128,10 @@ Changes in existing checks ` check by providing additional examples and fixing some macro related false positives. +- Improved :doc:`modernize-use-default-member-init + ` check by matching arithmetic + operations within member list initialization. + - Improved :doc:`performance/unnecessary-value-param ` check performance by tolerating fix-it breaking compilation when functions is used as pointers diff --git a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp index 81c980e0217e6..ff8c80b682bdb 100644 --- a/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp +++ b/clang-tools-extra/test/clang-tidy/checkers/modernize/use-default-member-init.cpp @@ -518,3 +518,29 @@ class ArrayBraceInitMultipleValues { }; } // namespace PR63285 + +namespace PR122480 { + +#define ARITHMETIC_MACRO (44 - 2) + +class DefaultMemberInitWithArithmetic { + DefaultMemberInitWithArithmetic() : a{1 + 1}, b{1 + 11 + 123 + 1234}, c{2 + (4 / 2) + 3 + (7 / 11)}, d{ARITHMETIC_MACRO * 2}, e{1.2 + 3.4} {} + // CHECK-MESSAGES: :[[@LINE-1]]:39: warning: member initializer for 'a' is redundant [modernize-use-default-member-init] + // CHECK-FIXES: DefaultMemberInitWithArithmetic() {} + + int a{1 + 1}; + int b; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'b' [modernize-use-default-member-init] + // CHECK-FIXES: int b{1 + 11 + 123 + 1234}; + int c; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'c' [modernize-use-default-member-init] + // CHECK-FIXES: int c{2 + (4 / 2) + 3 + (7 / 11)} + int d; + // CHECK-MESSAGES: :[[@LINE-1]]:7: warning: use default member initializer for 'd' [modernize-use-default-member-init] + // CHECK-FIXES: int d{ARIT
[clang-tools-extra] [clang-tidy] detect arithmetic operations within member list initialization in modernize-use-default-member-init check (PR #129370)
https://github.com/RiverDave edited https://github.com/llvm/llvm-project/pull/129370 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [HLSL][RootSignature] Implement Parsing of Descriptor Tables (PR #122982)
@@ -0,0 +1,417 @@ +#include "clang/Parse/ParseHLSLRootSignature.h" llvm-beanz wrote: This is the file with the missing license header that @bob80905 pointed out. https://github.com/llvm/llvm-project/pull/122982 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [llvm] [HLSL][RootSignature] Implement Parsing of Descriptor Tables (PR #122982)
@@ -0,0 +1,375 @@ +//=== ParseHLSLRootSignatureTest.cpp - Parse Root Signature tests -===// +// +// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. +// See https://llvm.org/LICENSE.txt for license information. llvm-beanz wrote: Every new file should get the license header. https://github.com/llvm/llvm-project/pull/122982 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)
https://github.com/llvm-beanz created https://github.com/llvm/llvm-project/pull/129396 This PR adds scalar/vector overloads for vector conditions to the `select` builtin, and updates the sema checking and codegen to allow scalars to extend to vectors. Fixes #126570 >From 999c9253dc69c43f2d5d686bb4e9a9fd2f8783d4 Mon Sep 17 00:00:00 2001 From: Chris Bieneman Date: Wed, 19 Feb 2025 17:18:20 -0600 Subject: [PATCH] [HLSL] select scalar overloads for vector conditions This PR adds scalar/vector overloads for vector conditions to the `select` builtin, and updates the sema checking and codegen to allow scalars to extend to vectors. Fixes #126570 --- .../clang/Basic/DiagnosticSemaKinds.td| 3 + clang/lib/CodeGen/CGBuiltin.cpp | 8 ++ clang/lib/Headers/hlsl/hlsl_detail.h | 5 + clang/lib/Headers/hlsl/hlsl_intrinsics.h | 36 +++ clang/lib/Sema/SemaHLSL.cpp | 56 ++- clang/test/CodeGenHLSL/builtins/select.hlsl | 29 ++ .../test/SemaHLSL/BuiltIns/select-errors.hlsl | 98 +-- 7 files changed, 135 insertions(+), 100 deletions(-) diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d094c075ecee2..be649f0bce320 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -12682,6 +12682,9 @@ def err_hlsl_param_qualifier_mismatch : def err_hlsl_vector_compound_assignment_truncation : Error< "left hand operand of type %0 to compound assignment cannot be truncated " "when used with right hand operand of type %1">; +def err_hlsl_builtin_scalar_vector_mismatch : Error< + "%select{all|second and third}0 arguments to %1 must be of scalar or " + "vector type with matching scalar element type%diff{: $ vs $|}2,3">; def warn_hlsl_impcast_vector_truncation : Warning< "implicit conversion truncates vector: %0 to %1">, InGroup; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 03b8d16b76e0d..a84e5e4b59c89 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -19741,6 +19741,14 @@ case Builtin::BI__builtin_hlsl_elementwise_isinf: { RValFalse.isScalar() ? RValFalse.getScalarVal() : RValFalse.getAggregatePointer(E->getArg(2)->getType(), *this); +if (auto *VTy = E->getType()->getAs()) { + if (!OpTrue->getType()->isVectorTy()) +OpTrue = +Builder.CreateVectorSplat(VTy->getNumElements(), OpTrue, "splat"); + if (!OpFalse->getType()->isVectorTy()) +OpFalse = +Builder.CreateVectorSplat(VTy->getNumElements(), OpFalse, "splat"); +} Value *SelectVal = Builder.CreateSelect(OpCond, OpTrue, OpFalse, "hlsl.select"); diff --git a/clang/lib/Headers/hlsl/hlsl_detail.h b/clang/lib/Headers/hlsl/hlsl_detail.h index 0d568539cd66a..daccd2d793aa8 100644 --- a/clang/lib/Headers/hlsl/hlsl_detail.h +++ b/clang/lib/Headers/hlsl/hlsl_detail.h @@ -95,6 +95,11 @@ constexpr vector reflect_vec_impl(vector I, vector N) { #endif } +template +struct is_arithmetic { + static const bool Value = __is_arithmetic(T); +}; + } // namespace __detail } // namespace hlsl #endif //_HLSL_HLSL_DETAILS_H_ diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index ed008eeb04ba8..77a7f773b85b2 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -2246,6 +2246,42 @@ template _HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) vector select(vector, vector, vector); + +/// \fn vector select(vector Conds, T TrueVal, +/// vector FalseVals) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVals The vector values are chosen from when conditions are +/// false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, T, vector); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVals The vector values are chosen from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, vector, T); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_
[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)
llvmbot wrote: @llvm/pr-subscribers-clang Author: Chris B (llvm-beanz) Changes This PR adds scalar/vector overloads for vector conditions to the `select` builtin, and updates the sema checking and codegen to allow scalars to extend to vectors. Fixes #126570 --- Full diff: https://github.com/llvm/llvm-project/pull/129396.diff 7 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) - (modified) clang/lib/CodeGen/CGBuiltin.cpp (+8) - (modified) clang/lib/Headers/hlsl/hlsl_detail.h (+5) - (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (+36) - (modified) clang/lib/Sema/SemaHLSL.cpp (+32-24) - (modified) clang/test/CodeGenHLSL/builtins/select.hlsl (+29) - (modified) clang/test/SemaHLSL/BuiltIns/select-errors.hlsl (+22-76) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d094c075ecee2..be649f0bce320 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -12682,6 +12682,9 @@ def err_hlsl_param_qualifier_mismatch : def err_hlsl_vector_compound_assignment_truncation : Error< "left hand operand of type %0 to compound assignment cannot be truncated " "when used with right hand operand of type %1">; +def err_hlsl_builtin_scalar_vector_mismatch : Error< + "%select{all|second and third}0 arguments to %1 must be of scalar or " + "vector type with matching scalar element type%diff{: $ vs $|}2,3">; def warn_hlsl_impcast_vector_truncation : Warning< "implicit conversion truncates vector: %0 to %1">, InGroup; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 03b8d16b76e0d..a84e5e4b59c89 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -19741,6 +19741,14 @@ case Builtin::BI__builtin_hlsl_elementwise_isinf: { RValFalse.isScalar() ? RValFalse.getScalarVal() : RValFalse.getAggregatePointer(E->getArg(2)->getType(), *this); +if (auto *VTy = E->getType()->getAs()) { + if (!OpTrue->getType()->isVectorTy()) +OpTrue = +Builder.CreateVectorSplat(VTy->getNumElements(), OpTrue, "splat"); + if (!OpFalse->getType()->isVectorTy()) +OpFalse = +Builder.CreateVectorSplat(VTy->getNumElements(), OpFalse, "splat"); +} Value *SelectVal = Builder.CreateSelect(OpCond, OpTrue, OpFalse, "hlsl.select"); diff --git a/clang/lib/Headers/hlsl/hlsl_detail.h b/clang/lib/Headers/hlsl/hlsl_detail.h index 0d568539cd66a..daccd2d793aa8 100644 --- a/clang/lib/Headers/hlsl/hlsl_detail.h +++ b/clang/lib/Headers/hlsl/hlsl_detail.h @@ -95,6 +95,11 @@ constexpr vector reflect_vec_impl(vector I, vector N) { #endif } +template +struct is_arithmetic { + static const bool Value = __is_arithmetic(T); +}; + } // namespace __detail } // namespace hlsl #endif //_HLSL_HLSL_DETAILS_H_ diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index ed008eeb04ba8..77a7f773b85b2 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -2246,6 +2246,42 @@ template _HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) vector select(vector, vector, vector); + +/// \fn vector select(vector Conds, T TrueVal, +/// vector FalseVals) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVals The vector values are chosen from when conditions are +/// false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, T, vector); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVals The vector values are chosen from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, vector, T); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +__detail::enable_if_t<__detail::is_arithmetic::Value, vector> select( +vector, T, T); + //===--===// // sin builtins //===--===// diff --git a/cl
[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)
llvmbot wrote: @llvm/pr-subscribers-clang-codegen Author: Chris B (llvm-beanz) Changes This PR adds scalar/vector overloads for vector conditions to the `select` builtin, and updates the sema checking and codegen to allow scalars to extend to vectors. Fixes #126570 --- Full diff: https://github.com/llvm/llvm-project/pull/129396.diff 7 Files Affected: - (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) - (modified) clang/lib/CodeGen/CGBuiltin.cpp (+8) - (modified) clang/lib/Headers/hlsl/hlsl_detail.h (+5) - (modified) clang/lib/Headers/hlsl/hlsl_intrinsics.h (+36) - (modified) clang/lib/Sema/SemaHLSL.cpp (+32-24) - (modified) clang/test/CodeGenHLSL/builtins/select.hlsl (+29) - (modified) clang/test/SemaHLSL/BuiltIns/select-errors.hlsl (+22-76) ``diff diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td b/clang/include/clang/Basic/DiagnosticSemaKinds.td index d094c075ecee2..be649f0bce320 100644 --- a/clang/include/clang/Basic/DiagnosticSemaKinds.td +++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td @@ -12682,6 +12682,9 @@ def err_hlsl_param_qualifier_mismatch : def err_hlsl_vector_compound_assignment_truncation : Error< "left hand operand of type %0 to compound assignment cannot be truncated " "when used with right hand operand of type %1">; +def err_hlsl_builtin_scalar_vector_mismatch : Error< + "%select{all|second and third}0 arguments to %1 must be of scalar or " + "vector type with matching scalar element type%diff{: $ vs $|}2,3">; def warn_hlsl_impcast_vector_truncation : Warning< "implicit conversion truncates vector: %0 to %1">, InGroup; diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp index 03b8d16b76e0d..a84e5e4b59c89 100644 --- a/clang/lib/CodeGen/CGBuiltin.cpp +++ b/clang/lib/CodeGen/CGBuiltin.cpp @@ -19741,6 +19741,14 @@ case Builtin::BI__builtin_hlsl_elementwise_isinf: { RValFalse.isScalar() ? RValFalse.getScalarVal() : RValFalse.getAggregatePointer(E->getArg(2)->getType(), *this); +if (auto *VTy = E->getType()->getAs()) { + if (!OpTrue->getType()->isVectorTy()) +OpTrue = +Builder.CreateVectorSplat(VTy->getNumElements(), OpTrue, "splat"); + if (!OpFalse->getType()->isVectorTy()) +OpFalse = +Builder.CreateVectorSplat(VTy->getNumElements(), OpFalse, "splat"); +} Value *SelectVal = Builder.CreateSelect(OpCond, OpTrue, OpFalse, "hlsl.select"); diff --git a/clang/lib/Headers/hlsl/hlsl_detail.h b/clang/lib/Headers/hlsl/hlsl_detail.h index 0d568539cd66a..daccd2d793aa8 100644 --- a/clang/lib/Headers/hlsl/hlsl_detail.h +++ b/clang/lib/Headers/hlsl/hlsl_detail.h @@ -95,6 +95,11 @@ constexpr vector reflect_vec_impl(vector I, vector N) { #endif } +template +struct is_arithmetic { + static const bool Value = __is_arithmetic(T); +}; + } // namespace __detail } // namespace hlsl #endif //_HLSL_HLSL_DETAILS_H_ diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index ed008eeb04ba8..77a7f773b85b2 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -2246,6 +2246,42 @@ template _HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) vector select(vector, vector, vector); + +/// \fn vector select(vector Conds, T TrueVal, +/// vector FalseVals) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVals The vector values are chosen from when conditions are +/// false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, T, vector); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVals The vector values are chosen from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +vector select(vector, vector, T); + +/// \fn vector select(vector Conds, vector TrueVals, +/// T FalseVal) +/// \brief ternary operator for vectors. All vectors must be the same size. +/// \param Conds The Condition input values. +/// \param TrueVal The scalar value to splat from when conditions are true. +/// \param FalseVal The scalar value to splat from when conditions are false. + +template +_HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) +__detail::enable_if_t<__detail::is_arithmetic::Value, vector> select( +vector, T, T); + //===--===// // sin builtins //===--===// diff --
[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)
github-actions[bot] wrote: :warning: C/C++ code formatter, clang-format found issues in your code. :warning: You can test this locally with the following command: ``bash git-clang-format --diff b65e0947cade9bd39036a7700b54c1df4ec00756 999c9253dc69c43f2d5d686bb4e9a9fd2f8783d4 --extensions h,cpp -- clang/lib/CodeGen/CGBuiltin.cpp clang/lib/Headers/hlsl/hlsl_detail.h clang/lib/Headers/hlsl/hlsl_intrinsics.h clang/lib/Sema/SemaHLSL.cpp `` View the diff from clang-format here. ``diff diff --git a/clang/lib/Headers/hlsl/hlsl_detail.h b/clang/lib/Headers/hlsl/hlsl_detail.h index daccd2d793..1587f233ac 100644 --- a/clang/lib/Headers/hlsl/hlsl_detail.h +++ b/clang/lib/Headers/hlsl/hlsl_detail.h @@ -95,8 +95,7 @@ constexpr vector reflect_vec_impl(vector I, vector N) { #endif } -template -struct is_arithmetic { +template struct is_arithmetic { static const bool Value = __is_arithmetic(T); }; diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h b/clang/lib/Headers/hlsl/hlsl_intrinsics.h index 77a7f773b8..07ee0be7bb 100644 --- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h +++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h @@ -2246,7 +2246,6 @@ template _HLSL_BUILTIN_ALIAS(__builtin_hlsl_select) vector select(vector, vector, vector); - /// \fn vector select(vector Conds, T TrueVal, /// vector FalseVals) /// \brief ternary operator for vectors. All vectors must be the same size. `` https://github.com/llvm/llvm-project/pull/129396 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
@@ -260,7 +260,8 @@ static bool EvaluateValue(PPValue &Result, Token &PeekTok, DefinedTracker &DT, PP.Diag(PeekTok, diag::warn_pp_undef_identifier) << II; const DiagnosticsEngine &DiagEngine = PP.getDiagnostics(); - // If 'Wundef' is enabled, do not emit 'undef-prefix' diagnostics. + // If 'Wundef' is enabled, do not emit 'undef-prefix' or 'undef-true' zygoloid wrote: You should pick the diagnostic ID (`warn_pp_undef_identifier` or `warn_pp_undef_true_identifier`) first, then change the code above to emit that diagnostic, and change this test to check that diagnostic, rather than conditionally emitting another diagnostic below. Branching on whether a diagnostic is enabled is discouraged. We do it here because `-Wundef-prefix=` is a weird special case, but `-Wundef-true` isn't, so it should do the more conventional thing of picking the diagnostic kind in advance. (There's a general principle here that we want it to be possible to enable "too many" warnings and filter them after the fact and still get the same output, as much as possible.) This is observable in that, with `-Wundef` enabled, the diagnostic for use of `#if true` will display the more precise warning flag `-Wundef-true`. https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang][diagnostics] add '-Wundef-true' warning option (PR #128265)
@@ -393,6 +393,9 @@ def pp_macro_not_used : Warning<"macro is not used">, DefaultIgnore, def warn_pp_undef_identifier : Warning< "%0 is not defined, evaluates to 0">, InGroup>, DefaultIgnore; +def warn_pp_undef_true_identifier : Warning< + "'true' is not defined, evaluates to 0">, + InGroup>; zygoloid wrote: `-Wundef-true` should be a child warning group under `-Wundef`, so that `-Wundef` and `-Wno-undef` continue to cover both cases. You'll need to define the groups in DiagnosticGroups.td https://github.com/llvm/llvm-project/pull/128265 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [SystemZ] Add header guard macros to vecintrin.h (PR #129170)
uweigand wrote: /cherry-pick https://github.com/llvm/llvm-project/commit/ddaa5b3bfb2980f79c6f277608ad33a6efe8d554 https://github.com/llvm/llvm-project/pull/129170 ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] [clang-tools-extra] [libcxx] [llvm] [libc++][ranges] P2542R8: Implement `views::concat` (PR #120920)
https://github.com/changkhothuychung updated https://github.com/llvm/llvm-project/pull/120920 error: too big or took too long to generate ___ cfe-commits mailing list cfe-commits@lists.llvm.org https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits
[clang] 304c053 - [cindex] Add API to query the class methods of a type (#123539)
Author: Trevor Laughlin Date: 2025-03-02T00:59:26+04:00 New Revision: 304c053a5c7b8a67f6f3fddf9492971a57901715 URL: https://github.com/llvm/llvm-project/commit/304c053a5c7b8a67f6f3fddf9492971a57901715 DIFF: https://github.com/llvm/llvm-project/commit/304c053a5c7b8a67f6f3fddf9492971a57901715.diff LOG: [cindex] Add API to query the class methods of a type (#123539) Inspired by https://github.com/llvm/llvm-project/pull/120300, add a new API `clang_visitCXXMethods` to libclang (and the Python bindings) which allows iterating over the class methods of a type. - Co-authored-by: Vlad Serebrennikov Co-authored-by: Aaron Ballman Added: Modified: clang/bindings/python/clang/cindex.py clang/bindings/python/tests/cindex/test_type.py clang/docs/ReleaseNotes.rst clang/include/clang-c/Index.h clang/tools/libclang/CIndexCXX.cpp clang/tools/libclang/libclang.map Removed: diff --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py index 722562220eeea..879a0a3c5c58c 100644 --- a/clang/bindings/python/clang/cindex.py +++ b/clang/bindings/python/clang/cindex.py @@ -2713,6 +2713,21 @@ def visitor(base, children): conf.lib.clang_visitCXXBaseClasses(self, fields_visit_callback(visitor), bases) return iter(bases) +def get_methods(self): +"""Return an iterator for accessing the methods of this type.""" + +def visitor(method, children): +assert method != conf.lib.clang_getNullCursor() + +# Create reference to TU so it isn't GC'd before Cursor. +method._tu = self._tu +methods.append(method) +return 1 # continue + +methods: list[Cursor] = [] +conf.lib.clang_visitCXXMethods(self, fields_visit_callback(visitor), methods) +return iter(methods) + def get_exception_specification_kind(self): """ Return the kind of the exception specification; a value from @@ -4020,6 +4035,7 @@ def set_property(self, property, value): ), ("clang_visitChildren", [Cursor, cursor_visit_callback, py_object], c_uint), ("clang_visitCXXBaseClasses", [Type, fields_visit_callback, py_object], c_uint), +("clang_visitCXXMethods", [Type, fields_visit_callback, py_object], c_uint), ("clang_Cursor_getNumArguments", [Cursor], c_int), ("clang_Cursor_getArgument", [Cursor, c_uint], Cursor), ("clang_Cursor_getNumTemplateArguments", [Cursor], c_int), diff --git a/clang/bindings/python/tests/cindex/test_type.py b/clang/bindings/python/tests/cindex/test_type.py index 9bac33f3041f4..bc893d509524e 100644 --- a/clang/bindings/python/tests/cindex/test_type.py +++ b/clang/bindings/python/tests/cindex/test_type.py @@ -559,3 +559,21 @@ class Template : public A, public B, virtual C { self.assertEqual(bases[1].get_base_offsetof(cursor_type_decl), 96) self.assertTrue(bases[2].is_virtual_base()) self.assertEqual(bases[2].get_base_offsetof(cursor_type_decl), 128) + +def test_class_methods(self): +source = """ +template +class Template { void Foo(); }; +typedef Template instance; +instance bar; +""" +tu = get_tu(source, lang="cpp", flags=["--target=x86_64-linux-gnu"]) +cursor = get_cursor(tu, "instance") +cursor_type = cursor.underlying_typedef_type +self.assertEqual(cursor.kind, CursorKind.TYPEDEF_DECL) +methods = list(cursor_type.get_methods()) +self.assertEqual(len(methods), 4) +self.assertEqual(methods[0].kind, CursorKind.CXX_METHOD) +self.assertEqual(methods[1].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[2].kind, CursorKind.CONSTRUCTOR) +self.assertEqual(methods[3].kind, CursorKind.CONSTRUCTOR) diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst index 7873c2048e53c..c4377c842cd96 100644 --- a/clang/docs/ReleaseNotes.rst +++ b/clang/docs/ReleaseNotes.rst @@ -349,6 +349,8 @@ clang-format libclang +- Added ``clang_visitCXXMethods``, which allows visiting the methods + of a class. - Fixed a buffer overflow in ``CXString`` implementation. The fix may result in increased memory allocation. @@ -388,6 +390,8 @@ Sanitizers Python Binding Changes -- +- Added ``Type.get_methods``, a binding for ``clang_visitCXXMethods``, which + allows visiting the methods of a class. OpenMP Support -- diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h index ed6bd797684d9..3a511de553ad4 100644 --- a/clang/include/clang-c/Index.h +++ b/clang/include/clang-c/Index.h @@ -6628,6 +6628,28 @@ CINDEX_LINKAGE unsigned clang_visitCXXBaseClasses(CXType T, CXFieldVisitor visitor, CXClientDat