[clang] [clang][bytecode] Don't discard all void-types expressions (PR #105625)

2024-08-22 Thread Timm Baeder via cfe-commits

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

For void-types InitListExprs, we need to diagnose them as invalid. But only if 
we are _not_ discarding.

>From 11c6e8da7bcdb2f4ad358fc346bf603f25cc62aa Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 22 Aug 2024 09:06:10 +0200
Subject: [PATCH] [clang][bytecode] Don't discard all void-types expressions

For void-types InitListExprs, we need to diagnose them as invalid. But
only if we are _not_ discarding.
---
 clang/lib/AST/ByteCode/Compiler.cpp  | 23 +--
 clang/test/AST/ByteCode/literals.cpp |  1 +
 2 files changed, 10 insertions(+), 14 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 6d05f75131640a..10f3222726fd43 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1318,15 +1318,6 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
-
-  QualType QT = E->getType();
-
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1336,6 +1327,13 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType())
+return this->emitInvalid(E);
+
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3251,12 +3249,9 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
-  if (E->getType()->isVoidType())
-return this->discard(E);
-
   // Create local variable to hold the return value.
-  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
-  !classify(E->getType())) {
+  if (!E->getType()->isVoidType() && !E->isGLValue() &&
+  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;
diff --git a/clang/test/AST/ByteCode/literals.cpp 
b/clang/test/AST/ByteCode/literals.cpp
index a46f6ed747ec2f..2329d4d973f01d 100644
--- a/clang/test/AST/ByteCode/literals.cpp
+++ b/clang/test/AST/ByteCode/literals.cpp
@@ -46,6 +46,7 @@ static_assert(Failed2 == 0, ""); // both-error {{not an 
integral constant expres
  // both-note {{initializer of 'Failed2' is 
not a constant expression}}
 
 const int x = *(volatile int*)0x1234;
+static_assert((void{}, true), "");
 
 namespace ScalarTypes {
   constexpr int ScalarInitInt = int();

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


[clang] [llvm] [ValueTracking] use KnownBits to compute fpclass from bitcast (PR #97762)

2024-08-22 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

Reverse ping :)


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


[clang] [clang][bytecode] Don't discard all void-types expressions (PR #105625)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

For void-types InitListExprs, we need to diagnose them as invalid. But only if 
we are _not_ discarding.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+9-14) 
- (modified) clang/test/AST/ByteCode/literals.cpp (+1) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 6d05f75131640a..10f3222726fd43 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1318,15 +1318,6 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
-
-  QualType QT = E->getType();
-
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1336,6 +1327,13 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType())
+return this->emitInvalid(E);
+
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3251,12 +3249,9 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
-  if (E->getType()->isVoidType())
-return this->discard(E);
-
   // Create local variable to hold the return value.
-  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
-  !classify(E->getType())) {
+  if (!E->getType()->isVoidType() && !E->isGLValue() &&
+  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;
diff --git a/clang/test/AST/ByteCode/literals.cpp 
b/clang/test/AST/ByteCode/literals.cpp
index a46f6ed747ec2f..2329d4d973f01d 100644
--- a/clang/test/AST/ByteCode/literals.cpp
+++ b/clang/test/AST/ByteCode/literals.cpp
@@ -46,6 +46,7 @@ static_assert(Failed2 == 0, ""); // both-error {{not an 
integral constant expres
  // both-note {{initializer of 'Failed2' is 
not a constant expression}}
 
 const int x = *(volatile int*)0x1234;
