[clang] [Clang][NFC] Improve const correctess of constraint normalization (PR #133633)

2025-03-30 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-aarch64-quick` 
running on `linaro-clang-aarch64-quick` while building `clang` at step 5 "ninja 
check 1".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/65/builds/14647


Here is the relevant piece of the build log for the reference

```
Step 5 (ninja check 1) failure: stage 1 checked (failure)
 TEST 'lit :: googletest-timeout.py' FAILED 

Exit Code: 1

Command Output (stdout):
--
# RUN: at line 9
not env -u FILECHECK_OPTS "/usr/bin/python3.10" 
/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/llvm/utils/lit/lit.py -j1 
--order=lexical -v Inputs/googletest-timeout--param 
gtest_filter=InfiniteLoopSubTest --timeout=1 > 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/Output/googletest-timeout.py.tmp.cmd.out
# executed command: not env -u FILECHECK_OPTS /usr/bin/python3.10 
/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/llvm/utils/lit/lit.py -j1 
--order=lexical -v Inputs/googletest-timeout --param 
gtest_filter=InfiniteLoopSubTest --timeout=1
# .---command stderr
# | lit.py: 
/home/tcwg-buildbot/worker/clang-aarch64-quick/llvm/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 1 seconds was requested on the command line. Forcing 
timeout to be 1 seconds.
# `-
# RUN: at line 11
FileCheck --check-prefix=CHECK-INF < 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/Output/googletest-timeout.py.tmp.cmd.out
 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/googletest-timeout.py
# executed command: FileCheck --check-prefix=CHECK-INF 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/googletest-timeout.py
# .---command stderr
# | 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/googletest-timeout.py:34:14:
 error: CHECK-INF: expected string not found in input
# | # CHECK-INF: Timed Out: 1
# |  ^
# | :13:29: note: scanning from here
# | Reached timeout of 1 seconds
# | ^
# | :37:2: note: possible intended match here
# |  Timed Out: 2 (100.00%)
# |  ^
# | 
# | Input file: 
# | Check file: 
/home/tcwg-buildbot/worker/clang-aarch64-quick/stage1/utils/lit/tests/googletest-timeout.py
# | 
# | -dump-input=help explains the following input dump.
# | 
# | Input was:
# | <<
# | .
# | .
# | .
# | 8:  
# | 9:  
# |10: -- 
# |11: exit: -9 
# |12: -- 
# |13: Reached timeout of 1 seconds 
# | check:34'0 X error: no match found
# |14:  
# | check:34'0 ~
# |15: TIMEOUT: googletest-timeout :: DummySubDir/OneTest.py/1/2 (2 
of 2) 
# | check:34'0 
~~~
# |16:  TEST 'googletest-timeout :: 
DummySubDir/OneTest.py/1/2' FAILED  
# | check:34'0 
~
# |17: Script(shard): 
# | check:34'0 ~~~
...

```



https://github.com/llvm/llvm-project/pull/133633
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -163,7 +163,11 @@ Options
 Semicolon-separated list of containers without their template parameters
 and some ``emplace``-like method of the container. Example:
 ``vector::emplace_back``. Those methods will be checked for improper use 
and
-the check will report when a temporary is unnecessarily created.
+the check will report when a temporary is unnecessarily created. Default

vbvictor wrote:

Ok, I will write all STL containers.
Also, need to add `std::flat_map` to that list. I will address this in another 
PR.

https://github.com/llvm/llvm-project/pull/133525
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][NFC] Improve const correctess of constraint normalization (PR #133633)

2025-03-30 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-aarch64-sve-vla` 
running on `linaro-g3-04` while building `clang` at step 7 "ninja check 1".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/17/builds/6876


Here is the relevant piece of the build log for the reference

