[clang] [Fuchsia] Remove linker flags from stage2 pass through (PR #99722)

2024-07-20 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `clang-hip-vega20` running 
on `hip-vega20-0` while building `clang` at step 3 "annotate".

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

Here is the relevant piece of the build log for the reference:
```
Step 3 (annotate) failure: 
'../llvm-zorg/zorg/buildbot/builders/annotated/hip-build.sh --jobs=' (failure)
...
[36/38] : && /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/clang++ -O3 
-DNDEBUG  
External/HIP/CMakeFiles/InOneWeekend-hip-6.0.2.dir/workload/ray-tracing/InOneWeekend/main.cc.o
 -o External/HIP/InOneWeekend-hip-6.0.2  
--rocm-path=/buildbot/Externals/hip/rocm-6.0.2 --hip-link -rtlib=compiler-rt 
-unwindlib=libgcc -frtlib-add-rpath && cd 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP && 
/usr/local/bin/cmake -E create_symlink 
/buildbot/llvm-test-suite/External/HIP/InOneWeekend.reference_output 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/InOneWeekend.reference_output-hip-6.0.2
[37/38] /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/clang++ -DNDEBUG  -O3 
-DNDEBUG   -w -Werror=date-time --rocm-path=/buildbot/Externals/hip/rocm-6.0.2 
--offload-arch=gfx908 --offload-arch=gfx90a --offload-arch=gfx1030 
--offload-arch=gfx1100 -xhip -mfma -MD -MT 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -MF 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o.d
 -o 
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -c 
/buildbot/llvm-test-suite/External/HIP/workload/ray-tracing/TheNextWeek/main.cc
[38/38] : && /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/clang++ -O3 
-DNDEBUG  
External/HIP/CMakeFiles/TheNextWeek-hip-6.0.2.dir/workload/ray-tracing/TheNextWeek/main.cc.o
 -o External/HIP/TheNextWeek-hip-6.0.2  
--rocm-path=/buildbot/Externals/hip/rocm-6.0.2 --hip-link -rtlib=compiler-rt 
-unwindlib=libgcc -frtlib-add-rpath && cd 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP && 
/usr/local/bin/cmake -E create_symlink 
/buildbot/llvm-test-suite/External/HIP/TheNextWeek.reference_output 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/TheNextWeek.reference_output-hip-6.0.2
+ build_step 'Testing HIP test-suite'
+ echo '@@@BUILD_STEP Testing HIP test-suite@@@'
+ ninja -v check-hip-simple
@@@BUILD_STEP Testing HIP test-suite@@@
[0/1] cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP 
&& /buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/llvm-lit -sv 
empty-hip-6.0.2.test with-fopenmp-hip-6.0.2.test saxpy-hip-6.0.2.test 
InOneWeekend-hip-6.0.2.test TheNextWeek-hip-6.0.2.test blender.test
-- Testing: 6 tests, 6 workers --
Testing:  0.. 10.. 20.. 30.. 40.. 
FAIL: test-suite :: External/HIP/InOneWeekend-hip-6.0.2.test (4 of 6)
 TEST 'test-suite :: 
External/HIP/InOneWeekend-hip-6.0.2.test' FAILED 

/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/timeit-target 
--timeout 7200 --limit-core 0 --limit-cpu 7200 --limit-file-size 209715200 
--limit-rss-size 838860800 --append-exitstatus --redirect-output 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 --redirect-input /dev/null --summary 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.time
 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/InOneWeekend-hip-6.0.2
cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP ; 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 InOneWeekend.reference_output-hip-6.0.2

+ cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP
+ /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target 
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP/Output/InOneWeekend-hip-6.0.2.test.out
 InOneWeekend.reference_output-hip-6.0.2
/buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/tools/fpcmp-target: 
Comparison failed, textual difference between 'M' and 'i'


/usr/bin/strip: /bin/bash.stripped: Bad file descriptor
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90.. 

Failed Tests (1):
  test-suite :: External/HIP/InOneWeekend-hip-6.0.2.test


Testing Time: 383.47s

Total Discovered Tests: 6
  Passed: 5 (83.33%)
  Failed: 1 (16.67%)
FAILED: External/HIP/CMakeFiles/check-hip-simple-hip-6.0.2 
cd /buildbot/hip-vega20-0/clang-hip-vega20/test-suite-build/External/HIP && 
/buildbot/hip-vega20-0/clang-hip-vega20/llvm/bin/llvm-lit -sv 
empty-hip-6.0.2.test with-fopenmp-hip-6.0.2.test saxpy-hip-6.0.2.test 
InOneWeekend-hip-6.0.2.test TheNextWeek-hip

[clang-tools-extra] [clang-tidy] Add modernize-use-cpp-style-comments check (PR #99713)

2024-07-20 Thread Congcong Cai via cfe-commits


@@ -0,0 +1,67 @@
+//===--- UseCppStyleCommentsCheck.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 "UseCppStyleCommentsCheck.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+#include "clang/Lex/Preprocessor.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+class UseCppStyleCommentsCheck::CStyleCommentHandler : public CommentHandler {
+public:
+  CStyleCommentHandler(UseCppStyleCommentsCheck &Check)
+  : Check(Check),
+CStyleCommentMatch(
+"^[ \t]*/\\*+[ \t\n]*(.*[ \t\n]*)*[ \t\n]*\\*+/[ \t\n]*$") {}

HerrCai0907 wrote:

Could you explain more about the regex in the comment?

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


[clang] 0d26f65 - [clang][Interp] Emit diagnostics if final ltor conversion fails

2024-07-20 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-20T10:01:25+02:00
New Revision: 0d26f65414afe496b00ee803cc24722a9bf3f41d

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

LOG: [clang][Interp] Emit diagnostics if final ltor conversion fails

Added: 


Modified: 
clang/lib/AST/Interp/EvalEmitter.cpp
clang/test/AST/Interp/cxx11.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index 59e78686b78ad..221bbfdc542ff 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -169,7 +169,9 @@ template <> bool EvalEmitter::emitRet(const 
SourceInfo &Info) {
   return false;
 // Never allow reading from a non-const pointer, unless the memory
 // has been created in this evaluation.
-if (!Ptr.isConst() && Ptr.block()->getEvalID() != Ctx.getEvalID())
+if (!Ptr.isZero() && Ptr.isBlockPointer() &&
+Ptr.block()->getEvalID() != Ctx.getEvalID() &&
+(!CheckLoad(S, OpPC, Ptr, AK_Read) || !Ptr.isConst()))
   return false;
 
 if (std::optional V =

diff  --git a/clang/test/AST/Interp/cxx11.cpp b/clang/test/AST/Interp/cxx11.cpp
index 92ab9b605f30d..cf2dfba079ef7 100644
--- a/clang/test/AST/Interp/cxx11.cpp
+++ b/clang/test/AST/Interp/cxx11.cpp
@@ -152,3 +152,11 @@ void A::f(SortOrder order) {
 return;
 }
 }
+
+namespace FinalLtorDiags {
+  template struct A {}; // both-note {{template parameter is declared 
here}}
+  int k;
+  int *q = &k; // both-note {{declared here}}
+  A c; // both-error {{non-type template argument of type 'int *' is not a 
constant expression}} \
+  // both-note {{read of non-constexpr variable 'q' is not allowed in 
a constant expression}}
+}



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


[clang] [llvm] [WIP][RISCV] Support __builtin_cpu_init and __builtin_cpu_supports (PR #99700)

2024-07-20 Thread Piyou Chen via cfe-commits


@@ -1020,3 +1020,64 @@ std::string 
RISCVISAInfo::getTargetFeatureForExtension(StringRef Ext) {
   return isExperimentalExtension(Name) ? "experimental-" + Name.str()
: Name.str();
 }
+
+struct RISCVExtBit {
+  const StringRef ext;
+  uint64_t bitpos;
+};
+
+/// Maps extensions with assigned bit positions within group 0 of
+/// __riscv_features_bits to their respective bit position.  At the
+/// moment all extensions are within group 0.
+static RISCVExtBit RISCVGroup0BitPositions[] = {

BeMg wrote:

One reason we choose the `tablegen` approach is trying to maintain the 
everything relate to extension (In this case is groupID/bitPos) inside 
`RISCVFeatures.td`. 

How about land https://github.com/llvm/llvm-project/pull/94440 now, and replace 
this struct with tablegen generated `.inc` file? Or maybe we could replace it 
after 19.x release?



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


[clang] 155f6b4 - [clang][Interp] Fix reporting invalid new/delete expressions

2024-07-20 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-20T10:41:12+02:00
New Revision: 155f6b49d90357d4062aa97f035f42617565ee26

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

LOG: [clang][Interp] Fix reporting invalid new/delete expressions

This should be a CCEDiag call and we do *not* abort because of it.

Added: 


Modified: 
clang/lib/AST/Interp/Interp.cpp
clang/test/AST/Interp/new-delete.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Interp.cpp b/clang/lib/AST/Interp/Interp.cpp
index cd6fc60400ebd..6fcd90e5f5849 100644
--- a/clang/lib/AST/Interp/Interp.cpp
+++ b/clang/lib/AST/Interp/Interp.cpp
@@ -728,8 +728,8 @@ bool CheckDynamicMemoryAllocation(InterpState &S, CodePtr 
OpPC) {
 return true;
 
   const SourceInfo &E = S.Current->getSource(OpPC);
-  S.FFDiag(E, diag::note_constexpr_new);
-  return false;
+  S.CCEDiag(E, diag::note_constexpr_new);
+  return true;
 }
 
 bool CheckNewDeleteForms(InterpState &S, CodePtr OpPC, bool NewWasArray,

diff  --git a/clang/test/AST/Interp/new-delete.cpp 
b/clang/test/AST/Interp/new-delete.cpp
index cb46426c0e3be..7a85def784920 100644
--- a/clang/test/AST/Interp/new-delete.cpp
+++ b/clang/test/AST/Interp/new-delete.cpp
@@ -560,4 +560,9 @@ constexpr int a() { // both-error {{never produces a 
constant expression}}
 }
 static_assert(a() == 1, ""); // both-error {{not an integral constant 
expression}} \
  // both-note {{in call to 'a()'}}
+
+
+static_assert(true ? *new int : 4, ""); // both-error {{expression is not an 
integral constant expression}} \
+// both-note {{read of uninitialized 
object is not allowed in a constant expression}}
+
 #endif



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


[clang] [Clang][AST] {CXXDefaultArgExpr, CXXDefaultInitExpr}::hasRewrittenInit return true iif the init expression was really rebuild (PR #99748)

2024-07-20 Thread via cfe-commits

https://github.com/yronglin created 
https://github.com/llvm/llvm-project/pull/99748

None

>From a79b9bbfcb666d7e841eda65a771970a811631a4 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 20 Jul 2024 17:47:39 +0800
Subject: [PATCH] [Clang][AST] {CXXDefaultArgExpr,
 CXXDefaultInitExpr}::hasRewrittenInit return true iif the init expression was
 really rebuild

Signed-off-by: yronglin 
---
 clang/include/clang/AST/ExprCXX.h | 13 ++-
 clang/lib/AST/ASTImporter.cpp |  7 +++---
 clang/lib/AST/ExprCXX.cpp | 22 +++
 clang/lib/AST/JSONNodeDumper.cpp  |  4 ++--
 clang/lib/Sema/SemaExpr.cpp   | 14 +++-
 clang/lib/Sema/TreeTransform.h|  9 
 clang/test/AST/ast-dump-default-init-json.cpp |  2 +-
 clang/test/AST/ast-dump-default-init.cpp  |  2 +-
 8 files changed, 42 insertions(+), 31 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index c2feac525c1ea..e863bcb104c09 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -1277,7 +1277,8 @@ class CXXDefaultArgExpr final
   DeclContext *UsedContext;
 
   CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
-Expr *RewrittenExpr, DeclContext *UsedContext)
+DeclContext *UsedContext, Expr *RewrittenExpr,
+bool HasRewrittenInit)
   : Expr(SC,
  Param->hasUnparsedDefaultArg()
  ? Param->getType().getNonReferenceType()
@@ -1286,7 +1287,7 @@ class CXXDefaultArgExpr final
  Param->getDefaultArg()->getObjectKind()),
 Param(Param), UsedContext(UsedContext) {
 CXXDefaultArgExprBits.Loc = Loc;
-CXXDefaultArgExprBits.HasRewrittenInit = RewrittenExpr != nullptr;
+CXXDefaultArgExprBits.HasRewrittenInit = HasRewrittenInit;
 if (RewrittenExpr)
   *getTrailingObjects() = RewrittenExpr;
 setDependence(computeDependence(this));
@@ -1304,8 +1305,8 @@ class CXXDefaultArgExpr final
   // \p Param is the parameter whose default argument is used by this
   // expression.
   static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
-   ParmVarDecl *Param, Expr *RewrittenExpr,
-   DeclContext *UsedContext);
+   ParmVarDecl *Param, DeclContext 
*UsedContext,
+   Expr *InitExpr, bool HasRewrittenInit);
   // Retrieve the parameter that the argument was created from.
   const ParmVarDecl *getParam() const { return Param; }
   ParmVarDecl *getParam() { return Param; }
@@ -1385,7 +1386,7 @@ class CXXDefaultInitExpr final
 
   CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
  FieldDecl *Field, QualType Ty, DeclContext *UsedContext,
- Expr *RewrittenInitExpr);
+ Expr *InitExpr, bool HasRewrittenInit);
 
   CXXDefaultInitExpr(EmptyShell Empty, bool HasRewrittenInit)
   : Expr(CXXDefaultInitExprClass, Empty) {
@@ -1399,7 +1400,7 @@ class CXXDefaultInitExpr final
   /// by this expression.
   static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
 FieldDecl *Field, DeclContext *UsedContext,
-Expr *RewrittenInitExpr);
+Expr *InitExpr, bool HasRewrittenInit);
 
   bool hasRewrittenInit() const {
 return CXXDefaultInitExprBits.HasRewrittenInit;
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 0c27f6f5df2da..4465c78d05ea1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8107,8 +8107,8 @@ ExpectedStmt 
ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
 RewrittenInit = ExprOrErr.get();
   }
   return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
-   *ToParamOrErr, RewrittenInit,
-   *UsedContextOrErr);
+   *ToParamOrErr, *UsedContextOrErr,
+   RewrittenInit, E->hasRewrittenInit());
 }
 
 ExpectedStmt
@@ -8814,7 +8814,8 @@ ExpectedStmt 
ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
   }
 
   return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr,
-ToField, *UsedContextOrErr, RewrittenInit);
+ToField, *UsedContextOrErr, RewrittenInit,
+E->hasRewrittenInit());
 }
 
 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 8d2a1b5611ccc..f8f1ccbbb7b34 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -1016,12 +

[clang] [Clang][AST] {CXXDefaultArgExpr, CXXDefaultInitExpr}::hasRewrittenInit return true iif the init expression was really rebuild (PR #99748)

2024-07-20 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 9d86722eeecbb1dd6a53c10f7c44fdc317de6809 
a79b9bbfcb666d7e841eda65a771970a811631a4 --extensions cpp,h -- 
clang/include/clang/AST/ExprCXX.h clang/lib/AST/ASTImporter.cpp 
clang/lib/AST/ExprCXX.cpp clang/lib/AST/JSONNodeDumper.cpp 
clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/TreeTransform.h 
clang/test/AST/ast-dump-default-init-json.cpp 
clang/test/AST/ast-dump-default-init.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index f8f1ccbbb7..bbbca3a40a 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -1013,12 +1013,10 @@ CXXDefaultArgExpr *CXXDefaultArgExpr::CreateEmpty(const 
ASTContext &C,
   return new (Mem) CXXDefaultArgExpr(EmptyShell(), HasRewrittenInit);
 }
 
-CXXDefaultArgExpr *CXXDefaultArgExpr::Create(const ASTContext &C,
- SourceLocation Loc,
- ParmVarDecl *Param,
- DeclContext *UsedContext,
- Expr *RewrittenExpr,
- bool HasRewrittenInit) {
+CXXDefaultArgExpr *
+CXXDefaultArgExpr::Create(const ASTContext &C, SourceLocation Loc,
+  ParmVarDecl *Param, DeclContext *UsedContext,
+  Expr *RewrittenExpr, bool HasRewrittenInit) {
   size_t Size = totalSizeToAlloc(RewrittenExpr != nullptr);
   auto *Mem = C.Allocate(Size, alignof(CXXDefaultArgExpr));
   return new (Mem)
@@ -1044,8 +1042,7 @@ Expr *CXXDefaultArgExpr::getAdjustedRewrittenExpr() {
 CXXDefaultInitExpr::CXXDefaultInitExpr(const ASTContext &Ctx,
SourceLocation Loc, FieldDecl *Field,
QualType Ty, DeclContext *UsedContext,
-   Expr *InitExpr,
-   bool HasRewrittenInit)
+   Expr *InitExpr, bool HasRewrittenInit)
 : Expr(CXXDefaultInitExprClass, Ty.getNonLValueExprType(Ctx),
Ty->isLValueReferenceType()   ? VK_LValue
: Ty->isRValueReferenceType() ? VK_XValue
@@ -1070,12 +1067,10 @@ CXXDefaultInitExpr 
*CXXDefaultInitExpr::CreateEmpty(const ASTContext &C,
   return new (Mem) CXXDefaultInitExpr(EmptyShell(), HasRewrittenInit);
 }
 
-CXXDefaultInitExpr *CXXDefaultInitExpr::Create(const ASTContext &Ctx,
-   SourceLocation Loc,
-   FieldDecl *Field,
-   DeclContext *UsedContext,
-   Expr *InitExpr,
-   bool HasRewrittenInit) {
+CXXDefaultInitExpr *
+CXXDefaultInitExpr::Create(const ASTContext &Ctx, SourceLocation Loc,
+   FieldDecl *Field, DeclContext *UsedContext,
+   Expr *InitExpr, bool HasRewrittenInit) {
 
   size_t Size = totalSizeToAlloc(InitExpr != nullptr);
   auto *Mem = Ctx.Allocate(Size, alignof(CXXDefaultInitExpr));

``




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


[clang] [clang-format] Fix a bug in annotating `*` in `#define`s (PR #99433)

2024-07-20 Thread Hirofumi Nakamura via cfe-commits

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


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


[clang] fix(clang/**.py): fix comparison to None (PR #94014)

2024-07-20 Thread Eisuke Kawashima via cfe-commits

https://github.com/e-kwsm updated 
https://github.com/llvm/llvm-project/pull/94014

>From cbc322d63ab460a1e13aa84b41c41c100fad13f9 Mon Sep 17 00:00:00 2001
From: Eisuke Kawashima 
Date: Sat, 11 May 2024 23:57:11 +0900
Subject: [PATCH] fix(clang/**.py): fix comparison to None

from PEP8 (https://peps.python.org/pep-0008/#programming-recommendations):

> Comparisons to singletons like None should always be done with is or
> is not, never the equality operators.
---
 clang/docs/DebuggingCoroutines.rst | 8 
 clang/tools/include-mapping/gen_std.py | 2 +-
 clang/utils/check_cfc/obj_diff.py  | 2 +-
 clang/utils/module-deps-to-rsp.py  | 2 +-
 4 files changed, 7 insertions(+), 7 deletions(-)

diff --git a/clang/docs/DebuggingCoroutines.rst 
b/clang/docs/DebuggingCoroutines.rst
index 53bdd08fdbc02..7f464c1f4f28c 100644
--- a/clang/docs/DebuggingCoroutines.rst
+++ b/clang/docs/DebuggingCoroutines.rst
@@ -513,7 +513,7 @@ So we can use the ``continuation`` field to construct the 
asynchronous stack:
   self.coro_frame = coro_frame
   self.resume_func = dereference(self.coro_frame.resume_addr)
   self.resume_func_block = gdb.block_for_pc(self.resume_func)
-  if self.resume_func_block == None:
+  if self.resume_func_block is None:
   raise Exception('Not stackless coroutine.')
   self.line_info = gdb.find_pc_line(self.resume_func)
 
@@ -543,8 +543,8 @@ So we can use the ``continuation`` field to construct the 
asynchronous stack:
   self.function_name = f
 
   def __str__(self, shift = 2):
-  addr = "" if self.address() == None else '%#x' % self.address() + " 
in "
-  location = "" if self.filename() == None else " at " + 
self.filename() + ":" + str(self.line())
+  addr = "" if self.address() is None else '%#x' % self.address() + " 
in "
+  location = "" if self.filename() is None else " at " + 
self.filename() + ":" + str(self.line())
   return addr + self.function() + " " + str([str(args) for args in 
self.frame_args()]) + location
 
   class CoroutineFilter:
@@ -598,7 +598,7 @@ So we can use the ``continuation`` field to construct the 
asynchronous stack:
 
   addr = int(argv[0], 16)
   block = 
gdb.block_for_pc(long(cast_addr2long_pointer(addr).dereference()))
-  if block == None:
+  if block is None:
   print "block " + str(addr) + "  is none."
   return
 
diff --git a/clang/tools/include-mapping/gen_std.py 
b/clang/tools/include-mapping/gen_std.py
index fcd3bd0d843ea..f362227bc6aab 100755
--- a/clang/tools/include-mapping/gen_std.py
+++ b/clang/tools/include-mapping/gen_std.py
@@ -215,7 +215,7 @@ def GetCCompatibilitySymbols(symbol):
 # Introduce two more entries, both in the global namespace, one using the
 # C++-compat header and another using the C header.
 results = []
-if symbol.namespace != None:
+if symbol.namespace is not None:
 # avoid printing duplicated entries, for C macros!
 results.append(cppreference_parser.Symbol(symbol.name, None, [header]))
 c_header = "<" + header[2:-1] + ".h>"  #  => 
diff --git a/clang/utils/check_cfc/obj_diff.py 
b/clang/utils/check_cfc/obj_diff.py
index 99ed19e522be2..9d602593a4e1a 100755
--- a/clang/utils/check_cfc/obj_diff.py
+++ b/clang/utils/check_cfc/obj_diff.py
@@ -57,7 +57,7 @@ def first_diff(a, b, fromfile, tofile):
 first_diff_idx = idx
 break
 
-if first_diff_idx == None:
+if first_diff_idx is None:
 # No difference
 return None
 
diff --git a/clang/utils/module-deps-to-rsp.py 
b/clang/utils/module-deps-to-rsp.py
index 6c9f263a786ef..b57a44e5c8780 100755
--- a/clang/utils/module-deps-to-rsp.py
+++ b/clang/utils/module-deps-to-rsp.py
@@ -74,7 +74,7 @@ def main():
 
 if args.module_name:
 cmd = findModule(args.module_name, full_deps)["command-line"]
-elif args.tu_index != None:
+elif args.tu_index is not None:
 tu = full_deps.translation_units[args.tu_index]
 cmd = tu["commands"][args.tu_cmd_index]["command-line"]
 

___
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 modernize-use-cpp-style-comments check (PR #99713)

2024-07-20 Thread Carlos Galvez via cfe-commits

https://github.com/carlosgalvezp requested changes to this pull request.

Good check idea! A couple of comments:

- This is not really a "modernize"check. Both styles are equally valid and it's 
a matter of taste. Modernize is typically for checks that bump from one 
standard to a newer one.

- Instead I think this check fits better in "readability".

- I think we can take the opportunity and make the check scope slightly more 
general, so that it enforces ether C style comments or C++ style comments. So 
the check could be called "readability-comment-style". Right now you can 
support only C->C++ conversion but can be extended in the future to do the 
opposite.

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


[libclc] libclc: increase fp16 support (PR #98149)

2024-07-20 Thread Michał Górny via cfe-commits

mgorny wrote:

This change seems to have caused test regression. This is Gentoo Linux amd64, 
tried LLVM 72d8c2737bb557af9d0c735b9fa30b1b03485627 and 18.1.8.

To reproduce, I've done:

```
cmake -G Ninja "${llvm_project}"/libclc 
-DLIBCLC_TARGETS_TO_BUILD="spirv-mesa3d-;spirv64-mesa3d-;r600--;amdgcn--;amdgcn-mesa-mesa3d;amdgcn--amdhsa"
ninja
ninja test
```

The result:

```
[0/1] Running tests...
Test project /home/mgorny/git/llvm-project/libclc/build
Start 1: external-calls-tahiti-amdgcn--.bc
1/7 Test #1: external-calls-tahiti-amdgcn--.bc .***Failed5.46 
sec
Start 2: external-calls-amdgcn--amdhsa.bc
2/7 Test #2: external-calls-amdgcn--amdhsa.bc ..***Failed5.54 
sec
Start 3: external-calls-tahiti-amdgcn-mesa-mesa3d.bc
3/7 Test #3: external-calls-tahiti-amdgcn-mesa-mesa3d.bc ...***Failed5.43 
sec
Start 4: external-calls-cedar-r600--.bc
4/7 Test #4: external-calls-cedar-r600--.bc    Passed2.05 
sec
Start 5: external-calls-cypress-r600--.bc
5/7 Test #5: external-calls-cypress-r600--.bc ..   Passed2.07 
sec
Start 6: external-calls-barts-r600--.bc
6/7 Test #6: external-calls-barts-r600--.bc    Passed2.03 
sec
Start 7: external-calls-cayman-r600--.bc
7/7 Test #7: external-calls-cayman-r600--.bc ...   Passed2.07 
sec

57% tests passed, 3 tests failed out of 7

Total Test time (real) =  24.66 sec

The following tests FAILED:
  1 - external-calls-tahiti-amdgcn--.bc (Failed)
  2 - external-calls-amdgcn--amdhsa.bc (Failed)
  3 - external-calls-tahiti-amdgcn-mesa-mesa3d.bc (Failed)
Errors while running CTest
Output from these tests are in: 
/home/mgorny/git/llvm-project/libclc/build/Testing/Temporary/LastTest.log
Use "--rerun-failed --output-on-failure" to re-run the failed cases verbosely.
FAILED: CMakeFiles/test.util 
cd /home/mgorny/git/llvm-project/libclc/build && /usr/bin/ctest 
--force-new-ctest-process
ninja: build stopped: subcommand failed.
```

LastTest.log: 
[LastTest.log](https://github.com/user-attachments/files/16320006/LastTest.log)

If I go back to 6838c7afb2d2fa5eb642a4b5922ae55d97f7b344, they all pass.

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


[clang] 54de554 - [Clang] Fix C library wrappers for offloading (#99716)

2024-07-20 Thread via cfe-commits

Author: Joseph Huber
Date: 2024-07-20T07:19:04-05:00
New Revision: 54de554ab8654c7a1f39199c1a491bc80edbba53

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

LOG: [Clang] Fix C library wrappers for offloading (#99716)

Summary:
This block of code wraps around the standard C library includes.
However, the order C library includes are presented is actually
important. If they are visible before the `libc++` headers then it will
cause errors. This patch simply moves the logic to just before it is
normally done. A more optimal solution would be to put this in the
toolchain, however doing it correctly would require knowing the
offloading kind and that would require rewriting the function signature
in all 30 or so ToolChains.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/gpu-libc-headers.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index c9f0fe0a3d60f..71cdaa10416f4 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1077,33 +1077,6 @@ void Clang::AddPreprocessingOptions(Compilation &C, 
const JobAction &JA,
   if (JA.isOffloading(Action::OFK_HIP))
 getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
 
-  // If we are compiling for a GPU target we want to override the system 
headers
-  // with ones created by the 'libc' project if present.
-  if (!Args.hasArg(options::OPT_nostdinc) &&
-  !Args.hasArg(options::OPT_nogpuinc) &&
-  !Args.hasArg(options::OPT_nobuiltininc)) {
-// Without an offloading language we will include these headers directly.
-// Offloading languages will instead only use the declarations stored in
-// the resource directory at clang/lib/Headers/llvm_libc_wrappers.
-if ((getToolChain().getTriple().isNVPTX() ||
- getToolChain().getTriple().isAMDGCN()) &&
-C.getActiveOffloadKinds() == Action::OFK_None) {
-  SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
-  llvm::sys::path::append(P, "include");
-  llvm::sys::path::append(P, getToolChain().getTripleString());
-  CmdArgs.push_back("-internal-isystem");
-  CmdArgs.push_back(Args.MakeArgString(P));
-} else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
-  // TODO: CUDA / HIP include their own headers for some common functions
-  // implemented here. We'll need to clean those up so they do not 
conflict.
-  SmallString<128> P(D.ResourceDir);
-  llvm::sys::path::append(P, "include");
-  llvm::sys::path::append(P, "llvm_libc_wrappers");
-  CmdArgs.push_back("-internal-isystem");
-  CmdArgs.push_back(Args.MakeArgString(P));
-}
-  }
-
   // If we are offloading to a target via OpenMP we need to include the
   // openmp_wrappers folder which contains alternative system headers.
   if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
@@ -1276,6 +1249,35 @@ void Clang::AddPreprocessingOptions(Compilation &C, 
const JobAction &JA,
 });
   }
 
+  // If we are compiling for a GPU target we want to override the system 
headers
+  // with ones created by the 'libc' project if present.
+  // TODO: This should be moved to `AddClangSystemIncludeArgs` by passing the
+  //   OffloadKind as an argument.
+  if (!Args.hasArg(options::OPT_nostdinc) &&
+  !Args.hasArg(options::OPT_nogpuinc) &&
+  !Args.hasArg(options::OPT_nobuiltininc)) {
+// Without an offloading language we will include these headers directly.
+// Offloading languages will instead only use the declarations stored in
+// the resource directory at clang/lib/Headers/llvm_libc_wrappers.
+if ((getToolChain().getTriple().isNVPTX() ||
+ getToolChain().getTriple().isAMDGCN()) &&
+C.getActiveOffloadKinds() == Action::OFK_None) {
+  SmallString<128> P(llvm::sys::path::parent_path(D.Dir));
+  llvm::sys::path::append(P, "include");
+  llvm::sys::path::append(P, getToolChain().getTripleString());
+  CmdArgs.push_back("-internal-isystem");
+  CmdArgs.push_back(Args.MakeArgString(P));
+} else if (C.getActiveOffloadKinds() == Action::OFK_OpenMP) {
+  // TODO: CUDA / HIP include their own headers for some common functions
+  // implemented here. We'll need to clean those up so they do not 
conflict.
+  SmallString<128> P(D.ResourceDir);
+  llvm::sys::path::append(P, "include");
+  llvm::sys::path::append(P, "llvm_libc_wrappers");
+  CmdArgs.push_back("-internal-isystem");
+  CmdArgs.push_back(Args.MakeArgString(P));
+}
+  }
+
   // Add system include arguments for all targets but IAMCU.
   if (!IsIAMCU)
 forAllAssociatedToolChains(C, JA, getToolChain(),

diff  --git a/clang/test/Driver/gpu-libc-headers.c 
b/clang/test/Driver/gp

[clang] [Clang] Fix C library wrappers for offloading (PR #99716)

2024-07-20 Thread Joseph Huber via cfe-commits

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


[clang] [llvm] Reapply "Add source file name for template instantiations in -ftime-trace" (PR #99757)

2024-07-20 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 created https://github.com/llvm/llvm-project/pull/99757

Reverts https://github.com/llvm/llvm-project/pull/99731

Remove accidentally added temporary file.
Also fix uninitialized read of line number.

>From 2c43d8b557192df6999437485cdbdc2e030f4fe5 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Sat, 20 Jul 2024 06:11:40 +
Subject: [PATCH 1/2] Reapply "Reapply "Add source file name for template
 instantiations in -ftime-trace"" (#99731)

This reverts commit abaf13ad589d72b356a8788a5095f869d9d038d0.
---
 a-abfdec1d.o.tmp  |   0
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Driver/Options.td |   4 +
 .../include/clang/Frontend/FrontendOptions.h  |   8 +-
 clang/lib/Driver/ToolChains/Clang.cpp |   1 +
 clang/lib/Sema/SemaTemplateInstantiate.cpp|  11 +-
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  11 +-
 clang/test/Driver/ftime-trace-sections.cpp|   2 +-
 clang/test/Driver/ftime-trace.cpp |  39 +++---
 clang/tools/driver/cc1_main.cpp   |   3 +-
 clang/unittests/Support/TimeProfilerTest.cpp  | 123 ++
 llvm/include/llvm/Support/TimeProfiler.h  |  23 +++-
 llvm/lib/Support/TimeProfiler.cpp |  61 +++--
 13 files changed, 225 insertions(+), 64 deletions(-)
 create mode 100644 a-abfdec1d.o.tmp

diff --git a/a-abfdec1d.o.tmp b/a-abfdec1d.o.tmp
new file mode 100644
index 0..e69de29bb2d1d
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa91663260755..7ac6ed934290d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -750,6 +750,9 @@ Improvements to Clang's time-trace
 - Clang now specifies that using ``auto`` in a lambda parameter is a C++14 
extension when
   appropriate. (`#46059: 
`_).
 
+- Clang now adds source file infomation for template instantiations as 
``event["args"]["filename"]``. This
+  added behind an option ``-ftime-trace-verbose``. This is expected to 
increase the size of trace by 2-3 times.
+
 Improvements to Coverage Mapping
 
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 8707e71f2a319..9c6cebd77ff0a 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3998,6 +3998,10 @@ def ftime_trace_granularity_EQ : Joined<["-"], 
"ftime-trace-granularity=">, Grou
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_verbose : Joined<["-"], "ftime-trace-verbose">, Group,
+  HelpText<"Make time trace capture verbose event details (e.g. source 
filenames). This can increase the size of the output by 2-3 times">,
+  Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
+  MarshallingInfoFlag>;
 def ftime_trace_EQ : Joined<["-"], "ftime-trace=">, Group,
   HelpText<"Similar to -ftime-trace. Specify the JSON file or a directory 
which will contain the JSON file">,
   Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
diff --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 5e5034fe01eb5..8241925c98476 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -580,6 +580,11 @@ class FrontendOptions {
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Make time trace capture verbose event details (e.g. source filenames).
+  /// This can increase the size of the output by 2-3 times.
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned TimeTraceVerbose : 1;
+
   /// Path which stores the output files for -ftime-trace
   std::string TimeTracePath;
 
@@ -601,7 +606,8 @@ class FrontendOptions {
 EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false),
 EmitSymbolGraphSymbolLabelsForTesting(false),
 EmitPrettySymbolGraphs(false), GenReducedBMI(false),
-UseClangIRPipeline(false), TimeTraceGranularity(500) {}
+UseClangIRPipeline(false), TimeTraceGranularity(500),
+TimeTraceVerbose(false) {}
 
   /// getInputKindForExtension - Return the appropriate input kind for a file
   /// extension. For example, "c" would return Language::C.
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index c9f0fe0a3d60f..f7b987bf810c1 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6757,6 +6757,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   if (const char *Name = C.getTimeTraceFile(&JA)) {
 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+Args.

[clang] [llvm] Reapply "Add source file name for template instantiations in -ftime-trace" (PR #99757)

2024-07-20 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-driver

Author: Utkarsh Saxena (usx95)


Changes

Reverts https://github.com/llvm/llvm-project/pull/99731

Remove accidentally added temporary file.
Also fix uninitialized read of line number.

---

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


12 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/include/clang/Driver/Options.td (+4) 
- (modified) clang/include/clang/Frontend/FrontendOptions.h (+7-1) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+1) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+8-3) 
- (modified) clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (+8-3) 
- (modified) clang/test/Driver/ftime-trace-sections.cpp (+1-1) 
- (modified) clang/test/Driver/ftime-trace.cpp (+20-19) 
- (modified) clang/tools/driver/cc1_main.cpp (+2-1) 
- (modified) clang/unittests/Support/TimeProfilerTest.cpp (+96-27) 
- (modified) llvm/include/llvm/Support/TimeProfiler.h (+22-1) 
- (modified) llvm/lib/Support/TimeProfiler.cpp (+53-8) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa91663260755..7ac6ed934290d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -750,6 +750,9 @@ Improvements to Clang's time-trace
 - Clang now specifies that using ``auto`` in a lambda parameter is a C++14 
extension when
   appropriate. (`#46059: 
`_).
 
+- Clang now adds source file infomation for template instantiations as 
``event["args"]["filename"]``. This
+  added behind an option ``-ftime-trace-verbose``. This is expected to 
increase the size of trace by 2-3 times.
+
 Improvements to Coverage Mapping
 
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 8707e71f2a319..9c6cebd77ff0a 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3998,6 +3998,10 @@ def ftime_trace_granularity_EQ : Joined<["-"], 
"ftime-trace-granularity=">, Grou
   HelpText<"Minimum time granularity (in microseconds) traced by time 
profiler">,
   Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
   MarshallingInfoInt, "500u">;
+def ftime_trace_verbose : Joined<["-"], "ftime-trace-verbose">, Group,
+  HelpText<"Make time trace capture verbose event details (e.g. source 
filenames). This can increase the size of the output by 2-3 times">,
+  Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
+  MarshallingInfoFlag>;
 def ftime_trace_EQ : Joined<["-"], "ftime-trace=">, Group,
   HelpText<"Similar to -ftime-trace. Specify the JSON file or a directory 
which will contain the JSON file">,
   Visibility<[ClangOption, CC1Option, CLOption, DXCOption]>,
diff --git a/clang/include/clang/Frontend/FrontendOptions.h 
b/clang/include/clang/Frontend/FrontendOptions.h
index 5e5034fe01eb5..8241925c98476 100644
--- a/clang/include/clang/Frontend/FrontendOptions.h
+++ b/clang/include/clang/Frontend/FrontendOptions.h
@@ -580,6 +580,11 @@ class FrontendOptions {
   /// Minimum time granularity (in microseconds) traced by time profiler.
   unsigned TimeTraceGranularity;
 
+  /// Make time trace capture verbose event details (e.g. source filenames).
+  /// This can increase the size of the output by 2-3 times.
+  LLVM_PREFERRED_TYPE(bool)
+  unsigned TimeTraceVerbose : 1;
+
   /// Path which stores the output files for -ftime-trace
   std::string TimeTracePath;
 
@@ -601,7 +606,8 @@ class FrontendOptions {
 EmitSymbolGraph(false), EmitExtensionSymbolGraphs(false),
 EmitSymbolGraphSymbolLabelsForTesting(false),
 EmitPrettySymbolGraphs(false), GenReducedBMI(false),
-UseClangIRPipeline(false), TimeTraceGranularity(500) {}
+UseClangIRPipeline(false), TimeTraceGranularity(500),
+TimeTraceVerbose(false) {}
 
   /// getInputKindForExtension - Return the appropriate input kind for a file
   /// extension. For example, "c" would return Language::C.
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index c9f0fe0a3d60f..f7b987bf810c1 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -6757,6 +6757,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction 
&JA,
   if (const char *Name = C.getTimeTraceFile(&JA)) {
 CmdArgs.push_back(Args.MakeArgString("-ftime-trace=" + Twine(Name)));
 Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_granularity_EQ);
+Args.AddLastArg(CmdArgs, options::OPT_ftime_trace_verbose);
   }
 
   if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index a7bc6749c5852..725b62db5e80a 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/

[clang] [Clang] Implement P3034R1 Module Declarations Shouldn’t be Macros (PR #90574)

2024-07-20 Thread via cfe-commits

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


[clang] [Clang] Implement P3034R1 Module Declarations Shouldn’t be Macros (PR #90574)

2024-07-20 Thread via cfe-commits

yronglin wrote:

I landed this PR and I'd be happy to follow up if you have any concerns.

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


[clang] [llvm] [RISCV][FMV] Support target_clones (PR #85786)

2024-07-20 Thread Piyou Chen via cfe-commits


@@ -2854,10 +2854,121 @@ void CodeGenFunction::EmitMultiVersionResolver(
   case llvm::Triple::aarch64:
 EmitAArch64MultiVersionResolver(Resolver, Options);
 return;
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64:
+EmitRISCVMultiVersionResolver(Resolver, Options);
+return;
 
   default:
-assert(false && "Only implemented for x86 and AArch64 targets");
+assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
+  }
+}
+
+void CodeGenFunction::EmitRISCVMultiVersionResolver(
+llvm::Function *Resolver, ArrayRef Options) {
+
+  if (getContext().getTargetInfo().getTriple().getOS() !=
+  llvm::Triple::OSType::Linux) {
+CGM.getDiags().Report(diag::err_os_unsupport_riscv_target_clones);
+return;
+  }
+
+  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
+  Builder.SetInsertPoint(CurBlock);
+  EmitRISCVCpuInit();
+
+  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
+  bool HasDefault = false;
+  unsigned DefaultIndex = 0;
+  // Check the each candidate function.
+  for (unsigned Index = 0; Index < Options.size(); Index++) {

BeMg wrote:

In other target, it sort the order base on target-defined priority score for 
all cpu/extension. 

Take Aarch64 as example, it define a table like:

```
// `llvm/lib/Target/AArch64/AArch64FMV.td`
// The last one  is score that using to sorting.
def : FMVExtension<"aes", "FEAT_AES", "+fp-armv8,+neon", 150>;
def : FMVExtension<"bf16", "FEAT_BF16", "+bf16", 280>;
def : FMVExtension<"bti", "FEAT_BTI", "+bti", 510>;
def : FMVExtension<"crc", "FEAT_CRC", "+crc", 110>;
...
```

And sort it before going to emit the resolver.

```
...
llvm::stable_sort(
Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
   const CodeGenFunction::MultiVersionResolverOption &RHS) {
  return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
});
...
static unsigned
TargetMVPriority(const TargetInfo &TI,
 const CodeGenFunction::MultiVersionResolverOption &RO) {
  unsigned Priority = 0;
  unsigned NumFeatures = 0;
  for (StringRef Feat : RO.Conditions.Features) {
Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
NumFeatures++;
  }

  if (!RO.Conditions.Architecture.empty())
Priority = std::max(
Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));

  Priority += TI.multiVersionFeatureCost() * NumFeatures;

  return Priority;
}

```



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


[clang] [llvm] [RISCV][FMV] Support target_clones (PR #85786)

2024-07-20 Thread Piyou Chen via cfe-commits


@@ -2854,10 +2854,121 @@ void CodeGenFunction::EmitMultiVersionResolver(
   case llvm::Triple::aarch64:
 EmitAArch64MultiVersionResolver(Resolver, Options);
 return;
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64:
+EmitRISCVMultiVersionResolver(Resolver, Options);
+return;
 
   default:
-assert(false && "Only implemented for x86 and AArch64 targets");
+assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
+  }
+}
+
+void CodeGenFunction::EmitRISCVMultiVersionResolver(
+llvm::Function *Resolver, ArrayRef Options) {
+
+  if (getContext().getTargetInfo().getTriple().getOS() !=
+  llvm::Triple::OSType::Linux) {
+CGM.getDiags().Report(diag::err_os_unsupport_riscv_target_clones);
+return;
+  }
+
+  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
+  Builder.SetInsertPoint(CurBlock);
+  EmitRISCVCpuInit();
+
+  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
+  bool HasDefault = false;
+  unsigned DefaultIndex = 0;
+  // Check the each candidate function.
+  for (unsigned Index = 0; Index < Options.size(); Index++) {

BeMg wrote:

For RISC-V target, I'm not sure that it is possible to define the score for all 
extension combination, then we could sort the order base on it. Or we could 
extend the `target_clones` syntax with `Priority=` to indicate the order 
by user. 

```
__attribute__((target_clones("default", "arch=+zba;Priority=1", 
"arch=+zba,+zbb;Priority=2"))) int bar() {  
return 1;
}
```

And Yes, It will third version (+zba,+zbb) will be dead in current 
implementation. It will always get into +zba version or default.

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


[clang] [llvm] [RISCV][FMV] Support target_clones (PR #85786)

2024-07-20 Thread Piyou Chen via cfe-commits

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


[clang] 56a9f7c - [clang][Interp] Pass ASTContext to toAPValue()

2024-07-20 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-20T15:29:32+02:00
New Revision: 56a9f7ce611ba21f51043d91c965b59e116013f2

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

LOG: [clang][Interp] Pass ASTContext to toAPValue()

Not yet needed, but we need to ASTContext in a later patch when we start
computing proper values for the APValue offset.

Added: 


Modified: 
clang/lib/AST/Interp/Boolean.h
clang/lib/AST/Interp/Disasm.cpp
clang/lib/AST/Interp/EvalEmitter.cpp
clang/lib/AST/Interp/EvaluationResult.cpp
clang/lib/AST/Interp/Floating.h
clang/lib/AST/Interp/FunctionPointer.h
clang/lib/AST/Interp/Integral.h
clang/lib/AST/Interp/IntegralAP.h
clang/lib/AST/Interp/Interp.h
clang/lib/AST/Interp/MemberPointer.cpp
clang/lib/AST/Interp/MemberPointer.h
clang/lib/AST/Interp/Pointer.cpp
clang/lib/AST/Interp/Pointer.h
clang/unittests/AST/Interp/toAPValue.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Boolean.h b/clang/lib/AST/Interp/Boolean.h
index 1bfb26b1b669f..23f7286036764 100644
--- a/clang/lib/AST/Interp/Boolean.h
+++ b/clang/lib/AST/Interp/Boolean.h
@@ -56,7 +56,7 @@ class Boolean final {
   APSInt toAPSInt(unsigned NumBits) const {
 return APSInt(toAPSInt().zextOrTrunc(NumBits), true);
   }
-  APValue toAPValue() const { return APValue(toAPSInt()); }
+  APValue toAPValue(const ASTContext &) const { return APValue(toAPSInt()); }
 
   Boolean toUnsigned() const { return *this; }
 

diff  --git a/clang/lib/AST/Interp/Disasm.cpp b/clang/lib/AST/Interp/Disasm.cpp
index c6c6275593007..867284ecf7f4b 100644
--- a/clang/lib/AST/Interp/Disasm.cpp
+++ b/clang/lib/AST/Interp/Disasm.cpp
@@ -366,9 +366,9 @@ LLVM_DUMP_METHOD void EvaluationResult::dump() const {
 
 OS << "LValue: ";
 if (const auto *P = std::get_if(&Value))
-  P->toAPValue().printPretty(OS, ASTCtx, SourceType);
+  P->toAPValue(ASTCtx).printPretty(OS, ASTCtx, SourceType);
 else if (const auto *FP = std::get_if(&Value)) // Nope
-  FP->toAPValue().printPretty(OS, ASTCtx, SourceType);
+  FP->toAPValue(ASTCtx).printPretty(OS, ASTCtx, SourceType);
 OS << "\n";
 break;
   }

diff  --git a/clang/lib/AST/Interp/EvalEmitter.cpp 
b/clang/lib/AST/Interp/EvalEmitter.cpp
index 221bbfdc542ff..08536536ac3c2 100644
--- a/clang/lib/AST/Interp/EvalEmitter.cpp
+++ b/clang/lib/AST/Interp/EvalEmitter.cpp
@@ -145,7 +145,7 @@ template  bool EvalEmitter::emitRet(const 
SourceInfo &Info) {
 return false;
 
   using T = typename PrimConv::T;
-  EvalResult.setValue(S.Stk.pop().toAPValue());
+  EvalResult.setValue(S.Stk.pop().toAPValue(Ctx.getASTContext()));
   return true;
 }
 
@@ -181,7 +181,7 @@ template <> bool EvalEmitter::emitRet(const 
SourceInfo &Info) {
   return false;
 }
   } else {
-EvalResult.setValue(Ptr.toAPValue());
+EvalResult.setValue(Ptr.toAPValue(Ctx.getASTContext()));
   }
 
   return true;
@@ -285,7 +285,8 @@ void EvalEmitter::updateGlobalTemporaries() {
   APValue *Cached = Temp->getOrCreateValue(true);
 
   if (std::optional T = Ctx.classify(E->getType())) {
-TYPE_SWITCH(*T, { *Cached = Ptr.deref().toAPValue(); });
+TYPE_SWITCH(
+*T, { *Cached = Ptr.deref().toAPValue(Ctx.getASTContext()); });
   } else {
 if (std::optional APV =
 Ptr.toRValue(Ctx, Temp->getTemporaryExpr()->getType()))

diff  --git a/clang/lib/AST/Interp/EvaluationResult.cpp 
b/clang/lib/AST/Interp/EvaluationResult.cpp
index 0bebfd4ad984e..1b255711c7b36 100644
--- a/clang/lib/AST/Interp/EvaluationResult.cpp
+++ b/clang/lib/AST/Interp/EvaluationResult.cpp
@@ -21,9 +21,9 @@ APValue EvaluationResult::toAPValue() const {
   case LValue:
 // Either a pointer or a function pointer.
 if (const auto *P = std::get_if(&Value))
-  return P->toAPValue();
+  return P->toAPValue(Ctx->getASTContext());
 else if (const auto *FP = std::get_if(&Value))
-  return FP->toAPValue();
+  return FP->toAPValue(Ctx->getASTContext());
 else
   llvm_unreachable("Unhandled LValue type");
 break;
@@ -46,7 +46,7 @@ std::optional EvaluationResult::toRValue() const {
   if (const auto *P = std::get_if(&Value))
 return P->toRValue(*Ctx, getSourceType());
   else if (const auto *FP = std::get_if(&Value)) // Nope
-return FP->toAPValue();
+return FP->toAPValue(Ctx->getASTContext());
   llvm_unreachable("Unhandled lvalue kind");
 }
 

diff  --git a/clang/lib/AST/Interp/Floating.h b/clang/lib/AST/Interp/Floating.h
index e4ac76d8509fb..114487821880f 100644
--- a/clang/lib/AST/Interp/Floating.h
+++ b/clang/lib/AST/Interp/Floating.h
@@ -69,7 +69,7 @@ class Floating final {
   APSInt toAPSInt(unsigned NumBits = 0) const {
 return APSInt(F.bitcastToAPInt());
   }
-  APValue toAPValue() const { r

[clang] [llvm] [RISCV][FMV] Support target_clones (PR #85786)

2024-07-20 Thread Piyou Chen via cfe-commits


@@ -2854,10 +2854,121 @@ void CodeGenFunction::EmitMultiVersionResolver(
   case llvm::Triple::aarch64:
 EmitAArch64MultiVersionResolver(Resolver, Options);
 return;
+  case llvm::Triple::riscv32:
+  case llvm::Triple::riscv64:
+EmitRISCVMultiVersionResolver(Resolver, Options);
+return;
 
   default:
-assert(false && "Only implemented for x86 and AArch64 targets");
+assert(false && "Only implemented for x86, AArch64 and RISC-V targets");
+  }
+}
+
+void CodeGenFunction::EmitRISCVMultiVersionResolver(
+llvm::Function *Resolver, ArrayRef Options) {
+
+  if (getContext().getTargetInfo().getTriple().getOS() !=
+  llvm::Triple::OSType::Linux) {
+CGM.getDiags().Report(diag::err_os_unsupport_riscv_target_clones);
+return;
+  }
+
+  llvm::BasicBlock *CurBlock = createBasicBlock("resolver_entry", Resolver);
+  Builder.SetInsertPoint(CurBlock);
+  EmitRISCVCpuInit();
+
+  bool SupportsIFunc = getContext().getTargetInfo().supportsIFunc();
+  bool HasDefault = false;
+  unsigned DefaultIndex = 0;
+  // Check the each candidate function.
+  for (unsigned Index = 0; Index < Options.size(); Index++) {
+
+if (Options[Index].Conditions.Features[0].starts_with("default")) {
+  HasDefault = true;
+  DefaultIndex = Index;
+  continue;
+}
+
+Builder.SetInsertPoint(CurBlock);
+
+std::vector TargetAttrFeats =
+getContext()
+.getTargetInfo()
+.parseTargetAttr(Options[Index].Conditions.Features[0])
+.Features;
+
+if (TargetAttrFeats.empty())
+  continue;
+
+// Two conditions need to be checked for the current version:
+//
+// 1. LengthCondition: The maximum group ID of the required extension
+//does not exceed the runtime object's length.
+//__riscv_feature_bits.length > MAX_USED_GROUPID
+//
+// 2. FeaturesCondition: The bitmask of the required extension has been
+//enabled by the runtime object.
+//(__riscv_feature_bits.features[i] & REQUIRED_BITMASK) ==
+//REQUIRED_BITMASK
+//
+// When both conditions are met, return this version of the function.
+// Otherwise, try the next version.
+//
+// if (LengthConditionVersion1 && FeaturesConditionVersion1)
+// return Version1;
+// else if (LengthConditionVersion2 && FeaturesConditionVersion2)
+// return Version2;
+// else if (LengthConditionVersion3 && FeaturesConditionVersion3)
+// return Version3;
+// ...
+// else
+// return DefaultVersion;
+llvm::SmallVector CurrTargetAttrFeats;
+
+for (auto Feat : TargetAttrFeats)
+  CurrTargetAttrFeats.push_back(StringRef(Feat).substr(1));

BeMg wrote:

Current target_clones syntax only accept the individual extension, so 
`parseTargetAttr` always return extension with `+` sign. 

But it worth to check here again to avoid the very surprising semantics.

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


[clang] [ASTContext] Add a break to nested switch in `encodeTypeForFunctionPointerAuth` (PR #99763)

2024-07-20 Thread Brandon Wu via cfe-commits

https://github.com/4vtomat created 
https://github.com/llvm/llvm-project/pull/99763

This prevent the warning from compiler.


>From faf331e112ddd7ab6633f5fced55cceaef7065e0 Mon Sep 17 00:00:00 2001
From: Brandon Wu 
Date: Sat, 20 Jul 2024 07:27:53 -0700
Subject: [PATCH] [ASTContext] Add a break to nested switch in
 `encodeTypeForFunctionPointerAuth`

This prevent the warning from compiler.
---
 clang/lib/AST/ASTContext.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 90bcbea072e39..9c7818e9dd80e 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -3363,6 +3363,7 @@ static void encodeTypeForFunctionPointerAuth(const 
ASTContext &Ctx,
 #include "clang/Basic/RISCVVTypes.def"
   llvm_unreachable("not yet implemented");
 }
+break;
   }
   case Type::Record: {
 const RecordDecl *RD = T->getAs()->getDecl();

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


[clang] [ASTContext] Add a break to nested switch in `encodeTypeForFunctionPointerAuth` (PR #99763)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Brandon Wu (4vtomat)


Changes

This prevent the warning from compiler.


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


1 Files Affected:

- (modified) clang/lib/AST/ASTContext.cpp (+1) 


``diff
diff --git a/clang/lib/AST/ASTContext.cpp b/clang/lib/AST/ASTContext.cpp
index 90bcbea072e39..9c7818e9dd80e 100644
--- a/clang/lib/AST/ASTContext.cpp
+++ b/clang/lib/AST/ASTContext.cpp
@@ -3363,6 +3363,7 @@ static void encodeTypeForFunctionPointerAuth(const 
ASTContext &Ctx,
 #include "clang/Basic/RISCVVTypes.def"
   llvm_unreachable("not yet implemented");
 }
+break;
   }
   case Type::Record: {
 const RecordDecl *RD = T->getAs()->getDecl();

``




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


[clang] [compiler-rt] [llvm] Remove 3dnow from X86TargetParser. (PR #99352)

2024-07-20 Thread James Y Knight via cfe-commits

https://github.com/jyknight updated 
https://github.com/llvm/llvm-project/pull/99352

>From 70160e033ac94de92fc2cd6289548094cd893498 Mon Sep 17 00:00:00 2001
From: James Y Knight 
Date: Wed, 17 Jul 2024 11:40:38 -0400
Subject: [PATCH 1/5] Remove 3dnow from X86TargetParser.

This should've been part of PR #96246, but was missed.

This addresses the spurious inclusion of (now unsupported) target
features '-3dnow' and '-3dnowa', when disabling mmx.
---
 clang/test/CodeGen/attr-target-x86.c   |  2 +-
 .../llvm/TargetParser/X86TargetParser.def  |  2 --
 llvm/lib/TargetParser/X86TargetParser.cpp  | 18 +++---
 3 files changed, 8 insertions(+), 14 deletions(-)

diff --git a/clang/test/CodeGen/attr-target-x86.c 
b/clang/test/CodeGen/attr-target-x86.c
index 3c2b511157f99..b1ae6678531b9 100644
--- a/clang/test/CodeGen/attr-target-x86.c
+++ b/clang/test/CodeGen/attr-target-x86.c
@@ -64,7 +64,7 @@ void __attribute__((target("avx10.1-512"))) avx10_1_512(void) 
{}
 // CHECK: #4 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-avx,-avx10.1-256,-avx10.1-512,-avx2,-avx512bf16,-avx512bitalg,-avx512bw,-avx512cd,-avx512dq,-avx512f,-avx512fp16,-avx512ifma,-avx512vbmi,-avx512vbmi2,-avx512vl,-avx512vnni,-avx512vp2intersect,-avx512vpopcntdq,-avxifma,-avxneconvert,-avxvnni,-avxvnniint16,-avxvnniint8,-f16c,-fma,-fma4,-sha512,-sm3,-sm4,-sse4.1,-sse4.2,-vaes,-vpclmulqdq,-xop"
 "tune-cpu"="i686"
 // CHECK: #5 = {{.*}}"target-cpu"="ivybridge" 
"target-features"="+avx,+cmov,+crc32,+cx16,+cx8,+f16c,+fsgsbase,+fxsr,+mmx,+pclmul,+popcnt,+rdrnd,+sahf,+sse,+sse2,+sse3,+sse4.1,+sse4.2,+ssse3,+x87,+xsave,+xsaveopt,-aes,-avx10.1-256,-avx10.1-512,-vaes"
 // CHECK-NOT: tune-cpu
-// CHECK: #6 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-3dnow,-3dnowa,-mmx"
+// CHECK: #6 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-mmx"
 // CHECK: #7 = {{.*}}"target-cpu"="lakemont" "target-features"="+cx8,+mmx"
 // CHECK-NOT: tune-cpu
 // CHECK: #8 = {{.*}}"target-cpu"="i686" "target-features"="+cmov,+cx8,+x87" 
"tune-cpu"="sandybridge"
diff --git a/llvm/include/llvm/TargetParser/X86TargetParser.def 
b/llvm/include/llvm/TargetParser/X86TargetParser.def
index 0e4ad873e3639..b078706e5f400 100644
--- a/llvm/include/llvm/TargetParser/X86TargetParser.def
+++ b/llvm/include/llvm/TargetParser/X86TargetParser.def
@@ -175,8 +175,6 @@ X86_FEATURE_COMPAT(AVX512BF16,  "avx512bf16",   
 34)
 X86_FEATURE_COMPAT(AVX512VP2INTERSECT, "avx512vp2intersect", 35)
 // Below Features has some missings comparing to gcc, it's because gcc has some
 // not one-to-one mapped in llvm.
-X86_FEATURE_COMPAT(3DNOW,   "3dnow",  0)
-X86_FEATURE   (3DNOWA,  "3dnowa")
 X86_FEATURE_COMPAT(ADX, "adx",0)
 X86_FEATURE   (64BIT,   "64bit")
 X86_FEATURE_COMPAT(CLDEMOTE,"cldemote",   0)
diff --git a/llvm/lib/TargetParser/X86TargetParser.cpp 
b/llvm/lib/TargetParser/X86TargetParser.cpp
index 141ecb936b708..5ace0045cb0e8 100644
--- a/llvm/lib/TargetParser/X86TargetParser.cpp
+++ b/llvm/lib/TargetParser/X86TargetParser.cpp
@@ -171,14 +171,14 @@ constexpr FeatureBitset FeaturesClearwaterforest =
 
 // Geode Processor.
 constexpr FeatureBitset FeaturesGeode =
-FeatureX87 | FeatureCMPXCHG8B | FeatureMMX | Feature3DNOW | Feature3DNOWA;
+FeatureX87 | FeatureCMPXCHG8B | FeatureMMX;
 
 // K6 processor.
 constexpr FeatureBitset FeaturesK6 = FeatureX87 | FeatureCMPXCHG8B | 
FeatureMMX;
 
 // K7 and K8 architecture processors.
 constexpr FeatureBitset FeaturesAthlon =
-FeatureX87 | FeatureCMPXCHG8B | FeatureMMX | Feature3DNOW | Feature3DNOWA;
+FeatureX87 | FeatureCMPXCHG8B | FeatureMMX;
 constexpr FeatureBitset FeaturesAthlonXP =
 FeaturesAthlon | FeatureFXSR | FeatureSSE;
 constexpr FeatureBitset FeaturesK8 =
@@ -256,8 +256,8 @@ constexpr ProcInfo Processors[] = {
   // i486-generation processors.
   { {"i486"}, CK_i486, ~0U, FeatureX87, '\0', false },
   { {"winchip-c6"}, CK_WinChipC6, ~0U, FeaturesPentiumMMX, '\0', false },
-  { {"winchip2"}, CK_WinChip2, ~0U, FeaturesPentiumMMX | Feature3DNOW, '\0', 
false },
-  { {"c3"}, CK_C3, ~0U, FeaturesPentiumMMX | Feature3DNOW, '\0', false },
+  { {"winchip2"}, CK_WinChip2, ~0U, FeaturesPentiumMMX, '\0', false },
+  { {"c3"}, CK_C3, ~0U, FeaturesPentiumMMX, '\0', false },
   // i586-generation processors, P5 microarchitecture based.
   { {"i586"}, CK_i586, ~0U, FeatureX87 | FeatureCMPXCHG8B, '\0', false },
   { {"pentium"}, CK_Pentium, ~0U, FeatureX87 | FeatureCMPXCHG8B, 'B', false },
@@ -386,8 +386,8 @@ constexpr ProcInfo Processors[] = {
   { {"lakemont"}, CK_Lakemont, ~0U, FeatureCMPXCHG8B, '\0', false },
   // K6 architecture processors.
   { {"k6"}, CK_K6, ~0U, FeaturesK6, '\0', false },
-  { {"k6-2"}, CK_K6_2, ~0U, FeaturesK6 | Feature3DNOW, '\0', false },
-  { {"k6-3"}, CK_K6_3, ~0U, FeaturesK6 | Feature3DNOW, '\0', false },
+  { {"k6-2"}, CK_K6_2, ~0U, Feat

[clang] [compiler-rt] [llvm] Remove 3DNow! from X86TargetParser. (PR #99352)

2024-07-20 Thread James Y Knight via cfe-commits

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


[clang] [compiler-rt] [llvm] Remove 3DNow! from X86TargetParser. (PR #99352)

2024-07-20 Thread James Y Knight via cfe-commits

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


[clang] [compiler-rt] [llvm] Remove 3DNow! from X86TargetParser. (PR #99352)

2024-07-20 Thread James Y Knight via cfe-commits

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


[clang] 3c6ea7b - Remove 3DNow! from X86TargetParser. (#99352)

2024-07-20 Thread via cfe-commits

Author: James Y Knight
Date: 2024-07-20T11:28:06-04:00
New Revision: 3c6ea7b7168fdb4d4396bcf67ea0d69495a558b8

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

LOG: Remove 3DNow! from X86TargetParser. (#99352)

This addresses the spurious inclusion of (now unsupported) target
features '-3dnow' and '-3dnowa' when disabling mmx (when then caused log
output from `clang -mno-mmx`).

It should've been part of PR #96246, but was missed.

Also tweaks the warning in prfchwintrin.h to not recommend the
deprecated mm3dnow.h header.

Added: 


Modified: 
clang/lib/Headers/prfchwintrin.h
clang/test/CodeGen/attr-target-x86.c
compiler-rt/lib/builtins/cpu_model/x86.c
llvm/include/llvm/TargetParser/X86TargetParser.def
llvm/lib/TargetParser/X86TargetParser.cpp

Removed: 




diff  --git a/clang/lib/Headers/prfchwintrin.h 
b/clang/lib/Headers/prfchwintrin.h
index 8a13784543c5f..eaea5f3cf8feb 100644
--- a/clang/lib/Headers/prfchwintrin.h
+++ b/clang/lib/Headers/prfchwintrin.h
@@ -8,7 +8,7 @@
  */
 
 #if !defined(__X86INTRIN_H) && !defined(_MM3DNOW_H_INCLUDED)
-#error "Never use  directly; include  or 
 instead."
+#error "Never use  directly; include  instead."
 #endif
 
 #ifndef __PRFCHWINTRIN_H

diff  --git a/clang/test/CodeGen/attr-target-x86.c 
b/clang/test/CodeGen/attr-target-x86.c
index 3c2b511157f99..b1ae6678531b9 100644
--- a/clang/test/CodeGen/attr-target-x86.c
+++ b/clang/test/CodeGen/attr-target-x86.c
@@ -64,7 +64,7 @@ void __attribute__((target("avx10.1-512"))) avx10_1_512(void) 
{}
 // CHECK: #4 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-avx,-avx10.1-256,-avx10.1-512,-avx2,-avx512bf16,-avx512bitalg,-avx512bw,-avx512cd,-avx512dq,-avx512f,-avx512fp16,-avx512ifma,-avx512vbmi,-avx512vbmi2,-avx512vl,-avx512vnni,-avx512vp2intersect,-avx512vpopcntdq,-avxifma,-avxneconvert,-avxvnni,-avxvnniint16,-avxvnniint8,-f16c,-fma,-fma4,-sha512,-sm3,-sm4,-sse4.1,-sse4.2,-vaes,-vpclmulqdq,-xop"
 "tune-cpu"="i686"
 // CHECK: #5 = {{.*}}"target-cpu"="ivybridge" 
"target-features"="+avx,+cmov,+crc32,+cx16,+cx8,+f16c,+fsgsbase,+fxsr,+mmx,+pclmul,+popcnt,+rdrnd,+sahf,+sse,+sse2,+sse3,+sse4.1,+sse4.2,+ssse3,+x87,+xsave,+xsaveopt,-aes,-avx10.1-256,-avx10.1-512,-vaes"
 // CHECK-NOT: tune-cpu
-// CHECK: #6 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-3dnow,-3dnowa,-mmx"
+// CHECK: #6 = {{.*}}"target-cpu"="i686" 
"target-features"="+cmov,+cx8,+x87,-mmx"
 // CHECK: #7 = {{.*}}"target-cpu"="lakemont" "target-features"="+cx8,+mmx"
 // CHECK-NOT: tune-cpu
 // CHECK: #8 = {{.*}}"target-cpu"="i686" "target-features"="+cmov,+cx8,+x87" 
"tune-cpu"="sandybridge"

diff  --git a/compiler-rt/lib/builtins/cpu_model/x86.c 
b/compiler-rt/lib/builtins/cpu_model/x86.c
index ab2b685e67ef8..867ed97e57bf2 100644
--- a/compiler-rt/lib/builtins/cpu_model/x86.c
+++ b/compiler-rt/lib/builtins/cpu_model/x86.c
@@ -141,7 +141,7 @@ enum ProcessorFeatures {
   FEATURE_AVX512VP2INTERSECT,
   // FIXME: Below Features has some missings comparing to gcc, it's because gcc
   // has some not one-to-one mapped in llvm.
-  FEATURE_3DNOW,
+  // FEATURE_3DNOW,
   // FEATURE_3DNOWP,
   FEATURE_ADX = 40,
   // FEATURE_ABM,

diff  --git a/llvm/include/llvm/TargetParser/X86TargetParser.def 
b/llvm/include/llvm/TargetParser/X86TargetParser.def
index 0e4ad873e3639..92798cbe4b4c1 100644
--- a/llvm/include/llvm/TargetParser/X86TargetParser.def
+++ b/llvm/include/llvm/TargetParser/X86TargetParser.def
@@ -175,8 +175,12 @@ X86_FEATURE_COMPAT(AVX512BF16,  "avx512bf16",  
  34)
 X86_FEATURE_COMPAT(AVX512VP2INTERSECT, "avx512vp2intersect", 35)
 // Below Features has some missings comparing to gcc, it's because gcc has some
 // not one-to-one mapped in llvm.
-X86_FEATURE_COMPAT(3DNOW,   "3dnow",  0)
-X86_FEATURE   (3DNOWA,  "3dnowa")
+
+// FIXME: dummy features were added to keep the numeric values of later 
features
+// stable. Since the values need to be ABI stable, they should be changed to
+// have explicitly assigned values, and then these dummy features removed.
+X86_FEATURE   (DUMMYFEATURE1,   "__dummyfeature1")
+X86_FEATURE   (DUMMYFEATURE2,   "__dummyfeature2")
 X86_FEATURE_COMPAT(ADX, "adx",0)
 X86_FEATURE   (64BIT,   "64bit")
 X86_FEATURE_COMPAT(CLDEMOTE,"cldemote",   0)

diff  --git a/llvm/lib/TargetParser/X86TargetParser.cpp 
b/llvm/lib/TargetParser/X86TargetParser.cpp
index 141ecb936b708..dcf9130052ac1 100644
--- a/llvm/lib/TargetParser/X86TargetParser.cpp
+++ b/llvm/lib/TargetParser/X86TargetParser.cpp
@@ -171,14 +171,14 @@ constexpr FeatureBitset FeaturesClearwaterforest =
 
 // Geode Processor.
 constexpr FeatureBitset FeaturesGeode =
-FeatureX87 | FeatureCMPXCHG8B | Featu

[clang] [compiler-rt] [llvm] Remove 3DNow! from X86TargetParser. (PR #99352)

2024-07-20 Thread James Y Knight via cfe-commits

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


[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2024-07-20 Thread Yingwei Zheng via cfe-commits

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


[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: Yingwei Zheng (dtcxzyw)


Changes

This patch adds `!dereferenceable/!nonnull/!align` for load from reference to 
improve codegen.


---

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


52 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+31-3) 
- (modified) clang/test/CodeGenCXX/matrix-type-operators.cpp (+10-10) 
- (modified) clang/test/CodeGenCXX/reference-field.cpp (+2-2) 
- (modified) clang/test/OpenMP/amdgcn_target_codegen.cpp (+11-11) 
- (modified) clang/test/OpenMP/cancel_codegen.cpp (+48-48) 
- (modified) clang/test/OpenMP/cancellation_point_codegen.cpp (+38-38) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_simd_firstprivate_codegen.cpp 
(+351-351) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_simd_lastprivate_codegen.cpp 
(+331-331) 
- (modified) clang/test/OpenMP/distribute_parallel_for_simd_private_codegen.cpp 
(+84-84) 
- (modified) clang/test/OpenMP/distribute_simd_firstprivate_codegen.cpp 
(+243-243) 
- (modified) clang/test/OpenMP/distribute_simd_lastprivate_codegen.cpp 
(+239-239) 
- (modified) clang/test/OpenMP/distribute_simd_private_codegen.cpp (+96-96) 
- (modified) clang/test/OpenMP/for_reduction_task_codegen.cpp (+23-23) 
- (modified) clang/test/OpenMP/parallel_for_reduction_task_codegen.cpp (+21-21) 
- (modified) clang/test/OpenMP/parallel_for_simd_codegen.cpp (+1-1) 
- (modified) clang/test/OpenMP/parallel_master_reduction_task_codegen.cpp 
(+21-21) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_codegen.cpp (+161-161) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_firstprivate_codegen.cpp (+105-105) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_lastprivate_codegen.cpp 
(+178-178) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_simd_codegen.cpp 
(+357-357) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_simd_firstprivate_codegen.cpp 
(+118-118) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_simd_lastprivate_codegen.cpp 
(+221-221) 
- (modified) clang/test/OpenMP/parallel_reduction_task_codegen.cpp (+21-21) 
- (modified) clang/test/OpenMP/parallel_sections_reduction_task_codegen.cpp 
(+22-22) 
- (modified) clang/test/OpenMP/sections_reduction_task_codegen.cpp (+24-24) 
- (modified) clang/test/OpenMP/simd_private_taskloop_codegen.cpp (+260-260) 
- (modified) clang/test/OpenMP/target_in_reduction_codegen.cpp (+11-11) 
- (modified) clang/test/OpenMP/target_map_codegen_35.cpp (+1-1) 
- (modified) clang/test/OpenMP/target_parallel_for_reduction_task_codegen.cpp 
(+22-22) 
- (modified) clang/test/OpenMP/target_parallel_reduction_task_codegen.cpp 
(+22-22) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_firstprivate_codegen.cpp
 (+426-426) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_lastprivate_codegen.cpp
 (+326-326) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_private_codegen.cpp 
(+18-18) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_collapse_codegen.cpp (+66-66) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_dist_schedule_codegen.cpp 
(+132-132) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_firstprivate_codegen.cpp 
(+141-141) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_lastprivate_codegen.cpp 
(+208-208) 
- (modified) clang/test/OpenMP/target_teams_distribute_simd_private_codegen.cpp 
(+11-11) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_reduction_codegen.cpp (+62-62) 
- (modified) clang/test/OpenMP/task_codegen.cpp (+1843-1843) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_collapse_codegen.cpp 
(+114-114) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_dist_schedule_codegen.cpp 
(+322-322) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_firstprivate_codegen.cpp 
(+236-236) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_lastprivate_codegen.cpp 
(+325-325) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_private_codegen.cpp 
(+33-33) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_reduction_codegen.cpp 
(+107-107) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_schedule_codegen.cpp 
(+980-980) 
- (modified) clang/test/OpenMP/teams_distribute_simd_firstprivate_codegen.cpp 
(+145-145) 
- (modified) clang/test/OpenMP/teams_distribute_simd_lastprivate_codegen.cpp 
(+229-229) 
- (modified) clang/test/OpenMP/teams_distribute_simd_private_codegen.cpp 
(+24-24) 
- (modified) 
clang/test/utils/update_cc_test_checks/Inputs/resolve-tmp-conflict.cpp.expected 
(+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b0afadfa8d324..c3fa6d1ca7a12 100644
--- a/clang/docs/ReleaseNo

[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Yingwei Zheng (dtcxzyw)


Changes

This patch adds `!dereferenceable/!nonnull/!align` for load from reference to 
improve codegen.


---

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


52 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/CodeGen/CGExpr.cpp (+31-3) 
- (modified) clang/test/CodeGenCXX/matrix-type-operators.cpp (+10-10) 
- (modified) clang/test/CodeGenCXX/reference-field.cpp (+2-2) 
- (modified) clang/test/OpenMP/amdgcn_target_codegen.cpp (+11-11) 
- (modified) clang/test/OpenMP/cancel_codegen.cpp (+48-48) 
- (modified) clang/test/OpenMP/cancellation_point_codegen.cpp (+38-38) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_simd_firstprivate_codegen.cpp 
(+351-351) 
- (modified) 
clang/test/OpenMP/distribute_parallel_for_simd_lastprivate_codegen.cpp 
(+331-331) 
- (modified) clang/test/OpenMP/distribute_parallel_for_simd_private_codegen.cpp 
(+84-84) 
- (modified) clang/test/OpenMP/distribute_simd_firstprivate_codegen.cpp 
(+243-243) 
- (modified) clang/test/OpenMP/distribute_simd_lastprivate_codegen.cpp 
(+239-239) 
- (modified) clang/test/OpenMP/distribute_simd_private_codegen.cpp (+96-96) 
- (modified) clang/test/OpenMP/for_reduction_task_codegen.cpp (+23-23) 
- (modified) clang/test/OpenMP/parallel_for_reduction_task_codegen.cpp (+21-21) 
- (modified) clang/test/OpenMP/parallel_for_simd_codegen.cpp (+1-1) 
- (modified) clang/test/OpenMP/parallel_master_reduction_task_codegen.cpp 
(+21-21) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_codegen.cpp (+161-161) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_firstprivate_codegen.cpp (+105-105) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_lastprivate_codegen.cpp 
(+178-178) 
- (modified) clang/test/OpenMP/parallel_master_taskloop_simd_codegen.cpp 
(+357-357) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_simd_firstprivate_codegen.cpp 
(+118-118) 
- (modified) 
clang/test/OpenMP/parallel_master_taskloop_simd_lastprivate_codegen.cpp 
(+221-221) 
- (modified) clang/test/OpenMP/parallel_reduction_task_codegen.cpp (+21-21) 
- (modified) clang/test/OpenMP/parallel_sections_reduction_task_codegen.cpp 
(+22-22) 
- (modified) clang/test/OpenMP/sections_reduction_task_codegen.cpp (+24-24) 
- (modified) clang/test/OpenMP/simd_private_taskloop_codegen.cpp (+260-260) 
- (modified) clang/test/OpenMP/target_in_reduction_codegen.cpp (+11-11) 
- (modified) clang/test/OpenMP/target_map_codegen_35.cpp (+1-1) 
- (modified) clang/test/OpenMP/target_parallel_for_reduction_task_codegen.cpp 
(+22-22) 
- (modified) clang/test/OpenMP/target_parallel_reduction_task_codegen.cpp 
(+22-22) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_firstprivate_codegen.cpp
 (+426-426) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_lastprivate_codegen.cpp
 (+326-326) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_parallel_for_simd_private_codegen.cpp 
(+18-18) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_collapse_codegen.cpp (+66-66) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_dist_schedule_codegen.cpp 
(+132-132) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_firstprivate_codegen.cpp 
(+141-141) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_lastprivate_codegen.cpp 
(+208-208) 
- (modified) clang/test/OpenMP/target_teams_distribute_simd_private_codegen.cpp 
(+11-11) 
- (modified) 
clang/test/OpenMP/target_teams_distribute_simd_reduction_codegen.cpp (+62-62) 
- (modified) clang/test/OpenMP/task_codegen.cpp (+1843-1843) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_collapse_codegen.cpp 
(+114-114) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_dist_schedule_codegen.cpp 
(+322-322) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_firstprivate_codegen.cpp 
(+236-236) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_lastprivate_codegen.cpp 
(+325-325) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_private_codegen.cpp 
(+33-33) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_reduction_codegen.cpp 
(+107-107) 
- (modified) 
clang/test/OpenMP/teams_distribute_parallel_for_simd_schedule_codegen.cpp 
(+980-980) 
- (modified) clang/test/OpenMP/teams_distribute_simd_firstprivate_codegen.cpp 
(+145-145) 
- (modified) clang/test/OpenMP/teams_distribute_simd_lastprivate_codegen.cpp 
(+229-229) 
- (modified) clang/test/OpenMP/teams_distribute_simd_private_codegen.cpp 
(+24-24) 
- (modified) 
clang/test/utils/update_cc_test_checks/Inputs/resolve-tmp-conflict.cpp.expected 
(+1-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index b0afadfa8d324..c3fa6d1ca7a12 100644
--- a/clang/docs/ReleaseNotes.rst

[clang] [Clang][CodeGen] Add metadata for load from reference (PR #98746)

2024-07-20 Thread Yingwei Zheng via cfe-commits


@@ -1,8 +1,8 @@
 // RUN: %clang_cc1 -emit-llvm -triple %itanium_abi_triple -o - %s -O2 | 
FileCheck %s
 
-// Make sure the call to b() doesn't get optimized out.
+// Make sure the call to b() is eliminated.
 extern struct x {char& x,y;}y;
 int b();  
 int a() { if (!&y.x) b(); }

dtcxzyw wrote:

Clang-tidy complains about this line: https://godbolt.org/z/4e55z7bdv
```
warning: reference cannot be bound to dereferenced null pointer in well-defined 
C++ code; pointer may be assumed to always convert to true 
[-Wundefined-bool-conversion]
```

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


[clang] 5303ca1 - [clang][Interp] Start computing APValue offsets

2024-07-20 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-07-20T17:29:31+02:00
New Revision: 5303ca1496fc5f604f37c071d37821597788e83e

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

LOG: [clang][Interp] Start computing APValue offsets

For array elements, arrays roots and fields.

Added: 
clang/test/AST/Interp/codegen.cpp

Modified: 
clang/lib/AST/Interp/Pointer.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index f7bd76b260584..229007c6d720a 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -16,6 +16,7 @@
 #include "MemberPointer.h"
 #include "PrimType.h"
 #include "Record.h"
+#include "clang/AST/RecordLayout.h"
 
 using namespace clang;
 using namespace clang::interp;
@@ -141,25 +142,38 @@ APValue Pointer::toAPValue(const ASTContext &ASTCtx) 
const {
   else
 llvm_unreachable("Invalid allocation type");
 
-  if (isDummy() || isUnknownSizeArray() || Desc->asExpr())
+  if (isUnknownSizeArray() || Desc->asExpr())
 return APValue(Base, CharUnits::Zero(), Path,
/*IsOnePastEnd=*/isOnePastEnd(), /*IsNullPtr=*/false);
 
-  // TODO: compute the offset into the object.
   CharUnits Offset = CharUnits::Zero();
 
+  auto getFieldOffset = [&](const FieldDecl *FD) -> CharUnits {
+const ASTRecordLayout &Layout = ASTCtx.getASTRecordLayout(FD->getParent());
+unsigned FieldIndex = FD->getFieldIndex();
+return ASTCtx.toCharUnitsFromBits(Layout.getFieldOffset(FieldIndex));
+  };
+
   // Build the path into the object.
   Pointer Ptr = *this;
   while (Ptr.isField() || Ptr.isArrayElement()) {
 if (Ptr.isArrayRoot()) {
   Path.push_back(APValue::LValuePathEntry(
   {Ptr.getFieldDesc()->asDecl(), /*IsVirtual=*/false}));
+
+  if (const auto *FD = dyn_cast(Ptr.getFieldDesc()->asDecl()))
+Offset += getFieldOffset(FD);
+
   Ptr = Ptr.getBase();
 } else if (Ptr.isArrayElement()) {
+  unsigned Index;
   if (Ptr.isOnePastEnd())
-
Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getArray().getNumElems()));
+Index = Ptr.getArray().getNumElems();
   else
-Path.push_back(APValue::LValuePathEntry::ArrayIndex(Ptr.getIndex()));
+Index = Ptr.getIndex();
+
+  Offset += (Index * ASTCtx.getTypeSizeInChars(Ptr.getType()));
+  Path.push_back(APValue::LValuePathEntry::ArrayIndex(Index));
   Ptr = Ptr.getArray();
 } else {
   // TODO: figure out if base is virtual
@@ -170,12 +184,21 @@ APValue Pointer::toAPValue(const ASTContext &ASTCtx) 
const {
   if (const auto *BaseOrMember = Desc->asDecl()) {
 Path.push_back(APValue::LValuePathEntry({BaseOrMember, IsVirtual}));
 Ptr = Ptr.getBase();
+
+if (const auto *FD = dyn_cast(BaseOrMember))
+  Offset += getFieldOffset(FD);
+
 continue;
   }
   llvm_unreachable("Invalid field type");
 }
   }
 
+  // FIXME(perf): We compute the lvalue path above, but we can't supply it
+  // for dummy pointers (that causes crashes later in CheckConstantExpression).
+  if (isDummy())
+Path.clear();
+
   // We assemble the LValuePath starting from the innermost pointer to the
   // outermost one. SO in a.b.c, the first element in Path will refer to
   // the field 'c', while later code expects it to refer to 'a'.

diff  --git a/clang/test/AST/Interp/codegen.cpp 
b/clang/test/AST/Interp/codegen.cpp
new file mode 100644
index 0..8a0d070d19da3
--- /dev/null
+++ b/clang/test/AST/Interp/codegen.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -triple x86_64-linux -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -emit-llvm -o - %s 
-fexperimental-new-constant-interpreter | FileCheck %s
+
+
+int arr[2];
+// CHECK: @pastEnd = constant ptr getelementptr (i8, ptr @arr, i64 8)
+int &pastEnd = arr[2];
+
+// CHECK: @F = constant ptr @arr, align 8
+int &F = arr[0];
+
+struct S {
+  int a;
+  float c[3];
+};
+
+// CHECK: @s = global %struct.S zeroinitializer, align 4
+S s;
+// CHECK: @sp = constant ptr getelementptr (i8, ptr @s, i64 16), align 8
+float &sp = s.c[3];



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


[clang] nonblocking/nonallocating attributes: 2nd pass caller/callee analysis (PR #99656)

2024-07-20 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos updated 
https://github.com/llvm/llvm-project/pull/99656

>From 8c5f85492091df2432701f15f4ec4b6acfe19944 Mon Sep 17 00:00:00 2001
From: Doug Wyatt 
Date: Sun, 5 May 2024 12:36:53 -0700
Subject: [PATCH 1/2] nonblocking/nonallocating attributes: 2nd pass
 caller/callee analysis/verification

---
 clang/include/clang/AST/Type.h|2 +-
 clang/include/clang/Basic/DiagnosticGroups.td |1 +
 .../clang/Basic/DiagnosticSemaKinds.td|   49 +
 clang/include/clang/Sema/Sema.h   |   13 +
 .../include/clang/Serialization/ASTBitCodes.h |4 +
 clang/include/clang/Serialization/ASTReader.h |3 +
 clang/include/clang/Serialization/ASTWriter.h |1 +
 clang/lib/Sema/AnalysisBasedWarnings.cpp  | 1259 +
 clang/lib/Sema/SemaDecl.cpp   |   56 +
 clang/lib/Sema/SemaExpr.cpp   |4 +
 clang/lib/Sema/SemaLambda.cpp |5 +
 clang/lib/Serialization/ASTReader.cpp |   19 +
 clang/lib/Serialization/ASTWriter.cpp |   12 +
 .../Sema/attr-nonblocking-constraints.cpp |  194 +++
 clang/test/Sema/attr-nonblocking-syntax.cpp   |1 +
 .../attr-nonblocking-constraints.mm   |   23 +
 16 files changed, 1645 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/attr-nonblocking-constraints.cpp
 create mode 100644 clang/test/SemaObjCXX/attr-nonblocking-constraints.mm

diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 25defea58c2dc..08141f75de8db 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4699,7 +4699,7 @@ class FunctionEffect {
 
 private:
   LLVM_PREFERRED_TYPE(Kind)
-  unsigned FKind : 3;
+  uint8_t FKind : 3;
 
   // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
   // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e043349..55d9442a939da 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1557,6 +1557,7 @@ def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", 
[UnsafeBufferUsageInCon
 // Warnings and notes related to the function effects system underlying
 // the nonblocking and nonallocating attributes.
 def FunctionEffects : DiagGroup<"function-effects">;
+def PerfConstraintImpliesNoexcept : 
DiagGroup<"perf-constraint-implies-noexcept">;
 
 // Warnings and notes InstallAPI verification.
 def InstallAPIViolation : DiagGroup<"installapi-violation">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d60f32674ca3a..ec02c02d158c8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10928,6 +10928,55 @@ def warn_imp_cast_drops_unaligned : Warning<
   InGroup>;
 
 // Function effects
+def warn_func_effect_allocates : Warning<
+  "'%0' function must not allocate or deallocate memory">,
+  InGroup;
+def note_func_effect_allocates : Note<
+  "function cannot be inferred '%0' because it allocates/deallocates memory">;
+def warn_func_effect_throws_or_catches : Warning<
+  "'%0' function must not throw or catch exceptions">,
+  InGroup;
+def note_func_effect_throws_or_catches : Note<
+  "function cannot be inferred '%0' because it throws or catches exceptions">;
+def warn_func_effect_has_static_local : Warning<
+  "'%0' function must not have static locals">,
+  InGroup;
+def note_func_effect_has_static_local : Note<
+  "function cannot be inferred '%0' because it has a static local">;
+def warn_func_effect_uses_thread_local : Warning<
+  "'%0' function must not use thread-local variables">,
+  InGroup;
+def note_func_effect_uses_thread_local : Note<
+  "function cannot be inferred '%0' because it uses a thread-local variable">;
+def warn_func_effect_calls_objc : Warning<
+  "'%0' function must not access an ObjC method or property">,
+  InGroup;
+def note_func_effect_calls_objc : Note<
+  "function cannot be inferred '%0' because it accesses an ObjC method or 
property">;
+def warn_func_effect_calls_func_without_effect : Warning<
+  "'%0' function must not call non-'%0' function '%1'">,
+  InGroup;
+def warn_func_effect_calls_expr_without_effect : Warning<
+  "'%0' function must not call non-'%0' expression">,
+  InGroup;
+def note_func_effect_calls_func_without_effect : Note<
+  "function cannot be inferred '%0' because it calls non-'%0' function '%1'">;
+def note_func_effect_call_extern : Note<
+  "function cannot be inferred '%0' because it has no definition in this 
translation unit">;
+def note_func_effect_call_disallows_inference : Note<
+  "function does not permit inference of '%0'">;
+def note_func_effect_call_virtual : Note<
+  "virtual method cannot be inferred '%0'">;
+def note_func_effect_call_func_ptr : Note<
+ 

[clang-tools-extra] [clang-tidy][cppcoreguidelines-missing-std-forward] Do not warn when the parameter is used in a `static_cast`. (PR #99477)

2024-07-20 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [clang-tidy][cppcoreguidelines-missing-std-forward] Do not warn when the parameter is used in a `static_cast`. (PR #99477)

2024-07-20 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti commented:

In your documentation, you say that this change allows for the use of a 
`static_cast` to use the parameter as an l-value reference. But your pr title 
and description sound like any reference category is allowed. I think only the 
l-value reference part is intended (it's the only cast that makes sense to 
allow IMO)?

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


[clang-tools-extra] [clang-tidy][cppcoreguidelines-missing-std-forward] Do not warn when the parameter is used in a `static_cast`. (PR #99477)

2024-07-20 Thread Julian Schmidt via cfe-commits


@@ -129,15 +129,19 @@ void MissingStdForwardCheck::registerMatchers(MatchFinder 
*Finder) {
   unless(anyOf(hasAncestor(typeLoc()),
hasAncestor(expr(hasUnevaluatedContext());
 
+  auto StaticCast = cxxStaticCastExpr(
+  hasSourceExpression(declRefExpr(to(equalsBoundNode("param");

5chmidti wrote:

Checkout https://godbolt.org/z/xncofxfdd (and maybe add the examples as test 
cases)
It's possible to match the type of the function parameter to that of the cast 
if it is written, however, not an instantiation dependent type like when using 
type-traits to add the reference.
I think this shortcoming is worth it if we can ensure that the `static_cast` is 
only about being explicit.

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


[clang] nonblocking/nonallocating attributes: 2nd pass caller/callee analysis (PR #99656)

2024-07-20 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 f6e01b9ece1e73f6eda6e1dbff3aa72e917f4007 
95b7a00467423e1a0e320a2fe45811739ce4d61e --extensions h,cpp -- 
clang/test/Sema/attr-nonblocking-constraints.cpp clang/include/clang/AST/Type.h 
clang/include/clang/Sema/Sema.h clang/include/clang/Serialization/ASTBitCodes.h 
clang/include/clang/Serialization/ASTReader.h 
clang/include/clang/Serialization/ASTWriter.h 
clang/lib/Sema/AnalysisBasedWarnings.cpp clang/lib/Sema/SemaDecl.cpp 
clang/lib/Sema/SemaExpr.cpp clang/lib/Sema/SemaLambda.cpp 
clang/lib/Serialization/ASTReader.cpp clang/lib/Serialization/ASTWriter.cpp 
clang/test/Sema/attr-nonblocking-syntax.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index e3259f147e..a42f6af3c7 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4317,7 +4317,8 @@ public:
   // Whether the callee should be ignored in CUDA/HIP/OpenMP host/device check.
   bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee);
 
-  /// Warn and return true if adding a function effect to a set would create a 
conflict.
+  /// Warn and return true if adding a function effect to a set would create a
+  /// conflict.
   bool diagnoseConflictingFunctionEffect(const FunctionEffectsRef &FX,
  const FunctionEffectWithCondition &EC,
  SourceLocation NewAttrLoc);

``




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


[clang] nonblocking/nonallocating attributes: 2nd pass caller/callee analysis (PR #99656)

2024-07-20 Thread Doug Wyatt via cfe-commits

https://github.com/dougsonos updated 
https://github.com/llvm/llvm-project/pull/99656

>From 8c5f85492091df2432701f15f4ec4b6acfe19944 Mon Sep 17 00:00:00 2001
From: Doug Wyatt 
Date: Sun, 5 May 2024 12:36:53 -0700
Subject: [PATCH 1/3] nonblocking/nonallocating attributes: 2nd pass
 caller/callee analysis/verification

---
 clang/include/clang/AST/Type.h|2 +-
 clang/include/clang/Basic/DiagnosticGroups.td |1 +
 .../clang/Basic/DiagnosticSemaKinds.td|   49 +
 clang/include/clang/Sema/Sema.h   |   13 +
 .../include/clang/Serialization/ASTBitCodes.h |4 +
 clang/include/clang/Serialization/ASTReader.h |3 +
 clang/include/clang/Serialization/ASTWriter.h |1 +
 clang/lib/Sema/AnalysisBasedWarnings.cpp  | 1259 +
 clang/lib/Sema/SemaDecl.cpp   |   56 +
 clang/lib/Sema/SemaExpr.cpp   |4 +
 clang/lib/Sema/SemaLambda.cpp |5 +
 clang/lib/Serialization/ASTReader.cpp |   19 +
 clang/lib/Serialization/ASTWriter.cpp |   12 +
 .../Sema/attr-nonblocking-constraints.cpp |  194 +++
 clang/test/Sema/attr-nonblocking-syntax.cpp   |1 +
 .../attr-nonblocking-constraints.mm   |   23 +
 16 files changed, 1645 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/Sema/attr-nonblocking-constraints.cpp
 create mode 100644 clang/test/SemaObjCXX/attr-nonblocking-constraints.mm

diff --git a/clang/include/clang/AST/Type.h b/clang/include/clang/AST/Type.h
index 25defea58c2dc..08141f75de8db 100644
--- a/clang/include/clang/AST/Type.h
+++ b/clang/include/clang/AST/Type.h
@@ -4699,7 +4699,7 @@ class FunctionEffect {
 
 private:
   LLVM_PREFERRED_TYPE(Kind)
-  unsigned FKind : 3;
+  uint8_t FKind : 3;
 
   // Expansion: for hypothetical TCB+types, there could be one Kind for TCB,
   // then ~16(?) bits "SubKind" to map to a specific named TCB. SubKind would
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e043349..55d9442a939da 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1557,6 +1557,7 @@ def UnsafeBufferUsage : DiagGroup<"unsafe-buffer-usage", 
[UnsafeBufferUsageInCon
 // Warnings and notes related to the function effects system underlying
 // the nonblocking and nonallocating attributes.
 def FunctionEffects : DiagGroup<"function-effects">;
+def PerfConstraintImpliesNoexcept : 
DiagGroup<"perf-constraint-implies-noexcept">;
 
 // Warnings and notes InstallAPI verification.
 def InstallAPIViolation : DiagGroup<"installapi-violation">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d60f32674ca3a..ec02c02d158c8 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10928,6 +10928,55 @@ def warn_imp_cast_drops_unaligned : Warning<
   InGroup>;
 
 // Function effects
+def warn_func_effect_allocates : Warning<
+  "'%0' function must not allocate or deallocate memory">,
+  InGroup;
+def note_func_effect_allocates : Note<
+  "function cannot be inferred '%0' because it allocates/deallocates memory">;
+def warn_func_effect_throws_or_catches : Warning<
+  "'%0' function must not throw or catch exceptions">,
+  InGroup;
+def note_func_effect_throws_or_catches : Note<
+  "function cannot be inferred '%0' because it throws or catches exceptions">;
+def warn_func_effect_has_static_local : Warning<
+  "'%0' function must not have static locals">,
+  InGroup;
+def note_func_effect_has_static_local : Note<
+  "function cannot be inferred '%0' because it has a static local">;
+def warn_func_effect_uses_thread_local : Warning<
+  "'%0' function must not use thread-local variables">,
+  InGroup;
+def note_func_effect_uses_thread_local : Note<
+  "function cannot be inferred '%0' because it uses a thread-local variable">;
+def warn_func_effect_calls_objc : Warning<
+  "'%0' function must not access an ObjC method or property">,
+  InGroup;
+def note_func_effect_calls_objc : Note<
+  "function cannot be inferred '%0' because it accesses an ObjC method or 
property">;
+def warn_func_effect_calls_func_without_effect : Warning<
+  "'%0' function must not call non-'%0' function '%1'">,
+  InGroup;
+def warn_func_effect_calls_expr_without_effect : Warning<
+  "'%0' function must not call non-'%0' expression">,
+  InGroup;
+def note_func_effect_calls_func_without_effect : Note<
+  "function cannot be inferred '%0' because it calls non-'%0' function '%1'">;
+def note_func_effect_call_extern : Note<
+  "function cannot be inferred '%0' because it has no definition in this 
translation unit">;
+def note_func_effect_call_disallows_inference : Note<
+  "function does not permit inference of '%0'">;
+def note_func_effect_call_virtual : Note<
+  "virtual method cannot be inferred '%0'">;
+def note_func_effect_call_func_ptr : Note<
+ 

[clang-tools-extra] [clang-tidy] Add modernize-use-cpp-style-comments check (PR #99713)

2024-07-20 Thread Julian Schmidt via cfe-commits


@@ -172,6 +172,11 @@ New checks
   Detects variables and functions that can be marked as static or moved into
   an anonymous namespace to enforce internal linkage.
 
+- New :doc:`modernize-use-cpp-style-comments

5chmidti wrote:

Please sort this release note correctly after 
`modernize-min-max-use-initializer-list`

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


[clang] [llvm] [llvm][clang] Move RewriterBuffer to ADT. (PR #99770)

2024-07-20 Thread Jacques Pienaar via cfe-commits

https://github.com/jpienaar created 
https://github.com/llvm/llvm-project/pull/99770

These classes are not specific to clang and useful for other rewriter tools 
(flagged in previous review).

>From 451a4c61066c4a433bc100ebc511dc6447f83ab0 Mon Sep 17 00:00:00 2001
From: Jacques Pienaar 
Date: Sat, 20 Jul 2024 16:25:14 +
Subject: [PATCH] [llvm][clang] Move RewriterBuffer to ADT.

These classes are not specific to clang and useful for other rewriter tools.
---
 clang/include/clang/Rewrite/Core/DeltaTree.h  |  50 --
 .../include/clang/Rewrite/Core/HTMLRewrite.h  |  11 +-
 .../include/clang/Rewrite/Core/RewriteRope.h  | 223 
 clang/include/clang/Rewrite/Core/Rewriter.h   |  19 +-
 clang/lib/ARCMigrate/ARCMT.cpp|   2 +-
 clang/lib/ARCMigrate/ObjCMT.cpp   |   1 +
 clang/lib/Frontend/Rewrite/FixItRewriter.cpp  |   3 +-
 clang/lib/Frontend/Rewrite/HTMLPrint.cpp  |   2 +
 clang/lib/Frontend/Rewrite/RewriteMacros.cpp  |   4 +-
 .../Frontend/Rewrite/RewriteModernObjC.cpp|   3 +-
 clang/lib/Frontend/Rewrite/RewriteObjC.cpp|   1 +
 clang/lib/Rewrite/CMakeLists.txt  |   2 -
 clang/lib/Rewrite/HTMLRewrite.cpp |   1 +
 clang/lib/Rewrite/Rewriter.cpp| 109 +---
 .../StaticAnalyzer/Core/HTMLDiagnostics.cpp   |   2 +
 clang/lib/Tooling/Core/Replacement.cpp|   2 +-
 clang/unittests/Rewrite/CMakeLists.txt|   1 -
 llvm/include/llvm/ADT/DeltaTree.h |  50 ++
 .../include/llvm/ADT}/RewriteBuffer.h |  40 +-
 llvm/include/llvm/ADT/RewriteRope.h   | 223 
 llvm/lib/Support/CMakeLists.txt   |   3 +
 .../lib/Support}/DeltaTree.cpp| 265 +
 llvm/lib/Support/RewriteBuffer.cpp| 107 
 .../lib/Support}/RewriteRope.cpp  | 507 +-
 llvm/unittests/ADT/CMakeLists.txt |   1 +
 .../unittests/ADT}/RewriteBufferTest.cpp  |   5 +-
 26 files changed, 825 insertions(+), 812 deletions(-)
 delete mode 100644 clang/include/clang/Rewrite/Core/DeltaTree.h
 delete mode 100644 clang/include/clang/Rewrite/Core/RewriteRope.h
 create mode 100644 llvm/include/llvm/ADT/DeltaTree.h
 rename {clang/include/clang/Rewrite/Core => 
llvm/include/llvm/ADT}/RewriteBuffer.h (82%)
 create mode 100644 llvm/include/llvm/ADT/RewriteRope.h
 rename {clang/lib/Rewrite => llvm/lib/Support}/DeltaTree.cpp (68%)
 create mode 100644 llvm/lib/Support/RewriteBuffer.cpp
 rename {clang/lib/Rewrite => llvm/lib/Support}/RewriteRope.cpp (63%)
 rename {clang/unittests/Rewrite => llvm/unittests/ADT}/RewriteBufferTest.cpp 
(96%)

diff --git a/clang/include/clang/Rewrite/Core/DeltaTree.h 
b/clang/include/clang/Rewrite/Core/DeltaTree.h
deleted file mode 100644
index e566c92aaff91..0
--- a/clang/include/clang/Rewrite/Core/DeltaTree.h
+++ /dev/null
@@ -1,50 +0,0 @@
-//===- DeltaTree.h - B-Tree for Rewrite Delta tracking --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file defines the DeltaTree class.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_REWRITE_CORE_DELTATREE_H
-#define LLVM_CLANG_REWRITE_CORE_DELTATREE_H
-
-namespace clang {
-
-  /// DeltaTree - a multiway search tree (BTree) structure with some fancy
-  /// features.  B-Trees are generally more memory and cache efficient than
-  /// binary trees, because they store multiple keys/values in each node.  This
-  /// implements a key/value mapping from index to delta, and allows fast 
lookup
-  /// on index.  However, an added (important) bonus is that it can also
-  /// efficiently tell us the full accumulated delta for a specific file offset
-  /// as well, without traversing the whole tree.
-  class DeltaTree {
-void *Root;// "DeltaTreeNode *"
-
-  public:
-DeltaTree();
-
-// Note: Currently we only support copying when the RHS is empty.
-DeltaTree(const DeltaTree &RHS);
-
-DeltaTree &operator=(const DeltaTree &) = delete;
-~DeltaTree();
-
-/// getDeltaAt - Return the accumulated delta at the specified file offset.
-/// This includes all insertions or delections that occurred *before* the
-/// specified file index.
-int getDeltaAt(unsigned FileIndex) const;
-
-/// AddDelta - When a change is made that shifts around the text buffer,
-/// this method is used to record that info.  It inserts a delta of 'Delta'
-/// into the current DeltaTree at offset FileIndex.
-void AddDelta(unsigned FileIndex, int Delta);
-  };
-
-} // namespace clang
-
-#endif // LLVM_CLANG_REWRITE_CORE_DELTATREE_H
diff --git a/clang/include/clang/Rewrite/Core/HTMLRewrite.h 
b/clang/include/clang/Rewrite/Core/HTMLRewrite.h
in

[clang] [llvm] [llvm][clang] Move RewriterBuffer to ADT. (PR #99770)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Jacques Pienaar (jpienaar)


Changes

These classes are not specific to clang and useful for other rewriter tools 
(flagged in previous review).

---

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


26 Files Affected:

- (removed) clang/include/clang/Rewrite/Core/DeltaTree.h (-50) 
- (modified) clang/include/clang/Rewrite/Core/HTMLRewrite.h (+7-4) 
- (removed) clang/include/clang/Rewrite/Core/RewriteRope.h (-223) 
- (modified) clang/include/clang/Rewrite/Core/Rewriter.h (+10-9) 
- (modified) clang/lib/ARCMigrate/ARCMT.cpp (+1-1) 
- (modified) clang/lib/ARCMigrate/ObjCMT.cpp (+1) 
- (modified) clang/lib/Frontend/Rewrite/FixItRewriter.cpp (+2-1) 
- (modified) clang/lib/Frontend/Rewrite/HTMLPrint.cpp (+2) 
- (modified) clang/lib/Frontend/Rewrite/RewriteMacros.cpp (+3-1) 
- (modified) clang/lib/Frontend/Rewrite/RewriteModernObjC.cpp (+2-1) 
- (modified) clang/lib/Frontend/Rewrite/RewriteObjC.cpp (+1) 
- (modified) clang/lib/Rewrite/CMakeLists.txt (-2) 
- (modified) clang/lib/Rewrite/HTMLRewrite.cpp (+1) 
- (modified) clang/lib/Rewrite/Rewriter.cpp (+7-102) 
- (modified) clang/lib/StaticAnalyzer/Core/HTMLDiagnostics.cpp (+2) 
- (modified) clang/lib/Tooling/Core/Replacement.cpp (+1-1) 
- (modified) clang/unittests/Rewrite/CMakeLists.txt (-1) 
- (added) llvm/include/llvm/ADT/DeltaTree.h (+50) 
- (renamed) llvm/include/llvm/ADT/RewriteBuffer.h (+20-20) 
- (added) llvm/include/llvm/ADT/RewriteRope.h (+223) 
- (modified) llvm/lib/Support/CMakeLists.txt (+3) 
- (renamed) llvm/lib/Support/DeltaTree.cpp (+130-135) 
- (added) llvm/lib/Support/RewriteBuffer.cpp (+107) 
- (renamed) llvm/lib/Support/RewriteRope.cpp (+249-258) 
- (modified) llvm/unittests/ADT/CMakeLists.txt (+1) 
- (renamed) llvm/unittests/ADT/RewriteBufferTest.cpp (+2-3) 


``diff
diff --git a/clang/include/clang/Rewrite/Core/DeltaTree.h 
b/clang/include/clang/Rewrite/Core/DeltaTree.h
deleted file mode 100644
index e566c92aaff91..0
--- a/clang/include/clang/Rewrite/Core/DeltaTree.h
+++ /dev/null
@@ -1,50 +0,0 @@
-//===- DeltaTree.h - B-Tree for Rewrite Delta tracking --*- C++ 
-*-===//
-//
-// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
-// See https://llvm.org/LICENSE.txt for license information.
-// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
-//
-//===--===//
-//
-// This file defines the DeltaTree class.
-//
-//===--===//
-
-#ifndef LLVM_CLANG_REWRITE_CORE_DELTATREE_H
-#define LLVM_CLANG_REWRITE_CORE_DELTATREE_H
-
-namespace clang {
-
-  /// DeltaTree - a multiway search tree (BTree) structure with some fancy
-  /// features.  B-Trees are generally more memory and cache efficient than
-  /// binary trees, because they store multiple keys/values in each node.  This
-  /// implements a key/value mapping from index to delta, and allows fast 
lookup
-  /// on index.  However, an added (important) bonus is that it can also
-  /// efficiently tell us the full accumulated delta for a specific file offset
-  /// as well, without traversing the whole tree.
-  class DeltaTree {
-void *Root;// "DeltaTreeNode *"
-
-  public:
-DeltaTree();
-
-// Note: Currently we only support copying when the RHS is empty.
-DeltaTree(const DeltaTree &RHS);
-
-DeltaTree &operator=(const DeltaTree &) = delete;
-~DeltaTree();
-
-/// getDeltaAt - Return the accumulated delta at the specified file offset.
-/// This includes all insertions or delections that occurred *before* the
-/// specified file index.
-int getDeltaAt(unsigned FileIndex) const;
-
-/// AddDelta - When a change is made that shifts around the text buffer,
-/// this method is used to record that info.  It inserts a delta of 'Delta'
-/// into the current DeltaTree at offset FileIndex.
-void AddDelta(unsigned FileIndex, int Delta);
-  };
-
-} // namespace clang
-
-#endif // LLVM_CLANG_REWRITE_CORE_DELTATREE_H
diff --git a/clang/include/clang/Rewrite/Core/HTMLRewrite.h 
b/clang/include/clang/Rewrite/Core/HTMLRewrite.h
index eecf589632746..9edb514d566b9 100644
--- a/clang/include/clang/Rewrite/Core/HTMLRewrite.h
+++ b/clang/include/clang/Rewrite/Core/HTMLRewrite.h
@@ -17,10 +17,13 @@
 #include "clang/Basic/SourceLocation.h"
 #include 
 
+namespace llvm {
+class RewriteBuffer;
+} // namespace llvm
+
 namespace clang {
 
 class Rewriter;
-class RewriteBuffer;
 class Preprocessor;
 
 namespace html {
@@ -53,9 +56,9 @@ namespace html {
 
   /// HighlightRange - This is the same as the above method, but takes
   /// decomposed file locations.
-  void HighlightRange(RewriteBuffer &RB, unsigned B, unsigned E,
-  const char *BufferStart,
-  const char *StartTag, const char *EndTag);
+  void HighlightR

[clang-tools-extra] [clang-tidy] `bugprone-exception-escape` didn't detech catching of an exception with pointer type by `void *` exception handler (PR #99773)

2024-07-20 Thread Hana Dusíková via cfe-commits

https://github.com/hanickadot created 
https://github.com/llvm/llvm-project/pull/99773

As in title, code which check eligibility of exceptions with pointer types to 
be handled by exception handler of type `void *` disallowed this case. It was 
check:

```c++
if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
  isUnambiguousPublicBaseClass(
  ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
  HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) {
```

but in `isUnambiguousPublicBaseClass` there was code which looked for 
definitions:

```c++
bool isUnambiguousPublicBaseClass(const Type *DerivedType,
  const Type *BaseType) {
  const auto *DerivedClass =
  DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  const auto *BaseClass =
  BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  if (!DerivedClass || !BaseClass)
return false;
```

This code disallowed usage of `void *` type which was correctly detected in 
`isStandardPointerConvertible`.

AFAIK this seems like misinterpretation of specification:

> 14.4 Handling an exception
> a standard [pointer conversion](https://eel.is/c++draft/conv.ptr) not 
> involving conversions to pointers to private or protected or ambiguous classes
(https://eel.is/c++draft/except.handle#3.3.1)

and 

> 7.3.12 Pointer conversions
> ... If B is an inaccessible 
> ([[class.access]](https://eel.is/c++draft/class.access)) or ambiguous 
> ([[class.member.lookup]](https://eel.is/c++draft/class.member.lookup)) base 
> class of D, a program that necessitates this conversion is 
> ill-formed[.](https://eel.is/c++draft/conv.ptr#3.sentence-2) ...
(https://eel.is/c++draft/conv.ptr#3)

14.4 is carving out private, protected, and ambiguous base classes, but they 
are already carved out in 7.3.12 and implemented in 
`isStandardPointerConvertible`



From 3ea4f5d28e3183243f9aa9da1c264e5d70b16563 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Hana=20Dusi=CC=81kova=CC=81?= 
Date: Sat, 20 Jul 2024 20:12:45 +0200
Subject: [PATCH] [clang-tidy] `bugprone-exception-escape` didn't detech
 catching of an exception with pointer type by `void *` exception handler

---
 .../clang-tidy/utils/ExceptionAnalyzer.cpp | 10 +-
 clang-tools-extra/docs/ReleaseNotes.rst|  4 
 .../checkers/bugprone/exception-escape.cpp | 18 ++
 3 files changed, 27 insertions(+), 5 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp 
b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
index 6ae46e2b1262a..9bfb7e2677533 100644
--- a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
@@ -141,7 +141,10 @@ bool isStandardPointerConvertible(QualType From, QualType 
To) {
 if (RD->isCompleteDefinition() &&
 isBaseOf(From->getPointeeType().getTypePtr(),
  To->getPointeeType().getTypePtr())) {
-  return true;
+  // If B is an inaccessible or ambiguous base class of D, a program
+  // that necessitates this conversion is ill-formed
+  return isUnambiguousPublicBaseClass(From->getPointeeType().getTypePtr(),
+  To->getPointeeType().getTypePtr());
 }
   }
 
@@ -375,10 +378,7 @@ bool ExceptionAnalyzer::ExceptionInfo::filterByCatch(
 isPointerOrPointerToMember(ExceptionCanTy->getTypePtr())) {
   // A standard pointer conversion not involving conversions to pointers to
   // private or protected or ambiguous classes ...
-  if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
-  isUnambiguousPublicBaseClass(
-  ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
-  HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) {
+  if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy)) {
 TypesToDelete.push_back(ExceptionTy);
   }
   // A function pointer conversion ...
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a23483e6df6d2..8e8c0cd0cc3d8 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -518,6 +518,10 @@ Changes in existing checks
   usages of ``std::string_view::compare``. Added a `StringLikeClasses` option
   to detect usages of ``compare`` method in custom string-like classes.
 
+- Improved :doc:`exception-escape 
`
+  check to correctly detect exception handler of type `CV void *` as catching 
all 
+  `CV` compatible pointer types.
+
 Removed checks
 ^^
 
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
index f5e74df1621ce..26c443b139629 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
+++ b/clang-tools-ext

[clang-tools-extra] [clang-tidy] `bugprone-exception-escape` didn't detech catching of an exception with pointer type by `void *` exception handler (PR #99773)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




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

Author: Hana Dusíková (hanickadot)


Changes

As in title, code which check eligibility of exceptions with pointer types to 
be handled by exception handler of type `void *` disallowed this case. It was 
check:

```c++
if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
  isUnambiguousPublicBaseClass(
  ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
  HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) 
{
```

but in `isUnambiguousPublicBaseClass` there was code which looked for 
definitions:

```c++
bool isUnambiguousPublicBaseClass(const Type *DerivedType,
  const Type *BaseType) {
  const auto *DerivedClass =
  DerivedType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  const auto *BaseClass =
  BaseType->getCanonicalTypeUnqualified()->getAsCXXRecordDecl();
  if (!DerivedClass || !BaseClass)
return false;
```

This code disallowed usage of `void *` type which was correctly detected in 
`isStandardPointerConvertible`.

AFAIK this seems like misinterpretation of specification:

> 14.4 Handling an exception
> a standard [pointer conversion](https://eel.is/c++draft/conv.ptr) not 
involving conversions to pointers to private or protected or ambiguous classes
(https://eel.is/c++draft/except.handle#3.3.1)

and 

> 7.3.12 Pointer conversions
> ... If B is an inaccessible 
([[class.access]](https://eel.is/c++draft/class.access)) or ambiguous 
([[class.member.lookup]](https://eel.is/c++draft/class.member.lookup)) base 
class of D, a program that necessitates this conversion is 
ill-formed[.](https://eel.is/c++draft/conv.ptr#3.sentence-2) ...
(https://eel.is/c++draft/conv.ptr#3)

14.4 is carving out private, protected, and ambiguous base classes, but they 
are already carved out in 7.3.12 and implemented in 
`isStandardPointerConvertible`



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


3 Files Affected:

- (modified) clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp (+5-5) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp (+18) 


``diff
diff --git a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp 
b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
index 6ae46e2b1262a..9bfb7e2677533 100644
--- a/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
+++ b/clang-tools-extra/clang-tidy/utils/ExceptionAnalyzer.cpp
@@ -141,7 +141,10 @@ bool isStandardPointerConvertible(QualType From, QualType 
To) {
 if (RD->isCompleteDefinition() &&
 isBaseOf(From->getPointeeType().getTypePtr(),
  To->getPointeeType().getTypePtr())) {
-  return true;
+  // If B is an inaccessible or ambiguous base class of D, a program
+  // that necessitates this conversion is ill-formed
+  return isUnambiguousPublicBaseClass(From->getPointeeType().getTypePtr(),
+  To->getPointeeType().getTypePtr());
 }
   }
 
@@ -375,10 +378,7 @@ bool ExceptionAnalyzer::ExceptionInfo::filterByCatch(
 isPointerOrPointerToMember(ExceptionCanTy->getTypePtr())) {
   // A standard pointer conversion not involving conversions to pointers to
   // private or protected or ambiguous classes ...
-  if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy) &&
-  isUnambiguousPublicBaseClass(
-  ExceptionCanTy->getTypePtr()->getPointeeType().getTypePtr(),
-  HandlerCanTy->getTypePtr()->getPointeeType().getTypePtr())) {
+  if (isStandardPointerConvertible(ExceptionCanTy, HandlerCanTy)) {
 TypesToDelete.push_back(ExceptionTy);
   }
   // A function pointer conversion ...
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index a23483e6df6d2..8e8c0cd0cc3d8 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -518,6 +518,10 @@ Changes in existing checks
   usages of ``std::string_view::compare``. Added a `StringLikeClasses` option
   to detect usages of ``compare`` method in custom string-like classes.
 
+- Improved :doc:`exception-escape 
`
+  check to correctly detect exception handler of type `CV void *` as catching 
all 
+  `CV` compatible pointer types.
+
 Removed checks
 ^^
 
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
index f5e74df1621ce..26c443b139629 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/exception-escape.cpp
@@ -756,3 +756,21 @@ struct test_implicit_throw {
 };
 
 }}
+
+void pointer_exception_can_not_escape_with_const_void_handler() noexcept {
+  // CHECK-

[clang-tools-extra] [clang-tidy] `bugprone-exception-escape` didn't detech catching of an exception with pointer type by `void *` exception handler (PR #99773)

2024-07-20 Thread Hana Dusíková via cfe-commits

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


[clang-tools-extra] [clang-tidy] `bugprone-exception-escape` didn't detech catching of an exception with pointer type by `void *` exception handler (PR #99773)

2024-07-20 Thread Hana Dusíková via cfe-commits

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


[clang-tools-extra] [clang-tidy] `bugprone-exception-escape` didn't detech catching of an exception with pointer type by `void *` exception handler (PR #99773)

2024-07-20 Thread Hana Dusíková via cfe-commits

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


RE: cfe-commits Digest, Vol 205, Issue 1750

2024-07-20 Thread via cfe-commits
STOP

  -Original Message-
  From: 
  Sent: Sat, 20 Jul 2024 08:29:50 -0700
  To: 7578703...@txt.att.net
 Subject: =?utf-8?q?cfe-commits_Digest=2C_Vol_205=2C_Issue_1750?=

>Send cfe-commits mailing list submissions to
>   cfe-commits@lists.llvm.org
>
>To subscribe or unsubscribe via the World Wide Web, visit
>   https://lists.llvm.org/cgi-bin/mailman/listin


==
This mobile text message is brought to you by AT&T
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] ce1a874 - [clang-format] Fix a bug in annotating `*` in `#define`s (#99433)

2024-07-20 Thread via cfe-commits

Author: Owen Pan
Date: 2024-07-20T12:22:50-07:00
New Revision: ce1a87437cc143889665c41046107e84cdf6246e

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

LOG: [clang-format] Fix a bug in annotating `*` in `#define`s (#99433)

Fixes #99271.

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/TokenAnnotatorTest.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index b6d6e52ccb8f8..db66911f00f63 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -372,10 +372,6 @@ class AnnotatingParser {
OpeningParen.Previous->is(tok::kw__Generic)) {
   Contexts.back().ContextType = Context::C11GenericSelection;
   Contexts.back().IsExpression = true;
-} else if (Line.InPPDirective &&
-   (!OpeningParen.Previous ||
-OpeningParen.Previous->isNot(tok::identifier))) {
-  Contexts.back().IsExpression = true;
 } else if (Contexts[Contexts.size() - 2].CaretFound) {
   // This is the parameter list of an ObjC block.
   Contexts.back().IsExpression = false;
@@ -388,7 +384,20 @@ class AnnotatingParser {
OpeningParen.Previous->MatchingParen->isOneOf(
TT_ObjCBlockLParen, TT_FunctionTypeLParen)) {
   Contexts.back().IsExpression = false;
-} else if (!Line.MustBeDeclaration && !Line.InPPDirective) {
+} else if (Line.InPPDirective) {
+  auto IsExpr = [&OpeningParen] {
+const auto *Tok = OpeningParen.Previous;
+if (!Tok || Tok->isNot(tok::identifier))
+  return true;
+Tok = Tok->Previous;
+while (Tok && Tok->endsSequence(tok::coloncolon, tok::identifier)) {
+  assert(Tok->Previous);
+  Tok = Tok->Previous->Previous;
+}
+return !Tok || !Tok->Tok.getIdentifierInfo();
+  };
+  Contexts.back().IsExpression = IsExpr();
+} else if (!Line.MustBeDeclaration) {
   bool IsForOrCatch =
   OpeningParen.Previous &&
   OpeningParen.Previous->isOneOf(tok::kw_for, tok::kw_catch);

diff  --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index c5e8aa72cd2cb..f70424c3ee060 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -75,6 +75,26 @@ TEST_F(TokenAnnotatorTest, UnderstandsUsesOfStarAndAmp) {
   EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_TypeDeclarationParen);
   EXPECT_TOKEN(Tokens[11], tok::star, TT_PointerOrReference);
 
+  Tokens = annotate("#define FOO bar(a * b)");
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::star, TT_BinaryOperator);
+
+  Tokens = annotate("#define FOO foo.bar(a & b)");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::amp, TT_BinaryOperator);
+
+  Tokens = annotate("#define FOO foo::bar(a && b)");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[8], tok::ampamp, TT_BinaryOperator);
+
+  Tokens = annotate("#define FOO foo bar(a *b)");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::star, TT_PointerOrReference);
+
+  Tokens = annotate("#define FOO void foo::bar(a &b)");
+  ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[9], tok::amp, TT_PointerOrReference);
+
   Tokens = annotate("void f() {\n"
 "  while (p < a && *p == 'a')\n"
 "p++;\n"



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


[clang] [clang-format] Fix a bug in annotating `*` in `#define`s (PR #99433)

2024-07-20 Thread Owen Pan via cfe-commits

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


[clang] [llvm] [OpenMP] OpenMP 5.1 "assume" directive parsing support (PR #92731)

2024-07-20 Thread Julian Brown via cfe-commits

https://github.com/jtb20 updated https://github.com/llvm/llvm-project/pull/92731

>From f6addc40ef18c3ca28ee79303bace08d30dc9817 Mon Sep 17 00:00:00 2001
From: Julian Brown 
Date: Wed, 1 May 2024 06:35:59 -0500
Subject: [PATCH] [OpenMP] OpenMP 5.1 "assume" directive parsing support

This patch supports parsing of "omp assume" directives.  These are
meant to be hints to a compiler' optimisers: as such, it is legitimate
(if not very useful) to ignore them.  This version of the patch
implements new AST nodes for the "assume" directive and the various
clauses it accepts as arguments, and adds new (C++ module) tests for
serialization/deserialization of said nodes.

Unlike the "omp [begin/end] assumes" directives, "omp assume" is
associated with a compound statement, i.e. it can appear within a
function.  The "holds" assumption could (theoretically) be mapped onto
the existing builtin "__builtin_assume", though the latter applies to a
single point in the program, and the former to a range (i.e. the whole
of the associated compound statement).

The "assume" directive appears to be distinct from the [[omp::assume]]
annotation.

This patch fixes sollve's OpenMP 5.1 "omp assume"-based tests.
---
 clang/include/clang-c/Index.h |   4 +
 clang/include/clang/AST/OpenMPClause.h| 174 ++
 clang/include/clang/AST/RecursiveASTVisitor.h |  35 
 clang/include/clang/AST/StmtOpenMP.h  |  30 +++
 clang/include/clang/Basic/OpenMPKinds.h   |   2 +
 clang/include/clang/Basic/StmtNodes.td|   1 +
 clang/include/clang/Parse/Parser.h|   4 +
 clang/include/clang/Sema/SemaOpenMP.h |  19 ++
 .../include/clang/Serialization/ASTBitCodes.h |   1 +
 clang/lib/AST/OpenMPClause.cpp|  43 +
 clang/lib/AST/StmtOpenMP.cpp  |  17 ++
 clang/lib/AST/StmtPrinter.cpp |   5 +
 clang/lib/AST/StmtProfile.cpp |  18 ++
 clang/lib/Basic/OpenMPKinds.cpp   |   8 +
 clang/lib/CodeGen/CGStmt.cpp  |   3 +
 clang/lib/CodeGen/CGStmtOpenMP.cpp|   7 +-
 clang/lib/CodeGen/CodeGenFunction.h   |   1 +
 clang/lib/Parse/ParseOpenMP.cpp   | 128 +
 clang/lib/Sema/SemaOpenMP.cpp |  72 +++-
 clang/lib/Sema/TreeTransform.h| 127 +
 clang/lib/Serialization/ASTReader.cpp |  50 +
 clang/lib/Serialization/ASTReaderStmt.cpp |  11 ++
 clang/lib/Serialization/ASTWriter.cpp |  28 +++
 clang/lib/Serialization/ASTWriterStmt.cpp |   6 +
 clang/test/OpenMP/assume_lambda.cpp   |  31 
 clang/test/OpenMP/assume_messages.c   |  30 +++
 clang/test/OpenMP/assume_messages_attr.c  |  30 +++
 .../OpenMP/assume_serialize_deserialize.cpp   |  31 
 .../assume_serialize_deserialize_tmpl.cpp |  72 
 clang/test/OpenMP/assume_template.cpp |  42 +
 clang/tools/libclang/CIndex.cpp   |  21 +++
 llvm/include/llvm/Frontend/OpenMP/OMP.td  |  30 +++
 32 files changed, 1079 insertions(+), 2 deletions(-)
 create mode 100644 clang/test/OpenMP/assume_lambda.cpp
 create mode 100644 clang/test/OpenMP/assume_messages.c
 create mode 100644 clang/test/OpenMP/assume_messages_attr.c
 create mode 100644 clang/test/OpenMP/assume_serialize_deserialize.cpp
 create mode 100644 clang/test/OpenMP/assume_serialize_deserialize_tmpl.cpp
 create mode 100644 clang/test/OpenMP/assume_template.cpp

diff --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index 115f5ab090f96..4b4adbfb236e7 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2154,6 +2154,10 @@ enum CXCursorKind {
*/
   CXCursor_OMPInterchangeDirective = 308,
 
+  /** OpenMP assume directive.
+   */
+  CXCursor_OMPAssumeDirective = 309,
+
   /** OpenACC Compute Construct.
*/
   CXCursor_OpenACCComputeConstruct = 320,
diff --git a/clang/include/clang/AST/OpenMPClause.h 
b/clang/include/clang/AST/OpenMPClause.h
index 325a1baa44614..13e3405890ba9 100644
--- a/clang/include/clang/AST/OpenMPClause.h
+++ b/clang/include/clang/AST/OpenMPClause.h
@@ -29,6 +29,7 @@
 #include "llvm/ADT/ArrayRef.h"
 #include "llvm/ADT/MapVector.h"
 #include "llvm/ADT/PointerIntPair.h"
+#include "llvm/ADT/SmallSet.h"
 #include "llvm/ADT/SmallVector.h"
 #include "llvm/ADT/iterator.h"
 #include "llvm/ADT/iterator_range.h"
@@ -2013,6 +2014,179 @@ class OMPMergeableClause : public OMPClause {
   }
 };
 
+/// This represents the 'absent' clause in the '#pragma omp assume'
+/// directive.
+///
+/// \code
+/// #pragma omp assume absent()
+/// \endcode
+/// In this example directive '#pragma omp assume' has an 'absent' clause.
+class OMPAbsentClause final : public OMPNoChildClause {
+  llvm::SmallSet DirectiveKinds;
+
+  /// Location of '('.
+  SourceLocation LParenLoc;
+
+public:
+  /// Build 'absent' clause.
+  ///
+  /// \param StartLoc Starting location of the clause.
+  /// \param EndLoc 

[clang] Add _MM_FROUND_TIES_TO_EVEN to avx512fintrin.h (PR #99691)

2024-07-20 Thread via cfe-commits

hpkfft wrote:

I understand that the details of floating point arithmetic are somewhat of a 
specialized area of computer science.  I suggest that this obligates a greater 
duty to show care and diligence, and so I thank you for not dismissing my 
concerns as too trivial to be worth discussing.

Rounding is necessary when the infinitely precise mathematical result of a 
floating point computation is not representable as a floating point number in 
the specified format (e.g., single precision).   Let's ignore directed rounding 
(`roundTowardPositive`, `roundTowardNegative`, and `roundTowardZero`) for this 
comment.  Often the mathematical result is closer to one particular 
representable floating point number than it is to any other.   Then, this 
result (the nearest floating point number) is returned as the result.   
However, it may happen that the infinitely precise mathematical result is 
exactly half-way between two representable values.   This is a tie.   In this 
case, the IEEE Std 754-2019 rounding attribute `roundTiesToEven` specifies 
that, of the two equidistant representable results, the result returned should 
have a bit pattern ending in 0.

Hardware correctly implements the IEEE rounding attribute  `roundTiesToEven`, 
so it seems best not to innovate in naming the macro.  I would suggest that the 
Intel SDM phrasing `Round to nearest (even)` is less than optimal.  A reader 
might be forgiven for mistakenly thinking that hardware always rounds to an 
even result.  In a macro definition, there is merit in brevity, but not so much 
in a developer manual.  I suggest `Round to nearest with ties rounding to even`.

Note that some few instructions, e.g., `ROUNDPS`, do round to an integer, so 
the existing macro definition `_MM_FROUND_TO_NEAREST_INT` ought not be 
deprecated.

I have written to the GCC mailing list to inquire as to whether they will 
accept this additional macro definition.

Regards,
Paul

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


[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits

https://github.com/memory-thrasher updated 
https://github.com/llvm/llvm-project/pull/97792

>From b3de931c063ed895b3fd040a6ef53f8422fc7741 Mon Sep 17 00:00:00 2001
From: Sidney Kelley 
Date: Thu, 4 Jul 2024 23:03:16 -0700
Subject: [PATCH] Adds support to clang"s windows mangler to handle template
 argument values that are pointers one-past-the-end of a non-array symbol.
 Also improves error messages in other template argument scenarios where clang
 bails.

---
 clang/lib/AST/MicrosoftMangle.cpp | 208 +++---
 .../CodeGen/ms_mangler_templatearg_opte.cpp   |  19 ++
 2 files changed, 96 insertions(+), 131 deletions(-)
 create mode 100644 clang/test/CodeGen/ms_mangler_templatearg_opte.cpp

diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index fac14ce1dce8c..d260ce3af7407 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -337,6 +337,9 @@ class MicrosoftCXXNameMangler {
 
   const bool PointersAre64Bit;
 
+  DiagnosticBuilder Error(SourceLocation, StringRef);
+  DiagnosticBuilder Error(StringRef);
+
 public:
   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
   enum class TplArgKind { ClassNTTP, StructuralValue };
@@ -564,6 +567,23 @@ 
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
   return true;
 }
 
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error, "cannot mangle this %0 %1 %2 %3 %4 yet");
+  return Diags.Report(loc, DiagID) << thingy;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error, "cannot mangle this %0 %1 %2 %3 %4 yet");
+  return Diags.Report(DiagID) << thingy;
+}
+
 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
   const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
@@ -1577,10 +1597,7 @@ void 
MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
   case OO_Spaceship: Out << "?__M"; break;
 
   case OO_Conditional: {
-DiagnosticsEngine &Diags = Context.getDiags();
-unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-  "cannot mangle this conditional operator yet");
-Diags.Report(Loc, DiagID);
+Error(Loc, "conditional operator");
 break;
   }
 
@@ -1672,11 +1689,8 @@ void MicrosoftCXXNameMangler::mangleExpression(
   }
 
   // As bad as this diagnostic is, it's better than crashing.
-  DiagnosticsEngine &Diags = Context.getDiags();
-  unsigned DiagID = Diags.getCustomDiagID(
-  DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
-  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
-<< E->getSourceRange();
+  Error(E->getExprLoc(), "expression type: ")
+  << E->getStmtClassName() << E->getSourceRange();
 }
 
 void MicrosoftCXXNameMangler::mangleTemplateArgs(
@@ -1922,11 +1936,19 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 if (WithScalarType)
   mangleType(T, SourceRange(), QMM_Escape);
 
-// We don't know how to mangle past-the-end pointers yet.
-if (V.isLValueOnePastTheEnd())
-  break;
-
 APValue::LValueBase Base = V.getLValueBase();
+
+// this might not cover every case but did cover issue 97756
+// see test CodeGen/ms_mangler_templatearg_opte
+if (V.isLValueOnePastTheEnd()) {
+  Out << "5E";
+  auto *VD = Base.dyn_cast();
+  if (VD)
+mangle(VD);
+  Out << "@";
+  return;
+}
+
 if (!V.hasLValuePath() || V.getLValuePath().empty()) {
   // Taking the address of a complete object has a special-case mangling.
   if (Base.isNull()) {
@@ -1938,12 +1960,14 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 mangleNumber(V.getLValueOffset().getQuantity());
   } else if (!V.hasLValuePath()) {
 // FIXME: This can only happen as an extension. Invent a mangling.
-break;
+Error("template argument (extension not comaptible with ms mangler)");
+return;
   } else if (auto *VD = Base.dyn_cast()) {
 Out << "E";
 mangle(VD);
   } else {
-break;
+Error("template argument (undeclared base)");
+return;
   }
 } else {
   if (TAK == TplArgKind::ClassNTTP && T->isPointerType())
@@ -1988,8 +2012,10 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 Out << *I;
 
   auto *VD = Base.dyn_cast();
-  if (!VD)
-

[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits


@@ -1938,12 +1946,23 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 mangleNumber(V.getLValueOffset().getQuantity());
   } else if (!V.hasLValuePath()) {
 // FIXME: This can only happen as an extension. Invent a mangling.
-break;
+DiagnosticsEngine &Diags = Context.getDiags();
+unsigned DiagID =
+Diags.getCustomDiagID(DiagnosticsEngine::Error,

memory-thrasher wrote:

Done. I couldn't stand to refactor just one piece of the class so I did all the 
"cannot mange * yet" errors.
@rnk 

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


[clang] nonblocking/nonallocating attributes: 2nd pass caller/callee analysis (PR #99656)

2024-07-20 Thread Doug Wyatt via cfe-commits


@@ -891,6 +898,12 @@ class Sema final : public SemaBase {
SourceLocation NewLoc,
SourceLocation OldLoc);
 
+  /// Potentially add a FunctionDecl or BlockDecl to DeclsWithEffectsToVerify.
+  void maybeAddDeclWithEffects(const Decl *D, const FunctionEffectsRef &FX);

dougsonos wrote:

Thanks, did this, including moving some of the other recent, related additions.

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


[clang] nonblocking/nonallocating attributes: 2nd pass caller/callee analysis (PR #99656)

2024-07-20 Thread Doug Wyatt via cfe-commits

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


[clang] [libc] [llvm] [OpenMP][libc] Remove special handling for OpenMP printf (PR #98940)

2024-07-20 Thread Jan Patrick Lehr via cfe-commits

jplehr wrote:

I was mostly curious if we have some coverage that would ideally break if the 
implementation breaks.

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


[clang] [Clang][AArch64][ARM]: Fix Inefficient loads/stores of _BitInt(N) (PR #93495)

2024-07-20 Thread Hassnaa Hamdi via cfe-commits

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


[clang] [clang] Add -Wimplicit-fallthrough to -Wextra (PR #97926)

2024-07-20 Thread Max Coplan via cfe-commits

vegerot wrote:

> I would put up a branch on http://llvm-compile-time-tracker.com (instructions 
> in the `About` page) and see how this impacts compile times. We've always 
> left diagnostics out of -Wextra that require a CFG, so getting performance 
> measurements is important.

Thanks!  The `About` page says

> If you are an LLVM contributor who **regularly** does compile-time sensitive 
> work

Do you think I should still ask for permission or should I leave it to someone 
else?

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


[clang] [clang] Add -Wimplicit-fallthrough to -Wextra (PR #97926)

2024-07-20 Thread Max Coplan via cfe-commits

https://github.com/vegerot updated 
https://github.com/llvm/llvm-project/pull/97926

>From 9640f00fac2be5984b6a0ee2f7f917a58f7e53d8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Max=20=F0=9F=91=A8=F0=9F=8F=BD=E2=80=8D=F0=9F=92=BB=20Copl?=
 =?UTF-8?q?an?= 
Date: Sat, 6 Jul 2024 17:22:55 -0700
Subject: [PATCH] [clang] Add -Wimplicit-fallthrough to -Wextra

This patch adds -Wimplicit-fallthrough to -Wextra. GCC already includes it in 
-Wextra.

This patch also adds a test to check that -Wimplicit-fallthrough is included in 
-Wextra.

Note: This patch may regress performance when building with -Wextra.
This is because -Wextra requires forming a CFG for every function.
---
 clang/include/clang/Basic/DiagnosticGroups.td| 1 +
 clang/test/Sema/fallthrough-attr.c   | 1 +
 clang/test/SemaCXX/switch-implicit-fallthrough-macro.cpp | 1 +
 3 files changed, 3 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e043349..2a307679c9283 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1067,6 +1067,7 @@ def Extra : DiagGroup<"extra", [
 StringConcatation,
 FUseLdPath,
 CastFunctionTypeMismatch,
+ImplicitFallthrough,
   ]>;
 
 def Most : DiagGroup<"most", [
diff --git a/clang/test/Sema/fallthrough-attr.c 
b/clang/test/Sema/fallthrough-attr.c
index de50ebf39d42f..6cc19136f30a7 100644
--- a/clang/test/Sema/fallthrough-attr.c
+++ b/clang/test/Sema/fallthrough-attr.c
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 -fsyntax-only -std=gnu99 -verify -Wimplicit-fallthrough %s
 // RUN: %clang_cc1 -fsyntax-only -std=c99 -verify -Wimplicit-fallthrough %s
 // RUN: %clang_cc1 -fsyntax-only -std=c11 -verify -Wimplicit-fallthrough %s
+// RUN: %clang_cc1 -fsyntax-only -std=c11 -verify -Wextra %s
 // RUN: %clang_cc1 -fsyntax-only -std=c2x -DC2X -verify -Wimplicit-fallthrough 
%s
 
 int fallthrough_attribute_spelling(int n) {
diff --git a/clang/test/SemaCXX/switch-implicit-fallthrough-macro.cpp 
b/clang/test/SemaCXX/switch-implicit-fallthrough-macro.cpp
index 11df2cbfb53f0..cbbff1f1793b8 100644
--- a/clang/test/SemaCXX/switch-implicit-fallthrough-macro.cpp
+++ b/clang/test/SemaCXX/switch-implicit-fallthrough-macro.cpp
@@ -3,6 +3,7 @@
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z -Wimplicit-fallthrough 
-DCLANG_PREFIX -DCOMMAND_LINE_FALLTHROUGH=[[clang::fallthrough]] %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z -Wimplicit-fallthrough 
-DCOMMAND_LINE_FALLTHROUGH=[[clang::fallthrough]] %s
 // RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z -Wimplicit-fallthrough 
-DCOMMAND_LINE_FALLTHROUGH=[[fallthrough]] -DUNCHOSEN=[[clang::fallthrough]] %s
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++1z -Wextra 
-DCOMMAND_LINE_FALLTHROUGH=[[fallthrough]] -DUNCHOSEN=[[clang::fallthrough]] %s
 
 int fallthrough_compatibility_macro_from_command_line(int n) {
   switch (n) {

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


[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits

https://github.com/memory-thrasher updated 
https://github.com/llvm/llvm-project/pull/97792

>From f0b53c557bcadc8b0d323144fc19f4b0f6767d94 Mon Sep 17 00:00:00 2001
From: Sidney Kelley 
Date: Thu, 4 Jul 2024 23:03:16 -0700
Subject: [PATCH] Adds support to clang"s windows mangler to handle template
 argument values that are pointers one-past-the-end of a non-array symbol.
 Also improves error messages in other template argument scenarios where clang
 bails.

---
 clang/lib/AST/MicrosoftMangle.cpp | 208 +++---
 .../CodeGen/ms_mangler_templatearg_opte.cpp   |  19 ++
 2 files changed, 96 insertions(+), 131 deletions(-)
 create mode 100644 clang/test/CodeGen/ms_mangler_templatearg_opte.cpp

diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 4016043df62ed..41722478084f2 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -337,6 +337,9 @@ class MicrosoftCXXNameMangler {
 
   const bool PointersAre64Bit;
 
+  DiagnosticBuilder Error(SourceLocation, StringRef);
+  DiagnosticBuilder Error(StringRef);
+
 public:
   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
   enum class TplArgKind { ClassNTTP, StructuralValue };
@@ -564,6 +567,23 @@ 
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
   return true;
 }
 
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error, "cannot mangle this %0%1%2%3%4 yet");
+  return Diags.Report(loc, DiagID) << thingy;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(
+  DiagnosticsEngine::Error, "cannot mangle this %0%1%2%3%4 yet");
+  return Diags.Report(DiagID) << thingy;
+}
+
 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
   const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
@@ -1578,10 +1598,7 @@ void 
MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
   case OO_Spaceship: Out << "?__M"; break;
 
   case OO_Conditional: {
-DiagnosticsEngine &Diags = Context.getDiags();
-unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-  "cannot mangle this conditional operator yet");
-Diags.Report(Loc, DiagID);
+Error(Loc, "conditional operator");
 break;
   }
 
@@ -1673,11 +1690,8 @@ void MicrosoftCXXNameMangler::mangleExpression(
   }
 
   // As bad as this diagnostic is, it's better than crashing.
-  DiagnosticsEngine &Diags = Context.getDiags();
-  unsigned DiagID = Diags.getCustomDiagID(
-  DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
-  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
-<< E->getSourceRange();
+  Error(E->getExprLoc(), "expression type: ")
+  << E->getStmtClassName() << E->getSourceRange();
 }
 
 void MicrosoftCXXNameMangler::mangleTemplateArgs(
@@ -1923,11 +1937,19 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 if (WithScalarType)
   mangleType(T, SourceRange(), QMM_Escape);
 
-// We don't know how to mangle past-the-end pointers yet.
-if (V.isLValueOnePastTheEnd())
-  break;
-
 APValue::LValueBase Base = V.getLValueBase();
+
+// this might not cover every case but did cover issue 97756
+// see test CodeGen/ms_mangler_templatearg_opte
+if (V.isLValueOnePastTheEnd()) {
+  Out << "5E";
+  auto *VD = Base.dyn_cast();
+  if (VD)
+mangle(VD);
+  Out << "@";
+  return;
+}
+
 if (!V.hasLValuePath() || V.getLValuePath().empty()) {
   // Taking the address of a complete object has a special-case mangling.
   if (Base.isNull()) {
@@ -1939,12 +1961,14 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 mangleNumber(V.getLValueOffset().getQuantity());
   } else if (!V.hasLValuePath()) {
 // FIXME: This can only happen as an extension. Invent a mangling.
-break;
+Error("template argument (extension not comaptible with ms mangler)");
+return;
   } else if (auto *VD = Base.dyn_cast()) {
 Out << "E";
 mangle(VD);
   } else {
-break;
+Error("template argument (undeclared base)");
+return;
   }
 } else {
   if (TAK == TplArgKind::ClassNTTP && T->isPointerType())
@@ -1989,8 +2013,10 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 Out << *I;
 
   auto *VD = Base.dyn_cast();
-  if (!VD)
-break;
+

[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits

https://github.com/memory-thrasher updated 
https://github.com/llvm/llvm-project/pull/97792

>From 81095a3fd1b5ce76a17922ad40a47f6a4a4308ab Mon Sep 17 00:00:00 2001
From: Sidney Kelley 
Date: Thu, 4 Jul 2024 23:03:16 -0700
Subject: [PATCH] Adds support to clang"s windows mangler to handle template
 argument values that are pointers one-past-the-end of a non-array symbol.
 Also improves error messages in other template argument scenarios where clang
 bails.

---
 clang/lib/AST/MicrosoftMangle.cpp | 217 +++---
 .../CodeGen/ms_mangler_templatearg_opte.cpp   |  19 ++
 2 files changed, 105 insertions(+), 131 deletions(-)
 create mode 100644 clang/test/CodeGen/ms_mangler_templatearg_opte.cpp

diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 4016043df62ed..e0d7c01ca3351 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -337,6 +337,10 @@ class MicrosoftCXXNameMangler {
 
   const bool PointersAre64Bit;
 
+  DiagnosticBuilder Error(SourceLocation, StringRef, StringRef);
+  DiagnosticBuilder Error(SourceLocation, StringRef);
+  DiagnosticBuilder Error(StringRef);
+
 public:
   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
   enum class TplArgKind { ClassNTTP, StructuralValue };
@@ -564,6 +568,31 @@ 
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
   return true;
 }
 
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thing1,
+ StringRef thing2) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 %1 yet");
+  return Diags.Report(loc, DiagID) << thing1 << thing2;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 yet");
+  return Diags.Report(loc, DiagID) << thingy;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 yet");
+  return Diags.Report(DiagID) << thingy;
+}
+
 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
   const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
@@ -1578,10 +1607,7 @@ void 
MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
   case OO_Spaceship: Out << "?__M"; break;
 
   case OO_Conditional: {
-DiagnosticsEngine &Diags = Context.getDiags();
-unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-  "cannot mangle this conditional operator yet");
-Diags.Report(Loc, DiagID);
+Error(Loc, "conditional operator");
 break;
   }
 
@@ -1673,11 +1699,8 @@ void MicrosoftCXXNameMangler::mangleExpression(
   }
 
   // As bad as this diagnostic is, it's better than crashing.
-  DiagnosticsEngine &Diags = Context.getDiags();
-  unsigned DiagID = Diags.getCustomDiagID(
-  DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
-  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
-<< E->getSourceRange();
+  Error(E->getExprLoc(), "expression type: ", E->getStmtClassName())
+  << E->getSourceRange();
 }
 
 void MicrosoftCXXNameMangler::mangleTemplateArgs(
@@ -1923,11 +1946,19 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 if (WithScalarType)
   mangleType(T, SourceRange(), QMM_Escape);
 
-// We don't know how to mangle past-the-end pointers yet.
-if (V.isLValueOnePastTheEnd())
-  break;
-
 APValue::LValueBase Base = V.getLValueBase();
+
+// this might not cover every case but did cover issue 97756
+// see test CodeGen/ms_mangler_templatearg_opte
+if (V.isLValueOnePastTheEnd()) {
+  Out << "5E";
+  auto *VD = Base.dyn_cast();
+  if (VD)
+mangle(VD);
+  Out << "@";
+  return;
+}
+
 if (!V.hasLValuePath() || V.getLValuePath().empty()) {
   // Taking the address of a complete object has a special-case mangling.
   if (Base.isNull()) {
@@ -1939,12 +1970,14 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 mangleNumber(V.getLValueOffset().getQuantity());
   } else if (!V.hasLValuePath()) {
 // FIXME: This can only happen as an extension. Invent a mangling.
-break;
+Error("template argum

[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits

https://github.com/memory-thrasher updated 
https://github.com/llvm/llvm-project/pull/97792

>From 5e5b80efa1e1903884db1f4ee8d92f79d139e7f9 Mon Sep 17 00:00:00 2001
From: Sidney Kelley 
Date: Thu, 4 Jul 2024 23:03:16 -0700
Subject: [PATCH] Adds support to clang"s windows mangler to handle template
 argument values that are pointers one-past-the-end of a non-array symbol.
 Also improves error messages in other template argument scenarios where clang
 bails.

---
 clang/lib/AST/MicrosoftMangle.cpp | 217 +++---
 .../CodeGen/ms_mangler_templatearg_opte.cpp   |  19 ++
 .../aarch64-mangle-sve-vectors-msvc.cpp   |   2 +-
 3 files changed, 106 insertions(+), 132 deletions(-)
 create mode 100644 clang/test/CodeGen/ms_mangler_templatearg_opte.cpp

diff --git a/clang/lib/AST/MicrosoftMangle.cpp 
b/clang/lib/AST/MicrosoftMangle.cpp
index 4016043df62ed..e0d7c01ca3351 100644
--- a/clang/lib/AST/MicrosoftMangle.cpp
+++ b/clang/lib/AST/MicrosoftMangle.cpp
@@ -337,6 +337,10 @@ class MicrosoftCXXNameMangler {
 
   const bool PointersAre64Bit;
 
+  DiagnosticBuilder Error(SourceLocation, StringRef, StringRef);
+  DiagnosticBuilder Error(SourceLocation, StringRef);
+  DiagnosticBuilder Error(StringRef);
+
 public:
   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
   enum class TplArgKind { ClassNTTP, StructuralValue };
@@ -564,6 +568,31 @@ 
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
   return true;
 }
 
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thing1,
+ StringRef thing2) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 %1 yet");
+  return Diags.Report(loc, DiagID) << thing1 << thing2;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(SourceLocation loc,
+ StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 yet");
+  return Diags.Report(loc, DiagID) << thingy;
+}
+
+DiagnosticBuilder MicrosoftCXXNameMangler::Error(StringRef thingy) {
+  DiagnosticsEngine &Diags = Context.getDiags();
+  // extra placeholders are ignored quietly when not used
+  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
+  "cannot mangle this %0 yet");
+  return Diags.Report(DiagID) << thingy;
+}
+
 void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
   const NamedDecl *D = cast(GD.getDecl());
   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
@@ -1578,10 +1607,7 @@ void 
MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
   case OO_Spaceship: Out << "?__M"; break;
 
   case OO_Conditional: {
-DiagnosticsEngine &Diags = Context.getDiags();
-unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
-  "cannot mangle this conditional operator yet");
-Diags.Report(Loc, DiagID);
+Error(Loc, "conditional operator");
 break;
   }
 
@@ -1673,11 +1699,8 @@ void MicrosoftCXXNameMangler::mangleExpression(
   }
 
   // As bad as this diagnostic is, it's better than crashing.
-  DiagnosticsEngine &Diags = Context.getDiags();
-  unsigned DiagID = Diags.getCustomDiagID(
-  DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
-  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
-<< E->getSourceRange();
+  Error(E->getExprLoc(), "expression type: ", E->getStmtClassName())
+  << E->getSourceRange();
 }
 
 void MicrosoftCXXNameMangler::mangleTemplateArgs(
@@ -1923,11 +1946,19 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 if (WithScalarType)
   mangleType(T, SourceRange(), QMM_Escape);
 
-// We don't know how to mangle past-the-end pointers yet.
-if (V.isLValueOnePastTheEnd())
-  break;
-
 APValue::LValueBase Base = V.getLValueBase();
+
+// this might not cover every case but did cover issue 97756
+// see test CodeGen/ms_mangler_templatearg_opte
+if (V.isLValueOnePastTheEnd()) {
+  Out << "5E";
+  auto *VD = Base.dyn_cast();
+  if (VD)
+mangle(VD);
+  Out << "@";
+  return;
+}
+
 if (!V.hasLValuePath() || V.getLValuePath().empty()) {
   // Taking the address of a complete object has a special-case mangling.
   if (Base.isNull()) {
@@ -1939,12 +1970,14 @@ void 
MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
 mangleNumber(V.getLValueOffset().getQuantity());
   } else if (!V.hasLValuePath()) {
 // FIXME: This can only happen as an extension. Invent a 

[clang] Adds a pseudonym to clang"s windows mangler... (PR #97792)

2024-07-20 Thread via cfe-commits

memory-thrasher wrote:

I finally got the tests to behave.

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


[clang] [Driver] Clean up fp-contract handling in clang driver (PR #99723)

2024-07-20 Thread Fangrui Song via cfe-commits


@@ -10,18 +10,18 @@
 // RUN: %clang -### -fno-fast-math -c %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-FPC-ON %s
 
-// RUN: %clang -### -Werror -ffast-math -ffp-contract=on -c %s 2>&1 \
+// RUN: %clang -### -ffast-math -ffp-contract=on -c %s 2>&1 \

MaskRay wrote:

If these RUN lines now emit warnings (upgraded to errors if -Werror), consider 
adding check prefixes for the warnings.

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits

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

Looks good aside from missing release notes, especially entries to potentially 
breaking changes.
Given that you've been making a significant amount of changes to Python 
bindings that are spread over multiple PRs, it's worth considering if 19 
release branching on Tuesday, 23rd of July is of any significance for this 
effort. If you think that broken or half-baked things are going into 19 branch, 
reach out to me or Aaron on `#clang` channel on our Discord server. We can both 
pull things out, or cherry-pick changes from `main` into `releases/19.x`, as 
long as we do it in a timely manner.

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits


@@ -66,46 +66,77 @@
 
 import collections.abc
 import os
+import sys
 from enum import Enum
 
+from typing import (
+Any,
+Callable,
+Generic,
+Optional,
+Type as TType,
+TypeVar,
+TYPE_CHECKING,
+Union as TUnion,
+)
+from typing_extensions import Protocol, TypeAlias
+
+if TYPE_CHECKING:
+from ctypes import _Pointer
+
+StrPath: TypeAlias = TUnion[str, os.PathLike[str]]
+LibFunc: TypeAlias = TUnion[
+"tuple[str, Optional[list[Any]]]",
+"tuple[str, Optional[list[Any]], Any]",
+"tuple[str, Optional[list[Any]], Any, Callable[..., Any]]",
+]
+CObjP: TypeAlias = _Pointer[Any]
+
+TSeq = TypeVar("TSeq", covariant=True)
+
+class NoSliceSequence(Protocol[TSeq]):
+def __len__(self) -> int: ...
+def __getitem__(self, key: int) -> TSeq: ...
+
 
 # Python 3 strings are unicode, translate them to/from utf8 for C-interop.
 class c_interop_string(c_char_p):
-def __init__(self, p=None):
+def __init__(self, p: str | bytes | None = None):
 if p is None:
 p = ""
 if isinstance(p, str):
 p = p.encode("utf8")
 super(c_char_p, self).__init__(p)
 
-def __str__(self):
-return self.value
+def __str__(self) -> str:
+return self.value or ""

Endilll wrote:

> I guess this is also worth a "potentially breaking change"

That's correct

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits


@@ -115,9 +146,7 @@ def b(x):
 # object. This is a problem, because it means that from_parameter will see an
 # integer and pass the wrong value on platforms where int != void*. Work around
 # this by marshalling object arguments as void**.
-c_object_p = POINTER(c_void_p)
-
-callbacks = {}

Endilll wrote:

If it's not used, I don't see a reason to keep it.

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits


@@ -200,13 +236,16 @@ class _CXString(Structure):
 
 _fields_ = [("spelling", c_char_p), ("free", c_int)]
 
-def __del__(self):
+def __del__(self) -> None:
 conf.lib.clang_disposeString(self)
 
 @staticmethod
-def from_result(res, fn=None, args=None):
+def from_result(res: _CXString, fn: Any = None, args: Any = None) -> str:
 assert isinstance(res, _CXString)
-return conf.lib.clang_getCString(res)
+pystr: str | None = conf.lib.clang_getCString(res)
+if pystr is None:
+return ""
+return pystr

Endilll wrote:

This change makes sense. I'm not sure it's breaking, though, because nothing 
breaks for both users who have been checking for `None`, and those who have not 
been.

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


[clang] [clang-format] Fix a bug in annotating StartOfName (PR #99791)

2024-07-20 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/99791

Fixes #99758.

>From f38256c028e1600bc6b957f851ffcc0dedab589c Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Sat, 20 Jul 2024 16:43:39 -0700
Subject: [PATCH] [clang-format] Fix a bug in annotating StartOfName

Fixes #99758.
---
 clang/lib/Format/TokenAnnotator.cpp   |  4 +++-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 14 ++
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index db66911f00f63..06c34bd45eb31 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2625,8 +2625,10 @@ class AnnotatingParser {
   return false;
 
 // int a or auto a.
-if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto))
+if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto) &&
+PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
   return true;
+}
 
 // *a or &a or &&a.
 if (PreviousNotConst->is(TT_PointerOrReference))
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index f70424c3ee060..e7bc15d7e1dfa 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2125,6 +2125,13 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   ASSERT_EQ(Tokens.size(), 21u) << Tokens;
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 
+  auto Style = getLLVMStyle();
+  Style.StatementAttributeLikeMacros.push_back("emit");
+  Tokens = annotate("emit foo()->bar;", Style);
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_StatementAttributeLikeMacro);
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
   // Mixed
   Tokens = annotate("auto f() -> int { auto a = b()->c; }");
   ASSERT_EQ(Tokens.size(), 18u) << Tokens;
@@ -2950,6 +2957,13 @@ TEST_F(TokenAnnotatorTest, StartOfName) {
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::at, TT_ObjCDecl);
   EXPECT_TOKEN(Tokens[2], tok::identifier, TT_StartOfName);
+
+  auto Style = getLLVMStyle();
+  Style.StatementAttributeLikeMacros.push_back("emit");
+  Tokens = annotate("emit foo = 0;", Style);
+  ASSERT_EQ(Tokens.size(), 6u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_StatementAttributeLikeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_Unknown);
 }
 
 TEST_F(TokenAnnotatorTest, BraceKind) {

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


[clang] [libclang/python] Fix some type errors, add type annotations (PR #98745)

2024-07-20 Thread Vlad Serebrennikov via cfe-commits


@@ -169,25 +198,32 @@ def __init__(self, enumeration, message):
 
 ### Structures and Utility Classes ###
 
+TInstance = TypeVar("TInstance")
+TResult = TypeVar("TResult")
+
 
-class CachedProperty:
+class CachedProperty(Generic[TInstance, TResult]):
 """Decorator that lazy-loads the value of a property.
 
 The first time the property is accessed, the original property function is
 executed. The value it returns is set as the new value of that instance's
 property, replacing the original method.
 """
 
-def __init__(self, wrapped):
+def __init__(self, wrapped: Callable[[TInstance], TResult]):
 self.wrapped = wrapped
 try:
 self.__doc__ = wrapped.__doc__
 except:
 pass
 
-def __get__(self, instance, instance_type=None):
+def __get__(self, instance: TInstance, instance_type: Any = None) -> 
TResult:
 if instance is None:
-return self
+property_name = self.wrapped.__name__
+class_name = instance_type.__name__
+raise TypeError(
+f"'{property_name}' is not a static attribute of 
'{class_name}'"
+)

Endilll wrote:

Makes sense. Worth noting that this is technically a breaking change.

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


[clang] [clang-format] Fix a bug in annotating StartOfName (PR #99791)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Fixes #99758.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+3-1) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+14) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index db66911f00f63..06c34bd45eb31 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -2625,8 +2625,10 @@ class AnnotatingParser {
   return false;
 
 // int a or auto a.
-if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto))
+if (PreviousNotConst->isOneOf(tok::identifier, tok::kw_auto) &&
+PreviousNotConst->isNot(TT_StatementAttributeLikeMacro)) {
   return true;
+}
 
 // *a or &a or &&a.
 if (PreviousNotConst->is(TT_PointerOrReference))
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index f70424c3ee060..e7bc15d7e1dfa 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2125,6 +2125,13 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsTrailingReturnArrow) {
   ASSERT_EQ(Tokens.size(), 21u) << Tokens;
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 
+  auto Style = getLLVMStyle();
+  Style.StatementAttributeLikeMacros.push_back("emit");
+  Tokens = annotate("emit foo()->bar;", Style);
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_StatementAttributeLikeMacro);
+  EXPECT_TOKEN(Tokens[4], tok::arrow, TT_Unknown);
+
   // Mixed
   Tokens = annotate("auto f() -> int { auto a = b()->c; }");
   ASSERT_EQ(Tokens.size(), 18u) << Tokens;
@@ -2950,6 +2957,13 @@ TEST_F(TokenAnnotatorTest, StartOfName) {
   ASSERT_EQ(Tokens.size(), 7u) << Tokens;
   EXPECT_TOKEN(Tokens[0], tok::at, TT_ObjCDecl);
   EXPECT_TOKEN(Tokens[2], tok::identifier, TT_StartOfName);
+
+  auto Style = getLLVMStyle();
+  Style.StatementAttributeLikeMacros.push_back("emit");
+  Tokens = annotate("emit foo = 0;", Style);
+  ASSERT_EQ(Tokens.size(), 6u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_StatementAttributeLikeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_Unknown);
 }
 
 TEST_F(TokenAnnotatorTest, BraceKind) {

``




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


[clang] [ExprConstant] Handle shift overflow the same way as other kinds of overflow (PR #99579)

2024-07-20 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

Thank you for the additional tests, so I am not sure if the coverage is 
sufficient I see changed under the following diagnostic:

note_constexpr_negative_shift
note_constexpr_large_shift
note_constexpr_lshift_of_negative
note_constexpr_lshift_discards

but I don't think I see tests that cover the negative shift changes, am I just 
missing it?

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


[clang] Add _MM_FROUND_TIES_TO_EVEN to avx512fintrin.h (PR #99691)

2024-07-20 Thread Phoebe Wang via cfe-commits

phoebewang wrote:

Thanks @hpkfft for the thorough explanation. I'm fine with either 
`_MM_FROUND_TIES_TO_EVEN` or `_MM_FROUND_TO_NEAREST_TIES_EVEN`. Let's see GCC 
community preference.

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


[clang] Add missing python binding for clang_getUnqualifiedType and clang_getNonReferenceType (PR #99793)

2024-07-20 Thread via cfe-commits

https://github.com/brendene created 
https://github.com/llvm/llvm-project/pull/99793

These are present in `clang/include/clang-c/Index.h` but not exported in the 
python bindings

This fixes https://github.com/llvm/llvm-project/issues/63235



>From 3c1d8fb295df55d60bc2d908fbb61642fcf392ca Mon Sep 17 00:00:00 2001
From: Brenden Eng 
Date: Sat, 20 Jul 2024 22:37:54 -0400
Subject: [PATCH] Add missing python binding for clang_getUnqualifiedType and
 clang_getNonReferenceType

---
 clang/bindings/python/clang/cindex.py | 16 
 1 file changed, 16 insertions(+)

diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index be024da5e005c..8de25e385473d 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -2487,6 +2487,20 @@ def get_canonical(self):
 """
 return conf.lib.clang_getCanonicalType(self)
 
+def get_unqualified(self):
+"""
+Return the unqualified variant of the given type, removing as little 
sugar as possible.
+"""
+
+return conf.lib.clang_getUnqualifiedType(self)
+
+def get_non_reference(self):
+"""
+Returns the type that the reference refers to, otherwise the type 
itself.
+"""
+
+return conf.lib.clang_getNonReferenceType(self)
+
 def is_const_qualified(self):
 """Determine whether a Type has the "const" qualifier set.
 
@@ -3738,6 +3752,8 @@ def write_main_file_to_stdout(self):
 ("clang_getFieldDeclBitWidth", [Cursor], c_int),
 ("clang_getCanonicalCursor", [Cursor], Cursor, Cursor.from_cursor_result),
 ("clang_getCanonicalType", [Type], Type, Type.from_result),
+("clang_getUnqualifiedType", [Type], Type, Type.from_result),
+("clang_getNonReferenceType", [Type], Type, Type.from_result),
 ("clang_getChildDiagnostics", [Diagnostic], c_object_p),
 ("clang_getCompletionAvailability", [c_void_p], c_int),
 ("clang_getCompletionBriefComment", [c_void_p], _CXString, 
_CXString.from_result),

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


[clang] Add missing python binding for clang_getUnqualifiedType and clang_getNonReferenceType (PR #99793)

2024-07-20 Thread via cfe-commits

github-actions[bot] wrote:



Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be
notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this 
page.

If this is not working for you, it is probably because you do not have write
permissions for the repository. In which case you can instead tag reviewers by
name in a comment by using `@` followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review
by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate
is once a week. Please remember that you are asking for valuable time from 
other developers.

If you have further questions, they may be answered by the [LLVM GitHub User 
Guide](https://llvm.org/docs/GitHub.html).

You can also ask questions in a comment on this PR, on the [LLVM 
Discord](https://discord.com/invite/xS7Z362) or on the 
[forums](https://discourse.llvm.org/).

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


[clang] Add missing python binding for clang_getUnqualifiedType and clang_getNonReferenceType (PR #99793)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (brendene)


Changes

These are present in `clang/include/clang-c/Index.h` but not exported in the 
python bindings

This fixes https://github.com/llvm/llvm-project/issues/63235



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


1 Files Affected:

- (modified) clang/bindings/python/clang/cindex.py (+16) 


``diff
diff --git a/clang/bindings/python/clang/cindex.py 
b/clang/bindings/python/clang/cindex.py
index be024da5e005c..8de25e385473d 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -2487,6 +2487,20 @@ def get_canonical(self):
 """
 return conf.lib.clang_getCanonicalType(self)
 
+def get_unqualified(self):
+"""
+Return the unqualified variant of the given type, removing as little 
sugar as possible.
+"""
+
+return conf.lib.clang_getUnqualifiedType(self)
+
+def get_non_reference(self):
+"""
+Returns the type that the reference refers to, otherwise the type 
itself.
+"""
+
+return conf.lib.clang_getNonReferenceType(self)
+
 def is_const_qualified(self):
 """Determine whether a Type has the "const" qualifier set.
 
@@ -3738,6 +3752,8 @@ def write_main_file_to_stdout(self):
 ("clang_getFieldDeclBitWidth", [Cursor], c_int),
 ("clang_getCanonicalCursor", [Cursor], Cursor, Cursor.from_cursor_result),
 ("clang_getCanonicalType", [Type], Type, Type.from_result),
+("clang_getUnqualifiedType", [Type], Type, Type.from_result),
+("clang_getNonReferenceType", [Type], Type, Type.from_result),
 ("clang_getChildDiagnostics", [Diagnostic], c_object_p),
 ("clang_getCompletionAvailability", [c_void_p], c_int),
 ("clang_getCompletionBriefComment", [c_void_p], _CXString, 
_CXString.from_result),

``




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


[clang] [clang] Add missing python binding for clang_getUnqualifiedType and clang_getNonReferenceType (PR #99793)

2024-07-20 Thread via cfe-commits

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


[clang] [Clang][Interp] Diagnose use sizeless vector type as the argument of `__builtin_vectorelements` (PR #99794)

2024-07-20 Thread via cfe-commits

https://github.com/yronglin created 
https://github.com/llvm/llvm-project/pull/99794

None

>From 6d9dbc3248ae8e8e374d6d7e656935b1bc82cdee Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sun, 21 Jul 2024 10:54:41 +0800
Subject: [PATCH] [Clang][Interp] Diagnose use sizeless vector type as the
 argument of __builtin_vectorelements

Signed-off-by: yronglin 
---
 clang/lib/AST/Interp/Compiler.cpp | 6 ++
 clang/lib/AST/Interp/Interp.h | 8 
 clang/lib/AST/Interp/Opcodes.td   | 2 ++
 clang/test/SemaCXX/builtin_vectorelements.cpp | 1 +
 4 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index ef579bc5d8972..aeefaf89cfc4b 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -1698,10 +1698,8 @@ bool Compiler::VisitUnaryExprOrTypeTraitExpr(
   if (Kind == UETT_VectorElements) {
 if (const auto *VT = E->getTypeOfArgument()->getAs())
   return this->emitConst(VT->getNumElements(), E);
-
-// FIXME: Apparently we need to catch the fact that a sizeless vector type
-// has been passed and diagnose that (at run time).
-assert(E->getTypeOfArgument()->isSizelessVectorType());
+if (E->getTypeOfArgument()->isSizelessVectorType())
+  return this->emitSizelessVectorElementSize(E);
   }
 
   if (Kind == UETT_VecStep) {
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index f86b787fb034e..be224a7b0dfd0 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -29,6 +29,7 @@
 #include "State.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
 #include 
@@ -870,6 +871,13 @@ bool Comp(InterpState &S, CodePtr OpPC) {
   return false;
 }
 
+inline bool SizelessVectorElementSize(InterpState &S, CodePtr OpPC) {
+  const SourceRange &ArgRange = S.Current->getRange(OpPC);
+  const Expr *E = S.Current->getExpr(OpPC);
+  S.FFDiag(E, diag::note_constexpr_non_const_vectorelements) << ArgRange;
+  return false;
+}
+
 
//===--===//
 // EQ, NE, GT, GE, LT, LE
 
//===--===//
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 49ebb156ab2fb..9f29fa9272711 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -733,6 +733,8 @@ def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
 
+def SizelessVectorElementSize : Opcode;
+
 def Assume : Opcode;
 
 def ArrayDecay : Opcode;
diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 59ff09ac72e42..197ab2fd9625e 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -2,6 +2,7 @@
 
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes 
-fexperimental-new-constant-interpreter %s
 
 template 
 using VecT __attribute__((vector_size(16))) = T;

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


[clang] [Clang][Interp] Diagnose use sizeless vector type as the argument of `__builtin_vectorelements` (PR #99794)

2024-07-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (yronglin)


Changes



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


4 Files Affected:

- (modified) clang/lib/AST/Interp/Compiler.cpp (+2-4) 
- (modified) clang/lib/AST/Interp/Interp.h (+8) 
- (modified) clang/lib/AST/Interp/Opcodes.td (+2) 
- (modified) clang/test/SemaCXX/builtin_vectorelements.cpp (+1) 


``diff
diff --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index ef579bc5d8972..aeefaf89cfc4b 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -1698,10 +1698,8 @@ bool Compiler::VisitUnaryExprOrTypeTraitExpr(
   if (Kind == UETT_VectorElements) {
 if (const auto *VT = E->getTypeOfArgument()->getAs())
   return this->emitConst(VT->getNumElements(), E);
-
-// FIXME: Apparently we need to catch the fact that a sizeless vector type
-// has been passed and diagnose that (at run time).
-assert(E->getTypeOfArgument()->isSizelessVectorType());
+if (E->getTypeOfArgument()->isSizelessVectorType())
+  return this->emitSizelessVectorElementSize(E);
   }
 
   if (Kind == UETT_VecStep) {
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index f86b787fb034e..be224a7b0dfd0 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -29,6 +29,7 @@
 #include "State.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
 #include 
@@ -870,6 +871,13 @@ bool Comp(InterpState &S, CodePtr OpPC) {
   return false;
 }
 
+inline bool SizelessVectorElementSize(InterpState &S, CodePtr OpPC) {
+  const SourceRange &ArgRange = S.Current->getRange(OpPC);
+  const Expr *E = S.Current->getExpr(OpPC);
+  S.FFDiag(E, diag::note_constexpr_non_const_vectorelements) << ArgRange;
+  return false;
+}
+
 
//===--===//
 // EQ, NE, GT, GE, LT, LE
 
//===--===//
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 49ebb156ab2fb..9f29fa9272711 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -733,6 +733,8 @@ def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
 
+def SizelessVectorElementSize : Opcode;
+
 def Assume : Opcode;
 
 def ArrayDecay : Opcode;
diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 59ff09ac72e42..197ab2fd9625e 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -2,6 +2,7 @@
 
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes 
-fexperimental-new-constant-interpreter %s
 
 template 
 using VecT __attribute__((vector_size(16))) = T;

``




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


[clang] [Clang][Interp] Diagnose use sizeless vector type as the argument of `__builtin_vectorelements` (PR #99794)

2024-07-20 Thread via cfe-commits

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


[clang] [Clang][AST] {CXXDefaultArgExpr, CXXDefaultInitExpr}::hasRewrittenInit return true iif the init expression was really rebuild (PR #99748)

2024-07-20 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/99748

>From c565183f352e3bb43bc375887a65f85dcdffb516 Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sat, 20 Jul 2024 17:47:39 +0800
Subject: [PATCH] [Clang][AST] {CXXDefaultArgExpr,
 CXXDefaultInitExpr}::hasRewrittenInit return true iif the init expression was
 really rebuild

Signed-off-by: yronglin 
---
 clang/include/clang/AST/ExprCXX.h | 13 
 clang/lib/AST/ASTImporter.cpp |  7 ++--
 clang/lib/AST/ExprCXX.cpp | 33 +--
 clang/lib/AST/JSONNodeDumper.cpp  |  4 +--
 clang/lib/Sema/SemaExpr.cpp   | 14 +---
 clang/lib/Sema/TreeTransform.h|  9 ++---
 clang/test/AST/ast-dump-default-init-json.cpp |  2 +-
 clang/test/AST/ast-dump-default-init.cpp  |  2 +-
 8 files changed, 45 insertions(+), 39 deletions(-)

diff --git a/clang/include/clang/AST/ExprCXX.h 
b/clang/include/clang/AST/ExprCXX.h
index c2feac525c1ea..e863bcb104c09 100644
--- a/clang/include/clang/AST/ExprCXX.h
+++ b/clang/include/clang/AST/ExprCXX.h
@@ -1277,7 +1277,8 @@ class CXXDefaultArgExpr final
   DeclContext *UsedContext;
 
   CXXDefaultArgExpr(StmtClass SC, SourceLocation Loc, ParmVarDecl *Param,
-Expr *RewrittenExpr, DeclContext *UsedContext)
+DeclContext *UsedContext, Expr *RewrittenExpr,
+bool HasRewrittenInit)
   : Expr(SC,
  Param->hasUnparsedDefaultArg()
  ? Param->getType().getNonReferenceType()
@@ -1286,7 +1287,7 @@ class CXXDefaultArgExpr final
  Param->getDefaultArg()->getObjectKind()),
 Param(Param), UsedContext(UsedContext) {
 CXXDefaultArgExprBits.Loc = Loc;
-CXXDefaultArgExprBits.HasRewrittenInit = RewrittenExpr != nullptr;
+CXXDefaultArgExprBits.HasRewrittenInit = HasRewrittenInit;
 if (RewrittenExpr)
   *getTrailingObjects() = RewrittenExpr;
 setDependence(computeDependence(this));
@@ -1304,8 +1305,8 @@ class CXXDefaultArgExpr final
   // \p Param is the parameter whose default argument is used by this
   // expression.
   static CXXDefaultArgExpr *Create(const ASTContext &C, SourceLocation Loc,
-   ParmVarDecl *Param, Expr *RewrittenExpr,
-   DeclContext *UsedContext);
+   ParmVarDecl *Param, DeclContext 
*UsedContext,
+   Expr *InitExpr, bool HasRewrittenInit);
   // Retrieve the parameter that the argument was created from.
   const ParmVarDecl *getParam() const { return Param; }
   ParmVarDecl *getParam() { return Param; }
@@ -1385,7 +1386,7 @@ class CXXDefaultInitExpr final
 
   CXXDefaultInitExpr(const ASTContext &Ctx, SourceLocation Loc,
  FieldDecl *Field, QualType Ty, DeclContext *UsedContext,
- Expr *RewrittenInitExpr);
+ Expr *InitExpr, bool HasRewrittenInit);
 
   CXXDefaultInitExpr(EmptyShell Empty, bool HasRewrittenInit)
   : Expr(CXXDefaultInitExprClass, Empty) {
@@ -1399,7 +1400,7 @@ class CXXDefaultInitExpr final
   /// by this expression.
   static CXXDefaultInitExpr *Create(const ASTContext &Ctx, SourceLocation Loc,
 FieldDecl *Field, DeclContext *UsedContext,
-Expr *RewrittenInitExpr);
+Expr *InitExpr, bool HasRewrittenInit);
 
   bool hasRewrittenInit() const {
 return CXXDefaultInitExprBits.HasRewrittenInit;
diff --git a/clang/lib/AST/ASTImporter.cpp b/clang/lib/AST/ASTImporter.cpp
index 0c27f6f5df2da..4465c78d05ea1 100644
--- a/clang/lib/AST/ASTImporter.cpp
+++ b/clang/lib/AST/ASTImporter.cpp
@@ -8107,8 +8107,8 @@ ExpectedStmt 
ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
 RewrittenInit = ExprOrErr.get();
   }
   return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr,
-   *ToParamOrErr, RewrittenInit,
-   *UsedContextOrErr);
+   *ToParamOrErr, *UsedContextOrErr,
+   RewrittenInit, E->hasRewrittenInit());
 }
 
 ExpectedStmt
@@ -8814,7 +8814,8 @@ ExpectedStmt 
ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
   }
 
   return CXXDefaultInitExpr::Create(Importer.getToContext(), *ToBeginLocOrErr,
-ToField, *UsedContextOrErr, RewrittenInit);
+ToField, *UsedContextOrErr, RewrittenInit,
+E->hasRewrittenInit());
 }
 
 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) {
diff --git a/clang/lib/AST/ExprCXX.cpp b/clang/lib/AST/ExprCXX.cpp
index 8d2a1b5611ccc..bbbca3a40aca9 100644
--- a/clang/lib/AST/ExprCXX.cpp
+++ b/clang/lib/AST/ExprCXX.cpp
@@ -1013,15 +1013,15 @@ CXXDefau

[clang] [Clang][Interp] Diagnose use sizeless vector type as the argument of `__builtin_vectorelements` (PR #99794)

2024-07-20 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/99794

>From 163c9201ddf944e9e7eeef54a620bcc89fbe9b3d Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sun, 21 Jul 2024 10:54:41 +0800
Subject: [PATCH] [Clang][Interp] Diagnose use sizeless vector type as the
 argument of __builtin_vectorelements

Signed-off-by: yronglin 
---
 clang/lib/AST/Interp/Compiler.cpp | 6 ++
 clang/lib/AST/Interp/Interp.h | 8 
 clang/lib/AST/Interp/Opcodes.td   | 2 ++
 clang/test/SemaCXX/builtin_vectorelements.cpp | 1 +
 4 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index ef579bc5d8972..aeefaf89cfc4b 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -1698,10 +1698,8 @@ bool Compiler::VisitUnaryExprOrTypeTraitExpr(
   if (Kind == UETT_VectorElements) {
 if (const auto *VT = E->getTypeOfArgument()->getAs())
   return this->emitConst(VT->getNumElements(), E);
-
-// FIXME: Apparently we need to catch the fact that a sizeless vector type
-// has been passed and diagnose that (at run time).
-assert(E->getTypeOfArgument()->isSizelessVectorType());
+if (E->getTypeOfArgument()->isSizelessVectorType())
+  return this->emitSizelessVectorElementSize(E);
   }
 
   if (Kind == UETT_VecStep) {
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index f86b787fb034e..412a72059c854 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -29,6 +29,7 @@
 #include "State.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
 #include 
@@ -2735,6 +2736,13 @@ inline bool InvalidDeclRef(InterpState &S, CodePtr OpPC,
   return CheckDeclRef(S, OpPC, DR);
 }
 
+inline bool SizelessVectorElementSize(InterpState &S, CodePtr OpPC) {
+  const SourceRange &ArgRange = S.Current->getRange(OpPC);
+  const Expr *E = S.Current->getExpr(OpPC);
+  S.FFDiag(E, diag::note_constexpr_non_const_vectorelements) << ArgRange;
+  return false;
+}
+
 inline bool Assume(InterpState &S, CodePtr OpPC) {
   const auto Val = S.Stk.pop();
 
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 49ebb156ab2fb..9f29fa9272711 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -733,6 +733,8 @@ def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
 
+def SizelessVectorElementSize : Opcode;
+
 def Assume : Opcode;
 
 def ArrayDecay : Opcode;
diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 59ff09ac72e42..197ab2fd9625e 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -2,6 +2,7 @@
 
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes 
-fexperimental-new-constant-interpreter %s
 
 template 
 using VecT __attribute__((vector_size(16))) = T;

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


[clang] [Clang][Interp] Diagnose use sizeless vector type as the argument of `__builtin_vectorelements` (PR #99794)

2024-07-20 Thread via cfe-commits

https://github.com/yronglin updated 
https://github.com/llvm/llvm-project/pull/99794

>From 163c9201ddf944e9e7eeef54a620bcc89fbe9b3d Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sun, 21 Jul 2024 10:54:41 +0800
Subject: [PATCH 1/2] [Clang][Interp] Diagnose use sizeless vector type as the
 argument of __builtin_vectorelements

Signed-off-by: yronglin 
---
 clang/lib/AST/Interp/Compiler.cpp | 6 ++
 clang/lib/AST/Interp/Interp.h | 8 
 clang/lib/AST/Interp/Opcodes.td   | 2 ++
 clang/test/SemaCXX/builtin_vectorelements.cpp | 1 +
 4 files changed, 13 insertions(+), 4 deletions(-)

diff --git a/clang/lib/AST/Interp/Compiler.cpp 
b/clang/lib/AST/Interp/Compiler.cpp
index ef579bc5d8972..aeefaf89cfc4b 100644
--- a/clang/lib/AST/Interp/Compiler.cpp
+++ b/clang/lib/AST/Interp/Compiler.cpp
@@ -1698,10 +1698,8 @@ bool Compiler::VisitUnaryExprOrTypeTraitExpr(
   if (Kind == UETT_VectorElements) {
 if (const auto *VT = E->getTypeOfArgument()->getAs())
   return this->emitConst(VT->getNumElements(), E);
-
-// FIXME: Apparently we need to catch the fact that a sizeless vector type
-// has been passed and diagnose that (at run time).
-assert(E->getTypeOfArgument()->isSizelessVectorType());
+if (E->getTypeOfArgument()->isSizelessVectorType())
+  return this->emitSizelessVectorElementSize(E);
   }
 
   if (Kind == UETT_VecStep) {
diff --git a/clang/lib/AST/Interp/Interp.h b/clang/lib/AST/Interp/Interp.h
index f86b787fb034e..412a72059c854 100644
--- a/clang/lib/AST/Interp/Interp.h
+++ b/clang/lib/AST/Interp/Interp.h
@@ -29,6 +29,7 @@
 #include "State.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/Expr.h"
+#include "clang/Basic/DiagnosticSema.h"
 #include "llvm/ADT/APFloat.h"
 #include "llvm/ADT/APSInt.h"
 #include 
@@ -2735,6 +2736,13 @@ inline bool InvalidDeclRef(InterpState &S, CodePtr OpPC,
   return CheckDeclRef(S, OpPC, DR);
 }
 
+inline bool SizelessVectorElementSize(InterpState &S, CodePtr OpPC) {
+  const SourceRange &ArgRange = S.Current->getRange(OpPC);
+  const Expr *E = S.Current->getExpr(OpPC);
+  S.FFDiag(E, diag::note_constexpr_non_const_vectorelements) << ArgRange;
+  return false;
+}
+
 inline bool Assume(InterpState &S, CodePtr OpPC) {
   const auto Val = S.Stk.pop();
 
diff --git a/clang/lib/AST/Interp/Opcodes.td b/clang/lib/AST/Interp/Opcodes.td
index 49ebb156ab2fb..9f29fa9272711 100644
--- a/clang/lib/AST/Interp/Opcodes.td
+++ b/clang/lib/AST/Interp/Opcodes.td
@@ -733,6 +733,8 @@ def InvalidDeclRef : Opcode {
   let Args = [ArgDeclRef];
 }
 
+def SizelessVectorElementSize : Opcode;
+
 def Assume : Opcode;
 
 def ArrayDecay : Opcode;
diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 59ff09ac72e42..197ab2fd9625e 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -2,6 +2,7 @@
 
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes 
-fexperimental-new-constant-interpreter %s
 
 template 
 using VecT __attribute__((vector_size(16))) = T;

>From 4767d9e117c1d11b130cf5b4b7cbd95cc32cf8be Mon Sep 17 00:00:00 2001
From: yronglin 
Date: Sun, 21 Jul 2024 11:37:17 +0800
Subject: [PATCH 2/2] Enable more test

Signed-off-by: yronglin 
---
 clang/test/SemaCXX/builtin_vectorelements.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/test/SemaCXX/builtin_vectorelements.cpp 
b/clang/test/SemaCXX/builtin_vectorelements.cpp
index 197ab2fd9625e..b23675ea0ac6a 100644
--- a/clang/test/SemaCXX/builtin_vectorelements.cpp
+++ b/clang/test/SemaCXX/builtin_vectorelements.cpp
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -triple x86_64   -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s
+// RUN: %clang_cc1 -triple x86_64   -std=c++20 
-fsyntax-only -verify -disable-llvm-passes 
-fexperimental-new-constant-interpreter %s
 
 // REQUIRES: aarch64-registered-target
 // RUN: %clang_cc1 -triple aarch64 -target-feature +sve -std=c++20 
-fsyntax-only -verify -disable-llvm-passes %s

___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),

5chmidti wrote:

Please replace
- `StrictModeIsEnabled` with `StrictMode`
- `CountingEnumHeuristicIsEnabled` with `EnableCountingEnumHeuristic`
(+ docs, tests)

https://github.com/llvm/llvm-project/pull/89925
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),
+
has(fieldDecl(hasType(qualType(hasCanonicalType(recordType()
+.bind("union")),
+has(fieldDecl(hasType(qualType(hasCanonicalType(enumType()
+.bind("tags"
+  .bind("root"),
+  this);
+}
+
+static bool isUnion(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isUnionType();
+}
+
+static bool isEnum(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isEnumeralType();
+}
+
+static bool hasMultipleUnionsOrEnums(const RecordDecl *Rec) {
+  return llvm::count_if(Rec->fields(), isUnion) > 1 ||
+ llvm::count_if(Rec->fields(), isEnum) > 1;
+}
+
+static bool signEquals(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isStrictlyPositive()) ||
+ (A.isZero() && B.isZero());
+}
+
+static bool greaterBySign(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNonNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isNonPositive());
+}
+
+bool TaggedUnionMemberCountCheck::isCountingEnumLikeName(
+StringRef Name) const noexcept {
+  if (llvm::any_of(ParsedCountingEnumPrefixes,
+   [&Name](const StringRef &prefix) -> bool {
+ return Name.starts_with_insensitive(prefix);
+   }))
+return true;
+  if (llvm::any_of(ParsedCountingEnumSuffixes,
+   [&Name](const StringRef &suffix) -> bool {
+ return Name.ends_with_insensitive(suffix);
+   }))
+return true;
+  return false;
+}
+
+size_t TaggedUnionMemberCountCheck::getNumberOfValidEnumValues(
+const EnumDecl *Ed) const noexcept {
+  bool FoundMax = false;
+  llvm::APSInt MaxTagValue;
+  llvm::SmallSet EnumValues;
+
+  // Heuristic for counter enum constants.
+  //
+  //   enum tag_with_counter {
+  // tag1,
+  // tag2,
+  // tag_count, <-- Searching for these enum constants
+  //   };
+  //
+  // The final tag count is decreased by 1 if and only if:
+  // 1. There is only one counting enum constant,
+  // 2. The counting enum constant is the last enum constant that is defined,
+  // 3. The value of the counting enum constant is the largest out of every 
enum
+  //constant.
+  // The 'ce' prefix is a shorthand for 'counting enum'.
+  size_t CeCount = 0;
+  bool IsLast = false;
+  llvm::APSInt CeValue = llvm::APSInt::get(0);
+
+  for (const auto &&[index, enumerator] : llvm::enumerate(Ed->enumerators())) {
+const llvm::APSInt Val = enumerator->getInitVal();
+EnumValues.insert(Val);
+if (FoundMax) {
+  if (greaterBySign(Val, MaxTagValue) ||
+  (signEquals(Val, MaxTagValue) && Val > MaxTagValue)) {
+MaxTagValue = Val;
+  }
+} else {
+ 

[clang-tools-extra] [clang-tidy] Add new check bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),
+
has(fieldDecl(hasType(qualType(hasCanonicalType(recordType()
+.bind("union")),
+has(fieldDecl(hasType(qualType(hasCanonicalType(enumType()
+.bind("tags"
+  .bind("root"),
+  this);
+}
+
+static bool isUnion(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isUnionType();
+}
+
+static bool isEnum(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isEnumeralType();
+}
+
+static bool hasMultipleUnionsOrEnums(const RecordDecl *Rec) {
+  return llvm::count_if(Rec->fields(), isUnion) > 1 ||
+ llvm::count_if(Rec->fields(), isEnum) > 1;
+}
+
+static bool signEquals(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isStrictlyPositive()) ||
+ (A.isZero() && B.isZero());
+}
+
+static bool greaterBySign(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNonNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isNonPositive());
+}
+
+bool TaggedUnionMemberCountCheck::isCountingEnumLikeName(
+StringRef Name) const noexcept {
+  if (llvm::any_of(ParsedCountingEnumPrefixes,
+   [&Name](const StringRef &prefix) -> bool {
+ return Name.starts_with_insensitive(prefix);
+   }))
+return true;
+  if (llvm::any_of(ParsedCountingEnumSuffixes,
+   [&Name](const StringRef &suffix) -> bool {
+ return Name.ends_with_insensitive(suffix);
+   }))
+return true;

5chmidti wrote:

Please use CamelCase for these two lambda parameters

https://github.com/llvm/llvm-project/pull/89925
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),
+
has(fieldDecl(hasType(qualType(hasCanonicalType(recordType()
+.bind("union")),
+has(fieldDecl(hasType(qualType(hasCanonicalType(enumType()
+.bind("tags"
+  .bind("root"),
+  this);
+}
+
+static bool isUnion(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isUnionType();
+}
+
+static bool isEnum(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isEnumeralType();
+}
+
+static bool hasMultipleUnionsOrEnums(const RecordDecl *Rec) {
+  return llvm::count_if(Rec->fields(), isUnion) > 1 ||
+ llvm::count_if(Rec->fields(), isEnum) > 1;
+}
+
+static bool signEquals(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isStrictlyPositive()) ||
+ (A.isZero() && B.isZero());
+}
+
+static bool greaterBySign(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNonNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isNonPositive());
+}
+
+bool TaggedUnionMemberCountCheck::isCountingEnumLikeName(
+StringRef Name) const noexcept {
+  if (llvm::any_of(ParsedCountingEnumPrefixes,
+   [&Name](const StringRef &prefix) -> bool {
+ return Name.starts_with_insensitive(prefix);
+   }))
+return true;
+  if (llvm::any_of(ParsedCountingEnumSuffixes,
+   [&Name](const StringRef &suffix) -> bool {
+ return Name.ends_with_insensitive(suffix);
+   }))
+return true;
+  return false;
+}
+
+size_t TaggedUnionMemberCountCheck::getNumberOfValidEnumValues(
+const EnumDecl *Ed) const noexcept {
+  bool FoundMax = false;
+  llvm::APSInt MaxTagValue;
+  llvm::SmallSet EnumValues;
+
+  // Heuristic for counter enum constants.
+  //
+  //   enum tag_with_counter {
+  // tag1,
+  // tag2,
+  // tag_count, <-- Searching for these enum constants
+  //   };
+  //
+  // The final tag count is decreased by 1 if and only if:
+  // 1. There is only one counting enum constant,
+  // 2. The counting enum constant is the last enum constant that is defined,
+  // 3. The value of the counting enum constant is the largest out of every 
enum
+  //constant.
+  // The 'ce' prefix is a shorthand for 'counting enum'.
+  size_t CeCount = 0;
+  bool IsLast = false;
+  llvm::APSInt CeValue = llvm::APSInt::get(0);
+
+  for (const auto &&[index, enumerator] : llvm::enumerate(Ed->enumerators())) {

5chmidti wrote:

CamelCase

https://github.com/llvm/llvm-project/pull/89925
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),
+
has(fieldDecl(hasType(qualType(hasCanonicalType(recordType()
+.bind("union")),
+has(fieldDecl(hasType(qualType(hasCanonicalType(enumType()
+.bind("tags"
+  .bind("root"),
+  this);
+}
+
+static bool isUnion(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isUnionType();
+}
+
+static bool isEnum(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isEnumeralType();
+}
+
+static bool hasMultipleUnionsOrEnums(const RecordDecl *Rec) {
+  return llvm::count_if(Rec->fields(), isUnion) > 1 ||
+ llvm::count_if(Rec->fields(), isEnum) > 1;
+}
+
+static bool signEquals(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isStrictlyPositive()) ||
+ (A.isZero() && B.isZero());
+}
+
+static bool greaterBySign(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNonNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isNonPositive());
+}
+
+bool TaggedUnionMemberCountCheck::isCountingEnumLikeName(
+StringRef Name) const noexcept {
+  if (llvm::any_of(ParsedCountingEnumPrefixes,
+   [&Name](const StringRef &prefix) -> bool {
+ return Name.starts_with_insensitive(prefix);
+   }))
+return true;
+  if (llvm::any_of(ParsedCountingEnumSuffixes,
+   [&Name](const StringRef &suffix) -> bool {
+ return Name.ends_with_insensitive(suffix);
+   }))
+return true;
+  return false;
+}
+
+size_t TaggedUnionMemberCountCheck::getNumberOfValidEnumValues(
+const EnumDecl *Ed) const noexcept {
+  bool FoundMax = false;
+  llvm::APSInt MaxTagValue;
+  llvm::SmallSet EnumValues;
+
+  // Heuristic for counter enum constants.
+  //
+  //   enum tag_with_counter {
+  // tag1,
+  // tag2,
+  // tag_count, <-- Searching for these enum constants
+  //   };
+  //
+  // The final tag count is decreased by 1 if and only if:
+  // 1. There is only one counting enum constant,
+  // 2. The counting enum constant is the last enum constant that is defined,
+  // 3. The value of the counting enum constant is the largest out of every 
enum
+  //constant.
+  // The 'ce' prefix is a shorthand for 'counting enum'.
+  size_t CeCount = 0;
+  bool IsLast = false;
+  llvm::APSInt CeValue = llvm::APSInt::get(0);
+
+  for (const auto &&[index, enumerator] : llvm::enumerate(Ed->enumerators())) {
+const llvm::APSInt Val = enumerator->getInitVal();
+EnumValues.insert(Val);
+if (FoundMax) {
+  if (greaterBySign(Val, MaxTagValue) ||
+  (signEquals(Val, MaxTagValue) && Val > MaxTagValue)) {
+MaxTagValue = Val;
+  }

5ch

[clang-tools-extra] [clang-tidy] Add new check bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),

5chmidti wrote:

All arguments passed to `recordDecl` are already behaving as if they were 
passed to an `allOf` matcher, so you can remove the `allOf`.

`recordDecl(foo(), bar())` has the same meaning as `recordDecl(allOf(foo(), 
bar()))`

https://github.com/llvm/llvm-project/pull/89925
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 





5chmidti wrote:

I'm not sure that we need to test `.m` and `.mm` files

https://github.com/llvm/llvm-project/pull/89925
___
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 bugprone-tagged-union-member-count (PR #89925)

2024-07-20 Thread Julian Schmidt via cfe-commits
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= ,
=?utf-8?b?R8OhYm9yIFTDs3RodsOhcmk=?= 
Message-ID:
In-Reply-To: 



@@ -0,0 +1,182 @@
+//===--- TaggedUnionMemberCountCheck.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 "TaggedUnionMemberCountCheck.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "llvm/ADT/STLExtras.h"
+#include "llvm/ADT/SmallSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+TaggedUnionMemberCountCheck::TaggedUnionMemberCountCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  StrictModeIsEnabled(Options.get(StrictModeIsEnabledOptionName, true)),
+  CountingEnumHeuristicIsEnabled(
+  Options.get(CountingEnumHeuristicIsEnabledOptionName, true)),
+  RawCountingEnumPrefixes(Options.get(CountingEnumPrefixesOptionName, "")),
+  RawCountingEnumSuffixes(
+  Options.get(CountingEnumSuffixesOptionName, "count")),
+  ParsedCountingEnumPrefixes(
+  utils::options::parseStringList(RawCountingEnumPrefixes)),
+  ParsedCountingEnumSuffixes(
+  utils::options::parseStringList(RawCountingEnumSuffixes)) {}
+
+void TaggedUnionMemberCountCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, StrictModeIsEnabledOptionName, StrictModeIsEnabled);
+  Options.store(Opts, CountingEnumHeuristicIsEnabledOptionName,
+CountingEnumHeuristicIsEnabled);
+  Options.store(Opts, CountingEnumPrefixesOptionName, RawCountingEnumPrefixes);
+  Options.store(Opts, CountingEnumSuffixesOptionName, RawCountingEnumSuffixes);
+}
+
+void TaggedUnionMemberCountCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  recordDecl(
+  allOf(anyOf(isStruct(), isClass()),
+
has(fieldDecl(hasType(qualType(hasCanonicalType(recordType()
+.bind("union")),
+has(fieldDecl(hasType(qualType(hasCanonicalType(enumType()
+.bind("tags"
+  .bind("root"),
+  this);
+}
+
+static bool isUnion(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isUnionType();
+}
+
+static bool isEnum(const FieldDecl *R) {
+  return R->getType().getCanonicalType().getTypePtr()->isEnumeralType();
+}
+
+static bool hasMultipleUnionsOrEnums(const RecordDecl *Rec) {
+  return llvm::count_if(Rec->fields(), isUnion) > 1 ||
+ llvm::count_if(Rec->fields(), isEnum) > 1;
+}
+
+static bool signEquals(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isStrictlyPositive()) ||
+ (A.isZero() && B.isZero());
+}
+
+static bool greaterBySign(const llvm::APSInt &A, const llvm::APSInt &B) {
+  return (A.isNonNegative() && B.isNegative()) ||
+ (A.isStrictlyPositive() && B.isNonPositive());
+}
+
+bool TaggedUnionMemberCountCheck::isCountingEnumLikeName(
+StringRef Name) const noexcept {
+  if (llvm::any_of(ParsedCountingEnumPrefixes,
+   [&Name](const StringRef &prefix) -> bool {
+ return Name.starts_with_insensitive(prefix);
+   }))
+return true;
+  if (llvm::any_of(ParsedCountingEnumSuffixes,
+   [&Name](const StringRef &suffix) -> bool {
+ return Name.ends_with_insensitive(suffix);
+   }))
+return true;
+  return false;
+}
+
+size_t TaggedUnionMemberCountCheck::getNumberOfValidEnumValues(
+const EnumDecl *Ed) const noexcept {
+  bool FoundMax = false;
+  llvm::APSInt MaxTagValue;
+  llvm::SmallSet EnumValues;
+
+  // Heuristic for counter enum constants.
+  //
+  //   enum tag_with_counter {
+  // tag1,
+  // tag2,
+  // tag_count, <-- Searching for these enum constants
+  //   };
+  //
+  // The final tag count is decreased by 1 if and only if:
+  // 1. There is only one counting enum constant,
+  // 2. The counting enum constant is the last enum constant that is defined,
+  // 3. The value of the counting enum constant is the largest out of every 
enum
+  //constant.
+  // The 'ce' prefix is a shorthand for 'counting enum'.
+  size_t CeCount = 0;
+  bool IsLast = false;
+  llvm::APSInt CeValue = llvm::APSInt::get(0);
+
+  for (const auto &&[index, enumerator] : llvm::enumerate(Ed->enumerators())) {
+const llvm::APSInt Val = enumerator->getInitVal();
+EnumValues.insert(Val);
+if (FoundMax) {
+  if (greaterBySign(Val, MaxTagValue) ||
+  (signEquals(Val, MaxTagValue) && Val > MaxTagValue)) {
+MaxTagValue = Val;
+  }
+} else {
+ 

  1   2   >