+static_assert((void{}, true), "");
 
 namespace ScalarTypes {
   constexpr int ScalarInitInt = int();

``




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


[clang] [clang-format] Correctly compute SplitPenalty of TrailingReturnArrow (PR #105613)

2024-08-22 Thread via cfe-commits

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


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


[clang] [clang-format] Correctly compute SplitPenalty of TrailingReturnArrow (PR #105613)

2024-08-22 Thread via cfe-commits


@@ -4050,7 +4050,7 @@ void 
TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) const {
  ChildSize + Current->SpacesRequiredBefore;
 }
 
-if (Current->is(TT_CtorInitializerColon))
+if (Current->isOneOf(TT_CtorInitializerColon, TT_LambdaLSquare))

mydeveloperday wrote:

is this bit tested or unrelated?

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


[clang] [clang] Merge lifetimebound and GSL code paths for lifetime analysis (PR #104906)

2024-08-22 Thread Utkarsh Saxena via cfe-commits

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


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


[clang] [clang] Merge lifetimebound and GSL code paths for lifetime analysis (PR #104906)

2024-08-22 Thread Haojian Wu via cfe-commits

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

>From d4778d06b71b34aa178ae7482c15a8e00d9f3f19 Mon Sep 17 00:00:00 2001
From: Haojian Wu 
Date: Tue, 20 Aug 2024 10:22:44 +0200
Subject: [PATCH 1/4] [clang] Merge the lifetimebound and GSL code paths for
 lifetime analysis.

---
 clang/docs/ReleaseNotes.rst   |   2 +
 clang/lib/Sema/CheckExprLifetime.cpp  | 129 --
 .../Sema/warn-lifetime-analysis-nocfg.cpp |  13 ++
 3 files changed, 72 insertions(+), 72 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5c156a9c073a9c..bb47350f76b308 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -239,6 +239,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Don't emit duplicated dangling diagnostics. (#GH93386).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7389046eaddde1..06eb909659d05d 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -326,66 +326,6 @@ static bool shouldTrackFirstArgument(const FunctionDecl 
*FD) {
   return false;
 }
 
-static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
-LocalVisitor Visit) {
-  auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
-// We are not interested in the temporary base objects of gsl Pointers:
-//   Temp().ptr; // Here ptr might not dangle.
-if (isa(Arg->IgnoreImpCasts()))
-  return;
-// Once we initialized a value with a reference, it can no longer dangle.
-if (!Value) {
-  for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
-if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
-  continue;
-if (PE.Kind == IndirectLocalPathEntry::GslPointerInit ||
-PE.Kind == IndirectLocalPathEntry::GslPointerAssignment)
-  return;
-break;
-  }
-}
-Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
-  : IndirectLocalPathEntry::GslReferenceInit,
-Arg, D});
-if (Arg->isGLValue())
-  visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit,
-/*EnableLifetimeWarnings=*/true);
-else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
-   /*EnableLifetimeWarnings=*/true);
-Path.pop_back();
-  };
-
-  if (auto *MCE = dyn_cast(Call)) {
-const auto *MD = cast_or_null(MCE->getDirectCallee());
-if (MD && shouldTrackImplicitObjectArg(MD))
-  VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
-  !MD->getReturnType()->isReferenceType());
-return;
-  } else if (auto *OCE = dyn_cast(Call)) {
-FunctionDecl *Callee = OCE->getDirectCallee();
-if (Callee && Callee->isCXXInstanceMember() &&
-shouldTrackImplicitObjectArg(cast(Callee)))
-  VisitPointerArg(Callee, OCE->getArg(0),
-  !Callee->getReturnType()->isReferenceType());
-return;
-  } else if (auto *CE = dyn_cast(Call)) {
-FunctionDecl *Callee = CE->getDirectCallee();
-if (Callee && shouldTrackFirstArgument(Callee))
-  VisitPointerArg(Callee, CE->getArg(0),
-  !Callee->getReturnType()->isReferenceType());
-return;
-  }
-
-  if (auto *CCE = dyn_cast(Call)) {
-const auto *Ctor = CCE->getConstructor();
-const CXXRecordDecl *RD = Ctor->getParent();
-if (CCE->getNumArgs() > 0 && RD->hasAttr())
-  VisitPointerArg(Ctor->getParamDecl(0), CCE->getArgs()[0], true);
-  }
-}
-
 static bool implicitObjectParamIsLifetimeBound(const FunctionDecl *FD) {
   const TypeSourceInfo *TSI = FD->getTypeSourceInfo();
   if (!TSI)
@@ -423,8 +363,10 @@ static bool implicitObjectParamIsLifetimeBound(const 
FunctionDecl *FD) {
   return false;
 }
 
-static void visitLifetimeBoundArguments(IndirectLocalPath &Path, Expr *Call,
-LocalVisitor Visit) {
+// Visit lifetimebound or gsl-pointer arguments.
+static void visitFunctionCallArguments(IndirectLocalPath &Path, Expr *Call,
+   LocalVisitor Visit,
+   bool EnableLifetimeWarnings) {
   const FunctionDecl *Callee;
   ArrayRef Args;
 
@@ -458,6 +400,35 @@ static void visitLifetimeBoundArguments(IndirectLocalPath 
&Path, Expr *Call,
/*EnableLifetimeWarnings=*/false);
 Path.pop_back();
   };
+  auto VisitGSLPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
+// We are not interested in the temporary base objects of gsl

[clang] [clang-format] Treat new expressions as simple functions (PR #105168)

2024-08-22 Thread via cfe-commits


@@ -848,6 +848,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   const auto IsSimpleFunction = [&](const FormatToken &Tok) {
 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
   return false;
+if (Tok.is(tok::kw_new))
+  return true;

mydeveloperday wrote:

Should we leave a simple comment? I feel like at some point someone will 
complain that AlwaysBreak doesn't always Break.

I spent a bit of time here wondering if it should return true or skip to the 
next argument, I'm in two minds but I think this is ok.

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


[clang] [llvm] [PGO][OpenMP] Instrumentation for GPU devices (Revision of #76587) (PR #102691)

2024-08-22 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `sanitizer-x86_64-linux` 
running on `sanitizer-buildbot2` while building `clang,llvm,offload` at step 2 
"annotate".

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

Here is the relevant piece of the build log for the reference:
```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
[373/378] Generating MSAN_INST_GTEST.gtest-all.cc.x86_64.o
[374/378] Generating MSAN_INST_TEST_OBJECTS.msan_test.cpp.x86_64-with-call.o
[375/378] Generating Msan-x86_64-with-call-Test
[376/378] Generating MSAN_INST_TEST_OBJECTS.msan_test.cpp.x86_64.o
[377/378] Generating Msan-x86_64-Test
[377/378] Running compiler_rt regression tests
llvm-lit: 
/home/b/sanitizer-x86_64-linux/build/llvm-project/llvm/utils/lit/lit/discovery.py:276:
 warning: input 
'/home/b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/rtsan/X86_64LinuxConfig'
 contained no tests
llvm-lit: 
/home/b/sanitizer-x86_64-linux/build/llvm-project/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 900 seconds was requested on the command line. Forcing 
timeout to be 900 seconds.
-- Testing: 10138 tests, 88 workers --
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60
FAIL: SanitizerCommon-hwasan-x86_64-Linux :: Linux/soft_rss_limit_mb_test.cpp 
(6646 of 10138)
 TEST 'SanitizerCommon-hwasan-x86_64-Linux :: 
Linux/soft_rss_limit_mb_test.cpp' FAILED 
Exit Code: 1

Command Output (stderr):
--
RUN: at line 2: /home/b/sanitizer-x86_64-linux/build/build_default/./bin/clang  
--driver-mode=g++ -gline-tables-only -fsanitize=hwaddress -fuse-ld=lld 
-fsanitize-hwaddress-experimental-aliasing  -m64 -funwind-tables  
-I/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test -ldl -O2 
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp
 -o 
/home/b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/hwasan-x86_64-Linux/Linux/Output/soft_rss_limit_mb_test.cpp.tmp
+ /home/b/sanitizer-x86_64-linux/build/build_default/./bin/clang 
--driver-mode=g++ -gline-tables-only -fsanitize=hwaddress -fuse-ld=lld 
-fsanitize-hwaddress-experimental-aliasing -m64 -funwind-tables 
-I/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test -ldl -O2 
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp
 -o 
/home/b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/hwasan-x86_64-Linux/Linux/Output/soft_rss_limit_mb_test.cpp.tmp
RUN: at line 5: env 
HWASAN_OPTIONS=soft_rss_limit_mb=220:quarantine_size=1:allocator_may_return_null=1
  
/home/b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/hwasan-x86_64-Linux/Linux/Output/soft_rss_limit_mb_test.cpp.tmp
 2>&1 | FileCheck 
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp
 -check-prefix=CHECK_MAY_RETURN_1
+ env 
HWASAN_OPTIONS=soft_rss_limit_mb=220:quarantine_size=1:allocator_may_return_null=1
 
/home/b/sanitizer-x86_64-linux/build/build_default/runtimes/runtimes-bins/compiler-rt/test/sanitizer_common/hwasan-x86_64-Linux/Linux/Output/soft_rss_limit_mb_test.cpp.tmp
+ FileCheck 
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp
 -check-prefix=CHECK_MAY_RETURN_1
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp:68:24:
 error: CHECK_MAY_RETURN_1: expected string not found in input
// CHECK_MAY_RETURN_1: allocating 512 times
   ^
:52:44: note: scanning from here
Some of the malloc calls returned non-null: 229
   ^
:52:45: note: possible intended match here
Some of the malloc calls returned non-null: 229
^

Input file: 
Check file: 
/home/b/sanitizer-x86_64-linux/build/llvm-project/compiler-rt/test/sanitizer_common/TestCases/Linux/soft_rss_limit_mb_test.cpp

-dump-input=help explains the following input dump.

Input was:
<<
.
.
.
   47:  [256] 
   48:  [320] 
   49:  [384] 
   50:  [448] 
   51: Some of the malloc calls returned null: 283 
   52: Some of the malloc calls returned non-null: 229 
check:68'0X error: no match 
found
check:68'1 ?possible 
intended match
Step 14 (test compiler

[clang] [clang][bytecode] Don't discard all void-typed expressions (PR #105625)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] c79d1fa - [clang][bytecode] Don't discard all void-typed expressions (#105625)

2024-08-22 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-22T09:51:16+02:00
New Revision: c79d1fa540390f6e37e1ea326153559eeadd0de6

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

LOG: [clang][bytecode] Don't discard all void-typed expressions (#105625)

For void-types InitListExprs, we need to diagnose them as invalid. But
only if we are _not_ discarding.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/test/AST/ByteCode/literals.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 6d05f75131640a..10f3222726fd43 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -1318,15 +1318,6 @@ bool Compiler::VisitArraySubscriptExpr(const 
ArraySubscriptExpr *E) {
 template 
 bool Compiler::visitInitList(ArrayRef Inits,
   const Expr *ArrayFiller, const Expr *E) {
-
-  QualType QT = E->getType();
-
-  if (const auto *AT = QT->getAs())
-QT = AT->getValueType();
-
-  if (QT->isVoidType())
-return this->emitInvalid(E);
-
   // Handle discarding first.
   if (DiscardResult) {
 for (const Expr *Init : Inits) {
@@ -1336,6 +1327,13 @@ bool Compiler::visitInitList(ArrayRef Inits,
 return true;
   }
 
+  QualType QT = E->getType();
+  if (const auto *AT = QT->getAs())
+QT = AT->getValueType();
+
+  if (QT->isVoidType())
+return this->emitInvalid(E);
+
   // Primitive values.
   if (std::optional T = classify(QT)) {
 assert(!DiscardResult);
@@ -3251,12 +3249,9 @@ template  bool 
Compiler::visit(const Expr *E) {
   if (E->getType().isNull())
 return false;
 
-  if (E->getType()->isVoidType())
-return this->discard(E);
-
   // Create local variable to hold the return value.
-  if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
-  !classify(E->getType())) {
+  if (!E->getType()->isVoidType() && !E->isGLValue() &&
+  !E->getType()->isAnyComplexType() && !classify(E->getType())) {
 std::optional LocalIndex = allocateLocal(E);
 if (!LocalIndex)
   return false;

diff  --git a/clang/test/AST/ByteCode/literals.cpp 
b/clang/test/AST/ByteCode/literals.cpp
index a46f6ed747ec2f..2329d4d973f01d 100644
--- a/clang/test/AST/ByteCode/literals.cpp
+++ b/clang/test/AST/ByteCode/literals.cpp
@@ -46,6 +46,7 @@ static_assert(Failed2 == 0, ""); // both-error {{not an 
integral constant expres
  // both-note {{initializer of 'Failed2' is 
not a constant expression}}
 
 const int x = *(volatile int*)0x1234;
+static_assert((void{}, true), "");
 
 namespace ScalarTypes {
   constexpr int ScalarInitInt = int();



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


[clang] [clang][bytecode] Don't discard all void-typed expressions (PR #105625)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] clang-format: Add "AllowShortNamespacesOnASingleLine" option (PR #105597)

2024-08-22 Thread via cfe-commits

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


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


[clang] clang-format: Add "AllowShortNamespacesOnASingleLine" option (PR #105597)

2024-08-22 Thread via cfe-commits


@@ -616,6 +625,62 @@ class LineJoiner {
 return 1;
   }
 
+  unsigned tryMergeNamespace(SmallVectorImpl::const_iterator 
I,
+ SmallVectorImpl::const_iterator 
E,
+ unsigned Limit) {
+if (Limit == 0)
+  return 0;
+if (I[1]->InPPDirective != (*I)->InPPDirective ||
+(I[1]->InPPDirective && I[1]->First->HasUnescapedNewline)) {
+  return 0;
+}
+if (I + 2 == E || I[2]->Type == LT_Invalid)
+  return 0;
+
+Limit = limitConsideringMacros(I + 1, E, Limit);
+
+if (!nextTwoLinesFitInto(I, Limit))
+  return 0;
+
+// Check if it's a namespace inside a namespace, and call recursively if so
+// '3' is the sizes of the whitespace and closing brace for " _inner_ }"
+if (I[1]->First->is(tok::kw_namespace)) {
+  if (I[1]->Last->is(TT_LineComment))
+return 0;
+
+  unsigned inner_limit = Limit - I[1]->Last->TotalLength - 3;

mydeveloperday wrote:

Local variables are normally `PascalCase`

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


[clang] [clang-repl] Teach clang-repl how to load PCHs. (PR #94166)

2024-08-22 Thread Vassil Vassilev via cfe-commits

https://github.com/vgvassilev updated 
https://github.com/llvm/llvm-project/pull/94166

>From 629683d9236c34b8e5c4bde01dcbe5a2b7c306c0 Mon Sep 17 00:00:00 2001
From: Vassil Vassilev 
Date: Thu, 30 May 2024 05:05:41 +
Subject: [PATCH 1/2] [clang-repl] Teach clang-repl how to load PCHs.

---
 clang/include/clang/CodeGen/ModuleBuilder.h |  6 ++
 clang/lib/CodeGen/BackendConsumer.h |  5 -
 clang/lib/CodeGen/CodeGenAction.cpp |  6 +-
 clang/lib/CodeGen/ModuleBuilder.cpp |  8 
 clang/lib/Interpreter/IncrementalParser.cpp |  4 
 clang/test/Interpreter/execute-pch.cpp  | 14 ++
 6 files changed, 33 insertions(+), 10 deletions(-)
 create mode 100644 clang/test/Interpreter/execute-pch.cpp

diff --git a/clang/include/clang/CodeGen/ModuleBuilder.h 
b/clang/include/clang/CodeGen/ModuleBuilder.h
index 59b9840d02e086..f1b8229edd362e 100644
--- a/clang/include/clang/CodeGen/ModuleBuilder.h
+++ b/clang/include/clang/CodeGen/ModuleBuilder.h
@@ -52,6 +52,12 @@ namespace CodeGen {
 class CodeGenerator : public ASTConsumer {
   virtual void anchor();
 
+protected:
+  /// True if we've finished generating IR. This prevents us from generating
+  /// additional LLVM IR after emitting output in HandleTranslationUnit. This
+  /// can happen when Clang plugins trigger additional AST deserialization.
+  bool IRGenFinished = false;
+
 public:
   /// Return an opaque reference to the CodeGenModule object, which can
   /// be used in various secondary APIs.  It is valid as long as the
diff --git a/clang/lib/CodeGen/BackendConsumer.h 
b/clang/lib/CodeGen/BackendConsumer.h
index a023d29cbd1d73..a4d737aa2e5876 100644
--- a/clang/lib/CodeGen/BackendConsumer.h
+++ b/clang/lib/CodeGen/BackendConsumer.h
@@ -41,11 +41,6 @@ class BackendConsumer : public ASTConsumer {
   llvm::Timer LLVMIRGeneration;
   unsigned LLVMIRGenerationRefCount;
 
-  /// True if we've finished generating IR. This prevents us from generating
-  /// additional LLVM IR after emitting output in HandleTranslationUnit. This
-  /// can happen when Clang plugins trigger additional AST deserialization.
-  bool IRGenFinished = false;
-
   bool TimerIsEnabled = false;
 
   std::unique_ptr Gen;
diff --git a/clang/lib/CodeGen/CodeGenAction.cpp 
b/clang/lib/CodeGen/CodeGenAction.cpp
index e87226e60297c0..0ffc5119f19c54 100644
--- a/clang/lib/CodeGen/CodeGenAction.cpp
+++ b/clang/lib/CodeGen/CodeGenAction.cpp
@@ -221,9 +221,7 @@ void 
BackendConsumer::HandleInlineFunctionDefinition(FunctionDecl *D) {
 }
 
 void BackendConsumer::HandleInterestingDecl(DeclGroupRef D) {
-  // Ignore interesting decls from the AST reader after IRGen is finished.
-  if (!IRGenFinished)
-HandleTopLevelDecl(D);
+  HandleTopLevelDecl(D);
 }
 
 // Links each entry in LinkModules into our module. Returns true on error.
@@ -280,8 +278,6 @@ void BackendConsumer::HandleTranslationUnit(ASTContext &C) {
   if (LLVMIRGenerationRefCount == 0)
 LLVMIRGeneration.stopTimer();
 }
-
-IRGenFinished = true;
   }
 
   // Silently ignore if we weren't initialized for some reason.
diff --git a/clang/lib/CodeGen/ModuleBuilder.cpp 
b/clang/lib/CodeGen/ModuleBuilder.cpp
index d4e0ab0339a8b0..1be9f286ab932b 100644
--- a/clang/lib/CodeGen/ModuleBuilder.cpp
+++ b/clang/lib/CodeGen/ModuleBuilder.cpp
@@ -138,6 +138,8 @@ namespace {
   assert(!M && "Replacing existing Module?");
   M.reset(new llvm::Module(ExpandModuleName(ModuleName, CodeGenOpts), C));
 
+  IRGenFinished = false;
+
   std::unique_ptr OldBuilder = std::move(Builder);
 
   Initialize(*Ctx);
@@ -179,6 +181,10 @@ namespace {
 }
 
 bool HandleTopLevelDecl(DeclGroupRef DG) override {
+  // Ignore interesting decls from the AST reader after IRGen is finished.
+  if (IRGenFinished)
+return true; // We can't CodeGen more but pass to other consumers.
+
   // FIXME: Why not return false and abort parsing?
   if (Diags.hasUnrecoverableErrorOccurred())
 return true;
@@ -282,6 +288,8 @@ namespace {
 }
 
 void HandleTranslationUnit(ASTContext &Ctx) override {
+  IRGenFinished = true;
+
   // Release the Builder when there is no error.
   if (!Diags.hasUnrecoverableErrorOccurred() && Builder)
 Builder->Release();
diff --git a/clang/lib/Interpreter/IncrementalParser.cpp 
b/clang/lib/Interpreter/IncrementalParser.cpp
index b7c809c45098ca..831b99c814f325 100644
--- a/clang/lib/Interpreter/IncrementalParser.cpp
+++ b/clang/lib/Interpreter/IncrementalParser.cpp
@@ -219,6 +219,10 @@ IncrementalParser::IncrementalParser(Interpreter &Interp,
   Consumer = &CI->getASTConsumer();
   P.reset(
   new Parser(CI->getPreprocessor(), CI->getSema(), /*SkipBodies=*/false));
+
+  if (ExternalASTSource *External = CI->getASTContext().getExternalSource())
+External->StartTranslationUnit(Consumer);
+
   P->Initialize();
 
   // An initial PTU is needed as CUDA includes some headers automatically
diff --git a/clang/test/In

[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/105043

>From 4aa47d190a84ecd0432dc9b6db1d38b296f4df23 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 20 Aug 2024 06:44:41 -0700
Subject: [PATCH 1/3] [clang-format] Don't insert a space between :: and *

Also, don't insert a space after ::* for method pointers.

See https://github.com/llvm/llvm-project/pull/86253#issuecomment-2298404887.

Fixes #100841.
---
 clang/lib/Format/TokenAnnotator.cpp   | 10 +++---
 clang/unittests/Format/FormatTest.cpp | 36 +--
 clang/unittests/Format/QualifierFixerTest.cpp | 36 +--
 3 files changed, 40 insertions(+), 42 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9d4204655b8ed6..f1f60bc0e8a72b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4478,10 +4478,8 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   }
   if (Left.is(tok::colon))
 return Left.isNot(TT_ObjCMethodExpr);
-  if (Left.is(tok::coloncolon)) {
-return Right.is(tok::star) && Right.is(TT_PointerOrReference) &&
-   Style.PointerAlignment != FormatStyle::PAS_Left;
-  }
+  if (Left.is(tok::coloncolon))
+return false;
   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
 if (Style.Language == FormatStyle::LK_TextProto ||
 (Style.Language == FormatStyle::LK_Proto &&
@@ -4591,7 +4589,9 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 if (!BeforeLeft)
   return false;
 if (BeforeLeft->is(tok::coloncolon)) {
-  return Left.is(tok::star) &&
+  const auto *Prev = BeforeLeft->Previous;
+  return Left.is(tok::star) && Prev &&
+ !Prev->endsSequence(tok::identifier, TT_FunctionTypeLParen) &&
  Style.PointerAlignment != FormatStyle::PAS_Right;
 }
 return !BeforeLeft->isOneOf(tok::l_paren, tok::l_square);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 794ccab3704534..e895f16465491a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3646,8 +3646,8 @@ TEST_F(FormatTest, FormatsClasses) {
": public aaa {};");
   verifyFormat("template \n"
-   "struct A\n"
-   ": A {};");
+   "struct A\n"
+   ": A {};");
   verifyFormat("class ::A::B {};");
 }
 
@@ -11166,10 +11166,10 @@ TEST_F(FormatTest, UnderstandsBinaryOperators) {
 }
 
 TEST_F(FormatTest, UnderstandsPointersToMembers) {
-  verifyFormat("int A:: *x;");
-  verifyFormat("int (S:: *func)(void *);");
-  verifyFormat("void f() { int (S:: *func)(void *); }");
-  verifyFormat("typedef bool *(Class:: *Member)() const;");
+  verifyFormat("int A::*x;");
+  verifyFormat("int (S::*func)(void *);");
+  verifyFormat("void f() { int (S::*func)(void *); }");
+  verifyFormat("typedef bool *(Class::*Member)() const;");
   verifyFormat("void f() {\n"
"  (a->*f)();\n"
"  a->*x;\n"
@@ -11187,16 +11187,16 @@ TEST_F(FormatTest, UnderstandsPointersToMembers) {
 
   FormatStyle Style = getLLVMStyle();
   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
-  verifyFormat("typedef bool *(Class:: *Member)() const;", Style);
-  verifyFormat("void f(int A:: *p) { int A:: *v = &A::B; }", Style);
+  verifyFormat("typedef bool *(Class::*Member)() const;", Style);
+  verifyFormat("void f(int A::*p) { int A::*v = &A::B; }", Style);
 
   Style.PointerAlignment = FormatStyle::PAS_Left;
-  verifyFormat("typedef bool* (Class::* Member)() const;", Style);
+  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
   verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
 
   Style.PointerAlignment = FormatStyle::PAS_Middle;
-  verifyFormat("typedef bool * (Class:: * Member)() const;", Style);
-  verifyFormat("void f(int A:: * p) { int A:: * v = &A::B; }", Style);
+  verifyFormat("typedef bool * (Class::*Member)() const;", Style);
+  verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
 }
 
 TEST_F(FormatTest, UnderstandsUnaryOperators) {
@@ -12539,7 +12539,7 @@ TEST_F(FormatTest, FormatsFunctionTypes) {
   verifyFormat("int (*func)(void *);");
   verifyFormat("void f() { int (*func)(void *); }");
   verifyFormat("template \n"
-   "using Callback = void (CallbackClass:: *)(SomeObject *Data);");
+   "using MyCallback = void (CallbackClass::*)(SomeObject 
*Data);");
 
   verifyGoogleFormat("A;");
   verifyGoogleFormat("void* (*a)(int);");
@@ -19462,13 +19462,13 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
"int   bbb = 0;",
Alignment);
   // http://llvm.org/PR68079
-  verifyFormat("using Fn   = int (A:: *)();\n"
-   "using RFn  = in

[clang] [clang][analyzer] Bring alpha.security.MmapWriteExec checker out of alpha package (PR #102636)

2024-08-22 Thread Balázs Kéri via cfe-commits

balazske wrote:

It is not easy to find an easily compilable (and not too big) project that 
contains `mmap` to test the checker. I could test it with libgit2, can try to 
find more projects to test.

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


[clang] c368a72 - [clang] Merge lifetimebound and GSL code paths for lifetime analysis (#104906)

2024-08-22 Thread via cfe-commits

Author: Haojian Wu
Date: 2024-08-22T10:35:49+02:00
New Revision: c368a720a0b40bb8fe4aff3971fe9a7009c85aa6

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

LOG: [clang] Merge lifetimebound and GSL code paths for lifetime analysis 
(#104906)

In the current lifetime analysis, we have two parallel code paths: one
for lifetimebound and another for GSL. These paths perform the same
logic, both determining whether to continue visiting subexpressions.

This PR merges the two paths into a single code path. As a result, we'll
reduce the overhead by eliminating a redundant visit to subexpressions.
The change is mostly NFC (No Functional Change). The only notable
difference is that when a subexpression is visited due to either
lifetimebound or GSL, we will prioritize the lifetimebound path. This
means the final diagnostic will be -Wdangling (rather than both
`-Wdangling` and `-Wdangling-gsl`)

This might cause a slight change in behavior if the -Wdangling
diagnostic is disabled, but I think this is not a major concern since
both diagnostics are enabled by default.

Fixes #93386

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/CheckExprLifetime.cpp
clang/test/Sema/warn-lifetime-analysis-nocfg.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 5c156a9c073a9c..bb47350f76b308 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -239,6 +239,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses when the result of a [[nodiscard]] function is discarded 
after being cast in C. Fixes #GH104391.
 
+- Don't emit duplicated dangling diagnostics. (#GH93386).
+
 Improvements to Clang's time-trace
 --
 

diff  --git a/clang/lib/Sema/CheckExprLifetime.cpp 
b/clang/lib/Sema/CheckExprLifetime.cpp
index 7389046eaddde1..7e23c08cc79ffb 100644
--- a/clang/lib/Sema/CheckExprLifetime.cpp
+++ b/clang/lib/Sema/CheckExprLifetime.cpp
@@ -237,13 +237,11 @@ static bool pathContainsInit(IndirectLocalPath &Path) {
 
 static void visitLocalsRetainedByInitializer(IndirectLocalPath &Path,
  Expr *Init, LocalVisitor Visit,
- bool RevisitSubinits,
- bool EnableLifetimeWarnings);
+ bool RevisitSubinits);
 
 static void visitLocalsRetainedByReferenceBinding(IndirectLocalPath &Path,
   Expr *Init, ReferenceKind RK,
-  LocalVisitor Visit,
-  bool EnableLifetimeWarnings);
+  LocalVisitor Visit);
 
 template  static bool isRecordWithAttr(QualType Type) {
   if (auto *RD = Type->getAsCXXRecordDecl())
@@ -326,66 +324,6 @@ static bool shouldTrackFirstArgument(const FunctionDecl 
*FD) {
   return false;
 }
 
-static void handleGslAnnotatedTypes(IndirectLocalPath &Path, Expr *Call,
-LocalVisitor Visit) {
-  auto VisitPointerArg = [&](const Decl *D, Expr *Arg, bool Value) {
-// We are not interested in the temporary base objects of gsl Pointers:
-//   Temp().ptr; // Here ptr might not dangle.
-if (isa(Arg->IgnoreImpCasts()))
-  return;
-// Once we initialized a value with a reference, it can no longer dangle.
-if (!Value) {
-  for (const IndirectLocalPathEntry &PE : llvm::reverse(Path)) {
-if (PE.Kind == IndirectLocalPathEntry::GslReferenceInit)
-  continue;
-if (PE.Kind == IndirectLocalPathEntry::GslPointerInit ||
-PE.Kind == IndirectLocalPathEntry::GslPointerAssignment)
-  return;
-break;
-  }
-}
-Path.push_back({Value ? IndirectLocalPathEntry::GslPointerInit
-  : IndirectLocalPathEntry::GslReferenceInit,
-Arg, D});
-if (Arg->isGLValue())
-  visitLocalsRetainedByReferenceBinding(Path, Arg, RK_ReferenceBinding,
-Visit,
-/*EnableLifetimeWarnings=*/true);
-else
-  visitLocalsRetainedByInitializer(Path, Arg, Visit, true,
-   /*EnableLifetimeWarnings=*/true);
-Path.pop_back();
-  };
-
-  if (auto *MCE = dyn_cast(Call)) {
-const auto *MD = cast_or_null(MCE->getDirectCallee());
-if (MD && shouldTrackImplicitObjectArg(MD))
-  VisitPointerArg(MD, MCE->getImplicitObjectArgument(),
-  !MD->getReturnType()->isReferenceType());
-return;
-  } else if (auto *OCE = dyn_cast(Call)) {
-FunctionDecl *Callee

[clang] [clang] Merge lifetimebound and GSL code paths for lifetime analysis (PR #104906)

2024-08-22 Thread Haojian Wu via cfe-commits

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


[clang] [clang][ASTImporter] set nonnull type for var specialized from lambda template (PR #105492)

2024-08-22 Thread Balázs Kéri via cfe-commits

balazske wrote:

This fix looks good, but I can not tell now why it would not work to import the 
type just before construction of the `VarTemplateSpecializationDecl`. I tried 
it and all tests passed. Probably I can test this on a set of projects.

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


[clang] [llvm] [Clang][AArch64] Add customisable immediate range checking to NEON (PR #100278)

2024-08-22 Thread via cfe-commits


@@ -2142,84 +2159,44 @@ void NeonEmitter::genOverloadTypeCheckCode(raw_ostream 
&OS,
   OS << "#endif\n\n";
 }
 
-void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
-SmallVectorImpl &Defs) {
-  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
+void NeonEmitter::genNeonImmCheckTypes(raw_ostream &OS) {
+  OS << "#ifdef GET_NEON_IMMCHECKTYPES\n";
+
+  for (auto *RV : Records.getAllDerivedDefinitions("ImmCheckType")) {
+OS << "  " << RV->getNameInitAsString() << " = "
+   << RV->getValueAsInt("Value") << ",\n";
+  }
+
+  OS << "#endif\n\n";
+}
 
+void NeonEmitter::genIntrinsicRangeCheckCode(
+raw_ostream &OS, SmallVectorImpl &Defs) {
+  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
+  int EltType;
+  // Ensure these are only emitted once.
   std::set Emitted;
 
-  for (auto *Def : Defs) {
-if (Def->hasBody())
-  continue;
-// Functions which do not have an immediate do not need to have range
-// checking code emitted.
-if (!Def->hasImmediate())
-  continue;
-if (Emitted.find(Def->getMangledName()) != Emitted.end())
+  for (auto &Def : Defs) {
+if (Emitted.find(Def->getMangledName()) != Emitted.end() ||
+!Def->hasImmediate())

SpencerAbson wrote:

Added now

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


[clang] [llvm] [Clang][AArch64] Add customisable immediate range checking to NEON (PR #100278)

2024-08-22 Thread via cfe-commits

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


[clang] [Sparc] Add flags to enable errata workaround pass for GR712RC and UT700 (PR #104742)

2024-08-22 Thread Daniel Cederman via cfe-commits

doac wrote:

> > We have also developed some performance related patches for the Sparc 
> > backend, but it has been difficult to get them upstreamed as, as you say, 
> > few people are working on the Sparc backend.
> 
> This is off-topic but is it possible for you to submit it (or if I can see 
> those)? I'd like to get them upstreamed, if possible~

Yes, we can definitively try to submit them. We are working on porting them to 
the latest main, but you can see the 8.0.0 version here: 
https://github.com/doac/llvm-project/tree/bcc-2.1-llvm-8.0.0
Some of them have already been upstreamed or fixed by others, and others, such 
as the ones marked by REX, might not be that interesting for you.

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


[clang] 1e44e7a - [Sparc] Add flags to enable errata workaround pass for GR712RC and UT700 (#104742)

2024-08-22 Thread via cfe-commits

Author: Daniel Cederman
Date: 2024-08-22T10:57:55+02:00
New Revision: 1e44e7afd799f582171a79355ce353fde134e806

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

LOG: [Sparc] Add flags to enable errata workaround pass for GR712RC and UT700 
(#104742)

This adds the flags -mfix-gr712rc and -mfix-ut700 which enables the
necessary errata workarounds for the GR712RC and UT700 processors. The
functionality enabled by the flags is the same as the functionality
provided by the corresponding GCC flags.

Added: 
clang/test/Driver/sparc-fix.c

Modified: 
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Arch/Sparc.cpp

Removed: 




diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index c204062b4f7353..5d8791727d2109 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -6155,6 +6155,10 @@ def mv8plus : Flag<["-"], "mv8plus">, 
Group,
   HelpText<"Enable V8+ mode, allowing use of 64-bit V9 instructions in 32-bit 
code">;
 def mno_v8plus : Flag<["-"], "mno-v8plus">, Group,
   HelpText<"Disable V8+ mode">;
+def mfix_gr712rc : Flag<["-"], "mfix-gr712rc">, Group,
+  HelpText<"Enable workarounds for GR712RC errata">;
+def mfix_ut700 : Flag<["-"], "mfix-ut700">, Group,
+  HelpText<"Enable workarounds for UT700 errata">;
 foreach i = 1 ... 7 in
   def ffixed_g#i : Flag<["-"], "ffixed-g"#i>, Group,
 HelpText<"Reserve the G"#i#" register (SPARC only)">;

diff  --git a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp 
b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
index 5a1fedbec06adf..f7f0a265fef68b 100644
--- a/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/Sparc.cpp
@@ -264,4 +264,17 @@ void sparc::getSparcTargetFeatures(const Driver &D, const 
ArgList &Args,
 
   if (Args.hasArg(options::OPT_ffixed_i5))
 Features.push_back("+reserve-i5");
+
+  if (Args.hasArg(options::OPT_mfix_gr712rc)) {
+Features.push_back("+fix-tn0009");
+Features.push_back("+fix-tn0011");
+Features.push_back("+fix-tn0012");
+Features.push_back("+fix-tn0013");
+  }
+
+  if (Args.hasArg(options::OPT_mfix_ut700)) {
+Features.push_back("+fix-tn0009");
+Features.push_back("+fix-tn0010");
+Features.push_back("+fix-tn0013");
+  }
 }

diff  --git a/clang/test/Driver/sparc-fix.c b/clang/test/Driver/sparc-fix.c
new file mode 100644
index 00..1f034399ce2245
--- /dev/null
+++ b/clang/test/Driver/sparc-fix.c
@@ -0,0 +1,5 @@
+// RUN: %clang --target=sparc -mfix-gr712rc -### %s 2>&1 | FileCheck 
--check-prefix=GR712RC %s
+// GR712RC: "-target-feature" "+fix-tn0009" "-target-feature" "+fix-tn0011" 
"-target-feature" "+fix-tn0012" "-target-feature" "+fix-tn0013"
+
+// RUN: %clang --target=sparc -mfix-ut700 -### %s 2>&1 | FileCheck 
--check-prefix=UT700 %s
+// UT700: "-target-feature" "+fix-tn0009" "-target-feature" "+fix-tn0010" 
"-target-feature" "+fix-tn0013"



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


[clang] [Sparc] Add flags to enable errata workaround pass for GR712RC and UT700 (PR #104742)

2024-08-22 Thread Daniel Cederman via cfe-commits

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


[clang] [clang-format] Treat new expressions as simple functions (PR #105168)

2024-08-22 Thread kadir çetinkaya via cfe-commits

https://github.com/kadircet updated 
https://github.com/llvm/llvm-project/pull/105168

From d0f1e7032647845fbe235856998e86bfbb59e937 Mon Sep 17 00:00:00 2001
From: Kadir Cetinkaya 
Date: Tue, 20 Aug 2024 19:40:42 +0200
Subject: [PATCH] [clang-format] Treat new expressions as simple functions

ccae7b461be339e717d02f99ac857cf0bc7d17f improved handling for nested
calls, but this resulted in a lot of changes near `new` expressions.

This patch tries to restore previous behavior around new expressions, by
treating them as simple functions, which seem to align with the concept.

Fixes https://github.com/llvm/llvm-project/issues/105133.
---
 clang/lib/Format/ContinuationIndenter.cpp | 8 
 clang/unittests/Format/FormatTest.cpp | 8 
 2 files changed, 16 insertions(+)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 46dafad65863dc..3184c5970b285a 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -848,6 +848,11 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   const auto IsSimpleFunction = [&](const FormatToken &Tok) {
 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
   return false;
+// Nested calls that inolve `new` expressions also look like simple
+// function calls, eg:
+// - foo(new Bar())
+if (Tok.is(tok::kw_new))
+  return true;
 const auto *Previous = Tok.Previous;
 if (!Previous || (!Previous->isOneOf(TT_FunctionDeclarationLParen,
  TT_LambdaDefinitionLParen) &&
@@ -870,6 +875,9 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   //   cll(
   //   cll(
   //   caaall(aa, 
a;
+  //  or
+  //  cal(
+  //   new SomethingElseee());
   !IsSimpleFunction(Current)) {
 CurrentState.NoLineBreak = true;
   }
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 794ccab3704534..7c14c1b65c5022 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -9292,6 +9292,14 @@ TEST_F(FormatTest, AlignsAfterOpenBracket) {
   "(a, )) &&\n"
   ");",
   Style);
+  verifyFormat(
+  "fooo(new BAR(\n"
+  "XXXZ()));",
+  Style);
+  verifyFormat(
+  "fooo(new FOO::BA(\n"
+  "XXXZ()));",
+  Style);
 
   Style.AlignAfterOpenBracket = FormatStyle::BAS_BlockIndent;
   Style.BinPackArguments = false;

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


[clang] [clang-format] Treat new expressions as simple functions (PR #105168)

2024-08-22 Thread kadir çetinkaya via cfe-commits


@@ -848,6 +848,8 @@ void ContinuationIndenter::addTokenOnCurrentLine(LineState 
&State, bool DryRun,
   const auto IsSimpleFunction = [&](const FormatToken &Tok) {
 if (!Tok.FakeLParens.empty() && Tok.FakeLParens.back() > prec::Unknown)
   return false;
+if (Tok.is(tok::kw_new))
+  return true;

kadircet wrote:

> Should we leave a simple comment?

Added some, LMK if you want something else mentioned.

> I spent a bit of time here wondering if it should return true or skip to the 
> next argument, I'm in two minds but I think this is ok.

I am wary of this as we can have cases like `new Foo::Bar();`, added some test 
cases.

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


[clang] [Clang][AArch64] Fix typo with colon-separated syntax for system registers (PR #105608)

2024-08-22 Thread Sam Elliott via cfe-commits

lenary wrote:

The existing implementation lines up with the ACLE, which specifies this 
colon-separated syntax: 
https://github.com/ARM-software/acle/blob/main/main/acle.md#aarch64-system-register
 - please send an update to that document before changing this behaviour.

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


[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread kadir çetinkaya via cfe-commits

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

thanks a lot!

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


[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread kadir çetinkaya via cfe-commits


@@ -4589,9 +4589,12 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 if (!BeforeLeft)
   return false;
 if (BeforeLeft->is(tok::coloncolon)) {
-  const auto *Prev = BeforeLeft->Previous;
-  return Left.is(tok::star) && Prev &&
- !Prev->endsSequence(tok::identifier, TT_FunctionTypeLParen);
+  if (Left.isNot(tok::star))
+return false;
+  if (!Right.startsSequence(tok::identifier, tok::r_paren))
+return true;
+  const auto *Tok = Right.Next->MatchingParen;

kadircet wrote:

`Right.Next` might be nullptr

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


[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread kadir çetinkaya via cfe-commits

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


[clang] [clang] Catch missing format attributes (PR #105479)

2024-08-22 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovichtec updated 
https://github.com/llvm/llvm-project/pull/105479

From 54e9ced2ab1a1a368046ea38b32a1f6d1ad651bc Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   5 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Attr.h   |   7 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaDecl.cpp   |   2 +
 clang/lib/Sema/SemaDeclAttr.cpp   | 219 +-
 clang/test/Sema/attr-format-missing.c | 393 ++
 clang/test/Sema/attr-format-missing.cpp   | 174 
 9 files changed, 805 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bb47350f76b308..2427b15010358f 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -241,6 +241,11 @@ Improvements to Clang's diagnostics
 
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
+- Don't emit duplicated dangling diagnostics. (#GH93386).
+
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH60718
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e0433496..3924677150a3a4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -529,7 +529,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4b6aadd635786a..14160f2911957e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1040,6 +1040,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Attr.h b/clang/include/clang/Sema/Attr.h
index 3f0b10212789a4..37c124ca7b454a 100644
--- a/clang/include/clang/Sema/Attr.h
+++ b/clang/include/clang/Sema/Attr.h
@@ -123,6 +123,13 @@ inline bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+inline bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 /// Diagnose mutually exclusive attributes when present on a given
 /// declaration. Returns true if diagnosed.
 template 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..9189216ed6e301 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4619,6 +4619,10 @@ class Sema final : public SemaBase {
 
   enum class RetainOwnershipKind { NS, CF, OS };
 
+  void DiagnoseMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+  std::vector
+  GetMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 503e93f9257137..500fb9d844372e 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15998,6 +15998,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt 
*Body,
 }
   }
 
+  DiagnoseMissingFormatAttributes(Body, FD);
+
   // We might not have found a prototype because we didn't wish to warn on
   // the lack of a missing prototype. Try again without the checks for
   // whether we want to warn on the missing prototype.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/Sema

[clang] [clang] Catch missing format attributes (PR #105479)

2024-08-22 Thread Budimir Aranđelović via cfe-commits

https://github.com/budimirarandjelovichtec updated 
https://github.com/llvm/llvm-project/pull/105479

From dd32b036bfc9e4c0bd467a4ec6f3e27e1770e1eb Mon Sep 17 00:00:00 2001
From: budimirarandjelovicsyrmia 
Date: Fri, 5 Apr 2024 15:20:37 +0200
Subject: [PATCH] [clang] Catch missing format attributes

---
 clang/docs/ReleaseNotes.rst   |   3 +
 clang/include/clang/Basic/DiagnosticGroups.td |   1 -
 .../clang/Basic/DiagnosticSemaKinds.td|   3 +
 clang/include/clang/Sema/Attr.h   |   7 +
 clang/include/clang/Sema/Sema.h   |   4 +
 clang/lib/Sema/SemaDecl.cpp   |   2 +
 clang/lib/Sema/SemaDeclAttr.cpp   | 219 +-
 clang/test/Sema/attr-format-missing.c | 393 ++
 clang/test/Sema/attr-format-missing.cpp   | 174 
 9 files changed, 803 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Sema/attr-format-missing.c
 create mode 100644 clang/test/Sema/attr-format-missing.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bb47350f76b308..df9a5ee9f43b90 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -241,6 +241,9 @@ Improvements to Clang's diagnostics
 
 - Don't emit duplicated dangling diagnostics. (#GH93386).
 
+- Clang now diagnoses missing format attributes for non-template functions and
+  class/struct/union members. Fixes #GH60718
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 19c3f1e0433496..3924677150a3a4 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -529,7 +529,6 @@ def MainReturnType : DiagGroup<"main-return-type">;
 def MaxUnsignedZero : DiagGroup<"max-unsigned-zero">;
 def MissingBraces : DiagGroup<"missing-braces">;
 def MissingDeclarations: DiagGroup<"missing-declarations">;
-def : DiagGroup<"missing-format-attribute">;
 def MissingIncludeDirs : DiagGroup<"missing-include-dirs">;
 def MissingNoreturn : DiagGroup<"missing-noreturn">;
 def MultiChar : DiagGroup<"multichar">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 4b6aadd635786a..14160f2911957e 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -1040,6 +1040,9 @@ def err_opencl_invalid_param : Error<
 def err_opencl_invalid_return : Error<
   "declaring function return value of type %0 is not allowed %select{; did you 
forget * ?|}1">;
 def warn_enum_value_overflow : Warning<"overflow in enumeration value">;
+def warn_missing_format_attribute : Warning<
+  "diagnostic behavior may be improved by adding the %0 format attribute to 
the declaration of %1">,
+  InGroup>, DefaultIgnore;
 def warn_pragma_options_align_reset_failed : Warning<
   "#pragma options align=reset failed: %0">,
   InGroup;
diff --git a/clang/include/clang/Sema/Attr.h b/clang/include/clang/Sema/Attr.h
index 3f0b10212789a4..37c124ca7b454a 100644
--- a/clang/include/clang/Sema/Attr.h
+++ b/clang/include/clang/Sema/Attr.h
@@ -123,6 +123,13 @@ inline bool isInstanceMethod(const Decl *D) {
   return false;
 }
 
+inline bool checkIfMethodHasImplicitObjectParameter(const Decl *D) {
+  if (const auto *MethodDecl = dyn_cast(D))
+return MethodDecl->isInstance() &&
+   !MethodDecl->hasCXXExplicitFunctionObjectParameter();
+  return false;
+}
+
 /// Diagnose mutually exclusive attributes when present on a given
 /// declaration. Returns true if diagnosed.
 template 
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 1f7e555d1b8717..9189216ed6e301 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -4619,6 +4619,10 @@ class Sema final : public SemaBase {
 
   enum class RetainOwnershipKind { NS, CF, OS };
 
+  void DiagnoseMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+  std::vector
+  GetMissingFormatAttributes(Stmt *Body, const FunctionDecl *FDecl);
+
   UuidAttr *mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI,
   StringRef UuidAsWritten, MSGuidDecl *GuidDecl);
 
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 503e93f9257137..500fb9d844372e 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15998,6 +15998,8 @@ Decl *Sema::ActOnFinishFunctionBody(Decl *dcl, Stmt 
*Body,
 }
   }
 
+  DiagnoseMissingFormatAttributes(Body, FD);
+
   // We might not have found a prototype because we didn't wish to warn on
   // the lack of a missing prototype. Try again without the checks for
   // whether we want to warn on the missing prototype.
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 73d11ac972b020..2ef4b2da5f4935 100644
--- a

[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread Owen Pan via cfe-commits


@@ -4589,9 +4589,12 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 if (!BeforeLeft)
   return false;
 if (BeforeLeft->is(tok::coloncolon)) {
-  const auto *Prev = BeforeLeft->Previous;
-  return Left.is(tok::star) && Prev &&
- !Prev->endsSequence(tok::identifier, TT_FunctionTypeLParen);
+  if (Left.isNot(tok::star))
+return false;
+  if (!Right.startsSequence(tok::identifier, tok::r_paren))
+return true;
+  const auto *Tok = Right.Next->MatchingParen;

owenca wrote:

No, because `startsSequence()` returned `true`. I'll add an assertion though.

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


[clang] [clang-format] Don't insert a space between :: and * (PR #105043)

2024-08-22 Thread Owen Pan via cfe-commits

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/105043

>From 4aa47d190a84ecd0432dc9b6db1d38b296f4df23 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Tue, 20 Aug 2024 06:44:41 -0700
Subject: [PATCH 1/4] [clang-format] Don't insert a space between :: and *

Also, don't insert a space after ::* for method pointers.

See https://github.com/llvm/llvm-project/pull/86253#issuecomment-2298404887.

Fixes #100841.
---
 clang/lib/Format/TokenAnnotator.cpp   | 10 +++---
 clang/unittests/Format/FormatTest.cpp | 36 +--
 clang/unittests/Format/QualifierFixerTest.cpp | 36 +--
 3 files changed, 40 insertions(+), 42 deletions(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 9d4204655b8ed6..f1f60bc0e8a72b 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4478,10 +4478,8 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
   }
   if (Left.is(tok::colon))
 return Left.isNot(TT_ObjCMethodExpr);
-  if (Left.is(tok::coloncolon)) {
-return Right.is(tok::star) && Right.is(TT_PointerOrReference) &&
-   Style.PointerAlignment != FormatStyle::PAS_Left;
-  }
+  if (Left.is(tok::coloncolon))
+return false;
   if (Left.is(tok::less) || Right.isOneOf(tok::greater, tok::less)) {
 if (Style.Language == FormatStyle::LK_TextProto ||
 (Style.Language == FormatStyle::LK_Proto &&
@@ -4591,7 +4589,9 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine &Line,
 if (!BeforeLeft)
   return false;
 if (BeforeLeft->is(tok::coloncolon)) {
-  return Left.is(tok::star) &&
+  const auto *Prev = BeforeLeft->Previous;
+  return Left.is(tok::star) && Prev &&
+ !Prev->endsSequence(tok::identifier, TT_FunctionTypeLParen) &&
  Style.PointerAlignment != FormatStyle::PAS_Right;
 }
 return !BeforeLeft->isOneOf(tok::l_paren, tok::l_square);
diff --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 794ccab3704534..e895f16465491a 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -3646,8 +3646,8 @@ TEST_F(FormatTest, FormatsClasses) {
": public aaa {};");
   verifyFormat("template \n"
-   "struct A\n"
-   ": A {};");
+   "struct A\n"
+   ": A {};");
   verifyFormat("class ::A::B {};");
 }
 
@@ -11166,10 +11166,10 @@ TEST_F(FormatTest, UnderstandsBinaryOperators) {
 }
 
 TEST_F(FormatTest, UnderstandsPointersToMembers) {
-  verifyFormat("int A:: *x;");
-  verifyFormat("int (S:: *func)(void *);");
-  verifyFormat("void f() { int (S:: *func)(void *); }");
-  verifyFormat("typedef bool *(Class:: *Member)() const;");
+  verifyFormat("int A::*x;");
+  verifyFormat("int (S::*func)(void *);");
+  verifyFormat("void f() { int (S::*func)(void *); }");
+  verifyFormat("typedef bool *(Class::*Member)() const;");
   verifyFormat("void f() {\n"
"  (a->*f)();\n"
"  a->*x;\n"
@@ -11187,16 +11187,16 @@ TEST_F(FormatTest, UnderstandsPointersToMembers) {
 
   FormatStyle Style = getLLVMStyle();
   EXPECT_EQ(Style.PointerAlignment, FormatStyle::PAS_Right);
-  verifyFormat("typedef bool *(Class:: *Member)() const;", Style);
-  verifyFormat("void f(int A:: *p) { int A:: *v = &A::B; }", Style);
+  verifyFormat("typedef bool *(Class::*Member)() const;", Style);
+  verifyFormat("void f(int A::*p) { int A::*v = &A::B; }", Style);
 
   Style.PointerAlignment = FormatStyle::PAS_Left;
-  verifyFormat("typedef bool* (Class::* Member)() const;", Style);
+  verifyFormat("typedef bool* (Class::*Member)() const;", Style);
   verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
 
   Style.PointerAlignment = FormatStyle::PAS_Middle;
-  verifyFormat("typedef bool * (Class:: * Member)() const;", Style);
-  verifyFormat("void f(int A:: * p) { int A:: * v = &A::B; }", Style);
+  verifyFormat("typedef bool * (Class::*Member)() const;", Style);
+  verifyFormat("void f(int A::* p) { int A::* v = &A::B; }", Style);
 }
 
 TEST_F(FormatTest, UnderstandsUnaryOperators) {
@@ -12539,7 +12539,7 @@ TEST_F(FormatTest, FormatsFunctionTypes) {
   verifyFormat("int (*func)(void *);");
   verifyFormat("void f() { int (*func)(void *); }");
   verifyFormat("template \n"
-   "using Callback = void (CallbackClass:: *)(SomeObject *Data);");
+   "using MyCallback = void (CallbackClass::*)(SomeObject 
*Data);");
 
   verifyGoogleFormat("A;");
   verifyGoogleFormat("void* (*a)(int);");
@@ -19462,13 +19462,13 @@ TEST_F(FormatTest, AlignConsecutiveDeclarations) {
"int   bbb = 0;",
Alignment);
   // http://llvm.org/PR68079
-  verifyFormat("using Fn   = int (A:: *)();\n"
-   "using RFn  = in

[clang] [llvm] [MC] Emit a jump table size section (PR #101962)

2024-08-22 Thread Nabeel Omer via cfe-commits

https://github.com/omern1 updated 
https://github.com/llvm/llvm-project/pull/101962

>From 14f3cb82f0d7e69261bd7e1317bd66392e9a2c2b Mon Sep 17 00:00:00 2001
From: Nabeel Omer 
Date: Mon, 5 Aug 2024 11:50:18 +0100
Subject: [PATCH 1/9] [MC] Emit a jump table size section

This patch will make LLVM emit a jump table size section containing
tuples of (jump table address, entry count) in object files.
This section is useful for tools that need to statically reconstruct
the control flow of executables.

The name of the new section is .debug_llvm_jump_table_sizes
because that makes both llvm-strip and GNU strip remove it.

At the moment this is only enabled by default for the PS5 target.
---
 clang/lib/Driver/ToolChains/PS4CPU.cpp|  8 ++
 clang/test/Driver/ps4-ps5-toolchain.c |  5 +
 llvm/docs/Extensions.rst  |  6 ++
 llvm/include/llvm/BinaryFormat/ELF.h  |  1 +
 llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp| 26 +
 llvm/lib/MC/MCParser/ELFAsmParser.cpp |  2 +
 llvm/lib/MC/MCSectionELF.cpp  |  2 +
 llvm/lib/Object/ELF.cpp   |  1 +
 .../CodeGen/X86/jump-table-size-section.ll| 97 +++
 9 files changed, 148 insertions(+)
 create mode 100644 llvm/test/CodeGen/X86/jump-table-size-section.ll

diff --git a/clang/lib/Driver/ToolChains/PS4CPU.cpp 
b/clang/lib/Driver/ToolChains/PS4CPU.cpp
index a9e612c44da06a..f9a9e995fff8e2 100644
--- a/clang/lib/Driver/ToolChains/PS4CPU.cpp
+++ b/clang/lib/Driver/ToolChains/PS4CPU.cpp
@@ -265,6 +265,8 @@ void tools::PS5cpu::Linker::ConstructJob(Compilation &C, 
const JobAction &JA,
 CmdArgs.push_back(D.getLTOMode() == LTOK_Thin ? "--lto=thin"
   : "--lto=full");
 
+  AddLTOFlag("-emit-jump-table-sizes-section");
+
   if (UseJMC)
 AddLTOFlag("-enable-jmc-instrument");
 
@@ -483,6 +485,12 @@ void toolchains::PS4PS5Base::addClangTargetOptions(
 else
   CC1Args.push_back("-fvisibility-externs-nodllstorageclass=keep");
   }
+
+  // Enable jump table sizes section for PS5.
+  if (getTriple().isPS5()) {
+CC1Args.push_back("-mllvm");
+CC1Args.push_back("-emit-jump-table-sizes-section");
+  }
 }
 
 // PS4 toolchain.
diff --git a/clang/test/Driver/ps4-ps5-toolchain.c 
b/clang/test/Driver/ps4-ps5-toolchain.c
index 444e9df24714bd..c9987c2b5758b3 100644
--- a/clang/test/Driver/ps4-ps5-toolchain.c
+++ b/clang/test/Driver/ps4-ps5-toolchain.c
@@ -11,3 +11,8 @@
 // RUN: %clang %s -### -target x86_64-sie-ps5 -flto 2>&1 | FileCheck %s 
--check-prefix=LTO
 // LTO-NOT: error:
 // LTO-NOT: unable to pass LLVM bit-code
+
+// Verify that the jump table sizes section is enabled.
+// RUN: %clang %s -target x86_64-sie-ps5 -### 2>&1 | FileCheck 
-check-prefix=JUMPTABLESIZES %s
+// JUMPTABLESIZES: "-mllvm" "-emit-jump-table-sizes-section"
+// JUMPTABLESIZES: "-plugin-opt=-emit-jump-table-sizes-section"
diff --git a/llvm/docs/Extensions.rst b/llvm/docs/Extensions.rst
index 74ca8cb0aa6879..0e209f3fe5cc0d 100644
--- a/llvm/docs/Extensions.rst
+++ b/llvm/docs/Extensions.rst
@@ -554,6 +554,12 @@ time. This section is generated when the compiler enables 
fat LTO. This section
 has the ``SHF_EXCLUDE`` flag so that it is stripped from the final executable
 or shared library.
 
+``SHT_LLVM_JT_SIZES`` Section (Jump table addresses and sizes)
+^^^
+This section stores pairs of (jump table address, number of entries).
+This information is useful for tools that need to statically reconstruct
+the control flow of executables.
+
 CodeView-Dependent
 --
 
diff --git a/llvm/include/llvm/BinaryFormat/ELF.h 
b/llvm/include/llvm/BinaryFormat/ELF.h
index fb39bb4b10b377..7bec01688783d3 100644
--- a/llvm/include/llvm/BinaryFormat/ELF.h
+++ b/llvm/include/llvm/BinaryFormat/ELF.h
@@ -1121,6 +1121,7 @@ enum : unsigned {
   SHT_LLVM_BB_ADDR_MAP = 0x6fff4c0a,// LLVM Basic Block Address Map.
   SHT_LLVM_OFFLOADING = 0x6fff4c0b, // LLVM device offloading data.
   SHT_LLVM_LTO = 0x6fff4c0c,// .llvm.lto for fat LTO.
+  SHT_LLVM_JT_SIZES = 0x6fff4c0d,   // LLVM jump tables sizes.
   // Android's experimental support for SHT_RELR sections.
   // 
https://android.googlesource.com/platform/bionic/+/b7feec74547f84559a1467aca02708ff61346d2a/libc/include/elf.h#512
   SHT_ANDROID_RELR = 0x6f00,   // Relocation entries; only offsets.
diff --git a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp 
b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
index b64fe83959eb18..05624d2728bfdb 100644
--- a/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
+++ b/llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
@@ -107,6 +107,7 @@
 #include "llvm/Pass.h"
 #include "llvm/Remarks/RemarkStreamer.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/CommandLine.h"
 #include "llvm/Support/Compiler.h"
 #include "llvm/Support/ErrorHandling.h"
 #include "llvm/Support/FileSystem.h"
@@ -155,6 +156,11 @@ static

[clang] [llvm] [MC] Emit a jump table size section (PR #101962)

2024-08-22 Thread Nabeel Omer via cfe-commits


@@ -2764,6 +2770,27 @@ void AsmPrinter::emitJumpTableInfo() {
 for (const MachineBasicBlock *MBB : JTBBs)
   emitJumpTableEntry(MJTI, MBB, JTI);
   }
+
+  if (EmitJumpTableSizesSection && TM.getTargetTriple().isOSBinFormatELF() &&

omern1 wrote:

I've added support for COFF (hopefully correctly). I'm completely unfamiliar 
with MachO so I suggest that we leave that for a followup.

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-22 Thread via cfe-commits


@@ -0,0 +1,115 @@
+// RUN: %clang_cc1 -std=c++2c -verify %s
+
+
+namespace std {
+  using size_t = decltype(sizeof(0));
+}
+
+void *operator new(std::size_t, void *p) { return p; }
+void* operator new[] (std::size_t, void* p) {return p;}
+
+
+consteval int ok() {
+int i;
+new (&i) int(0);
+new (&i) int[1]{1};
+new (static_cast(&i)) int(0);
+return 0;
+}
+
+consteval int conversion() {
+int i;
+new (static_cast(&i)) float(0);
+// expected-note@-1 {{placement new would change type of storage from 
'int' to 'float'}}
+return 0;
+}
+
+consteval int indeterminate() {
+int * indeterminate;
+new (indeterminate) int(0);
+// expected-note@-1 {{read of uninitialized object is not allowed in a 
constant expression}}
+return 0;
+}
+
+consteval int array1() {
+int i[2];
+new (&i) int[]{1,2};
+new (&i) int[]{1};
+new (&i) int(0);
+new (static_cast(&i)) int[]{1,2};
+new (static_cast(&i)) int[]{1};
+return 0;
+}
+
+consteval int array2() {
+int i[1];
+new (&i) int[2];
+//expected-note@-1 {{placement new would change type of storage from 
'int[1]' to 'int[2]'}}
+return 0;
+}
+
+struct S{
+int* i;
+constexpr S() : i(new int(42)) {} // expected-note {{allocation performed 
here was not deallocated}}
+constexpr ~S() {delete i;}
+};
+
+consteval void alloc() {
+S* s = new S();
+s->~S();
+new (s) S();
+delete s;
+}
+
+
+consteval void alloc_err() {
+S* s = new S();
+new (s) S();
+delete s;
+}
+
+
+
+int a = ok();
+int b = conversion(); // expected-error {{call to consteval function 
'conversion' is not a constant expression}} \
+ // expected-note {{in call to 'conversion()'}}
+int c = indeterminate(); // expected-error {{call to consteval function 
'indeterminate' is not a constant expression}} \
+ // expected-note {{in call to 'indeterminate()'}}
+int d = array1();
+int e = array2(); // expected-error {{call to consteval function 'array2' is 
not a constant expression}} \
+  // expected-note {{in call to 'array2()'}}
+int alloc1 = (alloc(), 0);
+int alloc2 = (alloc_err(), 0); // expected-error {{call to consteval function 
'alloc_err' is not a constant expression}}
+
+constexpr int *intptr() {
+  return new int;
+}
+
+constexpr bool yay() {
+  int *ptr = new (intptr()) int(42);
+  bool ret = *ptr == 42;
+  delete ptr;
+  return ret;
+}
+static_assert(yay());
+
+constexpr bool blah() {
+  int *ptr = new (intptr()) int[3]{ 1, 2, 3 }; // expected-note {{placement 
new would change type of storage from 'int' to 'int[3]'}}

cor3ntin wrote:

no, the _storage_ is int

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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-22 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/104586

>From 67201d1d2e4d092cf8712b1e1b63f2eceaf8d57c Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 9 Jul 2024 08:37:18 +0200
Subject: [PATCH 1/5] [Clang] Implement P2747 constexpr placement new

In C++26 and as an extension in C++20
---
 clang/docs/LanguageExtensions.rst |  1 +
 clang/docs/ReleaseNotes.rst   |  3 +
 .../include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp| 55 +++--
 clang/lib/Frontend/InitPreprocessor.cpp   |  2 +-
 clang/test/AST/ByteCode/new-delete.cpp|  4 +-
 clang/test/CXX/drs/cwg29xx.cpp| 26 ++
 clang/test/Lexer/cxx-features.cpp |  2 +-
 .../SemaCXX/constant-expression-cxx2a.cpp |  2 +-
 .../test/SemaCXX/cxx2a-constexpr-dynalloc.cpp | 82 ++-
 clang/www/cxx_dr_status.html  |  2 +-
 clang/www/cxx_status.html |  2 +-
 12 files changed, 150 insertions(+), 33 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 62903fc3744cad..23fe23208763b8 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1506,6 +1506,7 @@ Attributes on Structured Bindings
__cpp_structured_bindingsC+
 Pack Indexing__cpp_pack_indexing  
C++26 C++03
 ``= delete ("should have a reason");``   __cpp_deleted_function   
C++26 C++03
 Variadic Friends __cpp_variadic_friend
C++26 C++03
+``constexpr`` placement new  __cpp_constexpr  
C++26 C++20
   
- -
 Designated initializers (N494)
C99   C89
 Array & element qualification (N2607) 
C23   C89
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8f98167dff31ef..0852ac91ba4947 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -131,6 +131,9 @@ C++2c Feature Support
 
 - Implemented `P2893R3 Variadic Friends `_
 
+- Implemented `P2747R2 constexpr placement new `_.
+
+
 Resolutions to C++ Defect Reports
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index f317c5ac44f32b..569d2cc20a526c 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -335,7 +335,7 @@ def note_constexpr_new_non_replaceable : Note<
 def note_constexpr_new_placement : Note<
   "this placement new expression is not yet supported in constant 
expressions">;
 def note_constexpr_placement_new_wrong_type : Note<
-  "placement new would change type of storage from %0 to %1">;
+"placement new would change type of storage from %0 to %1">;
 def note_constexpr_new_negative : Note<
   "cannot allocate array; evaluated array bound %0 is negative">;
 def note_constexpr_new_too_large : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5540f58b526705..3df963c554a995 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -6691,7 +6691,7 @@ static bool HandleDestructionImpl(EvalInfo &Info, 
SourceRange CallRange,
 if (Size && Size > Value.getArrayInitializedElts())
   expandArray(Value, Value.getArraySize() - 1);
 
-for (; Size != 0; --Size) {
+for (Size = Value.getArraySize(); Size != 0; --Size) {
   APValue &Elem = Value.getArrayInitializedElt(Size - 1);
   if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
   !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
@@ -10003,23 +10003,14 @@ bool PointerExprEvaluator::VisitCXXNewExpr(const 
CXXNewExpr *E) {
 return false;
 
   FunctionDecl *OperatorNew = E->getOperatorNew();
+  QualType AllocType = E->getAllocatedType();
+  QualType TargetType = AllocType;
 
   bool IsNothrow = false;
   bool IsPlacement = false;
-  if (OperatorNew->isReservedGlobalPlacementOperator() &&
-  Info.CurrentCall->isStdFunction() && !E->isArray()) {
-// FIXME Support array placement new.
-assert(E->getNumPlacementArgs() == 1);
-if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
-  return false;
-if (Result.Designator.Invalid)
-  return false;
-IsPlacement = true;
-  } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
-Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
-<< isa(OperatorNew) << OperatorNew;
-return false;
-  } else if (E->getNumPlacementArgs()) {
+
+  if (E->getNumPlacementArgs() && E

[clang] [clang][Bytecode] Fix void unary * operators (PR #105640)

2024-08-22 Thread Timm Baeder via cfe-commits

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

Discard the subexpr.

>From 811ce07c27a92a55642088f26560b4698e5bfc7f Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 22 Aug 2024 12:54:27 +0200
Subject: [PATCH] [clang][Bytecode] Fix void unary * operators

Discard the subexpr.
---
 clang/lib/AST/ByteCode/Compiler.cpp | 2 +-
 clang/test/AST/ByteCode/invalid.cpp | 9 +++--
 2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..9d376641f9c5a3 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -5145,7 +5145,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult)
+if (DiscardResult || E->getType()->isVoidType())
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x
diff --git a/clang/test/AST/ByteCode/invalid.cpp 
b/clang/test/AST/ByteCode/invalid.cpp
index 522ad02f71ce07..3c142481f78119 100644
--- a/clang/test/AST/ByteCode/invalid.cpp
+++ b/clang/test/AST/ByteCode/invalid.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify=expected,both %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref,both %s
 
 namespace Throw {
 
@@ -65,4 +65,9 @@ namespace Casts {
// ref-error {{must be 
initialized by a constant expression}} \
// ref-note {{reinterpret_cast 
is not allowed}}
 
+  void func() {
+struct B {};
+B b;
+(void)*reinterpret_cast(&b); // both-error {{indirection not 
permitted on operand of type 'void *'}}
+  }
 }

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


[clang] [clang][Bytecode] Fix void unary * operators (PR #105640)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Discard the subexpr.

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


2 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+1-1) 
- (modified) clang/test/AST/ByteCode/invalid.cpp (+7-2) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..9d376641f9c5a3 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -5145,7 +5145,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult)
+if (DiscardResult || E->getType()->isVoidType())
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x
diff --git a/clang/test/AST/ByteCode/invalid.cpp 
b/clang/test/AST/ByteCode/invalid.cpp
index 522ad02f71ce07..3c142481f78119 100644
--- a/clang/test/AST/ByteCode/invalid.cpp
+++ b/clang/test/AST/ByteCode/invalid.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify=expected,both %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref,both %s
 
 namespace Throw {
 
@@ -65,4 +65,9 @@ namespace Casts {
// ref-error {{must be 
initialized by a constant expression}} \
// ref-note {{reinterpret_cast 
is not allowed}}
 
+  void func() {
+struct B {};
+B b;
+(void)*reinterpret_cast(&b); // both-error {{indirection not 
permitted on operand of type 'void *'}}
+  }
 }

``




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


[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-22 Thread Vlad Serebrennikov via cfe-commits


@@ -23,3 +23,29 @@ struct S {
   friend class C::Nested...; // expected-error {{friend declaration 
expands pack 'Ts' that is declared it its own template parameter list}}
 };
 } // namespace cwg2917
+
+#if __cplusplus >= 202002
+
+namespace std {
+  using size_t = decltype(sizeof(0));
+};
+void *operator new(std::size_t, void *p) { return p; }
+void* operator new[] (std::size_t, void* p) {return p;}
+
+
+namespace cwg2922 { // cwg2922: 20 open 2024-07-10
+union U { int a, b; };
+constexpr U nondeterministic(bool i) {
+  if(i) {
+U u;
+new (&u) int();
+// expected-note@-1 {{placement new would change type of storage from 'U' 
to 'int'}}
+return u;
+  }
+  return {};
+}
+constexpr U _ = nondeterministic(true);
+// expected-error@-1 {{constexpr variable '_' must be initialized by a 
constant expression}} \
+// expected-note@-1 {{in call to 'nondeterministic(true)'}}

Endilll wrote:

This is still outstanding, albeit minor.

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


[clang] [clang][Interp] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread Timm Baeder via cfe-commits

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

Convert them to Pointers, do the offset calculation and then convert them back 
to function pointers.

>From af18bbdf3440b3d13077dbcfd22a04fcf0b1564b Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 21 Aug 2024 09:49:54 +0200
Subject: [PATCH] [clang][Interp] Allow adding offsets to function pointers

Convert them to Pointers, do the offset calculation and then
convert them back to function pointers.
---
 clang/lib/AST/ByteCode/Compiler.cpp| 40 
 clang/lib/AST/ByteCode/FunctionPointer.cpp | 44 ++
 clang/lib/AST/ByteCode/FunctionPointer.h   | 41 +---
 clang/lib/AST/ByteCode/Interp.h| 37 +++---
 clang/lib/AST/ByteCode/Pointer.h   |  6 ++-
 clang/lib/AST/CMakeLists.txt   |  1 +
 clang/test/AST/ByteCode/c.c| 16 
 7 files changed, 140 insertions(+), 45 deletions(-)
 create mode 100644 clang/lib/AST/ByteCode/FunctionPointer.cpp

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..a91a3447230049 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -885,12 +885,21 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
   if (!LT || !RT)
 return false;
 
+  // Visit the given pointer expression and optionally convert to a PT_Ptr.
+  auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
+if (!this->visit(E))
+  return false;
+if (T != PT_Ptr)
+  return this->emitDecayPtr(T, PT_Ptr, E);
+return true;
+  };
+
   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
 if (Op != BO_Sub)
   return false;
 
 assert(E->getType()->isIntegerType());
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
   return false;
 
 return this->emitSubPtr(classifyPrim(E->getType()), E);
@@ -898,21 +907,38 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
 
   PrimType OffsetType;
   if (LHS->getType()->isIntegerType()) {
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS))
+  return false;
+if (!this->visit(LHS))
   return false;
 OffsetType = *LT;
   } else if (RHS->getType()->isIntegerType()) {
-if (!visit(LHS) || !visit(RHS))
+if (!visitAsPointer(LHS))
+  return false;
+if (!this->visit(RHS))
   return false;
 OffsetType = *RT;
   } else {
 return false;
   }
 
-  if (Op == BO_Add)
-return this->emitAddOffset(OffsetType, E);
-  else if (Op == BO_Sub)
-return this->emitSubOffset(OffsetType, E);
+  // Do the operation and optionally transform to
+  // result pointer type.
+  if (Op == BO_Add) {
+if (!this->emitAddOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  } else if (Op == BO_Sub) {
+if (!this->emitSubOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  }
 
   return false;
 }
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.cpp 
b/clang/lib/AST/ByteCode/FunctionPointer.cpp
new file mode 100644
index 00..4d6ca2e0f8ae2e
--- /dev/null
+++ b/clang/lib/AST/ByteCode/FunctionPointer.cpp
@@ -0,0 +1,44 @@
+//===--- FunctionPointer.cpp *- 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
+//
+//===--===//
+
+#include "FunctionPointer.h"
+
+namespace clang {
+namespace interp {
+
+APValue FunctionPointer::toAPValue(const ASTContext &) const {
+  llvm::errs() << __PRETTY_FUNCTION__ << ": " << Offset << '\n';
+  if (!Func)
+return APValue(static_cast(nullptr), CharUnits::Zero(), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/true);
+
+  if (!Valid)
+return APValue(static_cast(nullptr),
+   CharUnits::fromQuantity(getIntegerRepresentation()), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+
+  if (Func->getDecl())
+return APValue(Func->getDecl(), CharUnits::fromQuantity(Offset), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+  return APValue(Func->getExpr(), CharUnits::fromQuantity(Offset), {},
+ /*OnePastTheEnd=*/false, /*IsNull=*/false);
+}
+
+void FunctionPointer::print(llvm::raw_ostream &OS) const {
+  OS << "FnPtr(";
+  if (Func && Valid)
+OS << Func->getName();
+  else if (Func)
+OS << reinterpret_cast(Func);
+  else
+OS << "nullptr";
+  OS << ") + " << Off

[clang] [clang][Interp] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

Convert them to Pointers, do the offset calculation and then convert them back 
to function pointers.

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


7 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+33-7) 
- (added) clang/lib/AST/ByteCode/FunctionPointer.cpp (+44) 
- (modified) clang/lib/AST/ByteCode/FunctionPointer.h (+10-31) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+32-5) 
- (modified) clang/lib/AST/ByteCode/Pointer.h (+4-2) 
- (modified) clang/lib/AST/CMakeLists.txt (+1) 
- (modified) clang/test/AST/ByteCode/c.c (+16) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..a91a3447230049 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -885,12 +885,21 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
   if (!LT || !RT)
 return false;
 
+  // Visit the given pointer expression and optionally convert to a PT_Ptr.
+  auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
+if (!this->visit(E))
+  return false;
+if (T != PT_Ptr)
+  return this->emitDecayPtr(T, PT_Ptr, E);
+return true;
+  };
+
   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
 if (Op != BO_Sub)
   return false;
 
 assert(E->getType()->isIntegerType());
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
   return false;
 
 return this->emitSubPtr(classifyPrim(E->getType()), E);
@@ -898,21 +907,38 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
 
   PrimType OffsetType;
   if (LHS->getType()->isIntegerType()) {
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS))
+  return false;
+if (!this->visit(LHS))
   return false;
 OffsetType = *LT;
   } else if (RHS->getType()->isIntegerType()) {
-if (!visit(LHS) || !visit(RHS))
+if (!visitAsPointer(LHS))
+  return false;
+if (!this->visit(RHS))
   return false;
 OffsetType = *RT;
   } else {
 return false;
   }
 
-  if (Op == BO_Add)
-return this->emitAddOffset(OffsetType, E);
-  else if (Op == BO_Sub)
-return this->emitSubOffset(OffsetType, E);
+  // Do the operation and optionally transform to
+  // result pointer type.
+  if (Op == BO_Add) {
+if (!this->emitAddOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  } else if (Op == BO_Sub) {
+if (!this->emitSubOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  }
 
   return false;
 }
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.cpp 
b/clang/lib/AST/ByteCode/FunctionPointer.cpp
new file mode 100644
index 00..4d6ca2e0f8ae2e
--- /dev/null
+++ b/clang/lib/AST/ByteCode/FunctionPointer.cpp
@@ -0,0 +1,44 @@
+//===--- FunctionPointer.cpp *- 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
+//
+//===--===//
+
+#include "FunctionPointer.h"
+
+namespace clang {
+namespace interp {
+
+APValue FunctionPointer::toAPValue(const ASTContext &) const {
+  llvm::errs() << __PRETTY_FUNCTION__ << ": " << Offset << '\n';
+  if (!Func)
+return APValue(static_cast(nullptr), CharUnits::Zero(), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/true);
+
+  if (!Valid)
+return APValue(static_cast(nullptr),
+   CharUnits::fromQuantity(getIntegerRepresentation()), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+
+  if (Func->getDecl())
+return APValue(Func->getDecl(), CharUnits::fromQuantity(Offset), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+  return APValue(Func->getExpr(), CharUnits::fromQuantity(Offset), {},
+ /*OnePastTheEnd=*/false, /*IsNull=*/false);
+}
+
+void FunctionPointer::print(llvm::raw_ostream &OS) const {
+  OS << "FnPtr(";
+  if (Func && Valid)
+OS << Func->getName();
+  else if (Func)
+OS << reinterpret_cast(Func);
+  else
+OS << "nullptr";
+  OS << ") + " << Offset;
+}
+
+} // namespace interp
+} // namespace clang
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.h 
b/clang/lib/AST/ByteCode/FunctionPointer.h
index c9bdfbee55441a..e2b45b2344fdce 100644
--- a/clang/lib/AST/ByteCode/FunctionPointer.h
+++ b/clang/lib/AST/ByteCode/FunctionPointer.h
@@ -11,25 +11,29 @@
 
 #include "Function.h"
 #include "Primitives.h"
-#include "clang/AST/APValue.h"

[clang] [clang][bytecode] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Fix void unary * operators (PR #105640)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] [clang][bytecode] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/105641

>From 4285763a4138661dac7a2d4abac4e2e1cec019ec Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 21 Aug 2024 09:49:54 +0200
Subject: [PATCH] [clang][Interp] Allow adding offsets to function pointers

Convert them to Pointers, do the offset calculation and then
convert them back to function pointers.
---
 clang/lib/AST/ByteCode/Compiler.cpp| 40 
 clang/lib/AST/ByteCode/FunctionPointer.cpp | 44 ++
 clang/lib/AST/ByteCode/FunctionPointer.h   | 41 +---
 clang/lib/AST/ByteCode/Interp.h| 37 +++---
 clang/lib/AST/ByteCode/Pointer.h   |  6 ++-
 clang/lib/AST/CMakeLists.txt   |  1 +
 clang/test/AST/ByteCode/c.c| 16 
 7 files changed, 140 insertions(+), 45 deletions(-)
 create mode 100644 clang/lib/AST/ByteCode/FunctionPointer.cpp

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..d16d2840cc0e48 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -885,12 +885,21 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
   if (!LT || !RT)
 return false;
 
+  // Visit the given pointer expression and optionally convert to a PT_Ptr.
+  auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
+if (!this->visit(E))
+  return false;
+if (T != PT_Ptr)
+  return this->emitDecayPtr(T, PT_Ptr, E);
+return true;
+  };
+
   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
 if (Op != BO_Sub)
   return false;
 
 assert(E->getType()->isIntegerType());
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
   return false;
 
 return this->emitSubPtr(classifyPrim(E->getType()), E);
@@ -898,21 +907,38 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
 
   PrimType OffsetType;
   if (LHS->getType()->isIntegerType()) {
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT))
+  return false;
+if (!this->visit(LHS))
   return false;
 OffsetType = *LT;
   } else if (RHS->getType()->isIntegerType()) {
-if (!visit(LHS) || !visit(RHS))
+if (!visitAsPointer(LHS, *LT))
+  return false;
+if (!this->visit(RHS))
   return false;
 OffsetType = *RT;
   } else {
 return false;
   }
 
-  if (Op == BO_Add)
-return this->emitAddOffset(OffsetType, E);
-  else if (Op == BO_Sub)
-return this->emitSubOffset(OffsetType, E);
+  // Do the operation and optionally transform to
+  // result pointer type.
+  if (Op == BO_Add) {
+if (!this->emitAddOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  } else if (Op == BO_Sub) {
+if (!this->emitSubOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  }
 
   return false;
 }
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.cpp 
b/clang/lib/AST/ByteCode/FunctionPointer.cpp
new file mode 100644
index 00..4d6ca2e0f8ae2e
--- /dev/null
+++ b/clang/lib/AST/ByteCode/FunctionPointer.cpp
@@ -0,0 +1,44 @@
+//===--- FunctionPointer.cpp *- 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
+//
+//===--===//
+
+#include "FunctionPointer.h"
+
+namespace clang {
+namespace interp {
+
+APValue FunctionPointer::toAPValue(const ASTContext &) const {
+  llvm::errs() << __PRETTY_FUNCTION__ << ": " << Offset << '\n';
+  if (!Func)
+return APValue(static_cast(nullptr), CharUnits::Zero(), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/true);
+
+  if (!Valid)
+return APValue(static_cast(nullptr),
+   CharUnits::fromQuantity(getIntegerRepresentation()), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+
+  if (Func->getDecl())
+return APValue(Func->getDecl(), CharUnits::fromQuantity(Offset), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+  return APValue(Func->getExpr(), CharUnits::fromQuantity(Offset), {},
+ /*OnePastTheEnd=*/false, /*IsNull=*/false);
+}
+
+void FunctionPointer::print(llvm::raw_ostream &OS) const {
+  OS << "FnPtr(";
+  if (Func && Valid)
+OS << Func->getName();
+  else if (Func)
+OS << reinterpret_cast(Func);
+  else
+OS << "nullptr";
+  OS << ") + " << Offset;
+}
+
+} // namespace interp
+} // namespace clang
diff --git a/clang/lib/AST/ByteCode/Fu

[clang] [Clang] Implement P2747 constexpr placement new (PR #104586)

2024-08-22 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/104586

>From 67201d1d2e4d092cf8712b1e1b63f2eceaf8d57c Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Tue, 9 Jul 2024 08:37:18 +0200
Subject: [PATCH 1/6] [Clang] Implement P2747 constexpr placement new

In C++26 and as an extension in C++20
---
 clang/docs/LanguageExtensions.rst |  1 +
 clang/docs/ReleaseNotes.rst   |  3 +
 .../include/clang/Basic/DiagnosticASTKinds.td |  2 +-
 clang/lib/AST/ExprConstant.cpp| 55 +++--
 clang/lib/Frontend/InitPreprocessor.cpp   |  2 +-
 clang/test/AST/ByteCode/new-delete.cpp|  4 +-
 clang/test/CXX/drs/cwg29xx.cpp| 26 ++
 clang/test/Lexer/cxx-features.cpp |  2 +-
 .../SemaCXX/constant-expression-cxx2a.cpp |  2 +-
 .../test/SemaCXX/cxx2a-constexpr-dynalloc.cpp | 82 ++-
 clang/www/cxx_dr_status.html  |  2 +-
 clang/www/cxx_status.html |  2 +-
 12 files changed, 150 insertions(+), 33 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 62903fc3744cad..23fe23208763b8 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1506,6 +1506,7 @@ Attributes on Structured Bindings
__cpp_structured_bindingsC+
 Pack Indexing__cpp_pack_indexing  
C++26 C++03
 ``= delete ("should have a reason");``   __cpp_deleted_function   
C++26 C++03
 Variadic Friends __cpp_variadic_friend
C++26 C++03
+``constexpr`` placement new  __cpp_constexpr  
C++26 C++20
   
- -
 Designated initializers (N494)
C99   C89
 Array & element qualification (N2607) 
C23   C89
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8f98167dff31ef..0852ac91ba4947 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -131,6 +131,9 @@ C++2c Feature Support
 
 - Implemented `P2893R3 Variadic Friends `_
 
+- Implemented `P2747R2 constexpr placement new `_.
+
+
 Resolutions to C++ Defect Reports
 ^
 
diff --git a/clang/include/clang/Basic/DiagnosticASTKinds.td 
b/clang/include/clang/Basic/DiagnosticASTKinds.td
index f317c5ac44f32b..569d2cc20a526c 100644
--- a/clang/include/clang/Basic/DiagnosticASTKinds.td
+++ b/clang/include/clang/Basic/DiagnosticASTKinds.td
@@ -335,7 +335,7 @@ def note_constexpr_new_non_replaceable : Note<
 def note_constexpr_new_placement : Note<
   "this placement new expression is not yet supported in constant 
expressions">;
 def note_constexpr_placement_new_wrong_type : Note<
-  "placement new would change type of storage from %0 to %1">;
+"placement new would change type of storage from %0 to %1">;
 def note_constexpr_new_negative : Note<
   "cannot allocate array; evaluated array bound %0 is negative">;
 def note_constexpr_new_too_large : Note<
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 5540f58b526705..3df963c554a995 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -6691,7 +6691,7 @@ static bool HandleDestructionImpl(EvalInfo &Info, 
SourceRange CallRange,
 if (Size && Size > Value.getArrayInitializedElts())
   expandArray(Value, Value.getArraySize() - 1);
 
-for (; Size != 0; --Size) {
+for (Size = Value.getArraySize(); Size != 0; --Size) {
   APValue &Elem = Value.getArrayInitializedElt(Size - 1);
   if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
   !HandleDestructionImpl(Info, CallRange, ElemLV, Elem, ElemT))
@@ -10003,23 +10003,14 @@ bool PointerExprEvaluator::VisitCXXNewExpr(const 
CXXNewExpr *E) {
 return false;
 
   FunctionDecl *OperatorNew = E->getOperatorNew();
+  QualType AllocType = E->getAllocatedType();
+  QualType TargetType = AllocType;
 
   bool IsNothrow = false;
   bool IsPlacement = false;
-  if (OperatorNew->isReservedGlobalPlacementOperator() &&
-  Info.CurrentCall->isStdFunction() && !E->isArray()) {
-// FIXME Support array placement new.
-assert(E->getNumPlacementArgs() == 1);
-if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
-  return false;
-if (Result.Designator.Invalid)
-  return false;
-IsPlacement = true;
-  } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
-Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
-<< isa(OperatorNew) << OperatorNew;
-return false;
-  } else if (E->getNumPlacementArgs()) {
+
+  if (E->getNumPlacementArgs() && E

[clang] [clang][bytecode] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread Timm Baeder via cfe-commits

https://github.com/tbaederr updated 
https://github.com/llvm/llvm-project/pull/105641

>From 7c9321e85febf0fa177736f425fe286d24951eb7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Wed, 21 Aug 2024 09:49:54 +0200
Subject: [PATCH] [clang][Interp] Allow adding offsets to function pointers

Convert them to Pointers, do the offset calculation and then
convert them back to function pointers.
---
 clang/lib/AST/ByteCode/Compiler.cpp| 40 
 clang/lib/AST/ByteCode/FunctionPointer.cpp | 43 ++
 clang/lib/AST/ByteCode/FunctionPointer.h   | 41 +
 clang/lib/AST/ByteCode/Interp.h| 37 ---
 clang/lib/AST/ByteCode/Pointer.h   |  6 ++-
 clang/lib/AST/CMakeLists.txt   |  1 +
 clang/test/AST/ByteCode/c.c| 16 
 7 files changed, 139 insertions(+), 45 deletions(-)
 create mode 100644 clang/lib/AST/ByteCode/FunctionPointer.cpp

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..d16d2840cc0e48 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -885,12 +885,21 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
   if (!LT || !RT)
 return false;
 
+  // Visit the given pointer expression and optionally convert to a PT_Ptr.
+  auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
+if (!this->visit(E))
+  return false;
+if (T != PT_Ptr)
+  return this->emitDecayPtr(T, PT_Ptr, E);
+return true;
+  };
+
   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
 if (Op != BO_Sub)
   return false;
 
 assert(E->getType()->isIntegerType());
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
   return false;
 
 return this->emitSubPtr(classifyPrim(E->getType()), E);
@@ -898,21 +907,38 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
 
   PrimType OffsetType;
   if (LHS->getType()->isIntegerType()) {
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT))
+  return false;
+if (!this->visit(LHS))
   return false;
 OffsetType = *LT;
   } else if (RHS->getType()->isIntegerType()) {
-if (!visit(LHS) || !visit(RHS))
+if (!visitAsPointer(LHS, *LT))
+  return false;
+if (!this->visit(RHS))
   return false;
 OffsetType = *RT;
   } else {
 return false;
   }
 
-  if (Op == BO_Add)
-return this->emitAddOffset(OffsetType, E);
-  else if (Op == BO_Sub)
-return this->emitSubOffset(OffsetType, E);
+  // Do the operation and optionally transform to
+  // result pointer type.
+  if (Op == BO_Add) {
+if (!this->emitAddOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  } else if (Op == BO_Sub) {
+if (!this->emitSubOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  }
 
   return false;
 }
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.cpp 
b/clang/lib/AST/ByteCode/FunctionPointer.cpp
new file mode 100644
index 00..6b0b559a63386e
--- /dev/null
+++ b/clang/lib/AST/ByteCode/FunctionPointer.cpp
@@ -0,0 +1,43 @@
+//===--- FunctionPointer.cpp *- 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
+//
+//===--===//
+
+#include "FunctionPointer.h"
+
+namespace clang {
+namespace interp {
+
+APValue FunctionPointer::toAPValue(const ASTContext &) const {
+  if (!Func)
+return APValue(static_cast(nullptr), CharUnits::Zero(), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/true);
+
+  if (!Valid)
+return APValue(static_cast(nullptr),
+   CharUnits::fromQuantity(getIntegerRepresentation()), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+
+  if (Func->getDecl())
+return APValue(Func->getDecl(), CharUnits::fromQuantity(Offset), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+  return APValue(Func->getExpr(), CharUnits::fromQuantity(Offset), {},
+ /*OnePastTheEnd=*/false, /*IsNull=*/false);
+}
+
+void FunctionPointer::print(llvm::raw_ostream &OS) const {
+  OS << "FnPtr(";
+  if (Func && Valid)
+OS << Func->getName();
+  else if (Func)
+OS << reinterpret_cast(Func);
+  else
+OS << "nullptr";
+  OS << ") + " << Offset;
+}
+
+} // namespace interp
+} // namespace clang
diff --git a/clang/lib/AST/ByteCode/FunctionPointer.h 
b/clang/lib/AST/ByteCode/FunctionPointer.h
inde

[clang] [llvm] [NFC][SetTheory] Refactor to use const pointers and range loops (PR #105544)

2024-08-22 Thread Sergei Barannikov via cfe-commits

https://github.com/s-barannikov approved this pull request.


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


[clang] 125aa10 - [clang][bytecode] Fix void unary * operators (#105640)

2024-08-22 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-22T14:05:17+02:00
New Revision: 125aa10b3d645bd26523a1bc321bb2e6b1cf04e1

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

LOG: [clang][bytecode] Fix void unary * operators (#105640)

Discard the subexpr.

Added: 


Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/test/AST/ByteCode/invalid.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 10f3222726fd43..9d376641f9c5a3 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -5145,7 +5145,7 @@ bool Compiler::VisitUnaryOperator(const 
UnaryOperator *E) {
 // We should already have a pointer when we get here.
 return this->delegate(SubExpr);
   case UO_Deref: // *x
-if (DiscardResult)
+if (DiscardResult || E->getType()->isVoidType())
   return this->discard(SubExpr);
 return this->visit(SubExpr);
   case UO_Not: // ~x

diff  --git a/clang/test/AST/ByteCode/invalid.cpp 
b/clang/test/AST/ByteCode/invalid.cpp
index 522ad02f71ce07..3c142481f78119 100644
--- a/clang/test/AST/ByteCode/invalid.cpp
+++ b/clang/test/AST/ByteCode/invalid.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify %s
-// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 
-fexperimental-new-constant-interpreter -verify=expected,both %s
+// RUN: %clang_cc1 -fcxx-exceptions -std=c++20 -verify=ref,both %s
 
 namespace Throw {
 
@@ -65,4 +65,9 @@ namespace Casts {
// ref-error {{must be 
initialized by a constant expression}} \
// ref-note {{reinterpret_cast 
is not allowed}}
 
+  void func() {
+struct B {};
+B b;
+(void)*reinterpret_cast(&b); // both-error {{indirection not 
permitted on operand of type 'void *'}}
+  }
 }



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


[clang] [clang][bytecode] Fix void unary * operators (PR #105640)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] [Clang] correct error message when assigning to const reference captured in lambda (PR #105647)

2024-08-22 Thread via cfe-commits

https://github.com/nfrmtk created 
https://github.com/llvm/llvm-project/pull/105647

Fixes:#98772

>From 4bb6969d0969ca9b4df20693107fbc1980c90f0f Mon Sep 17 00:00:00 2001
From: ivan lykov 
Date: Thu, 22 Aug 2024 15:10:52 +0300
Subject: [PATCH] [Clang] correct error message when assigning to const
 reference captured in lambda

---
 clang/lib/Sema/SemaExpr.cpp   | 2 ++
 clang/test/SemaCXX/lambda-expressions.cpp | 5 +
 2 files changed, 7 insertions(+)

diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c67183df335dd5..9c256fd1ed1a41 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -13140,6 +13140,8 @@ static NonConstCaptureKind 
isReferenceToNonConstCapture(Sema &S, Expr *E) {
   VarDecl *var = dyn_cast(DRE->getDecl());
   if (!var) return NCCK_None;
   if (var->getType().isConstQualified()) return NCCK_None;
+  if (var->getType()->isReferenceType())
+return NCCK_None;
   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
 
   // Decide whether the first capture was for a block or a lambda.
diff --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index acf8d014a9896b..612c6db950f273 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -189,6 +189,11 @@ namespace ModifyingCapture {
 [=] {
   n = 1; // expected-error {{cannot assign to a variable captured by copy 
in a non-mutable lambda}}
 };
+const int cn = 0;
+// cxx03-cxx11-warning@+1 {{initialized lambda captures are a C++14 
extension}}
+[&cnr = cn]{ // expected-note {{variable 'cnr' declared const here}}
+  cnr = 1; // expected-error {{cannot assign to variable 'cnr' with 
const-qualified type 'const int &'}}
+};
   }
 }
 

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


[clang] [Clang] correct error message when assigning to const reference captured in lambda (PR #105647)

2024-08-22 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/105647
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [Clang] correct error message when assigning to const reference captured in lambda (PR #105647)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (nfrmtk)


Changes

Fixes:#98772

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


2 Files Affected:

- (modified) clang/lib/Sema/SemaExpr.cpp (+2) 
- (modified) clang/test/SemaCXX/lambda-expressions.cpp (+5) 


``diff
diff --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c67183df335dd5..9c256fd1ed1a41 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -13140,6 +13140,8 @@ static NonConstCaptureKind 
isReferenceToNonConstCapture(Sema &S, Expr *E) {
   VarDecl *var = dyn_cast(DRE->getDecl());
   if (!var) return NCCK_None;
   if (var->getType().isConstQualified()) return NCCK_None;
+  if (var->getType()->isReferenceType())
+return NCCK_None;
   assert(var->hasLocalStorage() && "capture added 'const' to non-local?");
 
   // Decide whether the first capture was for a block or a lambda.
diff --git a/clang/test/SemaCXX/lambda-expressions.cpp 
b/clang/test/SemaCXX/lambda-expressions.cpp
index acf8d014a9896b..612c6db950f273 100644
--- a/clang/test/SemaCXX/lambda-expressions.cpp
+++ b/clang/test/SemaCXX/lambda-expressions.cpp
@@ -189,6 +189,11 @@ namespace ModifyingCapture {
 [=] {
   n = 1; // expected-error {{cannot assign to a variable captured by copy 
in a non-mutable lambda}}
 };
+const int cn = 0;
+// cxx03-cxx11-warning@+1 {{initialized lambda captures are a C++14 
extension}}
+[&cnr = cn]{ // expected-note {{variable 'cnr' declared const here}}
+  cnr = 1; // expected-error {{cannot assign to variable 'cnr' with 
const-qualified type 'const int &'}}
+};
   }
 }
 

``




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


[clang] [llvm] [NVPTX] Support __usAtomicCAS builtin (PR #99646)

2024-08-22 Thread via cfe-commits

https://github.com/DenisGZM updated 
https://github.com/llvm/llvm-project/pull/99646

>From 0f5f1297393e88aed06672fbc753d918a11f2b00 Mon Sep 17 00:00:00 2001
From: Denis Gerasimov 
Date: Fri, 19 Jul 2024 15:47:57 +0300
Subject: [PATCH 1/8] [NVPTX] Support __usAtomicCAS builtin

---
 clang/include/clang/Basic/BuiltinsNVPTX.def   |  3 +++
 clang/lib/CodeGen/CGBuiltin.cpp   |  3 +++
 clang/lib/Headers/__clang_cuda_device_functions.h | 12 
 clang/test/CodeGen/builtins-nvptx.c   |  3 +++
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  2 +-
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  | 15 +++
 6 files changed, 37 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/BuiltinsNVPTX.def 
b/clang/include/clang/Basic/BuiltinsNVPTX.def
index c11970c279c4bb..20f038a0a9bbde 100644
--- a/clang/include/clang/Basic/BuiltinsNVPTX.def
+++ b/clang/include/clang/Basic/BuiltinsNVPTX.def
@@ -844,6 +844,9 @@ BUILTIN(__nvvm_atom_xor_gen_ll, "LLiLLiD*LLi", "n")
 TARGET_BUILTIN(__nvvm_atom_cta_xor_gen_ll, "LLiLLiD*LLi", "n", SM_60)
 TARGET_BUILTIN(__nvvm_atom_sys_xor_gen_ll, "LLiLLiD*LLi", "n", SM_60)
 
+TARGET_BUILTIN(__nvvm_atom_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
+TARGET_BUILTIN(__nvvm_atom_cta_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
+TARGET_BUILTIN(__nvvm_atom_sys_cas_gen_us, "UsUsD*UsUs", "n", SM_70)
 BUILTIN(__nvvm_atom_cas_gen_i, "iiD*ii", "n")
 TARGET_BUILTIN(__nvvm_atom_cta_cas_gen_i, "iiD*ii", "n", SM_60)
 TARGET_BUILTIN(__nvvm_atom_sys_cas_gen_i, "iiD*ii", "n", SM_60)
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 3d77b118235ca0..20c343c75f3a94 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -20351,6 +20351,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_atom_min_gen_ull:
 return MakeBinaryAtomicValue(*this, llvm::AtomicRMWInst::UMin, E);
 
+  case NVPTX::BI__nvvm_atom_cas_gen_us:
   case NVPTX::BI__nvvm_atom_cas_gen_i:
   case NVPTX::BI__nvvm_atom_cas_gen_l:
   case NVPTX::BI__nvvm_atom_cas_gen_ll:
@@ -20542,6 +20543,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
   case NVPTX::BI__nvvm_atom_sys_xor_gen_l:
   case NVPTX::BI__nvvm_atom_sys_xor_gen_ll:
 return MakeScopedAtomic(Intrinsic::nvvm_atomic_xor_gen_i_sys, *this, E);
+  case NVPTX::BI__nvvm_atom_cta_cas_gen_us:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_i:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_l:
   case NVPTX::BI__nvvm_atom_cta_cas_gen_ll: {
@@ -20553,6 +20555,7 @@ Value *CodeGenFunction::EmitNVPTXBuiltinExpr(unsigned 
BuiltinID,
 Intrinsic::nvvm_atomic_cas_gen_i_cta, {ElemTy, Ptr->getType()}),
 {Ptr, EmitScalarExpr(E->getArg(1)), EmitScalarExpr(E->getArg(2))});
   }
+  case NVPTX::BI__nvvm_atom_sys_cas_gen_us:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_i:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_l:
   case NVPTX::BI__nvvm_atom_sys_cas_gen_ll: {
diff --git a/clang/lib/Headers/__clang_cuda_device_functions.h 
b/clang/lib/Headers/__clang_cuda_device_functions.h
index f8a12cefdb81b4..f66fe625a39676 100644
--- a/clang/lib/Headers/__clang_cuda_device_functions.h
+++ b/clang/lib/Headers/__clang_cuda_device_functions.h
@@ -529,6 +529,18 @@ __DEVICE__ void __threadfence(void) { __nvvm_membar_gl(); }
 __DEVICE__ void __threadfence_block(void) { __nvvm_membar_cta(); };
 __DEVICE__ void __threadfence_system(void) { __nvvm_membar_sys(); };
 __DEVICE__ void __trap(void) { __asm__ __volatile__("trap;"); }
+__DEVICE__ unsigned short __usAtomicCAS(unsigned short *__p, unsigned short 
__cmp,
+unsigned short __v) {
+  return __nvvm_atom_cas_gen_us(__p, __cmp, __v);
+}
+__DEVICE__ unsigned short __usAtomicCAS_block(unsigned short *__p, unsigned 
short __cmp,
+  unsigned short __v) {
+  return __nvvm_atom_cta_cas_gen_us(__p, __cmp, __v);
+}
+__DEVICE__ unsigned short __usAtomicCAS_system(unsigned short *__p, unsigned 
short __cmp,
+   unsigned short __v) {
+  return __nvvm_atom_sys_cas_gen_us(__p, __cmp, __v);
+}
 __DEVICE__ unsigned int __uAtomicAdd(unsigned int *__p, unsigned int __v) {
   return __nvvm_atom_add_gen_i((int *)__p, __v);
 }
diff --git a/clang/test/CodeGen/builtins-nvptx.c 
b/clang/test/CodeGen/builtins-nvptx.c
index 20399b73e63757..645f036761c18f 100644
--- a/clang/test/CodeGen/builtins-nvptx.c
+++ b/clang/test/CodeGen/builtins-nvptx.c
@@ -309,6 +309,9 @@ __device__ void nvvm_atom(float *fp, float f, double *dfp, 
double df, int *ip,
   // CHECK: atomicrmw umin ptr {{.*}} seq_cst, align 8
   __nvvm_atom_min_gen_ull((unsigned long long *)&sll, ll);
 
+  // CHECK: cmpxchg ptr {{.*}} seq_cst seq_cst, align 2
+  // CHECK-NEXT: extractvalue { i16, i1 } {{%[0-9]+}}, 0
+  __nvvm_atom_cas_gen_us(ip, 0, i);
   // CHECK: cmpxchg ptr {{.*}} seq_cst seq_cst, align 4
   // CHECK-NEXT: extractvalue { 

[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto created 
https://github.com/llvm/llvm-project/pull/105648

Note, I prepared this PR to be rebased and merged with three commits that are 
self-sufficient and build on each other.

Fix some false negatives of StackAddrEscapeChecker:
- Output parameters
  ```
  void top(int **out) {
int local = 42;
*out = &local; // Noncompliant
  }
  ```
- Indirect global pointers
  ```
  int **global;

  void top() {
int local = 42;
*global = &local; // Noncompliant
  }
  ```

Note that now StackAddrEscapeChecker produces a diagnostic if a function with 
an output parameter is analyzed as top-level or as a callee. I took special 
care to make sure the reports point to the same primary location and, in many 
cases, feature the same primary message. That is the motivation to modify 
Core/BugReporter.cpp and Core/ExplodedGraph.cpp

To avoid false positive reports when a global indirect pointer is assigned a 
local address, invalidated, and then reset, I rely on the fact that the 
invalidation symbol will be a DerivedSymbol of a ConjuredSymbol that refers to 
the same memory region.

The checker still has a false negative for non-trivial escaping via a returned 
value. It requires an active

https://sonarsource.atlassian.net/browse/CPP-4734

>From 9219884befe8e3c7b4ac8bcbfce9ecf9063713ec Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/3] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +3

[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Arseniy Zaostrovnykh (necto)


Changes

Note, I prepared this PR to be rebased and merged with three commits that are 
self-sufficient and build on each other.

Fix some false negatives of StackAddrEscapeChecker:
- Output parameters
  ```
  void top(int **out) {
int local = 42;
*out = &local; // Noncompliant
  }
  ```
- Indirect global pointers
  ```
  int **global;

  void top() {
int local = 42;
*global = &local; // Noncompliant
  }
  ```

Note that now StackAddrEscapeChecker produces a diagnostic if a function with 
an output parameter is analyzed as top-level or as a callee. I took special 
care to make sure the reports point to the same primary location and, in many 
cases, feature the same primary message. That is the motivation to modify 
Core/BugReporter.cpp and Core/ExplodedGraph.cpp

To avoid false positive reports when a global indirect pointer is assigned a 
local address, invalidated, and then reset, I rely on the fact that the 
invalidation symbol will be a DerivedSymbol of a ConjuredSymbol that refers to 
the same memory region.

The checker still has a false negative for non-trivial escaping via a returned 
value. It requires an active

https://sonarsource.atlassian.net/browse/CPP-4734

---

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


10 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
(+128-38) 
- (modified) clang/lib/StaticAnalyzer/Core/BugReporter.cpp (+12-1) 
- (modified) clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp (+1-1) 
- (modified) clang/test/Analysis/copy-elision.cpp (+10-10) 
- (modified) clang/test/Analysis/incorrect-checker-names.cpp (+2-2) 
- (modified) clang/test/Analysis/loop-block-counts.c (+1-1) 
- (modified) clang/test/Analysis/stack-addr-ps.c (+31) 
- (modified) clang/test/Analysis/stack-addr-ps.cpp (+608-1) 
- (modified) clang/test/Analysis/stack-capture-leak-no-arc.mm (+2-2) 
- (modified) clang/test/Analysis/stackaddrleak.c (+4-4) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..ef477a808fac17 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,89 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) {
+  assert(R);
+  if (const auto *MemSpace = R->getMemorySpace()) {
+if (const auto *SSR = MemSpace->getAs())
+  return SSR;
+if (const auto *GSR = MemSpace->getAs())
+  return GSR;
+  }
+  // If R describes a lambda capture, it will be a symbolic region
+  // referring to a field region of another symbolic region.
+  if (const auto *SymReg = R->getBaseRegion()->getAs()) {
+if (const auto *OriginReg = SymReg->getSymbol()->getOriginRegion())
+  return getStackOrGlobalSpaceRegion(OriginReg);
+  }
+  return nullptr;
+}
+
+const MemRegion *getOriginBaseRegion(const MemRegion *Referrer) {
+  Referrer = Referrer->getBaseRegion();
+  while (const auto *SymReg = dyn_cast(Referrer)) {
+Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+  }
+  return Referrer;
+}
+
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+// UnknownSpaceRegion usually refers to pointers-to-pointers,
+// might be in top frame or not with pointers-to-pointers-to-pointers
+assert((isa(Space)));
+// These two cases are deliberately combined to keep the message identical
+// between the top-level and inlined analysis of the same function
+return "caller";
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr
+  return std::nullopt;
+} else {
+  Referrer->dump();
+  assert(false && "Unexpected referrer region type.");
+  return std::nullopt;
+}
+  }
+  assert(Referrer);
+  assert(Referrer->canPrintPretty());
+
+  std::string buf;
+  llvm::raw_string_ostream os(buf);
+  os << ReferrerMemorySpace << " variable ";
+  Referrer->printPretty(os);
+  return buf;
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  Progra

[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Arseniy Zaostrovnykh (necto)


Changes

Note, I prepared this PR to be rebased and merged with three commits that are 
self-sufficient and build on each other.

Fix some false negatives of StackAddrEscapeChecker:
- Output parameters
  ```
  void top(int **out) {
int local = 42;
*out = &local; // Noncompliant
  }
  ```
- Indirect global pointers
  ```
  int **global;

  void top() {
int local = 42;
*global = &local; // Noncompliant
  }
  ```

Note that now StackAddrEscapeChecker produces a diagnostic if a function with 
an output parameter is analyzed as top-level or as a callee. I took special 
care to make sure the reports point to the same primary location and, in many 
cases, feature the same primary message. That is the motivation to modify 
Core/BugReporter.cpp and Core/ExplodedGraph.cpp

To avoid false positive reports when a global indirect pointer is assigned a 
local address, invalidated, and then reset, I rely on the fact that the 
invalidation symbol will be a DerivedSymbol of a ConjuredSymbol that refers to 
the same memory region.

The checker still has a false negative for non-trivial escaping via a returned 
value. It requires an active

https://sonarsource.atlassian.net/browse/CPP-4734

---

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


10 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
(+128-38) 
- (modified) clang/lib/StaticAnalyzer/Core/BugReporter.cpp (+12-1) 
- (modified) clang/lib/StaticAnalyzer/Core/ExplodedGraph.cpp (+1-1) 
- (modified) clang/test/Analysis/copy-elision.cpp (+10-10) 
- (modified) clang/test/Analysis/incorrect-checker-names.cpp (+2-2) 
- (modified) clang/test/Analysis/loop-block-counts.c (+1-1) 
- (modified) clang/test/Analysis/stack-addr-ps.c (+31) 
- (modified) clang/test/Analysis/stack-addr-ps.cpp (+608-1) 
- (modified) clang/test/Analysis/stack-capture-leak-no-arc.mm (+2-2) 
- (modified) clang/test/Analysis/stackaddrleak.c (+4-4) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..ef477a808fac17 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,89 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) {
+  assert(R);
+  if (const auto *MemSpace = R->getMemorySpace()) {
+if (const auto *SSR = MemSpace->getAs())
+  return SSR;
+if (const auto *GSR = MemSpace->getAs())
+  return GSR;
+  }
+  // If R describes a lambda capture, it will be a symbolic region
+  // referring to a field region of another symbolic region.
+  if (const auto *SymReg = R->getBaseRegion()->getAs()) {
+if (const auto *OriginReg = SymReg->getSymbol()->getOriginRegion())
+  return getStackOrGlobalSpaceRegion(OriginReg);
+  }
+  return nullptr;
+}
+
+const MemRegion *getOriginBaseRegion(const MemRegion *Referrer) {
+  Referrer = Referrer->getBaseRegion();
+  while (const auto *SymReg = dyn_cast(Referrer)) {
+Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+  }
+  return Referrer;
+}
+
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+// UnknownSpaceRegion usually refers to pointers-to-pointers,
+// might be in top frame or not with pointers-to-pointers-to-pointers
+assert((isa(Space)));
+// These two cases are deliberately combined to keep the message identical
+// between the top-level and inlined analysis of the same function
+return "caller";
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr
+  return std::nullopt;
+} else {
+  Referrer->dump();
+  assert(false && "Unexpected referrer region type.");
+  return std::nullopt;
+}
+  }
+  assert(Referrer);
+  assert(Referrer->canPrintPretty());
+
+  std::string buf;
+  llvm::raw_string_ostream os(buf);
+  os << ReferrerMemorySpace << " variable ";
+  Referrer->printPretty(os);
+  return buf;
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = 

[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Balazs Benics via cfe-commits

steakhal wrote:

Review commit by commit.

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

necto wrote:

It turns out that you cannot rebase&merge in llvm-project repo, so I'll create 
two more PRs stacked PRs - one per commit


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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto updated 
https://github.com/llvm/llvm-project/pull/105648

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/3] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only have VarRegions here.
-// Anything else is reall

[clang] d7da79f - [NFC][SetTheory] Refactor to use const pointers and range loops (#105544)

2024-08-22 Thread via cfe-commits

Author: Rahul Joshi
Date: 2024-08-22T05:47:31-07:00
New Revision: d7da79f2cd025ab1a526c7011aab062817a656b2

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

LOG: [NFC][SetTheory] Refactor to use const pointers and range loops (#105544)

- Refactor SetTheory code to use const pointers when possible.
- Use auto for variables initialized using dyn_cast<>.
- Use range based for loops and early continue.

Added: 


Modified: 
clang/utils/TableGen/NeonEmitter.cpp
llvm/include/llvm/TableGen/SetTheory.h
llvm/lib/TableGen/SetTheory.cpp
llvm/utils/TableGen/Common/CodeGenRegisters.cpp
llvm/utils/TableGen/Common/CodeGenSchedule.cpp

Removed: 




diff  --git a/clang/utils/TableGen/NeonEmitter.cpp 
b/clang/utils/TableGen/NeonEmitter.cpp
index 30fbb8c5d65e5f..8ec8e67388bbd2 100644
--- a/clang/utils/TableGen/NeonEmitter.cpp
+++ b/clang/utils/TableGen/NeonEmitter.cpp
@@ -1569,7 +1569,7 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
   // See the documentation in arm_neon.td for a description of these operators.
   class LowHalf : public SetTheory::Operator {
   public:
-void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
+void apply(SetTheory &ST, const DagInit *Expr, SetTheory::RecSet &Elts,
ArrayRef Loc) override {
   SetTheory::RecSet Elts2;
   ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
@@ -1579,7 +1579,7 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
 
   class HighHalf : public SetTheory::Operator {
   public:
-void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
+void apply(SetTheory &ST, const DagInit *Expr, SetTheory::RecSet &Elts,
ArrayRef Loc) override {
   SetTheory::RecSet Elts2;
   ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
@@ -1593,7 +1593,7 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
   public:
 Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
 
-void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
+void apply(SetTheory &ST, const DagInit *Expr, SetTheory::RecSet &Elts,
ArrayRef Loc) override {
   SetTheory::RecSet Elts2;
   ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
@@ -1618,7 +1618,8 @@ std::pair 
Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
   public:
 MaskExpander(unsigned N) : N(N) {}
 
-void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
+void expand(SetTheory &ST, const Record *R,
+SetTheory::RecSet &Elts) override {
   unsigned Addend = 0;
   if (R->getName() == "mask0")
 Addend = 0;

diff  --git a/llvm/include/llvm/TableGen/SetTheory.h 
b/llvm/include/llvm/TableGen/SetTheory.h
index 4cff688164b0c4..954453b783d4d8 100644
--- a/llvm/include/llvm/TableGen/SetTheory.h
+++ b/llvm/include/llvm/TableGen/SetTheory.h
@@ -76,7 +76,7 @@ class SetTheory {
 
 /// apply - Apply this operator to Expr's arguments and insert the result
 /// in Elts.
-virtual void apply(SetTheory&, DagInit *Expr, RecSet &Elts,
+virtual void apply(SetTheory &, const DagInit *Expr, RecSet &Elts,
ArrayRef Loc) = 0;
   };
 
@@ -89,13 +89,13 @@ class SetTheory {
   public:
 virtual ~Expander() = default;
 
-virtual void expand(SetTheory&, Record*, RecSet &Elts) = 0;
+virtual void expand(SetTheory &, const Record *, RecSet &Elts) = 0;
   };
 
 private:
   // Map set defs to their fully expanded contents. This serves as a 
memoization
   // cache and it makes it possible to return const references on queries.
-  using ExpandMap = std::map;
+  using ExpandMap = std::map;
   ExpandMap Expansions;
 
   // Known DAG operators by name.
@@ -125,7 +125,7 @@ class SetTheory {
   void addOperator(StringRef Name, std::unique_ptr);
 
   /// evaluate - Evaluate Expr and append the resulting set to Elts.
-  void evaluate(Init *Expr, RecSet &Elts, ArrayRef Loc);
+  void evaluate(const Init *Expr, RecSet &Elts, ArrayRef Loc);
 
   /// evaluate - Evaluate a sequence of Inits and append to Elts.
   template
@@ -137,7 +137,7 @@ class SetTheory {
   /// expand - Expand a record into a set of elements if possible.  Return a
   /// pointer to the expanded elements, or NULL if Set cannot be expanded
   /// further.
-  const RecVec *expand(Record *Set);
+  const RecVec *expand(const Record *Set);
 };
 
 } // end namespace llvm

diff  --git a/llvm/lib/TableGen/SetTheory.cpp b/llvm/lib/TableGen/SetTheory.cpp
index f4e3e3d4ce473b..edb99827f7c676 100644
--- a/llvm/lib/TableGen/SetTheory.cpp
+++ b/llvm/lib/TableGen/SetTheory.cpp
@@ -13,6 +13,7 @@
 
 #include "llvm/TableGen/SetTheory.h"
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/STL

[clang] [llvm] [NFC][SetTheory] Refactor to use const pointers and range loops (PR #105544)

2024-08-22 Thread Rahul Joshi via cfe-commits

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


[clang] [analyzer] [NFC] Add tests for and refactor StackAddrEscapeChecker (PR #105652)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto created 
https://github.com/llvm/llvm-project/pull/105652

These tests and refactoring are preparatory for the upcoming changes: detection 
of the indirect leak via global variables and output parameters.

CPP-4734

---

This is 1 of three commits constituting 
https://github.com/llvm/llvm-project/pull/105648

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(

[clang] [analyzer] [NFC] Add tests for and refactor StackAddrEscapeChecker (PR #105652)

2024-08-22 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-static-analyzer-1

@llvm/pr-subscribers-clang

Author: Arseniy Zaostrovnykh (necto)


Changes

These tests and refactoring are preparatory for the upcoming changes: detection 
of the indirect leak via global variables and output parameters.

CPP-4734

---

This is 1 of three commits constituting 
https://github.com/llvm/llvm-project/pull/105648

---

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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
(+38-33) 
- (modified) clang/test/Analysis/stack-addr-ps.c (+31) 
- (modified) clang/test/Analysis/stack-addr-ps.cpp (+596) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   return;
 }
 
-const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
-  if (isa(Space))
-return "static";
-  if (isa(Space))
-return "global";
-  assert(isa(Space));
-  return "stack";
-}(Referrer->getMemorySpace());
-
-// We should really only ha

[clang] [analyzer] [NFC] Add tests for and refactor StackAddrEscapeChecker (PR #105652)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer] Moving TaintPropagation checker out of alpha (PR #67352)

2024-08-22 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Moving TaintPropagation checker out of alpha (PR #67352)

2024-08-22 Thread Balazs Benics via cfe-commits

https://github.com/steakhal commented:

I tried to look at the mentioned 3 TPs, but the links appear to be broken.

Contentwise, I assume its a pure cut-and-paste modulo replacement of `alpha` to 
`optin`.
I have no objection from moving this checker out of alpha.

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


[clang] [analyzer] Moving TaintPropagation checker out of alpha (PR #67352)

2024-08-22 Thread Balazs Benics via cfe-commits


@@ -992,6 +992,241 @@ optin.portability.UnixAPI
 "
 Finds implementation-defined behavior in UNIX/Posix functions.
 
+
+optin.taint
+

steakhal wrote:

```suggestion
optin.taint
^^^
```

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


[clang] [analyzer] Moving TaintPropagation checker out of alpha (PR #67352)

2024-08-22 Thread Balazs Benics via cfe-commits


@@ -992,6 +992,241 @@ optin.portability.UnixAPI
 "
 Finds implementation-defined behavior in UNIX/Posix functions.
 
+
+optin.taint
+
+
+Checkers implementing
+`taint analysis `_.
+
+.. _optin-taint-GenericTaint:
+
+optin.taint.GenericTaint (C, C++)
+""

steakhal wrote:

```suggestion
optin.taint.GenericTaint (C, C++)
"
```

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


[clang] [analyzer] Detect leak of a stack address through output arguments (PR #105653)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

https://github.com/necto created 
https://github.com/llvm/llvm-project/pull/105653

At this point, only functions called from other functions (i.e., not
top-level) are covered. Top-level functions have a different exit
sequence and will be handled by a subsequent change.

CPP-4734

---

This is the second of three commits constituting 
https://github.com/llvm/llvm-project/pull/105648
it must not be merged before https://github.com/llvm/llvm-project/pull/105652

>From db68dcfba96bfbf9367ba4159b6bf179c8c56f4f Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Tue, 20 Aug 2024 10:26:38 +0200
Subject: [PATCH 1/2] [analyzer] [NFC] Add tests for and refactor
 StackAddrEscapeChecker

These tests and refactoring are preparatory for the upcoming changes:
detection of the indirect leak via global variables and output parameters.

CPP-4734
---
 .../Checkers/StackAddrEscapeChecker.cpp   |  71 ++-
 clang/test/Analysis/stack-addr-ps.c   |  31 +
 clang/test/Analysis/stack-addr-ps.cpp | 596 ++
 3 files changed, 665 insertions(+), 33 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..2bd4ca4528de8b 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,37 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(Referrer->getMemorySpace());
+
+  // We should really only have VarRegions here.
+  // Anything else is really surprising, and we should get notified if such
+  // ever happens.
+  const auto *ReferrerVar = dyn_cast(Referrer);
+  if (!ReferrerVar) {
+assert(false && "We should have a VarRegion here");
+return std::nullopt; // Defensively skip this one.
+  }
+  const std::string ReferrerVarName =
+  ReferrerVar->getDecl()->getDeclName().getAsString();
+
+  return (ReferrerMemorySpace + " variable '" + ReferrerVarName + "'").str();
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -315,15 +340,10 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
-
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerMemSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +372,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
   Cb);
 
@@ -359,7 +380,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 return;
 
   // Generate an error node.
-  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State);
+  ExplodedNode *N = Ctx.generateNonFatalErrorNode(State, Node);
   if (!N)
 return;
 
@@ -374,13 +395,13 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 
 // Generate a report for this bug.
 const StringRef CommonSuffix =
-"upon returning to the caller.  This will be a dangling reference";
+" upon returning to the caller.  This will be a dangling reference";
 SmallString<128> Buf;
 llvm::raw_svector_ostream Out(Buf);
 const SourceRange Range = genName(Out, Referred, Ctx.getASTContext());
 
 if (isa(Referrer)) {
-  Out << " is still referred to by a temporary object on the stack "
+  Out << " is still referred to by a temporary object on the stack"
   << CommonSuffix;
   auto Report =
   std::make_unique(*BT_stackleak, Out.str(), 
N);
@@ -390,28 +411,12 @@ void StackAddrEscapeChecker::checkEndFunction(const 

[clang] [analyzer] Detect leak of a stack address through output arguments (PR #105653)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer] Detect leak of a stack address through output arguments (PR #105653)

2024-08-22 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-static-analyzer-1

Author: Arseniy Zaostrovnykh (necto)


Changes

At this point, only functions called from other functions (i.e., not
top-level) are covered. Top-level functions have a different exit
sequence and will be handled by a subsequent change.

CPP-4734

---

This is the second of three commits constituting 
https://github.com/llvm/llvm-project/pull/105648
it must not be merged before https://github.com/llvm/llvm-project/pull/105652

---

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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
(+70-35) 
- (modified) clang/test/Analysis/stack-addr-ps.c (+31) 
- (modified) clang/test/Analysis/stack-addr-ps.cpp (+596) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
index ea09c43cc5ce90..a704c4ff2eeb02 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StackAddrEscapeChecker.cpp
@@ -288,12 +288,63 @@ void StackAddrEscapeChecker::checkPreStmt(const 
ReturnStmt *RS,
   EmitStackError(C, R, RetE);
 }
 
+static const MemSpaceRegion *getStackOrGlobalSpaceRegion(const MemRegion *R) {
+  assert(R);
+  if (const auto *MemSpace = R->getMemorySpace()) {
+if (const auto *SSR = MemSpace->getAs())
+  return SSR;
+if (const auto *GSR = MemSpace->getAs())
+  return GSR;
+  }
+  // If R describes a lambda capture, it will be a symbolic region
+  // referring to a field region of another symbolic region.
+  if (const auto *SymReg = R->getBaseRegion()->getAs()) {
+if (const auto *OriginReg = SymReg->getSymbol()->getOriginRegion())
+  return getStackOrGlobalSpaceRegion(OriginReg);
+  }
+  return nullptr;
+}
+
+std::optional printReferrer(const MemRegion *Referrer) {
+  assert(Referrer);
+  const StringRef ReferrerMemorySpace = [](const MemSpaceRegion *Space) {
+if (isa(Space))
+  return "static";
+if (isa(Space))
+  return "global";
+assert(isa(Space));
+return "stack";
+  }(getStackOrGlobalSpaceRegion(Referrer));
+
+  while (!Referrer->canPrintPretty()) {
+if (const auto *SymReg = dyn_cast(Referrer)) {
+  Referrer = SymReg->getSymbol()->getOriginRegion()->getBaseRegion();
+} else if (isa(Referrer)) {
+  // Skip members of a class, it is handled by
+  // warn_bind_ref_member_to_parameter_addr
+  return std::nullopt;
+} else {
+  Referrer->dump();
+  assert(false && "Unexpected referrer region type.");
+  return std::nullopt;
+}
+  }
+  assert(Referrer);
+  assert(Referrer->canPrintPretty());
+
+  std::string buf;
+  llvm::raw_string_ostream os(buf);
+  os << ReferrerMemorySpace << " variable ";
+  Referrer->printPretty(os);
+  return buf;
+}
+
 void StackAddrEscapeChecker::checkEndFunction(const ReturnStmt *RS,
   CheckerContext &Ctx) const {
   if (!ChecksEnabled[CK_StackAddrEscapeChecker])
 return;
 
-  ProgramStateRef State = Ctx.getState();
+  ExplodedNode *Node = Ctx.getPredecessor();
 
   // Iterate over all bindings to global variables and see if it contains
   // a memory region in the stack space.
@@ -307,23 +358,22 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
 /// referred by an other stack variable from different stack frame.
 bool checkForDanglingStackVariable(const MemRegion *Referrer,
const MemRegion *Referred) {
-  const auto *ReferrerMemSpace =
-  Referrer->getMemorySpace()->getAs();
+  const auto *ReferrerMemSpace = getStackOrGlobalSpaceRegion(Referrer);
   const auto *ReferredMemSpace =
   Referred->getMemorySpace()->getAs();
 
   if (!ReferrerMemSpace || !ReferredMemSpace)
 return false;
 
-  const auto *ReferrerFrame = ReferrerMemSpace->getStackFrame();
-  const auto *ReferredFrame = ReferredMemSpace->getStackFrame();
+  const auto *ReferrerStackSpace =
+  ReferrerMemSpace->getAs();
+  if (!ReferrerStackSpace)
+return false;
 
-  if (ReferrerMemSpace && ReferredMemSpace) {
-if (ReferredFrame == PoppedFrame &&
-ReferrerFrame->isParentOf(PoppedFrame)) {
-  V.emplace_back(Referrer, Referred);
-  return true;
-}
+  if (ReferredMemSpace->getStackFrame() == PoppedFrame &&
+  ReferrerStackSpace->getStackFrame()->isParentOf(PoppedFrame)) {
+V.emplace_back(Referrer, Referred);
+return true;
   }
   return false;
 }
@@ -352,6 +402,7 @@ void StackAddrEscapeChecker::checkEndFunction(const 
ReturnStmt *RS,
   };
 
   CallBack Cb(Ctx);
+  ProgramStateRef State = Node->getState();
   State->getStateManager().getStoreManager().iterBindings(State->getStore(),
  

[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] [analyzer][NFC] Add tests for and refactor StackAddrEscapeChecker (PR #105652)

2024-08-22 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer][NFC] Add tests for and refactor StackAddrEscapeChecker 1/3 (PR #105652)

2024-08-22 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Detect leak of a stack address through output arguments 2/3 (PR #105653)

2024-08-22 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals 3/3 (PR #105648)

2024-08-22 Thread Balazs Benics via cfe-commits

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals 3/3 (PR #105648)

2024-08-22 Thread Balazs Benics via cfe-commits

steakhal wrote:

I already reviewed these three. LGTM

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


[clang] [analyzer] Detect leaks of stack addresses via output params, indirect globals 3/3 (PR #105648)

2024-08-22 Thread Arseniy Zaostrovnykh via cfe-commits

necto wrote:

> It turns out that you cannot rebase&merge in llvm-project repo, so I'll 
> create two more PRs stacked PRs - one per commit

Here are the two PRs that promote the first two commits of this branch: 
https://github.com/llvm/llvm-project/pull/105652 and 
https://github.com/llvm/llvm-project/pull/105653

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


[clang] [Clang] Implement C++26’s P2893R3 ‘Variadic friends’ (PR #101448)

2024-08-22 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

Note that there have been additional discussions happening on the new proposed 
resolution.
https://lists.isocpp.org/core/2024/08/16236.php

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


[clang] [clang][analyzer] Bring alpha.security.MmapWriteExec checker out of alpha package (PR #102636)

2024-08-22 Thread Balazs Benics via cfe-commits

steakhal wrote:

`nasm`, `breakpad`, `tinycbor`, `snappy`, `ffmpeg`, `libxml`, `tflite`, 
`tensorflow`, `abseil-cpp`, `LibreOffice`, `Redis`, `mongodb`, `PostgreSQL`, 
`rocksdb`, `aragondb`, `MySQL`, `HHVM`, `nginx`, `zfs`, `zstd`, 
`Clang/compiler-rt`, `transmission`, `OpenSSL` [and more] appears to reference 
`mmap` directly or transitively.

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


[clang] [Clang][Sema] Rebuild template parameters for out-of-line template definitions and partial specializations (PR #104030)

2024-08-22 Thread Krystian Stasiowski via cfe-commits

https://github.com/sdkrystian updated 
https://github.com/llvm/llvm-project/pull/104030

>From 14db4ba124a36ea778515fe0228ae959081f6d65 Mon Sep 17 00:00:00 2001
From: Krystian Stasiowski 
Date: Wed, 14 Aug 2024 09:00:30 -0400
Subject: [PATCH 1/3] [Clang][Sema] Rebuild template parameters for out-of-line
 template definitions and partial specializations

---
 clang/lib/Sema/SemaDecl.cpp   |   6 +
 clang/lib/Sema/SemaTemplate.cpp   |  20 ++--
 .../test/CXX/temp/temp.decls/temp.mem/p1.cpp  | 112 +-
 3 files changed, 129 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 503e93f9257137..b0ccbbe34b70c3 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -7502,6 +7502,12 @@ NamedDecl *Sema::ActOnVariableDeclarator(
 /*never a friend*/ false, IsMemberSpecialization, Invalid);
 
 if (TemplateParams) {
+  if (DC->isDependentContext()) {
+ContextRAII SavedContext(*this, DC);
+if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
+  Invalid = true;
+  }
+
   if (!TemplateParams->size() &&
   D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
 // There is an extraneous 'template<>' for this variable. Complain
diff --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 992565701d40ca..f8f41d0bafffc3 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -8089,13 +8089,14 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
 return true;
   }
 
+  DeclContext *DC = ClassTemplate->getDeclContext();
+
   bool isMemberSpecialization = false;
   bool isPartialSpecialization = false;
 
   if (SS.isSet()) {
 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
-diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
- ClassTemplate->getDeclName(),
+diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
  TemplateNameLoc, &TemplateId,
  /*IsMemberSpecialization=*/false))
   return true;
@@ -8117,6 +8118,12 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
 return true;
 
+  if (TemplateParams && DC->isDependentContext()) {
+ContextRAII SavedContext(*this, DC);
+if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
+  return true;
+  }
+
   if (TemplateParams && TemplateParams->size() > 0) {
 isPartialSpecialization = true;
 
@@ -8282,9 +8289,8 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   = cast_or_null(PrevDecl);
 ClassTemplatePartialSpecializationDecl *Partial =
 ClassTemplatePartialSpecializationDecl::Create(
-Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
-TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
-CanonType, PrevPartial);
+Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
+ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
 Partial->setTemplateArgsAsWritten(TemplateArgs);
 SetNestedNameSpecifier(*this, Partial, SS);
 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
@@ -8306,8 +8312,8 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
 // Create a new class template specialization declaration node for
 // this explicit specialization or friend declaration.
 Specialization = ClassTemplateSpecializationDecl::Create(
-Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
-ClassTemplate, CanonicalConverted, PrevDecl);
+Context, Kind, DC, KWLoc, TemplateNameLoc, ClassTemplate,
+CanonicalConverted, PrevDecl);
 Specialization->setTemplateArgsAsWritten(TemplateArgs);
 SetNestedNameSpecifier(*this, Specialization, SS);
 if (TemplateParameterLists.size() > 0) {
diff --git a/clang/test/CXX/temp/temp.decls/temp.mem/p1.cpp 
b/clang/test/CXX/temp/temp.decls/temp.mem/p1.cpp
index b48e145e1468db..64b1274419e35d 100644
--- a/clang/test/CXX/temp/temp.decls/temp.mem/p1.cpp
+++ b/clang/test/CXX/temp/temp.decls/temp.mem/p1.cpp
@@ -1,5 +1,4 @@
-// RUN: %clang_cc1 -fsyntax-only -verify %s
-// expected-no-diagnostics
+// RUN: %clang_cc1 -fsyntax-only -std=c++20 -verify %s
 
 template  struct A {
   static T cond;
@@ -35,3 +34,112 @@ namespace PR6376 {
 
   Z z0;
 }
+
+namespace OutOfLine {
+  template
+  struct A {
+struct B { };
+
+template
+void f();
+
+template
+void g() { } // expected-note {{previous definition is here}}
+
+template
+static int x;
+
+template
+static int x;
+
+template
+static constexpr int x = 0; // expected-note {{previous definition 
is here}}
+
+template
+struct C;
+
+template
+struct C;
+
+templ

[clang] [analyzer][NFC] Add tests for and refactor StackAddrEscapeChecker 1/3 (PR #105652)

2024-08-22 Thread Donát Nagy via cfe-commits

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

Nice cleanup, I especially like the through testing.

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


[clang] [clang][AArch64] Add SME2.1 feature macros (PR #105657)

2024-08-22 Thread via cfe-commits

https://github.com/SpencerAbson created 
https://github.com/llvm/llvm-project/pull/105657

This patch adds the following macros to clang which are described in the alpha 
SME2.1 specification 
([ACLE](https://github.com/ARM-software/acle/pull/309/files)).

- __ARM_FEATURE_SMEB16B16 (enabled by '+sme-b16b16')
- __ARM_FEATURE_SVEB16B16 (enabled by '+sve-b16b16' or '+sme-b16b16')
- __ARM_FEATURE_SMEF16F16 (enabled by '+sme-f16f16')

Redundant use of the clang macro-builder has also been removed, pre-processor 
tests have been added for each new macro.

>From 00a9729b2c9165216bb121ef21c71cef804dd429 Mon Sep 17 00:00:00 2001
From: Spencer Abson 
Date: Thu, 22 Aug 2024 13:14:19 +
Subject: [PATCH] [clang][AArch64] Add SME2.1 feature macros

This patch adds the following macros to clang which are described in the
alpha SME2.1 specification within the ACLE
(https://github.com/ARM-software/acle/pull/309/files)

- __ARM_FEATURE_SMEB16B16 (enabled by '+sme-b16b16')
- __ARM_FEATURE_SVEB16B16 (enabled by '+sve-b16b16' or '+sme-b16b16')
- __ARM_FEATURE_SMEF16F16 (enabled by '+sme-f16f16')

Redundant use of the clang macro-builder has also been removed, pre-processor
tests have been added for each new macro.
---
 clang/lib/Basic/Targets/AArch64.cpp   | 40 ++-
 clang/lib/Basic/Targets/AArch64.h |  3 ++
 .../Preprocessor/aarch64-target-features.c| 16 
 3 files changed, 50 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 6ba31cc05a0d75..63fc15f916c558 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -471,23 +471,25 @@ void AArch64TargetInfo::getTargetDefines(const 
LangOptions &Opts,
   if (HasSVE2 && HasSVE2SM4)
 Builder.defineMacro("__ARM_FEATURE_SVE2_SM4", "1");
 
+  if (HasSVEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SVE_B16B16", "1");
+
   if (HasSME) {
 Builder.defineMacro("__ARM_FEATURE_SME");
 Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
   }
 
-  if (HasSME2) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
+  if (HasSME2)
 Builder.defineMacro("__ARM_FEATURE_SME2", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
 
-  if (HasSME2p1) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
-Builder.defineMacro("__ARM_FEATURE_SME2", "1");
+  if (HasSME2p1)
 Builder.defineMacro("__ARM_FEATURE_SME2p1", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
+
+  if (HasSMEF16F16)
+Builder.defineMacro("__ARM_FEATURE_SME_F16F16", "1");
+
+  if (HasSMEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SME_B16B16", "1");
 
   if (HasCRC)
 Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
@@ -749,6 +751,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sve", FPU & SveMode)
   .Case("sve-bf16", FPU & SveMode && HasBFloat16)
   .Case("sve-i8mm", FPU & SveMode && HasMatMul)
+  .Case("sve-b16b16", HasSVEB16B16)
   .Case("f32mm", FPU & SveMode && HasMatmulFP32)
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
@@ -763,6 +766,8 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sme-f64f64", HasSMEF64F64)
   .Case("sme-i16i64", HasSMEI16I64)
   .Case("sme-fa64", HasSMEFA64)
+  .Case("sme-f16f16", HasSMEF16F16)
+  .Case("sme-b16b16", HasSMEB16B16)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -863,6 +868,8 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSVE2SM4 = true;
 }
+if (Feature == "+sve-b16b16")
+  HasSVEB16B16 = true;
 if (Feature == "+sve2-bitperm") {
   FPU |= NeonMode;
   FPU |= SveMode;
@@ -919,6 +926,21 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSMEFA64 = true;
 }
+if (Feature == "+sme-f16f16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSMEF16F16 = true;
+}
+if (Feature == "+sme-b16b16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSVEB16B16 = true;
+  HasSMEB16B16 = true;
+}
 if (Feature == "+sb")
   HasSB = true;
 if (Feature == "+predres")
diff --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7bdf5a2b4106e4..526f7f30a38618 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSVE2AES = false;
   bool HasSVE2SHA3 = false;
   bool HasSVE2SM4 = false;
+  bool HasSVEB16B16 = false;
   bool HasSVE2BitPerm = false;
   bool HasMatmulFP64 = false;
   bool HasMatmulFP32 = false;
@@

[clang] [clang][AArch64] Add SME2.1 feature macros (PR #105657)

2024-08-22 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-backend-aarch64

@llvm/pr-subscribers-clang

Author: None (SpencerAbson)


Changes

This patch adds the following macros to clang which are described in the alpha 
SME2.1 specification 
([ACLE](https://github.com/ARM-software/acle/pull/309/files)).

- __ARM_FEATURE_SMEB16B16 (enabled by '+sme-b16b16')
- __ARM_FEATURE_SVEB16B16 (enabled by '+sve-b16b16' or '+sme-b16b16')
- __ARM_FEATURE_SMEF16F16 (enabled by '+sme-f16f16')

Redundant use of the clang macro-builder has also been removed, pre-processor 
tests have been added for each new macro.

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


3 Files Affected:

- (modified) clang/lib/Basic/Targets/AArch64.cpp (+31-9) 
- (modified) clang/lib/Basic/Targets/AArch64.h (+3) 
- (modified) clang/test/Preprocessor/aarch64-target-features.c (+16) 


``diff
diff --git a/clang/lib/Basic/Targets/AArch64.cpp 
b/clang/lib/Basic/Targets/AArch64.cpp
index 6ba31cc05a0d75..63fc15f916c558 100644
--- a/clang/lib/Basic/Targets/AArch64.cpp
+++ b/clang/lib/Basic/Targets/AArch64.cpp
@@ -471,23 +471,25 @@ void AArch64TargetInfo::getTargetDefines(const 
LangOptions &Opts,
   if (HasSVE2 && HasSVE2SM4)
 Builder.defineMacro("__ARM_FEATURE_SVE2_SM4", "1");
 
+  if (HasSVEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SVE_B16B16", "1");
+
   if (HasSME) {
 Builder.defineMacro("__ARM_FEATURE_SME");
 Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
   }
 
-  if (HasSME2) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
+  if (HasSME2)
 Builder.defineMacro("__ARM_FEATURE_SME2", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
 
-  if (HasSME2p1) {
-Builder.defineMacro("__ARM_FEATURE_SME", "1");
-Builder.defineMacro("__ARM_FEATURE_SME2", "1");
+  if (HasSME2p1)
 Builder.defineMacro("__ARM_FEATURE_SME2p1", "1");
-Builder.defineMacro("__ARM_FEATURE_LOCALLY_STREAMING", "1");
-  }
+
+  if (HasSMEF16F16)
+Builder.defineMacro("__ARM_FEATURE_SME_F16F16", "1");
+
+  if (HasSMEB16B16)
+Builder.defineMacro("__ARM_FEATURE_SME_B16B16", "1");
 
   if (HasCRC)
 Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
@@ -749,6 +751,7 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sve", FPU & SveMode)
   .Case("sve-bf16", FPU & SveMode && HasBFloat16)
   .Case("sve-i8mm", FPU & SveMode && HasMatMul)
+  .Case("sve-b16b16", HasSVEB16B16)
   .Case("f32mm", FPU & SveMode && HasMatmulFP32)
   .Case("f64mm", FPU & SveMode && HasMatmulFP64)
   .Case("sve2", FPU & SveMode && HasSVE2)
@@ -763,6 +766,8 @@ bool AArch64TargetInfo::hasFeature(StringRef Feature) const 
{
   .Case("sme-f64f64", HasSMEF64F64)
   .Case("sme-i16i64", HasSMEI16I64)
   .Case("sme-fa64", HasSMEFA64)
+  .Case("sme-f16f16", HasSMEF16F16)
+  .Case("sme-b16b16", HasSMEB16B16)
   .Cases("memtag", "memtag2", HasMTE)
   .Case("sb", HasSB)
   .Case("predres", HasPredRes)
@@ -863,6 +868,8 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSVE2SM4 = true;
 }
+if (Feature == "+sve-b16b16")
+  HasSVEB16B16 = true;
 if (Feature == "+sve2-bitperm") {
   FPU |= NeonMode;
   FPU |= SveMode;
@@ -919,6 +926,21 @@ bool 
AArch64TargetInfo::handleTargetFeatures(std::vector &Features,
   HasSVE2 = true;
   HasSMEFA64 = true;
 }
+if (Feature == "+sme-f16f16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSMEF16F16 = true;
+}
+if (Feature == "+sme-b16b16") {
+  HasSME = true;
+  HasSME2 = true;
+  HasBFloat16 = true;
+  HasFullFP16 = true;
+  HasSVEB16B16 = true;
+  HasSMEB16B16 = true;
+}
 if (Feature == "+sb")
   HasSB = true;
 if (Feature == "+predres")
diff --git a/clang/lib/Basic/Targets/AArch64.h 
b/clang/lib/Basic/Targets/AArch64.h
index 7bdf5a2b4106e4..526f7f30a38618 100644
--- a/clang/lib/Basic/Targets/AArch64.h
+++ b/clang/lib/Basic/Targets/AArch64.h
@@ -53,6 +53,7 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSVE2AES = false;
   bool HasSVE2SHA3 = false;
   bool HasSVE2SM4 = false;
+  bool HasSVEB16B16 = false;
   bool HasSVE2BitPerm = false;
   bool HasMatmulFP64 = false;
   bool HasMatmulFP32 = false;
@@ -71,6 +72,8 @@ class LLVM_LIBRARY_VISIBILITY AArch64TargetInfo : public 
TargetInfo {
   bool HasSME2 = false;
   bool HasSMEF64F64 = false;
   bool HasSMEI16I64 = false;
+  bool HasSMEF16F16 = false;
+  bool HasSMEB16B16 = false;
   bool HasSME2p1 = false;
   bool HasSB = false;
   bool HasPredRes = false;
diff --git a/clang/test/Preprocessor/aarch64-target-features.c 
b/clang/test/Preprocessor/aarch64-target-features.c
index 87bd3e142d2c40..ae2bdda6f536c5 100644
--- a/clang/test/Preprocessor/aarch64-target-features.c
+++ b/clang/test/Preprocessor/aarch64-target-features.c
@@

[clang] c82f797 - [Clang][Sema] Rebuild template parameters for out-of-line template definitions and partial specializations (#104030)

2024-08-22 Thread via cfe-commits

Author: Krystian Stasiowski
Date: 2024-08-22T09:22:33-04:00
New Revision: c82f7976ae20a7c76904415eae1964bab78f1a04

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

LOG: [Clang][Sema] Rebuild template parameters for out-of-line template 
definitions and partial specializations (#104030)

We need to rebuild the template parameters of out-of-line
definitions/specializations of member templates in the context of the
current instantiation for the purposes of declaration matching. We
already do this for function templates and class templates, but not
variable templates, partial specializations of variable template, and
partial specializations of class templates. This patch fixes the latter
cases.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaDecl.cpp
clang/lib/Sema/SemaTemplate.cpp
clang/test/CXX/temp/temp.decls/temp.mem/p1.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index bb47350f76b308..12a924acc14331 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -294,6 +294,8 @@ Bug Fixes to C++ Support
 - Correctly check constraints of explicit instantiations of member functions. 
(#GH46029)
 - Fixed an assertion failure about a constraint of a friend function template 
references to a value with greater
   template depth than the friend function template. (#GH98258)
+- Clang now rebuilds the template parameters of out-of-line declarations and 
specializations in the context
+  of the current instantiation in all cases.
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 503e93f9257137..b0ccbbe34b70c3 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -7502,6 +7502,12 @@ NamedDecl *Sema::ActOnVariableDeclarator(
 /*never a friend*/ false, IsMemberSpecialization, Invalid);
 
 if (TemplateParams) {
+  if (DC->isDependentContext()) {
+ContextRAII SavedContext(*this, DC);
+if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
+  Invalid = true;
+  }
+
   if (!TemplateParams->size() &&
   D.getName().getKind() != UnqualifiedIdKind::IK_TemplateId) {
 // There is an extraneous 'template<>' for this variable. Complain

diff  --git a/clang/lib/Sema/SemaTemplate.cpp b/clang/lib/Sema/SemaTemplate.cpp
index 992565701d40ca..f8f41d0bafffc3 100644
--- a/clang/lib/Sema/SemaTemplate.cpp
+++ b/clang/lib/Sema/SemaTemplate.cpp
@@ -8089,13 +8089,14 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
 return true;
   }
 
+  DeclContext *DC = ClassTemplate->getDeclContext();
+
   bool isMemberSpecialization = false;
   bool isPartialSpecialization = false;
 
   if (SS.isSet()) {
 if (TUK != TagUseKind::Reference && TUK != TagUseKind::Friend &&
-diagnoseQualifiedDeclaration(SS, ClassTemplate->getDeclContext(),
- ClassTemplate->getDeclName(),
+diagnoseQualifiedDeclaration(SS, DC, ClassTemplate->getDeclName(),
  TemplateNameLoc, &TemplateId,
  /*IsMemberSpecialization=*/false))
   return true;
@@ -8117,6 +8118,12 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   if (TemplateParams && CheckTemplateDeclScope(S, TemplateParams))
 return true;
 
+  if (TemplateParams && DC->isDependentContext()) {
+ContextRAII SavedContext(*this, DC);
+if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
+  return true;
+  }
+
   if (TemplateParams && TemplateParams->size() > 0) {
 isPartialSpecialization = true;
 
@@ -8282,9 +8289,8 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
   = cast_or_null(PrevDecl);
 ClassTemplatePartialSpecializationDecl *Partial =
 ClassTemplatePartialSpecializationDecl::Create(
-Context, Kind, ClassTemplate->getDeclContext(), KWLoc,
-TemplateNameLoc, TemplateParams, ClassTemplate, CanonicalConverted,
-CanonType, PrevPartial);
+Context, Kind, DC, KWLoc, TemplateNameLoc, TemplateParams,
+ClassTemplate, CanonicalConverted, CanonType, PrevPartial);
 Partial->setTemplateArgsAsWritten(TemplateArgs);
 SetNestedNameSpecifier(*this, Partial, SS);
 if (TemplateParameterLists.size() > 1 && SS.isSet()) {
@@ -8306,8 +8312,8 @@ DeclResult Sema::ActOnClassTemplateSpecialization(
 // Create a new class template specialization declaration node for
 // this explicit specialization or friend declaration.
 Specialization = ClassTemplateSpecializationDecl::Create(
-Context, Kind, ClassTemplate->getDeclContext(), KWLoc, TemplateNameLoc,
-ClassTemp

[clang] [Clang][Sema] Rebuild template parameters for out-of-line template definitions and partial specializations (PR #104030)

2024-08-22 Thread Krystian Stasiowski via cfe-commits

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


[clang] db94852 - [clang][bytecode] Allow adding offsets to function pointers (#105641)

2024-08-22 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-08-22T15:23:50+02:00
New Revision: db94852b9b4ca1008ef2889175fe3af51f26a5b0

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

LOG: [clang][bytecode] Allow adding offsets to function pointers (#105641)

Convert them to Pointers, do the offset calculation and then convert
them back to function pointers.

Added: 
clang/lib/AST/ByteCode/FunctionPointer.cpp

Modified: 
clang/lib/AST/ByteCode/Compiler.cpp
clang/lib/AST/ByteCode/FunctionPointer.h
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/Pointer.h
clang/lib/AST/CMakeLists.txt
clang/test/AST/ByteCode/c.c

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index 9d376641f9c5a3..3a3927a9671345 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -885,12 +885,21 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
   if (!LT || !RT)
 return false;
 
+  // Visit the given pointer expression and optionally convert to a PT_Ptr.
+  auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
+if (!this->visit(E))
+  return false;
+if (T != PT_Ptr)
+  return this->emitDecayPtr(T, PT_Ptr, E);
+return true;
+  };
+
   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
 if (Op != BO_Sub)
   return false;
 
 assert(E->getType()->isIntegerType());
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
   return false;
 
 return this->emitSubPtr(classifyPrim(E->getType()), E);
@@ -898,21 +907,38 @@ bool Compiler::VisitPointerArithBinOp(const 
BinaryOperator *E) {
 
   PrimType OffsetType;
   if (LHS->getType()->isIntegerType()) {
-if (!visit(RHS) || !visit(LHS))
+if (!visitAsPointer(RHS, *RT))
+  return false;
+if (!this->visit(LHS))
   return false;
 OffsetType = *LT;
   } else if (RHS->getType()->isIntegerType()) {
-if (!visit(LHS) || !visit(RHS))
+if (!visitAsPointer(LHS, *LT))
+  return false;
+if (!this->visit(RHS))
   return false;
 OffsetType = *RT;
   } else {
 return false;
   }
 
-  if (Op == BO_Add)
-return this->emitAddOffset(OffsetType, E);
-  else if (Op == BO_Sub)
-return this->emitSubOffset(OffsetType, E);
+  // Do the operation and optionally transform to
+  // result pointer type.
+  if (Op == BO_Add) {
+if (!this->emitAddOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  } else if (Op == BO_Sub) {
+if (!this->emitSubOffset(OffsetType, E))
+  return false;
+
+if (classifyPrim(E) != PT_Ptr)
+  return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
+return true;
+  }
 
   return false;
 }

diff  --git a/clang/lib/AST/ByteCode/FunctionPointer.cpp 
b/clang/lib/AST/ByteCode/FunctionPointer.cpp
new file mode 100644
index 00..6b0b559a63386e
--- /dev/null
+++ b/clang/lib/AST/ByteCode/FunctionPointer.cpp
@@ -0,0 +1,43 @@
+//===--- FunctionPointer.cpp *- 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
+//
+//===--===//
+
+#include "FunctionPointer.h"
+
+namespace clang {
+namespace interp {
+
+APValue FunctionPointer::toAPValue(const ASTContext &) const {
+  if (!Func)
+return APValue(static_cast(nullptr), CharUnits::Zero(), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/true);
+
+  if (!Valid)
+return APValue(static_cast(nullptr),
+   CharUnits::fromQuantity(getIntegerRepresentation()), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+
+  if (Func->getDecl())
+return APValue(Func->getDecl(), CharUnits::fromQuantity(Offset), {},
+   /*OnePastTheEnd=*/false, /*IsNull=*/false);
+  return APValue(Func->getExpr(), CharUnits::fromQuantity(Offset), {},
+ /*OnePastTheEnd=*/false, /*IsNull=*/false);
+}
+
+void FunctionPointer::print(llvm::raw_ostream &OS) const {
+  OS << "FnPtr(";
+  if (Func && Valid)
+OS << Func->getName();
+  else if (Func)
+OS << reinterpret_cast(Func);
+  else
+OS << "nullptr";
+  OS << ") + " << Offset;
+}
+
+} // namespace interp
+} // namespace clang

diff  --git a/clang/lib/AST/ByteCode/FunctionPointer.h 
b/clang/lib/AST/ByteCode/FunctionPointer.h
index c9bdfbee55441a..e2b45b2344fdce 100644
--- a/clang/lib/AST/ByteCode/FunctionPointer.h
+++ b/clang/lib/AST/

[clang] [clang][bytecode] Allow adding offsets to function pointers (PR #105641)

2024-08-22 Thread Timm Baeder via cfe-commits

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


[clang] [compiler-rt] [XRay] Add support for instrumentation of DSOs on x86_64 (PR #90959)

2024-08-22 Thread Sebastian Kreutzer via cfe-commits

https://github.com/sebastiankreutzer updated 
https://github.com/llvm/llvm-project/pull/90959

>From 5143ef41ac88d88e53ebbf7d404f5a86ccd0a5c1 Mon Sep 17 00:00:00 2001
From: Sebastian Kreutzer 
Date: Thu, 26 Oct 2023 15:13:05 +0200
Subject: [PATCH 1/8] [XRay] Add DSO support for XRay instrumentation on X86_64

---
 clang/include/clang/Driver/Options.td |   4 +
 clang/include/clang/Driver/XRayArgs.h |   4 +
 clang/lib/Driver/ToolChains/CommonArgs.cpp|  12 +-
 clang/lib/Driver/XRayArgs.cpp |   7 +
 .../cmake/Modules/AllSupportedArchDefs.cmake  |   1 +
 compiler-rt/cmake/config-ix.cmake |   4 +
 compiler-rt/include/xray/xray_interface.h |  23 ++
 compiler-rt/lib/xray/CMakeLists.txt   |  73 -
 compiler-rt/lib/xray/xray_dso_init.cpp|  62 +
 compiler-rt/lib/xray/xray_init.cpp| 158 +--
 compiler-rt/lib/xray/xray_interface.cpp   | 261 ++
 .../lib/xray/xray_interface_internal.h|  83 +-
 compiler-rt/lib/xray/xray_trampoline_x86_64.S |  24 +-
 compiler-rt/lib/xray/xray_x86_64.cpp  |  23 +-
 .../xray/TestCases/Posix/basic-mode-dso.cpp   |  47 
 .../TestCases/Posix/clang-enable-shared.cpp   |  14 +
 .../test/xray/TestCases/Posix/dlopen.cpp  | 110 
 .../TestCases/Posix/patch-premain-dso.cpp |  45 +++
 .../Posix/patching-unpatching-dso.cpp |  75 +
 19 files changed, 912 insertions(+), 118 deletions(-)
 create mode 100644 compiler-rt/lib/xray/xray_dso_init.cpp
 create mode 100644 compiler-rt/test/xray/TestCases/Posix/basic-mode-dso.cpp
 create mode 100644 
compiler-rt/test/xray/TestCases/Posix/clang-enable-shared.cpp
 create mode 100644 compiler-rt/test/xray/TestCases/Posix/dlopen.cpp
 create mode 100644 compiler-rt/test/xray/TestCases/Posix/patch-premain-dso.cpp
 create mode 100644 
compiler-rt/test/xray/TestCases/Posix/patching-unpatching-dso.cpp

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index fae865571001ce..01b6e16262e9c9 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -2887,6 +2887,10 @@ def fxray_selected_function_group :
   HelpText<"When using -fxray-function-groups, select which group of functions 
to instrument. Valid range is 0 to fxray-function-groups - 1">,
   MarshallingInfoInt, "0">;
 
+def fxray_enable_shared : Flag<["-"], "fxray-enable-shared">, Group,  
Visibility<[ClangOption, CC1Option]>,
+  HelpText<"Enable shared library instrumentation.">;
+def fno_xray_enable_shared : Flag<["-"], "fno-xray-enable-shared">, 
Group,
+  Visibility<[ClangOption, CC1Option]>;
 
 defm fine_grained_bitfield_accesses : BoolOption<"f", 
"fine-grained-bitfield-accesses",
   CodeGenOpts<"FineGrainedBitfieldAccesses">, DefaultFalse,
diff --git a/clang/include/clang/Driver/XRayArgs.h 
b/clang/include/clang/Driver/XRayArgs.h
index bdd3d979547eed..90a21e69586033 100644
--- a/clang/include/clang/Driver/XRayArgs.h
+++ b/clang/include/clang/Driver/XRayArgs.h
@@ -27,6 +27,7 @@ class XRayArgs {
   XRayInstrSet InstrumentationBundle;
   llvm::opt::Arg *XRayInstrument = nullptr;
   bool XRayRT = true;
+  bool XRayEnableShared = false;
 
 public:
   /// Parses the XRay arguments from an argument list.
@@ -35,6 +36,9 @@ class XRayArgs {
llvm::opt::ArgStringList &CmdArgs, types::ID InputType) const;
 
   bool needsXRayRt() const { return XRayInstrument && XRayRT; }
+  bool needsXRayDSORt() const {
+return XRayInstrument && XRayRT && XRayEnableShared;
+  }
   llvm::ArrayRef modeList() const { return Modes; }
   XRayInstrSet instrumentationBundle() const { return InstrumentationBundle; }
 };
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index ab1590104b7903..b67e09145db2af 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1593,10 +1593,14 @@ bool tools::addSanitizerRuntimes(const ToolChain &TC, 
const ArgList &Args,
 }
 
 bool tools::addXRayRuntime(const ToolChain&TC, const ArgList &Args, 
ArgStringList &CmdArgs) {
-  if (Args.hasArg(options::OPT_shared))
-return false;
-
-  if (TC.getXRayArgs().needsXRayRt()) {
+  if (Args.hasArg(options::OPT_shared)) {
+if (TC.getXRayArgs().needsXRayDSORt()) {
+  CmdArgs.push_back("-whole-archive");
+  CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray-dso"));
+  CmdArgs.push_back("-no-whole-archive");
+  return true;
+}
+  } else if (TC.getXRayArgs().needsXRayRt()) {
 CmdArgs.push_back("--whole-archive");
 CmdArgs.push_back(TC.getCompilerRTArgString(Args, "xray"));
 for (const auto &Mode : TC.getXRayArgs().modeList())
diff --git a/clang/lib/Driver/XRayArgs.cpp b/clang/lib/Driver/XRayArgs.cpp
index 8c5134e2501358..7809cd7ef7c759 100644
--- a/clang/lib/Driver/XRayArgs.cpp
+++ b/clang/lib/Driver/XRayArgs.cpp
@@ -63,6 +63,10 @@ XRayArgs::XRayArgs(const ToolChain &TC, c

[clang] [compiler-rt] [XRay] Add support for instrumentation of DSOs on x86_64 (PR #90959)

2024-08-22 Thread Sebastian Kreutzer via cfe-commits


@@ -2887,6 +2887,10 @@ def fxray_selected_function_group :
   HelpText<"When using -fxray-function-groups, select which group of functions 
to instrument. Valid range is 0 to fxray-function-groups - 1">,
   MarshallingInfoInt, "0">;
 
+def fxray_enable_shared : Flag<["-"], "fxray-enable-shared">, Group,  
Visibility<[ClangOption, CC1Option]>,

sebastiankreutzer wrote:

Thanks, I changed the option as requested

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


[clang] [Clang] Implement C++26’s P2893R3 ‘Variadic friends’ (PR #101448)

2024-08-22 Thread via cfe-commits

Sirraide wrote:

> I would recommend creating an issue and see how ewg handles the new 
> information before reaping out a lot of code.

Hmm, I mean, it looks like they’ve already thought about the consequences 
though, or am I missing something here, because the case that we currently 
support and which this ends up disallowing is explicitly listed as disallowed 
in the core issue:
> The proposed resolution above disallows a few examples from paper 
> [P2893R3](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2024/p2893r3.html)
>  (Variadic friends), such as
> ```c++
>  template
>  struct VS {
>template
>friend class C::Nested...; // now ill-formed
>  };
> ```

> https://lists.isocpp.org/core/2024/08/16236.php

Ah, that I don’t appear to have access to unfortunately.

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


[clang] [llvm] [Clang][AArch64] Add customisable immediate range checking to NEON (PR #100278)

2024-08-22 Thread via cfe-commits


@@ -2142,85 +2169,35 @@ void NeonEmitter::genOverloadTypeCheckCode(raw_ostream 
&OS,
   OS << "#endif\n\n";
 }
 
-void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
-SmallVectorImpl &Defs) {
-  OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
-
-  std::set Emitted;
+void NeonEmitter::genIntrinsicRangeCheckCode(
+raw_ostream &OS, SmallVectorImpl &Defs) {
+  std::map> Emitted;

Lukacma wrote:

I think using std::unordered_map would be better here. 

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


[clang] [llvm] [Clang][AArch64] Add customisable immediate range checking to NEON (PR #100278)

2024-08-22 Thread via cfe-commits


@@ -1957,15 +1945,13 @@ multiclass VCMLA_ROTS {
 def : SOpInst<"vcmla" # ROT # "_lane", "...qI", "Q" # type, Op<(call 
"vcmla" # ROT, $p0, $p1,
(bitcast $p0, (dup_typed laneqty , (call "vget_lane", (bitcast 
lanety, $p2), $p3>>;
 
-let isLaneQ = 1 in  {
-  // vcmla{ROT}_laneq
-  def : SOpInst<"vcmla" # ROT # "_laneq", "...QI", type,  Op<(call "vcmla" 
# ROT, $p0, $p1,
-  (bitcast $p0, (dup_typed lanety, (call "vget_lane", (bitcast 
laneqty, $p2), $p3>>;
+// vcmla_{ROT}_laneq
+def : SOpInst<"vcmla" # ROT # "_laneq", "...QI", type,  Op<(call "vcmla" # 
ROT, $p0, $p1,
+(bitcast $p0, (dup_typed lanety, (call "vget_lane", (bitcast 
laneqty, $p2), $p3>>;
+// vcmlaq{ROT}_laneq
+def : SOpInst<"vcmla" # ROT # "_laneq", "...QI", "Q" # type, Op<(call 
"vcmla" # ROT, $p0, $p1,
+(bitcast $p0, (dup_typed laneqty , (call "vget_lane", (bitcast 
laneqty, $p2), $p3>>;
 

Lukacma wrote:

nit: this line is redundant here

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


[clang] [clang][bytecode] Fix 'if consteval' in non-constant contexts (PR #104707)

2024-08-22 Thread via cfe-commits


@@ -4368,8 +4363,19 @@ template  bool 
Compiler::visitIfStmt(const IfStmt *IS) {
 if (!visitDeclStmt(CondDecl))
   return false;
 
-  if (!this->visitBool(IS->getCond()))
-return false;
+  // Compile condition.
+  if (IS->isNonNegatedConsteval()) {
+if (!this->emitIsConstantContext(IS))
+  return false;
+  } else if (IS->isNegatedConsteval()) {
+if (!this->emitIsConstantContext(IS))
+  return false;
+if (!this->emitInv(IS))
+  return false;
+  } else {
+if (!this->visitBool(IS->getCond()))
+  return false;
+  }

cor3ntin wrote:

Ok, it took me a while, but iI think i got it... sorry for the brain fart.
Because the interpreter compile functions before they are evaluated (at least 
morally), we don't know in which context they are going to be executed.

This is somewhat confusing because that means which assume we can constant 
evaluate something that is not a constant expression, which i guess is true for 
constant folding. 

In that light the patch makes sense, I think

I still wants to make sure that we can recover nicely in the presence of things 
we can't evaluate, which seems to be the case https://godbolt.org/z/bofa9b8de


Do you do the same thing for `is_constant_evaluated`?

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


  1   2   3   4   >