```
Step 7 (ninja check 1) failure: stage 1 checked (failure)
...
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using ld64.lld: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/ld64.lld
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using wasm-ld: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/wasm-ld
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/discovery.py:276:
 warning: input 
'/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/interception/Unit'
 contained no tests
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/discovery.py:276:
 warning: input 
'/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/Unit'
 contained no tests
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using ld.lld: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/ld.lld
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using lld-link: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/lld-link
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using ld64.lld: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/ld64.lld
llvm-lit: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/llvm/llvm/utils/lit/lit/llvm/config.py:520:
 note: using wasm-ld: 
/home/tcwg-buildbot/worker/clang-aarch64-sve-vla/stage1/bin/wasm-ld
-- Testing: 97485 tests, 64 workers --
UNRESOLVED: Flang :: Driver/slp-vectorize.ll (1 of 97485)
 TEST 'Flang :: Driver/slp-vectorize.ll' FAILED 

Test has no 'RUN:' line

PASS: ScudoStandalone-Unit :: ./ScudoUnitTest-aarch64-Test/53/71 (2 of 97485)
PASS: ScudoStandalone-Unit-GwpAsanTorture :: ./ScudoUnitTest-aarch64-Test/53/71 
(3 of 97485)
PASS: Clang :: OpenMP/target_simd_codegen_registration.cpp (4 of 97485)
PASS: Clang :: Driver/clang_f_opts.c (5 of 97485)
PASS: libFuzzer-aarch64-default-Linux :: swap-cmp.test (6 of 97485)
PASS: libFuzzer-aarch64-default-Linux :: merge-sigusr.test (7 of 97485)
PASS: SanitizerCommon-hwasan-aarch64-Linux :: Linux/signal_segv_handler.cpp (8 
of 97485)
PASS: MemorySanitizer-AARCH64 :: release_origin.c (9 of 97485)
PASS: Clang :: OpenMP/target_teams_distribute_codegen_registration.cpp (10 of 
97485)
PASS: UBSan-AddressSanitizer-aarch64 :: 
TestCases/ImplicitConversion/signed-integer-truncation-ignorelist.c (11 of 
97485)
PASS: LLVM :: CodeGen/ARM/build-attributes.ll (12 of 97485)
PASS: Clang :: OpenMP/target_parallel_for_codegen_registration.cpp (13 of 97485)
PASS: Clang :: OpenMP/target_parallel_for_simd_codegen_registration.cpp (14 of 
97485)
PASS: Clang :: OpenMP/target_teams_distribute_simd_codegen_registration.cpp (15 
of 97485)
PASS: UBSan-AddressSanitizer-aarch64 :: 
TestCases/ImplicitConversion/unsigned-integer-truncation-ignorelist.c (16 of 
97485)
PASS: Clang :: Headers/arm-neon-header.c (17 of 97485)
PASS: Clang :: Driver/linux-ld.c (18 of 97485)
PASS: Clang :: CodeGen/X86/sse2-builtins.c (19 of 97485)
PASS: Clang :: CodeGen/X86/rot-intrinsics.c (20 of 97485)
PASS: SanitizerCommon-lsan-aarch64-Linux :: Linux/signal_segv_handler.cpp (21 
of 97485)
PASS: libFuzzer-aarch64-default-Linux :: large.test (22 of 97485)
PASS: UBSan-ThreadSanitizer-aarch64 :: 
TestCases/ImplicitConversion/unsigned-integer-truncation-ignorelist.c (23 of 
97485)
PASS: libFuzzer-aarch64-default-Linux :: value-profile-cmp.test (24 of 97485)
PASS: UBSan-ThreadSanitizer-aarch64 :: 
TestCases/ImplicitConversion/signed-integer-truncation-ignorelist.c (25 of 
97485)
PASS: Clang :: Analysis/runtime-regression.c (26 of 97485)
PASS: HWAddressSanitizer-aarch64 :: TestCases/Linux/create-thread-stress.cpp 
(27 of 97485)
PASS: SanitizerCommon-asan-aarch64-Linux :: Linux/signal_segv_handler.cpp (28 
of 97485)
PASS: libFuzzer-aarch64-default-Linux :: msan.test (29 of 97485)
PASS: SanitizerCommon-msan-aarch64-Linux :: Linux/signal_segv_handler.cpp (30 
of 97485)
PASS: Clang :: CodeGen/X86/avx-builtins.c (31 of 97485)
PASS: SanitizerCommon-tsan-aarch64-Linux :: Linux/signal_segv_handler.cpp (32 
of 97485)
PASS: Clang :: Preprocessor/predefined-arch-macros.c (33 of 97485)
PASS: libFuzzer-aarch64-default-Linux :: fuzzer-timeout.test (34 of 97485)
PASS: LLVM :: CodeGen/AMDGPU/sched-group-barrier-pipeline-solver.mir

[clang] [llvm] [IRBuilder] Add new overload for CreateIntrinsic (PR #131942)

2025-03-30 Thread Rahul Joshi via cfe-commits

https://github.com/jurahul updated 
https://github.com/llvm/llvm-project/pull/131942

>From 248b40f44df94093db8b1c8cd4284894be5b348a Mon Sep 17 00:00:00 2001
From: Rahul Joshi 
Date: Tue, 18 Mar 2025 13:19:24 -0700
Subject: [PATCH] [IRBuilder] Add new overload for CreateIntrinsic

Add a new `CreateIntrinsic` overload with no `Types`, useful for
creating calls to non-overloaded intrinsics that don't need
additional mangling.
---
 clang/lib/CodeGen/CGHLSLBuiltins.cpp  | 14 +++--
 clang/lib/CodeGen/CGHLSLRuntime.cpp   |  4 +-
 llvm/include/llvm/IR/IRBuilder.h  |  8 +++
 llvm/lib/CodeGen/SafeStack.cpp|  2 +-
 llvm/lib/CodeGen/StackProtector.cpp   |  4 +-
 llvm/lib/IR/AutoUpgrade.cpp   | 52 +--
 .../Target/AArch64/AArch64ISelLowering.cpp|  4 +-
 .../AArch64/AArch64TargetTransformInfo.cpp|  2 +-
 .../AMDGPU/AMDGPUAsanInstrumentation.cpp  |  2 +-
 .../Target/AMDGPU/AMDGPUAtomicOptimizer.cpp   | 11 ++--
 .../Target/AMDGPU/AMDGPUCodeGenPrepare.cpp|  2 +-
 .../AMDGPU/AMDGPULowerKernelArguments.cpp |  2 +-
 .../AMDGPU/AMDGPULowerModuleLDSPass.cpp   |  3 +-
 .../lib/Target/AMDGPU/AMDGPUPromoteAlloca.cpp |  6 +--
 llvm/lib/Target/AMDGPU/AMDGPUSwLowerLDS.cpp   | 18 +++
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  8 +--
 llvm/lib/Target/ARM/ARMISelLowering.cpp   | 10 ++--
 llvm/lib/Target/ARM/MVETailPredication.cpp|  2 +-
 llvm/lib/Target/Hexagon/HexagonGenExtract.cpp |  2 +-
 .../Target/Hexagon/HexagonISelLowering.cpp|  4 +-
 .../Target/Hexagon/HexagonVectorCombine.cpp   |  2 +-
 llvm/lib/Target/PowerPC/PPCISelLowering.cpp   |  2 +-
 llvm/lib/Target/SPIRV/SPIRVEmitIntrinsics.cpp |  6 +--
 llvm/lib/Target/SPIRV/SPIRVGlobalRegistry.cpp |  4 +-
 llvm/lib/Target/SPIRV/SPIRVStructurizer.cpp   |  2 +-
 .../Target/X86/X86InstCombineIntrinsic.cpp|  4 +-
 llvm/lib/Target/X86/X86LowerAMXType.cpp   | 20 +++
 llvm/lib/Target/X86/X86WinEHState.cpp |  6 +--
 .../Target/XCore/XCoreLowerThreadLocal.cpp|  2 +-
 llvm/lib/Transforms/IPO/CrossDSOCFI.cpp   |  2 +-
 .../Instrumentation/BoundsChecking.cpp|  4 +-
 .../Instrumentation/HWAddressSanitizer.cpp|  3 +-
 llvm/lib/Transforms/Instrumentation/KCFI.cpp  |  2 +-
 .../Instrumentation/MemorySanitizer.cpp   |  4 +-
 .../Instrumentation/PGOInstrumentation.cpp|  7 ++-
 .../Instrumentation/ThreadSanitizer.cpp   |  2 +-
 llvm/lib/Transforms/Scalar/SROA.cpp   |  2 +-
 llvm/lib/Transforms/Utils/GuardUtils.cpp  |  2 +-
 llvm/lib/Transforms/Utils/InlineFunction.cpp  |  4 +-
 llvm/unittests/IR/IRBuilderTest.cpp   | 44 +---
 llvm/unittests/Transforms/Utils/LocalTest.cpp |  4 +-
 41 files changed, 147 insertions(+), 141 deletions(-)

diff --git a/clang/lib/CodeGen/CGHLSLBuiltins.cpp 
b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
index 5709594a34826..136ea47451fed 100644
--- a/clang/lib/CodeGen/CGHLSLBuiltins.cpp
+++ b/clang/lib/CodeGen/CGHLSLBuiltins.cpp
@@ -66,13 +66,13 @@ static Value *handleHlslClip(const CallExpr *E, 
CodeGenFunction *CGF) {
 CMP = CGF->Builder.CreateIntrinsic(
 CGF->Builder.getInt1Ty(), CGF->CGM.getHLSLRuntime().getAnyIntrinsic(),
 {FCompInst});
-  } else
+  } else {
 CMP = CGF->Builder.CreateFCmpOLT(Op0, FZeroConst);
+  }
 
-  if (CGF->CGM.getTarget().getTriple().isDXIL())
-LastInstr =
-CGF->Builder.CreateIntrinsic(CGF->VoidTy, Intrinsic::dx_discard, 
{CMP});
-  else if (CGF->CGM.getTarget().getTriple().isSPIRV()) {
+  if (CGF->CGM.getTarget().getTriple().isDXIL()) {
+LastInstr = CGF->Builder.CreateIntrinsic(Intrinsic::dx_discard, {CMP});
+  } else if (CGF->CGM.getTarget().getTriple().isSPIRV()) {
 BasicBlock *LT0 = CGF->createBasicBlock("lt0", CGF->CurFn);
 BasicBlock *End = CGF->createBasicBlock("end", CGF->CurFn);
 
@@ -80,7 +80,7 @@ static Value *handleHlslClip(const CallExpr *E, 
CodeGenFunction *CGF) {
 
 CGF->Builder.SetInsertPoint(LT0);
 
-CGF->Builder.CreateIntrinsic(CGF->VoidTy, Intrinsic::spv_discard, {});
+CGF->Builder.CreateIntrinsic(Intrinsic::spv_discard, {});
 
 LastInstr = CGF->Builder.CreateBr(End);
 CGF->Builder.SetInsertPoint(End);
@@ -109,7 +109,6 @@ static Value *handleHlslSplitdouble(const CallExpr *E, 
CodeGenFunction *CGF) {
   Value *HighBits = nullptr;
 
   if (CGF->CGM.getTarget().getTriple().isDXIL()) {
-
 llvm::Type *RetElementTy = CGF->Int32Ty;
 if (auto *Op0VecTy = E->getArg(0)->getType()->getAs())
   RetElementTy = llvm::VectorType::get(
@@ -121,7 +120,6 @@ static Value *handleHlslSplitdouble(const CallExpr *E, 
CodeGenFunction *CGF) {
 
 LowBits = CGF->Builder.CreateExtractValue(CI, 0);
 HighBits = CGF->Builder.CreateExtractValue(CI, 1);
-
   } else {
 // For Non DXIL targets we generate the instructions.
 
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.cpp 
b/clang/lib/CodeGen/CGHLSLRuntime.cpp
index 0e859dd4a0b1d..3b1810b62a2cd 100644
--- a/clang/lib/Co

[clang] e6a87da - [CodeGen] Don't explicitly set intrinsic attributes (NFCI)

2025-03-30 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2025-03-20T15:04:03+01:00
New Revision: e6a87da8fe314a009eed769f9737b4b281a06fba

URL: 
https://github.com/llvm/llvm-project/commit/e6a87da8fe314a009eed769f9737b4b281a06fba
DIFF: 
https://github.com/llvm/llvm-project/commit/e6a87da8fe314a009eed769f9737b4b281a06fba.diff

LOG: [CodeGen] Don't explicitly set intrinsic attributes (NFCI)

The intrinsic attributes are automatically set when the function
is created, there is no need to assign them explicitly.

Added: 


Modified: 
clang/lib/CodeGen/CodeGenModule.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index e26c6c3da3091..257b7b40fd19e 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2936,9 +2936,8 @@ void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, 
llvm::Function *F,
   bool IsThunk) {
 
   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
-// If this is an intrinsic function, set the function's attributes
-// to the intrinsic's attributes.
-F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
+// If this is an intrinsic function, the attributes will have been set
+// when the function was created.
 return;
   }
 



___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [clang] Concepts: support pack expansions for type constraints (PR #132626)

2025-03-30 Thread Matheus Izvekov via cfe-commits

https://github.com/mizvekov updated 
https://github.com/llvm/llvm-project/pull/132626

>From 471bef0599a56ee90c1f8e2f7505a7b0003433c2 Mon Sep 17 00:00:00 2001
From: Matheus Izvekov 
Date: Sat, 22 Mar 2025 17:29:16 -0300
Subject: [PATCH 1/3] Revert "[Clang] Distinguish expanding-pack-in-place cases
 for SubstTemplateTypeParmTypes (#114220)"

This reverts commit adb0d8ddceb143749c519d14b8b31b481071da77.
---
 clang/include/clang/AST/ASTContext.h |  4 +--
 clang/include/clang/AST/PropertiesBase.td|  1 -
 clang/include/clang/AST/Type.h   | 29 ++--
 clang/include/clang/AST/TypeProperties.td|  5 +--
 clang/lib/AST/ASTContext.cpp |  7 ++--
 clang/lib/AST/ASTImporter.cpp|  4 +--
 clang/lib/AST/Type.cpp   |  6 +---
 clang/lib/Sema/SemaTemplateInstantiate.cpp   | 35 ++--
 clang/test/SemaCXX/cxx20-ctad-type-alias.cpp |  2 +-
 9 files changed, 23 insertions(+), 70 deletions(-)

diff --git a/clang/include/clang/AST/ASTContext.h 
b/clang/include/clang/AST/ASTContext.h
index af8c49e99a7ce..1f7c75559e1e9 100644
--- a/clang/include/clang/AST/ASTContext.h
+++ b/clang/include/clang/AST/ASTContext.h
@@ -1798,9 +1798,7 @@ class ASTContext : public RefCountedBase {
   QualType
   getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
unsigned Index,
-   std::optional PackIndex,
-   SubstTemplateTypeParmTypeFlag Flag =
-   SubstTemplateTypeParmTypeFlag::None) const;
+   std::optional PackIndex) const;
   QualType getSubstTemplateTypeParmPackType(Decl *AssociatedDecl,
 unsigned Index, bool Final,
 const TemplateArgument &ArgPack);
diff --git a/clang/include/clang/AST/PropertiesBase.td 
b/clang/include/clang/AST/PropertiesBase.td
index 42883b6419261..5f3a885832e2e 100644
--- a/clang/include/clang/AST/PropertiesBase.td
+++ b/clang/include/clang/AST/PropertiesBase.td
@@ -137,7 +137,6 @@ def Selector : PropertyType;
 def SourceLocation : PropertyType;
 def StmtRef : RefPropertyType<"Stmt"> { let ConstWhenWriting = 1; }
   def ExprRef : SubclassPropertyType<"Expr", StmtRef>;
-def SubstTemplateTypeParmTypeFlag : EnumPropertyType;
 def TemplateArgument : PropertyType;
 def TemplateArgumentKind : EnumPropertyType<"TemplateArgument::ArgKind">;
 def TemplateName : DefaultValuePropertyType;
diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index a809102c069a8..c927eb13711c1 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -1786,15 +1786,6 @@ enum class AutoTypeKeyword {
   GNUAutoType
 };
 
-enum class SubstTemplateTypeParmTypeFlag {
-  None,
-
-  /// Whether to expand the pack using the stored PackIndex in place. This is
-  /// useful for e.g. substituting into an atomic constraint expression, where
-  /// that expression is part of an unexpanded pack.
-  ExpandPacksInPlace,
-};
-
 enum class ArraySizeModifier;
 enum class ElaboratedTypeKeyword;
 enum class VectorKind;
@@ -2164,9 +2155,6 @@ class alignas(TypeAlignment) Type : public 
ExtQualsTypeCommonBase {
 LLVM_PREFERRED_TYPE(bool)
 unsigned HasNonCanonicalUnderlyingType : 1;
 
-LLVM_PREFERRED_TYPE(SubstTemplateTypeParmTypeFlag)
-unsigned SubstitutionFlag : 1;
-
 // The index of the template parameter this substitution represents.
 unsigned Index : 15;
 
@@ -6409,8 +6397,7 @@ class SubstTemplateTypeParmType final
   Decl *AssociatedDecl;
 
   SubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl,
-unsigned Index, std::optional PackIndex,
-SubstTemplateTypeParmTypeFlag Flag);
+unsigned Index, std::optional PackIndex);
 
 public:
   /// Gets the type that was substituted for the template
@@ -6439,31 +6426,21 @@ class SubstTemplateTypeParmType final
 return SubstTemplateTypeParmTypeBits.PackIndex - 1;
   }
 
-  SubstTemplateTypeParmTypeFlag getSubstitutionFlag() const {
-return static_cast(
-SubstTemplateTypeParmTypeBits.SubstitutionFlag);
-  }
-
   bool isSugared() const { return true; }
   QualType desugar() const { return getReplacementType(); }
 
   void Profile(llvm::FoldingSetNodeID &ID) {
 Profile(ID, getReplacementType(), getAssociatedDecl(), getIndex(),
-getPackIndex(), getSubstitutionFlag());
+getPackIndex());
   }
 
   static void Profile(llvm::FoldingSetNodeID &ID, QualType Replacement,
   const Decl *AssociatedDecl, unsigned Index,
-  std::optional PackIndex,
-  SubstTemplateTypeParmTypeFlag Flag) {
+  std::optional PackIndex) {
 Replacement.Profile(ID);
 ID.AddPointer(AssociatedDecl);
 ID.AddInteger(Index)

[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -16327,79 +16531,181 @@ static CanQualType RemoveAddressSpaceFromPtr(Sema 
&SemaRef,
   PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
 }
 
-static inline bool
-CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
-CanQualType ExpectedResultType,
-CanQualType ExpectedFirstParamType,
-unsigned DependentParamTypeDiag,
-unsigned InvalidParamTypeDiag) {
-  QualType ResultType =
-  FnDecl->getType()->castAs()->getReturnType();
+enum class AllocationOperatorKind { New, Delete };
+
+static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
+  const FunctionDecl *FD,
+  bool *WasMalformed) {
+  const Decl *MalformedDecl = nullptr;
+  if (FD->getNumParams() > 0 &&
+  SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
+/*TypeArgument=*/nullptr, &MalformedDecl))
+return true;
 
-  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
-// The operator is valid on any address space for OpenCL.
-// Drop address space from actual and expected result types.
-if (const auto *PtrTy = ResultType->getAs())
-  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+  if (!MalformedDecl)
+return false;
+
+  if (WasMalformed)
+*WasMalformed = true;
+
+  // SemaRef.Diag(MalformedDecl->getLocation(),
+  // diag::err_malformed_std_class_template) << "type_identity";

mizvekov wrote:

Leftovers?
```suggestion
```

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -16327,79 +16531,181 @@ static CanQualType RemoveAddressSpaceFromPtr(Sema 
&SemaRef,
   PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
 }
 
-static inline bool
-CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
-CanQualType ExpectedResultType,
-CanQualType ExpectedFirstParamType,
-unsigned DependentParamTypeDiag,
-unsigned InvalidParamTypeDiag) {
-  QualType ResultType =
-  FnDecl->getType()->castAs()->getReturnType();
+enum class AllocationOperatorKind { New, Delete };
+
+static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
+  const FunctionDecl *FD,
+  bool *WasMalformed) {
+  const Decl *MalformedDecl = nullptr;
+  if (FD->getNumParams() > 0 &&
+  SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
+/*TypeArgument=*/nullptr, &MalformedDecl))
+return true;
 
-  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
-// The operator is valid on any address space for OpenCL.
-// Drop address space from actual and expected result types.
-if (const auto *PtrTy = ResultType->getAs())
-  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+  if (!MalformedDecl)
+return false;
+
+  if (WasMalformed)
+*WasMalformed = true;
+
+  // SemaRef.Diag(MalformedDecl->getLocation(),
+  // diag::err_malformed_std_class_template) << "type_identity";
+  return true;
+}
+
+static bool isDestroyingDeleteT(QualType Type) {
+  auto *RD = Type->getAsCXXRecordDecl();
+  return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
+ RD->getIdentifier()->isStr("destroying_delete_t");
+}
+
+static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
+  const FunctionDecl *FD) {
+  // C++ P0722:
+  //   Within a class C, a single object deallocation function with signature
+  // (T, std::destroying_delete_t, )
+  //   is a destroying operator delete.
+  bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
+  SemaRef, FD, /*WasMalformed=*/nullptr);
+  unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
+  return isa(FD) && FD->getOverloadedOperator() == OO_Delete &&
+ FD->getNumParams() > DestroyingDeleteIdx &&
+ isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
+}
+
+static inline bool CheckOperatorNewDeleteTypes(
+Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
+CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
+unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
+  auto NormalizeType = [&SemaRef](QualType T) {
+if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
+  // The operator is valid on any address space for OpenCL.
+  // Drop address space from actual and expected result types.
+  if (const auto PtrTy = T->template getAs())
+T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+}
+return SemaRef.Context.getCanonicalType(T);
+  };
 
-if (auto ExpectedPtrTy = ExpectedResultType->getAs())
-  ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
+  const unsigned NumParams = FnDecl->getNumParams();
+  unsigned FirstNonTypeParam = 0;
+  bool MalformedTypeIdentity = false;
+  bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
+  SemaRef, FnDecl, &MalformedTypeIdentity);
+  unsigned MinimumMandatoryArgumentCount = 1;
+  unsigned SizeParameterIndex = 0;
+  if (IsPotentiallyTypeAware) {
+if (!FnDecl->isTemplateInstantiation()) {
+  unsigned DiagID = SemaRef.getLangOpts().CPlusPlus26
+? diag::warn_cxx26_type_aware_allocators
+: diag::ext_cxx26_type_aware_allocators;
+  SemaRef.Diag(FnDecl->getLocation(), DiagID);
+}
+
+if (OperatorKind == AllocationOperatorKind::New) {
+  SizeParameterIndex = 1;
+  MinimumMandatoryArgumentCount =
+  FunctionDecl::RequiredTypeAwareNewParameterCount;
+} else {
+  SizeParameterIndex = 2;
+  MinimumMandatoryArgumentCount =
+  FunctionDecl::RequiredTypeAwareDeleteParameterCount;
+}
+FirstNonTypeParam = 1;
   }
 
+  bool IsPotentiallyDestroyingDelete =
+  IsPotentiallyDestroyingOperatorDelete(SemaRef, FnDecl);
+
+  if (IsPotentiallyDestroyingDelete) {
+++MinimumMandatoryArgumentCount;
+++SizeParameterIndex;
+  }
+
+  if (NumParams < MinimumMandatoryArgumentCount)
+return SemaRef.Diag(FnDecl->getLocation(),
+diag::err_operator_new_delete_too_few_parameters)
+   << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
+   << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
-

[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -9817,27 +9817,54 @@ def err_operator_new_delete_invalid_result_type : Error<
 def err_operator_new_delete_dependent_result_type : Error<
   "%0 cannot have a dependent return type; use %1 instead">;
 def err_operator_new_delete_too_few_parameters : Error<
-  "%0 must have at least one parameter">;
+  "%select{|type aware }0%select{|destroying }1%2 must have at least 
%select{|one|two|three|four|five}3 parameter%s3">;
 def err_operator_new_delete_template_too_few_parameters : Error<
   "%0 template must have at least two parameters">;
 def warn_operator_new_returns_null : Warning<
   "%0 should not return a null pointer unless it is declared 'throw()'"
   "%select{| or 'noexcept'}1">, InGroup;
 
 def err_operator_new_dependent_param_type : Error<
-  "%0 cannot take a dependent type as first parameter; "
-  "use size_t (%1) instead">;
+  "%select{|type aware }0%select{|destroying }1%2 cannot take a dependent type 
as its %select{first|second|third|fourth|fifth}3 parameter; "

mizvekov wrote:

Pointing is better than having to spell the name or position.

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][NFC] Improve const correctess of constraint normalization (PR #133633)

2025-03-30 Thread via cfe-commits

https://github.com/cor3ntin closed 
https://github.com/llvm/llvm-project/pull/133633
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] 1cb6ba5 - [Clang][NFC] Improve const correctness of constraint normalization (#133633)

2025-03-30 Thread via cfe-commits

Author: cor3ntin
Date: 2025-03-30T11:56:36+02:00
New Revision: 1cb6ba5c60c3ce19785948eb327036a455dd1457

URL: 
https://github.com/llvm/llvm-project/commit/1cb6ba5c60c3ce19785948eb327036a455dd1457
DIFF: 
https://github.com/llvm/llvm-project/commit/1cb6ba5c60c3ce19785948eb327036a455dd1457.diff

LOG: [Clang][NFC] Improve const correctness of constraint normalization 
(#133633)

Follow up to #132849

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/include/clang/Sema/SemaConcept.h
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 066bce61c74c1..c74e709ce06d2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14660,7 +14660,8 @@ class Sema final : public SemaBase {
 bool First = true);
 
   const NormalizedConstraint *getNormalizedAssociatedConstraints(
-  NamedDecl *ConstrainedDecl, ArrayRef 
AssociatedConstraints);
+  const NamedDecl *ConstrainedDecl,
+  ArrayRef AssociatedConstraints);
 
   /// \brief Check whether the given declaration's associated constraints are
   /// at least as constrained than another declaration's according to the
@@ -14670,28 +14671,30 @@ class Sema final : public SemaBase {
   /// at least constrained than D2, and false otherwise.
   ///
   /// \returns true if an error occurred, false otherwise.
-  bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef AC1,
-  NamedDecl *D2, MutableArrayRef AC2,
-  bool &Result);
+  bool IsAtLeastAsConstrained(const NamedDecl *D1,
+  MutableArrayRef AC1,
+  const NamedDecl *D2,
+  MutableArrayRef AC2, bool &Result);
 
   /// If D1 was not at least as constrained as D2, but would've been if a pair
   /// of atomic constraints involved had been declared in a concept and not
   /// repeated in two separate places in code.
   /// \returns true if such a diagnostic was emitted, false otherwise.
   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
-  NamedDecl *D1, ArrayRef AC1, NamedDecl *D2,
+  const NamedDecl *D1, ArrayRef AC1, const NamedDecl *D2,
   ArrayRef AC2);
 
 private:
   /// Caches pairs of template-like decls whose associated constraints were
   /// checked for subsumption and whether or not the first's constraints did in
   /// fact subsume the second's.
-  llvm::DenseMap, bool> SubsumptionCache;
+  llvm::DenseMap, bool>
+  SubsumptionCache;
   /// Caches the normalized associated constraints of declarations (concepts or
   /// constrained declarations). If an error occurred while normalizing the
   /// associated constraints of the template or concept, nullptr will be cached
   /// here.
-  llvm::DenseMap NormalizationCache;
+  llvm::DenseMap NormalizationCache;
 
   llvm::ContextualFoldingSet
   SatisfactionCache;

diff  --git a/clang/include/clang/Sema/SemaConcept.h 
b/clang/include/clang/Sema/SemaConcept.h
index fda22b779c636..cbb3720c30ee2 100644
--- a/clang/include/clang/Sema/SemaConcept.h
+++ b/clang/include/clang/Sema/SemaConcept.h
@@ -31,10 +31,10 @@ enum { ConstraintAlignment = 8 };
 
 struct alignas(ConstraintAlignment) AtomicConstraint {
   const Expr *ConstraintExpr;
-  NamedDecl *ConstraintDecl;
+  const NamedDecl *ConstraintDecl;
   std::optional> ParameterMapping;
 
-  AtomicConstraint(const Expr *ConstraintExpr, NamedDecl *ConstraintDecl)
+  AtomicConstraint(const Expr *ConstraintExpr, const NamedDecl *ConstraintDecl)
   : ConstraintExpr(ConstraintExpr), ConstraintDecl(ConstraintDecl) {};
 
   bool hasMatchingParameterMapping(ASTContext &C,
@@ -114,9 +114,9 @@ struct NormalizedConstraint {
 
 private:
   static std::optional
-  fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef E);
+  fromConstraintExprs(Sema &S, const NamedDecl *D, ArrayRef E);
   static std::optional
-  fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E);
+  fromConstraintExpr(Sema &S, const NamedDecl *D, const Expr *E);
 };
 
 struct alignas(ConstraintAlignment) NormalizedConstraintPair {
@@ -137,7 +137,7 @@ struct alignas(ConstraintAlignment) FoldExpandedConstraint {
 };
 
 const NormalizedConstraint *getNormalizedAssociatedConstraints(
-Sema &S, NamedDecl *ConstrainedDecl,
+Sema &S, const NamedDecl *ConstrainedDecl,
 ArrayRef AssociatedConstraints);
 
 /// \brief SubsumptionChecker establishes subsumption
@@ -149,8 +149,8 @@ class SubsumptionChecker {
 
   SubsumptionChecker(Sema &SemaRef, SubsumptionCallable Callable = {});
 
-  std::optional Subsumes(NamedDecl *DP, ArrayRef P,
-   NamedDecl *DQ, ArrayRef Q);
+  std::optional Subsumes(const NamedDecl *DP, ArrayRef P,
+   const NamedDecl *DQ, ArrayRef Q);
 
   bool Subsumes(const NormalizedCon

[clang] [clang-format] Add an option for editing enum trailing commas (PR #133576)

2025-03-30 Thread Owen Pan via cfe-commits


@@ -2214,6 +2214,21 @@ FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind 
Language) const {
 
 namespace {
 
+void replaceToken(const FormatToken &Token, FormatToken *Next,
+  const SourceManager &SourceMgr, tooling::Replacements 
&Result,
+  const char *Text = "") {

owenca wrote:

I was going to use `StringRef` but instead settled on `const char *` because of 
#131299. I can switch to `StringRef` if you still think it's better.

https://github.com/llvm/llvm-project/pull/133576
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Oliver Hunt via cfe-commits


@@ -1466,17 +1477,30 @@ namespace {
 void Emit(CodeGenFunction &CGF, Flags flags) override {
   const auto *FPT = OperatorDelete->getType()->castAs();
   CallArgList DeleteArgs;
-
-  // The first argument is always a void* (or C* for a destroying operator
-  // delete for class type C).
-  DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
+  unsigned FirstNonTypeArg = 0;
+  TypeAwareAllocationMode TypeAwareDeallocation =
+  TypeAwareAllocationMode::No;
+  if (OperatorDelete->isTypeAwareOperatorNewOrDelete()) {
+TypeAwareDeallocation = TypeAwareAllocationMode::Yes;
+QualType SpecializedTypeIdentity = FPT->getParamType(0);
+++FirstNonTypeArg;
+CXXScalarValueInitExpr TypeIdentityParam(SpecializedTypeIdentity,
+ nullptr, SourceLocation());
+DeleteArgs.add(CGF.EmitAnyExprToTemp(&TypeIdentityParam),
+   SpecializedTypeIdentity);
+  }
+  // The first non type tag argument is always a void* (or C* for a

ojhunt wrote:

done

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [lldb] Reland: [clang] preserve class type sugar when taking pointer to member (PR #132401)

2025-03-30 Thread Alexander Kornienko via cfe-commits

alexfh wrote:

> @alexfh should be fixed by #133613

Thank you! The crash is resolved. Do you still need a reduced test case?

https://github.com/llvm/llvm-project/pull/132401
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang] [OpenMP] Support NOWAIT with optional argument (PR #128742)

2025-03-30 Thread via cfe-commits

https://github.com/jadhbeika updated 
https://github.com/llvm/llvm-project/pull/128742

>From fa3dd1423e4bf2209feb9713f1833e653ec43a74 Mon Sep 17 00:00:00 2001
From: Jad Hbeika 
Date: Wed, 19 Feb 2025 12:53:11 -0800
Subject: [PATCH 1/5] [Clang] [OpenMP] Support NOWAIT with optional argument

---
 clang/include/clang/AST/OpenMPClause.h| 58 ---
 clang/include/clang/AST/RecursiveASTVisitor.h |  3 +-
 clang/include/clang/Sema/SemaOpenMP.h |  6 +-
 clang/lib/AST/OpenMPClause.cpp| 11 +++-
 clang/lib/AST/StmtProfile.cpp |  5 +-
 clang/lib/Parse/ParseOpenMP.cpp   |  5 +-
 clang/lib/Sema/SemaOpenMP.cpp | 24 +++-
 clang/lib/Sema/TreeTransform.h| 21 ++-
 clang/lib/Serialization/ASTReader.cpp |  5 +-
 clang/lib/Serialization/ASTWriter.cpp |  5 +-
 clang/tools/libclang/CIndex.cpp   |  4 +-
 llvm/include/llvm/Frontend/OpenMP/OMP.td  |  2 +
 12 files changed, 127 insertions(+), 22 deletions(-)

diff --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index 154ecfbaa4418..b29fce9bd9729 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -2173,18 +2173,62 @@ class OMPOrderedClause final
 /// This represents 'nowait' clause in the '#pragma omp ...' directive.
 ///
 /// \code
-/// #pragma omp for nowait
+/// #pragma omp for nowait (cond)
 /// \endcode
-/// In this example directive '#pragma omp for' has 'nowait' clause.
-class OMPNowaitClause final : public OMPNoChildClause {
+/// In this example directive '#pragma omp for' has simple 'nowait' clause with
+/// condition 'cond'.
+class OMPNowaitClause final : public OMPClause {
+  friend class OMPClauseReader;
+
+  /// Location of '('.
+  SourceLocation LParenLoc;
+
+  /// Condition of the 'nowait' clause.
+  Stmt *Condition = nullptr;
+
+  /// Set condition.
+  void setCondition(Expr *Cond) { Condition = Cond; }
+
 public:
-  /// Build 'nowait' clause.
+  /// Build 'nowait' clause with condition \a Cond.
   ///
+  /// \param Cond Condition of the clause.
   /// \param StartLoc Starting location of the clause.
+  /// \param LParenLoc Location of '('.
   /// \param EndLoc Ending location of the clause.
-  OMPNowaitClause(SourceLocation StartLoc = SourceLocation(),
-  SourceLocation EndLoc = SourceLocation())
-  : OMPNoChildClause(StartLoc, EndLoc) {}
+  OMPNowaitClause(Expr *Cond, SourceLocation StartLoc, SourceLocation 
LParenLoc,
+  SourceLocation EndLoc)
+  : OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc),
+LParenLoc(LParenLoc), Condition(Cond) {}
+
+  /// Build an empty clause.
+  OMPNowaitClause()
+  : OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) 
{}
+
+  /// Sets the location of '('.
+  void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+
+  /// Returns the location of '('.
+  SourceLocation getLParenLoc() const { return LParenLoc; }
+
+  /// Returns condition.
+  Expr *getCondition() const { return cast_or_null(Condition); }
+
+  child_range children() { return child_range(&Condition, &Condition + 1); }
+
+  const_child_range children() const {
+return const_child_range(&Condition, &Condition + 1);
+  }
+
+  child_range used_children();
+  const_child_range used_children() const {
+auto Children = const_cast(this)->used_children();
+return const_child_range(Children.begin(), Children.end());
+  }
+
+  static bool classof(const OMPClause *T) {
+return T->getClauseKind() == llvm::omp::OMPC_nowait;
+  }
 };
 
 /// This represents 'untied' clause in the '#pragma omp ...' directive.
diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 560de7da9913a..52b940e7f3c0a 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -3466,7 +3466,8 @@ bool 
RecursiveASTVisitor::VisitOMPOrderedClause(OMPOrderedClause *C) {
 }
 
 template 
-bool RecursiveASTVisitor::VisitOMPNowaitClause(OMPNowaitClause *) {
+bool RecursiveASTVisitor::VisitOMPNowaitClause(OMPNowaitClause *C) {
+  TRY_TO(TraverseStmt(C->getCondition()));
   return true;
 }
 
diff --git a/clang/include/clang/Sema/SemaOpenMP.h 
b/clang/include/clang/Sema/SemaOpenMP.h
index 64f0cfa0676af..8af56c087a896 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -1001,8 +1001,10 @@ class SemaOpenMP : public SemaBase {
   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
   /// Called on well-formed 'nowait' clause.
-  OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
- SourceLocation EndLoc);
+  OMPClause *
+  ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc,
+  SourceLoc

[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,124 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes='sroa' -S | FileCheck %s
+target datalayout = 
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-n8:16:32:64"
+
+%ptr_pair = type { ptr, ptr }
+
+%struct.a = type { <32 x i8> }
+define void @vector_promote_memset_a(ptr %0) {
+; CHECK-LABEL: @vector_promote_memset_a(
+; CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[TMP0:%.*]], align 8
+; CHECK-NEXT:[[TMP3:%.*]] = load i8, ptr [[TMP2]], align 1
+; CHECK-NEXT:[[DOTSROA_0_0_VEC_INSERT:%.*]] = insertelement <32 x i8> 
zeroinitializer, i8 [[TMP3]], i32 0
+; CHECK-NEXT:ret void
+;
+  %2 = alloca %struct.a, align 32
+  %3 = alloca %ptr_pair, align 8
+  call void @llvm.memset.p0.i64(ptr align 32 %2, i8 0, i64 32, i1 false)
+
+  store ptr %2, ptr %3, align 8
+
+  %4 = getelementptr inbounds %ptr_pair, ptr %3, i64 0, i32 1
+  %5 = load ptr, ptr %0, align 8
+  store ptr %5, ptr %4, align 8
+
+  %6 = getelementptr inbounds i8, ptr %3, i32 8
+  %7 = load ptr, ptr %6, align 8
+
+  %8 = load i8, ptr %7, align 1
+  store i8 %8, ptr %2, align 32
+
+  ret void
+}
+
+%struct.b = type { <16 x i16> }
+define void @vector_promote_memset_b(ptr %0) {
+; CHECK-LABEL: @vector_promote_memset_b(
+; CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[TMP0:%.*]], align 8
+; CHECK-NEXT:[[TMP3:%.*]] = load i16, ptr [[TMP2]], align 1
+; CHECK-NEXT:[[DOTSROA_0_0_VEC_INSERT:%.*]] = insertelement <16 x i16> 
zeroinitializer, i16 [[TMP3]], i32 0
+; CHECK-NEXT:ret void
+;
+  %2 = alloca %struct.b, align 16
+  %3 = alloca %ptr_pair, align 8
+  call void @llvm.memset.p0.i64(ptr align 32 %2, i8 0, i64 32, i1 false)
+
+  store ptr %2, ptr %3, align 8
+
+  %4 = getelementptr inbounds %ptr_pair, ptr %3, i64 0, i32 1
+  %5 = load ptr, ptr %0, align 8
+  store ptr %5, ptr %4, align 8
+
+  %6 = getelementptr inbounds i8, ptr %3, i32 8
+  %7 = load ptr, ptr %6, align 8
+
+  %8 = load i16, ptr %7, align 1
+  store i16 %8, ptr %2, align 16
+
+  ret void
+}
+
+%struct.c = type { <4 x i32> }
+define void @vector_promote_memset_c(ptr %0) {
+; CHECK-LABEL: @vector_promote_memset_c(
+; CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[TMP0:%.*]], align 8
+; CHECK-NEXT:[[TMP3:%.*]] = load i32, ptr [[TMP2]], align 1
+; CHECK-NEXT:[[DOTSROA_0_8_VEC_INSERT:%.*]] = insertelement <4 x i32> 
zeroinitializer, i32 [[TMP3]], i32 2
+; CHECK-NEXT:ret void
+;
+  %2 = alloca %struct.c, align 4
+  %3 = alloca %ptr_pair, align 8
+  call void @llvm.memset.p0.i64(ptr align 32 %2, i8 0, i64 16, i1 false)
+
+  store ptr %2, ptr %3, align 8
+
+  %4 = getelementptr inbounds %ptr_pair, ptr %3, i64 0, i32 1
+  %5 = load ptr, ptr %0, align 8
+  store ptr %5, ptr %4, align 8
+
+  %6 = getelementptr inbounds i8, ptr %3, i32 8
+  %7 = load ptr, ptr %6, align 8
+
+  %8 = load i32, ptr %7, align 1
+
+  %9 = getelementptr inbounds i32, ptr %2, i32 2
+  store i32 %8, ptr %9, align 4
+
+  ret void
+}
+
+; We currently prevent promotion if the vector would require padding
+%struct.d = type { <6 x i32> }
+define void @vector_promote_memset_d(ptr %0) {
+; CHECK-LABEL: @vector_promote_memset_d(
+; CHECK-NEXT:[[DOTSROA_2:%.*]] = alloca [3 x i32], align 4
+; CHECK-NEXT:call void @llvm.memset.p0.i64(ptr align 4 [[DOTSROA_2]], i8 
0, i64 12, i1 false)
+; CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[TMP0:%.*]], align 8
+; CHECK-NEXT:[[TMP3:%.*]] = load i32, ptr [[TMP2]], align 1
+; CHECK-NEXT:ret void
+;
+  %2 = alloca %struct.d, align 4
+  %3 = alloca %ptr_pair, align 8
+  call void @llvm.memset.p0.i64(ptr align 32 %2, i8 0, i64 24, i1 false)
+
+  store ptr %2, ptr %3, align 8
+
+  %4 = getelementptr inbounds %ptr_pair, ptr %3, i64 0, i32 1
+  %5 = load ptr, ptr %0, align 8
+  store ptr %5, ptr %4, align 8
+
+  %6 = getelementptr inbounds i8, ptr %3, i32 8
+  %7 = load ptr, ptr %6, align 8
+
+  %8 = load i32, ptr %7, align 1
+
+  %9 = getelementptr inbounds i32, ptr %2, i32 2
+  store i32 %8, ptr %9, align 4
+
+  ret void
+}
+

arsenm wrote:

Test with the number of elements equalling and exceeding 32-bit limit case? 

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -1011,6 +1011,31 @@ static Value *foldPHINodeOrSelectInst(Instruction &I) {
   return foldSelectInst(cast(I));
 }
 
+/// Returns a fixed vector type equivalent to the memory set by II or nullptr 
if
+/// unable to do so.
+static FixedVectorType *getVectorTypeFor(const MemSetInst &II,
+ const DataLayout &DL) {
+  const ConstantInt *Length = dyn_cast(II.getLength());
+  if (!Length)
+return nullptr;
+
+  APInt Val = Length->getValue();
+  if (Val.ugt(std::numeric_limits::max()))
+return nullptr;

arsenm wrote:

Don't understand this limit. Is this the maximum number of vector elements? 
Should avoid hardcoding that 

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -1011,6 +1011,31 @@ static Value *foldPHINodeOrSelectInst(Instruction &I) {
   return foldSelectInst(cast(I));
 }
 
+/// Returns a fixed vector type equivalent to the memory set by II or nullptr 
if
+/// unable to do so.
+static FixedVectorType *getVectorTypeFor(const MemSetInst &II,
+ const DataLayout &DL) {
+  const ConstantInt *Length = dyn_cast(II.getLength());
+  if (!Length)
+return nullptr;
+
+  APInt Val = Length->getValue();
+  if (Val.ugt(std::numeric_limits::max()))
+return nullptr;

arsenm wrote:

Is this just because the maximum number of vector elts? Can you put this value 
into a helper on FixedVectorType instead of hardcoding unsigned here? 

Although we probably shouldn't be trying to promote anything that's anything 
close to that big. 

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,124 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes='sroa' -S | FileCheck %s
+target datalayout = 
"e-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:64:64-v64:64:64-v128:128:128-a0:0:64-n8:16:32:64"
+
+%ptr_pair = type { ptr, ptr }
+
+%struct.a = type { <32 x i8> }
+define void @vector_promote_memset_a(ptr %0) {
+; CHECK-LABEL: @vector_promote_memset_a(
+; CHECK-NEXT:[[TMP2:%.*]] = load ptr, ptr [[TMP0:%.*]], align 8
+; CHECK-NEXT:[[TMP3:%.*]] = load i8, ptr [[TMP2]], align 1
+; CHECK-NEXT:[[DOTSROA_0_0_VEC_INSERT:%.*]] = insertelement <32 x i8> 
zeroinitializer, i8 [[TMP3]], i32 0
+; CHECK-NEXT:ret void
+;
+  %2 = alloca %struct.a, align 32

arsenm wrote:

Use named values in tests 

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -1011,6 +1011,31 @@ static Value *foldPHINodeOrSelectInst(Instruction &I) {
   return foldSelectInst(cast(I));
 }
 
+/// Returns a fixed vector type equivalent to the memory set by II or nullptr 
if
+/// unable to do so.
+static FixedVectorType *getVectorTypeFor(const MemSetInst &II,
+ const DataLayout &DL) {
+  const ConstantInt *Length = dyn_cast(II.getLength());
+  if (!Length)
+return nullptr;
+
+  APInt Val = Length->getValue();
+  if (Val.ugt(std::numeric_limits::max()))
+return nullptr;
+
+  uint64_t MemSetLen = Val.getZExtValue();
+  auto *VTy = FixedVectorType::get(II.getValue()->getType(), MemSetLen);

arsenm wrote:

The element will always be i8. TODO to support 
llvm.experimental.memset.pattern? 

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] Make enums trivially equality comparable (PR #133587)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Nikolas Klauser (philnik777)


Changes

Fixes #132672



---
Full diff: https://github.com/llvm/llvm-project/pull/133587.diff


2 Files Affected:

- (modified) clang/lib/Sema/SemaExprCXX.cpp (+48-35) 
- (modified) clang/test/SemaCXX/type-traits.cpp (+12) 


``diff
diff --git a/clang/lib/Sema/SemaExprCXX.cpp b/clang/lib/Sema/SemaExprCXX.cpp
index 46895db4a0756..d4a9900d3fa8a 100644
--- a/clang/lib/Sema/SemaExprCXX.cpp
+++ b/clang/lib/Sema/SemaExprCXX.cpp
@@ -5174,6 +5174,43 @@ static bool HasNoThrowOperator(const RecordType *RT, 
OverloadedOperatorKind Op,
   return false;
 }
 
+static bool EqualityComparisonIsDefaulted(Sema &S, const TypeDecl *Decl,
+  SourceLocation KeyLoc) {
+  EnterExpressionEvaluationContext UnevaluatedContext(
+  S, Sema::ExpressionEvaluationContext::Unevaluated);
+  Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
+  Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
+
+  // const ClassT& obj;
+  OpaqueValueExpr Operand(
+  KeyLoc, 
Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
+  ExprValueKind::VK_LValue);
+  UnresolvedSet<16> Functions;
+  // obj == obj;
+  S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
+
+  auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
+Functions, &Operand, &Operand);
+  if (Result.isInvalid() || SFINAE.hasErrorOccurred())
+return false;
+
+  const auto *CallExpr = dyn_cast(Result.get());
+  if (!CallExpr)
+return isa(Decl);
+  const auto *Callee = CallExpr->getDirectCallee();
+  auto ParamT = Callee->getParamDecl(0)->getType();
+  if (!Callee->isDefaulted())
+return false;
+  if (!ParamT->isReferenceType()) {
+if (const CXXRecordDecl * RD = dyn_cast(Decl); 
!RD->isTriviallyCopyable())
+  return false;
+  }
+  if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
+  Decl->getTypeForDecl())
+return false;
+  return true;
+}
+
 static bool HasNonDeletedDefaultedEqualityComparison(Sema &S,
  const CXXRecordDecl *Decl,
  SourceLocation KeyLoc) {
@@ -5182,39 +5219,8 @@ static bool 
HasNonDeletedDefaultedEqualityComparison(Sema &S,
   if (Decl->isLambda())
 return Decl->isCapturelessLambda();
 
-  {
-EnterExpressionEvaluationContext UnevaluatedContext(
-S, Sema::ExpressionEvaluationContext::Unevaluated);
-Sema::SFINAETrap SFINAE(S, /*AccessCheckingSFINAE=*/true);
-Sema::ContextRAII TUContext(S, S.Context.getTranslationUnitDecl());
-
-// const ClassT& obj;
-OpaqueValueExpr Operand(
-KeyLoc,
-Decl->getTypeForDecl()->getCanonicalTypeUnqualified().withConst(),
-ExprValueKind::VK_LValue);
-UnresolvedSet<16> Functions;
-// obj == obj;
-S.LookupBinOp(S.TUScope, {}, BinaryOperatorKind::BO_EQ, Functions);
-
-auto Result = S.CreateOverloadedBinOp(KeyLoc, BinaryOperatorKind::BO_EQ,
-  Functions, &Operand, &Operand);
-if (Result.isInvalid() || SFINAE.hasErrorOccurred())
-  return false;
-
-const auto *CallExpr = dyn_cast(Result.get());
-if (!CallExpr)
-  return false;
-const auto *Callee = CallExpr->getDirectCallee();
-auto ParamT = Callee->getParamDecl(0)->getType();
-if (!Callee->isDefaulted())
-  return false;
-if (!ParamT->isReferenceType() && !Decl->isTriviallyCopyable())
-  return false;
-if (ParamT.getNonReferenceType()->getUnqualifiedDesugaredType() !=
-Decl->getTypeForDecl())
-  return false;
-  }
+  if (!EqualityComparisonIsDefaulted(S, Decl, KeyLoc))
+return false;
 
   return llvm::all_of(Decl->bases(),
   [&](const CXXBaseSpecifier &BS) {
@@ -5229,7 +5235,10 @@ static bool 
HasNonDeletedDefaultedEqualityComparison(Sema &S,
  Type = Type->getBaseElementTypeUnsafe()
 ->getCanonicalTypeUnqualified();
 
-   if (Type->isReferenceType() || Type->isEnumeralType())
+   if (Type->isReferenceType() ||
+   (Type->isEnumeralType() &&
+!EqualityComparisonIsDefaulted(
+S, cast(Type->getAsTagDecl()), KeyLoc)))
  return false;
if (const auto *RD = Type->getAsCXXRecordDecl())
  return HasNonDeletedDefaultedEqualityComparison(S, RD, KeyLoc);
@@ -5240,9 +5249,13 @@ static bool 
HasNonDeletedDefaultedEqualityComparison(Sema &S,
 static bool isTriviallyEqualityComparableType(Sema &S, QualType Type, 
SourceLocation KeyLoc) {
   QualType CanonicalType = Type.getCanonicalType();
   if (CanonicalType->isIncompleteType() || CanonicalType->isDependentType() ||
-  CanonicalType->isEnumeralType() || CanonicalType->isArrayType())
+  CanonicalType->isArrayType())
 return f

[clang] [Clang] Make enums trivially equality comparable (PR #133587)

2025-03-30 Thread Nikolas Klauser via cfe-commits

https://github.com/philnik777 ready_for_review 
https://github.com/llvm/llvm-project/pull/133587
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [Clang] [OpenMP] Support NOWAIT with optional argument (PR #128742)

2025-03-30 Thread via cfe-commits

https://github.com/jadhbeika updated 
https://github.com/llvm/llvm-project/pull/128742

>From fa3dd1423e4bf2209feb9713f1833e653ec43a74 Mon Sep 17 00:00:00 2001
From: Jad Hbeika 
Date: Wed, 19 Feb 2025 12:53:11 -0800
Subject: [PATCH 1/6] [Clang] [OpenMP] Support NOWAIT with optional argument

---
 clang/include/clang/AST/OpenMPClause.h| 58 ---
 clang/include/clang/AST/RecursiveASTVisitor.h |  3 +-
 clang/include/clang/Sema/SemaOpenMP.h |  6 +-
 clang/lib/AST/OpenMPClause.cpp| 11 +++-
 clang/lib/AST/StmtProfile.cpp |  5 +-
 clang/lib/Parse/ParseOpenMP.cpp   |  5 +-
 clang/lib/Sema/SemaOpenMP.cpp | 24 +++-
 clang/lib/Sema/TreeTransform.h| 21 ++-
 clang/lib/Serialization/ASTReader.cpp |  5 +-
 clang/lib/Serialization/ASTWriter.cpp |  5 +-
 clang/tools/libclang/CIndex.cpp   |  4 +-
 llvm/include/llvm/Frontend/OpenMP/OMP.td  |  2 +
 12 files changed, 127 insertions(+), 22 deletions(-)

diff --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index 154ecfbaa4418..b29fce9bd9729 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -2173,18 +2173,62 @@ class OMPOrderedClause final
 /// This represents 'nowait' clause in the '#pragma omp ...' directive.
 ///
 /// \code
-/// #pragma omp for nowait
+/// #pragma omp for nowait (cond)
 /// \endcode
-/// In this example directive '#pragma omp for' has 'nowait' clause.
-class OMPNowaitClause final : public OMPNoChildClause {
+/// In this example directive '#pragma omp for' has simple 'nowait' clause with
+/// condition 'cond'.
+class OMPNowaitClause final : public OMPClause {
+  friend class OMPClauseReader;
+
+  /// Location of '('.
+  SourceLocation LParenLoc;
+
+  /// Condition of the 'nowait' clause.
+  Stmt *Condition = nullptr;
+
+  /// Set condition.
+  void setCondition(Expr *Cond) { Condition = Cond; }
+
 public:
-  /// Build 'nowait' clause.
+  /// Build 'nowait' clause with condition \a Cond.
   ///
+  /// \param Cond Condition of the clause.
   /// \param StartLoc Starting location of the clause.
+  /// \param LParenLoc Location of '('.
   /// \param EndLoc Ending location of the clause.
-  OMPNowaitClause(SourceLocation StartLoc = SourceLocation(),
-  SourceLocation EndLoc = SourceLocation())
-  : OMPNoChildClause(StartLoc, EndLoc) {}
+  OMPNowaitClause(Expr *Cond, SourceLocation StartLoc, SourceLocation 
LParenLoc,
+  SourceLocation EndLoc)
+  : OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc),
+LParenLoc(LParenLoc), Condition(Cond) {}
+
+  /// Build an empty clause.
+  OMPNowaitClause()
+  : OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) 
{}
+
+  /// Sets the location of '('.
+  void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; }
+
+  /// Returns the location of '('.
+  SourceLocation getLParenLoc() const { return LParenLoc; }
+
+  /// Returns condition.
+  Expr *getCondition() const { return cast_or_null(Condition); }
+
+  child_range children() { return child_range(&Condition, &Condition + 1); }
+
+  const_child_range children() const {
+return const_child_range(&Condition, &Condition + 1);
+  }
+
+  child_range used_children();
+  const_child_range used_children() const {
+auto Children = const_cast(this)->used_children();
+return const_child_range(Children.begin(), Children.end());
+  }
+
+  static bool classof(const OMPClause *T) {
+return T->getClauseKind() == llvm::omp::OMPC_nowait;
+  }
 };
 
 /// This represents 'untied' clause in the '#pragma omp ...' directive.
diff --git a/clang/include/clang/AST/RecursiveASTVisitor.h 
b/clang/include/clang/AST/RecursiveASTVisitor.h
index 560de7da9913a..52b940e7f3c0a 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -3466,7 +3466,8 @@ bool 
RecursiveASTVisitor::VisitOMPOrderedClause(OMPOrderedClause *C) {
 }
 
 template 
-bool RecursiveASTVisitor::VisitOMPNowaitClause(OMPNowaitClause *) {
+bool RecursiveASTVisitor::VisitOMPNowaitClause(OMPNowaitClause *C) {
+  TRY_TO(TraverseStmt(C->getCondition()));
   return true;
 }
 
diff --git a/clang/include/clang/Sema/SemaOpenMP.h 
b/clang/include/clang/Sema/SemaOpenMP.h
index 64f0cfa0676af..8af56c087a896 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -1001,8 +1001,10 @@ class SemaOpenMP : public SemaBase {
   OMPClause *ActOnOpenMPClause(OpenMPClauseKind Kind, SourceLocation StartLoc,
SourceLocation EndLoc);
   /// Called on well-formed 'nowait' clause.
-  OMPClause *ActOnOpenMPNowaitClause(SourceLocation StartLoc,
- SourceLocation EndLoc);
+  OMPClause *
+  ActOnOpenMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc,
+  SourceLoc

[clang] [cmake] Refactor clang unittest cmake (PR #133545)

2025-03-30 Thread Reid Kleckner via cfe-commits

https://github.com/rnk updated https://github.com/llvm/llvm-project/pull/133545

>From e662d8d9483fdf82030ddec6969bc89ae2404060 Mon Sep 17 00:00:00 2001
From: Reid Kleckner 
Date: Fri, 28 Mar 2025 16:49:09 -0700
Subject: [PATCH 1/2] [cmake] Refactor clang unittest cmake

Pass all the dependencies into add_clang_unittest. This is consistent
with how it is done for LLDB. I borrowed the same named argument list
structure from add_lldb_unittest. This is a necessary step towards
consolidating unit tests into fewer binaries, but seems like a good
refactoring in its own right.
---
 clang/unittests/AST/ByteCode/CMakeLists.txt   | 12 ++-
 clang/unittests/AST/CMakeLists.txt| 23 -
 clang/unittests/ASTMatchers/CMakeLists.txt| 22 -
 .../ASTMatchers/Dynamic/CMakeLists.txt| 18 +++
 clang/unittests/Analysis/CMakeLists.txt   | 18 +++
 .../Analysis/FlowSensitive/CMakeLists.txt | 18 +++
 clang/unittests/Basic/CMakeLists.txt  | 18 +++
 clang/unittests/CMakeLists.txt| 32 ---
 clang/unittests/CodeGen/CMakeLists.txt| 15 +++--
 clang/unittests/CrossTU/CMakeLists.txt| 12 ++-
 .../unittests/DirectoryWatcher/CMakeLists.txt | 11 ++-
 clang/unittests/Driver/CMakeLists.txt | 19 ---
 clang/unittests/Format/CMakeLists.txt | 11 ++-
 clang/unittests/Frontend/CMakeLists.txt   | 12 +++
 clang/unittests/Index/CMakeLists.txt  | 14 
 clang/unittests/InstallAPI/CMakeLists.txt |  9 ++
 clang/unittests/Interpreter/CMakeLists.txt| 25 +++
 .../Interpreter/ExceptionTests/CMakeLists.txt | 20 ++--
 clang/unittests/Lex/CMakeLists.txt| 16 +++---
 clang/unittests/Rewrite/CMakeLists.txt| 10 ++
 clang/unittests/Sema/CMakeLists.txt   | 18 +++
 clang/unittests/Serialization/CMakeLists.txt  | 17 --
 clang/unittests/StaticAnalyzer/CMakeLists.txt | 18 +++
 clang/unittests/Support/CMakeLists.txt| 11 ++-
 clang/unittests/Tooling/CMakeLists.txt| 28 +++-
 clang/unittests/Tooling/Syntax/CMakeLists.txt | 15 +++--
 clang/unittests/libclang/CMakeLists.txt   |  5 +--
 .../libclang/CrashTests/CMakeLists.txt|  5 +--
 28 files changed, 166 insertions(+), 286 deletions(-)

diff --git a/clang/unittests/AST/ByteCode/CMakeLists.txt 
b/clang/unittests/AST/ByteCode/CMakeLists.txt
index b862fb4834fbd..7ccadda2eeb26 100644
--- a/clang/unittests/AST/ByteCode/CMakeLists.txt
+++ b/clang/unittests/AST/ByteCode/CMakeLists.txt
@@ -2,19 +2,13 @@ add_clang_unittest(InterpTests
   BitcastBuffer.cpp
   Descriptor.cpp
   toAPValue.cpp
-  )
-
-clang_target_link_libraries(InterpTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
   clangFrontend
   clangSerialization
   clangTooling
-  )
-
-  target_link_libraries(InterpTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
-)
+  )
diff --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index bfa6082a6ffa4..f27d34e8a0719 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -1,10 +1,3 @@
-set(LLVM_LINK_COMPONENTS
-  FrontendOpenMP
-  Support
-  TargetParser
-  )
-
-
 add_subdirectory(ByteCode)
 
 add_clang_unittest(ASTTests
@@ -43,10 +36,7 @@ add_clang_unittest(ASTTests
   TemplateNameTest.cpp
   TypePrinterTest.cpp
   UnresolvedSetTest.cpp
-  )
-
-clang_target_link_libraries(ASTTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
@@ -54,11 +44,12 @@ clang_target_link_libraries(ASTTests
   clangLex
   clangSerialization
   clangTooling
-  )
-
-target_link_libraries(ASTTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
   LLVMTestingAnnotations
   LLVMTestingSupport
-)
+  LLVM_COMPONENTS
+  FrontendOpenMP
+  Support
+  TargetParser
+  )
diff --git a/clang/unittests/ASTMatchers/CMakeLists.txt 
b/clang/unittests/ASTMatchers/CMakeLists.txt
index 6a1e629d81b65..47bd5c108bb5a 100644
--- a/clang/unittests/ASTMatchers/CMakeLists.txt
+++ b/clang/unittests/ASTMatchers/CMakeLists.txt
@@ -1,31 +1,23 @@
-set(LLVM_LINK_COMPONENTS
-  FrontendOpenMP
-  Support
-  TargetParser
-  )
-
 add_clang_unittest(ASTMatchersTests
   ASTMatchersInternalTest.cpp
   ASTMatchersNodeTest.cpp
   ASTMatchersNarrowingTest.cpp
   ASTMatchersTraversalTest.cpp
   GtestMatchersTest.cpp
-  )
-
-clang_target_link_libraries(ASTMatchersTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
   clangFrontend
   clangSerialization
   clangTooling
-  )
-
-target_link_libraries(ASTMatchersTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
   LLVMTestingSupport
-)
+  LLVM_COMPONENTS
+  FrontendOpenMP
+  Support
+  TargetParser
+  )
 
 add_subdirectory(Dynamic)
diff --git a/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt 
b/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt
index 6d0e12bcb0759..b6db7ce62afe7 100644
--- a/clang

[clang-tools-extra] [clang-tidy] Detect string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp created 
https://github.com/llvm/llvm-project/pull/133636

…-literal

Fixes #133618

>From 2baffdbd656723b15370d3dd3560f3bd62262664 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Sun, 30 Mar 2025 12:24:32 +
Subject: [PATCH] [clang-tidy] Detect string literals in macros in
 modernize-raw-string-literal

Fixes #133618
---
 .../clang-tidy/modernize/RawStringLiteralCheck.cpp| 11 ++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 
 .../checkers/modernize/raw-string-literal.cpp |  3 ++-
 3 files changed, 12 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
index 24674a407cb36..1be0d6cc23935 100644
--- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
@@ -58,7 +58,7 @@ bool containsEscapedCharacters(const MatchFinder::MatchResult 
&Result,
   *Result.SourceManager, Result.Context->getLangOpts());
   StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager,
 Result.Context->getLangOpts());
-  if (Text.empty() || isRawStringLiteral(Text))
+  if (Text.empty() || !Text.contains('"') || isRawStringLiteral(Text))
 return false;
 
   return containsEscapes(Text, R"('\"?x01)");
@@ -156,14 +156,14 @@ static bool compareStringLength(StringRef Replacement,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
   return Replacement.size() <=
- Lexer::MeasureTokenLength(Literal->getBeginLoc(), SM, LangOpts);
+ Lexer::MeasureTokenLength(SM.getSpellingLoc(Literal->getBeginLoc()), 
SM, LangOpts);
 }
 
 void RawStringLiteralCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *Literal = Result.Nodes.getNodeAs("lit");
-  if (Literal->getBeginLoc().isMacroID())
-return;
   const SourceManager &SM = *Result.SourceManager;
+  if (SM.getSpellingLoc(Literal->getBeginLoc()).isMacroID())
+return;
   const LangOptions &LangOpts = getLangOpts();
   if (containsEscapedCharacters(Result, Literal, DisallowedChars)) {
 const std::string Replacement =
@@ -172,7 +172,8 @@ void RawStringLiteralCheck::check(const 
MatchFinder::MatchResult &Result) {
 compareStringLength(Replacement, Literal, SM, LangOpts)) {
   diag(Literal->getBeginLoc(),
"escaped string literal can be written as a raw string literal")
-  << FixItHint::CreateReplacement(Literal->getSourceRange(),
+  << 
FixItHint::CreateReplacement(SourceRange(SM.getSpellingLoc(Literal->getBeginLoc()),
+  
SM.getSpellingLoc(Literal->getEndLoc())),
   Replacement);
 }
   }
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6cb8d572d3a78..c7c5ac75986be 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -181,6 +181,10 @@ Changes in existing checks
   ` check to support math
   functions of different precisions.
 
