[clang] [NFC][Clang][CodeGen] Remove vestigial assertion (PR #127528)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Alex Voicu (AlexVlx)


Changes

This removes a vestigial assertion, which would erroneously trigger even though 
we now correctly handle valid arg mismatches 
(;),
 after #114062 went in.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (-16) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e6c2ac939eb88..47bfd470dbafb 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -5633,22 +5633,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   if (!CallArgs.getCleanupsToDeactivate().empty())
 deactivateArgCleanupsBeforeCall(*this, CallArgs);
 
-  // Assert that the arguments we computed match up.  The IR verifier
-  // will catch this, but this is a common enough source of problems
-  // during IRGen changes that it's way better for debugging to catch
-  // it ourselves here.
-#ifndef NDEBUG
-  assert(IRCallArgs.size() == IRFuncTy->getNumParams() || 
IRFuncTy->isVarArg());
-  for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
-// Inalloca argument can have different type.
-if (IRFunctionArgs.hasInallocaArg() &&
-i == IRFunctionArgs.getInallocaArgNo())
-  continue;
-if (i < IRFuncTy->getNumParams())
-  assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
-  }
-#endif
-
   // Update the largest vector width if any arguments have vector types.
   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
 LargestVectorWidth = std::max(LargestVectorWidth,

``




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


[clang] [NFC][Clang][CodeGen] Remove vestigial assertion (PR #127528)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Alex Voicu (AlexVlx)


Changes

This removes a vestigial assertion, which would erroneously trigger even though 
we now correctly handle valid arg mismatches 
(;),
 after #114062 went in.

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


1 Files Affected:

- (modified) clang/lib/CodeGen/CGCall.cpp (-16) 


``diff
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e6c2ac939eb88..47bfd470dbafb 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -5633,22 +5633,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   if (!CallArgs.getCleanupsToDeactivate().empty())
 deactivateArgCleanupsBeforeCall(*this, CallArgs);
 
-  // Assert that the arguments we computed match up.  The IR verifier
-  // will catch this, but this is a common enough source of problems
-  // during IRGen changes that it's way better for debugging to catch
-  // it ourselves here.
-#ifndef NDEBUG
-  assert(IRCallArgs.size() == IRFuncTy->getNumParams() || 
IRFuncTy->isVarArg());
-  for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
-// Inalloca argument can have different type.
-if (IRFunctionArgs.hasInallocaArg() &&
-i == IRFunctionArgs.getInallocaArgNo())
-  continue;
-if (i < IRFuncTy->getNumParams())
-  assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
-  }
-#endif
-
   // Update the largest vector width if any arguments have vector types.
   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
 LargestVectorWidth = std::max(LargestVectorWidth,

``




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


[clang] [compiler-rt] [Clang][PGO] Fix profile function visibility bug (PR #127257)

2025-02-17 Thread Qiongsi Wu via cfe-commits

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

Thanks Ethan! LGTM! 

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


[clang] [clang][bytecode] Fix returne value of array CXXNewExprs (PR #127526)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Just like with the __builtin_operator_new version, we need to point to the 
first array element, not the array element itself.

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


3 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.cpp (+2-1) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+11-2) 
- (modified) clang/test/AST/ByteCode/new-delete.cpp (+14) 


``diff
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index c80be094856b0..0310870f7372e 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -1063,7 +1063,8 @@ bool Free(InterpState &S, CodePtr OpPC, bool 
DeleteIsArrayForm,
   return false;
 }
 
-if (!Ptr.isRoot() || Ptr.isOnePastEnd() || Ptr.isArrayElement()) {
+if (!Ptr.isRoot() || Ptr.isOnePastEnd() ||
+(Ptr.isArrayElement() && Ptr.getIndex() != 0)) {
   const SourceInfo &Loc = S.Current->getSource(OpPC);
   S.FFDiag(Loc, diag::note_constexpr_delete_subobject)
   << Ptr.toDiagnosticString(S.getASTContext()) << Ptr.isOnePastEnd();
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 73cc107b7dbff..10cf21e28437c 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -2915,13 +2915,17 @@ inline bool AllocN(InterpState &S, CodePtr OpPC, 
PrimType T, const Expr *Source,
 S.Stk.push(0, nullptr);
 return true;
   }
+  assert(NumElements.isPositive());
 
   DynamicAllocator &Allocator = S.getAllocator();
   Block *B =
   Allocator.allocate(Source, T, static_cast(NumElements),
  S.Ctx.getEvalID(), DynamicAllocator::Form::Array);
   assert(B);
-  S.Stk.push(B);
+  if (NumElements.isZero())
+S.Stk.push(B);
+  else
+S.Stk.push(Pointer(B).atIndex(0));
   return true;
 }
 
@@ -2941,13 +2945,18 @@ inline bool AllocCN(InterpState &S, CodePtr OpPC, const 
Descriptor *ElementDesc,
 S.Stk.push(0, ElementDesc);
 return true;
   }
+  assert(NumElements.isPositive());
 
   DynamicAllocator &Allocator = S.getAllocator();
   Block *B =
   Allocator.allocate(ElementDesc, static_cast(NumElements),
  S.Ctx.getEvalID(), DynamicAllocator::Form::Array);
   assert(B);
-  S.Stk.push(B);
+  if (NumElements.isZero())
+S.Stk.push(B);
+  else
+S.Stk.push(Pointer(B).atIndex(0));
+
   return true;
 }
 
diff --git a/clang/test/AST/ByteCode/new-delete.cpp 
b/clang/test/AST/ByteCode/new-delete.cpp
index e9850d27666e5..7e5f6ab8815ea 100644
--- a/clang/test/AST/ByteCode/new-delete.cpp
+++ b/clang/test/AST/ByteCode/new-delete.cpp
@@ -922,6 +922,20 @@ namespace NonConstexprArrayCtor {
  // both-note {{in call to}}
 }
 
+namespace ArrayBaseCast {
+  struct A {};
+  struct B : A {};
+  constexpr bool test() {
+B *b = new B[2];
+
+A* a = b;
+
+delete[] b;
+return true;
+  }
+  static_assert(test());
+}
+
 #else
 /// Make sure we reject this prior to C++20
 constexpr int a() { // both-error {{never produces a constant expression}}

``




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


[clang] [NFC][Clang][CodeGen] Remove vestigial assertion (PR #127528)

2025-02-17 Thread Joseph Huber via cfe-commits

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

Makes sense, since this is only for these call arguments which are handled in 
all cases now I presume.

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


[clang] [clang][CodeGen] `sret` args should always point to the `alloca` AS, so use that (PR #114062)

2025-02-17 Thread Alex Voicu via cfe-commits

AlexVlx wrote:

> @AlexVlx I found this breaks my clang build, reduced the C++ source to the 
> following reproducer https://godbolt.org/z/jGnvKeqvr. Please verify that it 
> breaks for you as well and revert or fix. (The issue is the s() function call 
> not using AS(5))
> 
> ```c++
> #pragma omp begin declare target
> struct S {
>   ~S() { };
> };
> S s();
> struct E {
>   S foo;
>   E();
> };
> E::E() : foo(s()) {}
> #pragma omp end declare target
> ```
> 
> ```
> > ./bin/clang++ omp-bug.cpp -fopenmp --offload-arch=gfx1030 -nogpulib
> clang-21: 
> /home/jhuber/Documents/llvm/llvm-project/clang/lib/CodeGen/CGCall.cpp:5648: 
> clang::CodeGen::RValue clang::CodeGen::CodeGenFunction::EmitCall(const 
> clang::CodeGen::CGFunctionInfo&, const clang::CodeGen::CGCallee&, 
> clang::CodeGen::ReturnValueSlot, const clang::CodeGen::CallArgList&, 
> llvm::CallBase**, bool, clang::SourceLocation, bool): Assertion 
> `IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)' failed.
> ```

Thank you for flagging this. Please see #127528.

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


[clang] [HLSL] Implement the 'and' HLSL function (PR #127098)

2025-02-17 Thread Farzon Lotfi via cfe-commits


@@ -2245,6 +2245,36 @@ bool SemaHLSL::CheckBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
 
 break;
   }
+  case Builtin::BI__builtin_hlsl_and: {
+if (SemaRef.checkArgCount(TheCall, 2))
+  return true;
+if (CheckVectorElementCallArgs(&SemaRef, TheCall))
+  return true;
+
+// CheckVectorElementCallArgs(...) guarantees both args are the same type.
+assert(TheCall->getArg(0)->getType() == TheCall->getArg(1)->getType() &&
+   "Both args must be of the same type");
+
+// check that the arguments are bools or, if vectors,
+// vectors of bools
+QualType ArgTy = TheCall->getArg(0)->getType();
+if (const auto *VecTy = ArgTy->getAs()) {
+  ArgTy = VecTy->getElementType();
+}
+if (!getASTContext().hasSameUnqualifiedType(ArgTy,

farzonl wrote:

Well  for one we only emit one diagnostic for `CheckScalarOrVector` even though 
there are multiple overloads, the example i give lets us specify   a diagnostic 
per overload like you mentioned in  the `cross` example for half or float which 
was one of the issue you raised earlier.

Second issue I  think we can do better  with how we are using 
`CheckScalarOrVector` for example see 
`BI__builtin_hlsl_elementwise_splitdouble` We could reduce the 3 function calls 
here to one if we take qual types as a list.

```cpp
if (CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.DoubleTy, 0) ||
CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.UnsignedIntTy,
1) ||
CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.UnsignedIntTy,
2))
```

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


[clang] [Clang][AArch64] Add support for SHF_AARCH64_PURECODE ELF section flag (2/3) (PR #125688)

2025-02-17 Thread Peter Smith via cfe-commits


@@ -0,0 +1,6 @@
+// RUN: %clang --sysroot=%S/Inputs -c -fdriver-only -Werror 
--target=aarch64-unknown-linux-gnu \

smithp35 wrote:

Can you check that this test still passes with a aarch64-none-elf bare-metal 
target?

There's a !ForMultilib in the ARM code 
https://github.com/llvm/llvm-project/blob/main/clang/lib/Driver/ToolChains/Arch/ARM.cpp#L887

Which I think would only take effect on the bare-metal driver. If it doesn't 
then would you be able to add a similar !ForMultilib to the AArch64 driver?

FWIW The git blame for b4eebc8674e1f1dc1ef08fa7648ca494a119449d says
```
[Driver] Enable multilib.yaml in the BareMetal ToolChain


The default location for multilib.yaml is 
lib/clang-runtimes, without
any target-specific suffix. This will allow multilibs for different
architectures to share a common include directory.

To avoid breaking the arm-execute-only.c CHECK-NO-EXECUTE-ONLY-ASM
test, add a ForMultilib argument to getARMTargetFeatures.

Since the presence of multilib.yaml can change the exact location of a  

library, relax the baremetal.cpp test.

Differential Revision: https://reviews.llvm.org/D142986
```

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


[clang] [llvm] [RISCV] Add Support of RISCV Zibimm Experimental Extension (PR #127463)

2025-02-17 Thread Craig Topper via cfe-commits


@@ -0,0 +1,48 @@
+//===-- RISCVInstrInfoZvabd.td - 'Zvabd' instructions --*- tablegen 
-*-===//

topperc wrote:

Incorrect file name

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


[libclc] [libclc] Suppress data-layout warnings during linking (PR #127532)

2025-02-17 Thread Fraser Cormack via cfe-commits

https://github.com/frasercrmck created 
https://github.com/llvm/llvm-project/pull/127532

libclc uses llvm-link to link together all of the individually built libclc 
builtins files into one module. Some of these builtins files are compiled from 
source by clang whilst others are converted from LLVM IR directly to bytecode.

When llvm-link links a 'source' module into a 'destination' module, it warns if 
the two modules have differing data layouts.

The LLVM IR files libclc links either have no data layout (shared submodule 
files) or an explicit data layout in the case of certain amdgcn/r600 files.

The warnings are very noisy and largely inconsequential. We can suppress them 
exploiting a specific behaviours exhibited by llvm-link. When the destination 
module has no data layout, it is given the source module's data layout. Thus, 
if we link together all IR files first, followed by the clang-compiled modules, 
99% of the warnings are suppressed as they arose from linking an empty data 
layout into a non-empty one.

The remaining warnings come from the amdgcn and r600 targets. Some of these 
were because the data layouts were out of date compared with what clang 
currently produced, so those were updated. However, even by grouping the IR 
files together, it may still link explicit ones with empty ones depending on 
the order the IR files are processed.

>From d9588e35df36015a91e0c71aa15c66ff2947251a Mon Sep 17 00:00:00 2001
From: Fraser Cormack 
Date: Mon, 17 Feb 2025 18:04:08 +
Subject: [PATCH] [libclc] Suppress data-layout warnings during linking

libclc uses llvm-link to link together all of the individually built
libclc builtins files into one module. Some of these builtins files are
compiled from source by clang whilst others are converted from LLVM IR
directly to bytecode.

When llvm-link links a 'source' module into a 'destination' module, it
warns if the two modules have differing data layouts.

The LLVM IR files libclc links either have no data layout (shared
submodule files) or an explicit data layout in the case of certain
amdgcn/r600 files.

The warnings are very noisy and largely inconsequential. We can suppress
them exploiting a specific behaviours exhibited by llvm-link. When the
destination module has no data layout, it is given the source module's
data layout. Thus, if we link together all IR files first, followed by
the clang-compiled modules, 99% of the warnings are suppressed as they
arose from linking an empty data layout into a non-empty one.

The remaining warnings come from the amdgcn and r600 targets. Some of
these were because the data layouts were out of date compared with what
clang currently produced, so those were updated. However, even by
grouping the IR files together, it may still link explicit ones with
empty ones depending on the order the IR files are processed.
---
 .../minmax_helpers.ll |  6 +-
 libclc/cmake/modules/AddLibclc.cmake  | 19 +--
 .../lib/image/get_image_attributes_impl.ll|  2 +-
 libclc/r600/lib/image/read_image_impl.ll  |  2 +-
 libclc/r600/lib/image/write_image_impl.ll |  2 +-
 5 files changed, 21 insertions(+), 10 deletions(-)

diff --git a/libclc/amdgcn/lib/cl_khr_int64_extended_atomics/minmax_helpers.ll 
b/libclc/amdgcn/lib/cl_khr_int64_extended_atomics/minmax_helpers.ll
index 98f1f54718a1f..5300f7718a591 100644
--- a/libclc/amdgcn/lib/cl_khr_int64_extended_atomics/minmax_helpers.ll
+++ b/libclc/amdgcn/lib/cl_khr_int64_extended_atomics/minmax_helpers.ll
@@ -1,8 +1,4 @@
-#if __clang_major__ >= 7
-target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5"
-#else
-target datalayout = 
"e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"
-#endif
+target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9"
 
 define i64 @__clc__sync_fetch_and_min_global_8(i64 addrspace(1)* nocapture 
%ptr, i64 %value) nounwind alwaysinline {
 entry:
diff --git a/libclc/cmake/modules/AddLibclc.cmake 
b/libclc/cmake/modules/AddLibclc.cmake
index 5347b0822477b..b90d15d3185d0 100644
--- a/libclc/cmake/modules/AddLibclc.cmake
+++ b/libclc/cmake/modules/AddLibclc.cmake
@@ -225,7 +225,8 @@ function(add_libclc_builtin_set)
 message( FATAL_ERROR "Must provide ARCH, ARCH_SUFFIX, and TRIPLE" )
   endif()
 
-  set( bytecode_files "" )
+  set( bytecode_files )
+  set( bytecode_ir_files )
   foreach( file IN LISTS ARG_GEN_FILES ARG_LIB_FILES )
 # We need to take each file and produce an absolute input file, as well
 # as a unique architecture-specific output file. We deal with a mix of

[libclc] [libclc] Suppress data-layout warnings during linking (PR #127532)

2025-02-17 Thread Fraser Cormack via cfe-commits


@@ -1,8 +1,4 @@
-#if __clang_major__ >= 7
-target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5"
-#else
-target datalayout = 
"e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64"
-#endif
+target datalayout = 
"e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-p7:160:256:256:32-p8:128:128-p9:192:256:256:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7:8:9"

frasercrmck wrote:

Could we just remove these explicit data layouts, and rely on `llvm-link` 
giving us the correct one from a source-compiled object, @arsenm?

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


[clang] [llvm] [OpenMP] Missing implicit otherwise clause in metadirective. (PR #127113)

2025-02-17 Thread Alexey Bataev via cfe-commits


@@ -2882,6 +2882,12 @@ StmtResult 
Parser::ParseOpenMPDeclarativeOrExecutableDirective(
   /*ReadDirectiveWithinMetadirective=*/true);
   break;
 }
+// If no match is found and no otherwise clause is present, skip
+// OMP5.2 Chapter 7.4: If no otherwise clause is specified the effect is as
+// if one was specified without an associated directive variant.
+if (BestIdx == -1 && Idx == 1) {
+  SkipUntil(tok::annot_pragma_openmp_end,tok::identifier);

alexey-bataev wrote:

You still losing some data, SkipUntil does not work here

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


[clang] [Clang][CodeGen] Bail out on constexpr unknown values in ConstantEmitter (PR #127525)

2025-02-17 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw created 
https://github.com/llvm/llvm-project/pull/127525

Close https://github.com/llvm/llvm-project/issues/127475

>From d931667e3b7e18f8ba6f054405ffc5fe2fac36b4 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Tue, 18 Feb 2025 01:26:26 +0800
Subject: [PATCH] [Clang][CodeGen] Bail out on constexpr unknown values in
 ConstantEmitter

---
 clang/lib/CodeGen/CGExprConstant.cpp|  6 --
 clang/test/CodeGenCXX/cxx23-p2280r4.cpp | 13 +
 2 files changed, 17 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/cxx23-p2280r4.cpp

diff --git a/clang/lib/CodeGen/CGExprConstant.cpp 
b/clang/lib/CodeGen/CGExprConstant.cpp
index ee5874b26f534..075f3f435ad74 100644
--- a/clang/lib/CodeGen/CGExprConstant.cpp
+++ b/clang/lib/CodeGen/CGExprConstant.cpp
@@ -1883,8 +1883,10 @@ llvm::Constant 
*ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) {
 
   // Try to emit the initializer.  Note that this can allow some things that
   // are not allowed by tryEmitPrivateForMemory alone.
-  if (APValue *value = D.evaluateValue())
-return tryEmitPrivateForMemory(*value, destType);
+  if (APValue *value = D.evaluateValue()) {
+if (!value->allowConstexprUnknown())
+  return tryEmitPrivateForMemory(*value, destType);
+  }
 
   return nullptr;
 }
diff --git a/clang/test/CodeGenCXX/cxx23-p2280r4.cpp 
b/clang/test/CodeGenCXX/cxx23-p2280r4.cpp
new file mode 100644
index 0..bb9a90ba18ece
--- /dev/null
+++ b/clang/test/CodeGenCXX/cxx23-p2280r4.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++23 %s -emit-llvm -o - | 
FileCheck %s
+
+extern int& s;
+
+// CHECK: @_Z4testv()
+// CHECK-NEXT: entry:
+// CHECK-NEXT: [[I:%.*]] = alloca ptr, align {{.*}}
+// CHECK-NEXT: [[X:%.*]] = load ptr, ptr @s, align {{.*}}
+// CHECK-NEXT: store ptr [[X]], ptr [[I]], align {{.*}}
+int& test() {
+  auto &i = s;
+  return i;
+}

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


[clang] [libc] [Clang] Add handlers for 'match_any' and 'match_all' to `gpuintrin.h` (PR #127504)

2025-02-17 Thread Joseph Huber via cfe-commits


@@ -162,6 +162,62 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__lane_mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t

jhuber6 wrote:

Honestly I got confused myself whether or not the return value was a number or 
a mask. I think that having a `typedef uint64_t __lanemask_t` would be helpful 
for keeping that unambiguous, but  I think that it's best just to keep it 
`uint64_t` for all targets to simplify code and keep it portable. I might do 
that in a follow-up patch.

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


[libclc] [libclc] Fix dependencies on generated convert builtins (PR #127515)

2025-02-17 Thread Fraser Cormack via cfe-commits

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


[clang] [clang] Implement __attribute__((format_matches)) (PR #116708)

2025-02-17 Thread via cfe-commits
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier ,
=?utf-8?q?Félix?= Cloutier 
Message-ID:
In-Reply-To: 


apple-fcloutier wrote:

@erichkeane, congrats on the C++26 milestone. I made changes to address your 
comment. Appreciate your time reviewing this PR.

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


[clang] [clang][bytecode] Fix returne value of array CXXNewExprs (PR #127526)

2025-02-17 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr created 
https://github.com/llvm/llvm-project/pull/127526

Just like with the __builtin_operator_new version, we need to point to the 
first array element, not the array element itself.

>From ba084758083d32d2db4773abd181880717830706 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Mon, 17 Feb 2025 18:33:51 +0100
Subject: [PATCH] [clang][bytecode] Fix returne value of array CXXNewExprs

Just like with the __builtin_operator_new version, we need to point
to the first array element, not the array element itself.
---
 clang/lib/AST/ByteCode/Interp.cpp  |  3 ++-
 clang/lib/AST/ByteCode/Interp.h| 13 +++--
 clang/test/AST/ByteCode/new-delete.cpp | 14 ++
 3 files changed, 27 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index c80be094856b0..0310870f7372e 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -1063,7 +1063,8 @@ bool Free(InterpState &S, CodePtr OpPC, bool 
DeleteIsArrayForm,
   return false;
 }
 
-if (!Ptr.isRoot() || Ptr.isOnePastEnd() || Ptr.isArrayElement()) {
+if (!Ptr.isRoot() || Ptr.isOnePastEnd() ||
+(Ptr.isArrayElement() && Ptr.getIndex() != 0)) {
   const SourceInfo &Loc = S.Current->getSource(OpPC);
   S.FFDiag(Loc, diag::note_constexpr_delete_subobject)
   << Ptr.toDiagnosticString(S.getASTContext()) << Ptr.isOnePastEnd();
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 73cc107b7dbff..10cf21e28437c 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -2915,13 +2915,17 @@ inline bool AllocN(InterpState &S, CodePtr OpPC, 
PrimType T, const Expr *Source,
 S.Stk.push(0, nullptr);
 return true;
   }
+  assert(NumElements.isPositive());
 
   DynamicAllocator &Allocator = S.getAllocator();
   Block *B =
   Allocator.allocate(Source, T, static_cast(NumElements),
  S.Ctx.getEvalID(), DynamicAllocator::Form::Array);
   assert(B);
-  S.Stk.push(B);
+  if (NumElements.isZero())
+S.Stk.push(B);
+  else
+S.Stk.push(Pointer(B).atIndex(0));
   return true;
 }
 
@@ -2941,13 +2945,18 @@ inline bool AllocCN(InterpState &S, CodePtr OpPC, const 
Descriptor *ElementDesc,
 S.Stk.push(0, ElementDesc);
 return true;
   }
+  assert(NumElements.isPositive());
 
   DynamicAllocator &Allocator = S.getAllocator();
   Block *B =
   Allocator.allocate(ElementDesc, static_cast(NumElements),
  S.Ctx.getEvalID(), DynamicAllocator::Form::Array);
   assert(B);
-  S.Stk.push(B);
+  if (NumElements.isZero())
+S.Stk.push(B);
+  else
+S.Stk.push(Pointer(B).atIndex(0));
+
   return true;
 }
 
diff --git a/clang/test/AST/ByteCode/new-delete.cpp 
b/clang/test/AST/ByteCode/new-delete.cpp
index e9850d27666e5..7e5f6ab8815ea 100644
--- a/clang/test/AST/ByteCode/new-delete.cpp
+++ b/clang/test/AST/ByteCode/new-delete.cpp
@@ -922,6 +922,20 @@ namespace NonConstexprArrayCtor {
  // both-note {{in call to}}
 }
 
+namespace ArrayBaseCast {
+  struct A {};
+  struct B : A {};
+  constexpr bool test() {
+B *b = new B[2];
+
+A* a = b;
+
+delete[] b;
+return true;
+  }
+  static_assert(test());
+}
+
 #else
 /// Make sure we reject this prior to C++20
 constexpr int a() { // both-error {{never produces a constant expression}}

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


[libclc] 15c2d1b - [libclc] Fix dependencies on generated convert builtins (#127515)

2025-02-17 Thread via cfe-commits

Author: Fraser Cormack
Date: 2025-02-17T17:36:02Z
New Revision: 15c2d1b328433d2c26327e072059c8960469d378

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

LOG: [libclc] Fix dependencies on generated convert builtins (#127515)

In #127378 it was reported that builds without clspv targets enabled
were failing after #124727, as all targets had a dependency on a file
that only clspv targets generated.

A quick fix was merged in #127315 which wasn't correct. It moved the
dependency on those generated files to the spirv targets, instead of
onto the clspv targets. This means a build with spirv targets and
without clspv targets would see the same problems as #127378 reported.

I tried simply removing the requirement to explicitly add dependencies
to the custom command, relying instead on the file-level dependencies.
This didn't seem reliable enough; in some cases on a Makefiles build,
the clang command compiling (e.g.,) convert.cl would begin before the
file was fully written.

Instead, we keep the target-level dependency but automatically infer it
based on the generated file name, to avoid manual book-keeping of pairs
of files and targets.

This commit also fixes what looks like an unintended bug where, when
ENABLE_RUNTIME_SUBNORMAL was enabled, the OpenCL conversions weren't
being compiled.

Added: 


Modified: 
libclc/CMakeLists.txt
libclc/cmake/modules/AddLibclc.cmake

Removed: 




diff  --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index c88ea9700d100..5cefa8a264310 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -243,30 +243,30 @@ add_custom_command(
   OUTPUT convert.cl
   COMMAND ${Python3_EXECUTABLE} ${script_loc} > convert.cl
   DEPENDS ${script_loc} )
-add_custom_target( "generate_convert.cl" DEPENDS convert.cl )
-set_target_properties( "generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+add_custom_target( generate-convert.cl DEPENDS convert.cl )
+set_target_properties( generate-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
 add_custom_command(
   OUTPUT clc-convert.cl
   COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc > clc-convert.cl
   DEPENDS ${script_loc} )
-add_custom_target( "clc-generate_convert.cl" DEPENDS clc-convert.cl )
-set_target_properties( "clc-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+add_custom_target( generate-clc-convert.cl DEPENDS clc-convert.cl )
+set_target_properties( generate-clc-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
 if ( clspv-- IN_LIST LIBCLC_TARGETS_TO_BUILD OR clspv64-- IN_LIST 
LIBCLC_TARGETS_TO_BUILD )
   add_custom_command(
 OUTPUT clspv-convert.cl
 COMMAND ${Python3_EXECUTABLE} ${script_loc} --clspv > clspv-convert.cl
 DEPENDS ${script_loc} )
-  add_custom_target( "clspv-generate_convert.cl" DEPENDS clspv-convert.cl )
-  set_target_properties( "clspv-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+  add_custom_target( generate-clspv-convert.cl DEPENDS clspv-convert.cl )
+  set_target_properties( generate-clspv-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
   add_custom_command(
 OUTPUT clc-clspv-convert.cl
 COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc --clspv > 
clc-clspv-convert.cl
 DEPENDS ${script_loc} )
-  add_custom_target( "clc-clspv-generate_convert.cl" DEPENDS 
clc-clspv-convert.cl )
-  set_target_properties( "clc-clspv-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+  add_custom_target( generate-clc-clspv-convert.cl DEPENDS 
clc-clspv-convert.cl )
+  set_target_properties( generate-clc-clspv-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 endif()
 
 enable_testing()
@@ -324,9 +324,11 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} )
   if( NOT ARCH STREQUAL spirv AND NOT ARCH STREQUAL spirv64 )
 if( ARCH STREQUAL clspv OR ARCH STREQUAL clspv64 )
   list( APPEND opencl_gen_files clspv-convert.cl )
-elseif ( NOT ENABLE_RUNTIME_SUBNORMAL )
+else()
   list( APPEND opencl_gen_files convert.cl )
-  list( APPEND opencl_lib_files generic/lib/subnormal_use_default.ll )
+  if ( NOT ENABLE_RUNTIME_SUBNORMAL )
+list( APPEND opencl_lib_files generic/lib/subnormal_use_default.ll )
+  endif()
 endif()
   endif()
 

diff  --git a/libclc/cmake/modules/AddLibclc.cmake 
b/libclc/cmake/modules/AddLibclc.cmake
index a3b311f12a1e3..5347b0822477b 100644
--- a/libclc/cmake/modules/AddLibclc.cmake
+++ b/libclc/cmake/modules/AddLibclc.cmake
@@ -230,11 +230,17 @@ function(add_libclc_builtin_set)
 # We need to take each file and produce an absolute input file, as well
 # as a unique architecture-specific output file. We deal with a mix of
 # 
diff erent input files, which makes this trickier.
+set( input_file_dep )
 if( $

[clang] [clang][Sema] Fix type of an statement expression ending with an atomic type (PR #119711)

2025-02-17 Thread John McCall via cfe-commits
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=,
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=,
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=,
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=,
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=,
Alejandro =?utf-8?q?=C3=81lvarez_Ayll=C3=B3n?=
Message-ID:
In-Reply-To: 


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

Thanks, LGTM.

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,146 @@
+//===--- SmartptrResetAmbiguousCallCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SmartptrResetAmbiguousCallCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER_P(CallExpr, everyArgumentMatches,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  for (const auto *Arg : Node.arguments()) {
+if (!InnerMatcher.matches(*Arg, Finder, Builder))
+  return false;
+  }
+
+  return true;
+}
+
+AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
+  for (const auto *Param : Node.parameters()) {
+if (!Param->hasDefaultArg())
+  return false;
+  }
+
+  return true;
+}
+
+const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr";
+} // namespace
+
+SmartptrResetAmbiguousCallCheck::SmartptrResetAmbiguousCallCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SmartPointers(utils::options::parseStringList(
+  Options.get("SmartPointers", DefaultSmartPointers))) {}
+
+void SmartptrResetAmbiguousCallCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "SmartPointers",
+utils::options::serializeStringList(SmartPointers));
+}
+
+void SmartptrResetAmbiguousCallCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IsSmartptr = hasAnyName(SmartPointers);
+
+  const auto ResetMethod =
+  cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());
+
+  const auto TypeWithReset =
+  anyOf(cxxRecordDecl(hasMethod(ResetMethod)),
+classTemplateSpecializationDecl(
+hasSpecializedTemplate(classTemplateDecl(has(ResetMethod);
+
+  const auto SmartptrWithBugproneReset = classTemplateSpecializationDecl(
+  IsSmartptr,
+  hasTemplateArgument(
+  0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(TypeWithReset)));
+
+  // Find a.reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(callee(memberExpr(member(hasName("reset",
+everyArgumentMatches(cxxDefaultArgExpr()),
+on(expr(hasType(SmartptrWithBugproneReset
+  .bind("smartptrResetCall"),
+  this);
+
+  // Find a->reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(
+  callee(memberExpr(
+  member(ResetMethod),
+  hasObjectExpression(
+  cxxOperatorCallExpr(
+  hasOverloadedOperatorName("->"),
+  hasArgument(
+  0, expr(hasType(
+ 
classTemplateSpecializationDecl(IsSmartptr)
+  .bind("OpCall",
+  everyArgumentMatches(cxxDefaultArgExpr()))
+  .bind("objectResetCall"),
+  this);
+}
+
+void SmartptrResetAmbiguousCallCheck::check(
+const MatchFinder::MatchResult &Result) {
+
+  if (const auto *SmartptrResetCall =
+  Result.Nodes.getNodeAs("smartptrResetCall")) {
+const auto *Member = cast(SmartptrResetCall->getCallee());
+
+diag(SmartptrResetCall->getBeginLoc(),
+ "be explicit when calling 'reset()' on a smart pointer with a "
+ "pointee that has a 'reset()' method");

vbvictor wrote:

Done

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


[clang] [HLSL] Implement the 'and' HLSL function (PR #127098)

2025-02-17 Thread Chris B via cfe-commits


@@ -2245,6 +2245,36 @@ bool SemaHLSL::CheckBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
 
 break;
   }
+  case Builtin::BI__builtin_hlsl_and: {
+if (SemaRef.checkArgCount(TheCall, 2))
+  return true;
+if (CheckVectorElementCallArgs(&SemaRef, TheCall))
+  return true;
+
+// CheckVectorElementCallArgs(...) guarantees both args are the same type.
+assert(TheCall->getArg(0)->getType() == TheCall->getArg(1)->getType() &&
+   "Both args must be of the same type");
+
+// check that the arguments are bools or, if vectors,
+// vectors of bools
+QualType ArgTy = TheCall->getArg(0)->getType();
+if (const auto *VecTy = ArgTy->getAs()) {
+  ArgTy = VecTy->getElementType();
+}
+if (!getASTContext().hasSameUnqualifiedType(ArgTy,

llvm-beanz wrote:

Why is "doing what `select` does" an ad-hoc fix?

My suggestion to @Icohedron 
[here](https://github.com/llvm/llvm-project/pull/127098#discussion_r1957372179),
 is literally to just do what we do to validate the first argument to 
`__builtin_hlsl_select`, which has the exact same requirement, and produces a 
meaningful and accurate diagnostic.

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,146 @@
+//===--- SmartptrResetAmbiguousCallCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SmartptrResetAmbiguousCallCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER_P(CallExpr, everyArgumentMatches,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  for (const auto *Arg : Node.arguments()) {
+if (!InnerMatcher.matches(*Arg, Finder, Builder))
+  return false;
+  }
+
+  return true;
+}
+
+AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
+  for (const auto *Param : Node.parameters()) {
+if (!Param->hasDefaultArg())
+  return false;
+  }
+
+  return true;
+}
+
+const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr";
+} // namespace
+
+SmartptrResetAmbiguousCallCheck::SmartptrResetAmbiguousCallCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SmartPointers(utils::options::parseStringList(
+  Options.get("SmartPointers", DefaultSmartPointers))) {}
+
+void SmartptrResetAmbiguousCallCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "SmartPointers",
+utils::options::serializeStringList(SmartPointers));
+}
+
+void SmartptrResetAmbiguousCallCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IsSmartptr = hasAnyName(SmartPointers);
+
+  const auto ResetMethod =
+  cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());
+
+  const auto TypeWithReset =
+  anyOf(cxxRecordDecl(hasMethod(ResetMethod)),
+classTemplateSpecializationDecl(
+hasSpecializedTemplate(classTemplateDecl(has(ResetMethod);
+
+  const auto SmartptrWithBugproneReset = classTemplateSpecializationDecl(
+  IsSmartptr,
+  hasTemplateArgument(
+  0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(TypeWithReset)));
+
+  // Find a.reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(callee(memberExpr(member(hasName("reset",
+everyArgumentMatches(cxxDefaultArgExpr()),
+on(expr(hasType(SmartptrWithBugproneReset
+  .bind("smartptrResetCall"),
+  this);
+
+  // Find a->reset() calls
+  Finder->addMatcher(

vbvictor wrote:

I Could not find a good way to use "anyOf" in this context.
If I write like this, it gives CE.
```cpp
Finder->addMatcher(anyOf(...));
```
If I write:
```cpp
Finder->addMatcher(
cxxMemberCallExpr(
   anyOf(...))
.bind("MemberCall"));
```
I get only one bind-name for `cxxMemberCallExpr` which complicates futher 
processing.
If there aren't any performance issues, I'd like to leave as is.

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


[clang] [analyzer] Add hack in ArrayBound to cover up missing casts (PR #127117)

2025-02-17 Thread Donát Nagy via cfe-commits

NagyDonat wrote:

> That being said, I wonder if we should record the presence of casts when we 
> produce `ElementRegion`s to better help checks suppress potentially false 
> results. This would just make some workarounds easier to write rather than 
> having full modelling.

After stabilizing the other bounds checking checkers (PointerArithm, 
ReturnPtrRange etc.), I'll start another "big project" (probably later this 
year), and for that my primary idea is that I'll try to improve the handling of 
symbols -- which would include proper cast modeling as one of the main goals. I 
hope that this could be one of the rare situations where I can apply my 
theoretical mathematics skills for something practical by designing a more 
accurate representation/architecture without sacrificing the performance.

I wrote this particular workaround because it was a low-hanging fruit (as I'm 
already familiar with the ArrayBound code), but I wouldn't want to spend time 
on systematically burdening more checkers with similar hacks. 

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


[clang-tools-extra] [clang-tidy] Add support for `-ignore-insert-conflict` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Vicente Mataix Ferrándiz via cfe-commits


@@ -446,6 +448,12 @@ async def main() -> None:
 action="store_true",
 help="Allow empty enabled checks.",
 )
+parser.add_argument(
+"-ignore-insert-conflict",

loumalouomega wrote:

The problem is that `-ignore-insert-conflict` does not eist to older versions 
of clang to 15.0, for example I am using 14.0

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


[clang] [clang] Fix false positive regression for lifetime analysis warning. (PR #127460)

2025-02-17 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/127460

>From 3601ae837475da3c473f5be9c17687c439495ded Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 17 Feb 2025 10:08:14 +0100
Subject: [PATCH 1/2] [clang] Fix false positive regression for lifetime
 analysis warning.

---
 clang/lib/Sema/CheckExprLifetime.cpp  |  5 ++--
 clang/test/Sema/Inputs/lifetime-analysis.h|  2 ++
 .../Sema/warn-lifetime-analysis-nocfg.cpp | 24 +++
 3 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8963cad86dbca..3e0867343ccee 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1239,11 +1239,12 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
 }
 // Check the return type, e.g.
 //   const GSLOwner& func(const Foo& foo [[clang::lifetimebound]])
+//   GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]])
 //   GSLPointer func(const Foo& foo [[clang::lifetimebound]])
 if (FD &&
-((FD->getReturnType()->isReferenceType() &&
+((FD->getReturnType()->isPointerOrReferenceType() &&
   isRecordWithAttr(FD->getReturnType()->getPointeeType())) 
||
- isPointerLikeType(FD->getReturnType(
+  isGLSPointerType(FD->getReturnType(
   return Report;
 
 return Abandon;
diff --git a/clang/test/Sema/Inputs/lifetime-analysis.h 
b/clang/test/Sema/Inputs/lifetime-analysis.h
index d318033ff0cc4..2072e4603cead 100644
--- a/clang/test/Sema/Inputs/lifetime-analysis.h
+++ b/clang/test/Sema/Inputs/lifetime-analysis.h
@@ -61,6 +61,7 @@ struct basic_string_view {
   basic_string_view();
   basic_string_view(const T *);
   const T *begin() const;
+  const T *data() const;
 };
 using string_view = basic_string_view;
 
@@ -80,6 +81,7 @@ struct basic_string {
   const T *c_str() const;
   operator basic_string_view () const;
   using const_iterator = iter;
+  const T *data() const;
 };
 using string = basic_string;
 
diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 04bb1330ded4c..a65bb936ca8cb 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -852,3 +852,27 @@ struct Test {
 };
 
 } // namespace GH120543
+
+namespace GH127195 {
+template 
+struct StatusOr {
+  T* operator->() [[clang::lifetimebound]];
+  T* value() [[clang::lifetimebound]];
+};
+
+const char* foo() {
+  StatusOr s;
+  return s->data(); // expected-warning {{address of stack memory associated 
with local variable}}
+  
+  StatusOr s2;
+  return s2->data();
+
+  StatusOr> s3;
+  return s3.value()->value()->data();
+
+  // would be nice to support the nested cases.
+  StatusOr> s4;
+  return s4.value()->value()->data();
+}
+
+} // namespace GH127195

>From 29e49e18339c7c2f2e9694c37a859967922c89e8 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 17 Feb 2025 14:23:39 +0100
Subject: [PATCH 2/2] add FIXME

---
 clang/test/Sema/warn-lifetime-analysis-nocfg.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index a65bb936ca8cb..66a2a19ceb321 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -870,7 +870,7 @@ const char* foo() {
   StatusOr> s3;
   return s3.value()->value()->data();
 
-  // would be nice to support the nested cases.
+  // FIXME: nested cases are not supported now.
   StatusOr> s4;
   return s4.value()->value()->data();
 }

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


[clang] [clang] Fix false positive regression for lifetime analysis warning. (PR #127460)

2025-02-17 Thread Haojian Wu via cfe-commits


@@ -852,3 +852,27 @@ struct Test {
 };
 
 } // namespace GH120543
+
+namespace GH127195 {
+template 
+struct StatusOr {
+  T* operator->() [[clang::lifetimebound]];
+  T* value() [[clang::lifetimebound]];
+};
+
+const char* foo() {
+  StatusOr s;
+  return s->data(); // expected-warning {{address of stack memory associated 
with local variable}}
+  
+  StatusOr s2;
+  return s2->data();
+
+  StatusOr> s3;
+  return s3.value()->value()->data();
+
+  // would be nice to support the nested cases.
+  StatusOr> s4;

hokein wrote:

Done.

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


[clang] Clang/bug113094 (PR #127439)

2025-02-17 Thread Joseph Huber via cfe-commits


@@ -8336,12 +8336,11 @@ static bool verifyValidIntegerConstantExpr(Sema &S, 
const ParsedAttr &Attr,
 /// match one of the standard Neon vector types.
 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  Sema &S, VectorKind VecKind) {
-  bool IsTargetCUDAAndHostARM = false;
-  if (S.getLangOpts().CUDAIsDevice) {
-const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
-IsTargetCUDAAndHostARM =
-AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM());
-  }
+  const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
+  bool IsArm = AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM());
+
+  bool IsTargetCUDAAndHostARM = IsArm && S.getLangOpts().CUDAIsDevice;

jhuber6 wrote:

I agree, unfortunately a lot of this handling is spread out all over the place. 
There's https://github.com/llvm/llvm-project/pull/126956 up which also tries to 
clean some of this up. However, right now I'd say that would be a larger 
cleanup out of scope for this bug fix.

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


[clang] Clang/bug113094 (PR #127439)

2025-02-17 Thread Joseph Huber via cfe-commits


@@ -0,0 +1,6 @@
+// RUN: %clang -fopenmp --offload-arch=sm_90 -nocudalib -target 
aarch64-unknown-linux-gnu -c -Xclang -verify %s

jhuber6 wrote:

Seems CUDA used to have a test for this but it was removed for some reason? I 
would just stash it in `SemaOpenMP` or `OpenMP` and copy one of the existing 
`-verify` tests.

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


[libunwind] Silence -Wunused-parameter warnings in Unwind-wasm.c (PR #125412)

2025-02-17 Thread Louis Dionne via cfe-commits

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


[libunwind] f4206f9 - [libunwind] Silence -Wunused-parameter warnings in Unwind-wasm.c (#125412)

2025-02-17 Thread via cfe-commits

Author: Yuriy Chernyshov
Date: 2025-02-17T08:39:18-05:00
New Revision: f4206f92c5f900a4e0fc0f6dcab6afb6865df1e9

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

LOG: [libunwind] Silence -Wunused-parameter warnings in Unwind-wasm.c (#125412)

Added: 


Modified: 
libunwind/src/Unwind-wasm.c

Removed: 




diff  --git a/libunwind/src/Unwind-wasm.c b/libunwind/src/Unwind-wasm.c
index b18b32c5d1784..b8b7bc2779f17 100644
--- a/libunwind/src/Unwind-wasm.c
+++ b/libunwind/src/Unwind-wasm.c
@@ -102,8 +102,7 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIP(struct 
_Unwind_Context *context) {
 }
 
 /// Not used in Wasm.
-_LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *context,
- uintptr_t value) {}
+_LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *, uintptr_t) {}
 
 /// Called by personality handler to get LSDA for current frame.
 _LIBUNWIND_EXPORT uintptr_t
@@ -115,8 +114,7 @@ _Unwind_GetLanguageSpecificData(struct _Unwind_Context 
*context) {
 }
 
 /// Not used in Wasm.
-_LIBUNWIND_EXPORT uintptr_t
-_Unwind_GetRegionStart(struct _Unwind_Context *context) {
+_LIBUNWIND_EXPORT uintptr_t _Unwind_GetRegionStart(struct _Unwind_Context *) {
   return 0;
 }
 



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


[clang] [OpenMP] Silencly accept `neon_vector_type` for the offloading device (PR #127439)

2025-02-17 Thread via cfe-commits

github-actions[bot] wrote:

⚠️ We detected that you are using a GitHub private e-mail address to contribute 
to the repo. Please turn off [Keep my email addresses 
private](https://github.com/settings/emails) setting in your account. See 
[LLVM 
Discourse](https://discourse.llvm.org/t/hidden-emails-on-github-should-we-do-something-about-it)
 for more information.

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


[clang] 9c49b18 - [clang] Fix false positive regression for lifetime analysis warning. (#127460)

2025-02-17 Thread via cfe-commits

Author: Haojian Wu
Date: 2025-02-17T14:40:31+01:00
New Revision: 9c49b188b8e1434eb774ee8422124ad3e8870dce

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

LOG: [clang] Fix false positive regression for lifetime analysis warning. 
(#127460)

This fixes a false positive caused by #114044.

For `GSLPointer*` types, it's less clear whether the lifetime issue is
about the GSLPointer object itself or the owner it points to. To avoid
false positives, we take a conservative approach in our heuristic.

Fixes #127195

(This will be backported to release 20).

Added: 


Modified: 
clang/lib/Sema/CheckExprLifetime.cpp
clang/test/Sema/Inputs/lifetime-analysis.h
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8963cad86dbca..1f87001f35b57 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1239,11 +1239,12 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
 }
 // Check the return type, e.g.
 //   const GSLOwner& func(const Foo& foo [[clang::lifetimebound]])
+//   GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]])
 //   GSLPointer func(const Foo& foo [[clang::lifetimebound]])
 if (FD &&
-((FD->getReturnType()->isReferenceType() &&
+((FD->getReturnType()->isPointerOrReferenceType() &&
   isRecordWithAttr(FD->getReturnType()->getPointeeType())) 
||
- isPointerLikeType(FD->getReturnType(
+ isGLSPointerType(FD->getReturnType(
   return Report;
 
 return Abandon;

diff  --git a/clang/test/Sema/Inputs/lifetime-analysis.h 
b/clang/test/Sema/Inputs/lifetime-analysis.h
index d318033ff0cc4..2072e4603cead 100644
--- a/clang/test/Sema/Inputs/lifetime-analysis.h
+++ b/clang/test/Sema/Inputs/lifetime-analysis.h
@@ -61,6 +61,7 @@ struct basic_string_view {
   basic_string_view();
   basic_string_view(const T *);
   const T *begin() const;
+  const T *data() const;
 };
 using string_view = basic_string_view;
 
@@ -80,6 +81,7 @@ struct basic_string {
   const T *c_str() const;
   operator basic_string_view () const;
   using const_iterator = iter;
+  const T *data() const;
 };
 using string = basic_string;
 

diff  --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 04bb1330ded4c..66a2a19ceb321 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -852,3 +852,27 @@ struct Test {
 };
 
 } // namespace GH120543
+
+namespace GH127195 {
+template 
+struct StatusOr {
+  T* operator->() [[clang::lifetimebound]];
+  T* value() [[clang::lifetimebound]];
+};
+
+const char* foo() {
+  StatusOr s;
+  return s->data(); // expected-warning {{address of stack memory associated 
with local variable}}
+  
+  StatusOr s2;
+  return s2->data();
+
+  StatusOr> s3;
+  return s3.value()->value()->data();
+
+  // FIXME: nested cases are not supported now.
+  StatusOr> s4;
+  return s4.value()->value()->data();
+}
+
+} // namespace GH127195



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


[clang] [clang] Fix false positive regression for lifetime analysis warning. (PR #127460)

2025-02-17 Thread Haojian Wu via cfe-commits

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


[clang] [lld] [llvm] Integrated Distributed ThinLTO (DTLTO): Initial support (PR #126654)

2025-02-17 Thread via cfe-commits

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


[clang] [analyzer] Add hack in ArrayBound to cover up missing casts (PR #127117)

2025-02-17 Thread Endre Fülöp via cfe-commits

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

LGTM. An interesting thing could be to track in the analyzer the number of 
suppressed underflows (i.e.: the number of times we resorted to hacking with 
this solution). That way, we could have more information about how far we 
deviate from the precise modelling. This could provide a useful metric in the 
future and may not belong strictly to this patch.

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits

vbvictor wrote:

@PiotrZSL, thank you for pointing out better naming pattern for diag-messages, 
would use it in the future.

1. Created new warning and fix-it messages.
2. Renamed check.
3. As for now, my check can support any type that will have `reset` method, 
this include `std::optional`. Maybe a more general approach would be to detect 
overlapping methods with classes that are returned via `operator*` and 
`operator->`. However, if some method is called on main object and there is no 
equivalent of `= nullptr` I don't know how user can fix such warning.

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


[clang] [SystemZ][z/OS] Mark text files as text in ClangScanDeps (PR #127514)

2025-02-17 Thread Abhina Sree via cfe-commits

https://github.com/abhina-sree updated 
https://github.com/llvm/llvm-project/pull/127514

>From a015e8389fa263cbbb28e56e93fae733f5e94dde Mon Sep 17 00:00:00 2001
From: Abhina Sreeskantharajan 
Date: Mon, 17 Feb 2025 10:56:10 -0500
Subject: [PATCH 1/2] mark text files as text in ClangScanDeps

---
 clang/tools/clang-scan-deps/ClangScanDeps.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 9cdb1eae56187..0849782a7354b 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,12 +298,12 @@ class ResourceDirectoryCache {
 };
 if (llvm::sys::ExecuteAndWait(ClangBinaryPath, PrintResourceDirArgs, {},
   Redirects)) {
-  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str());
+  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str(), 
/*IsText=*/true);
   llvm::errs() << ErrorBuf.get()->getBuffer();
   return "";
 }
 
-auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str());
+auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str(), 
/*IsText=*/true);
 if (!OutputBuf)
   return "";
 StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
@@ -1032,7 +1032,7 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
 std::unique_ptr TU;
 std::optional TUBuffer;
 if (!TranslationUnitFile.empty()) {
-  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile);
+  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
   if (!MaybeTU) {
 llvm::errs() << "cannot open input translation unit: "
  << MaybeTU.getError().message() << "\n";

>From 9b49cac4470fa0c13627077d3c1efcc6cee43ac5 Mon Sep 17 00:00:00 2001
From: Abhina Sreeskantharajan 
Date: Mon, 17 Feb 2025 11:02:05 -0500
Subject: [PATCH 2/2] formatting

---
 clang/tools/clang-scan-deps/ClangScanDeps.cpp | 9 ++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 0849782a7354b..3bdeb461e4bfa 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,12 +298,14 @@ class ResourceDirectoryCache {
 };
 if (llvm::sys::ExecuteAndWait(ClangBinaryPath, PrintResourceDirArgs, {},
   Redirects)) {
-  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str(), 
/*IsText=*/true);
+  auto ErrorBuf =
+  llvm::MemoryBuffer::getFile(ErrorFile.c_str(), /*IsText=*/true);
   llvm::errs() << ErrorBuf.get()->getBuffer();
   return "";
 }
 
-auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str(), 
/*IsText=*/true);
+auto OutputBuf =
+llvm::MemoryBuffer::getFile(OutputFile.c_str(), /*IsText=*/true);
 if (!OutputBuf)
   return "";
 StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
@@ -1032,7 +1034,8 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
 std::unique_ptr TU;
 std::optional TUBuffer;
 if (!TranslationUnitFile.empty()) {
-  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
+  auto MaybeTU =
+  llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
   if (!MaybeTU) {
 llvm::errs() << "cannot open input translation unit: "
  << MaybeTU.getError().message() << "\n";

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


[clang] [SystemZ][z/OS] Mark text files as text in ClangScanDeps (PR #127514)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Abhina Sree (abhina-sree)


Changes

This patch continues the work that was started here 
https://reviews.llvm.org/D99426 to correctly open text files in text mode.

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


1 Files Affected:

- (modified) clang/tools/clang-scan-deps/ClangScanDeps.cpp (+3-3) 


``diff
diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 9cdb1eae56187..0849782a7354b 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,12 +298,12 @@ class ResourceDirectoryCache {
 };
 if (llvm::sys::ExecuteAndWait(ClangBinaryPath, PrintResourceDirArgs, {},
   Redirects)) {
-  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str());
+  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str(), 
/*IsText=*/true);
   llvm::errs() << ErrorBuf.get()->getBuffer();
   return "";
 }
 
-auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str());
+auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str(), 
/*IsText=*/true);
 if (!OutputBuf)
   return "";
 StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
@@ -1032,7 +1032,7 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
 std::unique_ptr TU;
 std::optional TUBuffer;
 if (!TranslationUnitFile.empty()) {
-  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile);
+  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
   if (!MaybeTU) {
 llvm::errs() << "cannot open input translation unit: "
  << MaybeTU.getError().message() << "\n";

``




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


[clang] [SystemZ][z/OS] Mark text files as text in ClangScanDeps (PR #127514)

2025-02-17 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 48c92dda0086d0ec2e8c1032ec53edec743c85f3 
a015e8389fa263cbbb28e56e93fae733f5e94dde --extensions cpp -- 
clang/tools/clang-scan-deps/ClangScanDeps.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 0849782a73..3bdeb461e4 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,12 +298,14 @@ public:
 };
 if (llvm::sys::ExecuteAndWait(ClangBinaryPath, PrintResourceDirArgs, {},
   Redirects)) {
-  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str(), 
/*IsText=*/true);
+  auto ErrorBuf =
+  llvm::MemoryBuffer::getFile(ErrorFile.c_str(), /*IsText=*/true);
   llvm::errs() << ErrorBuf.get()->getBuffer();
   return "";
 }
 
-auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str(), 
/*IsText=*/true);
+auto OutputBuf =
+llvm::MemoryBuffer::getFile(OutputFile.c_str(), /*IsText=*/true);
 if (!OutputBuf)
   return "";
 StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
@@ -1032,7 +1034,8 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
 std::unique_ptr TU;
 std::optional TUBuffer;
 if (!TranslationUnitFile.empty()) {
-  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
+  auto MaybeTU =
+  llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
   if (!MaybeTU) {
 llvm::errs() << "cannot open input translation unit: "
  << MaybeTU.getError().message() << "\n";

``




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


[clang-tools-extra] [clang-tidy] Add AllowFalseEvaluated flag to clang-tidy noexcept-move-constructor check (PR #126897)

2025-02-17 Thread Dmitry Nechitaev via cfe-commits

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


[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Vicente Mataix Ferrándiz via cfe-commits

https://github.com/loumalouomega updated 
https://github.com/llvm/llvm-project/pull/127066

From 6c210298a5aab4eeb0d155534d739e21ba315469 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Vicente=20Mataix=20Ferr=C3=A1ndiz?= 
Date: Thu, 13 Feb 2025 15:28:30 +0100
Subject: [PATCH 1/5] [tool] Remove legacy argument `-ignore-insert-conflict`
 from `run-clang-tidy.py`

---
 clang-tools-extra/clang-tidy/tool/run-clang-tidy.py | 1 -
 1 file changed, 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index f1b934f7139e9..acee87c860aa0 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -200,7 +200,6 @@ def apply_fixes(
 ) -> None:
 """Calls clang-apply-fixes on a given directory."""
 invocation = [clang_apply_replacements_binary]
-invocation.append("-ignore-insert-conflict")
 if args.format:
 invocation.append("-format")
 if args.style:

From 65adc60c634d93eb2186ddb18ada0131698bcabe Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Vicente=20Mataix=20Ferr=C3=A1ndiz?= 
Date: Fri, 14 Feb 2025 09:35:47 +0100
Subject: [PATCH 2/5] Optional

---
 clang-tools-extra/clang-tidy/tool/run-clang-tidy.py | 11 ++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index acee87c860aa0..3301cf5a84a93 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -198,8 +198,12 @@ def find_binary(arg: str, name: str, build_path: str) -> 
str:
 def apply_fixes(
 args: argparse.Namespace, clang_apply_replacements_binary: str, tmpdir: str
 ) -> None:
-"""Calls clang-apply-fixes on a given directory."""
+"""Calls clang-apply-replacements on a given directory."""
 invocation = [clang_apply_replacements_binary]
+
+if args.ignore_insert_conflict:  # Only append if the user specified it
+invocation.append("-ignore-insert-conflict")
+
 if args.format:
 invocation.append("-format")
 if args.style:
@@ -445,6 +449,11 @@ async def main() -> None:
 action="store_true",
 help="Allow empty enabled checks.",
 )
+parser.add_argument(
+"-ignore-insert-conflict",
+action="store_true",
+help="Ignore insert conflict when applying fixes.",
+)
 args = parser.parse_args()
 
 db_path = "compile_commands.json"

From 89e2b4d227990968e909dbc88eaef27a93643d13 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Vicente=20Mataix=20Ferr=C3=A1ndiz?= 
Date: Fri, 14 Feb 2025 12:20:05 +0100
Subject: [PATCH 3/5] Suggestions

---
 clang-tools-extra/clang-tidy/tool/run-clang-tidy.py | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 3301cf5a84a93..090c99a8f049f 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -201,9 +201,8 @@ def apply_fixes(
 """Calls clang-apply-replacements on a given directory."""
 invocation = [clang_apply_replacements_binary]
 
-if args.ignore_insert_conflict:  # Only append if the user specified it
+if args.ignore_insert_conflict:
 invocation.append("-ignore-insert-conflict")
-
 if args.format:
 invocation.append("-format")
 if args.style:

From e8165bc2a8db2f4101d8e65f5d93cdb2c4a272d5 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Vicente=20Mataix=20Ferr=C3=A1ndiz?= 
Date: Fri, 14 Feb 2025 12:25:07 +0100
Subject: [PATCH 4/5] [clang-tidy] Preserve current behaviour in
 `run-clang-tidy.py`

---
 clang-tools-extra/clang-tidy/tool/run-clang-tidy.py | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 090c99a8f049f..89f55f33a578e 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -451,6 +451,7 @@ async def main() -> None:
 parser.add_argument(
 "-ignore-insert-conflict",
 action="store_true",
+default=True,
 help="Ignore insert conflict when applying fixes.",
 )
 args = parser.parse_args()

From b1b52865fef30fb2bef19a6725ed9e987f85c70b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Vicente=20Mataix=20Ferr=C3=A1ndiz?= 
Date: Mon, 17 Feb 2025 12:18:55 +0100
Subject: [PATCH 5/5] [clang-tidy] Check for `-ignore-insert-conflict` support
 before using it in `apply_fixes` in `run_clang_tidy.py`

---
 .../clang-tidy/tool/run-clang-tidy.py | 19 +++
 1 file changed, 11 insertions(+), 8 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 89f

[clang] [analyzer] Add hack in ArrayBound to cover up missing casts (PR #127117)

2025-02-17 Thread Endre Fülöp via cfe-commits


@@ -588,20 +603,48 @@ void ArrayBoundChecker::performCheck(const Expr *E, 
CheckerContext &C) const {
 State, ByteOffset, SVB.makeZeroArrayIndex(), SVB);
 
 if (PrecedesLowerBound) {
-  // The offset may be invalid (negative)...
-  if (!WithinLowerBound) {
-// ...and it cannot be valid (>= 0), so report an error.
-Messages Msgs = getPrecedesMsgs(Reg, ByteOffset);
-reportOOB(C, PrecedesLowerBound, Msgs, ByteOffset, std::nullopt);
-return;
+  // The analyzer thinks that the offset may be invalid (negative)...
+
+  if (isOffsetObviouslyNonnegative(E, C)) {
+// ...but the offset is obviously non-negative (clear array subscript
+// with an unsigned index), so we're in a buggy situation.
+
+// TODO: Currently the analyzer ignores many casts (e.g. signed ->
+// unsigned casts), so it can easily reach states where it will load a
+// signed (and negative) value from an unsigned variable. This sanity
+// check is a duct tape "solution" that silences most of the ugly false
+// positives that are caused by this buggy behavior. Note that this is
+// not a complete solution: this cannot silence reports where pointer
+// arithmetic complicates the picture and cannot ensure modeling of the
+// "unsigned index is positive with highest bit set" cases which are
+// "usurped" by the nonsense "unsigned index is negative" case.
+// For more information about this topic, see the umbrella ticket
+// https://github.com/llvm/llvm-project/issues/39492
+// TODO: Remove this hack once 'SymbolCast's are modeled properly.
+
+if (!WithinLowerBound) {
+  // The state is completely nonsense -- let's just sink it!

gamesh411 wrote:

I think this would be the place to track the number of times we resort to 
suppression.

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


[clang-tools-extra] [clang-tidy] Add new check `readability-use-numeric-limits` (PR #127430)

2025-02-17 Thread Katherine Whitlock via cfe-commits

https://github.com/stellar-aria updated 
https://github.com/llvm/llvm-project/pull/127430

>From ba0eef9808b42b01e356cd5c87745f7477e07c68 Mon Sep 17 00:00:00 2001
From: Katherine Whitlock 
Date: Sun, 16 Feb 2025 22:45:06 -0500
Subject: [PATCH 1/2] [clang-tidy] Add new check
 `readability-use-numeric-limits`

---
 .../clang-tidy/readability/CMakeLists.txt |   1 +
 .../readability/ReadabilityTidyModule.cpp |   3 +
 .../readability/UseNumericLimitsCheck.cpp | 135 ++
 .../readability/UseNumericLimitsCheck.h   |  41 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   5 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/readability/use-numeric-limits.rst |  22 +++
 .../readability/use-numeric-limits.cpp|  85 +++
 8 files changed, 293 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/readability/UseNumericLimitsCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/readability/UseNumericLimitsCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/readability/use-numeric-limits.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/readability/use-numeric-limits.cpp

diff --git a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
index 8f303c51e1b0d..e06f68bdda73f 100644
--- a/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/readability/CMakeLists.txt
@@ -57,6 +57,7 @@ add_clang_library(clangTidyReadabilityModule STATIC
   UniqueptrDeleteReleaseCheck.cpp
   UppercaseLiteralSuffixCheck.cpp
   UseAnyOfAllOfCheck.cpp
+  UseNumericLimitsCheck.cpp
   UseStdMinMaxCheck.cpp
 
   LINK_LIBS
diff --git a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp 
b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
index d61c0ba39658e..054083d25952a 100644
--- a/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/readability/ReadabilityTidyModule.cpp
@@ -60,6 +60,7 @@
 #include "UniqueptrDeleteReleaseCheck.h"
 #include "UppercaseLiteralSuffixCheck.h"
 #include "UseAnyOfAllOfCheck.h"
+#include "UseNumericLimitsCheck.h"
 #include "UseStdMinMaxCheck.h"
 
 namespace clang::tidy {
@@ -170,6 +171,8 @@ class ReadabilityModule : public ClangTidyModule {
 "readability-uppercase-literal-suffix");
 CheckFactories.registerCheck(
 "readability-use-anyofallof");
+CheckFactories.registerCheck(
+"readability-use-numeric-limits");
 CheckFactories.registerCheck(
 "readability-use-std-min-max");
   }
diff --git a/clang-tools-extra/clang-tidy/readability/UseNumericLimitsCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/UseNumericLimitsCheck.cpp
new file mode 100644
index 0..b26ae008cbdd5
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/readability/UseNumericLimitsCheck.cpp
@@ -0,0 +1,135 @@
+//===--- UseNumericLimitsCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseNumericLimitsCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Preprocessor.h"
+#include 
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::readability {
+
+UseNumericLimitsCheck::UseNumericLimitsCheck(StringRef Name,
+ ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SignedConstants{
+  {std::numeric_limits::min(),
+   "std::numeric_limits::min()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::min(),
+   "std::numeric_limits::min()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::min(),
+   "std::numeric_limits::min()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::min(),
+   "std::numeric_limits::min()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+
+  },
+  UnsignedConstants{
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  {std::numeric_limits::max(),
+   "std::numeric_limits::max()"},
+  },
+  Inserter(Options.getLocalOrGlobal("IncludeStyle",
+utils::IncludeSorter::IS_LLVM),
+   areDiagsSelfC

[clang] [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK streams (PR #127049)

2025-02-17 Thread Gábor Horváth via cfe-commits

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


[clang] [llvm] [OpenMP] Missing implicit otherwise clause in metadirective. (PR #127113)

2025-02-17 Thread Alexey Bataev via cfe-commits


@@ -2882,6 +2882,12 @@ StmtResult 
Parser::ParseOpenMPDeclarativeOrExecutableDirective(
   /*ReadDirectiveWithinMetadirective=*/true);
   break;
 }
+// If no match is found and no otherwise clause is present, skip
+// OMP5.2 Chapter 7.4: If no otherwise clause is specified the effect is as
+// if one was specified without an associated directive variant.
+if (BestIdx == -1 && Idx == 1) {
+  SkipUntil(tok::annot_pragma_openmp_end);
+}

alexey-bataev wrote:

Not sure skipUntil is good here, since you may miss some junk at the end of the 
directive

https://github.com/llvm/llvm-project/pull/127113
___
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 false positive for cppcoreguidelines-pro-bounds-pointer-arithmetic (PR #127394)

2025-02-17 Thread via cfe-commits


@@ -110,6 +110,10 @@ Changes in existing checks
   ` check by providing additional
   examples and fixing some macro related false positives.
 
+- Improved :doc:`cppcoreguidelines-pro-bounds-pointer-arithmetic

flovent wrote:

Done.

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


[clang] [Sema] Add code completion for if constexpr (PR #124315)

2025-02-17 Thread Letu Ren via cfe-commits

https://github.com/FantasqueX updated 
https://github.com/llvm/llvm-project/pull/124315

>From 23e07a719b8262bd68950812bf47c5b9c0ecbeba Mon Sep 17 00:00:00 2001
From: Letu Ren 
Date: Sat, 25 Jan 2025 01:23:52 +0800
Subject: [PATCH 1/5] [Sema] Add code completion for if constexpr

C++17 supports `if constexpr` statement. This patch implements this in
code completion.
---
 clang/include/clang/Sema/SemaCodeCompletion.h |  1 +
 clang/lib/Parse/ParseStmt.cpp |  8 
 clang/lib/Sema/SemaCodeComplete.cpp   | 15 +++
 3 files changed, 24 insertions(+)

diff --git a/clang/include/clang/Sema/SemaCodeCompletion.h 
b/clang/include/clang/Sema/SemaCodeCompletion.h
index e931596c215d3..af44745d5d123 100644
--- a/clang/include/clang/Sema/SemaCodeCompletion.h
+++ b/clang/include/clang/Sema/SemaCodeCompletion.h
@@ -152,6 +152,7 @@ class SemaCodeCompletion : public SemaBase {
   void CodeCompleteDesignator(const QualType BaseType,
   llvm::ArrayRef InitExprs,
   const Designation &D);
+  void CodeCompleteIfConstExpr(Scope *S) const;
   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
 
   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool 
EnteringContext,
diff --git a/clang/lib/Parse/ParseStmt.cpp b/clang/lib/Parse/ParseStmt.cpp
index cd4504630f871..3f9900dd997ad 100644
--- a/clang/lib/Parse/ParseStmt.cpp
+++ b/clang/lib/Parse/ParseStmt.cpp
@@ -1553,6 +1553,14 @@ StmtResult Parser::ParseIfStatement(SourceLocation 
*TrailingElseLoc) {
   IsConsteval = true;
   ConstevalLoc = ConsumeToken();
 }
+
+if (Tok.is(tok::code_completion)) {
+  if (getLangOpts().CPlusPlus17) {
+cutOffParsing();
+Actions.CodeCompletion().CodeCompleteIfConstExpr(getCurScope());
+return StmtError();
+  }
+}
   }
   if (!IsConsteval && (NotLocation.isValid() || Tok.isNot(tok::l_paren))) {
 Diag(Tok, diag::err_expected_lparen_after) << "if";
diff --git a/clang/lib/Sema/SemaCodeComplete.cpp 
b/clang/lib/Sema/SemaCodeComplete.cpp
index 80ae87e7c5725..bcc0cb18b8739 100644
--- a/clang/lib/Sema/SemaCodeComplete.cpp
+++ b/clang/lib/Sema/SemaCodeComplete.cpp
@@ -6749,6 +6749,21 @@ void SemaCodeCompletion::CodeCompleteInitializer(Scope 
*S, Decl *D) {
   CodeCompleteExpression(S, Data);
 }
 
+void SemaCodeCompletion::CodeCompleteIfConstExpr(Scope *S) const {
+  ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
+CodeCompleter->getCodeCompletionTUInfo(),
+CodeCompletionContext::CCC_SymbolOrNewName);
+  Results.EnterNewScope();
+
+  Results.AddResult(CodeCompletionResult("constexpr"));
+
+  Results.ExitScope();
+
+  HandleCodeCompleteResults(&SemaRef, CodeCompleter,
+Results.getCompletionContext(), Results.data(),
+Results.size());
+}
+
 void SemaCodeCompletion::CodeCompleteAfterIf(Scope *S, bool IsBracedThen) {
   ResultBuilder Results(SemaRef, CodeCompleter->getAllocator(),
 CodeCompleter->getCodeCompletionTUInfo(),

>From a7406e134dd5cf0ac42ca195418514b0bd0c480d Mon Sep 17 00:00:00 2001
From: Letu Ren 
Date: Mon, 3 Feb 2025 22:49:38 +0800
Subject: [PATCH 2/5] Add test for if constexpr completion

---
 clang/test/CodeCompletion/if-constexpr.cpp | 4 
 1 file changed, 4 insertions(+)
 create mode 100644 clang/test/CodeCompletion/if-constexpr.cpp

diff --git a/clang/test/CodeCompletion/if-constexpr.cpp 
b/clang/test/CodeCompletion/if-constexpr.cpp
new file mode 100644
index 0..48a89b4799cbc
--- /dev/null
+++ b/clang/test/CodeCompletion/if-constexpr.cpp
@@ -0,0 +1,4 @@
+void test() {
+  if c
+  // RUN: %clang_cc1 -fsyntax-only -std=c++17 
-code-completion-at=%s:%(line-1):7 %s -o - | FileCheck -check-prefix=CHECK-CC1 
%s
+  // CHECK-CC1: constexpr

>From 69b805acddc2e3609ca2049b560fa564e1b9be13 Mon Sep 17 00:00:00 2001
From: Letu Ren 
Date: Sat, 15 Feb 2025 18:03:38 +0800
Subject: [PATCH 3/5] rename function

---
 clang/include/clang/Sema/SemaCodeCompletion.h | 2 +-
 clang/lib/Parse/ParseStmt.cpp | 2 +-
 clang/lib/Sema/SemaCodeComplete.cpp   | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Sema/SemaCodeCompletion.h 
b/clang/include/clang/Sema/SemaCodeCompletion.h
index af44745d5d123..c79e6ec13634b 100644
--- a/clang/include/clang/Sema/SemaCodeCompletion.h
+++ b/clang/include/clang/Sema/SemaCodeCompletion.h
@@ -152,7 +152,7 @@ class SemaCodeCompletion : public SemaBase {
   void CodeCompleteDesignator(const QualType BaseType,
   llvm::ArrayRef InitExprs,
   const Designation &D);
-  void CodeCompleteIfConstExpr(Scope *S) const;
+  void CodeCompleteIfConstexpr(Scope *S) const;
   void CodeCompleteAfterIf(Scope *S, bool IsBracedThen);
 
   void CodeCompleteQualifiedId(Scope *S, CXXScopeSpec &SS, bool 
EnteringContext,
diff --git a/c

[clang] [Sema] Add code completion for if constexpr and consteval (PR #124315)

2025-02-17 Thread Letu Ren via cfe-commits

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


[clang] [Sema] Add code completion for if constexpr and consteval (PR #124315)

2025-02-17 Thread Letu Ren via cfe-commits

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


[clang] [llvm] [CMake] Fix -DLLVM_LINK_LLVM_DYLIB=on builds when using ninja multi config (PR #65451)

2025-02-17 Thread via cfe-commits

https://github.com/ur4t updated https://github.com/llvm/llvm-project/pull/65451

>From 77d8ba05ccf4f8d6953373d1e4f118ddbe865be9 Mon Sep 17 00:00:00 2001
From: ur4t <46435411+u...@users.noreply.github.com>
Date: Thu, 17 Aug 2023 23:21:39 +0800
Subject: [PATCH 1/2] [llvm][CMake] Fix llvm shared library when using ninja
 multi config

---
 llvm/tools/llvm-shlib/CMakeLists.txt | 25 +
 1 file changed, 17 insertions(+), 8 deletions(-)

diff --git a/llvm/tools/llvm-shlib/CMakeLists.txt 
b/llvm/tools/llvm-shlib/CMakeLists.txt
index ede3c5034e045..a5b0cab0f1ce5 100644
--- a/llvm/tools/llvm-shlib/CMakeLists.txt
+++ b/llvm/tools/llvm-shlib/CMakeLists.txt
@@ -45,10 +45,19 @@ if(LLVM_BUILD_LLVM_DYLIB)
   if("${CMAKE_SYSTEM_NAME}" STREQUAL "Darwin")
 set(LIB_NAMES -Wl,-all_load ${LIB_NAMES})
   else()
-configure_file(
-${CMAKE_CURRENT_SOURCE_DIR}/simple_version_script.map.in
-${LLVM_LIBRARY_DIR}/tools/llvm-shlib/simple_version_script.map)
-
+if("${CMAKE_CFG_INTDIR}" STREQUAL ".")
+  configure_file(
+${CMAKE_CURRENT_SOURCE_DIR}/simple_version_script.map.in
+${LLVM_LIBRARY_DIR}/tools/llvm-shlib/simple_version_script.map)
+else()
+  foreach(BUILD_MODE ${CMAKE_CONFIGURATION_TYPES})
+# Replace the special string with a per config directory.
+string(REPLACE ${CMAKE_CFG_INTDIR} ${BUILD_MODE} PER_CONF_LIBRARY_DIR 
${LLVM_LIBRARY_DIR})
+configure_file(
+  ${CMAKE_CURRENT_SOURCE_DIR}/simple_version_script.map.in
+  ${PER_CONF_LIBRARY_DIR}/tools/llvm-shlib/simple_version_script.map)
+  endforeach()
+endif()
 if(MSVC)
   target_link_directories(LLVM PRIVATE ${LLVM_LIBRARY_DIR})
   foreach(library ${LIB_NAMES})
@@ -156,7 +165,10 @@ if(LLVM_BUILD_LLVM_C_DYLIB AND MSVC)
   # Need to separate lib names with newlines.
   string(REPLACE ";" "\n" FILE_CONTENT "${FULL_LIB_NAMES}")
 
-  if(NOT "${CMAKE_CFG_INTDIR}" STREQUAL ".")
+  if("${CMAKE_CFG_INTDIR}" STREQUAL ".")
+# Write out the full lib names into file to be read by the python script.
+file(WRITE ${LIBSFILE} "${FILE_CONTENT}")
+  else()
 foreach(BUILD_MODE ${CMAKE_CONFIGURATION_TYPES})
   # Replace the special string with a per config directory.
   string(REPLACE ${CMAKE_CFG_INTDIR} ${BUILD_MODE} PER_CONF_CONTENT 
"${FILE_CONTENT}")
@@ -166,9 +178,6 @@ if(LLVM_BUILD_LLVM_C_DYLIB AND MSVC)
   # ${CMAKE_CFG_INTDIR} correctly and select the right one.
   file(WRITE ${LLVM_BINARY_DIR}/${BUILD_MODE}/libllvm-c.args 
"${PER_CONF_CONTENT}")
 endforeach()
-  else()
-# Write out the full lib names into file to be read by the python script.
-file(WRITE ${LIBSFILE} "${FILE_CONTENT}")
   endif()
 
   # Generate the exports file dynamically.

>From d603987c218e11761dc2d703241a4b1b056ecba7 Mon Sep 17 00:00:00 2001
From: ur4t <46435411+u...@users.noreply.github.com>
Date: Mon, 17 Feb 2025 20:10:10 +0800
Subject: [PATCH 2/2] [clang][CMake] Fix clang headers when using ninja multi
 config

---
 clang/lib/Headers/CMakeLists.txt | 25 +++--
 1 file changed, 19 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt
index 43124111b7ba5..a3a505bcb7f88 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -395,12 +395,25 @@ set(riscv_generated_files)
 
 function(copy_header_to_output_dir src_dir file)
   set(src ${src_dir}/${file})
-  set(dst ${output_dir}/${file})
-  add_custom_command(OUTPUT ${dst}
-DEPENDS ${src}
-COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst}
-COMMENT "Copying clang's ${file}...")
-  list(APPEND out_files ${dst})
+  if("${CMAKE_CFG_INTDIR}" STREQUAL ".")
+set(dst ${output_dir}/${file})
+add_custom_command(OUTPUT ${dst}
+  DEPENDS ${src}
+  COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst}
+  COMMENT "Copying clang's ${file}...")
+list(APPEND out_files ${dst})
+  else()
+foreach(BUILD_MODE ${CMAKE_CONFIGURATION_TYPES})
+  # Replace the special string with a per config directory.
+  string(REPLACE ${CMAKE_CFG_INTDIR} ${BUILD_MODE} per_conf_output_dir 
${output_dir})
+  set(dst ${per_conf_output_dir}/${file})
+  add_custom_command(OUTPUT ${dst}
+DEPENDS ${src}
+COMMAND ${CMAKE_COMMAND} -E copy_if_different ${src} ${dst}
+COMMENT "Copying clang's ${file}...")
+  list(APPEND out_files ${dst})
+endforeach()
+  endif()
   set(out_files ${out_files} PARENT_SCOPE)
 endfunction(copy_header_to_output_dir)
 

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


[clang] [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK streams (PR #127049)

2025-02-17 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`clang-cmake-x86_64-avx512-win` running on `avx512-intel64-win` while building 
`clang` at step 6 "ninja check 1".

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


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

```
Step 6 (ninja check 1) failure: stage 1 checked (failure)
 TEST 'Clang :: Driver/offload-Xarch.c' FAILED 

Exit Code: 1

Command Output (stdout):
--
# RUN: at line 3
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe 
--target=x86_64-unknown-linux-gnu -x cuda 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
 -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe 
-check-prefix=O3ONCE 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe' 
--target=x86_64-unknown-linux-gnu -x cuda 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
 -Xarch_nvptx64 -O3 -S -nogpulib -nogpuinc '-###'
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe'
 -check-prefix=O3ONCE 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
# RUN: at line 4
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe -x 
cuda 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
 -Xarch_device -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe 
-check-prefix=O3ONCE 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe' -x 
cuda 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
 -Xarch_device -O3 -S -nogpulib -nogpuinc '-###'
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe'
 -check-prefix=O3ONCE 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
# RUN: at line 5
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe -x 
hip 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
 -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc -### 2>&1 | 
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe 
-check-prefix=O3ONCE 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe' -x 
hip 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
 -Xarch_amdgcn -O3 -S -nogpulib -nogpuinc '-###'
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe'
 -check-prefix=O3ONCE 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
# RUN: at line 6
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe 
-fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib -nogpuinc
-Xarch_amdgcn -march=gfx90a -Xarch_amdgcn -O3 -S -### 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
 2>&1  | 
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe 
-check-prefix=O3ONCE 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe' 
-fopenmp=libomp -fopenmp-targets=amdgcn-amd-amdhsa -nogpulib -nogpuinc 
-Xarch_amdgcn -march=gfx90a -Xarch_amdgcn -O3 -S '-###' 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe'
 -check-prefix=O3ONCE 
'D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c'
# RUN: at line 9
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\clang.exe 
-fopenmp=libomp -fopenmp-targets=nvptx64-nvidia-cuda -nogpulib -nogpuinc
-Xarch_nvptx64 -march=sm_52 -Xarch_nvptx64 -O3 -S -### 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
 2>&1  | 
d:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\stage1\bin\filecheck.exe 
-check-prefix=O3ONCE 
D:\buildbot\llvm-worker\clang-cmake-x86_64-avx512-win\llvm\clang\test\Driver\offload-Xarch.c
# executed command: 
'd:\buildbot\llvm-worker\clang-cmake-x8

[clang-tools-extra] [clang-tidy] Add new check `readability-use-numeric-limits` (PR #127430)

2025-02-17 Thread Katherine Whitlock via cfe-commits


@@ -91,6 +91,11 @@ Improvements to clang-tidy
 New checks
 ^^
 
+- New :doc:`readability-use-numeric-limits
+  ` check to replace certain

stellar-aria wrote:

Reworded and reformatted to match 


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


[libclc] [libclc] Fix dependencies on generated convert builtins (PR #127515)

2025-02-17 Thread Fraser Cormack via cfe-commits

https://github.com/frasercrmck created 
https://github.com/llvm/llvm-project/pull/127515

In #127378 it was reported that builds without clspv targets enabled were 
failing after #124727, as all targets had a dependency on a file that only 
clspv targets generated.

A quick fix was merged in #127315 which wasn't correct. It moved the dependency 
on those generated files to the spirv targets, instead of onto the clspv 
targets. This means a build with spirv targets and without clspv targets would 
see the same problems as #127378 reported.

I tried simply removing the requirement to explicitly add dependencies to the 
custom command, relying instead on the file-level dependencies. This didn't 
seem reliable enough; in some cases on a Makefiles build, the clang command 
compiling (e.g.,) convert.cl would begin before the file was fully written.

Instead, we keep the target-level dependency but automatically infer it based 
on the generated file name, to avoid manual book-keeping of pairs of files and 
targets.

This commit also fixes what looks like an unintended bug where, when 
ENABLE_RUNTIME_SUBNORMAL was enabled, the OpenCL conversions weren't being 
compiled.

>From fcbce268befa82d9580c9437c7b6327c251a5299 Mon Sep 17 00:00:00 2001
From: Fraser Cormack 
Date: Mon, 17 Feb 2025 15:59:09 +
Subject: [PATCH] [libclc] Fix dependencies on generated convert builtins

In #127378 it was reported that builds without clspv targets enabled
were failing after #124727, as all targets had a dependency on a file
that only clspv targets generated.

A quick fix was merged in #127315 which wasn't correct. It moved the
dependency on those generated files to the spirv targets, instead of
onto the clspv targets. This means a build with spirv targets and
without clspv targets would see the same problems as #127378 reported.

I tried simply removing the requirement to explicitly add dependencies
to the custom command, relying instead on the file-level dependencies.
This didn't seem reliable enough; in some cases on a Makefiles build,
the clang command compiling (e.g.,) convert.cl would begin before the
file was fully written.

Instead, we keep the target-level dependency but automatically infer it
based on the generated file name, to avoid manual book-keeping of
pairs of files and targets.

This commit also fixes what looks like an unintended bug where, when
ENABLE_RUNTIME_SUBNORMAL was enabled, the OpenCL conversions weren't
being compiled.
---
 libclc/CMakeLists.txt| 22 --
 libclc/cmake/modules/AddLibclc.cmake | 14 +++---
 2 files changed, 19 insertions(+), 17 deletions(-)

diff --git a/libclc/CMakeLists.txt b/libclc/CMakeLists.txt
index c88ea9700d100..5cefa8a264310 100644
--- a/libclc/CMakeLists.txt
+++ b/libclc/CMakeLists.txt
@@ -243,30 +243,30 @@ add_custom_command(
   OUTPUT convert.cl
   COMMAND ${Python3_EXECUTABLE} ${script_loc} > convert.cl
   DEPENDS ${script_loc} )
-add_custom_target( "generate_convert.cl" DEPENDS convert.cl )
-set_target_properties( "generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+add_custom_target( generate-convert.cl DEPENDS convert.cl )
+set_target_properties( generate-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
 add_custom_command(
   OUTPUT clc-convert.cl
   COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc > clc-convert.cl
   DEPENDS ${script_loc} )
-add_custom_target( "clc-generate_convert.cl" DEPENDS clc-convert.cl )
-set_target_properties( "clc-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+add_custom_target( generate-clc-convert.cl DEPENDS clc-convert.cl )
+set_target_properties( generate-clc-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
 if ( clspv-- IN_LIST LIBCLC_TARGETS_TO_BUILD OR clspv64-- IN_LIST 
LIBCLC_TARGETS_TO_BUILD )
   add_custom_command(
 OUTPUT clspv-convert.cl
 COMMAND ${Python3_EXECUTABLE} ${script_loc} --clspv > clspv-convert.cl
 DEPENDS ${script_loc} )
-  add_custom_target( "clspv-generate_convert.cl" DEPENDS clspv-convert.cl )
-  set_target_properties( "clspv-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+  add_custom_target( generate-clspv-convert.cl DEPENDS clspv-convert.cl )
+  set_target_properties( generate-clspv-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 
   add_custom_command(
 OUTPUT clc-clspv-convert.cl
 COMMAND ${Python3_EXECUTABLE} ${script_loc} --clc --clspv > 
clc-clspv-convert.cl
 DEPENDS ${script_loc} )
-  add_custom_target( "clc-clspv-generate_convert.cl" DEPENDS 
clc-clspv-convert.cl )
-  set_target_properties( "clc-clspv-generate_convert.cl" PROPERTIES FOLDER 
"libclc/Sourcegenning" )
+  add_custom_target( generate-clc-clspv-convert.cl DEPENDS 
clc-clspv-convert.cl )
+  set_target_properties( generate-clc-clspv-convert.cl PROPERTIES FOLDER 
"libclc/Sourcegenning" )
 endif()
 
 enable_testing()
@@ -324,9 +324,11 @@ foreach( t ${LIBCLC_TARGETS_TO_BUILD} )
   if( NOT ARCH STREQUAL spirv AND 

[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,146 @@
+//===--- SmartptrResetAmbiguousCallCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SmartptrResetAmbiguousCallCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER_P(CallExpr, everyArgumentMatches,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  for (const auto *Arg : Node.arguments()) {
+if (!InnerMatcher.matches(*Arg, Finder, Builder))
+  return false;
+  }
+
+  return true;
+}
+
+AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
+  for (const auto *Param : Node.parameters()) {
+if (!Param->hasDefaultArg())
+  return false;
+  }
+
+  return true;
+}
+
+const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr";
+} // namespace
+
+SmartptrResetAmbiguousCallCheck::SmartptrResetAmbiguousCallCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SmartPointers(utils::options::parseStringList(
+  Options.get("SmartPointers", DefaultSmartPointers))) {}
+
+void SmartptrResetAmbiguousCallCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "SmartPointers",
+utils::options::serializeStringList(SmartPointers));
+}
+
+void SmartptrResetAmbiguousCallCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IsSmartptr = hasAnyName(SmartPointers);
+
+  const auto ResetMethod =
+  cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());
+
+  const auto TypeWithReset =
+  anyOf(cxxRecordDecl(hasMethod(ResetMethod)),
+classTemplateSpecializationDecl(
+hasSpecializedTemplate(classTemplateDecl(has(ResetMethod);
+
+  const auto SmartptrWithBugproneReset = classTemplateSpecializationDecl(
+  IsSmartptr,
+  hasTemplateArgument(
+  0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(TypeWithReset)));
+
+  // Find a.reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(callee(memberExpr(member(hasName("reset",
+everyArgumentMatches(cxxDefaultArgExpr()),
+on(expr(hasType(SmartptrWithBugproneReset
+  .bind("smartptrResetCall"),
+  this);
+
+  // Find a->reset() calls
+  Finder->addMatcher(

PiotrZSL wrote:

maybe something like this: 
```
Finder->addMatcher(
  cxxMemberCallExpr(
   callee(ResetMethod),
   unless(hasAnyArgument(expr(unless(cxxDefaultArgExpr(),
   anyOf(
 thisPointerType(SmartptrWithBugproneReset),
 on(cxxOperatorCallExpr(
  hasOverloadedOperatorName("->"),
  hasArgument(
  0, 
expr(hasType(classTemplateSpecializationDecl(IsSmartptr)
   )
   )
   ), this);
```

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


[clang] [llvm] [LLVM][Triple][NFCI] Add function to test for offloading triples (PR #126956)

2025-02-17 Thread Joseph Huber via cfe-commits

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,48 @@
+.. title:: clang-tidy - readability-ambiguous-smartptr-reset-call
+
+readability-ambiguous-smartptr-reset-call
+=
+
+Finds potentially erroneous calls to ``reset`` method on smart pointers when
+the pointee type also has a ``reset`` method. Having a ``reset`` method in
+both classes makes it easy to accidentally make the pointer null when
+intending to reset the underlying object.
+
+.. code-block:: c++
+
+  struct Resettable {
+void reset() { /* Own reset logic */ }
+  };
+
+  auto ptr = std::make_unique();
+
+  ptr->reset();  // Calls underlying reset method
+  ptr.reset();   // Makes the pointer null
+
+Both calls are valid C++ code, but the second one might not be what the
+developer intended, as it destroys the pointed-to object rather than resetting
+its state. It's easy to make such a typo because the difference between
+``.`` and ``->`` is really small.
+
+The recommended approach is to make the intent explicit by using either member
+access or direct assignment:
+
+.. code-block:: c++
+
+  std::unique_ptr ptr = std::make_unique();
+
+  (*ptr).reset();  // Clearly calls underlying reset method
+  ptr = nullptr;   // Clearly makes the pointer null
+
+The default smart pointers that are considered are ``std::unique_ptr``,
+``std::shared_ptr``, ``boost::unique_ptr``, ``boost::shared_ptr``. To specify
+other smart pointers or other classes use the :option:`SmartPointers` option.
+
+Options
+---
+
+.. option:: SmartPointers
+
+Semicolon-separated list of fully qualified class names of custom smart
+pointers. Default value is `::std::unique_ptr;::std::shared_ptr;

PiotrZSL wrote:

out of sync, change also DefaultSmartPointers to match this, consider adding 
std::optional here also (even that is not smart ptr)

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,239 @@
+// RUN: %check_clang_tidy %s readability-ambiguous-smartptr-reset-call %t 
--fix-notes --
+
+namespace std {
+
+template 
+struct unique_ptr {
+  T& operator*() const;
+  T* operator->() const;
+  void reset(T* p = nullptr);
+};
+
+template 
+struct shared_ptr {
+  T& operator*() const;
+  T* operator->() const;
+  void reset();
+  void reset(T*);
+};
+
+} // namespace std
+
+struct Resettable {
+  void reset();
+  void doSomething();
+};
+
+struct ResettableWithParam {
+  void reset(int a);
+  void doSomething();
+};
+
+struct ResettableWithDefaultParams {
+  void reset(int a = 0, double b = 0.0);
+  void doSomething();
+};
+
+struct NonResettable {
+  void doSomething();
+};
+
+void Positive() {
+  std::unique_ptr u;
+  u.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: u = nullptr;
+  u->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*u).reset();
+
+  std::shared_ptr s;
+  s.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: s = nullptr;
+  s->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*s).reset();
+
+  std::unique_ptr> uu_ptr;
+  uu_ptr.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: uu_ptr = nullptr;
+  uu_ptr->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*uu_ptr).reset();
+
+  std::unique_ptr> su_ptr;
+  su_ptr.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: su_ptr = nullptr;
+  su_ptr->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*su_ptr).reset();
+
+  std::unique_ptr rd;
+  rd.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: rd = nullptr;
+  rd->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*rd).reset();
+
+  std::unique_ptr>> nested_ptr;
+  nested_ptr.reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigning the pointer to 
'nullptr' here
+  // CHECK-FIXES: nested_ptr = nullptr;
+  nested_ptr->reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
pointee of a smart pointer, prefer more explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider dereferencing smart 
pointer to call 'reset' method of the pointee here
+  // CHECK-FIXES: (*nested_ptr).reset();
+  (*nested_ptr).reset();
+  // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: ambiguous call to 'reset()' on a 
smart pointer with pointee that also has a 'reset()' method, prefer more 
explicit approach
+  // CHECK-MESSAGES: :[[@LINE-2]]:3: note: consider assigni

[clang] [clang] Fix false positive regression for lifetime analysis warning. (PR #127460)

2025-02-17 Thread Haojian Wu via cfe-commits

https://github.com/hokein updated 
https://github.com/llvm/llvm-project/pull/127460

>From 3601ae837475da3c473f5be9c17687c439495ded Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 17 Feb 2025 10:08:14 +0100
Subject: [PATCH 1/3] [clang] Fix false positive regression for lifetime
 analysis warning.

---
 clang/lib/Sema/CheckExprLifetime.cpp  |  5 ++--
 clang/test/Sema/Inputs/lifetime-analysis.h|  2 ++
 .../Sema/warn-lifetime-analysis-nocfg.cpp | 24 +++
 3 files changed, 29 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 8963cad86dbca..3e0867343ccee 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1239,11 +1239,12 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
 }
 // Check the return type, e.g.
 //   const GSLOwner& func(const Foo& foo [[clang::lifetimebound]])
+//   GSLOwner* func(cosnt Foo& foo [[clang::lifetimebound]])
 //   GSLPointer func(const Foo& foo [[clang::lifetimebound]])
 if (FD &&
-((FD->getReturnType()->isReferenceType() &&
+((FD->getReturnType()->isPointerOrReferenceType() &&
   isRecordWithAttr(FD->getReturnType()->getPointeeType())) 
||
- isPointerLikeType(FD->getReturnType(
+  isGLSPointerType(FD->getReturnType(
   return Report;
 
 return Abandon;
diff --git a/clang/test/Sema/Inputs/lifetime-analysis.h 
b/clang/test/Sema/Inputs/lifetime-analysis.h
index d318033ff0cc4..2072e4603cead 100644
--- a/clang/test/Sema/Inputs/lifetime-analysis.h
+++ b/clang/test/Sema/Inputs/lifetime-analysis.h
@@ -61,6 +61,7 @@ struct basic_string_view {
   basic_string_view();
   basic_string_view(const T *);
   const T *begin() const;
+  const T *data() const;
 };
 using string_view = basic_string_view;
 
@@ -80,6 +81,7 @@ struct basic_string {
   const T *c_str() const;
   operator basic_string_view () const;
   using const_iterator = iter;
+  const T *data() const;
 };
 using string = basic_string;
 
diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index 04bb1330ded4c..a65bb936ca8cb 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -852,3 +852,27 @@ struct Test {
 };
 
 } // namespace GH120543
+
+namespace GH127195 {
+template 
+struct StatusOr {
+  T* operator->() [[clang::lifetimebound]];
+  T* value() [[clang::lifetimebound]];
+};
+
+const char* foo() {
+  StatusOr s;
+  return s->data(); // expected-warning {{address of stack memory associated 
with local variable}}
+  
+  StatusOr s2;
+  return s2->data();
+
+  StatusOr> s3;
+  return s3.value()->value()->data();
+
+  // would be nice to support the nested cases.
+  StatusOr> s4;
+  return s4.value()->value()->data();
+}
+
+} // namespace GH127195

>From 29e49e18339c7c2f2e9694c37a859967922c89e8 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 17 Feb 2025 14:23:39 +0100
Subject: [PATCH 2/3] add FIXME

---
 clang/test/Sema/warn-lifetime-analysis-nocfg.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp 
b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
index a65bb936ca8cb..66a2a19ceb321 100644
--- a/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
+++ b/clang/test/Sema/warn-lifetime-analysis-nocfg.cpp
@@ -870,7 +870,7 @@ const char* foo() {
   StatusOr> s3;
   return s3.value()->value()->data();
 
-  // would be nice to support the nested cases.
+  // FIXME: nested cases are not supported now.
   StatusOr> s4;
   return s4.value()->value()->data();
 }

>From 3f102069a5af3bd777e827735ea46d158a042193 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Mon, 17 Feb 2025 14:27:57 +0100
Subject: [PATCH 3/3] clang-format

---
 clang/lib/Sema/CheckExprLifetime.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 3e0867343ccee..1f87001f35b57 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -1244,7 +1244,7 @@ static AnalysisResult analyzePathForGSLPointer(const 
IndirectLocalPath &Path,
 if (FD &&
 ((FD->getReturnType()->isPointerOrReferenceType() &&
   isRecordWithAttr(FD->getReturnType()->getPointeeType())) 
||
-  isGLSPointerType(FD->getReturnType(
+ isGLSPointerType(FD->getReturnType(
   return Report;
 
 return Abandon;

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


[clang] [OpenMP] Silencly accept `neon_vector_type` for the offloading device (PR #127439)

2025-02-17 Thread Joseph Huber via cfe-commits

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


[clang] [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK streams (PR #127049)

2025-02-17 Thread Gábor Horváth via cfe-commits

https://github.com/Xazax-hun approved this pull request.


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


[clang] 9d48705 - [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK streams (#127049)

2025-02-17 Thread via cfe-commits

Author: flovent
Date: 2025-02-17T15:35:40+01:00
New Revision: 9d487050a144b895950a6fd48b993513a714e69d

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

LOG: [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK 
streams (#127049)

this PR close #124474 
when calling `read` and `recv` function for a non-block file descriptor
or a invalid file descriptor(`-1`), it will not cause block inside a
critical section.
this commit checks for non-block file descriptor assigned by `open`
function with `O_NONBLOCK` flag.

-

Co-authored-by: Balazs Benics 

Added: 
clang/test/Analysis/Inputs/system-header-simulator-cxx-std-locks.h
clang/test/Analysis/issue-124474.cpp

Modified: 
clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp

Removed: 




diff  --git 
a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
index 7460781799d08..bf35bee70870b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BlockInCriticalSectionChecker.cpp
@@ -145,6 +145,57 @@ using MutexDescriptor =
 std::variant;
 
+class SuppressNonBlockingStreams : public BugReporterVisitor {
+private:
+  const CallDescription OpenFunction{CDM::CLibrary, {"open"}, 2};
+  SymbolRef StreamSym;
+  const int NonBlockMacroVal;
+  bool Satisfied = false;
+
+public:
+  SuppressNonBlockingStreams(SymbolRef StreamSym, int NonBlockMacroVal)
+  : StreamSym(StreamSym), NonBlockMacroVal(NonBlockMacroVal) {}
+
+  static void *getTag() {
+static bool Tag;
+return &Tag;
+  }
+
+  void Profile(llvm::FoldingSetNodeID &ID) const override {
+ID.AddPointer(getTag());
+  }
+
+  PathDiagnosticPieceRef VisitNode(const ExplodedNode *N,
+   BugReporterContext &BRC,
+   PathSensitiveBugReport &BR) override {
+if (Satisfied)
+  return nullptr;
+
+std::optional Point = N->getLocationAs();
+if (!Point)
+  return nullptr;
+
+const auto *CE = Point->getStmtAs();
+if (!CE || !OpenFunction.matchesAsWritten(*CE))
+  return nullptr;
+
+if (N->getSVal(CE).getAsSymbol() != StreamSym)
+  return nullptr;
+
+Satisfied = true;
+
+// Check if open's second argument contains O_NONBLOCK
+const llvm::APSInt *FlagVal = N->getSVal(CE->getArg(1)).getAsInteger();
+if (!FlagVal)
+  return nullptr;
+
+if ((*FlagVal & NonBlockMacroVal) != 0)
+  BR.markInvalid(getTag(), nullptr);
+
+return nullptr;
+  }
+};
+
 class BlockInCriticalSectionChecker : public Checker {
 private:
   const std::array MutexDescriptors{
@@ -182,6 +233,9 @@ class BlockInCriticalSectionChecker : public 
Checker {
   const BugType BlockInCritSectionBugType{
   this, "Call to blocking function in critical section", "Blocking Error"};
 
+  using O_NONBLOCKValueTy = std::optional;
+  mutable std::optional O_NONBLOCKValue;
+
   void reportBlockInCritSection(const CallEvent &call, CheckerContext &C) 
const;
 
   [[nodiscard]] const NoteTag *createCritSectionNote(CritSectionMarker M,
@@ -337,6 +391,28 @@ void 
BlockInCriticalSectionChecker::reportBlockInCritSection(
  << "' inside of critical section";
   auto R = std::make_unique(BlockInCritSectionBugType,
 os.str(), ErrNode);
+  // for 'read' and 'recv' call, check whether it's file descriptor(first
+  // argument) is
+  // created by 'open' API with O_NONBLOCK flag or is equal to -1, they will
+  // not cause block in these situations, don't report
+  StringRef FuncName = Call.getCalleeIdentifier()->getName();
+  if (FuncName == "read" || FuncName == "recv") {
+SVal SV = Call.getArgSVal(0);
+SValBuilder &SVB = C.getSValBuilder();
+ProgramStateRef state = C.getState();
+ConditionTruthVal CTV =
+state->areEqual(SV, SVB.makeIntVal(-1, C.getASTContext().IntTy));
+if (CTV.isConstrainedTrue())
+  return;
+
+if (SymbolRef SR = SV.getAsSymbol()) {
+  if (!O_NONBLOCKValue)
+O_NONBLOCKValue = tryExpandAsInteger(
+"O_NONBLOCK", C.getBugReporter().getPreprocessor());
+  if (*O_NONBLOCKValue)
+R->addVisitor(SR, **O_NONBLOCKValue);
+}
+  }
   R->addRange(Call.getSourceRange());
   R->markInteresting(Call.getReturnValue());
   C.emitReport(std::move(R));

diff  --git 
a/clang/test/Analysis/Inputs/system-header-simulator-cxx-std-locks.h 
b/clang/test/Analysis/Inputs/system-header-simulator-cxx-std-locks.h
new file mode 100644
index 0..054dd5405e1be
--- /dev/null
+++ b/clang/test/Analysis/Inputs/system-header-simulator-cxx-std-locks.h
@@ -0,0 +1,13 @@
+#pragma clang system_header
+

[clang] Add support for dynamic libraries in CLANG_BOLT (PR #127020)

2025-02-17 Thread via cfe-commits

https://github.com/serge-sans-paille updated 
https://github.com/llvm/llvm-project/pull/127020

>From a701851462a19b4708599bd1bfcdd154b5b95573 Mon Sep 17 00:00:00 2001
From: serge-sans-paille 
Date: Thu, 13 Feb 2025 08:54:03 +0100
Subject: [PATCH] [clang][bolt] Improve CLANG_BOLT setup to support shared
 libraries

When linking clang with libLLVM and clang-cpp dynamically, bolt post
processing only optimizes the clang binary.

This patch makes sure it also instruments libLLVM and libclang-cpp,
otherwise optimizing just the clang binary yields limited benefits.

This currently only works on Linux due to reliance on LD_PRELOAD to have
the instrumented binary use the instrumented shared libraries.
---
 clang/cmake/caches/BOLT.cmake|   1 +
 clang/tools/driver/CMakeLists.txt|  40 ++--
 clang/utils/perf-training/perf-helper.py | 115 +++
 3 files changed, 109 insertions(+), 47 deletions(-)

diff --git a/clang/cmake/caches/BOLT.cmake b/clang/cmake/caches/BOLT.cmake
index eba2346b2f4ca..1956c10463148 100644
--- a/clang/cmake/caches/BOLT.cmake
+++ b/clang/cmake/caches/BOLT.cmake
@@ -1,6 +1,7 @@
 set(CMAKE_BUILD_TYPE Release CACHE STRING "")
 set(CLANG_BOLT "INSTRUMENT" CACHE STRING "")
 set(CMAKE_EXE_LINKER_FLAGS "-Wl,--emit-relocs,-znow" CACHE STRING "")
+set(CMAKE_SHARED_LINKER_FLAGS "-Wl,--emit-relocs,-znow" CACHE STRING "")
 
 set(LLVM_ENABLE_PROJECTS "bolt;clang" CACHE STRING "")
 set(LLVM_TARGETS_TO_BUILD Native CACHE STRING "")
diff --git a/clang/tools/driver/CMakeLists.txt 
b/clang/tools/driver/CMakeLists.txt
index 5d7962769014a..10ea5de387220 100644
--- a/clang/tools/driver/CMakeLists.txt
+++ b/clang/tools/driver/CMakeLists.txt
@@ -168,6 +168,28 @@ if (CLANG_BOLT AND NOT LLVM_BUILD_INSTRUMENTED)
   )
   set(LIT_COMMAND "${lit_base_dir}/${lit_file_name}")
 
+  set(CLANG_BOLT_INPUTS $)
+  set(CLANG_INSTRUMENTED_OUTPUTS ${CLANG_INSTRUMENTED})
+
+  # Add in dynamically linked libraries, if needs be. Currently only supported
+  # on Linux because it relies on LD_PRELOAD for instrumentation.
+  if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
+if (CLANG_LINK_CLANG_DYLIB)
+ set(CLANG_CPP_BOLT_INSTRUMENTED "clang-cxx-bolt.inst" CACHE STRING
+   "Name of BOLT-instrumented Clang library")
+ set(CLANG_CPP_INSTRUMENTED 
${LLVM_RUNTIME_OUTPUT_INTDIR}/${CLANG_CPP_BOLT_INSTRUMENTED})
+ list(APPEND CLANG_BOLT_INPUTS $)
+ list(APPEND CLANG_INSTRUMENTED_OUTPUTS ${CLANG_CPP_INSTRUMENTED})
+endif()
+if (LLVM_LINK_LLVM_DYLIB)
+  set(LLVM_BOLT_INSTRUMENTED "LLVM-bolt.inst" CACHE STRING
+"Name of BOLT-instrumented LLVM library")
+  set(LLVM_INSTRUMENTED 
${LLVM_RUNTIME_OUTPUT_INTDIR}/${LLVM_BOLT_INSTRUMENTED})
+  list(APPEND CLANG_BOLT_INPUTS $)
+  list(APPEND CLANG_INSTRUMENTED_OUTPUTS ${LLVM_INSTRUMENTED})
+endif()
+  endif()
+
   # This POST_BUILD command is executed unconditionally even if the clang 
target
   # is already built.  We need to wrap the whole bolt optimization process in
   # a single python wrapper, so that we can first check if the binary has
@@ -176,15 +198,15 @@ if (CLANG_BOLT AND NOT LLVM_BUILD_INSTRUMENTED)
 TARGET clang POST_BUILD
 COMMAND  "${Python3_EXECUTABLE}" 
${CMAKE_CURRENT_SOURCE_DIR}/../../utils/perf-training/perf-helper.py
  bolt-optimize
---method ${CLANG_BOLT}
---input $
---instrumented-output ${CLANG_INSTRUMENTED}
---fdata ${BOLT_FDATA}
---perf-training-binary-dir ${PERF_TRAINING_BINARY_DIR}
---readelf $
---bolt $
---lit "${LIT_COMMAND}"
---merge-fdata $
+ --method ${CLANG_BOLT}
+ --input "${CLANG_BOLT_INPUTS}"
+ --instrumented-output "${CLANG_INSTRUMENTED_OUTPUTS}"
+ --fdata ${BOLT_FDATA}
+ --perf-training-binary-dir ${PERF_TRAINING_BINARY_DIR}
+ --readelf $
+ --bolt $
+ --lit "${LIT_COMMAND}"
+ --merge-fdata $
 COMMENT "Optimizing Clang with BOLT"
 USES_TERMINAL
 VERBATIM
diff --git a/clang/utils/perf-training/perf-helper.py 
b/clang/utils/perf-training/perf-helper.py
index 55c5160a71c4f..cdb6c39f6c50e 100644
--- a/clang/utils/perf-training/perf-helper.py
+++ b/clang/utils/perf-training/perf-helper.py
@@ -560,6 +560,23 @@ def genOrderFile(args):
 return 0
 
 
+def filter_bolt_optimized(inputs, instrumented_outputs):
+new_inputs = []
+new_instrumented_ouputs = []
+for input, instrumented_output in zip(inputs, instrumented_outputs):
+output = subprocess.check_output(
+[opts.readelf, "-WS", input], universal_newlines=True
+)
+
+# This binary has already been bolt-optimized, so skip further 
processing.
+if re.search("\\.bolt\\.org\\.text", output, re.MULTILINE):
+print(f"Skipping {input}, it's already instrumented")
+else:
+new_inputs.append(input)
+new_

[clang] [compiler-rt] [llvm] [SystemZ] Add support for half (fp16) (PR #109164)

2025-02-17 Thread Jonas Paulsson via cfe-commits


@@ -541,11 +543,26 @@ SystemZTargetLowering::SystemZTargetLowering(const 
TargetMachine &TM,
   }
 
   // Handle floating-point types.
+  // Promote all f16 operations to float, with some exceptions below.
+  for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
+setOperationAction(Opc, MVT::f16, Promote);
+  setOperationAction(ISD::ConstantFP, MVT::f16, Expand);
+  for (MVT VT : {MVT::f32, MVT::f64, MVT::f128}) {
+setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
+setTruncStoreAction(VT, MVT::f16, Expand);
+  }
+  for (auto Op : {ISD::LOAD, ISD::ATOMIC_LOAD, ISD::STORE, ISD::ATOMIC_STORE})
+setOperationAction(Op, MVT::f16, Subtarget.hasVector() ? Legal : Custom);
+  setOperationAction(ISD::FP_ROUND, MVT::f16, LibCall);
+  setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, LibCall);
+  if (Subtarget.hasVector()) // f16 <-> i16 bitcasts.
+setOperationAction(ISD::BITCAST, MVT::i16, Custom);

JonPsson1 wrote:

Then common-code will fall back to do a bitcast via memory.

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


[clang] [clang][analyzer] Teach the BlockInCriticalSectionChecker about O_NONBLOCK streams (PR #127049)

2025-02-17 Thread Balazs Benics via cfe-commits

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


[clang] Add support for dynamic libraries in CLANG_BOLT (PR #127020)

2025-02-17 Thread via cfe-commits

serge-sans-paille wrote:

@tstellar : gentle ping :-)

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


[clang] [clang][analyzer] Add checker 'alpha.core.FixedAddressDereference' (PR #127191)

2025-02-17 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 



@@ -1,7 +1,163 @@
 // RUN: %clang_analyze_cc1 -analyzer-checker=core,alpha.core -verify %s
-// expected-no-diagnostics
 
-void foo(void) {
+extern void __assert_fail (__const char *__assertion, __const char *__file,
+unsigned int __line, __const char *__function)
+ __attribute__ ((__noreturn__));
+
+#define assert(expr) \
+  ((expr)  ? (void)(0)  : __assert_fail (#expr, __FILE__, __LINE__, __func__))
+
+typedef unsigned long uintptr_t;
+
+void f0(void) {
   int *p = (int*) 0x1; // Should not crash here.
-  *p = 3;
+  *p = 3; // expected-warning{{Dereference of a fixed address}}
+}
+
+void f1(int *p) {
+  if (p != (int *)-1)
+*p = 1;
+  else
+*p = 0; // expected-warning{{Dereference of a fixed address}}
+}
+
+struct f2_struct {
+  int x;
+};
+
+int f2(struct f2_struct* p) {
+
+  if (p != (struct f2_struct *)1)
+p->x = 1;
+
+  return p->x++; // expected-warning{{Access to field 'x' results in a 
dereference of a fixed address (loaded from variable 'p')}}
+}
+
+int f3_1(char* x) {
+  int i = 2;
+
+  if (x != (char *)1)
+return x[i - 1];
+
+  return x[i+1]; // expected-warning{{Array access (from variable 'x') results 
in a dereference of a fixed address}}
+}
+
+int f3_2(char* x) {
+  int i = 2;
+
+  if (x != (char *)1)
+return x[i - 1];
+
+  return x[i+1]++; // expected-warning{{Array access (from variable 'x') 
results in a dereference of a fixed address}}
+}
+
+int f4_1(int *p) {
+  uintptr_t x = (uintptr_t) p;
+
+  if (x != (uintptr_t)1)
+return 1;
+
+  int *q = (int*) x;
+  return *q; // expected-warning{{Dereference of a fixed address (loaded from 
variable 'q')}}
+}
+
+int f4_2(void) {
+  short array[2];
+  uintptr_t x = (uintptr_t)array;
+  short *p = (short *)x;
+
+  // The following branch should be infeasible.
+  if (!(p == &array[0])) {
+p = (short *)1;
+*p = 1; // no-warning
+  }
+
+  if (p != (short *)1) {
+*p = 5; // no-warning
+p = (short *)1; // expected-warning {{Using a fixed address is not 
portable}}
+  }
+  else return 1;
+
+  *p += 10; // expected-warning{{Dereference of a fixed}}
+  return 0;
+}
+
+int f5(void) {
+  char *s = "hello world";
+  return s[0]; // no-warning
+}
+
+void f6(int *p, int *q) {
+  if (p != (int *)1)
+if (p == (int *)1)
+  *p = 1; // no-warning
+
+  if (q == (int *)1)
+if (q != (int *)1)
+  *q = 1; // no-warning
+}
+
+int* qux(int);
+
+int f7_1(unsigned len) {
+  assert (len != 0);
+  int *p = (int *)1;
+  unsigned i;
+
+  for (i = 0; i < len; ++i)
+   p = qux(i);
+
+  return *p++; // no-warning
+}
+
+int f7_2(unsigned len) {
+  assert (len > 0);  // note use of '>'
+  int *p = (int *)1;
+  unsigned i;
+
+  for (i = 0; i < len; ++i)
+   p = qux(i);
+
+  return *p++; // no-warning
+}
+
+struct f8_s {
+  int x;
+  int y[2];
+};
+
+void f8(struct f8_s *s, int coin) {
+  if (s != (struct f8_s *)7)
+return;
+
+  if (coin)
+s->x = 5; // expected-warning{{Access to field 'x' results in a 
dereference of a fixed address (loaded from variable 's')}}
+  else
+s->y[1] = 6; // expected-warning{{Array access (via field 'y') results in 
a dereference of a fixed address}}
+}
+
+void f9() {
+  int (*p_function) (char, char) = (int (*)(char, char))0x04040; // FIXME: 
warn at this initialization
+  p_function = (int (*)(char, char))0x04080; // expected-warning {{Using a 
fixed address is not portable}}
+  // FIXME: there should be a warning from calling the function pointer with 
fixed address
+  int x = (*p_function) ('x', 'y');
+}
+
+#define AS_ATTRIBUTE volatile __attribute__((address_space(256)))

steakhal wrote:

Yea, let's pin both then.

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


[clang] [clang][analyzer] Add checker 'alpha.core.FixedAddressDereference' (PR #127191)

2025-02-17 Thread Balazs Benics via cfe-commits
=?utf-8?q?Balázs_Kéri?= ,
=?utf-8?q?Balázs_Kéri?= 
Message-ID:
In-Reply-To: 


steakhal wrote:

I've marked the resolved comments. There are a few unresolved conversations 
left.

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


[clang] [flang] [flang][OpenMP] Upstream `do concurrent` loop-nest detection. (PR #127478)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-flang-fir-hlfir

Author: Kareem Ergawy (ergawy)


Changes

Upstreams the next part of `do concurrent` to OpenMP mapping pass (from
AMD's ROCm implementation). See 
https://github.com/llvm/llvm-project/pull/126026 for more context.

This PR add loop nest detection logic. This enables us to discover
muli-range `do concurrent` loops and then map them as "collapsed" loop
nests to OpenMP.

This is a follow up for #126026, only the latest commit is relevant.

---

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


19 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+4) 
- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+2-1) 
- (added) flang/docs/DoConcurrentConversionToOpenMP.md (+229) 
- (modified) flang/docs/index.md (+1) 
- (modified) flang/include/flang/Frontend/CodeGenOptions.def (+2) 
- (modified) flang/include/flang/Frontend/CodeGenOptions.h (+5) 
- (modified) flang/include/flang/Optimizer/OpenMP/Passes.h (+2) 
- (modified) flang/include/flang/Optimizer/OpenMP/Passes.td (+30) 
- (added) flang/include/flang/Optimizer/OpenMP/Utils.h (+26) 
- (modified) flang/include/flang/Optimizer/Passes/Pipelines.h (+15-3) 
- (modified) flang/lib/Frontend/CompilerInvocation.cpp (+28) 
- (modified) flang/lib/Frontend/FrontendActions.cpp (+27-5) 
- (modified) flang/lib/Optimizer/OpenMP/CMakeLists.txt (+1) 
- (added) flang/lib/Optimizer/OpenMP/DoConcurrentConversion.cpp (+209) 
- (modified) flang/lib/Optimizer/Passes/Pipelines.cpp (+10-2) 
- (added) flang/test/Driver/do_concurrent_to_omp_cli.f90 (+20) 
- (added) flang/test/Transforms/DoConcurrent/basic_host.f90 (+53) 
- (added) flang/test/Transforms/DoConcurrent/loop_nest_test.f90 (+89) 
- (modified) flang/tools/bbc/bbc.cpp (+19-1) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5ad187926e710..0cd3dfd3fb29d 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6927,6 +6927,10 @@ defm loop_versioning : BoolOptionWithoutMarshalling<"f", 
"version-loops-for-stri
 
 def fhermetic_module_files : Flag<["-"], "fhermetic-module-files">, 
Group,
   HelpText<"Emit hermetic module files (no nested USE association)">;
+
+def fdo_concurrent_to_openmp_EQ : Joined<["-"], "fdo-concurrent-to-openmp=">,
+  HelpText<"Try to map `do concurrent` loops to OpenMP [none|host|device]">,
+  Values<"none, host, device">;
 } // let Visibility = [FC1Option, FlangOption]
 
 def J : JoinedOrSeparate<["-"], "J">,
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 9ad795edd724d..cb0b00a2fd699 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -153,7 +153,8 @@ void Flang::addCodegenOptions(const ArgList &Args,
 CmdArgs.push_back("-fversion-loops-for-stride");
 
   Args.addAllArgs(CmdArgs,
-  {options::OPT_flang_experimental_hlfir,
+  {options::OPT_fdo_concurrent_to_openmp_EQ,
+   options::OPT_flang_experimental_hlfir,
options::OPT_flang_deprecated_no_hlfir,
options::OPT_fno_ppc_native_vec_elem_order,
options::OPT_fppc_native_vec_elem_order,
diff --git a/flang/docs/DoConcurrentConversionToOpenMP.md 
b/flang/docs/DoConcurrentConversionToOpenMP.md
new file mode 100644
index 0..de2525dd8b57d
--- /dev/null
+++ b/flang/docs/DoConcurrentConversionToOpenMP.md
@@ -0,0 +1,229 @@
+
+
+# `DO CONCURRENT` mapping to OpenMP
+
+```{contents}
+---
+local:
+---
+```
+
+This document seeks to describe the effort to parallelize `do concurrent` loops
+by mapping them to OpenMP worksharing constructs. The goals of this document
+are:
+* Describing how to instruct `flang` to map `DO CONCURRENT` loops to OpenMP
+  constructs.
+* Tracking the current status of such mapping.
+* Describing the limitations of the current implementation.
+* Describing next steps.
+* Tracking the current upstreaming status (from the AMD ROCm fork).
+
+## Usage
+
+In order to enable `do concurrent` to OpenMP mapping, `flang` adds a new
+compiler flag: `-fdo-concurrent-to-openmp`. This flag has 3 possible values:
+1. `host`: this maps `do concurrent` loops to run in parallel on the host CPU.
+   This maps such loops to the equivalent of `omp parallel do`.
+2. `device`: this maps `do concurrent` loops to run in parallel on a target 
device.
+   This maps such loops to the equivalent of
+   `omp target teams distribute parallel do`.
+3. `none`: this disables `do concurrent` mapping altogether. In that case, such
+   loops are emitted as sequential loops.
+
+The `-fdo-concurrent-to-openmp` compiler switch is currently available only 
when
+OpenMP is also enabled. So you need to provide the following options to flang 
in
+order to enable it:
+```
+flang ... -fopenmp -fdo-concurrent-to-openmp=[host|de

[clang] [clang] Fix false positive regression for lifetime analysis warning. (PR #127460)

2025-02-17 Thread Utkarsh Saxena via cfe-commits

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


[clang] [analyzer] Delay the checker constructions after parsing (PR #127409)

2025-02-17 Thread Balazs Benics via cfe-commits

https://github.com/steakhal updated 
https://github.com/llvm/llvm-project/pull/127409

>From 5eb1d222478c6966780f22aa664321807da87114 Mon Sep 17 00:00:00 2001
From: Balazs Benics 
Date: Sun, 16 Feb 2025 20:37:34 +0100
Subject: [PATCH 1/2] [analyzer] Delay the checker constructions after parsing

If we were to delay checker constructions after we have a filled
ASTContext, then we could get rid of a bunch of "lazy initializers" in
checkers.

Turns out in the register functions of the checkers we could transfer
the ASTContext and all other things to checkers, so those could benefit
from in-class initializers and const fields.

For example, if a checker would take the ASTContext as the first field,
then the rest of the fields could use it in their in-class initializers,
so the ctor of the checker would only need to set a single field!

This would open uup countless opportunities for cleaning up the
asthetics of our checkers.

I attached a single use-case for the AST and the PP as demonstrating
purposes. You can imagine the rest.
---
 .../Core/PathSensitive/CheckerHelpers.h   | 17 ++
 .../Checkers/UnixAPIChecker.cpp   | 61 ++-
 .../Frontend/AnalysisConsumer.cpp | 18 +++---
 3 files changed, 57 insertions(+), 39 deletions(-)

diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
index b4afaaeec9a4b..f7635aa0342d1 100644
--- a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
+++ b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/CheckerHelpers.h
@@ -73,6 +73,23 @@ Nullability getNullabilityAnnotation(QualType Type);
 /// returned.
 std::optional tryExpandAsInteger(StringRef Macro, const Preprocessor &PP);
 
+class CachedMacroValue {
+public:
+  CachedMacroValue(StringRef MacroSpelling, const Preprocessor &PP)
+  : MacroValueOrFailure(tryExpandAsInteger(MacroSpelling, PP)) {}
+  explicit CachedMacroValue(int ConcreteValue)
+  : MacroValueOrFailure(ConcreteValue) {}
+
+  int valueOr(int Default) const {
+return MacroValueOrFailure.value_or(Default);
+  }
+  bool hasValue() const { return MacroValueOrFailure.has_value(); }
+  int value() const { return MacroValueOrFailure.value(); }
+
+private:
+  std::optional MacroValueOrFailure;
+};
+
 class OperatorKind {
   union {
 BinaryOperatorKind Bin;
diff --git a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
index da2d16ca9b5dd..0452e541e8d5c 100644
--- a/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/UnixAPIChecker.cpp
@@ -40,17 +40,28 @@ enum class OpenVariant {
   OpenAt
 };
 
+static CachedMacroValue getCreateFlagValue(const ASTContext &Ctx,
+   const Preprocessor &PP) {
+  CachedMacroValue MacroVal("O_CREAT", PP);
+  if (MacroVal.hasValue())
+return MacroVal;
+
+  // If we failed, fall-back to known values.
+  if (Ctx.getTargetInfo().getTriple().getVendor() == llvm::Triple::Apple)
+return CachedMacroValue{0x0200};
+  return MacroVal;
+}
+
 namespace {
 
-class UnixAPIMisuseChecker
-: public Checker> {
+class UnixAPIMisuseChecker : public Checker {
   const BugType BT_open{this, "Improper use of 'open'", categories::UnixAPI};
   const BugType BT_getline{this, "Improper use of getdelim",
categories::UnixAPI};
   const BugType BT_pthreadOnce{this, "Improper use of 'pthread_once'",
categories::UnixAPI};
   const BugType BT_ArgumentNull{this, "NULL pointer", categories::UnixAPI};
-  mutable std::optional Val_O_CREAT;
+  const CachedMacroValue Val_O_CREAT;
 
   ProgramStateRef
   EnsurePtrNotNull(SVal PtrVal, const Expr *PtrExpr, CheckerContext &C,
@@ -63,6 +74,9 @@ class UnixAPIMisuseChecker
   const Expr *SizePtrExpr, CheckerContext &C, ProgramStateRef State) const;
 
 public:
+  UnixAPIMisuseChecker(const ASTContext &Ctx, const Preprocessor &PP)
+  : Val_O_CREAT(getCreateFlagValue(Ctx, PP)) {}
+
   void checkASTDecl(const TranslationUnitDecl *TU, AnalysisManager &Mgr,
 BugReporter &BR) const;
 
@@ -134,20 +148,6 @@ ProgramStateRef UnixAPIMisuseChecker::EnsurePtrNotNull(
   return PtrNotNull;
 }
 
-void UnixAPIMisuseChecker::checkASTDecl(const TranslationUnitDecl *TU,
-AnalysisManager &Mgr,
-BugReporter &) const {
-  // The definition of O_CREAT is platform specific.
-  // Try to get the macro value from the preprocessor.
-  Val_O_CREAT = tryExpandAsInteger("O_CREAT", Mgr.getPreprocessor());
-  // If we failed, fall-back to known values.
-  if (!Val_O_CREAT) {
-if (TU->getASTContext().getTargetInfo().getTriple().getVendor() ==
-llvm::Triple::Apple)
-  Val_O_CREAT = 0x0200;
-  }
-}
-
 
//===--

[clang] [SystemZ][z/OS] Mark text files as text in ClangScanDeps (PR #127514)

2025-02-17 Thread Abhina Sree via cfe-commits

https://github.com/abhina-sree created 
https://github.com/llvm/llvm-project/pull/127514

This patch continues the work that was started here 
https://reviews.llvm.org/D99426 to correctly open text files in text mode.

>From a015e8389fa263cbbb28e56e93fae733f5e94dde Mon Sep 17 00:00:00 2001
From: Abhina Sreeskantharajan 
Date: Mon, 17 Feb 2025 10:56:10 -0500
Subject: [PATCH] mark text files as text in ClangScanDeps

---
 clang/tools/clang-scan-deps/ClangScanDeps.cpp | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/tools/clang-scan-deps/ClangScanDeps.cpp 
b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
index 9cdb1eae56187..0849782a7354b 100644
--- a/clang/tools/clang-scan-deps/ClangScanDeps.cpp
+++ b/clang/tools/clang-scan-deps/ClangScanDeps.cpp
@@ -298,12 +298,12 @@ class ResourceDirectoryCache {
 };
 if (llvm::sys::ExecuteAndWait(ClangBinaryPath, PrintResourceDirArgs, {},
   Redirects)) {
-  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str());
+  auto ErrorBuf = llvm::MemoryBuffer::getFile(ErrorFile.c_str(), 
/*IsText=*/true);
   llvm::errs() << ErrorBuf.get()->getBuffer();
   return "";
 }
 
-auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str());
+auto OutputBuf = llvm::MemoryBuffer::getFile(OutputFile.c_str(), 
/*IsText=*/true);
 if (!OutputBuf)
   return "";
 StringRef Output = OutputBuf.get()->getBuffer().rtrim('\n');
@@ -1032,7 +1032,7 @@ int clang_scan_deps_main(int argc, char **argv, const 
llvm::ToolContext &) {
 std::unique_ptr TU;
 std::optional TUBuffer;
 if (!TranslationUnitFile.empty()) {
-  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile);
+  auto MaybeTU = llvm::MemoryBuffer::getFile(TranslationUnitFile, 
/*IsText=*/true);
   if (!MaybeTU) {
 llvm::errs() << "cannot open input translation unit: "
  << MaybeTU.getError().message() << "\n";

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


[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Carlos Galvez via cfe-commits
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= 
Message-ID:
In-Reply-To: 


carlosgalvezp wrote:

>  should have delivered a run-clang-tidy.py that is appropriate for that 
> version.

It should, but does it? A typical installation comes from installing the Ubuntu 
packages, do they include `run-clang-tidy.py` at all?

If not, then I don't think `run-clang-tidy.py` should have the expectations of 
backwards compatibility and so on that we have for the more "public" 
deliveries. In that case, I agree with @whisperity that you should use a 
matching version.

You are not in control of the Clang/clang-tidy packages, but what about 
`run-clang-tidy.py`, @loumalouomega ? Can you downgrade that instead, to a 
version that matches the Clang/clang-tidy installation you have? I mean you 
should be able to clone this repo and checkout a compatible version, right? 
Since you already can clone the repo and put up a PR.

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


[clang-tools-extra] [clang-tidy] Add new check `readability-use-numeric-limits` (PR #127430)

2025-02-17 Thread via cfe-commits


@@ -91,6 +91,11 @@ Improvements to clang-tidy
 New checks
 ^^
 
+- New :doc:`readability-use-numeric-limits
+  ` check to replace certain

EugeneZelenko wrote:

See 19 Release Notes for such statements format examples.

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


[clang] [libc] [Clang] Add handlers for 'match_any' and 'match_all' to `gpuintrin.h` (PR #127504)

2025-02-17 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/127504

Summary:
These helpers are very useful but currently absent. They allow the user
to get a bitmask representing the matches within the warp. I have made
an executive decision to drop the `predicate` return from `match_all`
because it's easily testable with `match_all() == __activemask()`.


>From ef1627cafc5caf43e6ca8ef3fe5e389c76b22b07 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Mon, 17 Feb 2025 09:04:03 -0600
Subject: [PATCH] [Clang] Add handlers for 'match_any' and 'match_all' to
 `gpuintrin.h`

Summary:
These helpers are very useful but currently absent. They allow the user
to get a bitmask representing the matches within the warp. I have made
an executive decision to drop the `predicate` return from `match_all`
because it's easily testable with `match_all() == __activemask()`.
---
 clang/lib/Headers/amdgpuintrin.h  | 56 ++
 clang/lib/Headers/nvptxintrin.h   | 74 +++
 libc/src/__support/GPU/utils.h|  8 ++
 .../src/__support/GPU/CMakeLists.txt  |  9 +++
 .../integration/src/__support/GPU/match.cpp   | 32 
 5 files changed, 179 insertions(+)
 create mode 100644 libc/test/integration/src/__support/GPU/match.cpp

diff --git a/clang/lib/Headers/amdgpuintrin.h b/clang/lib/Headers/amdgpuintrin.h
index 9dad99ffe9439..355e75d0b2d42 100644
--- a/clang/lib/Headers/amdgpuintrin.h
+++ b/clang/lib/Headers/amdgpuintrin.h
@@ -162,6 +162,62 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__lane_mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, __done)) {
+if (!__done) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
 // Returns true if the flat pointer points to AMDGPU 'shared' memory.
 _DEFAULT_FN_ATTRS static __inline__ bool __gpu_is_ptr_local(void *ptr) {
   return __builtin_amdgcn_is_shared((void [[clang::address_space(0)]] *)((
diff --git a/clang/lib/Headers/nvptxintrin.h b/clang/lib/Headers/nvptxintrin.h
index 40fa2edebe975..f857a87b5f4c7 100644
--- a/clang/lib/Headers/nvptxintrin.h
+++ b/clang/lib/Headers/nvptxintrin.h
@@ -13,6 +13,10 @@
 #error "This file is intended for NVPTX targets or offloading to NVPTX"
 #endif
 
+#ifndef __CUDA_ARCH__
+#define __CUDA_ARCH__ 0
+#endif
+
 #include 
 
 #if !defined(__cplusplus)
@@ -168,6 +172,76 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  // Newer targets can use the dedicated CUDA support.
+  if (__CUDA_ARCH__ >= 700 || __nvvm_reflect("__CUDA_ARCH") >= 700)
+return __nvvm_match_any_sync_i32(__lane_mask, __x);
+
+  uint32_t __match_mask = 0;
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane

[clang] [libc] [Clang] Add handlers for 'match_any' and 'match_all' to `gpuintrin.h` (PR #127504)

2025-02-17 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-backend-x86

Author: Joseph Huber (jhuber6)


Changes

Summary:
These helpers are very useful but currently absent. They allow the user
to get a bitmask representing the matches within the warp. I have made
an executive decision to drop the `predicate` return from `match_all`
because it's easily testable with `match_all() == __activemask()`.


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


5 Files Affected:

- (modified) clang/lib/Headers/amdgpuintrin.h (+56) 
- (modified) clang/lib/Headers/nvptxintrin.h (+74) 
- (modified) libc/src/__support/GPU/utils.h (+8) 
- (modified) libc/test/integration/src/__support/GPU/CMakeLists.txt (+9) 
- (added) libc/test/integration/src/__support/GPU/match.cpp (+32) 


``diff
diff --git a/clang/lib/Headers/amdgpuintrin.h b/clang/lib/Headers/amdgpuintrin.h
index 9dad99ffe9439..355e75d0b2d42 100644
--- a/clang/lib/Headers/amdgpuintrin.h
+++ b/clang/lib/Headers/amdgpuintrin.h
@@ -162,6 +162,62 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__lane_mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, __done)) {
+if (!__done) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
 // Returns true if the flat pointer points to AMDGPU 'shared' memory.
 _DEFAULT_FN_ATTRS static __inline__ bool __gpu_is_ptr_local(void *ptr) {
   return __builtin_amdgcn_is_shared((void [[clang::address_space(0)]] *)((
diff --git a/clang/lib/Headers/nvptxintrin.h b/clang/lib/Headers/nvptxintrin.h
index 40fa2edebe975..f857a87b5f4c7 100644
--- a/clang/lib/Headers/nvptxintrin.h
+++ b/clang/lib/Headers/nvptxintrin.h
@@ -13,6 +13,10 @@
 #error "This file is intended for NVPTX targets or offloading to NVPTX"
 #endif
 
+#ifndef __CUDA_ARCH__
+#define __CUDA_ARCH__ 0
+#endif
+
 #include 
 
 #if !defined(__cplusplus)
@@ -168,6 +172,76 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  // Newer targets can use the dedicated CUDA support.
+  if (__CUDA_ARCH__ >= 700 || __nvvm_reflect("__CUDA_ARCH") >= 700)
+return __nvvm_match_any_sync_i32(__lane_mask, __x);
+
+  uint32_t __match_mask = 0;
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  return __match_mask;
+}
+
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u64(uint64_t __lane_mask, uint64_t __x) {
+  // Newer targets can use the dedicated CUDA support.
+  if (__CUDA_ARCH__ >= 700 || __nvvm_reflect("__CUDA_ARCH") >= 700)
+return __nvvm_match_any_sync_i64(__lane_mask, __x);
+
+  uint64_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(_

[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Vicente Mataix Ferrándiz via cfe-commits

loumalouomega wrote:

> > should have delivered a run-clang-tidy.py that is appropriate for that 
> > version.
> 
> It should, but does it? A typical installation comes from installing the 
> Ubuntu packages, do they include `run-clang-tidy.py` at all?
> 
> If not, then I don't think `run-clang-tidy.py` should have the expectations 
> of backwards compatibility and so on that we have for the more "public" 
> deliveries. In that case, I agree with @whisperity that you should use a 
> matching version.
> 
> You are not in control of the Clang/clang-tidy packages, but what about 
> `run-clang-tidy.py`, @loumalouomega ? Can you downgrade that instead, to a 
> version that matches the Clang/clang-tidy installation you have? I mean you 
> should be able to clone this repo and checkout a compatible version, right? 
> Since you already can clone the repo and put up a PR.

The script is not included in the installation, and I cannot install them, 
thats why I downloaded manually the script and detected the problem. I can 
close this, if it is too problematic. I just wanted some people to not suffer 
this problematic in the future.

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


[clang] [libc] [Clang] Add handlers for 'match_any' and 'match_all' to `gpuintrin.h` (PR #127504)

2025-02-17 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-amdgpu

@llvm/pr-subscribers-libc

Author: Joseph Huber (jhuber6)


Changes

Summary:
These helpers are very useful but currently absent. They allow the user
to get a bitmask representing the matches within the warp. I have made
an executive decision to drop the `predicate` return from `match_all`
because it's easily testable with `match_all() == __activemask()`.


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


5 Files Affected:

- (modified) clang/lib/Headers/amdgpuintrin.h (+56) 
- (modified) clang/lib/Headers/nvptxintrin.h (+74) 
- (modified) libc/src/__support/GPU/utils.h (+8) 
- (modified) libc/test/integration/src/__support/GPU/CMakeLists.txt (+9) 
- (added) libc/test/integration/src/__support/GPU/match.cpp (+32) 


``diff
diff --git a/clang/lib/Headers/amdgpuintrin.h b/clang/lib/Headers/amdgpuintrin.h
index 9dad99ffe9439..355e75d0b2d42 100644
--- a/clang/lib/Headers/amdgpuintrin.h
+++ b/clang/lib/Headers/amdgpuintrin.h
@@ -162,6 +162,62 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__lane_mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __match_mask = 0;
+
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, __done)) {
+if (!__done) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  __gpu_sync_lane(__lane_mask);
+  return __match_mask;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u32(uint64_t __lane_mask, uint32_t __x) {
+  uint32_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
+// Returns the current lane mask if every lane contains __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_all_u64(uint64_t __lane_mask, uint64_t __x) {
+  uint64_t __first = __gpu_read_first_lane_u64(__lane_mask, __x);
+  uint64_t __ballot = __gpu_ballot(__lane_mask, __x == __first);
+  __gpu_sync_lane(__lane_mask);
+  return __ballot == __gpu_lane_mask() ? __gpu_lane_mask() : 0ull;
+}
+
 // Returns true if the flat pointer points to AMDGPU 'shared' memory.
 _DEFAULT_FN_ATTRS static __inline__ bool __gpu_is_ptr_local(void *ptr) {
   return __builtin_amdgcn_is_shared((void [[clang::address_space(0)]] *)((
diff --git a/clang/lib/Headers/nvptxintrin.h b/clang/lib/Headers/nvptxintrin.h
index 40fa2edebe975..f857a87b5f4c7 100644
--- a/clang/lib/Headers/nvptxintrin.h
+++ b/clang/lib/Headers/nvptxintrin.h
@@ -13,6 +13,10 @@
 #error "This file is intended for NVPTX targets or offloading to NVPTX"
 #endif
 
+#ifndef __CUDA_ARCH__
+#define __CUDA_ARCH__ 0
+#endif
+
 #include 
 
 #if !defined(__cplusplus)
@@ -168,6 +172,76 @@ __gpu_shuffle_idx_u64(uint64_t __lane_mask, uint32_t 
__idx, uint64_t __x,
  ((uint64_t)__gpu_shuffle_idx_u32(__mask, __idx, __lo, __width));
 }
 
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u32(uint64_t __lane_mask, uint32_t __x) {
+  // Newer targets can use the dedicated CUDA support.
+  if (__CUDA_ARCH__ >= 700 || __nvvm_reflect("__CUDA_ARCH") >= 700)
+return __nvvm_match_any_sync_i32(__lane_mask, __x);
+
+  uint32_t __match_mask = 0;
+  bool __done = 0;
+  while (__gpu_ballot(__lane_mask, !__done)) {
+if (!__done) {
+  uint32_t __first = __gpu_read_first_lane_u32(__lane_mask, __x);
+  if (__first == __x) {
+__match_mask = __gpu_lane_mask();
+__done = 1;
+  }
+}
+  }
+  return __match_mask;
+}
+
+// Returns a bitmask marking all lanes that have the same value of __x.
+_DEFAULT_FN_ATTRS static __inline__ uint64_t
+__gpu_match_any_u64(uint64_t __lane_mask, uint64_t __x) {
+  // Newer targets can use the dedicated CUDA support.
+  if (__CUDA_ARCH__ >= 700 || __nvvm_reflect("__CUDA_ARCH") >= 700)
+return __nvvm_match_any_sync_i64(__lane_mask, __x);
+
+  uint64_t __match_mask = 0;
+
+  bool __done 

[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Vicente Mataix Ferrándiz via cfe-commits

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


[clang-tools-extra] [clang-tidy] Add new check `readability-use-numeric-limits` (PR #127430)

2025-02-17 Thread via cfe-commits


@@ -0,0 +1,85 @@
+// RUN: %check_clang_tidy -std=c++11-or-later %s 
readability-use-numeric-limits %t
+#include 
+
+void constants() {
+  // CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant -128 is being 
utilized. Consider using std::numeric_limits::min() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int8_t _ = std::numeric_limits::min();
+  int8_t _ = -128;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant 127 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int8_t _ = std::numeric_limits::max();
+  int8_t _ = +127;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:14: warning: The constant 127 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int8_t _ = std::numeric_limits::max();
+  int8_t _ = 127;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant -32768 is being 
utilized. Consider using std::numeric_limits::min() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int16_t _ = std::numeric_limits::min();
+  int16_t _ = -32768;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 32767 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int16_t _ = std::numeric_limits::max();
+  int16_t _ = +32767;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 32767 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int16_t _ = std::numeric_limits::max();
+  int16_t _ = 32767;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant -2147483648 is 
being utilized. Consider using std::numeric_limits::min() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int32_t _ = std::numeric_limits::min();
+  int32_t _ = -2147483648;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 2147483647 is 
being utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int32_t _ = std::numeric_limits::max();
+  int32_t _ = +2147483647;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 2147483647 is 
being utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: int32_t _ = std::numeric_limits::max();
+  int32_t _ = 2147483647;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 
-9223372036854775808 is being utilized. Consider using 
std::numeric_limits::min() instead [readability-use-numeric-limits]
+  // CHECK-FIXES: int64_t _ = std::numeric_limits::min();
+  int64_t _ = -9223372036854775808;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 
9223372036854775807 is being utilized. Consider using 
std::numeric_limits::max() instead [readability-use-numeric-limits]
+  // CHECK-FIXES: int64_t _ = std::numeric_limits::max();
+  int64_t _ = +9223372036854775807;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 
9223372036854775807 is being utilized. Consider using 
std::numeric_limits::max() instead [readability-use-numeric-limits]
+  // CHECK-FIXES: int64_t _ = std::numeric_limits::max();
+  int64_t _ = 9223372036854775807;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 255 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint8_t _ = std::numeric_limits::max();
+  uint8_t _ = 255;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:15: warning: The constant 255 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint8_t _ = std::numeric_limits::max();
+  uint8_t _ = +255;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 65535 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint16_t _ = std::numeric_limits::max();
+  uint16_t _ = 65535;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 65535 is being 
utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint16_t _ = std::numeric_limits::max();
+  uint16_t _ = +65535;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 4294967295 is 
being utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint32_t _ = std::numeric_limits::max();
+  uint32_t _ = 4294967295;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 4294967295 is 
being utilized. Consider using std::numeric_limits::max() instead 
[readability-use-numeric-limits]
+  // CHECK-FIXES: uint32_t _ = std::numeric_limits::max();
+  uint32_t _ = +4294967295;
+
+  // CHECK-MESSAGES: :[[@LINE+2]]:16: warning: The constant 
18446744073709551615 is being utilized. Consider using 
std::numeric_limits::max(

[clang] [analyzer] Add hack in ArrayBound to cover up missing casts (PR #127117)

2025-02-17 Thread Endre Fülöp via cfe-commits

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


[clang] [nfc][analyzer] Add MemSpace trait to program state (PR #123003)

2025-02-17 Thread Donát Nagy via cfe-commits

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

LGTM, thanks for the improvements :)

In the follow-up commits let's pay attention to the `ArrayBound` lower bound 
check where the code says that _"A symbolic region in unknown space represents 
an unknown pointer that may point into the middle of an array, so we don't look 
for underflows."_ and assumes that e.g. a symbolic region in a known space 
necessarily points to the beginning of a memory area (i.e. negative indices are 
erroneous).

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,146 @@
+//===--- SmartptrResetAmbiguousCallCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SmartptrResetAmbiguousCallCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER_P(CallExpr, everyArgumentMatches,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  for (const auto *Arg : Node.arguments()) {
+if (!InnerMatcher.matches(*Arg, Finder, Builder))
+  return false;
+  }
+
+  return true;
+}
+
+AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
+  for (const auto *Param : Node.parameters()) {
+if (!Param->hasDefaultArg())
+  return false;
+  }
+
+  return true;
+}
+
+const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr";
+} // namespace
+
+SmartptrResetAmbiguousCallCheck::SmartptrResetAmbiguousCallCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SmartPointers(utils::options::parseStringList(
+  Options.get("SmartPointers", DefaultSmartPointers))) {}
+
+void SmartptrResetAmbiguousCallCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "SmartPointers",
+utils::options::serializeStringList(SmartPointers));
+}
+
+void SmartptrResetAmbiguousCallCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IsSmartptr = hasAnyName(SmartPointers);
+
+  const auto ResetMethod =
+  cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());
+
+  const auto TypeWithReset =
+  anyOf(cxxRecordDecl(hasMethod(ResetMethod)),
+classTemplateSpecializationDecl(
+hasSpecializedTemplate(classTemplateDecl(has(ResetMethod);
+
+  const auto SmartptrWithBugproneReset = classTemplateSpecializationDecl(
+  IsSmartptr,
+  hasTemplateArgument(
+  0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(TypeWithReset)));
+
+  // Find a.reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(callee(memberExpr(member(hasName("reset",
+everyArgumentMatches(cxxDefaultArgExpr()),
+on(expr(hasType(SmartptrWithBugproneReset
+  .bind("smartptrResetCall"),
+  this);
+
+  // Find a->reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(
+  callee(memberExpr(
+  member(ResetMethod),
+  hasObjectExpression(
+  cxxOperatorCallExpr(
+  hasOverloadedOperatorName("->"),
+  hasArgument(
+  0, expr(hasType(
+ 
classTemplateSpecializationDecl(IsSmartptr)
+  .bind("OpCall",
+  everyArgumentMatches(cxxDefaultArgExpr()))
+  .bind("objectResetCall"),
+  this);
+}
+
+void SmartptrResetAmbiguousCallCheck::check(
+const MatchFinder::MatchResult &Result) {
+
+  if (const auto *SmartptrResetCall =
+  Result.Nodes.getNodeAs("smartptrResetCall")) {
+const auto *Member = cast(SmartptrResetCall->getCallee());
+
+diag(SmartptrResetCall->getBeginLoc(),
+ "be explicit when calling 'reset()' on a smart pointer with a "
+ "pointee that has a 'reset()' method");
+
+diag(SmartptrResetCall->getBeginLoc(), "assign the pointer to 'nullptr'",

vbvictor wrote:

Done

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,146 @@
+//===--- SmartptrResetAmbiguousCallCheck.cpp - clang-tidy 
-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "SmartptrResetAmbiguousCallCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+
+AST_MATCHER_P(CallExpr, everyArgumentMatches,
+  ast_matchers::internal::Matcher, InnerMatcher) {
+  for (const auto *Arg : Node.arguments()) {
+if (!InnerMatcher.matches(*Arg, Finder, Builder))
+  return false;
+  }
+
+  return true;
+}
+
+AST_MATCHER(CXXMethodDecl, hasOnlyDefaultParameters) {
+  for (const auto *Param : Node.parameters()) {
+if (!Param->hasDefaultArg())
+  return false;
+  }
+
+  return true;
+}
+
+const auto DefaultSmartPointers = "::std::shared_ptr;::std::unique_ptr";
+} // namespace
+
+SmartptrResetAmbiguousCallCheck::SmartptrResetAmbiguousCallCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  SmartPointers(utils::options::parseStringList(
+  Options.get("SmartPointers", DefaultSmartPointers))) {}
+
+void SmartptrResetAmbiguousCallCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "SmartPointers",
+utils::options::serializeStringList(SmartPointers));
+}
+
+void SmartptrResetAmbiguousCallCheck::registerMatchers(MatchFinder *Finder) {
+  const auto IsSmartptr = hasAnyName(SmartPointers);
+
+  const auto ResetMethod =
+  cxxMethodDecl(hasName("reset"), hasOnlyDefaultParameters());
+
+  const auto TypeWithReset =
+  anyOf(cxxRecordDecl(hasMethod(ResetMethod)),
+classTemplateSpecializationDecl(
+hasSpecializedTemplate(classTemplateDecl(has(ResetMethod);
+
+  const auto SmartptrWithBugproneReset = classTemplateSpecializationDecl(
+  IsSmartptr,
+  hasTemplateArgument(
+  0, templateArgument(refersToType(hasUnqualifiedDesugaredType(
+ recordType(hasDeclaration(TypeWithReset)));
+
+  // Find a.reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(callee(memberExpr(member(hasName("reset",
+everyArgumentMatches(cxxDefaultArgExpr()),
+on(expr(hasType(SmartptrWithBugproneReset
+  .bind("smartptrResetCall"),
+  this);
+
+  // Find a->reset() calls
+  Finder->addMatcher(
+  cxxMemberCallExpr(
+  callee(memberExpr(
+  member(ResetMethod),
+  hasObjectExpression(
+  cxxOperatorCallExpr(
+  hasOverloadedOperatorName("->"),
+  hasArgument(
+  0, expr(hasType(
+ 
classTemplateSpecializationDecl(IsSmartptr)
+  .bind("OpCall",
+  everyArgumentMatches(cxxDefaultArgExpr()))
+  .bind("objectResetCall"),
+  this);
+}
+
+void SmartptrResetAmbiguousCallCheck::check(
+const MatchFinder::MatchResult &Result) {
+
+  if (const auto *SmartptrResetCall =
+  Result.Nodes.getNodeAs("smartptrResetCall")) {
+const auto *Member = cast(SmartptrResetCall->getCallee());
+
+diag(SmartptrResetCall->getBeginLoc(),
+ "be explicit when calling 'reset()' on a smart pointer with a "
+ "pointee that has a 'reset()' method");
+
+diag(SmartptrResetCall->getBeginLoc(), "assign the pointer to 'nullptr'",
+ DiagnosticIDs::Note)
+<< FixItHint::CreateReplacement(
+   SourceRange(Member->getOperatorLoc(),
+   Member->getOperatorLoc().getLocWithOffset(0)),
+   " =")
+<< FixItHint::CreateReplacement(
+   SourceRange(Member->getMemberLoc(),
+   SmartptrResetCall->getEndLoc()),
+   " nullptr");
+return;
+  }
+
+  if (const auto *ObjectResetCall =
+  Result.Nodes.getNodeAs("objectResetCall")) {
+const auto *Arrow = Result.Nodes.getNodeAs("OpCall");
+
+const CharSourceRange SmartptrSourceRange =
+Lexer::getAsCharRange(Arrow->getArg(0)->getSourceRange(),
+  *Result.SourceManager, getLangOpts());
+
+diag(ObjectResetCall->getBeginLoc(),
+ "be explicit when calling 'reset()' on a pointee of a smart pointer");

vbvictor wrote:

Done

https://github.com/llvm/llvm-project/pull/121291
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/

[clang] [HLSL] Implement the 'and' HLSL function (PR #127098)

2025-02-17 Thread Chris B via cfe-commits

llvm-beanz wrote:

For this issue I think there is a clear path forward to use the utilities that 
the `__builtin_hlsl_select` builtin uses to validate its arguments. I've filed 
https://github.com/llvm/llvm-project/issues/127512 to revisit all the other 
builtins that are using the pattern which produces misleading diagnostics, we 
can handle the "everything else" problem separately there.

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


[clang-tools-extra] [clang-tidy] Add bugprone-smartptr-reset-ambiguous-call check (PR #121291)

2025-02-17 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,47 @@
+.. title:: clang-tidy - bugprone-smartptr-reset-ambiguous-call
+
+bugprone-smartptr-reset-ambiguous-call
+==
+
+Finds potentially erroneous calls to ``reset`` method on smart pointers when
+the pointee type also has a ``reset`` method. Having a ``reset`` method in
+both classes makes it easy to accidentally make the pointer null when
+intending to reset the underlying object.
+
+.. code-block:: c++
+
+  struct Resettable {
+void reset() { /* Own reset logic */ }
+  };
+
+  auto ptr = std::make_unique();
+
+  ptr->reset();  // Calls underlying reset method
+  ptr.reset();   // Makes the pointer null
+
+Both calls are valid C++ code, but the second one might not be what the
+developer intended, as it destroys the pointed-to object rather than resetting
+its state. It's easy to make such a typo because the difference between
+``.`` and ``->`` is really small.
+
+The recommended approach is to make the intent explicit by using either member
+access or direct assignment:
+
+.. code-block:: c++
+
+  std::unique_ptr ptr = std::make_unique();
+
+  (*ptr).reset();  // Clearly calls underlying reset method
+  ptr = nullptr;   // Clearly makes the pointer null
+
+The default smart pointers that are considered are ``std::unique_ptr``,
+``std::shared_ptr``. To specify other smart pointers or other classes use the
+:option:`SmartPointers` option.
+
+Options
+---
+
+.. option:: SmartPointers
+
+Semicolon-separated list of class names of custom smart pointers.

vbvictor wrote:

Done

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


[clang] [NFC][Clang][CodeGen] Remove vestigial assertion (PR #127528)

2025-02-17 Thread Alex Voicu via cfe-commits

https://github.com/AlexVlx created 
https://github.com/llvm/llvm-project/pull/127528

This removes a vestigial assertion, which would erroneously trigger even though 
we now correctly handle valid arg mismatches 
(),
 after #114062 went in.

>From 489331ae8b3b09ef305b2b63c67a4c1aa8c2c90a Mon Sep 17 00:00:00 2001
From: Alex Voicu 
Date: Mon, 17 Feb 2025 19:38:15 +0200
Subject: [PATCH] Remove vestigial assertion.

---
 clang/lib/CodeGen/CGCall.cpp | 16 
 1 file changed, 16 deletions(-)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index e6c2ac939eb88..47bfd470dbafb 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -5633,22 +5633,6 @@ RValue CodeGenFunction::EmitCall(const CGFunctionInfo 
&CallInfo,
   if (!CallArgs.getCleanupsToDeactivate().empty())
 deactivateArgCleanupsBeforeCall(*this, CallArgs);
 
-  // Assert that the arguments we computed match up.  The IR verifier
-  // will catch this, but this is a common enough source of problems
-  // during IRGen changes that it's way better for debugging to catch
-  // it ourselves here.
-#ifndef NDEBUG
-  assert(IRCallArgs.size() == IRFuncTy->getNumParams() || 
IRFuncTy->isVarArg());
-  for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
-// Inalloca argument can have different type.
-if (IRFunctionArgs.hasInallocaArg() &&
-i == IRFunctionArgs.getInallocaArgNo())
-  continue;
-if (i < IRFuncTy->getNumParams())
-  assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
-  }
-#endif
-
   // Update the largest vector width if any arguments have vector types.
   for (unsigned i = 0; i < IRCallArgs.size(); ++i)
 LargestVectorWidth = std::max(LargestVectorWidth,

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


[clang] [flang] [flang] Add -f[no-]vectorize flags (PR #119718)

2025-02-17 Thread David Truby via cfe-commits

https://github.com/DavidTruby updated 
https://github.com/llvm/llvm-project/pull/119718

>From af135a1a4156be9076931ceeb92f75171a0cb7ad Mon Sep 17 00:00:00 2001
From: David Truby 
Date: Thu, 12 Dec 2024 14:50:19 +
Subject: [PATCH] [flang] Add -f[no-]vectorize flags

---
 clang/include/clang/Driver/Options.td | 11 +--
 clang/lib/Driver/ToolChains/Clang.cpp | 33 ---
 clang/lib/Driver/ToolChains/CommonArgs.cpp| 33 +++
 clang/lib/Driver/ToolChains/CommonArgs.h  |  2 ++
 clang/lib/Driver/ToolChains/Flang.cpp | 10 ++
 .../include/flang/Frontend/CodeGenOptions.def |  1 +
 flang/lib/Frontend/CompilerInvocation.cpp |  4 +++
 flang/lib/Frontend/FrontendActions.cpp|  2 ++
 flang/test/Driver/optimization-remark.f90 | 22 ++---
 flang/test/Integration/unroll-loops.f90   |  4 +--
 flang/test/Lower/HLFIR/unroll-loops.fir   |  4 +--
 11 files changed, 75 insertions(+), 51 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 5ad187926e710..6824ffb8828d4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3986,11 +3986,15 @@ defm assumptions : BoolFOption<"assumptions",
   "Disable codegen and compile-time checks for C++23's [[assume]] 
attribute">,
   PosFlag>;
 
+
+let Visibility = [ClangOption, FlangOption] in {
 def fvectorize : Flag<["-"], "fvectorize">, Group,
   HelpText<"Enable the loop vectorization passes">;
 def fno_vectorize : Flag<["-"], "fno-vectorize">, Group;
 def : Flag<["-"], "ftree-vectorize">, Alias;
 def : Flag<["-"], "fno-tree-vectorize">, Alias;
+}
+
 def fslp_vectorize : Flag<["-"], "fslp-vectorize">, Group,
   HelpText<"Enable the superword-level parallelism vectorization passes">;
 def fno_slp_vectorize : Flag<["-"], "fno-slp-vectorize">, Group;
@@ -7332,6 +7336,10 @@ def mlink_builtin_bitcode : Separate<["-"], 
"mlink-builtin-bitcode">,
 def mlink_bitcode_file
 : Separate<["-"], "mlink-bitcode-file">,
   HelpText<"Link the given bitcode file before performing optimizations.">;
+
+def vectorize_loops : Flag<["-"], "vectorize-loops">,
+  HelpText<"Run the Loop vectorization passes">,
+  MarshallingInfoFlag>;
 } // let Visibility = [CC1Option, FC1Option]
 
 let Visibility = [CC1Option] in {
@@ -7447,9 +7455,6 @@ defm link_builtin_bitcode_postopt: 
BoolMOption<"link-builtin-bitcode-postopt",
   PosFlag,
   NegFlag>;
-def vectorize_loops : Flag<["-"], "vectorize-loops">,
-  HelpText<"Run the Loop vectorization passes">,
-  MarshallingInfoFlag>;
 def vectorize_slp : Flag<["-"], "vectorize-slp">,
   HelpText<"Run the SLP vectorization passes">,
   MarshallingInfoFlag>;
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 96af466e067a8..7c50970068fa9 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -511,39 +511,6 @@ static void addCoveragePrefixMapArg(const Driver &D, const 
ArgList &Args,
   }
 }
 
-/// Vectorize at all optimization levels greater than 1 except for -Oz.
-/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
-/// enabled.
-static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) 
{
-  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
-if (A->getOption().matches(options::OPT_O4) ||
-A->getOption().matches(options::OPT_Ofast))
-  return true;
-
-if (A->getOption().matches(options::OPT_O0))
-  return false;
-
-assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
-
-// Vectorize -Os.
-StringRef S(A->getValue());
-if (S == "s")
-  return true;
-
-// Don't vectorize -Oz, unless it's the slp vectorizer.
-if (S == "z")
-  return isSlpVec;
-
-unsigned OptLevel = 0;
-if (S.getAsInteger(10, OptLevel))
-  return false;
-
-return OptLevel > 1;
-  }
-
-  return false;
-}
-
 /// Add -x lang to \p CmdArgs for \p Input.
 static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
  ArgStringList &CmdArgs) {
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 2d01943ca1ac4..1a2299a92c54e 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -3133,3 +3133,36 @@ void tools::renderCommonIntegerOverflowOptions(const 
ArgList &Args,
   if (use_fwrapv_pointer)
 CmdArgs.push_back("-fwrapv-pointer");
 }
+
+/// Vectorize at all optimization levels greater than 1 except for -Oz.
+/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
+/// enabled.
+bool tools::shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) 
{
+  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
+if (A->getOption().matches(options::OPT_O4) ||
+A->getOption().matches(options::OPT_Ofast))
+

[clang-tools-extra] [clangd] Update XRefs to support overriden ObjC methods (PR #127109)

2025-02-17 Thread kadir çetinkaya via cfe-commits


@@ -1438,6 +1461,15 @@ ReferencesResult findReferences(ParsedAST &AST, Position 
Pos, uint32_t Limit,
 getOverriddenMethods(CMD, OverriddenMethods);
   }
 }
+// Special case: Objective-C methods can override a parent class or
+// protocol, we should be sure to report references to those.
+if (const auto *OMD = llvm::dyn_cast(ND)) {
+  OverriddenBy.Subjects.insert(getSymbolID(OMD));
+  llvm::SmallVector Overrides;
+  OMD->getOverriddenMethods(Overrides);
+  for (const auto *Override : Overrides)
+OverriddenMethods.insert(getSymbolID(Override));

kadircet wrote:

i am not sure if it does, e.g. 
https://github.com/llvm/llvm-project/blob/main/clang/lib/AST/DeclObjC.cpp#L1268-L1273
 stops at the first overridden method.

maybe you can add some unittests for this as well ?

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


[clang] [flang] [flang] Add -f[no-]vectorize flags (PR #119718)

2025-02-17 Thread David Truby via cfe-commits

DavidTruby wrote:

It looks like the force push has worked this time. Sorry it took so long to do, 
I was on holiday.

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


[clang] [TBAA] Refine pointer-tbaa for void pointers by pointer depth (PR #126047)

2025-02-17 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

@brunodf-snps A reminder at the moment when you think this should be merged 
would be appreciated.

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


[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread Vicente Mataix Ferrándiz via cfe-commits

loumalouomega wrote:

> I am a bit confused here. If you're using the **system** Clang toolchain 
> assembled by your company (outside of your control), that toolchain should 
> have delivered a `run-clang-tidy.py` that is appropriate for that version.
> 
> If you are using `run-clang-tidy.py` from the Git working directory obtained 
> from upstream sources (i.e., `run-clang-tidy.py` is newer and has this flag), 
> then all the other tools (including `clang-tidy` and 
> `clang-apply-replacements`) should be the appropriate newer version.
> 
> Otherwise you might be mixing versions, standard library implementations, 
> intrinsic headers, etc., and there will be plenty of subtle bugs lurking 
> behind every corner!
> 
> So in general, what was the original point you're trying to achieve? To me, 
> the solution to the lack of `-ignore-insert-conflict` in 
> `clang-apply-replacements` would be to **build a newer 
> `clang-apply-replacements`** and have that in the _`PATH`_ earlier than the 
> system version. So your local `clang-tidy` binary, the 
> `clang-apply-replacements`, and the `run-clang-tidy.py` are all appropriately 
> from the same version.

I have a certain version of Ubuntu with a certain version of Clang, not custom 
compiled.

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


[clang] [analyzer] Delay the checker constructions after parsing (PR #127409)

2025-02-17 Thread Balazs Benics via cfe-commits


@@ -40,17 +40,28 @@ enum class OpenVariant {
   OpenAt
 };
 
+static CachedMacroValue getCreateFlagValue(const ASTContext &Ctx,
+   const Preprocessor &PP) {
+  CachedMacroValue MacroVal("O_CREAT", PP);
+  if (MacroVal.hasValue())
+return MacroVal;
+
+  // If we failed, fall-back to known values.
+  if (Ctx.getTargetInfo().getTriple().getVendor() == llvm::Triple::Apple)
+return CachedMacroValue{0x0200};
+  return MacroVal;
+}
+

steakhal wrote:

I'd refrain from generalizing right away. If we see this pattern appear again, 
we can think about concrete steps reducing the code duplication. So far I don't 
think it's the time.

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


[clang] [analyzer] Delay the checker constructions after parsing (PR #127409)

2025-02-17 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Delay the checker constructions after parsing (PR #127409)

2025-02-17 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

Thanks for the reviews!

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


[clang] [analyzer] Delay the checker constructions after parsing (PR #127409)

2025-02-17 Thread Balazs Benics via cfe-commits


@@ -73,6 +73,23 @@ Nullability getNullabilityAnnotation(QualType Type);
 /// returned.
 std::optional tryExpandAsInteger(StringRef Macro, const Preprocessor &PP);
 
+class CachedMacroValue {

steakhal wrote:

Right! Dropped in 10b4bd0403aa82a97f22a7fd55ee512625139091

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


[clang-tools-extra] [clangd] Store full decl/def range with symbol locations (PR #118102)

2025-02-17 Thread Christian Kandeler via cfe-commits

ckandeler wrote:

*sigh*
I want to use clangd for this purpose because it produces correct results 
particularly with non-trivial constructs, so I'm afraid 
that using such textual heuristics would kill that advantage.

I'll give it a try, though.

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


[clang] [OpenMP] Silencly accept `neon_vector_type` for the offloading device (PR #127439)

2025-02-17 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 d841c8842e17b7e74c3ee98c13a8a2505566deed 
55e4d444572da286fdd4218178c6bc03c3e56b5b --extensions cpp -- 
clang/test/Sema/bug113094.cpp clang/lib/Sema/SemaType.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 0c5cfdbba8..9aeab7595d 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -8337,10 +8337,12 @@ static bool verifyValidIntegerConstantExpr(Sema &S, 
const ParsedAttr &Attr,
 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
  Sema &S, VectorKind VecKind) {
   const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
-  bool IsArm = AuxTI && (AuxTI->getTriple().isAArch64() || 
AuxTI->getTriple().isARM());
+  bool IsArm =
+  AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM());
 
   bool IsTargetCUDAAndHostARM = IsArm && S.getLangOpts().CUDAIsDevice;
-  bool IsTargetOpenMPDeviceAndHostARM = IsArm && 
S.getLangOpts().OpenMPIsTargetDevice;
+  bool IsTargetOpenMPDeviceAndHostARM =
+  IsArm && S.getLangOpts().OpenMPIsTargetDevice;
 
   // Target must have NEON (or MVE, whose vectors are similar enough
   // not to need a separate attribute)

``




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


[clang] [OpenMP] Silencly accept `neon_vector_type` for the offloading device (PR #127439)

2025-02-17 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

The test you added doesn't seem to pass. You can run it locally with `llvm-lit 
/path/to/your/test -v`.

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


[clang-tools-extra] [clang-tidy] Check for `-ignore-insert-conflict` support before using it in `apply_fixes` in `run-clang-tidy.py` (PR #127066)

2025-02-17 Thread via cfe-commits
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= ,
Vicente Mataix =?utf-8?q?Ferrándiz?= 
Message-ID:
In-Reply-To: 


whisperity wrote:

I am a bit confused here. If you're using the **system** Clang toolchain 
assembled by your company (outside of your control), that toolchain should have 
delivered a `run-clang-tidy.py` that is appropriate for that version.

If you are using `run-clang-tidy.py` from the Git working directory obtained 
from upstream sources (i.e., `run-clang-tidy.py` is newer and has this flag), 
then all the other tools (including `clang-tidy` and 
`clang-apply-replacements`) should be the appropriate newer version.

Otherwise you might be mixing versions, standard library implementations, 
intrinsic headers, etc., and there will be plenty of subtle bugs lurking behind 
every corner!

So in general, what was the original point you're trying to achieve? To me, the 
solution to the lack of `-ignore-insert-conflict` in `clang-apply-replacements` 
would be to **build a newer `clang-apply-replacements`** and have that in the 
_`PATH`_ earlier than the system version. So your local `clang-tidy` binary, 
the `clang-apply-replacements`, and the `run-clang-tidy.py` are all 
appropriately from the same version.

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


[clang] Diagnose the code with trailing comma in the function call. (PR #125232)

2025-02-17 Thread Björn Pettersson via cfe-commits

bjope wrote:

Thanks. I see now that it did not work with older clang (at least not 19.1.0).

It did however work with our downstream fork before this patch. I haven't 
figured out how we avoided the error in the past. I guess we must have 
something downstream that avoided the error in the past, but I can't remember 
that we've done anything actively to suppress such errors. Weird.

I also agree that our downstream users should try to use __VA_OPT__ instead 
(hopefully there are no other tools that would complain about that).

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


  1   2   3   4   5   >