+- Improved :doc:`modernize-raw-string-literal
+  ` check to detect string
+  literals passed into macros.
+
 - Improved :doc:`performance-move-const-arg
   ` check by fixing false
   negatives on ternary operators calling ``std::move``.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
index 5856b8882574a..fc4e966e92e07 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
@@ -105,7 +105,8 @@ char const *const StringizedMacroArgument = HAT(foo\\bar);
 
 #define SUBST(lit_) lit_
 char const *const MacroArgument = SUBST("foo\\bar");
-// FIXME: We should be able to replace this string literal macro argument
+// CHECK-MESSAGES: :[[@LINE-1]]:41: warning: {{.*}} can be written as a raw 
string literal
+// CHECK-FIXES: {{^}}char const *const MacroArgument = 
SUBST(R"(foo\bar)");{{$}}
 
 template 
 void fn(char const *const Arg) {

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add an option for editing enum trailing commas (PR #133576)

2025-03-30 Thread Björn Schäpers via cfe-commits


@@ -2214,6 +2214,21 @@ FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind 
Language) const {
 
 namespace {
 
+void replaceToken(const FormatToken &Token, FormatToken *Next,
+  const SourceManager &SourceMgr, tooling::Replacements 
&Result,
+  const char *Text = "") {

HazardyKnusperkeks wrote:

```suggestion
  StringRef Text = "") {
```


https://github.com/llvm/llvm-project/pull/133576
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -163,7 +163,11 @@ Options
 Semicolon-separated list of containers without their template parameters
 and some ``emplace``-like method of the container. Example:
 ``vector::emplace_back``. Those methods will be checked for improper use 
and
-the check will report when a temporary is unnecessarily created.
+the check will report when a temporary is unnecessarily created. Default

vbvictor wrote:

Yes, here i thought full list of methods will be big and not very informative.
https://github.com/llvm/llvm-project/blob/main/clang-tools-extra%2Fclang-tidy%2Fmodernize%2FUseEmplaceCheck.cpp#L118-L131

If it is okay, i can copy-paste that list in docs.

https://github.com/llvm/llvm-project/pull/133525
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [lldb] Reland: [clang] preserve class type sugar when taking pointer to member (PR #132401)

2025-03-30 Thread Matheus Izvekov via cfe-commits

mizvekov wrote:

> > @alexfh should be fixed by #133613
> 
> 
> 
> Thank you! The crash is resolved. Do you still need a reduced test case?

No worries, the tests included in PR already reproduce it.

https://github.com/llvm/llvm-project/pull/132401
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][C++20] Add support for Initialization Forwarding in structs and Nested Objects within modernize-use-emplace (PR #131969)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -305,6 +320,36 @@ void UseEmplaceCheck::registerMatchers(MatchFinder 
*Finder) {
   this);
 }
 
+static const CXXConstructExpr *unwrapToConstructorExpr(const Expr *E) {
+
+  while (E) {
+

vbvictor wrote:

```suggestion
```

https://github.com/llvm/llvm-project/pull/131969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options

vbvictor wrote:

Could you please rebase on fresh main, this must be added by 
https://github.com/llvm/llvm-project/commit/52639d69acbed0e49fd855c8c04cd9307405e2e6

https://github.com/llvm/llvm-project/pull/133639
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 created 
https://github.com/llvm/llvm-project/pull/133639

Fixes: #133425.

Add `WarnOnExplicitCast` to accept explicit cast to unsigned char and signed 
char.

>From c7f63c4d221055c375d363785277c2f8a6522284 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sun, 30 Mar 2025 14:57:05 +
Subject: [PATCH] [clang-tidy][bugprone-unintended-char-ostream-output] add
 `WarnOnExplicitCast` option

Fixes: #133425.

Add `WarnOnExplicitCast` to accept explicit cast to unsigned char and
signed char.
---
 .../UnintendedCharOstreamOutputCheck.cpp  | 11 +++--
 .../UnintendedCharOstreamOutputCheck.h|  1 +
 .../unintended-char-ostream-output.rst| 11 +
 ...nded-char-ostream-output-explicit-cast.cpp | 40 +++
 4 files changed, 60 insertions(+), 3 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
index 7250e4ccb8c69..b6fbb8bd0ffe4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
@@ -35,12 +35,13 @@ AST_MATCHER(Type, isChar) {
 
 UnintendedCharOstreamOutputCheck::UnintendedCharOstreamOutputCheck(
 StringRef Name, ClangTidyContext *Context)
-: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")) 
{
-}
+: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")),
+  WarnOnExplicitCast(Options.get("WarnOnExplicitCast", true)) {}
 void UnintendedCharOstreamOutputCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   if (CastTypeName.has_value())
 Options.store(Opts, "CastTypeName", CastTypeName.value());
+  Options.store(Opts, "WarnOnExplicitCast", WarnOnExplicitCast);
 }
 
 void UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
@@ -50,13 +51,17 @@ void 
UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
 // with char / unsigned char / signed char
 classTemplateSpecializationDecl(
 hasTemplateArgument(0, refersToType(isChar();
+  auto IsNumbericCharType =
+  hasType(hasUnqualifiedDesugaredType(isNumericChar()));
   Finder->addMatcher(
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("<<"),
   hasLHS(hasType(hasUnqualifiedDesugaredType(
   recordType(hasDeclaration(cxxRecordDecl(
   anyOf(BasicOstream, isDerivedFrom(BasicOstream,
-  hasRHS(hasType(hasUnqualifiedDesugaredType(isNumericChar()
+  hasRHS(WarnOnExplicitCast
+ ? expr(IsNumbericCharType)
+ : expr(IsNumbericCharType, unless(explicitCastExpr()
   .bind("x"),
   this);
 }
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
index 61ea623d139ea..2e1859bbe21a7 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
@@ -31,6 +31,7 @@ class UnintendedCharOstreamOutputCheck : public 
ClangTidyCheck {
 
 private:
   const std::optional CastTypeName;
+  const bool WarnOnExplicitCast;
 };
 
 } // namespace clang::tidy::bugprone
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
index ea1051847129b..a6196ae8c2448 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options
+---
+
+.. option:: WarnOnExplicitCast
+
+  When `WarnOnExplicitCast` is set to `false`, the check will not warn when
+  output of ostream is explicitly cast to a ``unsigned char`` or ``signed 
char``.
+  Attention: Explicit casting cannot solve the any problem if the value is not
+  character.
+  Default is `true`.
+
 .. option:: CastTypeName
 
   When `CastTypeName` is specified, the fix-it will use `CastTypeName` as the
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
new file mode 100644
index 0..9722fae39f129
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
@@ -0,0 +1,40 @@
+// RUN: %check

[clang] Improved the ``-Wtautological-overlap-compare`` diagnostics to warn a… (PR #133653)

2025-03-30 Thread Yutong Zhu via cfe-commits

https://github.com/YutongZhuu created 
https://github.com/llvm/llvm-project/pull/133653

This PR attempts to improve the diagnostics flag 
``-Wtautological-overlap-compare`` (#13473). I have added code to warn about 
float-point literals and character literals. I have also changed the warning 
message for the non-overlapping case to provide a more correct hint to the 
user. 

>From 00ad6a946ffd2aef0ab63210e9cc9f1ef661507e Mon Sep 17 00:00:00 2001
From: Yutong Zhu 
Date: Sun, 30 Mar 2025 15:53:12 -0400
Subject: [PATCH] Improved the ``-Wtautological-overlap-compare`` diagnostics
 to warn about overlapping and non-overlapping ranges involving character
 literals and floating-point literals.

---
 clang/docs/ReleaseNotes.rst   |   3 +
 .../clang/Basic/DiagnosticSemaKinds.td|   5 +-
 clang/lib/Analysis/CFG.cpp| 213 --
 clang/lib/Sema/AnalysisBasedWarnings.cpp  |   9 +-
 clang/test/Sema/warn-overlap.c| 108 +++--
 5 files changed, 243 insertions(+), 95 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..e6a31072567e7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -256,6 +256,9 @@ Improvements to Clang's diagnostics
 
 - Improve the diagnostics for shadows template parameter to report correct 
location (#GH129060).
 
+- Improved the ``-Wtautological-overlap-compare`` diagnostics to warn about 
overlapping and non-overlapping ranges involving character literals and 
floating-point literals. 
+  The warning message for non-overlapping cases has also been improved 
(#GH13473).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 86c9c955c1c78..493a66df982c4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10398,7 +10398,10 @@ def warn_tautological_negation_or_compare: Warning<
   "'||' of a value and its negation always evaluates to true">,
   InGroup, DefaultIgnore;
 def warn_tautological_overlap_comparison : Warning<
-  "overlapping comparisons always evaluate to %select{false|true}0">,
+  "overlapping comparisons always evaluate to true">,
+  InGroup, DefaultIgnore;
+def warn_tautological_non_overlap_comparison : Warning<
+  "non-overlapping comparisons always evaluate to false">,
   InGroup, DefaultIgnore;
 def warn_depr_array_comparison : Warning<
   "comparison between two arrays is deprecated; "
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 9af1e915482da..c6b7c49d4cb4a 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -70,13 +70,11 @@ static SourceLocation GetEndLoc(Decl *D) {
   return D->getLocation();
 }
 
-/// Returns true on constant values based around a single IntegerLiteral.
-/// Allow for use of parentheses, integer casts, and negative signs.
-/// FIXME: it would be good to unify this function with
-/// getIntegerLiteralSubexpressionValue at some point given the similarity
-/// between the functions.
+/// Returns true on constant values based around a single IntegerLiteral,
+/// CharacterLiteral, or FloatingLiteral. Allow for use of parentheses, integer
+/// casts, and negative signs.
 
-static bool IsIntegerLiteralConstantExpr(const Expr *E) {
+static bool IsLiteralConstantExpr(const Expr *E) {
   // Allow parentheses
   E = E->IgnoreParens();
 
@@ -93,16 +91,16 @@ static bool IsIntegerLiteralConstantExpr(const Expr *E) {
   return false;
 E = UO->getSubExpr();
   }
-
-  return isa(E);
+  return isa(E) || isa(E) ||
+ isa(E);
 }
 
 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an 
IntegerLiteral
 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
 /// returns nullptr.
-static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
+static const Expr *tryTransformToLiteralConstants(const Expr *E) {
   E = E->IgnoreParens();
-  if (IsIntegerLiteralConstantExpr(E))
+  if (IsLiteralConstantExpr(E))
 return E;
   if (auto *DR = dyn_cast(E->IgnoreParenImpCasts()))
 return isa(DR->getDecl()) ? DR : nullptr;
@@ -119,7 +117,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   BinaryOperatorKind Op = B->getOpcode();
 
   const Expr *MaybeDecl = B->getLHS();
-  const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
+  const Expr *Constant = tryTransformToLiteralConstants(B->getRHS());
   // Expr looked like `0 == Foo` instead of `Foo == 0`
   if (Constant == nullptr) {
 // Flip the operator
@@ -133,7 +131,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   Op = BO_GE;
 
 MaybeDecl = B->getRHS();
-Constant = tryTransformToIntOrEnumConstant(B->getLHS());
+Constant = tryTransformToLiteralConstants(B->getLHS());
   }
 
   return std::make_tuple(MaybeDecl, Op, C

[clang-tools-extra] [clang-tidy] Fix broken HeaderFilterRegex when read from config file (PR #133582)

2025-03-30 Thread Carlos Galvez via cfe-commits


@@ -571,17 +560,30 @@ void 
ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
   }
 
   StringRef FileName(File->getName());
-  LastErrorRelatesToUserCode =
-  LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
-  (HeaderFilter &&
-   (HeaderFilter->match(FileName) &&
-!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName;
+  LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
+   Sources.isInMainFile(Location) ||
+   (getHeaderFilter()->match(FileName) &&
+!getExcludeHeaderFilter()->match(FileName));
 
   unsigned LineNumber = Sources.getExpansionLineNumber(Location);
   LastErrorPassesLineFilter =
   LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
 }
 
+llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
+  if (!HeaderFilter)
+HeaderFilter =
+std::make_unique(*Context.getOptions().HeaderFilterRegex);

carlosgalvezp wrote:

Thanks, good point. That was also changed in the original PR so I will revert 
that too. I wonder if it makes more sense to do a full revert and reland with 
the right changes instead. But since the PR is 1 year old it might be tricky.

https://github.com/llvm/llvm-project/pull/133582
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

I believe it would be good to wait before the discussion settled in the issue 
ticket. Personally I think this should be solved with a `NOLINT` suppression 
instead of adding a new feature which just adds confusion.

https://github.com/llvm/llvm-project/pull/133639
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread Congcong Cai via cfe-commits


@@ -105,7 +105,8 @@ char const *const StringizedMacroArgument = HAT(foo\\bar);
 
 #define SUBST(lit_) lit_

HerrCai0907 wrote:

what about concat string in macro?
e.g.
```
#define SUBST(a,b) a#b
char const *const MacroArgument = SUBST("foo\\bar","cd");
```

https://github.com/llvm/llvm-project/pull/133636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add an option for editing enum trailing commas (PR #133576)

2025-03-30 Thread Björn Schäpers via cfe-commits


@@ -2214,6 +2214,21 @@ FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind 
Language) const {
 
 namespace {
 
+void replaceToken(const FormatToken &Token, FormatToken *Next,
+  const SourceManager &SourceMgr, tooling::Replacements 
&Result,
+  const char *Text = "") {

HazardyKnusperkeks wrote:

This is a local function and we use it with string literals. And if I looked 
correctly `tooling::Replacement` takes an `StringRef`.

https://github.com/llvm/llvm-project/pull/133576
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Add linker options to support statical linking to shared flang-rt on AIX. (PR #131822)

2025-03-30 Thread Daniel Chen via cfe-commits


@@ -127,9 +127,19 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   }
 
   // Force static linking when "-static" is present.
-  if (Args.hasArg(options::OPT_static))
+  if (Args.hasArg(options::OPT_static)) {
 CmdArgs.push_back("-bnso");
 
+if (D.IsFlangMode()) {
+  // The folllowing linker options are needed to statically link to the
+  // shared libflang_rt.runtime.a on AIX
+  CmdArgs.push_back("-bI:/usr/lib/syscalls.exp");
+  CmdArgs.push_back("-bI:/usr/lib/aio.exp");
+  CmdArgs.push_back("-bI:/usr/lib/threads.exp");
+  CmdArgs.push_back("-lcrypt");
+}

DanielCChen wrote:

These extra options will be linked in when `flang` is the invocation driver. As 
the driver code is written in PR #131041, `libflang_rt.runtime.a` is always 
linked in with the full path name no matter if it is static or shared.


https://github.com/llvm/llvm-project/pull/131822
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix broken HeaderFilterRegex when read from config file (PR #133582)

2025-03-30 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp updated 
https://github.com/llvm/llvm-project/pull/133582

>From c2b1748bedf97f158a42ada308e22b1a4392ec9a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Sat, 29 Mar 2025 11:55:02 +
Subject: [PATCH] [clang-tidy] Fix broken HeaderFilterRegex when read from
 config file

PR https://github.com/llvm/llvm-project/pull/91400 broke the usage
of HeaderFilterRegex via config file, because it is now created at a
different point in the execution and leads to a different value.

The result of that is that using HeaderFilterRegex only in the config
file does NOT work, in other words clang-tidy stops triggering warnings
on header files, thereby losing a lot of coverage.

This patch reverts the logic so that the header filter is created
upon calling the getHeaderFilter() function.

Additionally, this patch adds 2 unit tests to prevent regressions in
the future:

- One of them, "simple", tests the most basic use case with a single
  top-level .clang-tidy file.

- The second one, "inheritance", demonstrates that the subfolder only
  gets warnings from headers within it, and not from parent headers.

Fixes #118009, #121969, #133453
---
 .../ClangTidyDiagnosticConsumer.cpp   | 36 ++-
 .../clang-tidy/ClangTidyDiagnosticConsumer.h  |  4 +++
 .../clang-tidy/ClangTidyOptions.cpp   |  4 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 ++
 .../inheritance/.clang-tidy   |  1 +
 .../inheritance/foo.cpp   |  3 ++
 .../inheritance/foo.h |  1 +
 .../inheritance/subfolder/.clang-tidy |  2 ++
 .../inheritance/subfolder/bar.cpp |  8 +
 .../inheritance/subfolder/bar.h   |  1 +
 .../simple/.clang-tidy|  1 +
 .../simple/foo.cpp|  3 ++
 .../simple/foo.h  |  1 +
 13 files changed, 49 insertions(+), 19 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/foo.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/foo.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/bar.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/bar.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/foo.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/foo.h

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 4c75b42270114..71e852545203e 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -311,18 +311,7 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
   RemoveIncompatibleErrors(RemoveIncompatibleErrors),
   GetFixesFromNotes(GetFixesFromNotes),
-  EnableNolintBlocks(EnableNolintBlocks) {
-
-  if (Context.getOptions().HeaderFilterRegex &&
-  !Context.getOptions().HeaderFilterRegex->empty())
-HeaderFilter =
-std::make_unique(*Context.getOptions().HeaderFilterRegex);
-
-  if (Context.getOptions().ExcludeHeaderFilterRegex &&
-  !Context.getOptions().ExcludeHeaderFilterRegex->empty())
-ExcludeHeaderFilter = std::make_unique(
-*Context.getOptions().ExcludeHeaderFilterRegex);
-}
+  EnableNolintBlocks(EnableNolintBlocks) {}
 
 void ClangTidyDiagnosticConsumer::finalizeLastError() {
   if (!Errors.empty()) {
@@ -571,17 +560,30 @@ void 
ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
   }
 
   StringRef FileName(File->getName());
-  LastErrorRelatesToUserCode =
-  LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
-  (HeaderFilter &&
-   (HeaderFilter->match(FileName) &&
-!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName;
+  LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
+   Sources.isInMainFile(Location) ||
+   (getHeaderFilter()->match(FileName) &&
+!getExcludeHeaderFilter()->match(FileName));
 
   unsigned LineNumber = Sources.getExpansionLineNumber(Location);
   LastErr

[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Carlos Galvez via cfe-commits


@@ -163,7 +163,11 @@ Options
 Semicolon-separated list of containers without their template parameters
 and some ``emplace``-like method of the container. Example:
 ``vector::emplace_back``. Those methods will be checked for improper use 
and
-the check will report when a temporary is unnecessarily created.
+the check will report when a temporary is unnecessarily created. Default

carlosgalvezp wrote:

Since this is a semicolon-separated list of strings, we typically write: 
"Default is ``vector;deque;forward_list...``". This helps the user understand 
what format they should use if they'd like to use something else.

https://github.com/llvm/llvm-project/pull/133525
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] clang/HIP: Use regex for final path separator in hip-partial-link, again (PR #130371)

2025-03-30 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`llvm-clang-x86_64-win-fast` running on `as-builder-3` while building `clang` 
at step 7 "test-build-unified-tree-check-llvm-unit".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/2/builds/18764


Here is the relevant piece of the build log for the reference

```
Step 7 (test-build-unified-tree-check-llvm-unit) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/48/86' 
FAILED 
Script(shard):
--
GTEST_OUTPUT=json:C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-6248-48-86.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=86 GTEST_SHARD_INDEX=48 
C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\unittests\Support\.\SupportTests.exe
--

Script:
--
C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\build\unittests\Support\.\SupportTests.exe
 --gtest_filter=Caching.WriteAfterCommit
--
C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\llvm\unittests\Support\Caching.cpp(103):
 error: Value of: AddStream
  Actual: false
Expected: true


C:\buildbot\as-builder-3\llvm-clang-x86_64-win-fast\llvm-project\llvm\unittests\Support\Caching.cpp:103
Value of: AddStream
  Actual: false
Expected: true






```



https://github.com/llvm/llvm-project/pull/130371
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Carlos Galvez via cfe-commits


@@ -163,7 +163,11 @@ Options
 Semicolon-separated list of containers without their template parameters
 and some ``emplace``-like method of the container. Example:
 ``vector::emplace_back``. Those methods will be checked for improper use 
and
-the check will report when a temporary is unnecessarily created.
+the check will report when a temporary is unnecessarily created. Default

carlosgalvezp wrote:

Yeah that can create some unnecessary maintenance work. Maybe we don't need to 
write it out explicitly, but simply say "all STL containers with such a member 
function are supported by default".

https://github.com/llvm/llvm-project/pull/133525
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Baranov Victor via cfe-commits

https://github.com/vbvictor edited 
https://github.com/llvm/llvm-project/pull/133639
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][C++20] Add support for Initialization Forwarding in structs and Nested Objects within modernize-use-emplace (PR #131969)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -1285,11 +1289,9 @@ void testBracedInitTemporaries() {
 
 
   // These should not be noticed or fixed; after the correction, the code won't
-  // compile.
+  // compile in version previous to C++20.

vbvictor wrote:

This is not needed anymore since those cases moved to another place?
```suggestion
  // compile.
```

https://github.com/llvm/llvm-project/pull/131969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][C++20] Add support for Initialization Forwarding in structs and Nested Objects within modernize-use-emplace (PR #131969)

2025-03-30 Thread Baranov Victor via cfe-commits

https://github.com/vbvictor edited 
https://github.com/llvm/llvm-project/pull/131969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][C++20] Add support for Initialization Forwarding in structs and Nested Objects within modernize-use-emplace (PR #131969)

2025-03-30 Thread David Rivera via cfe-commits


@@ -1285,11 +1289,9 @@ void testBracedInitTemporaries() {
 
 
   // These should not be noticed or fixed; after the correction, the code won't
-  // compile.
+  // compile in version previous to C++20.

RiverDave wrote:

Indeed, forgot to delete that, thx

https://github.com/llvm/llvm-project/pull/131969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [NFC][clang-tidy] Add type annotations to check_clang_tidy (PR #133140)

2025-03-30 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 approved this pull request.


https://github.com/llvm/llvm-project/pull/133140
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][C++20] Add support for Initialization Forwarding in structs and Nested Objects within modernize-use-emplace (PR #131969)

2025-03-30 Thread David Rivera via cfe-commits

https://github.com/RiverDave edited 
https://github.com/llvm/llvm-project/pull/131969
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Baranov Victor via cfe-commits

vbvictor wrote:

@carlosgalvezp, Can you please help land this PR? Thank you

https://github.com/llvm/llvm-project/pull/133525
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp closed 
https://github.com/llvm/llvm-project/pull/133525
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread Carlos Galvez via cfe-commits


@@ -105,7 +105,8 @@ char const *const StringizedMacroArgument = HAT(foo\\bar);
 
 #define SUBST(lit_) lit_

carlosgalvezp wrote:

Good point, this doesn't work. It wants to create a replacement 
`"R\"(foo\\bar\\baz\\bazz\\foo\"cd\")\""` which is non sense.

Most likely macros should be handled in a `PPCallback` instead, thus it's 
better to drop this PR and implement this feature there instead.

https://github.com/llvm/llvm-project/pull/133636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][NFC][doc] improve "options" sections of `bugprone-` and `modernize-` checks (PR #133525)

2025-03-30 Thread Baranov Victor via cfe-commits

https://github.com/vbvictor updated 
https://github.com/llvm/llvm-project/pull/133525

>From 9b88fc69e06d08fd06b60af24b5a9c12749185ef Mon Sep 17 00:00:00 2001
From: Victor Baranov 
Date: Sat, 29 Mar 2025 00:46:22 +0300
Subject: [PATCH 1/3] improve docs options of `bugprone-` and `modernize-`
 checks

---
 .../docs/clang-tidy/checks/bugprone/assert-side-effect.rst  | 1 +
 .../checks/bugprone/capturing-this-in-member-variable.rst   | 3 +++
 .../docs/clang-tidy/checks/bugprone/signed-char-misuse.rst  | 5 -
 .../clang-tidy/checks/bugprone/suspicious-enum-usage.rst| 1 +
 .../checks/bugprone/suspicious-stringview-data-usage.rst| 3 +++
 .../clang-tidy/checks/bugprone/too-small-loop-variable.rst  | 3 +++
 .../checks/bugprone/unhandled-self-assignment.rst   | 3 +++
 .../checks/bugprone/unintended-char-ostream-output.rst  | 3 +++
 .../docs/clang-tidy/checks/modernize/avoid-bind.rst | 3 ++-
 .../docs/clang-tidy/checks/modernize/avoid-c-arrays.rst | 3 +++
 .../docs/clang-tidy/checks/modernize/loop-convert.rst   | 3 +++
 .../docs/clang-tidy/checks/modernize/make-shared.rst| 2 +-
 .../docs/clang-tidy/checks/modernize/make-unique.rst| 2 +-
 .../docs/clang-tidy/checks/modernize/raw-string-literal.rst | 3 +++
 .../docs/clang-tidy/checks/modernize/use-emplace.rst| 6 +-
 15 files changed, 39 insertions(+), 5 deletions(-)

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/assert-side-effect.rst 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/assert-side-effect.rst
index 1355afae92e4f..3ca712b958d04 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/assert-side-effect.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/assert-side-effect.rst
@@ -15,6 +15,7 @@ Options
 .. option:: AssertMacros
 
A comma-separated list of the names of assert macros to be checked.
+   Default is `assert,NSAssert,NSCAssert`.
 
 .. option:: CheckFunctionCalls
 
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/capturing-this-in-member-variable.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/capturing-this-in-member-variable.rst
index bb75e9239d9b5..b09d7d5fce959 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/capturing-this-in-member-variable.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/capturing-this-in-member-variable.rst
@@ -32,6 +32,9 @@ Possible fixes:
 object types.
   - passing ``this`` pointer as parameter 
 
+Options
+---
+
 .. option:: FunctionWrapperTypes
 
   A semicolon-separated list of names of types. Used to specify function
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/signed-char-misuse.rst 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/signed-char-misuse.rst
index 72860e8cf2a1d..4edbad5eac81b 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/bugprone/signed-char-misuse.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/bugprone/signed-char-misuse.rst
@@ -104,13 +104,16 @@ so both arguments will have the same type.
 return false;
   }
 
+Options
+---
+
 .. option:: CharTypdefsToIgnore
 
   A semicolon-separated list of typedef names. In this list, we can list
   typedefs for ``char`` or ``signed char``, which will be ignored by the
   check. This is useful when a typedef introduces an integer alias like
   ``sal_Int8`` or ``int8_t``. In this case, human misinterpretation is not
-  an issue.
+  an issue. Default is an empty string.
 
 .. option:: DiagnoseSignedUnsignedCharComparisons
 
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-enum-usage.rst 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-enum-usage.rst
index e87172414a23e..94f29ee11ee39 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-enum-usage.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-enum-usage.rst
@@ -71,6 +71,7 @@ Examples:
 
 Options
 ---
+
 .. option:: StrictMode
 
Default value: 0.
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.rst
index 9b38d83601810..de10da21e8442 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/suspicious-stringview-data-usage.rst
@@ -43,6 +43,9 @@ lead to a compilation error due to the explicit nature of the 
``std::string``
 constructor. Consequently, developers might opt for ``sv.data()`` to resolve 
the
 compilation error, albeit introducing potential hazards as discussed.
 
+Options
+---
+
 .. option:: StringViewTypes
 
   Option allows users to specify custom string view-like types for analysis. It
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/too-small-loop-variable.rst 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/too-small-loop-variable.rst
index 2c3de

[clang-tools-extra] [clang-tidy] Detect string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

This approach does not scale for macros, it should rather be implemented in a 
`PPCallback` instead.

https://github.com/llvm/llvm-project/pull/133636
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp closed 
https://github.com/llvm/llvm-project/pull/133636
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Carlos Galvez (carlosgalvezp)


Changes

…-literal

Fixes #133618

---
Full diff: https://github.com/llvm/llvm-project/pull/133636.diff


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
(+6-5) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp 
(+2-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
index 24674a407cb36..1be0d6cc23935 100644
--- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
@@ -58,7 +58,7 @@ bool containsEscapedCharacters(const MatchFinder::MatchResult 
&Result,
   *Result.SourceManager, Result.Context->getLangOpts());
   StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager,
 Result.Context->getLangOpts());
-  if (Text.empty() || isRawStringLiteral(Text))
+  if (Text.empty() || !Text.contains('"') || isRawStringLiteral(Text))
 return false;
 
   return containsEscapes(Text, R"('\"?x01)");
@@ -156,14 +156,14 @@ static bool compareStringLength(StringRef Replacement,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
   return Replacement.size() <=
- Lexer::MeasureTokenLength(Literal->getBeginLoc(), SM, LangOpts);
+ Lexer::MeasureTokenLength(SM.getSpellingLoc(Literal->getBeginLoc()), 
SM, LangOpts);
 }
 
 void RawStringLiteralCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *Literal = Result.Nodes.getNodeAs("lit");
-  if (Literal->getBeginLoc().isMacroID())
-return;
   const SourceManager &SM = *Result.SourceManager;
+  if (SM.getSpellingLoc(Literal->getBeginLoc()).isMacroID())
+return;
   const LangOptions &LangOpts = getLangOpts();
   if (containsEscapedCharacters(Result, Literal, DisallowedChars)) {
 const std::string Replacement =
@@ -172,7 +172,8 @@ void RawStringLiteralCheck::check(const 
MatchFinder::MatchResult &Result) {
 compareStringLength(Replacement, Literal, SM, LangOpts)) {
   diag(Literal->getBeginLoc(),
"escaped string literal can be written as a raw string literal")
-  << FixItHint::CreateReplacement(Literal->getSourceRange(),
+  << 
FixItHint::CreateReplacement(SourceRange(SM.getSpellingLoc(Literal->getBeginLoc()),
+  
SM.getSpellingLoc(Literal->getEndLoc())),
   Replacement);
 }
   }
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6cb8d572d3a78..c7c5ac75986be 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -181,6 +181,10 @@ Changes in existing checks
   ` check to support math
   functions of different precisions.
 
+- Improved :doc:`modernize-raw-string-literal
+  ` check to detect string
+  literals passed into macros.
+
 - Improved :doc:`performance-move-const-arg
   ` check by fixing false
   negatives on ternary operators calling ``std::move``.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
index 5856b8882574a..fc4e966e92e07 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
@@ -105,7 +105,8 @@ char const *const StringizedMacroArgument = HAT(foo\\bar);
 
 #define SUBST(lit_) lit_
 char const *const MacroArgument = SUBST("foo\\bar");
-// FIXME: We should be able to replace this string literal macro argument
+// CHECK-MESSAGES: :[[@LINE-1]]:41: warning: {{.*}} can be written as a raw 
string literal
+// CHECK-FIXES: {{^}}char const *const MacroArgument = 
SUBST(R"(foo\bar)");{{$}}
 
 template 
 void fn(char const *const Arg) {

``




https://github.com/llvm/llvm-project/pull/133636
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Carlos Galvez (carlosgalvezp)


Changes

…-literal

Fixes #133618

---
Full diff: https://github.com/llvm/llvm-project/pull/133636.diff


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
(+6-5) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp 
(+2-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
index 24674a407cb36..1be0d6cc23935 100644
--- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
@@ -58,7 +58,7 @@ bool containsEscapedCharacters(const MatchFinder::MatchResult 
&Result,
   *Result.SourceManager, Result.Context->getLangOpts());
   StringRef Text = Lexer::getSourceText(CharRange, *Result.SourceManager,
 Result.Context->getLangOpts());
-  if (Text.empty() || isRawStringLiteral(Text))
+  if (Text.empty() || !Text.contains('"') || isRawStringLiteral(Text))
 return false;
 
   return containsEscapes(Text, R"('\"?x01)");
@@ -156,14 +156,14 @@ static bool compareStringLength(StringRef Replacement,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
   return Replacement.size() <=
- Lexer::MeasureTokenLength(Literal->getBeginLoc(), SM, LangOpts);
+ Lexer::MeasureTokenLength(SM.getSpellingLoc(Literal->getBeginLoc()), 
SM, LangOpts);
 }
 
 void RawStringLiteralCheck::check(const MatchFinder::MatchResult &Result) {
   const auto *Literal = Result.Nodes.getNodeAs("lit");
-  if (Literal->getBeginLoc().isMacroID())
-return;
   const SourceManager &SM = *Result.SourceManager;
+  if (SM.getSpellingLoc(Literal->getBeginLoc()).isMacroID())
+return;
   const LangOptions &LangOpts = getLangOpts();
   if (containsEscapedCharacters(Result, Literal, DisallowedChars)) {
 const std::string Replacement =
@@ -172,7 +172,8 @@ void RawStringLiteralCheck::check(const 
MatchFinder::MatchResult &Result) {
 compareStringLength(Replacement, Literal, SM, LangOpts)) {
   diag(Literal->getBeginLoc(),
"escaped string literal can be written as a raw string literal")
-  << FixItHint::CreateReplacement(Literal->getSourceRange(),
+  << 
FixItHint::CreateReplacement(SourceRange(SM.getSpellingLoc(Literal->getBeginLoc()),
+  
SM.getSpellingLoc(Literal->getEndLoc())),
   Replacement);
 }
   }
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6cb8d572d3a78..c7c5ac75986be 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -181,6 +181,10 @@ Changes in existing checks
   ` check to support math
   functions of different precisions.
 
+- Improved :doc:`modernize-raw-string-literal
+  ` check to detect string
+  literals passed into macros.
+
 - Improved :doc:`performance-move-const-arg
   ` check by fixing false
   negatives on ternary operators calling ``std::move``.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
index 5856b8882574a..fc4e966e92e07 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
@@ -105,7 +105,8 @@ char const *const StringizedMacroArgument = HAT(foo\\bar);
 
 #define SUBST(lit_) lit_
 char const *const MacroArgument = SUBST("foo\\bar");
-// FIXME: We should be able to replace this string literal macro argument
+// CHECK-MESSAGES: :[[@LINE-1]]:41: warning: {{.*}} can be written as a raw 
string literal
+// CHECK-FIXES: {{^}}char const *const MacroArgument = 
SUBST(R"(foo\bar)");{{$}}
 
 template 
 void fn(char const *const Arg) {

``




https://github.com/llvm/llvm-project/pull/133636
___
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 string literals in macros in modernize-raw-string… (PR #133636)

2025-03-30 Thread via cfe-commits

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 HEAD~1 HEAD --extensions cpp -- 
clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
clang-tools-extra/test/clang-tidy/checkers/modernize/raw-string-literal.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
index 1be0d6cc2..b7fad9193 100644
--- a/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/RawStringLiteralCheck.cpp
@@ -156,7 +156,8 @@ static bool compareStringLength(StringRef Replacement,
 const SourceManager &SM,
 const LangOptions &LangOpts) {
   return Replacement.size() <=
- Lexer::MeasureTokenLength(SM.getSpellingLoc(Literal->getBeginLoc()), 
SM, LangOpts);
+ Lexer::MeasureTokenLength(SM.getSpellingLoc(Literal->getBeginLoc()),
+   SM, LangOpts);
 }
 
 void RawStringLiteralCheck::check(const MatchFinder::MatchResult &Result) {
@@ -172,9 +173,10 @@ void RawStringLiteralCheck::check(const 
MatchFinder::MatchResult &Result) {
 compareStringLength(Replacement, Literal, SM, LangOpts)) {
   diag(Literal->getBeginLoc(),
"escaped string literal can be written as a raw string literal")
-  << 
FixItHint::CreateReplacement(SourceRange(SM.getSpellingLoc(Literal->getBeginLoc()),
-  
SM.getSpellingLoc(Literal->getEndLoc())),
-  Replacement);
+  << FixItHint::CreateReplacement(
+ SourceRange(SM.getSpellingLoc(Literal->getBeginLoc()),
+ SM.getSpellingLoc(Literal->getEndLoc())),
+ Replacement);
 }
   }
 }

``




https://github.com/llvm/llvm-project/pull/133636
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #133425.

Add `WarnOnExplicitCast` to accept explicit cast to unsigned char and signed 
char.

---
Full diff: https://github.com/llvm/llvm-project/pull/133639.diff


4 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp 
(+8-3) 
- (modified) 
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h (+1) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
 (+11) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
 (+40) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
index 7250e4ccb8c69..b6fbb8bd0ffe4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
@@ -35,12 +35,13 @@ AST_MATCHER(Type, isChar) {
 
 UnintendedCharOstreamOutputCheck::UnintendedCharOstreamOutputCheck(
 StringRef Name, ClangTidyContext *Context)
-: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")) 
{
-}
+: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")),
+  WarnOnExplicitCast(Options.get("WarnOnExplicitCast", true)) {}
 void UnintendedCharOstreamOutputCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   if (CastTypeName.has_value())
 Options.store(Opts, "CastTypeName", CastTypeName.value());
+  Options.store(Opts, "WarnOnExplicitCast", WarnOnExplicitCast);
 }
 
 void UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
@@ -50,13 +51,17 @@ void 
UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
 // with char / unsigned char / signed char
 classTemplateSpecializationDecl(
 hasTemplateArgument(0, refersToType(isChar();
+  auto IsNumbericCharType =
+  hasType(hasUnqualifiedDesugaredType(isNumericChar()));
   Finder->addMatcher(
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("<<"),
   hasLHS(hasType(hasUnqualifiedDesugaredType(
   recordType(hasDeclaration(cxxRecordDecl(
   anyOf(BasicOstream, isDerivedFrom(BasicOstream,
-  hasRHS(hasType(hasUnqualifiedDesugaredType(isNumericChar()
+  hasRHS(WarnOnExplicitCast
+ ? expr(IsNumbericCharType)
+ : expr(IsNumbericCharType, unless(explicitCastExpr()
   .bind("x"),
   this);
 }
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
index 61ea623d139ea..2e1859bbe21a7 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
@@ -31,6 +31,7 @@ class UnintendedCharOstreamOutputCheck : public 
ClangTidyCheck {
 
 private:
   const std::optional CastTypeName;
+  const bool WarnOnExplicitCast;
 };
 
 } // namespace clang::tidy::bugprone
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
index ea1051847129b..a6196ae8c2448 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options
+---
+
+.. option:: WarnOnExplicitCast
+
+  When `WarnOnExplicitCast` is set to `false`, the check will not warn when
+  output of ostream is explicitly cast to a ``unsigned char`` or ``signed 
char``.
+  Attention: Explicit casting cannot solve the any problem if the value is not
+  character.
+  Default is `true`.
+
 .. option:: CastTypeName
 
   When `CastTypeName` is specified, the fix-it will use `CastTypeName` as the
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
new file mode 100644
index 0..9722fae39f129
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
@@ -0,0 +1,40 @@
+// RUN: %check_clang_tidy %s bugprone-unintended-char-ostream-output %t 
-check-suffix=WARN-EXPLICIT-CAST
+// RUN: %check_clang_tidy %s bugprone-unintended-char-ostream-output %t \
+// RUN:   -config='{CheckOptions: { \
+// RUN:   b

[clang-tools-extra] [clang-tidy] Fix broken HeaderFilterRegex when read from config file (PR #133582)

2025-03-30 Thread Congcong Cai via cfe-commits


@@ -571,17 +560,30 @@ void 
ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
   }
 
   StringRef FileName(File->getName());
-  LastErrorRelatesToUserCode =
-  LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
-  (HeaderFilter &&
-   (HeaderFilter->match(FileName) &&
-!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName;
+  LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
+   Sources.isInMainFile(Location) ||
+   (getHeaderFilter()->match(FileName) &&
+!getExcludeHeaderFilter()->match(FileName));
 
   unsigned LineNumber = Sources.getExpansionLineNumber(Location);
   LastErrorPassesLineFilter =
   LastErrorPassesLineFilter || passesLineFilter(FileName, LineNumber);
 }
 
+llvm::Regex *ClangTidyDiagnosticConsumer::getHeaderFilter() {
+  if (!HeaderFilter)
+HeaderFilter =
+std::make_unique(*Context.getOptions().HeaderFilterRegex);

HerrCai0907 wrote:

HeaderFilterRegex is `std::optional<>`. How to handle `HeaderFilterRegex` is 
`std::nullopt`?

https://github.com/llvm/llvm-project/pull/133582
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -7353,6 +7354,69 @@ void Sema::CheckCompletedCXXClass(Scope *S, 
CXXRecordDecl *Record) {
 else if (Record->hasAttr())
   checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
   }
+
+  llvm::SmallVector TypeAwareNewDecls;
+  llvm::SmallVector TypeAwareDeleteDecls;
+  llvm::SmallVector TypeAwareArrayNewDecls;
+  llvm::SmallVector TypeAwareArrayDeleteDecls;
+
+  for (auto *D : Record->decls()) {
+const FunctionDecl *FnDecl = nullptr;
+if (auto *FTD = dyn_cast(D))
+  FnDecl = FTD->getTemplatedDecl();
+else if (auto *FD = dyn_cast(D))
+  FnDecl = FD;
+if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
+  continue;
+switch (FnDecl->getOverloadedOperator()) {
+case OO_New:
+  TypeAwareNewDecls.push_back(FnDecl);
+  break;
+case OO_Array_New:
+  TypeAwareArrayNewDecls.push_back(FnDecl);
+  break;
+case OO_Delete:
+  TypeAwareDeleteDecls.push_back(FnDecl);
+  break;
+case OO_Array_Delete:
+  TypeAwareArrayDeleteDecls.push_back(FnDecl);
+  break;
+default:
+  continue;
+}
+  }
+  auto CheckMismatchedTypeAwareAllocators =
+  [this,
+   Record](OverloadedOperatorKind NewKind,
+   const llvm::SmallVector &NewDecls,
+   OverloadedOperatorKind DeleteKind,
+   const llvm::SmallVector &DeleteDecls) {
+if (NewDecls.empty() == DeleteDecls.empty())
+  return;
+DeclarationName FoundOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? DeleteKind : NewKind);
+DeclarationName MissingOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? NewKind : DeleteKind);
+Diag(Record->getLocation(),
+ diag::err_type_aware_allocator_missing_matching_operator)
+<< FoundOperator << Context.getRecordType(Record)
+<< MissingOperator;

mizvekov wrote:

Do we need to spell the record's type in this diagnostic, given that we are 
pointing to it?
This same comment applies in other places in this PR.

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options
+---
+
+.. option:: WarnOnExplicitCast
+
+  When `WarnOnExplicitCast` is set to `false`, the check will not warn when
+  output of ostream is explicitly cast to a ``unsigned char`` or ``signed 
char``.
+  Attention: Explicit casting cannot solve the any problem if the value is not

vbvictor wrote:

```suggestion
  Attention: Explicit casting cannot solve any problem if the value is not
```

https://github.com/llvm/llvm-project/pull/133639
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread Baranov Victor via cfe-commits


@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options
+---
+
+.. option:: WarnOnExplicitCast
+
+  When `WarnOnExplicitCast` is set to `false`, the check will not warn when
+  output of ostream is explicitly cast to a ``unsigned char`` or ``signed 
char``.

vbvictor wrote:

```suggestion
  output of an ``ostream`` is explicitly cast to an ``unsigned char`` or 
``signed char``.
```

https://github.com/llvm/llvm-project/pull/133639
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy][bugprone-unintended-char-ostream-output] add `WarnOnExplicitCast` option (PR #133639)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #133425.

Add `WarnOnExplicitCast` to accept explicit cast to unsigned char and signed 
char.

---
Full diff: https://github.com/llvm/llvm-project/pull/133639.diff


4 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp 
(+8-3) 
- (modified) 
clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h (+1) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
 (+11) 
- (added) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
 (+40) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
index 7250e4ccb8c69..b6fbb8bd0ffe4 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.cpp
@@ -35,12 +35,13 @@ AST_MATCHER(Type, isChar) {
 
 UnintendedCharOstreamOutputCheck::UnintendedCharOstreamOutputCheck(
 StringRef Name, ClangTidyContext *Context)
-: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")) 
{
-}
+: ClangTidyCheck(Name, Context), CastTypeName(Options.get("CastTypeName")),
+  WarnOnExplicitCast(Options.get("WarnOnExplicitCast", true)) {}
 void UnintendedCharOstreamOutputCheck::storeOptions(
 ClangTidyOptions::OptionMap &Opts) {
   if (CastTypeName.has_value())
 Options.store(Opts, "CastTypeName", CastTypeName.value());
+  Options.store(Opts, "WarnOnExplicitCast", WarnOnExplicitCast);
 }
 
 void UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
@@ -50,13 +51,17 @@ void 
UnintendedCharOstreamOutputCheck::registerMatchers(MatchFinder *Finder) {
 // with char / unsigned char / signed char
 classTemplateSpecializationDecl(
 hasTemplateArgument(0, refersToType(isChar();
+  auto IsNumbericCharType =
+  hasType(hasUnqualifiedDesugaredType(isNumericChar()));
   Finder->addMatcher(
   cxxOperatorCallExpr(
   hasOverloadedOperatorName("<<"),
   hasLHS(hasType(hasUnqualifiedDesugaredType(
   recordType(hasDeclaration(cxxRecordDecl(
   anyOf(BasicOstream, isDerivedFrom(BasicOstream,
-  hasRHS(hasType(hasUnqualifiedDesugaredType(isNumericChar()
+  hasRHS(WarnOnExplicitCast
+ ? expr(IsNumbericCharType)
+ : expr(IsNumbericCharType, unless(explicitCastExpr()
   .bind("x"),
   this);
 }
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
index 61ea623d139ea..2e1859bbe21a7 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UnintendedCharOstreamOutputCheck.h
@@ -31,6 +31,7 @@ class UnintendedCharOstreamOutputCheck : public 
ClangTidyCheck {
 
 private:
   const std::optional CastTypeName;
+  const bool WarnOnExplicitCast;
 };
 
 } // namespace clang::tidy::bugprone
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
index ea1051847129b..a6196ae8c2448 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unintended-char-ostream-output.rst
@@ -39,6 +39,17 @@ Or cast to char to explicitly indicate that output should be 
a character.
 
   std::cout << static_cast(v);
 
+Options
+---
+
+.. option:: WarnOnExplicitCast
+
+  When `WarnOnExplicitCast` is set to `false`, the check will not warn when
+  output of ostream is explicitly cast to a ``unsigned char`` or ``signed 
char``.
+  Attention: Explicit casting cannot solve the any problem if the value is not
+  character.
+  Default is `true`.
+
 .. option:: CastTypeName
 
   When `CastTypeName` is specified, the fix-it will use `CastTypeName` as the
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
new file mode 100644
index 0..9722fae39f129
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unintended-char-ostream-output-explicit-cast.cpp
@@ -0,0 +1,40 @@
+// RUN: %check_clang_tidy %s bugprone-unintended-char-ostream-output %t 
-check-suffix=WARN-EXPLICIT-CAST
+// RUN: %check_clang_tidy %s bugprone-unintended-char-ostream-output %t \
+// RUN:   -config='{CheckOptions: { \
+// RUN: 

[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -16327,79 +16531,181 @@ static CanQualType RemoveAddressSpaceFromPtr(Sema 
&SemaRef,
   PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
 }
 
-static inline bool
-CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
-CanQualType ExpectedResultType,
-CanQualType ExpectedFirstParamType,
-unsigned DependentParamTypeDiag,
-unsigned InvalidParamTypeDiag) {
-  QualType ResultType =
-  FnDecl->getType()->castAs()->getReturnType();
+enum class AllocationOperatorKind { New, Delete };
+
+static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
+  const FunctionDecl *FD,
+  bool *WasMalformed) {
+  const Decl *MalformedDecl = nullptr;
+  if (FD->getNumParams() > 0 &&
+  SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
+/*TypeArgument=*/nullptr, &MalformedDecl))
+return true;
 
-  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
-// The operator is valid on any address space for OpenCL.
-// Drop address space from actual and expected result types.
-if (const auto *PtrTy = ResultType->getAs())
-  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+  if (!MalformedDecl)
+return false;
+
+  if (WasMalformed)
+*WasMalformed = true;
+
+  // SemaRef.Diag(MalformedDecl->getLocation(),
+  // diag::err_malformed_std_class_template) << "type_identity";
+  return true;
+}
+
+static bool isDestroyingDeleteT(QualType Type) {
+  auto *RD = Type->getAsCXXRecordDecl();
+  return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
+ RD->getIdentifier()->isStr("destroying_delete_t");
+}
+
+static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
+  const FunctionDecl *FD) {
+  // C++ P0722:
+  //   Within a class C, a single object deallocation function with signature
+  // (T, std::destroying_delete_t, )
+  //   is a destroying operator delete.
+  bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
+  SemaRef, FD, /*WasMalformed=*/nullptr);
+  unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
+  return isa(FD) && FD->getOverloadedOperator() == OO_Delete &&
+ FD->getNumParams() > DestroyingDeleteIdx &&
+ isDestroyingDeleteT(FD->getParamDecl(DestroyingDeleteIdx)->getType());
+}
+
+static inline bool CheckOperatorNewDeleteTypes(
+Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
+CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
+unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
+  auto NormalizeType = [&SemaRef](QualType T) {
+if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
+  // The operator is valid on any address space for OpenCL.
+  // Drop address space from actual and expected result types.
+  if (const auto PtrTy = T->template getAs())
+T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+}
+return SemaRef.Context.getCanonicalType(T);
+  };
 
-if (auto ExpectedPtrTy = ExpectedResultType->getAs())
-  ExpectedResultType = RemoveAddressSpaceFromPtr(SemaRef, ExpectedPtrTy);
+  const unsigned NumParams = FnDecl->getNumParams();
+  unsigned FirstNonTypeParam = 0;
+  bool MalformedTypeIdentity = false;
+  bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
+  SemaRef, FnDecl, &MalformedTypeIdentity);
+  unsigned MinimumMandatoryArgumentCount = 1;
+  unsigned SizeParameterIndex = 0;
+  if (IsPotentiallyTypeAware) {
+if (!FnDecl->isTemplateInstantiation()) {
+  unsigned DiagID = SemaRef.getLangOpts().CPlusPlus26
+? diag::warn_cxx26_type_aware_allocators
+: diag::ext_cxx26_type_aware_allocators;
+  SemaRef.Diag(FnDecl->getLocation(), DiagID);
+}
+
+if (OperatorKind == AllocationOperatorKind::New) {
+  SizeParameterIndex = 1;
+  MinimumMandatoryArgumentCount =
+  FunctionDecl::RequiredTypeAwareNewParameterCount;
+} else {
+  SizeParameterIndex = 2;
+  MinimumMandatoryArgumentCount =
+  FunctionDecl::RequiredTypeAwareDeleteParameterCount;
+}
+FirstNonTypeParam = 1;
   }
 
+  bool IsPotentiallyDestroyingDelete =
+  IsPotentiallyDestroyingOperatorDelete(SemaRef, FnDecl);
+
+  if (IsPotentiallyDestroyingDelete) {
+++MinimumMandatoryArgumentCount;
+++SizeParameterIndex;
+  }
+
+  if (NumParams < MinimumMandatoryArgumentCount)
+return SemaRef.Diag(FnDecl->getLocation(),
+diag::err_operator_new_delete_too_few_parameters)
+   << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
+   << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
+
+  for (uns

[clang] Improved the ``-Wtautological-overlap-compare`` diagnostics to warn a… (PR #133653)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yutong Zhu (YutongZhuu)


Changes

This PR attempts to improve the diagnostics flag 
``-Wtautological-overlap-compare`` (#13473). I have added code to warn 
about float-point literals and character literals. I have also changed the 
warning message for the non-overlapping case to provide a more correct hint to 
the user. 

---

Patch is 22.65 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/133653.diff


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4-1) 
- (modified) clang/lib/Analysis/CFG.cpp (+143-70) 
- (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+6-3) 
- (modified) clang/test/Sema/warn-overlap.c (+87-21) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..e6a31072567e7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -256,6 +256,9 @@ Improvements to Clang's diagnostics
 
 - Improve the diagnostics for shadows template parameter to report correct 
location (#GH129060).
 
+- Improved the ``-Wtautological-overlap-compare`` diagnostics to warn about 
overlapping and non-overlapping ranges involving character literals and 
floating-point literals. 
+  The warning message for non-overlapping cases has also been improved 
(#GH13473).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 86c9c955c1c78..493a66df982c4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10398,7 +10398,10 @@ def warn_tautological_negation_or_compare: Warning<
   "'||' of a value and its negation always evaluates to true">,
   InGroup, DefaultIgnore;
 def warn_tautological_overlap_comparison : Warning<
-  "overlapping comparisons always evaluate to %select{false|true}0">,
+  "overlapping comparisons always evaluate to true">,
+  InGroup, DefaultIgnore;
+def warn_tautological_non_overlap_comparison : Warning<
+  "non-overlapping comparisons always evaluate to false">,
   InGroup, DefaultIgnore;
 def warn_depr_array_comparison : Warning<
   "comparison between two arrays is deprecated; "
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 9af1e915482da..c6b7c49d4cb4a 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -70,13 +70,11 @@ static SourceLocation GetEndLoc(Decl *D) {
   return D->getLocation();
 }
 
-/// Returns true on constant values based around a single IntegerLiteral.
-/// Allow for use of parentheses, integer casts, and negative signs.
-/// FIXME: it would be good to unify this function with
-/// getIntegerLiteralSubexpressionValue at some point given the similarity
-/// between the functions.
+/// Returns true on constant values based around a single IntegerLiteral,
+/// CharacterLiteral, or FloatingLiteral. Allow for use of parentheses, integer
+/// casts, and negative signs.
 
-static bool IsIntegerLiteralConstantExpr(const Expr *E) {
+static bool IsLiteralConstantExpr(const Expr *E) {
   // Allow parentheses
   E = E->IgnoreParens();
 
@@ -93,16 +91,16 @@ static bool IsIntegerLiteralConstantExpr(const Expr *E) {
   return false;
 E = UO->getSubExpr();
   }
-
-  return isa(E);
+  return isa(E) || isa(E) ||
+ isa(E);
 }
 
 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an 
IntegerLiteral
 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
 /// returns nullptr.
-static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
+static const Expr *tryTransformToLiteralConstants(const Expr *E) {
   E = E->IgnoreParens();
-  if (IsIntegerLiteralConstantExpr(E))
+  if (IsLiteralConstantExpr(E))
 return E;
   if (auto *DR = dyn_cast(E->IgnoreParenImpCasts()))
 return isa(DR->getDecl()) ? DR : nullptr;
@@ -119,7 +117,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   BinaryOperatorKind Op = B->getOpcode();
 
   const Expr *MaybeDecl = B->getLHS();
-  const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
+  const Expr *Constant = tryTransformToLiteralConstants(B->getRHS());
   // Expr looked like `0 == Foo` instead of `Foo == 0`
   if (Constant == nullptr) {
 // Flip the operator
@@ -133,7 +131,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   Op = BO_GE;
 
 MaybeDecl = B->getRHS();
-Constant = tryTransformToIntOrEnumConstant(B->getLHS());
+Constant = tryTransformToLiteralConstants(B->getLHS());
   }
 
   return std::make_tuple(MaybeDecl, Op, Constant);
@@ -1104,6 +1102,27 @@ class CFGBuilder {
 }
   }
 
+  TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
+  const llvm::APFloat &Value1,
+ 

[clang] Improved the ``-Wtautological-overlap-compare`` diagnostics to warn a… (PR #133653)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: Yutong Zhu (YutongZhuu)


Changes

This PR attempts to improve the diagnostics flag 
``-Wtautological-overlap-compare`` (#13473). I have added code to warn 
about float-point literals and character literals. I have also changed the 
warning message for the non-overlapping case to provide a more correct hint to 
the user. 

---

Patch is 22.65 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/133653.diff


5 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+4-1) 
- (modified) clang/lib/Analysis/CFG.cpp (+143-70) 
- (modified) clang/lib/Sema/AnalysisBasedWarnings.cpp (+6-3) 
- (modified) clang/test/Sema/warn-overlap.c (+87-21) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2a1c5ee2d788e..e6a31072567e7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -256,6 +256,9 @@ Improvements to Clang's diagnostics
 
 - Improve the diagnostics for shadows template parameter to report correct 
location (#GH129060).
 
+- Improved the ``-Wtautological-overlap-compare`` diagnostics to warn about 
overlapping and non-overlapping ranges involving character literals and 
floating-point literals. 
+  The warning message for non-overlapping cases has also been improved 
(#GH13473).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 86c9c955c1c78..493a66df982c4 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10398,7 +10398,10 @@ def warn_tautological_negation_or_compare: Warning<
   "'||' of a value and its negation always evaluates to true">,
   InGroup, DefaultIgnore;
 def warn_tautological_overlap_comparison : Warning<
-  "overlapping comparisons always evaluate to %select{false|true}0">,
+  "overlapping comparisons always evaluate to true">,
+  InGroup, DefaultIgnore;
+def warn_tautological_non_overlap_comparison : Warning<
+  "non-overlapping comparisons always evaluate to false">,
   InGroup, DefaultIgnore;
 def warn_depr_array_comparison : Warning<
   "comparison between two arrays is deprecated; "
diff --git a/clang/lib/Analysis/CFG.cpp b/clang/lib/Analysis/CFG.cpp
index 9af1e915482da..c6b7c49d4cb4a 100644
--- a/clang/lib/Analysis/CFG.cpp
+++ b/clang/lib/Analysis/CFG.cpp
@@ -70,13 +70,11 @@ static SourceLocation GetEndLoc(Decl *D) {
   return D->getLocation();
 }
 
-/// Returns true on constant values based around a single IntegerLiteral.
-/// Allow for use of parentheses, integer casts, and negative signs.
-/// FIXME: it would be good to unify this function with
-/// getIntegerLiteralSubexpressionValue at some point given the similarity
-/// between the functions.
+/// Returns true on constant values based around a single IntegerLiteral,
+/// CharacterLiteral, or FloatingLiteral. Allow for use of parentheses, integer
+/// casts, and negative signs.
 
-static bool IsIntegerLiteralConstantExpr(const Expr *E) {
+static bool IsLiteralConstantExpr(const Expr *E) {
   // Allow parentheses
   E = E->IgnoreParens();
 
@@ -93,16 +91,16 @@ static bool IsIntegerLiteralConstantExpr(const Expr *E) {
   return false;
 E = UO->getSubExpr();
   }
-
-  return isa(E);
+  return isa(E) || isa(E) ||
+ isa(E);
 }
 
 /// Helper for tryNormalizeBinaryOperator. Attempts to extract an 
IntegerLiteral
 /// constant expression or EnumConstantDecl from the given Expr. If it fails,
 /// returns nullptr.
-static const Expr *tryTransformToIntOrEnumConstant(const Expr *E) {
+static const Expr *tryTransformToLiteralConstants(const Expr *E) {
   E = E->IgnoreParens();
-  if (IsIntegerLiteralConstantExpr(E))
+  if (IsLiteralConstantExpr(E))
 return E;
   if (auto *DR = dyn_cast(E->IgnoreParenImpCasts()))
 return isa(DR->getDecl()) ? DR : nullptr;
@@ -119,7 +117,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   BinaryOperatorKind Op = B->getOpcode();
 
   const Expr *MaybeDecl = B->getLHS();
-  const Expr *Constant = tryTransformToIntOrEnumConstant(B->getRHS());
+  const Expr *Constant = tryTransformToLiteralConstants(B->getRHS());
   // Expr looked like `0 == Foo` instead of `Foo == 0`
   if (Constant == nullptr) {
 // Flip the operator
@@ -133,7 +131,7 @@ tryNormalizeBinaryOperator(const BinaryOperator *B) {
   Op = BO_GE;
 
 MaybeDecl = B->getRHS();
-Constant = tryTransformToIntOrEnumConstant(B->getLHS());
+Constant = tryTransformToLiteralConstants(B->getLHS());
   }
 
   return std::make_tuple(MaybeDecl, Op, Constant);
@@ -1104,6 +1102,27 @@ class CFGBuilder {
 }
   }
 
+  TryResult analyzeLogicOperatorCondition(BinaryOperatorKind Relation,
+  const llvm::APFloat &Value1,
+

[clang] [clang] Use DenseMap::insert_range (NFC) (PR #133655)

2025-03-30 Thread Kazu Hirata via cfe-commits

https://github.com/kazutakahirata created 
https://github.com/llvm/llvm-project/pull/133655

None

>From 9fe28b2669aae7fec6353c7c1fe60aae434b98b8 Mon Sep 17 00:00:00 2001
From: Kazu Hirata 
Date: Sun, 30 Mar 2025 13:16:22 -0700
Subject: [PATCH] [clang] Use DenseMap::insert_range (NFC)

---
 clang/lib/AST/VTableBuilder.cpp | 6 ++
 clang/lib/CodeGen/CodeGenModule.cpp | 3 +--
 clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp | 4 ++--
 3 files changed, 5 insertions(+), 8 deletions(-)

diff --git a/clang/lib/AST/VTableBuilder.cpp b/clang/lib/AST/VTableBuilder.cpp
index 18893b996b5d6..6c97b8718c65e 100644
--- a/clang/lib/AST/VTableBuilder.cpp
+++ b/clang/lib/AST/VTableBuilder.cpp
@@ -3736,8 +3736,7 @@ void 
MicrosoftVTableContext::computeVTableRelatedInformation(
 }
   }
 
-  MethodVFTableLocations.insert(NewMethodLocations.begin(),
-NewMethodLocations.end());
+  MethodVFTableLocations.insert_range(NewMethodLocations);
   if (Context.getLangOpts().DumpVTableLayouts)
 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
 }
@@ -3824,8 +3823,7 @@ const VirtualBaseInfo 
&MicrosoftVTableContext::computeVBTableRelatedInformation(
 // virtual bases come first so that the layout is the same.
 const VirtualBaseInfo &BaseInfo =
 computeVBTableRelatedInformation(VBPtrBase);
-VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
-   BaseInfo.VBTableIndices.end());
+VBI->VBTableIndices.insert_range(BaseInfo.VBTableIndices);
   }
 
   // New vbases are added to the end of the vbtable.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 5dbd50be6ca1a..43345da268868 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -853,8 +853,7 @@ void CodeGenModule::Release() {
   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
 EmitModuleInitializers(Primary);
   EmitDeferred();
-  DeferredDecls.insert(EmittedDeferredDecls.begin(),
-   EmittedDeferredDecls.end());
+  DeferredDecls.insert_range(EmittedDeferredDecls);
   EmittedDeferredDecls.clear();
   EmitVTablesOpportunistically();
   applyGlobalValReplacements();
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 52dec2013a24f..52d922abbcaec 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -1099,7 +1099,7 @@ Expected getSymbolsFromBitcode(MemoryBufferRef 
Buffer, OffloadKind Kind,
 
   // If the file gets extracted we update the table with the new symbols.
   if (ShouldExtract)
-Syms.insert(std::begin(TmpSyms), std::end(TmpSyms));
+Syms.insert_range(TmpSyms);
 
   return ShouldExtract;
 }
@@ -1154,7 +1154,7 @@ Expected getSymbolsFromObject(const ObjectFile 
&Obj, OffloadKind Kind,
 
   // If the file gets extracted we update the table with the new symbols.
   if (ShouldExtract)
-Syms.insert(std::begin(TmpSyms), std::end(TmpSyms));
+Syms.insert_range(TmpSyms);
 
   return ShouldExtract;
 }

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang] Use DenseMap::insert_range (NFC) (PR #133655)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Kazu Hirata (kazutakahirata)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/133655.diff


3 Files Affected:

- (modified) clang/lib/AST/VTableBuilder.cpp (+2-4) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+1-2) 
- (modified) clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp (+2-2) 


``diff
diff --git a/clang/lib/AST/VTableBuilder.cpp b/clang/lib/AST/VTableBuilder.cpp
index 18893b996b5d6..6c97b8718c65e 100644
--- a/clang/lib/AST/VTableBuilder.cpp
+++ b/clang/lib/AST/VTableBuilder.cpp
@@ -3736,8 +3736,7 @@ void 
MicrosoftVTableContext::computeVTableRelatedInformation(
 }
   }
 
-  MethodVFTableLocations.insert(NewMethodLocations.begin(),
-NewMethodLocations.end());
+  MethodVFTableLocations.insert_range(NewMethodLocations);
   if (Context.getLangOpts().DumpVTableLayouts)
 dumpMethodLocations(RD, NewMethodLocations, llvm::outs());
 }
@@ -3824,8 +3823,7 @@ const VirtualBaseInfo 
&MicrosoftVTableContext::computeVBTableRelatedInformation(
 // virtual bases come first so that the layout is the same.
 const VirtualBaseInfo &BaseInfo =
 computeVBTableRelatedInformation(VBPtrBase);
-VBI->VBTableIndices.insert(BaseInfo.VBTableIndices.begin(),
-   BaseInfo.VBTableIndices.end());
+VBI->VBTableIndices.insert_range(BaseInfo.VBTableIndices);
   }
 
   // New vbases are added to the end of the vbtable.
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 5dbd50be6ca1a..43345da268868 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -853,8 +853,7 @@ void CodeGenModule::Release() {
   if (CXX20ModuleInits && Primary && !Primary->isHeaderLikeModule())
 EmitModuleInitializers(Primary);
   EmitDeferred();
-  DeferredDecls.insert(EmittedDeferredDecls.begin(),
-   EmittedDeferredDecls.end());
+  DeferredDecls.insert_range(EmittedDeferredDecls);
   EmittedDeferredDecls.clear();
   EmitVTablesOpportunistically();
   applyGlobalValReplacements();
diff --git a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp 
b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
index 52dec2013a24f..52d922abbcaec 100644
--- a/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ b/clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -1099,7 +1099,7 @@ Expected getSymbolsFromBitcode(MemoryBufferRef 
Buffer, OffloadKind Kind,
 
   // If the file gets extracted we update the table with the new symbols.
   if (ShouldExtract)
-Syms.insert(std::begin(TmpSyms), std::end(TmpSyms));
+Syms.insert_range(TmpSyms);
 
   return ShouldExtract;
 }
@@ -1154,7 +1154,7 @@ Expected getSymbolsFromObject(const ObjectFile 
&Obj, OffloadKind Kind,
 
   // If the file gets extracted we update the table with the new symbols.
   if (ShouldExtract)
-Syms.insert(std::begin(TmpSyms), std::end(TmpSyms));
+Syms.insert_range(TmpSyms);
 
   return ShouldExtract;
 }

``




https://github.com/llvm/llvm-project/pull/133655
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang][modules] Guard against bad -fmodule-file mappings (#132059) (PR #133462)

2025-03-30 Thread Naveen Seth Hanig via cfe-commits

https://github.com/naveen-seth edited 
https://github.com/llvm/llvm-project/pull/133462
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format] Add an option for editing enum trailing commas (PR #133576)

2025-03-30 Thread Owen Pan via cfe-commits


@@ -2214,6 +2214,21 @@ FormatStyle::GetLanguageStyle(FormatStyle::LanguageKind 
Language) const {
 
 namespace {
 
+void replaceToken(const FormatToken &Token, FormatToken *Next,
+  const SourceManager &SourceMgr, tooling::Replacements 
&Result,
+  const char *Text = "") {

owenca wrote:

`StringRef` it is.

https://github.com/llvm/llvm-project/pull/133576
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Oliver Hunt via cfe-commits


@@ -7353,6 +7354,69 @@ void Sema::CheckCompletedCXXClass(Scope *S, 
CXXRecordDecl *Record) {
 else if (Record->hasAttr())
   checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
   }
+
+  llvm::SmallVector TypeAwareNewDecls;
+  llvm::SmallVector TypeAwareDeleteDecls;
+  llvm::SmallVector TypeAwareArrayNewDecls;
+  llvm::SmallVector TypeAwareArrayDeleteDecls;
+
+  for (auto *D : Record->decls()) {
+const FunctionDecl *FnDecl = nullptr;
+if (auto *FTD = dyn_cast(D))
+  FnDecl = FTD->getTemplatedDecl();
+else if (auto *FD = dyn_cast(D))
+  FnDecl = FD;
+if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
+  continue;
+switch (FnDecl->getOverloadedOperator()) {
+case OO_New:
+  TypeAwareNewDecls.push_back(FnDecl);
+  break;
+case OO_Array_New:
+  TypeAwareArrayNewDecls.push_back(FnDecl);
+  break;
+case OO_Delete:
+  TypeAwareDeleteDecls.push_back(FnDecl);
+  break;
+case OO_Array_Delete:
+  TypeAwareArrayDeleteDecls.push_back(FnDecl);
+  break;
+default:
+  continue;
+}
+  }
+  auto CheckMismatchedTypeAwareAllocators =
+  [this,
+   Record](OverloadedOperatorKind NewKind,
+   const llvm::SmallVector &NewDecls,
+   OverloadedOperatorKind DeleteKind,
+   const llvm::SmallVector &DeleteDecls) {
+if (NewDecls.empty() == DeleteDecls.empty())
+  return;
+DeclarationName FoundOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? DeleteKind : NewKind);
+DeclarationName MissingOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? NewKind : DeleteKind);
+Diag(Record->getLocation(),
+ diag::err_type_aware_allocator_missing_matching_operator)
+<< FoundOperator << Context.getRecordType(Record)
+<< MissingOperator;

ojhunt wrote:

@mizvekov Ah right, when you remove class name the message starts to sound like 
the only requirement is that there is a matching operator, but the 
specification requires the corresponding operator to be declared in the same 
scope/class.

So removing the class name is obviously easy enough, but given those semantics 
it seems worth having it present - what do you thing?

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Oliver Hunt via cfe-commits


@@ -16327,79 +16531,181 @@ static CanQualType RemoveAddressSpaceFromPtr(Sema 
&SemaRef,
   PtrTy->getPointeeType().getUnqualifiedType(), PtrQuals)));
 }
 
-static inline bool
-CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
-CanQualType ExpectedResultType,
-CanQualType ExpectedFirstParamType,
-unsigned DependentParamTypeDiag,
-unsigned InvalidParamTypeDiag) {
-  QualType ResultType =
-  FnDecl->getType()->castAs()->getReturnType();
+enum class AllocationOperatorKind { New, Delete };
+
+static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
+  const FunctionDecl *FD,
+  bool *WasMalformed) {
+  const Decl *MalformedDecl = nullptr;
+  if (FD->getNumParams() > 0 &&
+  SemaRef.isStdTypeIdentity(FD->getParamDecl(0)->getType(),
+/*TypeArgument=*/nullptr, &MalformedDecl))
+return true;
 
-  if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
-// The operator is valid on any address space for OpenCL.
-// Drop address space from actual and expected result types.
-if (const auto *PtrTy = ResultType->getAs())
-  ResultType = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
+  if (!MalformedDecl)
+return false;
+
+  if (WasMalformed)
+*WasMalformed = true;
+
+  // SemaRef.Diag(MalformedDecl->getLocation(),
+  // diag::err_malformed_std_class_template) << "type_identity";

ojhunt wrote:

Yup, hilariously I just saw it while looking for erroneous getLocation() 
instead of getSourceRange(), I had to remind myself what this problem was. 
Basically (from a QoL PoV) I'd like to diagnose "you are using  
but the definition is wrong", however because the type decl is not actually 
invalid it's wrong to mark it as such, and so we end up producing the same 
diagnostic for the same type repeatedly.

For now it seems acceptable to not diagnose here and maintain the existing 
semantics presented by initializer_list (which originated the malformed class 
diagnostic) and only diagnose when we attempt to actually call the function.

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Add linker options to support statical linking to shared flang-rt on AIX. (PR #131822)

2025-03-30 Thread Daniel Chen via cfe-commits

https://github.com/DanielCChen edited 
https://github.com/llvm/llvm-project/pull/131822
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RFC] Initial implementation of P2719 (PR #113510)

2025-03-30 Thread Matheus Izvekov via cfe-commits


@@ -7353,6 +7354,69 @@ void Sema::CheckCompletedCXXClass(Scope *S, 
CXXRecordDecl *Record) {
 else if (Record->hasAttr())
   checkCUDADeviceBuiltinTextureClassTemplate(*this, Record);
   }
+
+  llvm::SmallVector TypeAwareNewDecls;
+  llvm::SmallVector TypeAwareDeleteDecls;
+  llvm::SmallVector TypeAwareArrayNewDecls;
+  llvm::SmallVector TypeAwareArrayDeleteDecls;
+
+  for (auto *D : Record->decls()) {
+const FunctionDecl *FnDecl = nullptr;
+if (auto *FTD = dyn_cast(D))
+  FnDecl = FTD->getTemplatedDecl();
+else if (auto *FD = dyn_cast(D))
+  FnDecl = FD;
+if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
+  continue;
+switch (FnDecl->getOverloadedOperator()) {
+case OO_New:
+  TypeAwareNewDecls.push_back(FnDecl);
+  break;
+case OO_Array_New:
+  TypeAwareArrayNewDecls.push_back(FnDecl);
+  break;
+case OO_Delete:
+  TypeAwareDeleteDecls.push_back(FnDecl);
+  break;
+case OO_Array_Delete:
+  TypeAwareArrayDeleteDecls.push_back(FnDecl);
+  break;
+default:
+  continue;
+}
+  }
+  auto CheckMismatchedTypeAwareAllocators =
+  [this,
+   Record](OverloadedOperatorKind NewKind,
+   const llvm::SmallVector &NewDecls,
+   OverloadedOperatorKind DeleteKind,
+   const llvm::SmallVector &DeleteDecls) {
+if (NewDecls.empty() == DeleteDecls.empty())
+  return;
+DeclarationName FoundOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? DeleteKind : NewKind);
+DeclarationName MissingOperator =
+Context.DeclarationNames.getCXXOperatorName(
+NewDecls.empty() ? NewKind : DeleteKind);
+Diag(Record->getLocation(),
+ diag::err_type_aware_allocator_missing_matching_operator)
+<< FoundOperator << Context.getRecordType(Record)
+<< MissingOperator;

mizvekov wrote:

Right, that makes sense.

On one hand, your diagnostic could be something like: 'declaration of type 
aware %0 in **this class** must have matching type aware %2'

But if you want to talk about the class, you might as well say it by name, 
instead of 'this class'.

If you pass a bare CXXRecordType, then the class name will be printed fully 
qualified, which might not be needed in this case since you are already 
pointing to it after all. If you pass the Decl, it should print just its quoted 
identifier.

Is it possible to get here with an anonymous class? If so, then you might need 
a 'this class' fallback as well. 

https://github.com/llvm/llvm-project/pull/113510
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][Cmake] fix libtool duplicate member name warnings (PR #133619)

2025-03-30 Thread Farzon Lotfi via cfe-commits

farzonl wrote:

@nikic  what is considered a neglible difference in elapsesed time? Elapsed is 
consistently a little more after my change in the order of 5-20 seconds. 
Examples below:

## Specs
```
processor   : 63
vendor_id   : AuthenticAMD
cpu family  : 25
model   : 8
model name  : AMD Ryzen Threadripper PRO 5975WX 32-Cores
stepping: 2
microcode   : 0xa008205
cpu MHz : 1800.000
cache size  : 512 KB
physical id : 0
siblings: 64
core id : 31
cpu cores   : 32
```

## Debug build before changes:
```
[5363/5363] Generated
Command being timed: "ninja -C ../llvm_debug_build/"
User time (seconds): 28679.90
System time (seconds): 1482.99
Percent of CPU this job got: 5620%
Elapsed (wall clock) time (h:mm:ss or m:ss): 8:56.62
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 10034904
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 89825
Minor (reclaiming a frame) page faults: 310462049
Voluntary context switches: 1261232
Involuntary context switches: 1125893
Swaps: 0
File system inputs: 37896
File system outputs: 112778048
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```
## Release build before changes:
```
ninja: Entering directory `../llvm_release_build/'
[5363/5363] Generated
Command being timed: "ninja -C ../llvm_release_build/"
User time (seconds): 25730.83
System time (seconds): 1238.55
Percent of CPU this job got: 6140%
Elapsed (wall clock) time (h:mm:ss or m:ss): 7:19.22
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 1696776
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 2113
Minor (reclaiming a frame) page faults: 268141745
Voluntary context switches: 551323
Involuntary context switches: 1124237
Swaps: 0
File system inputs: 944
File system outputs: 10928088
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```
## Release build after changes:
```
 [5365/5365] Generated
Command being timed: "ninja -C ../llvm_release_build/"
User time (seconds): 25542.24
System time (seconds): 1235.53
Percent of CPU this job got: 5852%
Elapsed (wall clock) time (h:mm:ss or m:ss): 7:37.54
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 1695512
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 2075
Minor (reclaiming a frame) page faults: 268176633
Voluntary context switches: 554573
Involuntary context switches: 1113659
Swaps: 0
File system inputs: 264
File system outputs: 11055600
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```
## Debug build after changes:
```
[5365/5365] Generated
Command being timed: "ninja -C ../llvm_debug_build/"
User time (seconds): 28477.94
System time (seconds): 1469.80
Percent of CPU this job got: 5523%
Elapsed (wall clock) time (h:mm:ss or m:ss): 9:02.20
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 10817400
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 89172
Minor (reclaiming a frame) page faults: 310414009
Voluntary context switches: 1002199
Involuntary context switches: 1243091
Swaps: 0
File system inputs: 384
File system outputs: 112886080
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0
```

https://github.com/llvm/llvm-project/pull/133619
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [analyzer] Unknown array lvalue element in Store (PR #133381)

2025-03-30 Thread Balazs Benics via cfe-commits

https://github.com/steakhal closed 
https://github.com/llvm/llvm-project/pull/133381
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clangd] Store documentation when indexing standard library (PR #133681)

2025-03-30 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/133681

Fixes https://github.com/clangd/clangd/issues/2344

>From 646963c0fdf3265e6149091786df7090d7b9dfb2 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Mon, 31 Mar 2025 02:25:45 -0400
Subject: [PATCH] [clangd] Store documentation when indexing standard library

Fixes https://github.com/clangd/clangd/issues/2344
---
 clang-tools-extra/clangd/index/Background.cpp |  1 +
 .../clangd/index/IndexAction.cpp  |  1 -
 .../clangd/indexer/IndexerMain.cpp|  1 +
 .../clangd/unittests/StdLibTests.cpp  | 37 +++
 .../clangd/unittests/SyncAPI.cpp  |  7 
 clang-tools-extra/clangd/unittests/SyncAPI.h  |  3 ++
 6 files changed, 49 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index 496d1455def4b..8013e9ea86112 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -306,6 +306,7 @@ llvm::Error BackgroundIndex::index(tooling::CompileCommand 
Cmd) {
 return true;
   };
   IndexOpts.CollectMainFileRefs = true;
+  IndexOpts.StoreAllDocumentation = false;
 
   IndexFileIn Index;
   auto Action = createStaticIndexingAction(
diff --git a/clang-tools-extra/clangd/index/IndexAction.cpp 
b/clang-tools-extra/clangd/index/IndexAction.cpp
index ed56c2a9d2e81..cec5f4558455c 100644
--- a/clang-tools-extra/clangd/index/IndexAction.cpp
+++ b/clang-tools-extra/clangd/index/IndexAction.cpp
@@ -223,7 +223,6 @@ std::unique_ptr createStaticIndexingAction(
   Opts.CollectIncludePath = true;
   if (Opts.Origin == SymbolOrigin::Unknown)
 Opts.Origin = SymbolOrigin::Static;
-  Opts.StoreAllDocumentation = false;
   if (RefsCallback != nullptr) {
 Opts.RefFilter = RefKind::All;
 Opts.RefsInHeaders = true;
diff --git a/clang-tools-extra/clangd/indexer/IndexerMain.cpp 
b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
index bc5d1a7408991..806734f6ad40e 100644
--- a/clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -55,6 +55,7 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
   std::unique_ptr create() override {
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
+Opts.StoreAllDocumentation = false;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
   const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
diff --git a/clang-tools-extra/clangd/unittests/StdLibTests.cpp 
b/clang-tools-extra/clangd/unittests/StdLibTests.cpp
index a7a33f78303d3..00c6d629e1c25 100644
--- a/clang-tools-extra/clangd/unittests/StdLibTests.cpp
+++ b/clang-tools-extra/clangd/unittests/StdLibTests.cpp
@@ -158,6 +158,43 @@ TEST(StdLibTests, EndToEnd) {
   UnorderedElementsAre(StdlibSymbol("list"), StdlibSymbol("vector")));
 }
 
+TEST(StdLibTests, StdLibDocComments) {
+  Config Cfg;
+  Cfg.Index.StandardLibrary = true;
+  WithContextValue Enabled(Config::Key, std::move(Cfg));
+
+  MockFS FS;
+  FS.Files["stdlib/vector"] = R"cpp(
+namespace std {
+  template 
+  class vector {
+  public:
+/**doc comment*/
+unsigned int size() const;
+  };
+}
+  )cpp";
+  MockCompilationDatabase CDB;
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("stdlib"));
+  ClangdServer::Options Opts = ClangdServer::optsForTest();
+  Opts.BuildDynamicSymbolIndex = true; // also used for stdlib index
+  ClangdServer Server(CDB, FS, Opts);
+
+  Annotations A(R"cpp(
+#include 
+void foo() {
+  std::vector v;
+  v.si^ze();
+}
+  )cpp");
+
+  Server.addDocument(testPath("foo.cc"), A.code());
+  ASSERT_TRUE(Server.blockUntilIdleForTest());
+  auto HI = cantFail(runHover(Server, testPath("foo.cc"), A.point()));
+  EXPECT_TRUE(HI.has_value());
+  EXPECT_EQ(HI->Documentation, "doc comment");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.cpp 
b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
index d48622eba5378..00bec7afd1a98 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.cpp
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
@@ -68,6 +68,13 @@ template  CaptureProxy 
capture(std::optional &Target) {
 }
 } // namespace
 
+llvm::Expected> runHover(ClangdServer &Server,
+  PathRef File, Position Pos) {
+  std::optional>> HI;
+  Server.findHover(File, Pos, capture(HI));
+  return std::move(*HI);
+}
+
 llvm::Expected
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
 clangd::CodeCompleteOptions Opts) {
diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.h 
b/clang-tools-extra/clangd/unittests/SyncAPI.h
index cf3de4f742e84..e0c7c4d72e73e 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.h
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.h
@@ -2

[clang-tools-extra] [clangd] Store documentation when indexing standard library (PR #133681)

2025-03-30 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clangd

@llvm/pr-subscribers-clang-tools-extra

Author: Nathan Ridge (HighCommander4)


Changes

Fixes https://github.com/clangd/clangd/issues/2344

---
Full diff: https://github.com/llvm/llvm-project/pull/133681.diff


6 Files Affected:

- (modified) clang-tools-extra/clangd/index/Background.cpp (+1) 
- (modified) clang-tools-extra/clangd/index/IndexAction.cpp (-1) 
- (modified) clang-tools-extra/clangd/indexer/IndexerMain.cpp (+1) 
- (modified) clang-tools-extra/clangd/unittests/StdLibTests.cpp (+37) 
- (modified) clang-tools-extra/clangd/unittests/SyncAPI.cpp (+7) 
- (modified) clang-tools-extra/clangd/unittests/SyncAPI.h (+3) 


``diff
diff --git a/clang-tools-extra/clangd/index/Background.cpp 
b/clang-tools-extra/clangd/index/Background.cpp
index 496d1455def4b..8013e9ea86112 100644
--- a/clang-tools-extra/clangd/index/Background.cpp
+++ b/clang-tools-extra/clangd/index/Background.cpp
@@ -306,6 +306,7 @@ llvm::Error BackgroundIndex::index(tooling::CompileCommand 
Cmd) {
 return true;
   };
   IndexOpts.CollectMainFileRefs = true;
+  IndexOpts.StoreAllDocumentation = false;
 
   IndexFileIn Index;
   auto Action = createStaticIndexingAction(
diff --git a/clang-tools-extra/clangd/index/IndexAction.cpp 
b/clang-tools-extra/clangd/index/IndexAction.cpp
index ed56c2a9d2e81..cec5f4558455c 100644
--- a/clang-tools-extra/clangd/index/IndexAction.cpp
+++ b/clang-tools-extra/clangd/index/IndexAction.cpp
@@ -223,7 +223,6 @@ std::unique_ptr createStaticIndexingAction(
   Opts.CollectIncludePath = true;
   if (Opts.Origin == SymbolOrigin::Unknown)
 Opts.Origin = SymbolOrigin::Static;
-  Opts.StoreAllDocumentation = false;
   if (RefsCallback != nullptr) {
 Opts.RefFilter = RefKind::All;
 Opts.RefsInHeaders = true;
diff --git a/clang-tools-extra/clangd/indexer/IndexerMain.cpp 
b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
index bc5d1a7408991..806734f6ad40e 100644
--- a/clang-tools-extra/clangd/indexer/IndexerMain.cpp
+++ b/clang-tools-extra/clangd/indexer/IndexerMain.cpp
@@ -55,6 +55,7 @@ class IndexActionFactory : public 
tooling::FrontendActionFactory {
   std::unique_ptr create() override {
 SymbolCollector::Options Opts;
 Opts.CountReferences = true;
+Opts.StoreAllDocumentation = false;
 Opts.FileFilter = [&](const SourceManager &SM, FileID FID) {
   const auto F = SM.getFileEntryRefForID(FID);
   if (!F)
diff --git a/clang-tools-extra/clangd/unittests/StdLibTests.cpp 
b/clang-tools-extra/clangd/unittests/StdLibTests.cpp
index a7a33f78303d3..00c6d629e1c25 100644
--- a/clang-tools-extra/clangd/unittests/StdLibTests.cpp
+++ b/clang-tools-extra/clangd/unittests/StdLibTests.cpp
@@ -158,6 +158,43 @@ TEST(StdLibTests, EndToEnd) {
   UnorderedElementsAre(StdlibSymbol("list"), StdlibSymbol("vector")));
 }
 
+TEST(StdLibTests, StdLibDocComments) {
+  Config Cfg;
+  Cfg.Index.StandardLibrary = true;
+  WithContextValue Enabled(Config::Key, std::move(Cfg));
+
+  MockFS FS;
+  FS.Files["stdlib/vector"] = R"cpp(
+namespace std {
+  template 
+  class vector {
+  public:
+/**doc comment*/
+unsigned int size() const;
+  };
+}
+  )cpp";
+  MockCompilationDatabase CDB;
+  CDB.ExtraClangFlags.push_back("-isystem" + testPath("stdlib"));
+  ClangdServer::Options Opts = ClangdServer::optsForTest();
+  Opts.BuildDynamicSymbolIndex = true; // also used for stdlib index
+  ClangdServer Server(CDB, FS, Opts);
+
+  Annotations A(R"cpp(
+#include 
+void foo() {
+  std::vector v;
+  v.si^ze();
+}
+  )cpp");
+
+  Server.addDocument(testPath("foo.cc"), A.code());
+  ASSERT_TRUE(Server.blockUntilIdleForTest());
+  auto HI = cantFail(runHover(Server, testPath("foo.cc"), A.point()));
+  EXPECT_TRUE(HI.has_value());
+  EXPECT_EQ(HI->Documentation, "doc comment");
+}
+
 } // namespace
 } // namespace clangd
 } // namespace clang
diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.cpp 
b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
index d48622eba5378..00bec7afd1a98 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.cpp
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.cpp
@@ -68,6 +68,13 @@ template  CaptureProxy 
capture(std::optional &Target) {
 }
 } // namespace
 
+llvm::Expected> runHover(ClangdServer &Server,
+  PathRef File, Position Pos) {
+  std::optional>> HI;
+  Server.findHover(File, Pos, capture(HI));
+  return std::move(*HI);
+}
+
 llvm::Expected
 runCodeComplete(ClangdServer &Server, PathRef File, Position Pos,
 clangd::CodeCompleteOptions Opts) {
diff --git a/clang-tools-extra/clangd/unittests/SyncAPI.h 
b/clang-tools-extra/clangd/unittests/SyncAPI.h
index cf3de4f742e84..e0c7c4d72e73e 100644
--- a/clang-tools-extra/clangd/unittests/SyncAPI.h
+++ b/clang-tools-extra/clangd/unittests/SyncAPI.h
@@ -29,6 +29,9 @@ void runAddDocument(ClangdServer &Server, PathRef File, 
StringRef Contents,

[clang] [analyzer] Unknown array lvalue element in Store (PR #133381)

2025-03-30 Thread Balazs Benics via cfe-commits

https://github.com/steakhal approved this pull request.


https://github.com/llvm/llvm-project/pull/133381
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Vectorize: Support fminimumnum and fmaximumnum (PR #131781)

2025-03-30 Thread YunQiang Su via cfe-commits

wzssyqa wrote:

ping

https://github.com/llvm/llvm-project/pull/131781
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Clang: Add elementwise minnum/maxnum builtin functions (PR #129207)

2025-03-30 Thread YunQiang Su via cfe-commits

wzssyqa wrote:

ping

https://github.com/llvm/llvm-project/pull/129207
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][BPF] Add tests for btf_type_tag c2x-style attributes (PR #133666)

2025-03-30 Thread via cfe-commits

https://github.com/yonghong-song created 
https://github.com/llvm/llvm-project/pull/133666

For btf_type_tag implementation, in order to have the same results with clang 
(__attribute__((btf_type_tag("...", gcc intends to use c2x syntax 
'[[...]]'. Clang also supports similar c2x syntax. Currently, the clang 
selftest contains the following five tests:
```
  attr-btf_type_tag-func.c
  attr-btf_type_tag-similar-type.c
  attr-btf_type_tag-var.c
  attr-btf_type_tag-func-ptr.c
  attr-btf_type_tag-typedef-field.c
```

Tests attr-btf_type_tag-func.c and attr-btf_type_tag-var.c already have c2x 
syntax test.

Test attr-btf_type_tag-func-ptr.c does not support c2x syntax when 
'__attribute__((...))' is replaced with with '[[...]]'. This should not be an 
issue since we do not have use cases for function pointer yet.

This patch added '[[...]]' syntax for
```
  attr-btf_type_tag-similar-type.c
  attr-btf_type_tag-typedef-field.c
```

>From 2c891f0102501ac8d6000f383352095323cd5d23 Mon Sep 17 00:00:00 2001
From: Yonghong Song 
Date: Sun, 30 Mar 2025 08:40:33 -0700
Subject: [PATCH] [Clang][BPF] Add tests for btf_type_tag c2x-style attributes

For btf_type_tag implementation, in order to have the same results
with clang (__attribute__((btf_type_tag("...", gcc intends to
use c2x syntax '[[...]]'. Clang also supports similar c2x syntax.
Currently, the clang selftest contains the following five tests:
  attr-btf_type_tag-func.c
  attr-btf_type_tag-similar-type.c
  attr-btf_type_tag-var.c
  attr-btf_type_tag-func-ptr.c
  attr-btf_type_tag-typedef-field.c

Tests attr-btf_type_tag-func.c and attr-btf_type_tag-var.c already
have c2x syntax test.

Test attr-btf_type_tag-func-ptr.c does not support c2x syntax when
'__attribute__((...))' is replaced with with '[[...]]'. This should
not be an issue since we do not have use cases for function pointer
yet.

This patch added '[[...]]' syntax for
  attr-btf_type_tag-similar-type.c
  attr-btf_type_tag-typedef-field.c
---
 .../CodeGen/attr-btf_type_tag-similar-type.c| 17 +++--
 .../CodeGen/attr-btf_type_tag-typedef-field.c   |  8 +++-
 2 files changed, 22 insertions(+), 3 deletions(-)

diff --git a/clang/test/CodeGen/attr-btf_type_tag-similar-type.c 
b/clang/test/CodeGen/attr-btf_type_tag-similar-type.c
index 3960d6f5c93fb..ba9cd2ea16510 100644
--- a/clang/test/CodeGen/attr-btf_type_tag-similar-type.c
+++ b/clang/test/CodeGen/attr-btf_type_tag-similar-type.c
@@ -1,8 +1,21 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple -debug-info-kind=limited 
-emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple %itanium_abi_triple -DDOUBLE_BRACKET_ATTRS=1 
-debug-info-kind=limited -emit-llvm -o - %s | FileCheck %s
+
+#if DOUBLE_BRACKET_ATTRS
+#define __tag1 [[clang::btf_type_tag("tag1")]]
+#define __tag2 [[clang::btf_type_tag("tag2")]]
+#define __tag3 [[clang::btf_type_tag("tag3")]]
+#define __tag4 [[clang::btf_type_tag("tag4")]]
+#else
+#define __tag1 __attribute__((btf_type_tag("tag1")))
+#define __tag2 __attribute__((btf_type_tag("tag2")))
+#define __tag3 __attribute__((btf_type_tag("tag3")))
+#define __tag4 __attribute__((btf_type_tag("tag4")))
+#endif
 
 struct map_value {
-int __attribute__((btf_type_tag("tag1"))) 
__attribute__((btf_type_tag("tag3"))) *a;
-int __attribute__((btf_type_tag("tag2"))) 
__attribute__((btf_type_tag("tag4"))) *b;
+int __tag1 __tag3 *a;
+int __tag2 __tag4 *b;
 };
 
 struct map_value *func(void);
diff --git a/clang/test/CodeGen/attr-btf_type_tag-typedef-field.c 
b/clang/test/CodeGen/attr-btf_type_tag-typedef-field.c
index 5c8955fbf89a8..0c02336532fd8 100644
--- a/clang/test/CodeGen/attr-btf_type_tag-typedef-field.c
+++ b/clang/test/CodeGen/attr-btf_type_tag-typedef-field.c
@@ -1,7 +1,13 @@
 // RUN: %clang_cc1 -triple %itanium_abi_triple -debug-info-kind=limited 
-emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple %itanium_abi_triple -DDOUBLE_BRACKET_ATTRS=1 
-debug-info-kind=limited -emit-llvm -o - %s | FileCheck %s
 
+#if DOUBLE_BRACKET_ATTRS
+#define __tag1 [[clang::btf_type_tag("tag1")]]
+#define __tag2 [[clang::btf_type_tag("tag2")]]
+#else
 #define __tag1 __attribute__((btf_type_tag("tag1")))
 #define __tag2 __attribute__((btf_type_tag("tag2")))
+#endif
 
 typedef void __fn_t(int);
 typedef __fn_t __tag1 __tag2 *__fn2_t;
@@ -31,5 +37,5 @@ int *foo1(struct t *a1) {
 // CHECK: ![[L28]] = !DISubroutineType(types: ![[L29:[0-9]+]])
 // CHECK: ![[L29]] = !{null, ![[L4]]}
 // CHECK: ![[L30]] = !{![[L21]], ![[L23]]}
-// CHECK: ![[L31]] = !DIDerivedType(tag: DW_TAG_member, name: "c", scope: 
![[#]], file: ![[#]], line: [[#]]1, baseType: ![[L32:[0-9]+]]
+// CHECK: ![[L31]] = !DIDerivedType(tag: DW_TAG_member, name: "c", scope: 
![[#]], file: ![[#]], line: [[#]], baseType: ![[L32:[0-9]+]]
 // CHECK: ![[L32]] = !DIBasicType(name: "long", size: [[#]], encoding: 
DW_ATE_signed)

___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.

[clang] [Clang][BPF] Add tests for btf_type_tag c2x-style attributes (PR #133666)

2025-03-30 Thread via cfe-commits

yonghong-song wrote:

cc @jemarch

https://github.com/llvm/llvm-project/pull/133666
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Driver] Add linker options to support statical linking to shared flang-rt on AIX. (PR #131822)

2025-03-30 Thread Hubert Tong via cfe-commits


@@ -127,9 +127,19 @@ void aix::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   }
 
   // Force static linking when "-static" is present.
-  if (Args.hasArg(options::OPT_static))
+  if (Args.hasArg(options::OPT_static)) {
 CmdArgs.push_back("-bnso");
 
+if (D.IsFlangMode()) {
+  // The folllowing linker options are needed to statically link to the
+  // shared libflang_rt.runtime.a on AIX
+  CmdArgs.push_back("-bI:/usr/lib/syscalls.exp");
+  CmdArgs.push_back("-bI:/usr/lib/aio.exp");
+  CmdArgs.push_back("-bI:/usr/lib/threads.exp");
+  CmdArgs.push_back("-lcrypt");
+}

hubert-reinterpretcast wrote:

> As the driver code is written in PR #131041, `libflang_rt.runtime.a` is 
> always linked in with the full path name no matter if it is static or shared.

The other PR does not change the lines I referenced in a way that causes 
`libflang_rt.runtime.a` to _always_ be linked in.

https://github.com/llvm/llvm-project/pull/131822
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] Fix some typos under clang (NFC) (PR #133558)

2025-03-30 Thread via cfe-commits

https://github.com/cor3ntin commented:

Thanks for working on this (that's a lot of typos!) 

https://github.com/llvm/llvm-project/pull/133558
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix broken HeaderFilterRegex when read from config file (PR #133582)

2025-03-30 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp updated 
https://github.com/llvm/llvm-project/pull/133582

>From 7c94ad36ff8eefd1d09cf303f8983d88cc25370c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Carlos=20G=C3=A1lvez?= 
Date: Sat, 29 Mar 2025 11:55:02 +
Subject: [PATCH] [clang-tidy] Fix broken HeaderFilterRegex when read from
 config file

PR https://github.com/llvm/llvm-project/pull/91400 broke the usage
of HeaderFilterRegex via config file, because it is now created at a
different point in the execution and leads to a different value.

The result of that is that using HeaderFilterRegex only in the config
file does NOT work, in other words clang-tidy stops triggering warnings
on header files, thereby losing a lot of coverage.

This patch reverts the logic so that the header filter is created
upon calling the getHeaderFilter() function.

Additionally, this patch adds 2 unit tests to prevent regressions in
the future:

- One of them, "simple", tests the most basic use case with a single
  top-level .clang-tidy file.

- The second one, "inheritance", demonstrates that the subfolder only
  gets warnings from headers within it, and not from parent headers.

Fixes #118009, #121969, #133453
---
 .../ClangTidyDiagnosticConsumer.cpp   | 36 ++-
 .../clang-tidy/ClangTidyDiagnosticConsumer.h  |  4 +++
 .../clang-tidy/ClangTidyOptions.cpp   |  4 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 ++
 .../inheritance/.clang-tidy   |  1 +
 .../inheritance/foo.cpp   |  3 ++
 .../inheritance/foo.h |  1 +
 .../inheritance/subfolder/.clang-tidy |  2 ++
 .../inheritance/subfolder/bar.cpp |  8 +
 .../inheritance/subfolder/bar.h   |  1 +
 .../simple/.clang-tidy|  1 +
 .../simple/foo.cpp|  3 ++
 .../simple/foo.h  |  1 +
 13 files changed, 49 insertions(+), 19 deletions(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/foo.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/foo.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/bar.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/inheritance/subfolder/bar.h
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/.clang-tidy
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/foo.cpp
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/header-filter-from-config-file/simple/foo.h

diff --git a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp 
b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
index 4c75b42270114..71e852545203e 100644
--- a/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
+++ b/clang-tools-extra/clang-tidy/ClangTidyDiagnosticConsumer.cpp
@@ -311,18 +311,7 @@ ClangTidyDiagnosticConsumer::ClangTidyDiagnosticConsumer(
 : Context(Ctx), ExternalDiagEngine(ExternalDiagEngine),
   RemoveIncompatibleErrors(RemoveIncompatibleErrors),
   GetFixesFromNotes(GetFixesFromNotes),
-  EnableNolintBlocks(EnableNolintBlocks) {
-
-  if (Context.getOptions().HeaderFilterRegex &&
-  !Context.getOptions().HeaderFilterRegex->empty())
-HeaderFilter =
-std::make_unique(*Context.getOptions().HeaderFilterRegex);
-
-  if (Context.getOptions().ExcludeHeaderFilterRegex &&
-  !Context.getOptions().ExcludeHeaderFilterRegex->empty())
-ExcludeHeaderFilter = std::make_unique(
-*Context.getOptions().ExcludeHeaderFilterRegex);
-}
+  EnableNolintBlocks(EnableNolintBlocks) {}
 
 void ClangTidyDiagnosticConsumer::finalizeLastError() {
   if (!Errors.empty()) {
@@ -571,17 +560,30 @@ void 
ClangTidyDiagnosticConsumer::checkFilters(SourceLocation Location,
   }
 
   StringRef FileName(File->getName());
-  LastErrorRelatesToUserCode =
-  LastErrorRelatesToUserCode || Sources.isInMainFile(Location) ||
-  (HeaderFilter &&
-   (HeaderFilter->match(FileName) &&
-!(ExcludeHeaderFilter && ExcludeHeaderFilter->match(FileName;
+  LastErrorRelatesToUserCode = LastErrorRelatesToUserCode ||
+   Sources.isInMainFile(Location) ||
+   (getHeaderFilter()->match(FileName) &&
+!getExcludeHeaderFilter()->match(FileName));
 
   unsigned LineNumber = Sources.getExpansionLineNumber(Location);
   LastErr

[clang] [clang-format]: Add `StaticInlineOnly` and `StaticInline` options to `ShortFunctionStyle` (PR #133598)

2025-03-30 Thread via cfe-commits

irymarchyk wrote:

@owenca, just to confirm - you are suggesting to add `Custom` string to 
`AllowShortFunctionsOnASingleLine` and new parameter 
(`AllowShortFunctionsOnASingleLineOptions` for example) which will control 
behavior if `AllowShortFunctionsOnASingleLine == Custom`? What options should 
be present? I think we can start with `Inline`, `Empty`, `static inline`, 
`constexpr` (?). 


https://github.com/llvm/llvm-project/pull/133598
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [X86][AVX10] Re-target mavx10.1 and emit warning for mavx10.x-256/512 and m[no-]evex512 (PR #132542)

2025-03-30 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

Ping?

https://github.com/llvm/llvm-project/pull/132542
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] Remove Native Client support (PR #133661)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-x86

Author: Brad Smith (brad0)


Changes

Working on preparing a patch to remove the Native Client support now that it is 
finally reaching end of life.

---

Patch is 156.94 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/133661.diff


97 Files Affected:

- (modified) clang/include/clang/Basic/TargetInfo.h (-4) 
- (modified) clang/lib/AST/ASTContext.cpp (-10) 
- (modified) clang/lib/Basic/CMakeLists.txt (-1) 
- (modified) clang/lib/Basic/Targets.cpp (-12) 
- (modified) clang/lib/Basic/Targets/ARM.cpp (-3) 
- (modified) clang/lib/Basic/Targets/OSTargets.h (-47) 
- (removed) clang/lib/Basic/Targets/PNaCl.cpp (-29) 
- (removed) clang/lib/Basic/Targets/PNaCl.h (-90) 
- (modified) clang/lib/CodeGen/CMakeLists.txt (-1) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+1-3) 
- (modified) clang/lib/CodeGen/TargetInfo.h (-3) 
- (removed) clang/lib/CodeGen/Targets/PNaCl.cpp (-114) 
- (modified) clang/lib/CodeGen/Targets/X86.cpp (+1-2) 
- (modified) clang/lib/Driver/CMakeLists.txt (-1) 
- (modified) clang/lib/Driver/Driver.cpp (-4) 
- (removed) clang/lib/Driver/ToolChains/NaCl.cpp (-371) 
- (removed) clang/lib/Driver/ToolChains/NaCl.h (-88) 
- (modified) clang/lib/Lex/InitHeaderSearch.cpp (-1) 
- (removed) clang/test/CodeGen/X86/x86_64-arguments-nacl.c (-92) 
- (modified) clang/test/CodeGen/X86/x86_64-longdouble.c (-16) 
- (modified) clang/test/CodeGen/arm-aapcs-vfp.c (-6) 
- (modified) clang/test/CodeGen/ext-int-cc.c (-9) 
- (modified) clang/test/CodeGen/long_double_fp128.cpp (-4) 
- (removed) clang/test/CodeGen/malign-double-x86-nacl.c (-43) 
- (modified) clang/test/CodeGen/target-data.c (-16) 
- (removed) clang/test/CodeGenCXX/x86_64-arguments-nacl-x32.cpp (-57) 
- (modified) clang/test/Driver/arm-alignment.c (-6) 
- (removed) clang/test/Driver/nacl-direct.c (-146) 
- (modified) clang/test/Driver/unsupported-target-arch.c (-4) 
- (removed) clang/test/Driver/x86_64-nacl-defines.cpp (-45) 
- (removed) clang/test/Frontend/x86_64-nacl-types.cpp (-37) 
- (modified) clang/test/Preprocessor/predefined-macros-no-warnings.c (-4) 
- (modified) llvm/include/llvm/BinaryFormat/ELF.h (-1) 
- (modified) llvm/include/llvm/BinaryFormat/MinidumpConstants.def (-1) 
- (modified) llvm/include/llvm/CodeGen/AtomicExpandUtils.h (+1-2) 
- (modified) llvm/include/llvm/TargetParser/Triple.h (-6) 
- (modified) llvm/lib/Target/ARM/ARMAsmPrinter.cpp (-6) 
- (modified) llvm/lib/Target/ARM/ARMFastISel.cpp (+2-6) 
- (modified) llvm/lib/Target/ARM/ARMFeatures.td (-6) 
- (modified) llvm/lib/Target/ARM/ARMFrameLowering.cpp (+1-2) 
- (modified) llvm/lib/Target/ARM/ARMISelLowering.cpp (+1-6) 
- (modified) llvm/lib/Target/ARM/ARMInstrInfo.td (+2-18) 
- (modified) llvm/lib/Target/ARM/ARMPredicates.td (-4) 
- (modified) llvm/lib/Target/ARM/ARMSubtarget.cpp (+3-3) 
- (modified) llvm/lib/Target/ARM/ARMSubtarget.h (-1) 
- (modified) llvm/lib/Target/ARM/ARMTargetMachine.cpp (+2-3) 
- (modified) llvm/lib/Target/ARM/ARMTargetTransformInfo.h (+3-3) 
- (modified) llvm/lib/Target/ARM/MCTargetDesc/ARMMCTargetDesc.cpp (-6) 
- (modified) llvm/lib/Target/Mips/MCTargetDesc/CMakeLists.txt (-1) 
- (removed) llvm/lib/Target/Mips/MCTargetDesc/MipsMCNaCl.h (-31) 
- (modified) llvm/lib/Target/Mips/MCTargetDesc/MipsMCTargetDesc.cpp (+2-7) 
- (removed) llvm/lib/Target/Mips/MCTargetDesc/MipsNaClELFStreamer.cpp (-274) 
- (modified) llvm/lib/Target/Mips/MipsAsmPrinter.cpp (-31) 
- (modified) llvm/lib/Target/Mips/MipsAsmPrinter.h (-2) 
- (modified) llvm/lib/Target/Mips/MipsBranchExpansion.cpp (+1-18) 
- (modified) llvm/lib/Target/Mips/MipsCallingConv.td (+2-9) 
- (modified) llvm/lib/Target/Mips/MipsDelaySlotFiller.cpp (-13) 
- (modified) llvm/lib/Target/Mips/MipsInstrFPU.td (+8-10) 
- (modified) llvm/lib/Target/Mips/MipsInstrInfo.td (-1) 
- (modified) llvm/lib/Target/Mips/MipsRegisterInfo.cpp (-7) 
- (modified) llvm/lib/Target/Mips/MipsSubtarget.h (-1) 
- (modified) llvm/lib/Target/X86/X86ExpandPseudo.cpp (+1-2) 
- (modified) llvm/lib/Target/X86/X86FrameLowering.cpp (+3-3) 
- (modified) llvm/lib/Target/X86/X86ISelDAGToDAG.cpp (-4) 
- (modified) llvm/lib/Target/X86/X86ISelLowering.cpp (+3-5) 
- (modified) llvm/lib/Target/X86/X86InstrPredicates.td (-2) 
- (modified) llvm/lib/Target/X86/X86Subtarget.cpp (+2-2) 
- (modified) llvm/lib/Target/X86/X86Subtarget.h (+2-5) 
- (modified) llvm/lib/Target/X86/X86TargetMachine.cpp (+3-3) 
- (modified) llvm/lib/TargetParser/ARMTargetParser.cpp (-1) 
- (modified) llvm/lib/TargetParser/Triple.cpp (-2) 
- (modified) llvm/test/CodeGen/ARM/fast-isel-align.ll (-3) 
- (modified) llvm/test/CodeGen/ARM/struct_byval.ll (-14) 
- (modified) llvm/test/CodeGen/ARM/trap.ll (-20) 
- (removed) llvm/test/CodeGen/ARM/varargs-spill-stack-align-nacl.ll (-31) 
- (modified) llvm/test/CodeGen/Mips/fastcc.ll (-12) 
- (modified) llvm/test/CodeGen/Mips/fp-indexed-ls.ll (-11) 
- (modified) llvm/test/CodeGen/Mips/indirect-jump-hazard/long-branch.ll (-1) 
- (modified) llvm/test/C

[clang] [Clang][Cmake] fix libtool duplicate member name warnings (PR #133619)

2025-03-30 Thread Jonathan Thackray via cfe-commits

https://github.com/jthackray approved this pull request.

Thanks for this fix. LGTM.

https://github.com/llvm/llvm-project/pull/133619
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-format]: Add `StaticInlineOnly` and `StaticInline` options to `ShortFunctionStyle` (PR #133598)

2025-03-30 Thread via cfe-commits

https://github.com/irymarchyk updated 
https://github.com/llvm/llvm-project/pull/133598

>From cc9c8d79396b6be64910eda59c4f7bd1a1d0a839 Mon Sep 17 00:00:00 2001
From: Ivan Rymarchyk <>
Date: Sat, 29 Mar 2025 13:54:32 -0700
Subject: [PATCH 1/3] [clang-format]: Add `StaticInlineOnly` and `StaticInline`
 options to `ShortFunctionStyle`

Currently, the `ShortFunctionStyle` option in clang-format lacks the 
granularity to specifically control the single-line formatting of `static 
inline` C functions independently from other function types like regular empty 
functions.

**Problem:**

Users may want to enforce a style where:

1.  **Only `static inline` functions** are allowed on a single line (if they 
fit), forcing all other functions (including empty ones) onto multiple lines. 
This is useful for keeping utility/helper functions concise while maintaining a 
consistent multi-line format for primary function definitions.
2.  **`static inline` functions *or* empty functions** are allowed on a single 
line (if they fit), while other non-empty, non-`static inline` functions are 
forced onto multiple lines. This is a slightly less strict variation.

The existing `ShortFunctionStyle` options do not cover these specific C use 
cases adequately:

*   `None`: Forces all functions multi-line.
*   `Empty`: Allows *any* empty function on one line, not just `static inline` 
ones.
*   `All`: Allows any short function on one line.
*   `Inline`/`InlineOnly`: Primarily target C++ member functions or C++ free 
inline functions, not specifically the C `static inline` pattern.

**Proposed Solution:**

Introduce two new values for the `ShortFunctionStyle` enum (currently named 
`ShortFunctionStyle` internally, likely `SFS_...` values):

1.  **`StaticInlineOnly`**
*   **Configuration Name:** `StaticInlineOnly`
*   **Internal Enum Value (Suggestion):** `SFS_StaticInlineOnly`
*   **Behavior:** Allows *only* functions declared with both `static` and 
`inline` specifiers to be formatted on a single line, provided they fit within 
the `ColumnLimit`. All other functions (regular, static non-inline, inline 
non-static, empty or not) must be formatted across multiple lines.

2.  **`StaticInline`**
*   **Configuration Name:** `StaticInline`
*   **Internal Enum Value (Suggestion):** `SFS_StaticInline`
*   **Behavior:** Allows functions declared with both `static` and `inline` 
specifiers *or* functions with an empty body (`{}`) to be formatted on a single 
line, provided they fit within the `ColumnLimit`. Non-empty functions that are 
*not* `static inline` must be formatted across multiple lines. This effectively 
combines the `SFS_Empty` behavior with allowing non-empty `static inline` 
functions.

**Expected Formatting:**

*   **With `ShortFunctionStyle: StaticInlineOnly`**
```c
void f1(void) // Multi-line (not static inline)
{
}
int f2(int a, int b) // Multi-line (not static inline)
{
return a + b;
}
static void f3(void) // Multi-line (not static inline)
{
}
static int f4(int a, int b) // Multi-line (not static inline)
{
return a + b;
}
static inline void f5(void) {} // Single-line allowed
static inline int f6(int a, int b) { return a + b; } // Single-line allowed 
(if fits)
inline void f7(void) // Multi-line (not static inline)
{
}
```

*   **With `ShortFunctionStyle: StaticInline`** (Implies Empty)
```c
void f1(void) {} // Single-line allowed (empty)
int f2(int a, int b) // Multi-line (non-empty, not static inline)
{
return a + b;
}
static void f3(void) {} // Single-line allowed (empty)
static int f4(int a, int b) // Multi-line (non-empty, not static inline)
{
return a + b;
}
static inline void f5(void) {} // Single-line allowed (static inline and 
empty)
static inline int f6(int a, int b) { return a + b; } // Single-line allowed 
(static inline, if fits)
inline void f7(void) {} // Single-line allowed (empty)
```
---
 clang/docs/ClangFormatStyleOptions.rst  | 17 +
 clang/include/clang/Format/Format.h | 13 
 clang/lib/Format/Format.cpp |  2 +
 clang/lib/Format/TokenAnnotator.cpp |  6 +-
 clang/lib/Format/UnwrappedLineFormatter.cpp | 31 +++-
 clang/unittests/Format/ConfigParseTest.cpp  |  6 ++
 clang/unittests/Format/FormatTest.cpp   | 79 +
 7 files changed, 150 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 9ecac68ae72bf..e5641fa5037ae 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1926,6 +1926,15 @@ the configuration (without a prefix: ``Auto``).
   void f() {
   }
 
+  * ``SFS_StaticInlineOnly`` (in configuration: ``StaticInlineOnly``)
+Only merge functions defined as static inline.
+
+.. code-block:: c++
+
+  void f5(void) 

[clang] [clang][modules] Guard against bad -fmodule-file mappings (#132059) (PR #133462)

2025-03-30 Thread Naveen Seth Hanig via cfe-commits

https://github.com/naveen-seth updated 
https://github.com/llvm/llvm-project/pull/133462

>From 74ace4fd3c71ff59f2d89680c0f1382d0f9933f4 Mon Sep 17 00:00:00 2001
From: naveen-seth 
Date: Fri, 28 Mar 2025 06:59:06 +0100
Subject: [PATCH] [clang][modules] Guard against bad -fmodule-file mappings
 (#132059)

Fix #132059.

Providing incorrect mappings via -fmodule-file==,
such that the BMI file corresponds to a different module which
transitively imports the specified module, could previously crash the
compiler.

The crash is caused during serialization, when trying to resolve
declaration IDs in the AST body after having loaded the wrong module.

This commit fixes the issue by checking the module's identity while
reading the AST's control block and erroring out if a mismatch is
detected.
---
 .../Basic/DiagnosticSerializationKinds.td |  2 +
 clang/include/clang/Serialization/ASTReader.h | 17 +
 clang/lib/Frontend/ASTUnit.cpp|  1 +
 clang/lib/Frontend/ChainedIncludesSource.cpp  |  1 +
 clang/lib/Frontend/CompilerInstance.cpp   | 15 ++--
 clang/lib/Serialization/ASTReader.cpp | 73 +--
 .../fmodule-file-bad-transitive-mapping.cpp   | 46 
 7 files changed, 124 insertions(+), 31 deletions(-)
 create mode 100644 clang/test/Modules/fmodule-file-bad-transitive-mapping.cpp

diff --git a/clang/include/clang/Basic/DiagnosticSerializationKinds.td 
b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
index 3914d3930bec7..16cc946e3f3d9 100644
--- a/clang/include/clang/Basic/DiagnosticSerializationKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSerializationKinds.td
@@ -98,6 +98,8 @@ def err_imported_module_relocated : Error<
 def err_module_different_modmap : Error<
 "module '%0' %select{uses|does not use}1 additional module map '%2'"
 "%select{| not}1 used when the module was built">;
+def err_module_mismatch : Error<
+  "tried loading module '%0' from '%1' but found module '%2' instead">, 
DefaultFatal;
 
 def err_ast_file_macro_def_undef : Error<
 "macro '%0' was %select{defined|undef'd}1 in the AST file '%2' but "
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 2779b3d1cf2ea..57f2a08e09359 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -423,6 +423,9 @@ class ASTReader
 /// configuration.
 ConfigurationMismatch,
 
+/// The AST file contains a different module than expected.
+ModuleMismatch,
+
 /// The AST file has errors.
 HadErrors
   };
@@ -1512,11 +1515,13 @@ class ASTReader
 SourceLocation ImportLoc, ModuleFile *ImportedBy,
 SmallVectorImpl &Loaded,
 off_t ExpectedSize, time_t ExpectedModTime,
+StringRef ExpectedModuleName,
 ASTFileSignature ExpectedSignature,
 unsigned ClientLoadCapabilities);
   ASTReadResult ReadControlBlock(ModuleFile &F,
  SmallVectorImpl &Loaded,
  const ModuleFile *ImportedBy,
+ StringRef ExpectedModuleName,
  unsigned ClientLoadCapabilities);
   static ASTReadResult
   ReadOptionsBlock(llvm::BitstreamCursor &Stream, StringRef Filename,
@@ -1819,6 +1824,18 @@ class ASTReader
 unsigned ClientLoadCapabilities,
 ModuleFile **NewLoadedModuleFile = nullptr);
 
+  /// \overload
+  ///
+  /// Calls the above function and checks if the AST file contains the expected
+  /// module. Returns ASTReadResult::Failure on mismatch.
+  ///
+  /// \param ExpectedModuleName The expected name of the new loaded module.
+  ASTReadResult ReadAST(StringRef FileName, ModuleKind Type,
+SourceLocation ImportLoc,
+unsigned ClientLoadCapabilities,
+StringRef ExpectedModuleName,
+ModuleFile **NewLoadedModuleFile = nullptr);
+
   /// Make the entities in the given module and any of its (non-explicit)
   /// submodules visible to name lookup.
   ///
diff --git a/clang/lib/Frontend/ASTUnit.cpp b/clang/lib/Frontend/ASTUnit.cpp
index 0a5f1cfd1a264..7500be81ea976 100644
--- a/clang/lib/Frontend/ASTUnit.cpp
+++ b/clang/lib/Frontend/ASTUnit.cpp
@@ -887,6 +887,7 @@ std::unique_ptr ASTUnit::LoadFromASTFile(
   case ASTReader::OutOfDate:
   case ASTReader::VersionMismatch:
   case ASTReader::ConfigurationMismatch:
+  case ASTReader::ModuleMismatch:
   case ASTReader::HadErrors:
 AST->getDiagnostics().Report(diag::err_fe_unable_to_load_pch);
 return nullptr;
diff --git a/clang/lib/Frontend/ChainedIncludesSource.cpp 
b/clang/lib/Frontend/ChainedIncludesSource.cpp
index a7096e27796a0..ee0363249124b 100644
--- a/clang/lib/Frontend/ChainedIncludesSource.cpp
+++

[clang-tools-extra] [NFC][clang-tidy] Add type annotations to check_clang_tidy (PR #133140)

2025-03-30 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `flang-runtime-cuda-clang` 
running on `as-builder-7` while building `clang-tools-extra` at step 7 
"build-flang-default".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/7/builds/12917


Here is the relevant piece of the build log for the reference

```
Step 7 (build-flang-default) failure: cmake (failure)
...
92.613 [1554/130/6034] Building CXX object 
tools/mlir/lib/ExecutionEngine/CMakeFiles/MLIRExecutionEngine.dir/ExecutionEngine.cpp.o
92.669 [1553/130/6035] Building CXX object 
tools/mlir/test/lib/Dialect/Transform/CMakeFiles/MLIRTestTransformDialect.dir/TestTransformDialectInterpreter.cpp.o
92.740 [1552/130/6036] Building CXX object 
tools/mlir/lib/CAPI/Dialect/CMakeFiles/obj.MLIRCAPIAMDGPU.dir/AMDGPU.cpp.o
92.743 [1551/130/6037] Linking CXX static library lib/libMLIRTransformUtils.a
92.803 [1550/130/6038] Building CXX object 
tools/mlir/lib/CAPI/Dialect/CMakeFiles/obj.MLIRCAPIArith.dir/Arith.cpp.o
92.839 [1549/130/6039] Linking CXX static library lib/libMLIRMathToEmitC.a
92.969 [1548/130/6040] Linking CXX static library lib/libMLIRComplexToLibm.a
93.040 [1547/130/6041] Linking CXX static library lib/libMLIRControlFlowToSCF.a
93.145 [1546/130/6042] Linking CXX static library lib/libMLIRFuncToEmitC.a
93.157 [1545/130/6043] Linking CXX static library lib/libMLIRMathToLibm.a
command timed out: 1200 seconds without output running [b'cmake', b'--build', 
b'.'], attempting to kill
process killed by signal 9
program finished with exit code -1
elapsedTime=4050.115849

```



https://github.com/llvm/llvm-project/pull/133140
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix broken HeaderFilterRegex when read from config file (PR #133582)

2025-03-30 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

Was there anything else I should fix @HerrCai0907 ? It would be good to get 
this in in soon and cherrypick to branch 20.

https://github.com/llvm/llvm-project/pull/133582
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [llvm] [PowerPC] Enable indiviual crbits tracking at -O2 (PR #133617)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Henry Jiang (mustartt)


Changes

https://reviews.llvm.org/D124060

---
Full diff: https://github.com/llvm/llvm-project/pull/133617.diff


5 Files Affected:

- (modified) clang/lib/Basic/Targets/PPC.cpp (-5) 
- (modified) llvm/lib/Target/PowerPC/PPC.td (+43-39) 
- (modified) llvm/lib/Target/PowerPC/PPCSubtarget.cpp (+9) 
- (modified) llvm/lib/Target/PowerPC/PPCSubtarget.h (+1) 
- (modified) llvm/lib/Target/PowerPC/PPCTargetMachine.cpp (-7) 


``diff
diff --git a/clang/lib/Basic/Targets/PPC.cpp b/clang/lib/Basic/Targets/PPC.cpp
index 425ad68bb9098..61d567892b498 100644
--- a/clang/lib/Basic/Targets/PPC.cpp
+++ b/clang/lib/Basic/Targets/PPC.cpp
@@ -559,11 +559,6 @@ bool PPCTargetInfo::initFeatureMap(
 .Case("pwr9", true)
 .Case("pwr8", true)
 .Default(false);
-  Features["crbits"] = llvm::StringSwitch(CPU)
-.Case("ppc64le", true)
-.Case("pwr9", true)
-.Case("pwr8", true)
-.Default(false);
   Features["vsx"] = llvm::StringSwitch(CPU)
 .Case("ppc64le", true)
 .Case("pwr9", true)
diff --git a/llvm/lib/Target/PowerPC/PPC.td b/llvm/lib/Target/PowerPC/PPC.td
index 39da428461393..9f0f271b619c7 100644
--- a/llvm/lib/Target/PowerPC/PPC.td
+++ b/llvm/lib/Target/PowerPC/PPC.td
@@ -74,7 +74,7 @@ def Feature64BitRegs : 
SubtargetFeature<"64bitregs","Use64BitRegs", "true",
 
 // Specify if we should store and manipulate i1 values in the individual
 // condition register bits.
-def FeatureCRBits: SubtargetFeature<"crbits", "UseCRBits", "true",
+def FeatureCRBits: SubtargetFeature<"crbits", "HasCRBits", "true",
   "Use condition-register bits individually">;
 def FeatureFPU   : SubtargetFeature<"fpu","HasFPU","true",
 "Enable classic FPU instructions",
@@ -390,6 +390,7 @@ def ProcessorFeatures {
   FeatureFPCVT,
   FeatureISEL,
   FeaturePOPCNTD,
+  FeatureCRBits,
   FeatureCMPB,
   FeatureLDBRX,
   Feature64Bit,
@@ -577,79 +578,82 @@ include "GISel/PPCRegisterBanks.td"
 //
 
 def : Processor<"generic", G3Itineraries, [Directive32, FeatureHardFloat,
-   FeatureMFTB]>;
+   FeatureMFTB, FeatureCRBits]>;
 def : ProcessorModel<"440", PPC440Model, [Directive440, FeatureISEL,
   FeatureFRES, FeatureFRSQRTE,
   FeatureICBT, FeatureBookE,
-  FeatureMSYNC, FeatureMFTB]>;
+  FeatureMSYNC, FeatureMFTB,
+  FeatureCRBits]>;
 def : ProcessorModel<"450", PPC440Model, [Directive440, FeatureISEL,
   FeatureFRES, FeatureFRSQRTE,
   FeatureICBT, FeatureBookE,
-  FeatureMSYNC, FeatureMFTB]>;
-def : Processor<"601", G3Itineraries, [Directive601, FeatureFPU]>;
+  FeatureMSYNC, FeatureMFTB,
+  FeatureCRBits]>;
+def : Processor<"601", G3Itineraries, [Directive601, FeatureFPU,
+   FeatureCRBits]>;
 def : Processor<"602", G3Itineraries, [Directive602, FeatureFPU,
-   FeatureMFTB]>;
-def : Processor<"603", G3Itineraries, [Directive603,
-   FeatureFRES, FeatureFRSQRTE,
-   FeatureMFTB]>;
-def : Processor<"603e", G3Itineraries, [Directive603,
-FeatureFRES, FeatureFRSQRTE,
-FeatureMFTB]>;
+   FeatureMFTB, FeatureCRBits]>;
+def : Processor<"603", G3Itineraries, [Directive603, FeatureFRES,
+   FeatureFRSQRTE, FeatureMFTB,
+   FeatureCRBits]>;
+def : Processor<"603e", G3Itineraries, [Directive603, FeatureFRES,
+FeatureFRSQRTE, FeatureMFTB,
+FeatureCRBits]>;
 def : Processor<"603ev", G3Itineraries, [Directive603,
  FeatureFRES, FeatureFRSQRTE,
- FeatureMFTB]>;
+ 

[clang] [cmake] Refactor clang unittest cmake (PR #133545)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-modules

Author: Reid Kleckner (rnk)


Changes

Pass all the dependencies into add_clang_unittest. This is consistent with how 
it is done for LLDB. I borrowed the same named argument list structure from 
add_lldb_unittest. This is a necessary step towards consolidating unit tests 
into fewer binaries, but seems like a good refactoring in its own right.

---

Patch is 22.08 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/133545.diff


28 Files Affected:

- (modified) clang/unittests/AST/ByteCode/CMakeLists.txt (+3-9) 
- (modified) clang/unittests/AST/CMakeLists.txt (+7-16) 
- (modified) clang/unittests/ASTMatchers/CMakeLists.txt (+7-15) 
- (modified) clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/Analysis/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/Analysis/FlowSensitive/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/Basic/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/CMakeLists.txt (+28-4) 
- (modified) clang/unittests/CodeGen/CMakeLists.txt (+5-10) 
- (modified) clang/unittests/CrossTU/CMakeLists.txt (+3-9) 
- (modified) clang/unittests/DirectoryWatcher/CMakeLists.txt (+3-8) 
- (modified) clang/unittests/Driver/CMakeLists.txt (+7-12) 
- (modified) clang/unittests/Format/CMakeLists.txt (+3-8) 
- (modified) clang/unittests/Frontend/CMakeLists.txt (+4-8) 
- (modified) clang/unittests/Index/CMakeLists.txt (+8-6) 
- (modified) clang/unittests/InstallAPI/CMakeLists.txt (+3-6) 
- (modified) clang/unittests/Interpreter/CMakeLists.txt (+12-13) 
- (modified) clang/unittests/Interpreter/ExceptionTests/CMakeLists.txt (+9-11) 
- (modified) clang/unittests/Lex/CMakeLists.txt (+4-12) 
- (modified) clang/unittests/Rewrite/CMakeLists.txt (+3-7) 
- (modified) clang/unittests/Sema/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/Serialization/CMakeLists.txt (+6-11) 
- (modified) clang/unittests/StaticAnalyzer/CMakeLists.txt (+5-13) 
- (modified) clang/unittests/Support/CMakeLists.txt (+3-8) 
- (modified) clang/unittests/Tooling/CMakeLists.txt (+11-17) 
- (modified) clang/unittests/Tooling/Syntax/CMakeLists.txt (+5-10) 
- (modified) clang/unittests/libclang/CMakeLists.txt (+1-4) 
- (modified) clang/unittests/libclang/CrashTests/CMakeLists.txt (+1-4) 


``diff
diff --git a/clang/unittests/AST/ByteCode/CMakeLists.txt 
b/clang/unittests/AST/ByteCode/CMakeLists.txt
index b862fb4834fbd..7ccadda2eeb26 100644
--- a/clang/unittests/AST/ByteCode/CMakeLists.txt
+++ b/clang/unittests/AST/ByteCode/CMakeLists.txt
@@ -2,19 +2,13 @@ add_clang_unittest(InterpTests
   BitcastBuffer.cpp
   Descriptor.cpp
   toAPValue.cpp
-  )
-
-clang_target_link_libraries(InterpTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
   clangFrontend
   clangSerialization
   clangTooling
-  )
-
-  target_link_libraries(InterpTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
-)
+  )
diff --git a/clang/unittests/AST/CMakeLists.txt 
b/clang/unittests/AST/CMakeLists.txt
index bfa6082a6ffa4..f27d34e8a0719 100644
--- a/clang/unittests/AST/CMakeLists.txt
+++ b/clang/unittests/AST/CMakeLists.txt
@@ -1,10 +1,3 @@
-set(LLVM_LINK_COMPONENTS
-  FrontendOpenMP
-  Support
-  TargetParser
-  )
-
-
 add_subdirectory(ByteCode)
 
 add_clang_unittest(ASTTests
@@ -43,10 +36,7 @@ add_clang_unittest(ASTTests
   TemplateNameTest.cpp
   TypePrinterTest.cpp
   UnresolvedSetTest.cpp
-  )
-
-clang_target_link_libraries(ASTTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
@@ -54,11 +44,12 @@ clang_target_link_libraries(ASTTests
   clangLex
   clangSerialization
   clangTooling
-  )
-
-target_link_libraries(ASTTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
   LLVMTestingAnnotations
   LLVMTestingSupport
-)
+  LLVM_COMPONENTS
+  FrontendOpenMP
+  Support
+  TargetParser
+  )
diff --git a/clang/unittests/ASTMatchers/CMakeLists.txt 
b/clang/unittests/ASTMatchers/CMakeLists.txt
index 6a1e629d81b65..47bd5c108bb5a 100644
--- a/clang/unittests/ASTMatchers/CMakeLists.txt
+++ b/clang/unittests/ASTMatchers/CMakeLists.txt
@@ -1,31 +1,23 @@
-set(LLVM_LINK_COMPONENTS
-  FrontendOpenMP
-  Support
-  TargetParser
-  )
-
 add_clang_unittest(ASTMatchersTests
   ASTMatchersInternalTest.cpp
   ASTMatchersNodeTest.cpp
   ASTMatchersNarrowingTest.cpp
   ASTMatchersTraversalTest.cpp
   GtestMatchersTest.cpp
-  )
-
-clang_target_link_libraries(ASTMatchersTests
-  PRIVATE
+  CLANG_LIBS
   clangAST
   clangASTMatchers
   clangBasic
   clangFrontend
   clangSerialization
   clangTooling
-  )
-
-target_link_libraries(ASTMatchersTests
-  PRIVATE
+  LINK_LIBS
   clangTesting
   LLVMTestingSupport
-)
+  LLVM_COMPONENTS
+  FrontendOpenMP
+  Support
+  TargetParser
+  )
 
 add_subdirectory(Dynamic)
diff --git a/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt 
b/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt
index 6d0e12bcb0759..b6db7ce62afe7 100644
--- a/clang/unittests/ASTMatchers/Dynamic/CMakeLists.txt

[clang] [llvm] [SROA] Vector promote some memsets (PR #133301)

2025-03-30 Thread Matt Arsenault via cfe-commits


@@ -1011,6 +1011,31 @@ static Value *foldPHINodeOrSelectInst(Instruction &I) {
   return foldSelectInst(cast(I));
 }
 
+/// Returns a fixed vector type equivalent to the memory set by II or nullptr 
if
+/// unable to do so.
+static FixedVectorType *getVectorTypeFor(const MemSetInst &II,
+ const DataLayout &DL) {
+  const ConstantInt *Length = dyn_cast(II.getLength());
+  if (!Length)
+return nullptr;
+
+  APInt Val = Length->getValue();

arsenm wrote:

```suggestion
  const APInt &Val = Length->getValue();
```

https://github.com/llvm/llvm-project/pull/133301
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [lldb] [llvm] Add test to clang-doc, it can test comments in macro. Original issue is #59819. (PR #132360)

2025-03-30 Thread Paul Kirth via cfe-commits


@@ -0,0 +1,32 @@
+// RUN: rm -rf %t && mkdir -p %t
+// RUN: clang-doc --format=md --doxygen --output=%t --executor=standalone %s
+// RUN: clang-doc --format=html --doxygen --output=%t --executor=standalone %s
+// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.md 
--check-prefix=MD-MyClass-LINE
+// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.md --check-prefix=MD-MyClass
+// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.html 
--check-prefix=HTML-MyClass-LINE
+// RUN: FileCheck %s < %t/GlobalNamespace/MyClass.html 
--check-prefix=HTML-MyClass
+
+#define DECLARE_METHODS   \
+/**
+ * @brief Declare a method to calculate the sum of two numbers
+ */   \
+int Add(int a, int b) \
+{ \
+return a + b; \
+}
+
+// MD-MyClass: ### Add
+// MD-MyClass: *public int Add(int a, int b)*
+// MD-MyClass: **brief** Declare a method to calculate the sum of two numbers
+
+// HTML-MyClass: public int Add(int a, int b)
+// HTML-MyClass: brief
+// HTML-MyClass:  Declare a method to calculate the sum of two numbers
+
+
+class MyClass {

ilovepi wrote:

What is this class testing? It's not clear what property you're trying to 
exercise. I see you expect the macro to expand in the class, but I don't think 
you're testing what you think you are. 

https://github.com/llvm/llvm-project/pull/132360
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [flang] [flang] Expose -m64 option (PR #132409)

2025-03-30 Thread Kiran Chandramohan via cfe-commits

kiranchandramohan wrote:

> @JDPailleux @kiranchandramohan We are planning to add support for flang to 
> compile 32-bit application as well as building 32-bit flang-rt on AIX. The 
> first thing would be to enable `-m32` for flang in the driver. I saw Kiran's 
> comment. Would it be possible to make `-m32` available in the driver but 
> disable it in front_end if desired?

When you start working on 32-bit flang-rt support, you should feel free to add 
the `-m32` flag to the driver.

https://github.com/llvm/llvm-project/pull/132409
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang][NFC] Improve const correctess of constraint normalization (PR #133633)

2025-03-30 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/133633

None

>From ffd42830be4e9b4a92524797988d5f0c1deccf70 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Sun, 30 Mar 2025 11:26:30 +0200
Subject: [PATCH] [Clang][NFC] Improve const correctess of constraint
 normalization

---
 clang/include/clang/Sema/Sema.h| 17 +++-
 clang/include/clang/Sema/SemaConcept.h | 14 +-
 clang/lib/Sema/SemaConcept.cpp | 36 ++
 3 files changed, 37 insertions(+), 30 deletions(-)

diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 066bce61c74c1..c74e709ce06d2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14660,7 +14660,8 @@ class Sema final : public SemaBase {
 bool First = true);
 
   const NormalizedConstraint *getNormalizedAssociatedConstraints(
-  NamedDecl *ConstrainedDecl, ArrayRef 
AssociatedConstraints);
+  const NamedDecl *ConstrainedDecl,
+  ArrayRef AssociatedConstraints);
 
   /// \brief Check whether the given declaration's associated constraints are
   /// at least as constrained than another declaration's according to the
@@ -14670,28 +14671,30 @@ class Sema final : public SemaBase {
   /// at least constrained than D2, and false otherwise.
   ///
   /// \returns true if an error occurred, false otherwise.
-  bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef AC1,
-  NamedDecl *D2, MutableArrayRef AC2,
-  bool &Result);
+  bool IsAtLeastAsConstrained(const NamedDecl *D1,
+  MutableArrayRef AC1,
+  const NamedDecl *D2,
+  MutableArrayRef AC2, bool &Result);
 
   /// If D1 was not at least as constrained as D2, but would've been if a pair
   /// of atomic constraints involved had been declared in a concept and not
   /// repeated in two separate places in code.
   /// \returns true if such a diagnostic was emitted, false otherwise.
   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
-  NamedDecl *D1, ArrayRef AC1, NamedDecl *D2,
+  const NamedDecl *D1, ArrayRef AC1, const NamedDecl *D2,
   ArrayRef AC2);
 
 private:
   /// Caches pairs of template-like decls whose associated constraints were
   /// checked for subsumption and whether or not the first's constraints did in
   /// fact subsume the second's.
-  llvm::DenseMap, bool> SubsumptionCache;
+  llvm::DenseMap, bool>
+  SubsumptionCache;
   /// Caches the normalized associated constraints of declarations (concepts or
   /// constrained declarations). If an error occurred while normalizing the
   /// associated constraints of the template or concept, nullptr will be cached
   /// here.
-  llvm::DenseMap NormalizationCache;
+  llvm::DenseMap NormalizationCache;
 
   llvm::ContextualFoldingSet
   SatisfactionCache;
diff --git a/clang/include/clang/Sema/SemaConcept.h 
b/clang/include/clang/Sema/SemaConcept.h
index fda22b779c636..cbb3720c30ee2 100644
--- a/clang/include/clang/Sema/SemaConcept.h
+++ b/clang/include/clang/Sema/SemaConcept.h
@@ -31,10 +31,10 @@ enum { ConstraintAlignment = 8 };
 
 struct alignas(ConstraintAlignment) AtomicConstraint {
   const Expr *ConstraintExpr;
-  NamedDecl *ConstraintDecl;
+  const NamedDecl *ConstraintDecl;
   std::optional> ParameterMapping;
 
-  AtomicConstraint(const Expr *ConstraintExpr, NamedDecl *ConstraintDecl)
+  AtomicConstraint(const Expr *ConstraintExpr, const NamedDecl *ConstraintDecl)
   : ConstraintExpr(ConstraintExpr), ConstraintDecl(ConstraintDecl) {};
 
   bool hasMatchingParameterMapping(ASTContext &C,
@@ -114,9 +114,9 @@ struct NormalizedConstraint {
 
 private:
   static std::optional
-  fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef E);
+  fromConstraintExprs(Sema &S, const NamedDecl *D, ArrayRef E);
   static std::optional
-  fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E);
+  fromConstraintExpr(Sema &S, const NamedDecl *D, const Expr *E);
 };
 
 struct alignas(ConstraintAlignment) NormalizedConstraintPair {
@@ -137,7 +137,7 @@ struct alignas(ConstraintAlignment) FoldExpandedConstraint {
 };
 
 const NormalizedConstraint *getNormalizedAssociatedConstraints(
-Sema &S, NamedDecl *ConstrainedDecl,
+Sema &S, const NamedDecl *ConstrainedDecl,
 ArrayRef AssociatedConstraints);
 
 /// \brief SubsumptionChecker establishes subsumption
@@ -149,8 +149,8 @@ class SubsumptionChecker {
 
   SubsumptionChecker(Sema &SemaRef, SubsumptionCallable Callable = {});
 
-  std::optional Subsumes(NamedDecl *DP, ArrayRef P,
-   NamedDecl *DQ, ArrayRef Q);
+  std::optional Subsumes(const NamedDecl *DP, ArrayRef P,
+   const NamedDecl *DQ, ArrayRef Q);
 
   bool Subsumes(const NormalizedConstraint *P, const NormalizedConstraint *Q);
 
diff --git a/clang/lib/Sema/SemaConcept.cp

[clang] [Clang][NFC] Improve const correctess of constraint normalization (PR #133633)

2025-03-30 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes



---
Full diff: https://github.com/llvm/llvm-project/pull/133633.diff


3 Files Affected:

- (modified) clang/include/clang/Sema/Sema.h (+10-7) 
- (modified) clang/include/clang/Sema/SemaConcept.h (+7-7) 
- (modified) clang/lib/Sema/SemaConcept.cpp (+20-16) 


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 066bce61c74c1..c74e709ce06d2 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -14660,7 +14660,8 @@ class Sema final : public SemaBase {
 bool First = true);
 
   const NormalizedConstraint *getNormalizedAssociatedConstraints(
-  NamedDecl *ConstrainedDecl, ArrayRef 
AssociatedConstraints);
+  const NamedDecl *ConstrainedDecl,
+  ArrayRef AssociatedConstraints);
 
   /// \brief Check whether the given declaration's associated constraints are
   /// at least as constrained than another declaration's according to the
@@ -14670,28 +14671,30 @@ class Sema final : public SemaBase {
   /// at least constrained than D2, and false otherwise.
   ///
   /// \returns true if an error occurred, false otherwise.
-  bool IsAtLeastAsConstrained(NamedDecl *D1, MutableArrayRef AC1,
-  NamedDecl *D2, MutableArrayRef AC2,
-  bool &Result);
+  bool IsAtLeastAsConstrained(const NamedDecl *D1,
+  MutableArrayRef AC1,
+  const NamedDecl *D2,
+  MutableArrayRef AC2, bool &Result);
 
   /// If D1 was not at least as constrained as D2, but would've been if a pair
   /// of atomic constraints involved had been declared in a concept and not
   /// repeated in two separate places in code.
   /// \returns true if such a diagnostic was emitted, false otherwise.
   bool MaybeEmitAmbiguousAtomicConstraintsDiagnostic(
-  NamedDecl *D1, ArrayRef AC1, NamedDecl *D2,
+  const NamedDecl *D1, ArrayRef AC1, const NamedDecl *D2,
   ArrayRef AC2);
 
 private:
   /// Caches pairs of template-like decls whose associated constraints were
   /// checked for subsumption and whether or not the first's constraints did in
   /// fact subsume the second's.
-  llvm::DenseMap, bool> SubsumptionCache;
+  llvm::DenseMap, bool>
+  SubsumptionCache;
   /// Caches the normalized associated constraints of declarations (concepts or
   /// constrained declarations). If an error occurred while normalizing the
   /// associated constraints of the template or concept, nullptr will be cached
   /// here.
-  llvm::DenseMap NormalizationCache;
+  llvm::DenseMap NormalizationCache;
 
   llvm::ContextualFoldingSet
   SatisfactionCache;
diff --git a/clang/include/clang/Sema/SemaConcept.h 
b/clang/include/clang/Sema/SemaConcept.h
index fda22b779c636..cbb3720c30ee2 100644
--- a/clang/include/clang/Sema/SemaConcept.h
+++ b/clang/include/clang/Sema/SemaConcept.h
@@ -31,10 +31,10 @@ enum { ConstraintAlignment = 8 };
 
 struct alignas(ConstraintAlignment) AtomicConstraint {
   const Expr *ConstraintExpr;
-  NamedDecl *ConstraintDecl;
+  const NamedDecl *ConstraintDecl;
   std::optional> ParameterMapping;
 
-  AtomicConstraint(const Expr *ConstraintExpr, NamedDecl *ConstraintDecl)
+  AtomicConstraint(const Expr *ConstraintExpr, const NamedDecl *ConstraintDecl)
   : ConstraintExpr(ConstraintExpr), ConstraintDecl(ConstraintDecl) {};
 
   bool hasMatchingParameterMapping(ASTContext &C,
@@ -114,9 +114,9 @@ struct NormalizedConstraint {
 
 private:
   static std::optional
-  fromConstraintExprs(Sema &S, NamedDecl *D, ArrayRef E);
+  fromConstraintExprs(Sema &S, const NamedDecl *D, ArrayRef E);
   static std::optional
-  fromConstraintExpr(Sema &S, NamedDecl *D, const Expr *E);
+  fromConstraintExpr(Sema &S, const NamedDecl *D, const Expr *E);
 };
 
 struct alignas(ConstraintAlignment) NormalizedConstraintPair {
@@ -137,7 +137,7 @@ struct alignas(ConstraintAlignment) FoldExpandedConstraint {
 };
 
 const NormalizedConstraint *getNormalizedAssociatedConstraints(
-Sema &S, NamedDecl *ConstrainedDecl,
+Sema &S, const NamedDecl *ConstrainedDecl,
 ArrayRef AssociatedConstraints);
 
 /// \brief SubsumptionChecker establishes subsumption
@@ -149,8 +149,8 @@ class SubsumptionChecker {
 
   SubsumptionChecker(Sema &SemaRef, SubsumptionCallable Callable = {});
 
-  std::optional Subsumes(NamedDecl *DP, ArrayRef P,
-   NamedDecl *DQ, ArrayRef Q);
+  std::optional Subsumes(const NamedDecl *DP, ArrayRef P,
+   const NamedDecl *DQ, ArrayRef Q);
 
   bool Subsumes(const NormalizedConstraint *P, const NormalizedConstraint *Q);
 
diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index e7e0b4cfb72a7..ebee5994bfed2 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -453,6 +453,7 @@ static ExprResult c

  1   2   >