[clang] [clang] Do less advertising for unresolved issues in `cxx_dr_status.html` (PR #78836)

2024-02-12 Thread via cfe-commits


@@ -159,21 +165,37 @@ def availability(issue):
   if status == 'unknown':
 avail = 'Unknown'
 avail_style = ' class="unknown"'
-  elif re.match('^[0-9]+\.?[0-9]*', status):
-avail = 'Clang %s' % status
-if float(status) > latest_release:
-  avail_style = ' class="unreleased"'
-else:
-  avail_style = ' class="full"'
+  elif re.match(r'^[0-9]+\.?[0-9]*', status):
+if not proposed_resolution:
+  avail = 'Clang %s' % status
+  if float(status) > latest_release:
+avail_style = ' class="unreleased"'
+  else:
+avail_style = ' class="full"'
+else: 
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang {status} implements {proposed_resolution} 
resolution"'
   elif status == 'yes':
-avail = 'Yes'
-avail_style = ' class="full"'
+if not proposed_resolution:
+  avail = 'Yes'
+  avail_style = ' class="full"'
+else:
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang implements {proposed_resolution} 
resolution"'
   elif status == 'partial':
-avail = 'Partial'
-avail_style = ' class="partial"'
+if not proposed_resolution:
+  avail = 'Partial'
+  avail_style = ' class="partial"'
+else:
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang partially implements {proposed_resolution} 
resolution"'

cor3ntin wrote:

Does this case happen?

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


[clang] [clang] Do less advertising for unresolved issues in `cxx_dr_status.html` (PR #78836)

2024-02-12 Thread via cfe-commits


@@ -159,21 +165,37 @@ def availability(issue):
   if status == 'unknown':
 avail = 'Unknown'
 avail_style = ' class="unknown"'
-  elif re.match('^[0-9]+\.?[0-9]*', status):
-avail = 'Clang %s' % status
-if float(status) > latest_release:
-  avail_style = ' class="unreleased"'
-else:
-  avail_style = ' class="full"'
+  elif re.match(r'^[0-9]+\.?[0-9]*', status):
+if not proposed_resolution:
+  avail = 'Clang %s' % status
+  if float(status) > latest_release:
+avail_style = ' class="unreleased"'
+  else:
+avail_style = ' class="full"'
+else: 
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang {status} implements {proposed_resolution} 
resolution"'
   elif status == 'yes':
-avail = 'Yes'
-avail_style = ' class="full"'
+if not proposed_resolution:
+  avail = 'Yes'
+  avail_style = ' class="full"'
+else:
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang implements {proposed_resolution} 
resolution"'
   elif status == 'partial':
-avail = 'Partial'
-avail_style = ' class="partial"'
+if not proposed_resolution:
+  avail = 'Partial'
+  avail_style = ' class="partial"'
+else:
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang partially implements {proposed_resolution} 
resolution"'
   elif status == 'no':
-avail = 'No'
-avail_style = ' class="none"'
+if not proposed_resolution:
+  avail = 'No'
+  avail_style = ' class="none"'
+else:
+  avail = 'Not Resolved*'
+  avail_style = f' title="Clang does not implement {proposed_resolution} 
resolution"'

cor3ntin wrote:

In the no case, I would leave it unknown / no comment... that we don't do 
something is not useful information for users. WDYT?

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


[clang] [clang] Add some CodeGen tests for CWG 2xx issues (PR #80823)

2024-02-12 Thread via cfe-commits

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

LGTM

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


[clang] [clang] Better bitfield access units (PR #65742)

2024-02-12 Thread John McCall via cfe-commits

rjmccall wrote:

> @rjmccall thanks for your comments. Here's a reimplementation using a single 
> loop -- the downside is that we may end up repeating the initial grouping 
> scan, if we search more than 1 Access Unit ahead and fail to find a 'good' 
> access unit. This update changes the algorithm slightly, as I realized that 
> `struct A { short a: 16; char b:8; int c;};` and `struct B { char b: 8; short 
> a:16; int c;};` should have the same (32-bit) access unit. Originally only 
> `A` got that.

Thanks.  Sorry about the delay, I'll try to take a look in the next day.

> 1. I noticed that several `CGRecordLowering` member fns could either be 
> `const` or `static` -- would you like that as a separate NFC PR?

Yes, please.

> 2. I have corrected the error about merging across zero-sized members.
> 3. It may not be obvious from GH, but this PR breaks down to 3 (or 4) 
> separate commits:
>a) A set of test cases, marked up for the current scheme
>b) A new Target hook indicating whether unaligned accesses are cheap
>c) [optional] the CGRecordLowering change just mentioned
>d) the algorithm change, which updates those tests and makes it easier to 
> see how the behaviour changes.
>Do you want that commit structure maintained?

That sounds like good commit structure.

On the target hook, it's a shame we can't easily get this information from 
LLVM.  I believe it's already there — `TargetLowering` has an 
`allowsMisalignedMemoryAccesses` method that includes some approximation of how 
fast a particular access would be.  In practice, it seems to be quite complex 
and often specific to the type and subtarget.  Maybe it'd be worth starting a 
conversation with LLVM folks to see if this could reasonably be lifted 
somewhere we could use it?

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-12 Thread Timm Baeder via cfe-commits

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

>From 9234c4224e02e5170d81aeb5fb2bfa9fe7a26eb1 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Thu, 25 Jan 2024 15:20:52 +0100
Subject: [PATCH] [clang][Interp] Handle complex values in visitBool()

In C++, we get a ComplexToBool cast, but we might not in C.
---
 clang/lib/AST/Interp/ByteCodeExprGen.cpp | 115 +--
 clang/lib/AST/Interp/ByteCodeExprGen.h   |   1 +
 clang/test/AST/Interp/c.c|   4 +
 clang/test/AST/Interp/complex.cpp|   2 +
 4 files changed, 72 insertions(+), 50 deletions(-)

diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index ba6c1d5f5c9470..eaa6d47f601bcc 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -241,57 +241,11 @@ bool ByteCodeExprGen::VisitCastExpr(const 
CastExpr *CE) {
 
   case CK_IntegralComplexToBoolean:
   case CK_FloatingComplexToBoolean: {
-PrimType ElemT = classifyComplexElementType(SubExpr->getType());
-// We emit the expression (__real(E) != 0 || __imag(E) != 0)
-// for us, that means (bool)E[0] || (bool)E[1]
+if (DiscardResult)
+  return this->discard(SubExpr);
 if (!this->visit(SubExpr))
   return false;
-if (!this->emitConstUint8(0, CE))
-  return false;
-if (!this->emitArrayElemPtrUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-
-// We now have the bool value of E[0] on the stack.
-LabelTy LabelTrue = this->getLabel();
-if (!this->jumpTrue(LabelTrue))
-  return false;
-
-if (!this->emitConstUint8(1, CE))
-  return false;
-if (!this->emitArrayElemPtrPopUint8(CE))
-  return false;
-if (!this->emitLoadPop(ElemT, CE))
-  return false;
-if (ElemT == PT_Float) {
-  if (!this->emitCastFloatingIntegral(PT_Bool, CE))
-return false;
-} else {
-  if (!this->emitCast(ElemT, PT_Bool, CE))
-return false;
-}
-// Leave the boolean value of E[1] on the stack.
-LabelTy EndLabel = this->getLabel();
-this->jump(EndLabel);
-
-this->emitLabel(LabelTrue);
-if (!this->emitPopPtr(CE))
-  return false;
-if (!this->emitConstBool(true, CE))
-  return false;
-
-this->fallthrough(EndLabel);
-this->emitLabel(EndLabel);
-
-return true;
+return this->emitComplexBoolCast(SubExpr);
   }
 
   case CK_IntegralComplexToReal:
@@ -2120,8 +2074,15 @@ bool ByteCodeExprGen::visitInitializer(const 
Expr *E) {
 template 
 bool ByteCodeExprGen::visitBool(const Expr *E) {
   std::optional T = classify(E->getType());
-  if (!T)
+  if (!T) {
+// Convert complex values to bool.
+if (E->getType()->isAnyComplexType()) {
+  if (!this->visit(E))
+return false;
+  return this->emitComplexBoolCast(E);
+}
 return false;
+  }
 
   if (!this->visit(E))
 return false;
@@ -3249,6 +3210,60 @@ bool ByteCodeExprGen::emitComplexReal(const 
Expr *SubExpr) {
   return true;
 }
 
+template 
+bool ByteCodeExprGen::emitComplexBoolCast(const Expr *E) {
+  assert(!DiscardResult);
+  PrimType ElemT = classifyComplexElementType(E->getType());
+  // We emit the expression (__real(E) != 0 || __imag(E) != 0)
+  // for us, that means (bool)E[0] || (bool)E[1]
+  if (!this->emitConstUint8(0, E))
+return false;
+  if (!this->emitArrayElemPtrUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+
+  // We now have the bool value of E[0] on the stack.
+  LabelTy LabelTrue = this->getLabel();
+  if (!this->jumpTrue(LabelTrue))
+return false;
+
+  if (!this->emitConstUint8(1, E))
+return false;
+  if (!this->emitArrayElemPtrPopUint8(E))
+return false;
+  if (!this->emitLoadPop(ElemT, E))
+return false;
+  if (ElemT == PT_Float) {
+if (!this->emitCastFloatingIntegral(PT_Bool, E))
+  return false;
+  } else {
+if (!this->emitCast(ElemT, PT_Bool, E))
+  return false;
+  }
+  // Leave the boolean value of E[1] on the stack.
+  LabelTy EndLabel = this->getLabel();
+  this->jump(EndLabel);
+
+  this->emitLabel(LabelTrue);
+  if (!this->emitPopPtr(E))
+return false;
+  if (!this->emitConstBool(true, E))
+return false;
+
+  this->fallthrough(EndLabel);
+  this->emitLabel(EndLabel);
+
+  return true;
+}
+
 /// When calling this, we have a pointer of the local-to-destroy
 /// on the stack.
 /// Emit destruction of record types (or arrays of record types).
diff --git a/clang/lib/AST/Interp/ByteCodeExprGen.h 

[clang] 66f7310 - [clang][Interp] Fix ltor conversion for pointer types

2024-02-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-13T08:44:15+01:00
New Revision: 66f73100b8c758248724d53598165d850fdaf364

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

LOG: [clang][Interp] Fix ltor conversion for pointer types

This special case is wrong, we need to handle pointer types here
just like anything else.

Added: 


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

Removed: 




diff  --git a/clang/lib/AST/Interp/Pointer.cpp 
b/clang/lib/AST/Interp/Pointer.cpp
index 8a0a15547b0f2f..3f85635f43674d 100644
--- a/clang/lib/AST/Interp/Pointer.cpp
+++ b/clang/lib/AST/Interp/Pointer.cpp
@@ -232,11 +232,7 @@ std::optional Pointer::toRValue(const Context 
) const {
 
 // Primitive values.
 if (std::optional T = Ctx.classify(Ty)) {
-  if (T == PT_Ptr || T == PT_FnPtr) {
-R = Ptr.toAPValue();
-  } else {
-TYPE_SWITCH(*T, R = Ptr.deref().toAPValue());
-  }
+  TYPE_SWITCH(*T, R = Ptr.deref().toAPValue());
   return true;
 }
 

diff  --git a/clang/test/AST/Interp/literals.cpp 
b/clang/test/AST/Interp/literals.cpp
index f5b5f77ffc624b..9202bb98c822fc 100644
--- a/clang/test/AST/Interp/literals.cpp
+++ b/clang/test/AST/Interp/literals.cpp
@@ -1105,3 +1105,13 @@ namespace NonConstReads {
   static_assert(z == 0, ""); // both-error {{not an integral constant 
expression}} \
  // both-note {{read of non-const variable 'z'}}
 }
+
+/// This test passes a MaterializedTemporaryExpr to evaluateAsRValue.
+/// That needs to return a null pointer after the lvalue-to-rvalue conversion.
+/// We used to fail to do that.
+namespace rdar8769025 {
+  __attribute__((nonnull)) void f1(int * const );
+  void test_f1() {
+f1(0); // both-warning{{null passed to a callee that requires a non-null 
argument}}
+  }
+}



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


[clang] [clang] Use "notable" for "interesting" identifiers in `IdentifierInfo` (PR #81542)

2024-02-12 Thread Vlad Serebrennikov via cfe-commits

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


[clang] [clang] Add some CodeGen tests for CWG 2xx issues (PR #80823)

2024-02-12 Thread Vlad Serebrennikov via cfe-commits

https://github.com/Endilll updated 
https://github.com/llvm/llvm-project/pull/80823

>From 560713b5d45236956198654a10e0795eb56cad7b Mon Sep 17 00:00:00 2001
From: Vlad Serebrennikov 
Date: Tue, 6 Feb 2024 13:23:36 +0300
Subject: [PATCH 1/4] [Clang] Add some CodeGen tests for CWG 2xx issues

This patch covers CWG issues
[201](https://cplusplus.github.io/CWG/issues/201.html),
[210](https://cplusplus.github.io/CWG/issues/210.html),
[292](https://cplusplus.github.io/CWG/issues/292.html).

[CWG208](https://cplusplus.github.io/CWG/issues/208.html) is not covered, as it 
actually requires a libcxxabi test.
---
 clang/test/CXX/drs/dr201.cpp | 43 
 clang/test/CXX/drs/dr210.cpp | 41 ++
 clang/test/CXX/drs/dr292.cpp | 38 +++
 clang/test/CXX/drs/dr2xx.cpp |  6 ++---
 clang/www/cxx_dr_status.html |  8 +++
 5 files changed, 129 insertions(+), 7 deletions(-)
 create mode 100644 clang/test/CXX/drs/dr201.cpp
 create mode 100644 clang/test/CXX/drs/dr210.cpp
 create mode 100644 clang/test/CXX/drs/dr292.cpp

diff --git a/clang/test/CXX/drs/dr201.cpp b/clang/test/CXX/drs/dr201.cpp
new file mode 100644
index 00..48495d337e00ff
--- /dev/null
+++ b/clang/test/CXX/drs/dr201.cpp
@@ -0,0 +1,43 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++11 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++14 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++17 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++20 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++23 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+// RUN: %clang_cc1 -std=c++2c %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O3 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck %s --check-prefixes CHECK
+
+#if __cplusplus == 199711L
+#define NOTHROW throw()
+#else
+#define NOTHROW noexcept(true)
+#endif
+
+namespace dr201 { // dr201: 2.8
+
+struct A {
+  ~A() NOTHROW {}
+};
+
+struct B {
+  B(A) NOTHROW {}
+  ~B() NOTHROW {}
+};
+
+void foo() {
+  B b = A();
+}
+
+// CHECK-LABEL: define {{.*}} void @dr201::foo()
+// CHECK: call void @dr201::A::~A()
+// CHECK: call void @dr201::B::~B()
+// CHECK-LABEL: }
+
+} // namespace dr201
diff --git a/clang/test/CXX/drs/dr210.cpp b/clang/test/CXX/drs/dr210.cpp
new file mode 100644
index 00..c19771229596f1
--- /dev/null
+++ b/clang/test/CXX/drs/dr210.cpp
@@ -0,0 +1,41 @@
+// RUN: %clang_cc1 -std=c++98 %s -triple x86_64-linux-gnu -emit-llvm 
-disable-llvm-passes -O0 -o - -fexceptions -fcxx-exceptions -pedantic-errors | 
llvm-cxxfilt -n | FileCheck 

[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-12 Thread Owen Pan via cfe-commits

owenca wrote:

Feel free to open another PR if you're interested.  

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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-12 Thread via cfe-commits

rmarker wrote:

Thanks for updating `ConfigParseTest.cpp` @owenca and merging.

Do you also want to do the subsequent NFC commit directly? Like 
[7664ddf](https://github.com/llvm/llvm-project/commit/7664ddf8811242295abb837640cad8dd8cefb5e8).
Or do you want me to make another pull request for that?

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


[clang] [clang] Remove #undef alloca workaround (PR #81534)

2024-02-12 Thread Vlad Serebrennikov via cfe-commits

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

Thank you for your time to fix that `-fPIE` failure caused by my PR!

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Add a few more safe functions to call. (PR #81532)

2024-02-12 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81532

>From 52b6e959d69a96704ec2a403131627049a782352 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 12 Feb 2024 12:31:37 -0800
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Add a few more safe
 functions to call.

Added checkedDowncast, uncheckedDowncast, & toString as safe functions to call.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp |  5 +++--
 .../WebKit/UncountedCallArgsChecker.cpp   | 11 +-
 ...ncast.cpp => call-args-safe-functions.cpp} | 21 +++
 3 files changed, 30 insertions(+), 7 deletions(-)
 rename clang/test/Analysis/Checkers/WebKit/{call-args-dynamic-downcast.cpp => 
call-args-safe-functions.cpp} (55%)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index d2b66341058000..c4a78da25438be 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -192,8 +192,9 @@ bool isPtrConversion(const FunctionDecl *F) {
   // FIXME: check # of params == 1
   const auto FunctionName = safeGetName(F);
   if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
-  FunctionName == "dynamicDowncast"
-  || FunctionName == "downcast" || FunctionName == "bitwise_cast")
+  FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
+  FunctionName == "checkedDowncast" ||
+  FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast")
 return true;
 
   return false;
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 31ccae8b097b89..cc4585a0b0eeff 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -148,13 +148,14 @@ class UncountedCallArgsChecker
 
 auto name = safeGetName(Callee);
 if (name == "adoptRef" || name == "getPtr" || name == "WeakPtr" ||
-name == "dynamicDowncast" || name == "downcast" || name == 
"bitwise_cast" ||
-name == "is" || name == "equal" || name == "hash" ||
-name == "isType"
+name == "dynamicDowncast" || name == "downcast" ||
+name == "checkedDowncast" || name == "uncheckedDowncast" ||
+name == "bitwise_cast" || name == "is" || name == "equal" ||
+name == "hash" || name == "isType" ||
 // FIXME: Most/all of these should be implemented via attributes.
-|| name == "equalIgnoringASCIICase" ||
+name == "equalIgnoringASCIICase" ||
 name == "equalIgnoringASCIICaseCommon" ||
-name == "equalIgnoringNullity")
+name == "equalIgnoringNullity" || name == "toString")
   return true;
 
 return false;
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
similarity index 55%
rename from clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp
rename to clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
index 28156623d9a0fd..a87446564870cd 100644
--- a/clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
@@ -23,13 +23,34 @@ class OtherObject {
 Derived* obj();
 };
 
+class String {
+};
+
 template
 inline Target* dynamicDowncast(Source* source)
 {
 return static_cast(source);
 }
 
+template
+inline Target* checkedDowncast(Source* source)
+{
+return static_cast(source);
+}
+
+template
+inline Target* uncheckedDowncast(Source* source)
+{
+return static_cast(source);
+}
+
+template
+String toString(const Types&... values);
+
 void foo(OtherObject* other)
 {
 dynamicDowncast(other->obj());
+checkedDowncast(other->obj());
+uncheckedDowncast(other->obj());
+toString(other->obj());
 }

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


[clang] [alpha.webkit.UncountedCallArgsChecker] Add a few more safe functions to call. (PR #81532)

2024-02-12 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa updated https://github.com/llvm/llvm-project/pull/81532

>From 9a25673cf0c585b1d13e54b1b836edaae1a1ca2c Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Mon, 12 Feb 2024 12:31:37 -0800
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] Add a few more safe
 functions to call.

Added checkedDowncast, uncheckedDowncast, & toString as safe functions to call.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp |  5 +++--
 .../WebKit/UncountedCallArgsChecker.cpp   | 11 +-
 ...ncast.cpp => call-args-safe-functions.cpp} | 21 +++
 3 files changed, 30 insertions(+), 7 deletions(-)
 rename clang/test/Analysis/Checkers/WebKit/{call-args-dynamic-downcast.cpp => 
call-args-safe-functions.cpp} (55%)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index d2b66341058000..d9f4e1a598e788 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -192,8 +192,9 @@ bool isPtrConversion(const FunctionDecl *F) {
   // FIXME: check # of params == 1
   const auto FunctionName = safeGetName(F);
   if (FunctionName == "getPtr" || FunctionName == "WeakPtr" ||
-  FunctionName == "dynamicDowncast"
-  || FunctionName == "downcast" || FunctionName == "bitwise_cast")
+  FunctionName == "dynamicDowncast" || FunctionName == "downcast" ||
+  FunctionName == "checkedDowncast" ||
+  FunctionName == "uncheckedDowncast" || FunctionName == "bitwise_cast"
 return true;
 
   return false;
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
index 31ccae8b097b89..cc4585a0b0eeff 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/UncountedCallArgsChecker.cpp
@@ -148,13 +148,14 @@ class UncountedCallArgsChecker
 
 auto name = safeGetName(Callee);
 if (name == "adoptRef" || name == "getPtr" || name == "WeakPtr" ||
-name == "dynamicDowncast" || name == "downcast" || name == 
"bitwise_cast" ||
-name == "is" || name == "equal" || name == "hash" ||
-name == "isType"
+name == "dynamicDowncast" || name == "downcast" ||
+name == "checkedDowncast" || name == "uncheckedDowncast" ||
+name == "bitwise_cast" || name == "is" || name == "equal" ||
+name == "hash" || name == "isType" ||
 // FIXME: Most/all of these should be implemented via attributes.
-|| name == "equalIgnoringASCIICase" ||
+name == "equalIgnoringASCIICase" ||
 name == "equalIgnoringASCIICaseCommon" ||
-name == "equalIgnoringNullity")
+name == "equalIgnoringNullity" || name == "toString")
   return true;
 
 return false;
diff --git a/clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp 
b/clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
similarity index 55%
rename from clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp
rename to clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
index 28156623d9a0fd..a87446564870cd 100644
--- a/clang/test/Analysis/Checkers/WebKit/call-args-dynamic-downcast.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/call-args-safe-functions.cpp
@@ -23,13 +23,34 @@ class OtherObject {
 Derived* obj();
 };
 
+class String {
+};
+
 template
 inline Target* dynamicDowncast(Source* source)
 {
 return static_cast(source);
 }
 
+template
+inline Target* checkedDowncast(Source* source)
+{
+return static_cast(source);
+}
+
+template
+inline Target* uncheckedDowncast(Source* source)
+{
+return static_cast(source);
+}
+
+template
+String toString(const Types&... values);
+
 void foo(OtherObject* other)
 {
 dynamicDowncast(other->obj());
+checkedDowncast(other->obj());
+uncheckedDowncast(other->obj());
+toString(other->obj());
 }

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


[clang] [RISCV] Add canonical ISA string as Module metadata in IR. (PR #80760)

2024-02-12 Thread Fangrui Song via cfe-commits

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


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


[clang] [RISCV] Add canonical ISA string as Module metadata in IR. (PR #80760)

2024-02-12 Thread Fangrui Song via cfe-commits

MaskRay wrote:

I share a similar concern about not addressing the issue in a target-specific 
manner. However, I know a lot of confused users by the behavior, and this patch 
will significantly improve the status quo. I concur with asb's analysis.

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


[clang-tools-extra] [clangd] Clean formatting modernize-use-override (PR #81435)

2024-02-12 Thread Kevin Joseph via cfe-commits

kevinjoseph1995 wrote:

> Small fix in release notes needed. If with this change tests are passing, 
> then it's looking fine for me.

ninja check-clang-tools reports the following:
```
Total Discovered Tests: 2813
Unsupported  :7 (0.25%)
Passed   : 2804 (99.68%)
Expectedly Failed:2 (0.07%)
```
And all of the ClangdTests pass as well:
```
[==] 1232 tests from 179 test suites ran. (86642 ms total)
[  PASSED  ] 1232 tests.
```

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


[clang-tools-extra] [clangd] Clean formatting modernize-use-override (PR #81435)

2024-02-12 Thread Kevin Joseph via cfe-commits


@@ -160,6 +160,10 @@ Changes in existing checks
   `AllowStringArrays` option, enabling the exclusion of array types with 
deduced
   length initialized from string literals.
 
+- Improved :doc:`

kevinjoseph1995 wrote:

Thanks, added the missing check name.

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


[clang-tools-extra] [clangd] Clean formatting modernize-use-override (PR #81435)

2024-02-12 Thread Kevin Joseph via cfe-commits

https://github.com/kevinjoseph1995 updated 
https://github.com/llvm/llvm-project/pull/81435

>From db2c4ee74ffb0592ec7f3fd5557dbb5399ef998d Mon Sep 17 00:00:00 2001
From: Kevin Joseph 
Date: Sun, 11 Feb 2024 13:39:51 -0800
Subject: [PATCH 1/3] [clangd] Clean formatting modernize-use-override

When applying the recommended fix for the
"modernize-use-override" clang-tidy diagnostic
there was a stray whitespace.

This commit fixes: https://github.com/clangd/clangd/issues/1704
---
 .../clang-tidy/modernize/UseOverrideCheck.cpp |  4 +--
 .../clangd/unittests/DiagnosticsTests.cpp | 28 +++
 2 files changed, 30 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
index e348968b325a5a..4db32b02ee5a0c 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
@@ -228,8 +228,8 @@ void UseOverrideCheck::check(const MatchFinder::MatchResult 
) {
   if (HasVirtual) {
 for (Token Tok : Tokens) {
   if (Tok.is(tok::kw_virtual)) {
-Diag << FixItHint::CreateRemoval(CharSourceRange::getTokenRange(
-Tok.getLocation(), Tok.getLocation()));
+Diag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
+Tok.getLocation(), Tok.getEndLoc().getLocWithOffset(1)));
 break;
   }
 }
diff --git a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp 
b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
index f302dcf5f09db0..76874ac9a2a4e7 100644
--- a/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ b/clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -898,6 +898,34 @@ TEST(DiagnosticTest, ClangTidySelfContainedDiags) {
 withFix(equalToFix(ExpectedDFix));
 }
 
+TEST(DiagnosticTest, ClangTidySelfContainedDiagsFormatting) {
+  Annotations Main(R"cpp(
+class Interface {
+public:
+  virtual void Reset() = 0;
+};
+class A : public Interface {
+  // This will be marked by clangd to use override instead of virtual
+  $virtual[[virtual ]] void $Reset[[Reset]]()$override[[]];
+};
+  )cpp");
+  TestTU TU = TestTU::withCode(Main.code());
+  TU.ClangTidyProvider =
+  addTidyChecks("cppcoreguidelines-explicit-virtual-functions,");
+  clangd::Fix const ExpectedFix{"prefer using 'override' or (rarely) 'final' "
+"instead of 'virtual'",
+{TextEdit{Main.range("override"), " override"},
+ TextEdit{Main.range("virtual"), ""}}};
+  // Note that in the Fix we expect the "virtual" keyword and the following
+  // whitespace to be deleted
+  EXPECT_THAT(TU.build().getDiagnostics(),
+  ifTidyChecks(UnorderedElementsAre(
+  AllOf(Diag(Main.range("Reset"),
+ "prefer using 'override' or (rarely) 'final' "
+ "instead of 'virtual'"),
+withFix(equalToFix(ExpectedFix));
+}
+
 TEST(DiagnosticsTest, Preprocessor) {
   // This looks like a preamble, but there's an #else in the middle!
   // Check that:

>From 7b868a4ede5f49f2c4471b85ac389b36aaf1c6e1 Mon Sep 17 00:00:00 2001
From: Kevin Joseph 
Date: Sun, 11 Feb 2024 19:35:29 -0800
Subject: [PATCH 2/3] fixup! [clangd] Clean formatting modernize-use-override

---
 .../clang-tidy/modernize/UseOverrideCheck.cpp | 12 ++--
 .../clangd/unittests/DiagnosticsTests.cpp | 28 +--
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 +++
 .../checkers/modernize/use-override.cpp   |  5 
 4 files changed, 38 insertions(+), 11 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
index 4db32b02ee5a0c..fd5bd9f0b181b1 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseOverrideCheck.cpp
@@ -7,6 +7,7 @@
 
//===--===//
 
 #include "UseOverrideCheck.h"
+#include "../utils/LexerUtils.h"
 #include "clang/AST/ASTContext.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/Lex/Lexer.h"
@@ -228,9 +229,14 @@ void UseOverrideCheck::check(const 
MatchFinder::MatchResult ) {
   if (HasVirtual) {
 for (Token Tok : Tokens) {
   if (Tok.is(tok::kw_virtual)) {
-Diag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
-Tok.getLocation(), Tok.getEndLoc().getLocWithOffset(1)));
-break;
+std::optional NextToken =
+utils::lexer::findNextTokenIncludingComments(
+Tok.getEndLoc(), Sources, getLangOpts());
+if (NextToken.has_value()) {
+  Diag << FixItHint::CreateRemoval(CharSourceRange::getCharRange(
+  Tok.getLocation(), 

[clang] 85e6e71 - [clang][Interp] Handle discarded PointerToIntegral casts

2024-02-12 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2024-02-13T06:57:30+01:00
New Revision: 85e6e71eb09cb9e75bbd475e5f54f876653c3f16

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

LOG: [clang][Interp] Handle discarded PointerToIntegral casts

Resolve an old TODO comment.

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp
clang/test/AST/Interp/c.c

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index 8a2c1e54e10a50..ba6c1d5f5c9470 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -167,7 +167,9 @@ bool ByteCodeExprGen::VisitCastExpr(const CastExpr 
*CE) {
 return this->emitNull(classifyPrim(CE->getType()), CE);
 
   case CK_PointerToIntegral: {
-// TODO: Discard handling.
+if (DiscardResult)
+  return this->discard(SubExpr);
+
 if (!this->visit(SubExpr))
   return false;
 

diff  --git a/clang/test/AST/Interp/c.c b/clang/test/AST/Interp/c.c
index 392b682afd602b..85c195d33a96d7 100644
--- a/clang/test/AST/Interp/c.c
+++ b/clang/test/AST/Interp/c.c
@@ -24,6 +24,7 @@ _Static_assert(!!1, "");
 int a = (1 == 1 ? 5 : 3);
 _Static_assert(a == 5, ""); // all-error {{not an integral constant 
expression}}
 
+const int DiscardedPtrToIntCast = ((intptr_t)((void*)0), 0); // all-warning 
{{left operand of comma operator has no effect}}
 
 const int b = 3;
 _Static_assert(b == 3, ""); // pedantic-ref-warning {{not an integer constant 
expression}} \



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


[clang] [HLSL] Vector standard conversions (PR #71098)

2024-02-12 Thread John McCall via cfe-commits


@@ -361,6 +361,9 @@ CAST_OPERATION(AddressSpaceConversion)
 // Convert an integer initializer to an OpenCL sampler.
 CAST_OPERATION(IntToOCLSampler)
 
+// Truncate a vector type (HLSL only).
+CAST_OPERATION(HLSLVectorTruncation)

rjmccall wrote:

Okay.  I think this patch overall looks fine to land, except please do expand 
on the comment here to explain what truncating a vector type means (dropping 
elements from the end).

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


[clang] b56b3d7 - [Clang][Sema] Don't consider top-level cv-qualifiers in template partial orderings (#81449)

2024-02-12 Thread via cfe-commits

Author: Younan Zhang
Date: 2024-02-13T13:34:27+08:00
New Revision: b56b3d75b04cda762ac8e15b7ec6fa4f52a6735a

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

LOG: [Clang][Sema] Don't consider top-level cv-qualifiers in template partial 
orderings (#81449)

This fixes a regression since
https://github.com/llvm/llvm-project/commit/340eac01f7dad6c24cee35dd35f2484098dd6b1a,
from which we compared function parameter types with cv-qualifiers taken
into account. However, as per [dcl.fct]/p5:

> After producing the list of parameter types, any top-level
cv-qualifiers modifying
> a parameter type are deleted when forming the function type.

Thus, I think we should use `hasSameUnqualifiedType` for type
comparison.

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaTemplateDeduction.cpp
clang/test/CXX/over/over.match/over.match.best/p1-2a.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index aa167d75c3bfd1..dd790236e03bb7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -228,6 +228,8 @@ Bug Fixes to C++ Support
   or non-constant more accurately. Previously, only a subset of the initializer
   elements were considered, misclassifying some initializers as constant. Fixes
   some of (`#80510 `).
+- Clang now ignores top-level cv-qualifiers on function parameters in template 
partial orderings.
+  (`#75404 `_)
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaTemplateDeduction.cpp 
b/clang/lib/Sema/SemaTemplateDeduction.cpp
index 994c997b9f6acd..47cc22310c4eec 100644
--- a/clang/lib/Sema/SemaTemplateDeduction.cpp
+++ b/clang/lib/Sema/SemaTemplateDeduction.cpp
@@ -5642,9 +5642,12 @@ FunctionTemplateDecl *Sema::getMoreSpecializedTemplate(
   Sema::TPL_TemplateParamsEquivalent))
 return nullptr;
 
+  // [dcl.fct]p5:
+  // Any top-level cv-qualifiers modifying a parameter type are deleted when
+  // forming the function type.
   for (unsigned i = 0; i < NumParams1; ++i)
-if (!Context.hasSameType(FD1->getParamDecl(i)->getType(),
- FD2->getParamDecl(i)->getType()))
+if (!Context.hasSameUnqualifiedType(FD1->getParamDecl(i)->getType(),
+FD2->getParamDecl(i)->getType()))
   return nullptr;
 
   // C++20 [temp.func.order]p6.3:

diff  --git a/clang/test/CXX/over/over.match/over.match.best/p1-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.best/p1-2a.cpp
index dae1ba760cc203..db3e3e3bc85966 100644
--- a/clang/test/CXX/over/over.match/over.match.best/p1-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.best/p1-2a.cpp
@@ -97,13 +97,16 @@ namespace non_template
   static_assert(is_same_v()), int>); // expected-error 
{{call to 'baz' is ambiguous}}
   static_assert(is_same_v()), void>); // expected-error 
{{call to 'bar' is ambiguous}}
 
+  // Top-level cv-qualifiers are ignored in template partial ordering per 
[dcl.fct]/p5.
+  //   After producing the list of parameter types, any top-level 
cv-qualifiers modifying
+  //   a parameter type are deleted when forming the function type.
   template
-  constexpr int goo(int a) requires AtLeast2 && true { // expected-note 
{{candidate function}}
+  constexpr int goo(T a) requires AtLeast2 && true {
 return 1;
   }
 
   template
-  constexpr int goo(const int b) requires AtLeast2 { // expected-note 
{{candidate function}}
+  constexpr int goo(const T b) requires AtLeast2 {
 return 2;
   }
 
@@ -122,7 +125,6 @@ namespace non_template
 return 2;
   }
 
-  // By temp.func.order-6.2.2, this is ambiguous because parameter a and b 
have 
diff erent types.
-  static_assert(goo(1) == 1); // expected-error {{call to 'goo' is 
ambiguous}}
+  static_assert(goo(1) == 1);
   static_assert(doo(2) == 1);
 }



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


[clang] [Clang][Sema] Don't consider top-level cv-qualifiers in template partial orderings (PR #81449)

2024-02-12 Thread Younan Zhang via cfe-commits

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


[clang] [clang][Interp] Handle complex values in visitBool() (PR #79452)

2024-02-12 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Ping

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


[clang] Avoid printing overly large integer. (PR #75902)

2024-02-12 Thread Nhat Nguyen via cfe-commits
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,
=?utf-8?q?“Nhat?= ,Nhat Nguyen
 
Message-ID:
In-Reply-To: 


changkhothuychung wrote:

> Looks like all the tests disappeared? Only thing I see is the code change. 
> Also, no release note is currently present.

Hi I am still slowly working on it. I am not familiar with the release note. 
Can you provide me some pointers so I can follow accordingly? Thanks a lot. 

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


[clang] [clang][InstallAPI] Introduce basic driver to write out tbd files (PR #81571)

2024-02-12 Thread Cyndy Ishida via cfe-commits

cyndyishida wrote:

In case anyone is interested, 
Here are relevant links for upstreaming `tapi` in LLVM: 
* [Inital 
RFC](https://discourse.llvm.org/t/rfc-open-sourcing-and-contributing-tapi-back-to-the-llvm-community/46214/24)
* [Continued 
RFC](https://discourse.llvm.org/t/rfc-continuation-of-tapi-into-llvm/52825)
* [Dev Talk](https://www.youtube.com/watch?v=B9li6EkD5zA)
* [Full TAPI sources](https://github.com/apple-oss-distributions/tapi), 
includes docs

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


[clang] [clang][InstallAPI] Introduce basic driver to write out tbd files (PR #81571)

2024-02-12 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 4af24d4ab76539706bfbceec4b3923426fb1b9e7 
0f938ae8480f74a44bf6fe4aac6105e457315bb9 -- 
clang/include/clang/Frontend/InstallAPIOptions.h 
clang/include/clang/InstallAPI/Context.h 
clang/lib/Frontend/InstallAPIConsumer.cpp clang/lib/InstallAPI/Context.cpp 
clang/test/Driver/installapi.h clang/include/clang/Driver/Action.h 
clang/include/clang/Frontend/CompilerInstance.h 
clang/include/clang/Frontend/CompilerInvocation.h 
clang/include/clang/Frontend/FrontendActions.h 
clang/include/clang/Frontend/FrontendOptions.h clang/lib/Driver/Action.cpp 
clang/lib/Driver/Driver.cpp clang/lib/Driver/ToolChain.cpp 
clang/lib/Driver/ToolChains/Clang.cpp clang/lib/Frontend/CompilerInvocation.cpp 
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/include/clang/Frontend/CompilerInvocation.h 
b/clang/include/clang/Frontend/CompilerInvocation.h
index a01d9695dc..d3faa87018 100644
--- a/clang/include/clang/Frontend/CompilerInvocation.h
+++ b/clang/include/clang/Frontend/CompilerInvocation.h
@@ -229,20 +229,20 @@ public:
   /// @{
   // Note: These need to be pulled in manually. Otherwise, they get hidden by
   // the mutable getters with the same names.
-  using CompilerInvocationBase::getLangOpts;
-  using CompilerInvocationBase::getTargetOpts;
-  using CompilerInvocationBase::getDiagnosticOpts;
-  using CompilerInvocationBase::getHeaderSearchOpts;
-  using CompilerInvocationBase::getPreprocessorOpts;
   using CompilerInvocationBase::getAnalyzerOpts;
-  using CompilerInvocationBase::getMigratorOpts;
   using CompilerInvocationBase::getAPINotesOpts;
   using CompilerInvocationBase::getCodeGenOpts;
+  using CompilerInvocationBase::getDependencyOutputOpts;
+  using CompilerInvocationBase::getDiagnosticOpts;
   using CompilerInvocationBase::getFileSystemOpts;
   using CompilerInvocationBase::getFrontendOpts;
-  using CompilerInvocationBase::getDependencyOutputOpts;
-  using CompilerInvocationBase::getPreprocessorOutputOpts;
+  using CompilerInvocationBase::getHeaderSearchOpts;
   using CompilerInvocationBase::getInstallAPIOpts;
+  using CompilerInvocationBase::getLangOpts;
+  using CompilerInvocationBase::getMigratorOpts;
+  using CompilerInvocationBase::getPreprocessorOpts;
+  using CompilerInvocationBase::getPreprocessorOutputOpts;
+  using CompilerInvocationBase::getTargetOpts;
   /// @}
 
   /// Mutable getters.

``




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


[clang] [clang][InstallAPI] Introduce basic driver to write out tbd files (PR #81571)

2024-02-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver

Author: Cyndy Ishida (cyndyishida)


Changes

This introduces a basic outline of installapi as a clang driver option. It 
captures relevant information as cc1 args, which are common arguments already 
passed to the linker to encode into TBD file outputs. This is effectively an 
upstream for what already exists as `tapi installapi` in Xcode toolchains, but 
directly in Clang. This patch does not handle any AST traversing on input yet.

InstallAPI is broadly an operation that takes a series of header files that 
represent a single dynamic library and generates a TBD file out of it which 
represents all the linkable symbols and necessary attributes for statically 
linking in clients. It is the linkable object in all Apple SDKs and when 
building dylibs in Xcode. `clang -installapi` also will support verification 
where it compares all the information recorded for the TBD files against the 
already built binary, to catch possible mismatches like when a declaration is 
missing a definition for an exported symbol.

---

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


25 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticDriverKinds.td (+3) 
- (modified) clang/include/clang/Driver/Action.h (+12) 
- (modified) clang/include/clang/Driver/Options.td (+10-2) 
- (modified) clang/include/clang/Driver/Types.def (+1) 
- (modified) clang/include/clang/Frontend/CompilerInstance.h (+7) 
- (modified) clang/include/clang/Frontend/CompilerInvocation.h (+8-1) 
- (modified) clang/include/clang/Frontend/FrontendActions.h (+10) 
- (modified) clang/include/clang/Frontend/FrontendOptions.h (+3) 
- (added) clang/include/clang/Frontend/InstallAPIOptions.h (+28) 
- (added) clang/include/clang/InstallAPI/Context.h (+65) 
- (modified) clang/lib/CMakeLists.txt (+1) 
- (modified) clang/lib/Driver/Action.cpp (+7) 
- (modified) clang/lib/Driver/Driver.cpp (+14-1) 
- (modified) clang/lib/Driver/ToolChain.cpp (+1) 
- (modified) clang/lib/Driver/ToolChains/Clang.cpp (+11) 
- (modified) clang/lib/Frontend/CMakeLists.txt (+2) 
- (modified) clang/lib/Frontend/CompilerInvocation.cpp (+40-1) 
- (added) clang/lib/Frontend/InstallAPIConsumer.cpp (+43) 
- (modified) clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp (+2) 
- (added) clang/lib/InstallAPI/CMakeLists.txt (+11) 
- (added) clang/lib/InstallAPI/Context.cpp (+27) 
- (modified) clang/test/CMakeLists.txt (+1) 
- (added) clang/test/Driver/installapi.h (+13) 
- (added) clang/test/InstallAPI/installapi-basic.test (+34) 
- (modified) clang/test/lit.cfg.py (+2) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index b13181f6e70894..24cc17420c16cc 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -804,4 +804,7 @@ def warn_android_unversioned_fallback : Warning<
 
 def err_drv_triple_version_invalid : Error<
   "version '%0' in target triple '%1' is invalid">;
+
+def err_drv_installapi_unsupported : Error<
+  "the clang compiler does not support '%0' for InstallAPI">;
 }
diff --git a/clang/include/clang/Driver/Action.h 
b/clang/include/clang/Driver/Action.h
index 04fa8b01b418f8..2768e2f5df1a9e 100644
--- a/clang/include/clang/Driver/Action.h
+++ b/clang/include/clang/Driver/Action.h
@@ -59,6 +59,7 @@ class Action {
 PreprocessJobClass,
 PrecompileJobClass,
 ExtractAPIJobClass,
+InstallAPIJobClass,
 AnalyzeJobClass,
 MigrateJobClass,
 CompileJobClass,
@@ -448,6 +449,17 @@ class ExtractAPIJobAction : public JobAction {
   void addHeaderInput(Action *Input) { getInputs().push_back(Input); }
 };
 
+class InstallAPIJobAction : public JobAction {
+  void anchor() override;
+
+public:
+  InstallAPIJobAction(Action *Input, types::ID OutputType);
+
+  static bool classof(const Action *A) {
+return A->getKind() == InstallAPIJobClass;
+  }
+};
+
 class AnalyzeJobAction : public JobAction {
   void anchor() override;
 
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 31e8571758bfce..52c892b8b7f82c 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -309,6 +309,8 @@ class AnalyzerOpts
   : KeyPathAndMacro<"AnalyzerOpts->", base, "ANALYZER_"> {}
 class MigratorOpts
   : KeyPathAndMacro<"MigratorOpts.", base, "MIGRATOR_"> {}
+class InstallAPIOpts
+  : KeyPathAndMacro<"InstallAPIOpts.", base, "INSTALLAPI_"> {}
 
 // A boolean option which is opt-in in CC1. The positive option exists in CC1 
and
 // Args.hasArg(OPT_ffoo) can be used to check that the flag is enabled.
@@ -1114,7 +1116,8 @@ def config_user_dir_EQ : Joined<["--"], 
"config-user-dir=">,
 def coverage : Flag<["-", "--"], "coverage">, Group,
   Visibility<[ClangOption, CLOption]>;
 def cpp_precomp : Flag<["-"], "cpp-precomp">, Group;

[clang] [clang][InstallAPI] Introduce basic driver to write out tbd files (PR #81571)

2024-02-12 Thread Cyndy Ishida via cfe-commits

https://github.com/cyndyishida created 
https://github.com/llvm/llvm-project/pull/81571

This introduces a basic outline of installapi as a clang driver option. It 
captures relevant information as cc1 args, which are common arguments already 
passed to the linker to encode into TBD file outputs. This is effectively an 
upstream for what already exists as `tapi installapi` in Xcode toolchains, but 
directly in Clang. This patch does not handle any AST traversing on input yet.

InstallAPI is broadly an operation that takes a series of header files that 
represent a single dynamic library and generates a TBD file out of it which 
represents all the linkable symbols and necessary attributes for statically 
linking in clients. It is the linkable object in all Apple SDKs and when 
building dylibs in Xcode. `clang -installapi` also will support verification 
where it compares all the information recorded for the TBD files against the 
already built binary, to catch possible mismatches like when a declaration is 
missing a definition for an exported symbol.

>From 0f938ae8480f74a44bf6fe4aac6105e457315bb9 Mon Sep 17 00:00:00 2001
From: Cyndy Ishida 
Date: Mon, 12 Feb 2024 20:53:25 -0800
Subject: [PATCH]  [clang][InstallAPI] Introduce basic driver to write out tbd
 files.

This introduces a basic outline of installapi as a clang driver option.
It captures relavant information as cc1 args, which is commonly
arguments already passed to the linker to encode into TBD file outputs.
This is effectively an upstream for what already exists as `tapi installapi` in
Xcode toolchains, but direclty in clang. This patch does not handle any AST 
traversing on input yet.

InstallAPI is broadly an operation thats takes a series of header files
that represent a single dynamic library and generates a TBD file out of
it which represents all the linkable symbols and necessary attributes for 
statically linking in clients.
It also will support verification where it compares all the information
recorded for the TBD file against the already built binary, to catch
possible mismatches like when an symbol export is missing a matching
declaration.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |  3 +
 clang/include/clang/Driver/Action.h   | 12 
 clang/include/clang/Driver/Options.td | 12 +++-
 clang/include/clang/Driver/Types.def  |  1 +
 .../include/clang/Frontend/CompilerInstance.h |  7 ++
 .../clang/Frontend/CompilerInvocation.h   |  9 ++-
 .../include/clang/Frontend/FrontendActions.h  | 10 +++
 .../include/clang/Frontend/FrontendOptions.h  |  3 +
 .../clang/Frontend/InstallAPIOptions.h| 28 
 clang/include/clang/InstallAPI/Context.h  | 65 +++
 clang/lib/CMakeLists.txt  |  1 +
 clang/lib/Driver/Action.cpp   |  7 ++
 clang/lib/Driver/Driver.cpp   | 15 -
 clang/lib/Driver/ToolChain.cpp|  1 +
 clang/lib/Driver/ToolChains/Clang.cpp | 11 
 clang/lib/Frontend/CMakeLists.txt |  2 +
 clang/lib/Frontend/CompilerInvocation.cpp | 41 +++-
 clang/lib/Frontend/InstallAPIConsumer.cpp | 43 
 .../ExecuteCompilerInvocation.cpp |  2 +
 clang/lib/InstallAPI/CMakeLists.txt   | 11 
 clang/lib/InstallAPI/Context.cpp  | 27 
 clang/test/CMakeLists.txt |  1 +
 clang/test/Driver/installapi.h| 13 
 clang/test/InstallAPI/installapi-basic.test   | 34 ++
 clang/test/lit.cfg.py |  2 +
 25 files changed, 356 insertions(+), 5 deletions(-)
 create mode 100644 clang/include/clang/Frontend/InstallAPIOptions.h
 create mode 100644 clang/include/clang/InstallAPI/Context.h
 create mode 100644 clang/lib/Frontend/InstallAPIConsumer.cpp
 create mode 100644 clang/lib/InstallAPI/CMakeLists.txt
 create mode 100644 clang/lib/InstallAPI/Context.cpp
 create mode 100644 clang/test/Driver/installapi.h
 create mode 100644 clang/test/InstallAPI/installapi-basic.test

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index b13181f6e70894..24cc17420c16cc 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -804,4 +804,7 @@ def warn_android_unversioned_fallback : Warning<
 
 def err_drv_triple_version_invalid : Error<
   "version '%0' in target triple '%1' is invalid">;
+
+def err_drv_installapi_unsupported : Error<
+  "the clang compiler does not support '%0' for InstallAPI">;
 }
diff --git a/clang/include/clang/Driver/Action.h 
b/clang/include/clang/Driver/Action.h
index 04fa8b01b418f8..2768e2f5df1a9e 100644
--- a/clang/include/clang/Driver/Action.h
+++ b/clang/include/clang/Driver/Action.h
@@ -59,6 +59,7 @@ class Action {
 PreprocessJobClass,
 PrecompileJobClass,
 ExtractAPIJobClass,
+InstallAPIJobClass,
 AnalyzeJobClass,
 

[clang] [clang] Implement `__is_layout_compatible` (PR #81506)

2024-02-12 Thread Timm Baeder via cfe-commits


@@ -14040,6 +14040,8 @@ class Sema final {
   bool SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum);
 
 public:
+  bool SemaIsLayoutCompatible(QualType T1, QualType T2);

tbaederr wrote:

Can this function no be `const`? And I guess the "Sema" prefix is to 
disambiguate with the existing `isLayoutCompatible`?

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


[clang] [clang-tools-extra] [codegen] Emit missing cleanups when an expression contains a branch (PR #80698)

2024-02-12 Thread James Y Knight via cfe-commits

jyknight wrote:

Is there a valid use for having "EHCleanup" that _doesn't_ handle branches 
across it? That is, do we _ever_ need a cleanup to be called only for an 
exception thrown, and not otherwise leaving the scope? I'm just wondering if we 
can simplify things conceptually here and remove an option.

The only case I can think of is, perhaps, constructor's member initializer 
lists.

That is...we apparently accept the following code...and it does, I suppose, 
what one might "expect": skips over construction of "b" and "c" and jumps into 
the middle of the constructor function, from which it returns normally as if 
the object was fully constructed. Using "return" instead of "goto" works too, 
also returning "successfully" from the constructor.
```
struct X { X(int); ~X(); };

struct Test {
Test() : a(1), b( ({ goto label; 2; }) ), c(3) { label: f();}
X a, b, c;
};

Test* test() { return new Test(); }
```
But...that really seems like code we should be rejecting as invalid (in which 
case, there need not be a distinction between cleanup due to exception or 
branch).

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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-12 Thread Owen Pan via cfe-commits

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


[clang] 91dcf53 - [clang-format] Rename option AlwaysBreakAfterReturnType. (#80827)

2024-02-12 Thread via cfe-commits

Author: rmarker
Date: 2024-02-12T20:28:33-08:00
New Revision: 91dcf53abd34fa836a126c706f87b810d299d802

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

LOG: [clang-format] Rename option AlwaysBreakAfterReturnType. (#80827)

Changes the option to BreakAfterReturnType option, with a more relevant
name, deprecating and replacing AlwaysBreakAfterReturnType.
Following up on #78010.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/unittests/Format/ConfigParseTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 5deeff0db239a8..fdf7bfaeaa4ec7 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1531,114 +1531,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. _AlwaysBreakAfterReturnType:
 
-**AlwaysBreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 3.8` :ref:`¶ `
-  The function declaration return type breaking style to use.
-
-  Possible values:
-
-  * ``RTBS_None`` (in configuration: ``None``)
-This is **deprecated**. See ``Automatic`` below.
-
-  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
-Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
-Same as ``Automatic`` above, except that there is no break after short
-return types.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int LongName::
-  AnotherLongName();
-
-  * ``RTBS_All`` (in configuration: ``All``)
-Always break after the return type.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevel`` (in configuration: ``TopLevel``)
-Always break after the return types of top-level functions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_AllDefinitions`` (in configuration: ``AllDefinitions``)
-Always break after the return type of function definitions.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevelDefinitions`` (in configuration: ``TopLevelDefinitions``)
-Always break after the return type of top-level definitions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-
+**AlwaysBreakAfterReturnType** (``deprecated``) :versionbadge:`clang-format 
3.8` :ref:`¶ `
+  This option is renamed to ``BreakAfterReturnType``.
 
 .. _AlwaysBreakBeforeMultilineStrings:
 
@@ -2219,6 +2113,117 @@ the configuration (without a prefix: ``Auto``).
  @Mock
  DataLoad loader;
 
+.. _BreakAfterReturnType:
+
+**BreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 19` :ref:`¶ `
+  The function declaration return type breaking style to use.
+
+  Possible values:
+
+  * ``RTBS_None`` (in configuration: ``None``)
+This is **deprecated**. See ``Automatic`` below.
+
+  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
+Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int
+  LongName::AnotherLongName();
+
+  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
+Same as ``Automatic`` above, except that there is no break after short
+return types.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int LongName::
+  AnotherLongName();
+
+  * ``RTBS_All`` (in configuration: ``All``)
+Always break after the return type.
+
+.. code-block:: c++
+
+  class A {
+int
+f() {
+  return 0;
+};

[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits


@@ -145,9 +164,94 @@ namespace {
   .addImm(0);
 
 if (IsAIX) {
-  // The variable offset and region handle are copied in r4 and r3. The
-  // copies are followed by GETtlsADDR32AIX/GETtlsADDR64AIX.
-  if (!IsTLSTPRelMI) {
+  if (IsTLSLDAIXMI) {
+// The relative order between the LoadOffset@toc node (for the
+// variable offset), and the .__tls_get_mod node is being tuned
+// here. It is better to put the LoadOffset@toc node after the 
call,
+// since the LoadOffset@toc node can use clobbers r4/r5. Search for
+// the pattern of two Load@toc nodes (either for the variable 
offset
+// or for the module handle), and then move the LoadOffset@toc node
+// right before the node that uses the OutReg of the .__tls_get_mod
+// node.
+unsigned LDTocOp =
+Is64Bit ? (IsLargeModel ? PPC::LDtocL : PPC::LDtoc)
+: (IsLargeModel ? PPC::LWZtocL : PPC::LWZtoc);
+if (!RegInfo.use_empty(OutReg)) {
+  std::set Uses;
+  // Collect all instructions that use the OutReg.
+  for (MachineOperand  : RegInfo.use_operands(OutReg))
+Uses.insert(MO.getParent());
+  // Find the first user (e.g.: lwax/stfdx) of the OutReg within 
the
+  // current BB.
+  MachineBasicBlock::iterator UseIter = MBB.begin();
+  for (MachineBasicBlock::iterator IE = MBB.end(); UseIter != IE;
+   ++UseIter)
+if (Uses.count(&*UseIter))
+  break;
+
+  // Additional handling is required when UserIter (the first user
+  // of OutReg) is pointing to a valid node. Check the pattern and
+  // do the movement if the pattern matches.
+  if (UseIter != MBB.end()) {
+// Collect associated Load@toc nodes. Use hasOneDef() to guard
+// against unexpected scenarios.
+std::set LoadFromTocs;
+for (MachineOperand  : UseIter->operands())
+  if (MO.isReg() && MO.isUse()) {
+Register MOReg = MO.getReg();
+if (RegInfo.hasOneDef(MOReg)) {
+  MachineInstr *Temp =
+  RegInfo.getOneDef(MOReg)->getParent();
+  // For the current TLSLDAIX node, get the Load@toc node
+  // for the InReg. Otherwise, Temp probably pointed to the
+  // LoadOffset@toc node that we would like to move.
+  if (Temp ==  && RegInfo.hasOneDef(InReg))
+Temp = RegInfo.getOneDef(InReg)->getParent();
+  if (Temp->getOpcode() == LDTocOp)
+LoadFromTocs.insert(Temp);
+} else {
+  // FIXME: analyze this scenario if there is one.
+  LoadFromTocs.clear();
+  break;
+}
+  }
+
+// Check the two Load@toc: one should be _$TLSML, and the other
+// will be moved before the node that uses the OutReg of the
+// .__tls_get_mod node.
+if (LoadFromTocs.size() == 2) {
+  MachineBasicBlock::iterator TLSMLIter = MBB.end();
+  MachineBasicBlock::iterator OffsetIter = MBB.end();
+  // Make sure the two LoadFromTocs are within current BB, and
+  // one of them from the "_$TLSML" pseudo symbol, while the
+  // other from the variable.
+  for (MachineBasicBlock::iterator I = MBB.begin(),
+   IE = MBB.end();
+   I != IE; ++I)
+if (LoadFromTocs.count(&*I)) {
+  MachineOperand MO = I->getOperand(1);
+  if (MO.isGlobal() && MO.getGlobal()->hasName() &&
+  MO.getGlobal()->getName() == "_$TLSML")
+TLSMLIter = I;
+  else
+OffsetIter = I;
+}
+  // If both two iterators are valid, we should have identified
+  // the scenario, and do the movement.

amy-kwan wrote:

```suggestion
  // Perform the movement when the desired scenario has been
  // identified, which should be when both of the iterators are 
valid.
```
This may sound a bit better.

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits


@@ -145,9 +164,94 @@ namespace {
   .addImm(0);
 
 if (IsAIX) {
-  // The variable offset and region handle are copied in r4 and r3. The
-  // copies are followed by GETtlsADDR32AIX/GETtlsADDR64AIX.
-  if (!IsTLSTPRelMI) {
+  if (IsTLSLDAIXMI) {
+// The relative order between the LoadOffset@toc node (for the
+// variable offset), and the .__tls_get_mod node is being tuned
+// here. It is better to put the LoadOffset@toc node after the 
call,
+// since the LoadOffset@toc node can use clobbers r4/r5. Search for
+// the pattern of two Load@toc nodes (either for the variable 
offset
+// or for the module handle), and then move the LoadOffset@toc node
+// right before the node that uses the OutReg of the .__tls_get_mod
+// node.
+unsigned LDTocOp =
+Is64Bit ? (IsLargeModel ? PPC::LDtocL : PPC::LDtoc)
+: (IsLargeModel ? PPC::LWZtocL : PPC::LWZtoc);
+if (!RegInfo.use_empty(OutReg)) {
+  std::set Uses;
+  // Collect all instructions that use the OutReg.
+  for (MachineOperand  : RegInfo.use_operands(OutReg))
+Uses.insert(MO.getParent());
+  // Find the first user (e.g.: lwax/stfdx) of the OutReg within 
the
+  // current BB.
+  MachineBasicBlock::iterator UseIter = MBB.begin();
+  for (MachineBasicBlock::iterator IE = MBB.end(); UseIter != IE;
+   ++UseIter)
+if (Uses.count(&*UseIter))
+  break;
+
+  // Additional handling is required when UserIter (the first user
+  // of OutReg) is pointing to a valid node. Check the pattern and
+  // do the movement if the pattern matches.
+  if (UseIter != MBB.end()) {
+// Collect associated Load@toc nodes. Use hasOneDef() to guard
+// against unexpected scenarios.
+std::set LoadFromTocs;
+for (MachineOperand  : UseIter->operands())
+  if (MO.isReg() && MO.isUse()) {
+Register MOReg = MO.getReg();
+if (RegInfo.hasOneDef(MOReg)) {
+  MachineInstr *Temp =
+  RegInfo.getOneDef(MOReg)->getParent();
+  // For the current TLSLDAIX node, get the Load@toc node
+  // for the InReg. Otherwise, Temp probably pointed to the
+  // LoadOffset@toc node that we would like to move.
+  if (Temp ==  && RegInfo.hasOneDef(InReg))
+Temp = RegInfo.getOneDef(InReg)->getParent();
+  if (Temp->getOpcode() == LDTocOp)
+LoadFromTocs.insert(Temp);
+} else {
+  // FIXME: analyze this scenario if there is one.
+  LoadFromTocs.clear();
+  break;
+}
+  }
+
+// Check the two Load@toc: one should be _$TLSML, and the other

amy-kwan wrote:

```suggestion
// Check the two Load@toc nodes: one should be _$TLSML, and the 
other
```

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits

https://github.com/amy-kwan commented:

I believe some of the test cases also require updates as a result of 
https://github.com/llvm/llvm-project/pull/80162.

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits


@@ -145,9 +164,94 @@ namespace {
   .addImm(0);
 
 if (IsAIX) {
-  // The variable offset and region handle are copied in r4 and r3. The
-  // copies are followed by GETtlsADDR32AIX/GETtlsADDR64AIX.
-  if (!IsTLSTPRelMI) {
+  if (IsTLSLDAIXMI) {
+// The relative order between the LoadOffset@toc node (for the
+// variable offset), and the .__tls_get_mod node is being tuned
+// here. It is better to put the LoadOffset@toc node after the 
call,
+// since the LoadOffset@toc node can use clobbers r4/r5. Search for
+// the pattern of two Load@toc nodes (either for the variable 
offset
+// or for the module handle), and then move the LoadOffset@toc node
+// right before the node that uses the OutReg of the .__tls_get_mod
+// node.
+unsigned LDTocOp =
+Is64Bit ? (IsLargeModel ? PPC::LDtocL : PPC::LDtoc)
+: (IsLargeModel ? PPC::LWZtocL : PPC::LWZtoc);
+if (!RegInfo.use_empty(OutReg)) {
+  std::set Uses;
+  // Collect all instructions that use the OutReg.
+  for (MachineOperand  : RegInfo.use_operands(OutReg))
+Uses.insert(MO.getParent());
+  // Find the first user (e.g.: lwax/stfdx) of the OutReg within 
the
+  // current BB.
+  MachineBasicBlock::iterator UseIter = MBB.begin();
+  for (MachineBasicBlock::iterator IE = MBB.end(); UseIter != IE;
+   ++UseIter)
+if (Uses.count(&*UseIter))
+  break;
+
+  // Additional handling is required when UserIter (the first user
+  // of OutReg) is pointing to a valid node. Check the pattern and
+  // do the movement if the pattern matches.
+  if (UseIter != MBB.end()) {
+// Collect associated Load@toc nodes. Use hasOneDef() to guard
+// against unexpected scenarios.
+std::set LoadFromTocs;
+for (MachineOperand  : UseIter->operands())
+  if (MO.isReg() && MO.isUse()) {
+Register MOReg = MO.getReg();
+if (RegInfo.hasOneDef(MOReg)) {
+  MachineInstr *Temp =
+  RegInfo.getOneDef(MOReg)->getParent();
+  // For the current TLSLDAIX node, get the Load@toc node
+  // for the InReg. Otherwise, Temp probably pointed to the
+  // LoadOffset@toc node that we would like to move.
+  if (Temp ==  && RegInfo.hasOneDef(InReg))
+Temp = RegInfo.getOneDef(InReg)->getParent();
+  if (Temp->getOpcode() == LDTocOp)
+LoadFromTocs.insert(Temp);
+} else {
+  // FIXME: analyze this scenario if there is one.
+  LoadFromTocs.clear();
+  break;
+}
+  }
+
+// Check the two Load@toc: one should be _$TLSML, and the other
+// will be moved before the node that uses the OutReg of the
+// .__tls_get_mod node.
+if (LoadFromTocs.size() == 2) {
+  MachineBasicBlock::iterator TLSMLIter = MBB.end();
+  MachineBasicBlock::iterator OffsetIter = MBB.end();
+  // Make sure the two LoadFromTocs are within current BB, and
+  // one of them from the "_$TLSML" pseudo symbol, while the
+  // other from the variable.

amy-kwan wrote:

```suggestion
  // Make sure the two LoadFromTocs nodes are within the 
current BB, and
  // that one of them is from the "_$TLSML" pseudo symbol, 
while the
  // other from the variable.
```

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2024-02-12 Thread Amy Kwan via cfe-commits


@@ -145,9 +164,94 @@ namespace {
   .addImm(0);
 
 if (IsAIX) {
-  // The variable offset and region handle are copied in r4 and r3. The
-  // copies are followed by GETtlsADDR32AIX/GETtlsADDR64AIX.
-  if (!IsTLSTPRelMI) {
+  if (IsTLSLDAIXMI) {
+// The relative order between the LoadOffset@toc node (for the
+// variable offset), and the .__tls_get_mod node is being tuned
+// here. It is better to put the LoadOffset@toc node after the 
call,
+// since the LoadOffset@toc node can use clobbers r4/r5. Search for
+// the pattern of two Load@toc nodes (either for the variable 
offset
+// or for the module handle), and then move the LoadOffset@toc node
+// right before the node that uses the OutReg of the .__tls_get_mod
+// node.
+unsigned LDTocOp =
+Is64Bit ? (IsLargeModel ? PPC::LDtocL : PPC::LDtoc)
+: (IsLargeModel ? PPC::LWZtocL : PPC::LWZtoc);
+if (!RegInfo.use_empty(OutReg)) {
+  std::set Uses;
+  // Collect all instructions that use the OutReg.
+  for (MachineOperand  : RegInfo.use_operands(OutReg))
+Uses.insert(MO.getParent());
+  // Find the first user (e.g.: lwax/stfdx) of the OutReg within 
the
+  // current BB.
+  MachineBasicBlock::iterator UseIter = MBB.begin();
+  for (MachineBasicBlock::iterator IE = MBB.end(); UseIter != IE;
+   ++UseIter)
+if (Uses.count(&*UseIter))
+  break;
+
+  // Additional handling is required when UserIter (the first user
+  // of OutReg) is pointing to a valid node. Check the pattern and
+  // do the movement if the pattern matches.
+  if (UseIter != MBB.end()) {
+// Collect associated Load@toc nodes. Use hasOneDef() to guard
+// against unexpected scenarios.
+std::set LoadFromTocs;
+for (MachineOperand  : UseIter->operands())
+  if (MO.isReg() && MO.isUse()) {
+Register MOReg = MO.getReg();
+if (RegInfo.hasOneDef(MOReg)) {
+  MachineInstr *Temp =
+  RegInfo.getOneDef(MOReg)->getParent();
+  // For the current TLSLDAIX node, get the Load@toc node
+  // for the InReg. Otherwise, Temp probably pointed to the
+  // LoadOffset@toc node that we would like to move.
+  if (Temp ==  && RegInfo.hasOneDef(InReg))
+Temp = RegInfo.getOneDef(InReg)->getParent();
+  if (Temp->getOpcode() == LDTocOp)
+LoadFromTocs.insert(Temp);
+} else {
+  // FIXME: analyze this scenario if there is one.
+  LoadFromTocs.clear();
+  break;
+}
+  }
+
+// Check the two Load@toc: one should be _$TLSML, and the other
+// will be moved before the node that uses the OutReg of the
+// .__tls_get_mod node.
+if (LoadFromTocs.size() == 2) {
+  MachineBasicBlock::iterator TLSMLIter = MBB.end();
+  MachineBasicBlock::iterator OffsetIter = MBB.end();
+  // Make sure the two LoadFromTocs are within current BB, and
+  // one of them from the "_$TLSML" pseudo symbol, while the
+  // other from the variable.
+  for (MachineBasicBlock::iterator I = MBB.begin(),
+   IE = MBB.end();
+   I != IE; ++I)
+if (LoadFromTocs.count(&*I)) {
+  MachineOperand MO = I->getOperand(1);
+  if (MO.isGlobal() && MO.getGlobal()->hasName() &&
+  MO.getGlobal()->getName() == "_$TLSML")
+TLSMLIter = I;
+  else
+OffsetIter = I;
+}
+  // If both two iterators are valid, we should have identified
+  // the scenario, and do the movement.
+  if (TLSMLIter != MBB.end() && OffsetIter != MBB.end())
+OffsetIter->moveBefore(&*UseIter);
+}
+  }
+}
+// The module-handle is copied into r3. The copy is followed by
+// GETtlsMOD32AIX/GETtlsMOD64AIX.
+BuildMI(MBB, I, DL, TII->get(TargetOpcode::COPY), GPR3)
+.addReg(InReg);
+// The call to .__tls_get_mod.
+BuildMI(MBB, I, DL, TII->get(Opc2), 

[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)

2024-02-12 Thread Connor Sughrue via cfe-commits

https://github.com/cpsughrue updated 
https://github.com/llvm/llvm-project/pull/67562

>From 03d3310ca300630a94517fa300858d1f2645e843 Mon Sep 17 00:00:00 2001
From: cpsughrue 
Date: Sun, 9 Jul 2023 23:19:58 -0400
Subject: [PATCH 01/17] [clang][MBD] set up module build daemon infrastructure

The module build daemon (mbd) will serve as a cc1 tool that helps convert
implicit module command lines to explicit module command lines. A clang
invocation will check to see if a mbd exists, if not the invocation will spawn
one. After the mbd is up and running and a handshake has successfully been
carried out between the mbd and clang invocation the clang invocation will
share it's command line with the mbd. The mbd will then scan the translation
unit and build all modular dependencies before returning a modified cc1 command
line such that all arguments related to modules are converted from the
implicit option to their explicit option.

This commit sets up the basic mbd infrastructure. Including the ability to
spawn a mbd and carry out a handshake between the clang invocation and mbd.

RFC: 
https://discourse.llvm.org/t/rfc-modules-build-daemon-build-system-agnostic-support-for-explicitly-built-modules/71524
---
 .../clang/Basic/DiagnosticFrontendKinds.td|  20 ++
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 clang/include/clang/Driver/Options.td |  13 +
 .../include/clang/Frontend/FrontendOptions.h  |   8 +
 .../Tooling/ModuleBuildDaemon/Frontend.h  |  36 +++
 .../Tooling/ModuleBuildDaemon/SocketSupport.h | 126 +
 .../clang/Tooling/ModuleBuildDaemon/Utils.h   |  58 
 clang/lib/Driver/ToolChains/Clang.cpp |  14 +-
 clang/lib/Tooling/CMakeLists.txt  |   1 +
 .../Tooling/ModuleBuildDaemon/CMakeLists.txt  |   9 +
 .../Tooling/ModuleBuildDaemon/Frontend.cpp| 166 
 .../ModuleBuildDaemon/SocketSupport.cpp   |  66 +
 clang/lib/Tooling/ModuleBuildDaemon/Utils.cpp |  49 
 clang/test/Driver/unknown-arg.c   |   2 +-
 clang/test/Frontend/warning-options.cpp   |   2 +-
 clang/test/ModuleBuildDaemon/daemon-launch.c  |  18 ++
 clang/test/ModuleBuildDaemon/handshake.c  |  22 ++
 clang/test/lit.cfg.py |  11 +
 clang/tools/driver/CMakeLists.txt |   3 +
 clang/tools/driver/cc1_main.cpp   |  17 +-
 clang/tools/driver/cc1modbuildd_main.cpp  | 255 ++
 clang/tools/driver/driver.cpp |  10 +-
 clang/utils/kill_process.py   |  86 ++
 llvm/include/llvm/Support/Program.h   |   3 +-
 llvm/include/llvm/Support/raw_socket_stream.h |   8 +-
 llvm/lib/Support/Program.cpp  |   9 +-
 llvm/lib/Support/Unix/Program.inc |  18 +-
 llvm/lib/Support/Windows/Program.inc  |   7 +-
 llvm/lib/Support/raw_socket_stream.cpp|  46 +++-
 29 files changed, 1055 insertions(+), 29 deletions(-)
 create mode 100644 clang/include/clang/Tooling/ModuleBuildDaemon/Frontend.h
 create mode 100644 
clang/include/clang/Tooling/ModuleBuildDaemon/SocketSupport.h
 create mode 100644 clang/include/clang/Tooling/ModuleBuildDaemon/Utils.h
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/CMakeLists.txt
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/Frontend.cpp
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/SocketSupport.cpp
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/Utils.cpp
 create mode 100644 clang/test/ModuleBuildDaemon/daemon-launch.c
 create mode 100644 clang/test/ModuleBuildDaemon/handshake.c
 create mode 100644 clang/tools/driver/cc1modbuildd_main.cpp
 create mode 100644 clang/utils/kill_process.py

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 85ecfdf9de62d4..a858bc163de0c3 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -262,6 +262,26 @@ def err_test_module_file_extension_version : Error<
   "test module file extension '%0' has different version (%1.%2) than expected 
"
   "(%3.%4)">;
 
+// Module Build Daemon
+def err_basepath_length :
+  Error<"BasePath '%0' is longer then the max length of %1">,
+  DefaultFatal;
+def err_mbd_handshake :
+  Error<"Attempt to handshake with module build daemon has failed: %0">,
+  DefaultFatal;
+def err_mbd_connect :
+  Error<"Attempt to connect to module build daemon has failed: %0">,
+  DefaultFatal;
+def remark_mbd_spawn :
+  Remark<"Successfully spawned module build daemon">,
+  InGroup;
+def remark_mbd_connection :
+  Remark<"Successfully connected to module build daemon at %0">,
+  InGroup;
+def remark_mbd_handshake :
+  Remark<"Successfully completed handshake with module build daemon">,
+  InGroup;
+
 def warn_eagerly_load_for_standard_cplusplus_modules : Warning<
   "the form '-fmodule-file=' is deprecated for standard C++ named 
modules;"
   "consider to use '-fmodule-file==' 

[clang] [llvm] [clang][MBD] set up module build daemon infrastructure (PR #67562)

2024-02-12 Thread Connor Sughrue via cfe-commits

https://github.com/cpsughrue updated 
https://github.com/llvm/llvm-project/pull/67562

>From 03d3310ca300630a94517fa300858d1f2645e843 Mon Sep 17 00:00:00 2001
From: cpsughrue 
Date: Sun, 9 Jul 2023 23:19:58 -0400
Subject: [PATCH 01/17] [clang][MBD] set up module build daemon infrastructure

The module build daemon (mbd) will serve as a cc1 tool that helps convert
implicit module command lines to explicit module command lines. A clang
invocation will check to see if a mbd exists, if not the invocation will spawn
one. After the mbd is up and running and a handshake has successfully been
carried out between the mbd and clang invocation the clang invocation will
share it's command line with the mbd. The mbd will then scan the translation
unit and build all modular dependencies before returning a modified cc1 command
line such that all arguments related to modules are converted from the
implicit option to their explicit option.

This commit sets up the basic mbd infrastructure. Including the ability to
spawn a mbd and carry out a handshake between the clang invocation and mbd.

RFC: 
https://discourse.llvm.org/t/rfc-modules-build-daemon-build-system-agnostic-support-for-explicitly-built-modules/71524
---
 .../clang/Basic/DiagnosticFrontendKinds.td|  20 ++
 clang/include/clang/Basic/DiagnosticGroups.td |   1 +
 clang/include/clang/Driver/Options.td |  13 +
 .../include/clang/Frontend/FrontendOptions.h  |   8 +
 .../Tooling/ModuleBuildDaemon/Frontend.h  |  36 +++
 .../Tooling/ModuleBuildDaemon/SocketSupport.h | 126 +
 .../clang/Tooling/ModuleBuildDaemon/Utils.h   |  58 
 clang/lib/Driver/ToolChains/Clang.cpp |  14 +-
 clang/lib/Tooling/CMakeLists.txt  |   1 +
 .../Tooling/ModuleBuildDaemon/CMakeLists.txt  |   9 +
 .../Tooling/ModuleBuildDaemon/Frontend.cpp| 166 
 .../ModuleBuildDaemon/SocketSupport.cpp   |  66 +
 clang/lib/Tooling/ModuleBuildDaemon/Utils.cpp |  49 
 clang/test/Driver/unknown-arg.c   |   2 +-
 clang/test/Frontend/warning-options.cpp   |   2 +-
 clang/test/ModuleBuildDaemon/daemon-launch.c  |  18 ++
 clang/test/ModuleBuildDaemon/handshake.c  |  22 ++
 clang/test/lit.cfg.py |  11 +
 clang/tools/driver/CMakeLists.txt |   3 +
 clang/tools/driver/cc1_main.cpp   |  17 +-
 clang/tools/driver/cc1modbuildd_main.cpp  | 255 ++
 clang/tools/driver/driver.cpp |  10 +-
 clang/utils/kill_process.py   |  86 ++
 llvm/include/llvm/Support/Program.h   |   3 +-
 llvm/include/llvm/Support/raw_socket_stream.h |   8 +-
 llvm/lib/Support/Program.cpp  |   9 +-
 llvm/lib/Support/Unix/Program.inc |  18 +-
 llvm/lib/Support/Windows/Program.inc  |   7 +-
 llvm/lib/Support/raw_socket_stream.cpp|  46 +++-
 29 files changed, 1055 insertions(+), 29 deletions(-)
 create mode 100644 clang/include/clang/Tooling/ModuleBuildDaemon/Frontend.h
 create mode 100644 
clang/include/clang/Tooling/ModuleBuildDaemon/SocketSupport.h
 create mode 100644 clang/include/clang/Tooling/ModuleBuildDaemon/Utils.h
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/CMakeLists.txt
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/Frontend.cpp
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/SocketSupport.cpp
 create mode 100644 clang/lib/Tooling/ModuleBuildDaemon/Utils.cpp
 create mode 100644 clang/test/ModuleBuildDaemon/daemon-launch.c
 create mode 100644 clang/test/ModuleBuildDaemon/handshake.c
 create mode 100644 clang/tools/driver/cc1modbuildd_main.cpp
 create mode 100644 clang/utils/kill_process.py

diff --git a/clang/include/clang/Basic/DiagnosticFrontendKinds.td 
b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
index 85ecfdf9de62d4..a858bc163de0c3 100644
--- a/clang/include/clang/Basic/DiagnosticFrontendKinds.td
+++ b/clang/include/clang/Basic/DiagnosticFrontendKinds.td
@@ -262,6 +262,26 @@ def err_test_module_file_extension_version : Error<
   "test module file extension '%0' has different version (%1.%2) than expected 
"
   "(%3.%4)">;
 
+// Module Build Daemon
+def err_basepath_length :
+  Error<"BasePath '%0' is longer then the max length of %1">,
+  DefaultFatal;
+def err_mbd_handshake :
+  Error<"Attempt to handshake with module build daemon has failed: %0">,
+  DefaultFatal;
+def err_mbd_connect :
+  Error<"Attempt to connect to module build daemon has failed: %0">,
+  DefaultFatal;
+def remark_mbd_spawn :
+  Remark<"Successfully spawned module build daemon">,
+  InGroup;
+def remark_mbd_connection :
+  Remark<"Successfully connected to module build daemon at %0">,
+  InGroup;
+def remark_mbd_handshake :
+  Remark<"Successfully completed handshake with module build daemon">,
+  InGroup;
+
 def warn_eagerly_load_for_standard_cplusplus_modules : Warning<
   "the form '-fmodule-file=' is deprecated for standard C++ named 
modules;"
   "consider to use '-fmodule-file==' 

[clang] [llvm] [PGO] Add ability to mark cold functions as optsize/minsize/optnone (PR #69030)

2024-02-12 Thread via cfe-commits

WenleiHe wrote:

> > > > Good example. This pass should be run post-inline. @aeubanks, any 
> > > > reason we want to run it early in the pipeline?
> > > 
> > > 
> > > We want the main function simplification pipeline to see these function 
> > > attributes because some optimizations trigger or don't trigger depending 
> > > on the presence of the attributes. Modifying function attributes is 
> > > typically done in CGSCC/module passes since doing so can affect what 
> > > callers of those functions see (in effect changing other functions), 
> > > which shouldn't happen in function passes. I suppose it's possible to add 
> > > this as a CGSCC pass that runs after inlining and before the function 
> > > simplification pipeline, but this is more of a one time thing and CGSCC 
> > > passes can revisit functions. So this pass makes the most sense as a 
> > > module pass, but we can't insert a module pass between inlining and the 
> > > function simplification pipeline.
> > > Can/does the inliner ignore these size attributes when it has call-site 
> > > profile information?
> > 
> > 
> > Looking at the current change, this new pass is actually after the sample 
> > loader (including sample loader inlining) pass, so wenlei@'s concern should 
> > be addressed.
> 
> Oh I forgot that the sample profile has its own inliner. Yes this pass runs 
> after we load profiling information since it uses profiling information, 
> whether it's sample or instrumented.
> 
> Is this patch good to go?

This is good to go only because it's off by default. Otherwise it's not. 

Left one more comment on the patch as I didn't get a chance to look at final 
code before it went in. 

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


[clang] [llvm] [PGO] Add ability to mark cold functions as optsize/minsize/optnone (PR #69030)

2024-02-12 Thread via cfe-commits


@@ -0,0 +1,61 @@
+//===--===//
+//
+// 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 "llvm/Transforms/Instrumentation/PGOForceFunctionAttrs.h"
+#include "llvm/Analysis/BlockFrequencyInfo.h"
+#include "llvm/Analysis/ProfileSummaryInfo.h"
+#include "llvm/IR/PassManager.h"
+#include "llvm/Support/ErrorHandling.h"
+
+using namespace llvm;
+
+static bool shouldRunOnFunction(Function , ProfileSummaryInfo ,
+FunctionAnalysisManager ) {
+  if (F.isDeclaration())
+return false;
+  // Respect existing attributes.
+  if (F.hasOptNone() || F.hasOptSize() || F.hasMinSize())
+return false;
+  if (F.hasFnAttribute(Attribute::Cold))
+return true;
+  if (!PSI.hasProfileSummary())
+return false;
+  BlockFrequencyInfo  = FAM.getResult(F);
+  return PSI.isFunctionColdInCallGraph(, BFI);
+}
+
+PreservedAnalyses PGOForceFunctionAttrsPass::run(Module ,
+ ModuleAnalysisManager ) {
+  if (ColdType == PGOOptions::ColdFuncOpt::Default)
+return PreservedAnalyses::all();
+  ProfileSummaryInfo  = AM.getResult(M);
+  FunctionAnalysisManager  =
+  AM.getResult(M).getManager();
+  bool MadeChange = false;
+  for (Function  : M) {
+if (!shouldRunOnFunction(F, PSI, FAM))
+  continue;
+MadeChange = true;
+switch (ColdType) {
+case PGOOptions::ColdFuncOpt::Default:
+  llvm_unreachable("bailed out for default above");
+  break;
+case PGOOptions::ColdFuncOpt::OptSize:
+  F.addFnAttr(Attribute::OptimizeForSize);
+  break;
+case PGOOptions::ColdFuncOpt::MinSize:
+  F.addFnAttr(Attribute::MinSize);
+  break;
+case PGOOptions::ColdFuncOpt::OptNone:
+  F.addFnAttr(Attribute::OptimizeNone);
+  F.addFnAttr(Attribute::NoInline);

WenleiHe wrote:

What if functions originally has `AlwaysInline` attribute? 

More generally, what if function originally has a conflicting attribute from 
what's being set here? 

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


[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and builtin for realtime clocks (PR #81331)

2024-02-12 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> Add to release notes?

Done

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


[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and builtin for realtime clocks (PR #81331)

2024-02-12 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 updated 
https://github.com/llvm/llvm-project/pull/81331

>From 4a0ee4be9690e0665ca93d63ffdd2dea404fd72d Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Fri, 9 Feb 2024 16:13:42 -0600
Subject: [PATCH] [LLVM] Add `__builtin_readsteadycounter` intrinsic and
 buiiltin

Summary:
This patch adds a new intrinsic and builtin function mirroring the
existing `__builtin_readcyclecounter`. The difference is that this
implementation targets a separate counter that some targets have which
returns a fixed frequency clock that can be used to determine elapsed
time, this is different compared to the cycle counter which often has
variable frequency. This is currently only valid for the NVPTX and
AMDGPU targets.
---
 clang/docs/LanguageExtensions.rst | 33 ++
 clang/docs/ReleaseNotes.rst   |  3 +
 clang/include/clang/Basic/Builtins.td |  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 ++
 clang/test/CodeGen/builtins.c |  6 ++
 llvm/include/llvm/CodeGen/ISDOpcodes.h|  6 ++
 llvm/include/llvm/IR/Intrinsics.td|  2 +
 llvm/include/llvm/Support/TargetOpcodes.def   |  3 +
 llvm/include/llvm/Target/GenericOpcodes.td|  6 ++
 .../Target/GlobalISel/SelectionDAGCompat.td   |  1 +
 .../include/llvm/Target/TargetSelectionDAG.td |  3 +
 llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp  |  2 +
 llvm/lib/CodeGen/IntrinsicLowering.cpp|  6 ++
 llvm/lib/CodeGen/SelectionDAG/LegalizeDAG.cpp |  6 +-
 .../SelectionDAG/LegalizeIntegerTypes.cpp |  7 ++-
 llvm/lib/CodeGen/SelectionDAG/LegalizeTypes.h |  2 +-
 .../SelectionDAG/SelectionDAGBuilder.cpp  |  8 +++
 .../SelectionDAG/SelectionDAGDumper.cpp   |  1 +
 llvm/lib/CodeGen/TargetLoweringBase.cpp   |  3 +
 .../lib/Target/AMDGPU/AMDGPULegalizerInfo.cpp |  2 +
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  1 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  4 ++
 llvm/lib/Target/AMDGPU/SMInstructions.td  | 14 +
 llvm/lib/Target/NVPTX/NVPTXISelLowering.cpp   |  2 +
 llvm/lib/Target/NVPTX/NVPTXInstrInfo.td   |  1 -
 llvm/lib/Target/NVPTX/NVPTXIntrinsics.td  |  1 +
 .../GlobalISel/legalizer-info-validation.mir  |  3 +
 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll | 24 +++
 llvm/test/CodeGen/NVPTX/intrinsics.ll | 12 
 .../builtins/match-table-replacerreg.td   | 24 +++
 .../match-table-imms.td   | 32 +-
 .../match-table-intrinsics.td |  5 +-
 .../match-table-patfrag-root.td   |  4 +-
 .../GlobalISelCombinerEmitter/match-table.td  | 62 +--
 llvm/test/TableGen/GlobalISelEmitter.td   |  2 +-
 35 files changed, 229 insertions(+), 72 deletions(-)
 create mode 100644 llvm/test/CodeGen/AMDGPU/readsteadycounter.ll

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index e91156837290f7..ca78a5c39cf736 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -2764,6 +2764,39 @@ Query for this feature with 
``__has_builtin(__builtin_readcyclecounter)``. Note
 that even if present, its use may depend on run-time privilege or other OS
 controlled state.
 
+``__builtin_readsteadycounter``
+--
+
+``__builtin_readsteadycounter`` is used to access the fixed frequency counter
+register (or a similar steady-rate clock) on those targets that support it.
+The function is similar to ``__builtin_readcyclecounter`` above except that the
+frequency is fixed, making it suitable for measuring elapsed time.
+
+**Syntax**:
+
+.. code-block:: c++
+
+  __builtin_readsteadycounter()
+
+**Example of Use**:
+
+.. code-block:: c++
+
+  unsigned long long t0 = __builtin_readsteadycounter();
+  do_something();
+  unsigned long long t1 = __builtin_readsteadycounter();
+  unsigned long long secs_to_do_something = (t1 - t0) / tick_rate;
+
+**Description**:
+
+The ``__builtin_readsteadycounter()`` builtin returns the frequency counter 
value.
+When not supported by the target, the return value is always zero. This builtin
+takes no arguments and produces an unsigned long long result. The builtin does 
+not guarantee any particular frequency, only that it is stable. Knowledge of 
the 
+counter's true frequency will need to be provided by the user.
+
+Query for this feature with ``__has_builtin(__builtin_readsteadycounter)``.
+
 ``__builtin_dump_struct``
 -
 
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 402a2f8687386c..6633b544d93d32 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -117,6 +117,9 @@ C23 Feature Support
 Non-comprehensive list of changes in this release
 -
 
+- Added ``__builtin_readsteadycounter`` for reading fixed frequency hardware
+  counters.
+
 New Compiler Flags
 --
 
diff --git a/clang/include/clang/Basic/Builtins.td 

[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-12 Thread Owen Pan via cfe-commits

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

>From 3c3e167711dccfcc0a56c5b465b20c17854451a4 Mon Sep 17 00:00:00 2001
From: rmarker 
Date: Tue, 6 Feb 2024 21:53:20 +1030
Subject: [PATCH 1/2] [clang-format] Rename option AlwaysBreakAfterReturnType.

---
 clang/docs/ClangFormatStyleOptions.rst | 221 +++--
 clang/docs/ReleaseNotes.rst|   2 +
 clang/include/clang/Format/Format.h|   7 +-
 clang/lib/Format/Format.cpp|   5 +-
 clang/unittests/Format/ConfigParseTest.cpp |  17 ++
 5 files changed, 141 insertions(+), 111 deletions(-)

diff --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index 5deeff0db239a8..fdf7bfaeaa4ec7 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -1531,114 +1531,8 @@ the configuration (without a prefix: ``Auto``).
 
 .. _AlwaysBreakAfterReturnType:
 
-**AlwaysBreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 3.8` :ref:`¶ `
-  The function declaration return type breaking style to use.
-
-  Possible values:
-
-  * ``RTBS_None`` (in configuration: ``None``)
-This is **deprecated**. See ``Automatic`` below.
-
-  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
-Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
-Same as ``Automatic`` above, except that there is no break after short
-return types.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int f() { return 1; }
-  int LongName::
-  AnotherLongName();
-
-  * ``RTBS_All`` (in configuration: ``All``)
-Always break after the return type.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevel`` (in configuration: ``TopLevel``)
-Always break after the return types of top-level functions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int
-  f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_AllDefinitions`` (in configuration: ``AllDefinitions``)
-Always break after the return type of function definitions.
-
-.. code-block:: c++
-
-  class A {
-int
-f() {
-  return 0;
-};
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-  * ``RTBS_TopLevelDefinitions`` (in configuration: ``TopLevelDefinitions``)
-Always break after the return type of top-level definitions.
-
-.. code-block:: c++
-
-  class A {
-int f() { return 0; };
-  };
-  int f();
-  int
-  f() {
-return 1;
-  }
-  int
-  LongName::AnotherLongName();
-
-
+**AlwaysBreakAfterReturnType** (``deprecated``) :versionbadge:`clang-format 
3.8` :ref:`¶ `
+  This option is renamed to ``BreakAfterReturnType``.
 
 .. _AlwaysBreakBeforeMultilineStrings:
 
@@ -2219,6 +2113,117 @@ the configuration (without a prefix: ``Auto``).
  @Mock
  DataLoad loader;
 
+.. _BreakAfterReturnType:
+
+**BreakAfterReturnType** (``ReturnTypeBreakingStyle``) 
:versionbadge:`clang-format 19` :ref:`¶ `
+  The function declaration return type breaking style to use.
+
+  Possible values:
+
+  * ``RTBS_None`` (in configuration: ``None``)
+This is **deprecated**. See ``Automatic`` below.
+
+  * ``RTBS_Automatic`` (in configuration: ``Automatic``)
+Break after return type based on ``PenaltyReturnTypeOnItsOwnLine``.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int
+  LongName::AnotherLongName();
+
+  * ``RTBS_ExceptShortType`` (in configuration: ``ExceptShortType``)
+Same as ``Automatic`` above, except that there is no break after short
+return types.
+
+.. code-block:: c++
+
+  class A {
+int f() { return 0; };
+  };
+  int f();
+  int f() { return 1; }
+  int LongName::
+  AnotherLongName();
+
+  * ``RTBS_All`` (in configuration: ``All``)
+Always break after the return type.
+
+.. code-block:: c++
+
+  class A {
+int
+f() {
+  return 0;
+};
+  };
+  int
+  f();
+  int
+  f() {
+return 1;
+  }
+  int
+  LongName::AnotherLongName();
+
+  * ``RTBS_TopLevel`` (in configuration: ``TopLevel``)
+Always break 

[clang] [llvm] [LLVM] Add `__builtin_readsteadycounter` intrinsic and builtin for realtime clocks (PR #81331)

2024-02-12 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

Add to release notes?

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


[clang] [clang-format] Don't remove parentheses in macro definitions (PR #81444)

2024-02-12 Thread Owen Pan via cfe-commits

owenca wrote:

> Any hope that this lands in 18.1? Thanks anyway!

Most likely.

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


[clang] [clang-format] Don't remove parentheses in macro definitions (PR #81444)

2024-02-12 Thread via cfe-commits

llvmbot wrote:

/pull-request llvm/llvm-project#81566

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


[clang] Add option to generate additional debug info for expression dereferencing pointer to pointers. (PR #81545)

2024-02-12 Thread Snehasish Kumar via cfe-commits

snehasish wrote:

Any measurements of impact to compile time, memory etc on a reasonable size 
benchmark (e.g. clang)?

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


[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)

2024-02-12 Thread John McCall via cfe-commits

rjmccall wrote:

> Alright. I think the LTO should be done as a follow-up PR since it will 
> likely take some time and multiple reviews to get right.

Yes, that's a fine plan.  I expect that that'll be a significant amount of work.

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


[clang] [ObjC] Check entire chain of superclasses to see if class layout can be statically known (PR #81335)

2024-02-12 Thread John McCall via cfe-commits

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

> @rjmccall Are these tests adequate?

No.  You need to test the behavior of ivar accesses in the subclass when there 
is an intermediate superclass that has ivars declared in all the ways I 
identified.  Your test has many tests for ivar accesses in immediate subclasses 
of `NSObject`, which is an optimization that we've already been doing for 
several years.  It only tests indirect subclasses in one configuration, which 
is when the intermediate superclass has all its ivars declared in the 
`@interface`.

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


[clang] [clang-format] Don't remove parentheses in macro definitions (PR #81444)

2024-02-12 Thread Owen Pan via cfe-commits

owenca wrote:

/cherry-pick 4af24d4ab765

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


[clang] [clang-format] Don't remove parentheses in macro definitions (PR #81444)

2024-02-12 Thread Owen Pan via cfe-commits

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


[clang] [clang-format] Don't remove parentheses in macro definitions (PR #81444)

2024-02-12 Thread Owen Pan via cfe-commits

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


[clang] 4af24d4 - [clang-format] Don't remove parentheses in macro definitions (#81444)

2024-02-12 Thread via cfe-commits

Author: Owen Pan
Date: 2024-02-12T19:20:26-08:00
New Revision: 4af24d4ab76539706bfbceec4b3923426fb1b9e7

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

LOG: [clang-format] Don't remove parentheses in macro definitions (#81444)

Closes #81399.

Added: 


Modified: 
clang/lib/Format/UnwrappedLineParser.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index d84914c6a4cf1c..8f6453a25d9d41 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2518,7 +2518,7 @@ bool UnwrappedLineParser::parseParens(TokenType 
AmpAmpTokenType) {
 parseChildBlock();
   break;
 case tok::r_paren:
-  if (!MightBeStmtExpr &&
+  if (!MightBeStmtExpr && !Line->InMacroBody &&
   Style.RemoveParentheses > FormatStyle::RPS_Leave) {
 const auto *Prev = LeftParen->Previous;
 const auto *Next = Tokens->peekNextToken();

diff  --git a/clang/unittests/Format/FormatTest.cpp 
b/clang/unittests/Format/FormatTest.cpp
index 7b65c8d6e21b00..13937a15fdaee2 100644
--- a/clang/unittests/Format/FormatTest.cpp
+++ b/clang/unittests/Format/FormatTest.cpp
@@ -26972,6 +26972,7 @@ TEST_F(FormatTest, RemoveParentheses) {
   EXPECT_EQ(Style.RemoveParentheses, FormatStyle::RPS_Leave);
 
   Style.RemoveParentheses = FormatStyle::RPS_MultipleParentheses;
+  verifyFormat("#define Foo(...) foo((__VA_ARGS__))", Style);
   verifyFormat("int x __attribute__((aligned(16))) = 0;", Style);
   verifyFormat("decltype((foo->bar)) baz;", Style);
   verifyFormat("class __declspec(dllimport) X {};",
@@ -27006,6 +27007,7 @@ TEST_F(FormatTest, RemoveParentheses) {
   verifyFormat("return (({ 0; }));", "return ((({ 0; })));", Style);
 
   Style.RemoveParentheses = FormatStyle::RPS_ReturnStatement;
+  verifyFormat("#define Return0 return (0);", Style);
   verifyFormat("return 0;", "return (0);", Style);
   verifyFormat("co_return 0;", "co_return ((0));", Style);
   verifyFormat("return 0;", "return (((0)));", Style);



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


[clang] [clang-format] Rename option AlwaysBreakAfterReturnType. (PR #80827)

2024-02-12 Thread Owen Pan via cfe-commits


@@ -677,6 +677,23 @@ TEST(ConfigParseTest, ParsesConfiguration) {
   "  AfterControlStatement: false",
   BraceWrapping.AfterControlStatement, FormatStyle::BWACS_Never);
 
+  Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;
+  CHECK_PARSE("BreakAfterReturnType: None", AlwaysBreakAfterReturnType,
+  FormatStyle::RTBS_None);
+  CHECK_PARSE("BreakAfterReturnType: Automatic", AlwaysBreakAfterReturnType,
+  FormatStyle::RTBS_Automatic);
+  CHECK_PARSE("BreakAfterReturnType: ExceptShortType",
+  AlwaysBreakAfterReturnType, FormatStyle::RTBS_ExceptShortType);
+  CHECK_PARSE("BreakAfterReturnType: All", AlwaysBreakAfterReturnType,
+  FormatStyle::RTBS_All);
+  CHECK_PARSE("BreakAfterReturnType: TopLevel", AlwaysBreakAfterReturnType,
+  FormatStyle::RTBS_TopLevel);
+  CHECK_PARSE("BreakAfterReturnType: AllDefinitions",
+  AlwaysBreakAfterReturnType, FormatStyle::RTBS_AllDefinitions);
+  CHECK_PARSE("BreakAfterReturnType: TopLevelDefinitions",
+  AlwaysBreakAfterReturnType,
+  FormatStyle::RTBS_TopLevelDefinitions);
+  // For backward compatibility:
   Style.AlwaysBreakAfterReturnType = FormatStyle::RTBS_All;

owenca wrote:

Redundant.

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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From 73cc9fde36a44ba1715a3c9fc6d48196602d5dc4 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH] [HLSL] Implementation of dot intrinsic This change implements
 #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in BuiltinsHLSL.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

As a side note adding the dot product intrinsic to BuiltinsHLSL.td had a
significant impact on re-compile time speeds. I recommend we move the
other hlsl functions here. Further it lets us tap into the existing
target specifc code organizations that exist in Sema and CodeGen.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is a target specific intrinsic and so needed to establish
a pattern for Target builtins via EmitDXILBuiltinExpr.
The call chain looks like this now: EmitBuiltinExpr -> EmitTargetBuiltinExpr -> 
EmitTargetArchBuiltinExpr -> EmitDXILBuiltinExp

EmitDXILBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
target specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/BuiltinsHLSL.td|  15 ++
 clang/include/clang/Basic/CMakeLists.txt |   6 +-
 clang/include/clang/Basic/TargetBuiltins.h   |  10 +
 clang/include/clang/Sema/Sema.h  |   1 +
 clang/lib/Basic/Targets/DirectX.cpp  |  13 ++
 clang/lib/Basic/Targets/DirectX.h|   4 +-
 clang/lib/CodeGen/CGBuiltin.cpp  |  41 
 clang/lib/CodeGen/CodeGenFunction.h  |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h |  68 +++
 clang/lib/Sema/SemaChecking.cpp  |  71 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl | 202 +++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl |  43 
 llvm/include/llvm/IR/IntrinsicsDirectX.td|   5 +
 13 files changed, 471 insertions(+), 9 deletions(-)
 create mode 100644 clang/include/clang/Basic/BuiltinsHLSL.td
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/BuiltinsHLSL.td 
b/clang/include/clang/Basic/BuiltinsHLSL.td
new file mode 100644
index 00..edff801f905641
--- /dev/null
+++ b/clang/include/clang/Basic/BuiltinsHLSL.td
@@ -0,0 +1,15 @@
+//===--- BuiltinsHLSL.td - HLSL Builtin function database -*- 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 "clang/Basic/BuiltinsBase.td"
+
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 7785fb430c069b..01233eb44feffc 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -65,7 +65,11 @@ clang_tablegen(BuiltinsBPF.inc -gen-clang-builtins
   SOURCE BuiltinsBPF.td
   TARGET ClangBuiltinsBPF)
 
-clang_tablegen(BuiltinsRISCV.inc -gen-clang-builtins
+clang_tablegen(BuiltinsHLSL.inc -gen-clang-builtins
+  SOURCE BuiltinsHLSL.td
+  TARGET ClangBuiltinsHLSL)
+
+  clang_tablegen(BuiltinsRISCV.inc -gen-clang-builtins
   SOURCE BuiltinsRISCV.td
   TARGET ClangBuiltinsRISCV)
 
diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index 4333830bf34f24..15cf111ae5e9e5 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -89,6 +89,16 @@ namespace clang {
   };
   }
 
+  /// HLSL builtins
+  namespace hlsl {
+  enum {
+LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/BuiltinsHLSL.inc"
+LastTSBuiltin
+  };
+  } // namespace hlsl
+
   /// PPC 

[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From 4103940b5a2578efc08df554ccdf80cb34925d09 Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH] [HLSL] Implementation of dot intrinsic This change implements
 #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in BuiltinsHLSL.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

As a side note adding the dot product intrinsic to BuiltinsHLSL.td had a
significant impact on re-compile time speeds. I recommend we move the
other hlsl functions here. Further it lets us tap into the existing
target specifc code organizations that exist in Sema and CodeGen.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is a target specific intrinsic and so needed to establish
a pattern for Target builtins via EmitDXILBuiltinExpr.
The call chain looks like this now: EmitBuiltinExpr -> EmitTargetBuiltinExpr -> 
EmitTargetArchBuiltinExpr -> EmitDXILBuiltinExp

EmitDXILBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
target specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/BuiltinsHLSL.td|  15 ++
 clang/include/clang/Basic/CMakeLists.txt |   4 +
 clang/include/clang/Basic/TargetBuiltins.h   |  10 +
 clang/include/clang/Sema/Sema.h  |   1 +
 clang/lib/Basic/Targets/DirectX.cpp  |  13 ++
 clang/lib/Basic/Targets/DirectX.h|   4 +-
 clang/lib/CodeGen/CGBuiltin.cpp  |  41 
 clang/lib/CodeGen/CodeGenFunction.h  |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h |  68 +++
 clang/lib/Sema/SemaChecking.cpp  |  71 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl | 202 +++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl |  43 
 llvm/include/llvm/IR/IntrinsicsDirectX.td|   5 +
 13 files changed, 470 insertions(+), 8 deletions(-)
 create mode 100644 clang/include/clang/Basic/BuiltinsHLSL.td
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/BuiltinsHLSL.td 
b/clang/include/clang/Basic/BuiltinsHLSL.td
new file mode 100644
index 00..edff801f905641
--- /dev/null
+++ b/clang/include/clang/Basic/BuiltinsHLSL.td
@@ -0,0 +1,15 @@
+//===--- BuiltinsHLSL.td - HLSL Builtin function database -*- 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 "clang/Basic/BuiltinsBase.td"
+
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 9689a0f48c3ca3..29e5211602a9c8 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -65,6 +65,10 @@ clang_tablegen(BuiltinsBPF.inc -gen-clang-builtins
   SOURCE BuiltinsBPF.td
   TARGET ClangBuiltinsBPF)
 
+  clang_tablegen(BuiltinsHLSL.inc -gen-clang-builtins
+  SOURCE BuiltinsHLSL.td
+  TARGET ClangBuiltinsHLSL)
+
 # ARM NEON and MVE
 clang_tablegen(arm_neon.inc -gen-arm-neon-sema
   SOURCE arm_neon.td
diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index a4abaaef44c06c..38452553bd2df2 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -89,6 +89,16 @@ namespace clang {
   };
   }
 
+  /// HLSL builtins
+  namespace hlsl {
+  enum {
+LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/BuiltinsHLSL.inc"
+LastTSBuiltin
+  };
+  } // namespace hlsl
+
   /// PPC builtins
   namespace PPC {
 enum {
diff --git 

[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits


@@ -144,6 +144,92 @@ double3 cos(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_cos)
 double4 cos(double4);
 
+//===--===//
+// dot product builtins
+//===--===//
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half, half);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half2, half2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half3, half3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half4, half4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t, int16_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t2, int16_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t3, int16_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t4, int16_t4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t, uint16_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t2, uint16_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t3, uint16_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t4, uint16_t4);
+#endif
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float, float);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float2, float2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float3, float3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float4, float4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+double dot(double, double);

farzonl wrote:

mentioned in another conversation. only the scalar case of double remains. 

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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits


@@ -19,4 +19,9 @@ def int_dx_flattened_thread_id_in_group : 
Intrinsic<[llvm_i32_ty], [], [IntrNoMe
 
 def int_dx_create_handle : ClangBuiltin<"__builtin_hlsl_create_handle">,
 Intrinsic<[ llvm_ptr_ty ], [llvm_i8_ty], [IntrWillReturn]>;
-}
+
+def int_dx_dot : 
+Intrinsic<[LLVMVectorElementType<0>], 
+[llvm_anyvector_ty, LLVMScalarOrSameVectorWidth<0, 
LLVMVectorElementType<0>>],

farzonl wrote:

@python3kgae  Are you ok with leaving this as is?

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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits

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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits


@@ -19,4 +19,9 @@ def int_dx_flattened_thread_id_in_group : 
Intrinsic<[llvm_i32_ty], [], [IntrNoMe
 
 def int_dx_create_handle : ClangBuiltin<"__builtin_hlsl_create_handle">,
 Intrinsic<[ llvm_ptr_ty ], [llvm_i8_ty], [IntrWillReturn]>;
-}
+
+def int_dx_dot : 
+Intrinsic<[LLVMVectorElementType<0>], 
+[llvm_anyvector_ty, LLVMScalarOrSameVectorWidth<0, 
LLVMVectorElementType<0>>],
+[IntrNoMem, IntrWillReturn, Commutative] >;

farzonl wrote:

This might have to come later when I start to work  on lowering.

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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits


@@ -144,6 +144,92 @@ double3 cos(double3);
 _HLSL_BUILTIN_ALIAS(__builtin_elementwise_cos)
 double4 cos(double4);
 
+//===--===//
+// dot product builtins
+//===--===//
+#ifdef __HLSL_ENABLE_16_BIT
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half, half);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half2, half2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half3, half3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+half dot(half4, half4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t, int16_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t2, int16_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t3, int16_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int16_t dot(int16_t4, int16_t4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t, uint16_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t2, uint16_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t3, uint16_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint16_t dot(uint16_t4, uint16_t4);
+#endif
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float, float);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float2, float2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float3, float3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+float dot(float4, float4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+double dot(double, double);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+double dot(double2, double2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+double dot(double3, double3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+double dot(double4, double4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int dot(int, int);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int dot(int2, int2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int dot(int3, int3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int dot(int4, int4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint dot(uint, uint);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint dot(uint2, uint2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint dot(uint3, uint3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint dot(uint4, uint4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int64_t dot(int64_t, int64_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int64_t dot(int64_t2, int64_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int64_t dot(int64_t3, int64_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+int64_t dot(int64_t4, int64_t4);
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint64_t dot(uint64_t, uint64_t);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint64_t dot(uint64_t2, uint64_t2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint64_t dot(uint64_t3, uint64_t3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_dot)
+uint64_t dot(uint64_t4, uint64_t4);

farzonl wrote:

1. I removed the  `int64` and `uint64`  support and tests, but it does seem 
like it is supported see `fn6` and `fn7`. Left the scalar support for both.
2. You are correct no double vector support so removed it. However scalar 
double is supported see `fn8`. Left this one.

https://godbolt.org/z/vT9xTMffE


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


[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits


@@ -4518,6 +4518,12 @@ def HLSLCreateHandle : LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void*(unsigned char)";
 }
 
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];

farzonl wrote:

I have added SemaChecking 
However I have 4 cases I can't check via `SemaChecking.cpp` Because
`BuildRecoveryCallExpr` is usurping calls to `BuildResolvedCallExpr`. 
This seems to be caused by how we are defining apis via `hlsl_intrinsics.h` and 
it doesn't seem to matter if I added Types to the table gen or not like so
```python
class HLSLMathTemplate : Template<["__fp16", "float", "double", "short", "int", 
"int64_t", "unsigned short", "uint32_t", "uint64_t" ],
  ["f16","",  "f64","i16",   "i32", 
"i64", "u16","u32",  "u64"]>;

def HLSLDotProduct : LangBuiltin<"HLSL_LANG">, HLSLMathTemplate {
  let Spellings = ["__builtin_hlsl_dot"];
  let Attributes = [NoThrow, Const, CustomTypeChecking];
  let Prototype = "T(_Complex T , _Complex T )";
}
```
Example test cases that hit `BuildRecoveryCallExpr`:
```hlsl
float test_dot_scalar_mismatch ( float p0, int p1 ) {
  return dot ( p0, p1 );
}

float test_dot_vector_size_mismatch ( float3 p0, float2 p1 ) {
  return dot ( p0, p1 );
}

float test__no_second_arg ( float2 p0) {
  return dot ( p0 );
}

float test_dot_element_type_mismatch ( int2 p0, float2 p1 ) {
  return dot ( p0, p1 );
}
```

For example If we take `sin`:

```hlsl
// RUN: %clang_cc1 -std=hlsl2021 -finclude-default-header -x hlsl -triple \
// RUN:   dxil-pc-shadermodel6.3-library %s -fnative-half-type \
// RUN:   -emit-llvm -disable-llvm-passes  -o -

float4 test( int4 p0) {
  return sin ( p0 );
}
```
I get the same errors:

```
clang\test\CodeGenHLSL\builtins\dot2.hlsl:6:10: error: no matching function for 
call to 'sin'
6 |   return sin ( p0 );
  |  ^~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:611:6:
 note: candidate function not viable: no known conversion from 'int4' (aka 
'vector') to 'half' for 1st argument
  611 | half sin(half);
  |  ^   
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:613:7:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  613 | half2 sin(half2);
  |   ^   ~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:615:7:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  615 | half3 sin(half3);
  |   ^   ~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:617:7:
 note: candidate function not viable: no known conversion from 'vector' to 'vector' for 1st argument
  617 | half4 sin(half4);
  |   ^   ~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:621:7:
 note: candidate function not viable: no known conversion from 'int4' (aka 
'vector') to 'float' for 1st argument
  621 | float sin(float);
  |   ^   ~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:623:8:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  623 | float2 sin(float2);
  |^   ~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:625:8:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  625 | float3 sin(float3);
  |^   ~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:627:8:
 note: candidate function not viable: no known conversion from 'vector' to 'vector' for 1st argument
  627 | float4 sin(float4);
  |^   ~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:630:8:
 note: candidate function not viable: no known conversion from 'int4' (aka 
'vector') to 'double' for 1st argument
  630 | double sin(double);
  |^   ~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:632:9:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  632 | double2 sin(double2);
  | ^   ~~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:634:9:
 note: candidate function not viable: no known conversion from 'vector' 
to 'vector' for 1st argument
  634 | double3 sin(double3);
  | ^   ~~~
D:\projects\llvm_win_clang-cl_debug_build\lib\clang\19\include\hlsl/hlsl_intrinsics.h:636:9:
 note: candidate function not viable: no known conversion from 'vector' to 'vector' for 1st argument
  636 | double4 sin(double4);
  | ^   ~~~
1 

[clang] [llvm] [HLSL] Implementation of dot intrinsic (PR #81190)

2024-02-12 Thread Farzon Lotfi via cfe-commits

https://github.com/farzonl updated 
https://github.com/llvm/llvm-project/pull/81190

>From 5082bc7fb49761424c7984a594a5afad9a03f04d Mon Sep 17 00:00:00 2001
From: Farzon Lotfi 
Date: Thu, 8 Feb 2024 11:08:59 -0500
Subject: [PATCH] [HLSL] Implementation of dot intrinsic This change implements
 #70073

HLSL has a dot intrinsic defined here:
https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-dot

The intrinsic itself is defined as a HLSL_LANG LangBuiltin in BuiltinsHLSL.td.
This is used to associate all the dot product typdef defined hlsl_intrinsics.h
with a single intrinsic check in CGBuiltin.cpp & SemaChecking.cpp.

As a side note adding the dot product intrinsic to BuiltinsHLSL.td had a
significant impact on re-compile time speeds. I recommend we move the
other hlsl functions here. Further it lets us tap into the existing
target specifc code organizations that exist in Sema and CodeGen.

In IntrinsicsDirectX.td we define the llvmIR for the dot product.
A few goals were in mind for this IR. First it should operate on only
vectors. Second the return type should be the vector element type. Third
the second parameter vector should be of the same size as the first
parameter. Finally `a dot b` should be the same as `b dot a`.

In CGBuiltin.cpp hlsl has built on top of existing clang intrinsics via 
EmitBuiltinExpr. Dot
product though is a target specific intrinsic and so needed to establish
a pattern for Target builtins via EmitDXILBuiltinExpr.
The call chain looks like this now: EmitBuiltinExpr -> EmitTargetBuiltinExpr -> 
EmitTargetArchBuiltinExpr -> EmitDXILBuiltinExp

EmitDXILBuiltinExp dot product intrinsics makes a destinction
between vectors and scalars. This is because HLSL supports dot product on 
scalars which simplifies down to multiply.

Sema.h & SemaChecking.cpp saw the addition of CheckHLSLBuiltinFunctionCall, a 
target specific semantic validation that can be expanded for other hlsl 
specific intrinsics.
---
 clang/include/clang/Basic/BuiltinsHLSL.td|  15 ++
 clang/include/clang/Basic/CMakeLists.txt |   4 +
 clang/include/clang/Basic/TargetBuiltins.h   |  10 +
 clang/include/clang/Sema/Sema.h  |   1 +
 clang/lib/Basic/Targets/DirectX.cpp  |  13 ++
 clang/lib/Basic/Targets/DirectX.h|   4 +-
 clang/lib/CodeGen/CGBuiltin.cpp  |  41 
 clang/lib/CodeGen/CodeGenFunction.h  |   1 +
 clang/lib/Headers/hlsl/hlsl_intrinsics.h |  68 +++
 clang/lib/Sema/SemaChecking.cpp  |  74 ++-
 clang/test/CodeGenHLSL/builtins/dot.hlsl | 202 +++
 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl |  43 
 llvm/include/llvm/IR/IntrinsicsDirectX.td|   5 +
 13 files changed, 473 insertions(+), 8 deletions(-)
 create mode 100644 clang/include/clang/Basic/BuiltinsHLSL.td
 create mode 100644 clang/test/CodeGenHLSL/builtins/dot.hlsl
 create mode 100644 clang/test/SemaHLSL/BuiltIns/dot-errors.hlsl

diff --git a/clang/include/clang/Basic/BuiltinsHLSL.td 
b/clang/include/clang/Basic/BuiltinsHLSL.td
new file mode 100644
index 00..edff801f905641
--- /dev/null
+++ b/clang/include/clang/Basic/BuiltinsHLSL.td
@@ -0,0 +1,15 @@
+//===--- BuiltinsHLSL.td - HLSL Builtin function database -*- 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 "clang/Basic/BuiltinsBase.td"
+
+def HLSLDotProduct : LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_dot"];
+  let Attributes = [NoThrow, Const, CustomTypeChecking];
+  let Prototype = "void(...)";
+}
diff --git a/clang/include/clang/Basic/CMakeLists.txt 
b/clang/include/clang/Basic/CMakeLists.txt
index 9689a0f48c3ca3..29e5211602a9c8 100644
--- a/clang/include/clang/Basic/CMakeLists.txt
+++ b/clang/include/clang/Basic/CMakeLists.txt
@@ -65,6 +65,10 @@ clang_tablegen(BuiltinsBPF.inc -gen-clang-builtins
   SOURCE BuiltinsBPF.td
   TARGET ClangBuiltinsBPF)
 
+  clang_tablegen(BuiltinsHLSL.inc -gen-clang-builtins
+  SOURCE BuiltinsHLSL.td
+  TARGET ClangBuiltinsHLSL)
+
 # ARM NEON and MVE
 clang_tablegen(arm_neon.inc -gen-arm-neon-sema
   SOURCE arm_neon.td
diff --git a/clang/include/clang/Basic/TargetBuiltins.h 
b/clang/include/clang/Basic/TargetBuiltins.h
index a4abaaef44c06c..38452553bd2df2 100644
--- a/clang/include/clang/Basic/TargetBuiltins.h
+++ b/clang/include/clang/Basic/TargetBuiltins.h
@@ -89,6 +89,16 @@ namespace clang {
   };
   }
 
+  /// HLSL builtins
+  namespace hlsl {
+  enum {
+LastTIBuiltin = clang::Builtin::FirstTSBuiltin - 1,
+#define BUILTIN(ID, TYPE, ATTRS) BI##ID,
+#include "clang/Basic/BuiltinsHLSL.inc"
+LastTSBuiltin
+  };
+  } // namespace hlsl
+
   /// PPC builtins
   namespace PPC {
 enum {
diff --git 

[clang] [Clang][Sema] fix crash in codegen stage when an lambda expression declared in an unevaluated context (PR #80802)

2024-02-12 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/80802

>From 2f09be514adff0c5e19494b14fbe4cc9588fea9c Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Tue, 6 Feb 2024 14:06:40 +0800
Subject: [PATCH] [Clang][Sema] fix crash in codegen stage when an lambda
 expression declared in an unevaluated context

---
 clang/docs/ReleaseNotes.rst|  2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp | 18 --
 clang/test/CodeGen/PR76674.cpp | 11 +++
 3 files changed, 25 insertions(+), 6 deletions(-)
 create mode 100644 clang/test/CodeGen/PR76674.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index ece6013f672621..d809d7eec4d550 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -225,6 +225,8 @@ Bug Fixes to C++ Support
   or non-constant more accurately. Previously, only a subset of the initializer
   elements were considered, misclassifying some initializers as constant. Fixes
   some of (`#80510 `).
+- Fix a crash in codegen when lambdas declared in an unevaluated context.
+  Fixes (`#76674 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 6d59180bc446d2..f80664e0e29a47 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1614,7 +1614,18 @@ bool TemplateInstantiator::AlreadyTransformed(QualType 
T) {
   if (T.isNull())
 return true;
 
-  if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
+  bool DependentLambdaType = false;
+  CXXRecordDecl *RD = T->getAsCXXRecordDecl();
+  if (RD && RD->isLambda()) {
+QualType LambdaCallType = RD->getLambdaCallOperator()->getType();
+if (LambdaCallType->isInstantiationDependentType() ||
+LambdaCallType->isVariablyModifiedType()) {
+  DependentLambdaType = true;
+}
+  }
+
+  if (T->isInstantiationDependentType() || T->isVariablyModifiedType() ||
+  DependentLambdaType)
 return false;
 
   getSema().MarkDeclarationsReferencedInType(Loc, T);
@@ -2683,11 +2694,6 @@ QualType Sema::SubstType(QualType T,
  "Cannot perform an instantiation without some context on the "
  "instantiation stack");
 
-  // If T is not a dependent type or a variably-modified type, there
-  // is nothing to do.
-  if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
-return T;
-
   TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
   return Instantiator.TransformType(T);
 }
diff --git a/clang/test/CodeGen/PR76674.cpp b/clang/test/CodeGen/PR76674.cpp
new file mode 100644
index 00..2ce931920afe4f
--- /dev/null
+++ b/clang/test/CodeGen/PR76674.cpp
@@ -0,0 +1,11 @@
+// RUN: %clang_cc1 -std=c++20 -emit-llvm -o - %s
+// expected-no-diagnostics
+
+template 
+struct A {
+template 
+using Func = decltype([] {return U{};});
+};
+
+A::Func f{};
+int i{f()};

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


[clang] [compiler-rt] [Sanitizer] add signed-integer-wrap sanitizer (PR #80089)

2024-02-12 Thread Kees Cook via cfe-commits

kees wrote:

I've tested this with the Linux kernel, and it is working as expected. It is 
ready and waiting for this option to gain back a bunch of sanitizer coverage 
for CIs and likely in production kernels. :)

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


[clang-tools-extra] [clang-tidy] ignore local variable with [maybe_unused] attribute in bugprone-unused-local-non-trivial-variable (PR #81563)

2024-02-12 Thread via cfe-commits

llvmbot wrote:




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

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #81419.

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


4 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
(+1) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+4) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 (+1) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
 (+1) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
index 1b763d291082b6..37baae7a6f0c3a 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -60,6 +60,7 @@ void 
UnusedLocalNonTrivialVariableCheck::registerMatchers(MatchFinder *Finder) {
   varDecl(isLocalVarDecl(), unless(isReferenced()),
   unless(isExceptionVariable()), hasLocalStorage(), isDefinition(),
   unless(hasType(isReferenceType())), unless(hasType(isTrivial())),
+  unless(hasAttr(attr::Kind::Unused)),
   hasType(hasUnqualifiedDesugaredType(
   anyOf(recordType(hasDeclaration(namedDecl(
 matchesAnyListedName(IncludeTypes),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ee68c8f49b3df2..f2fba9aa1450d6 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -121,6 +121,10 @@ Changes in existing checks
   ` check by incorporating
   better support for ``const`` loop boundaries.
 
+- Improved :doc:`bugprone-unused-local-non-trivial-variable
+  ` check by
+  ignoring local variable with ``[maybe_unused]`` attribute.
+
 - Cleaned up :doc:`cppcoreguidelines-prefer-member-initializer
   `
   by removing enforcement of rule `C.48
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
index 7531f19f3ebc15..9f283de78fbdec 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
@@ -11,6 +11,7 @@ The following types of variables are excluded from this check:
 * exception variables in catch clauses
 * static or thread local
 * structured bindings
+* variables with ``[[maybe_unused]]`` attribute
 
 This check can be configured to warn on all non-trivial variables by setting
 `IncludeTypes` to `.*`, and excluding specific types using `ExcludeTypes`.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
index 19f2344de4a650..3fdc24b94a6cb2 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
@@ -77,6 +77,7 @@ T qux(T Generic) {
 // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: unused local variable 
'TemplateType' of type 'async::Future' 
[bugprone-unused-local-non-trivial-variable]
 a::Future AliasTemplateType;
 // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unused local variable 
'AliasTemplateType' of type 'a::Future' (aka 'Future') 
[bugprone-unused-local-non-trivial-variable]
+[[maybe_unused]] async::Future MaybeUnused;
 return Generic;
 }
 

``




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


[clang-tools-extra] [clang-tidy] ignore local variable with [maybe_unused] attribute in bugprone-unused-local-non-trivial-variable (PR #81563)

2024-02-12 Thread Congcong Cai via cfe-commits

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

Fixes: #81419.

>From fefe52614837d14858d056783dca8b08745de9d4 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Tue, 13 Feb 2024 09:47:52 +0800
Subject: [PATCH] [clang-tidy] ignore local variable with [maybe_unused]
 attribute in bugprone-unused-local-non-trivial-variable

Fixes: #81419.
---
 .../bugprone/UnusedLocalNonTrivialVariableCheck.cpp   | 1 +
 clang-tools-extra/docs/ReleaseNotes.rst   | 4 
 .../checks/bugprone/unused-local-non-trivial-variable.rst | 1 +
 .../checkers/bugprone/unused-local-non-trivial-variable.cpp   | 1 +
 4 files changed, 7 insertions(+)

diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
index 1b763d291082b6..37baae7a6f0c3a 100644
--- 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -60,6 +60,7 @@ void 
UnusedLocalNonTrivialVariableCheck::registerMatchers(MatchFinder *Finder) {
   varDecl(isLocalVarDecl(), unless(isReferenced()),
   unless(isExceptionVariable()), hasLocalStorage(), isDefinition(),
   unless(hasType(isReferenceType())), unless(hasType(isTrivial())),
+  unless(hasAttr(attr::Kind::Unused)),
   hasType(hasUnqualifiedDesugaredType(
   anyOf(recordType(hasDeclaration(namedDecl(
 matchesAnyListedName(IncludeTypes),
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ee68c8f49b3df2..f2fba9aa1450d6 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -121,6 +121,10 @@ Changes in existing checks
   ` check by incorporating
   better support for ``const`` loop boundaries.
 
+- Improved :doc:`bugprone-unused-local-non-trivial-variable
+  ` check by
+  ignoring local variable with ``[maybe_unused]`` attribute.
+
 - Cleaned up :doc:`cppcoreguidelines-prefer-member-initializer
   `
   by removing enforcement of rule `C.48
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
index 7531f19f3ebc15..9f283de78fbdec 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
@@ -11,6 +11,7 @@ The following types of variables are excluded from this check:
 * exception variables in catch clauses
 * static or thread local
 * structured bindings
+* variables with ``[[maybe_unused]]`` attribute
 
 This check can be configured to warn on all non-trivial variables by setting
 `IncludeTypes` to `.*`, and excluding specific types using `ExcludeTypes`.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
index 19f2344de4a650..3fdc24b94a6cb2 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp
@@ -77,6 +77,7 @@ T qux(T Generic) {
 // CHECK-MESSAGES: :[[@LINE-1]]:22: warning: unused local variable 
'TemplateType' of type 'async::Future' 
[bugprone-unused-local-non-trivial-variable]
 a::Future AliasTemplateType;
 // CHECK-MESSAGES: :[[@LINE-1]]:18: warning: unused local variable 
'AliasTemplateType' of type 'a::Future' (aka 'Future') 
[bugprone-unused-local-non-trivial-variable]
+[[maybe_unused]] async::Future MaybeUnused;
 return Generic;
 }
 

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


[clang] [-Wunsafe-buffer-usage] Add fixits for array to pointer assignment (PR #81343)

2024-02-12 Thread via cfe-commits

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


[clang] [-Wunsafe-buffer-usage] Fixits for array decayed to pointer (PR #80347)

2024-02-12 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-analysis

@llvm/pr-subscribers-clang

Author: None (jkorous-apple)


Changes

depends on 
https://github.com/llvm/llvm-project/pull/80084

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


2 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+1-1) 
- (modified) 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp (+49-1) 


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 3c2a6fd81b1d8f..d00c598c4b9de3 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1876,6 +1876,7 @@ std::optional
 UPCStandalonePointerGadget::getFixits(const FixitStrategy ) const {
   const auto VD = cast(Node->getDecl());
   switch (S.lookup(VD)) {
+  case FixitStrategy::Kind::Array:
   case FixitStrategy::Kind::Span: {
 ASTContext  = VD->getASTContext();
 SourceManager  = Ctx.getSourceManager();
@@ -1890,7 +1891,6 @@ UPCStandalonePointerGadget::getFixits(const FixitStrategy 
) const {
   }
   case FixitStrategy::Kind::Wontfix:
   case FixitStrategy::Kind::Iterator:
-  case FixitStrategy::Kind::Array:
 return std::nullopt;
   case FixitStrategy::Kind::Vector:
 llvm_unreachable("unsupported strategies for FixableGadgets");
diff --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
index ca19702c7ec300..f94072015ff87d 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
@@ -83,12 +83,27 @@ void unsafe_method_invocation_single_param() {
 
 }
 
+void unsafe_method_invocation_single_param_array() {
+  int p[32];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p"
+
+  int tmp = p[5];
+  foo(p);
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:8-[[@LINE-1]]:8}:".data()"
+}
+
 void safe_method_invocation_single_param() {
   int* p = new int[10];
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}-[[@LINE-1]]:{{.*}}}
   foo(p);
 }
 
+void safe_method_invocation_single_param_array() {
+  int p[10];
+  foo(p);
+  // CHECK-NO: 
fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}-[[@LINE-1]]:{{.*}}}:".data()"
+}
+
 void unsafe_method_invocation_double_param() {
   int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span 
p"
@@ -111,6 +126,20 @@ void unsafe_method_invocation_double_param() {
   m1(q, q, 8);
 }
 
+void unsafe_method_invocation_double_param_array() {
+  int p[14];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p"
+
+  int q[40];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array q"
+
+  q[5] = p[5];
+
+  m1(p, p, 10);
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:7}:".data()"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:10-[[@LINE-2]]:10}:".data()"
+}
+
 void unsafe_access_in_lamda() {
   int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span 
p"
@@ -177,4 +206,23 @@ void fixits_in_lambda_capture_rename() {
   };
 
   p[5] = 10;
-} 
+}
+
+bool ptr_comparison(int* ptr, unsigned idx) {
+  int arr[10];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:14}:"std::array arr"
+  arr[idx] = idx;
+
+  return arr > ptr;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:13}:".data()"
+}
+
+int long long ptr_distance(int* ptr, unsigned idx) {
+  int arr[10];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:14}:"std::array arr"
+  arr[idx] = idx;
+
+  int long long dist = arr - ptr;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:27-[[@LINE-1]]:27}:".data()"
+  return dist;
+}

``




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


[clang] [-Wunsafe-buffer-usage] Fixits for array decayed to pointer (PR #80347)

2024-02-12 Thread via cfe-commits

https://github.com/jkorous-apple updated 
https://github.com/llvm/llvm-project/pull/80347

>From 245ea0a82fdd1b24a5c7175fc90379a86df77fe8 Mon Sep 17 00:00:00 2001
From: Jan Korous 
Date: Wed, 24 Jan 2024 17:35:47 -0800
Subject: [PATCH 1/2] [-Wunsafe-buffer-usage] Emit fixits for array used as a
 pointer

Covers cases where DeclRefExpr referring to a const-size array decays to a
pointer and is used "as a pointer" (e. g. passed to a pointer type
parameter).

Since std::array doesn't implicitly convert to pointer to its element
type T* the cast needs to be done explicitly as part of the fixit
when we retrofit std::array to code that previously worked with constant
size array. std::array::data() method is used for the explicit
cast.

In terms of the fixit machine this covers the UPC(DRE) case for Array fixit 
strategy.
The emitted fixit inserts call to std::array::data() method similarly to
analogous fixit for Span strategy.
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp  |  2 +-
 ...afe-buffer-usage-fixits-pointer-access.cpp | 29 +++
 2 files changed, 30 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 3c2a6fd81b1d8f..d00c598c4b9de3 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -1876,6 +1876,7 @@ std::optional
 UPCStandalonePointerGadget::getFixits(const FixitStrategy ) const {
   const auto VD = cast(Node->getDecl());
   switch (S.lookup(VD)) {
+  case FixitStrategy::Kind::Array:
   case FixitStrategy::Kind::Span: {
 ASTContext  = VD->getASTContext();
 SourceManager  = Ctx.getSourceManager();
@@ -1890,7 +1891,6 @@ UPCStandalonePointerGadget::getFixits(const FixitStrategy 
) const {
   }
   case FixitStrategy::Kind::Wontfix:
   case FixitStrategy::Kind::Iterator:
-  case FixitStrategy::Kind::Array:
 return std::nullopt;
   case FixitStrategy::Kind::Vector:
 llvm_unreachable("unsupported strategies for FixableGadgets");
diff --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
index ca19702c7ec300..f8caff5b1a3ef7 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
@@ -83,12 +83,27 @@ void unsafe_method_invocation_single_param() {
 
 }
 
+void unsafe_method_invocation_single_param_array() {
+  int p[32];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p"
+
+  int tmp = p[5];
+  foo(p);
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:8-[[@LINE-1]]:8}:".data()"
+}
+
 void safe_method_invocation_single_param() {
   int* p = new int[10];
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}-[[@LINE-1]]:{{.*}}}
   foo(p);
 }
 
+void safe_method_invocation_single_param_array() {
+  int p[10];
+  foo(p);
+  // CHECK-NO: 
fix-it:"{{.*}}":{[[@LINE-1]]:{{.*}}-[[@LINE-1]]:{{.*}}}:".data()"
+}
+
 void unsafe_method_invocation_double_param() {
   int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span 
p"
@@ -111,6 +126,20 @@ void unsafe_method_invocation_double_param() {
   m1(q, q, 8);
 }
 
+void unsafe_method_invocation_double_param_array() {
+  int p[14];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array p"
+
+  int q[40];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:12}:"std::array q"
+
+  q[5] = p[5];
+
+  m1(p, p, 10);
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:7}:".data()"
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-2]]:10-[[@LINE-2]]:10}:".data()"
+}
+
 void unsafe_access_in_lamda() {
   int* p = new int[10];
   // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:11}:"std::span 
p"

>From 39a2d21e874756aa914e1461abff93bfda6c8e66 Mon Sep 17 00:00:00 2001
From: Jan Korous 
Date: Tue, 6 Feb 2024 14:51:17 -0800
Subject: [PATCH 2/2] [-Wunsafe-buffer-usage][NFC] Test more fixits of array
 decayed to pointer

---
 ...afe-buffer-usage-fixits-pointer-access.cpp | 21 ++-
 1 file changed, 20 insertions(+), 1 deletion(-)

diff --git 
a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
index f8caff5b1a3ef7..f94072015ff87d 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-pointer-access.cpp
@@ -206,4 +206,23 @@ void fixits_in_lambda_capture_rename() {
   };
 
   p[5] = 10;
-} 
+}
+
+bool ptr_comparison(int* ptr, unsigned idx) {
+  int arr[10];
+  // CHECK-DAG: 
fix-it:"{{.*}}":{[[@LINE-1]]:3-[[@LINE-1]]:14}:"std::array arr"
+  arr[idx] = idx;
+
+  return arr > ptr;
+  // CHECK-DAG: fix-it:"{{.*}}":{[[@LINE-1]]:13-[[@LINE-1]]:13}:".data()"
+}
+
+int long long ptr_distance(int* ptr, unsigned idx) {
+  int arr[10];
+  // 

[clang-tools-extra] [clang-tidy] fix incorrect hint for InitListExpr in prefer-member-initializer (PR #81560)

2024-02-12 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang-tidy

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

Author: Congcong Cai (HerrCai0907)


Changes

Fixes: #77684.

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


3 Files Affected:

- (modified) 
clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp 
(+5) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+2-1) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
 (+23) 


``diff
diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
index de96c3dc4efef7..7ede900d7ba7b1 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -203,6 +203,7 @@ void PreferMemberInitializerCheck::check(
 SourceLocation InsertPos;
 SourceRange ReplaceRange;
 bool AddComma = false;
+bool AddBracket = false;
 bool InvalidFix = false;
 unsigned Index = Field->getFieldIndex();
 const CXXCtorInitializer *LastInListInit = nullptr;
@@ -216,6 +217,7 @@ void PreferMemberInitializerCheck::check(
 else {
   ReplaceRange = Init->getInit()->getSourceRange();
 }
+AddBracket = isa(Init->getInit());
 break;
   }
   if (Init->isMemberInitializer() &&
@@ -279,6 +281,9 @@ void PreferMemberInitializerCheck::check(
 if (HasInitAlready) {
   if (InsertPos.isValid())
 Diag << FixItHint::CreateInsertion(InsertPos, NewInit);
+  else if (AddBracket)
+Diag << FixItHint::CreateReplacement(ReplaceRange,
+ ("{" + NewInit + "}").str());
   else
 Diag << FixItHint::CreateReplacement(ReplaceRange, NewInit);
 } else {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ee68c8f49b3df2..f8bc85d78315bf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -127,7 +127,8 @@ Changes in existing checks
   
`_,
   which was deprecated since :program:`clang-tidy` 17. This rule is now covered
   by :doc:`cppcoreguidelines-use-default-member-init
-  `.
+  ` and fixes
+  incorrect hints when using list-initialization.
 
 - Improved :doc:`google-build-namespaces
   ` check by replacing the local
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
index 8086caa2aa6f2c..63b4919608ff18 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
@@ -616,3 +616,26 @@ class Foo {
 #undef INVALID_HANDLE_VALUE
 #undef RGB
 }
+
+namespace GH77684 {
+struct S1 {
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S1() : M{} { M = 0; }
+// CHECK-FIXES: {{ S1.+M\{0\} }}
+  int M;
+};
+struct S2 {
+// CHECK-MESSAGES: :[[@LINE+1]]:17: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S2() : M{2} { M = 1; }
+// CHECK-FIXES: {{ S2.+M\{1\} }}
+  int M;
+};
+struct T { int a; int b; int c; };
+T v;
+struct S3 {
+// CHECK-MESSAGES: :[[@LINE+1]]:21: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S3() : M{1,2,3} { M = v; }
+// CHECK-FIXES: {{ S3.+M\{v\} }}
+  T M;
+};
+}

``




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


[clang-tools-extra] [clang-tidy] fix incorrect hint for InitListExpr in prefer-member-initializer (PR #81560)

2024-02-12 Thread Congcong Cai via cfe-commits

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

Fixes: #77684.

>From 35dba54b1d6d158118c34d0f1bd8038b64c9bda4 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Tue, 13 Feb 2024 09:11:06 +0800
Subject: [PATCH] [clang-tidy] fix incorrect hint for InitListExpr in
 prefer-member-initializer

Fixes: #77684.
---
 .../PreferMemberInitializerCheck.cpp  |  5 
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 ++-
 .../prefer-member-initializer.cpp | 23 +++
 3 files changed, 30 insertions(+), 1 deletion(-)

diff --git 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
index de96c3dc4efef7..7ede900d7ba7b1 100644
--- 
a/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
+++ 
b/clang-tools-extra/clang-tidy/cppcoreguidelines/PreferMemberInitializerCheck.cpp
@@ -203,6 +203,7 @@ void PreferMemberInitializerCheck::check(
 SourceLocation InsertPos;
 SourceRange ReplaceRange;
 bool AddComma = false;
+bool AddBracket = false;
 bool InvalidFix = false;
 unsigned Index = Field->getFieldIndex();
 const CXXCtorInitializer *LastInListInit = nullptr;
@@ -216,6 +217,7 @@ void PreferMemberInitializerCheck::check(
 else {
   ReplaceRange = Init->getInit()->getSourceRange();
 }
+AddBracket = isa(Init->getInit());
 break;
   }
   if (Init->isMemberInitializer() &&
@@ -279,6 +281,9 @@ void PreferMemberInitializerCheck::check(
 if (HasInitAlready) {
   if (InsertPos.isValid())
 Diag << FixItHint::CreateInsertion(InsertPos, NewInit);
+  else if (AddBracket)
+Diag << FixItHint::CreateReplacement(ReplaceRange,
+ ("{" + NewInit + "}").str());
   else
 Diag << FixItHint::CreateReplacement(ReplaceRange, NewInit);
 } else {
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ee68c8f49b3df2..f8bc85d78315bf 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -127,7 +127,8 @@ Changes in existing checks
   
`_,
   which was deprecated since :program:`clang-tidy` 17. This rule is now covered
   by :doc:`cppcoreguidelines-use-default-member-init
-  `.
+  ` and fixes
+  incorrect hints when using list-initialization.
 
 - Improved :doc:`google-build-namespaces
   ` check by replacing the local
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
index 8086caa2aa6f2c..63b4919608ff18 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/cppcoreguidelines/prefer-member-initializer.cpp
@@ -616,3 +616,26 @@ class Foo {
 #undef INVALID_HANDLE_VALUE
 #undef RGB
 }
+
+namespace GH77684 {
+struct S1 {
+// CHECK-MESSAGES: :[[@LINE+1]]:16: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S1() : M{} { M = 0; }
+// CHECK-FIXES: {{ S1.+M\{0\} }}
+  int M;
+};
+struct S2 {
+// CHECK-MESSAGES: :[[@LINE+1]]:17: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S2() : M{2} { M = 1; }
+// CHECK-FIXES: {{ S2.+M\{1\} }}
+  int M;
+};
+struct T { int a; int b; int c; };
+T v;
+struct S3 {
+// CHECK-MESSAGES: :[[@LINE+1]]:21: warning: 'M' should be initialized in a 
member initializer of the constructor 
[cppcoreguidelines-prefer-member-initializer]
+  S3() : M{1,2,3} { M = v; }
+// CHECK-FIXES: {{ S3.+M\{v\} }}
+  T M;
+};
+}

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-12 Thread Dinar Temirbulatov via cfe-commits

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


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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-12 Thread Dinar Temirbulatov via cfe-commits


@@ -814,6 +820,49 @@ Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction , 
Address VAListAddr,
   /*allowHigherAlign*/ false);
 }
 
+class SMEAttributes {
+public:
+  bool IsStreaming = false;
+  bool IsStreamingCompatible = false;
+  bool HasNewZA = false;
+
+  SMEAttributes(const FunctionDecl *F) {
+if (F->hasAttr())
+  IsStreaming = true;
+if (auto *NewAttr = F->getAttr()) {
+  if (NewAttr->isNewZA())
+HasNewZA = true;
+}
+if (const auto *T = F->getType()->getAs()) {
+  if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
+IsStreaming = true;
+  if (T->getAArch64SMEAttributes() &
+  FunctionType::SME_PStateSMCompatibleMask)
+IsStreamingCompatible = true;
+}
+  }
+};
+
+void AArch64TargetCodeGenInfo::checkFunctionCallABI(
+CodeGenModule , SourceLocation CallLoc, const FunctionDecl *Caller,
+const FunctionDecl *Callee, const CallArgList ) const {
+  if (!Callee->hasAttr())
+return;
+
+  SMEAttributes CalleeAttrs(Callee);
+  SMEAttributes CallerAttrs(Caller);

dtemirbulatov wrote:

Caller or Callee might be Null?

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


[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-12 Thread Dinar Temirbulatov via cfe-commits

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


[clang] [RISCV] Add canonical ISA string as Module metadata in IR. (PR #80760)

2024-02-12 Thread Jessica Clarke via cfe-commits

jrtc27 wrote:

That's fair. I just imagine this is going to result in people forgetting about 
the underlying issue and adding their own patchwork fixes to work around it in 
their targets, so it would be a nice motivation to fix it properly.

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


[clang] [clang] Remove #undef alloca workaround (PR #81534)

2024-02-12 Thread Nico Weber via cfe-commits

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

LG, great investigation!

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


[clang-tools-extra] [llvm] Add bazel support for clangd as a library. (PR #81556)

2024-02-12 Thread via cfe-commits

https://github.com/josh11b updated 
https://github.com/llvm/llvm-project/pull/81556

>From e2b83f086e51d7144d8e6ac1d1850300de55f01f Mon Sep 17 00:00:00 2001
From: Josh L 
Date: Mon, 12 Feb 2024 22:59:21 +
Subject: [PATCH] Add bazel support for clangd as a library.

---
 clang-tools-extra/clangd/Transport.h  |  1 -
 .../clang-tools-extra/clangd/BUILD.bazel  | 45 +++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 
utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel

diff --git a/clang-tools-extra/clangd/Transport.h 
b/clang-tools-extra/clangd/Transport.h
index 4e80ea95b8537d..f17441cfc1ef22 100644
--- a/clang-tools-extra/clangd/Transport.h
+++ b/clang-tools-extra/clangd/Transport.h
@@ -18,7 +18,6 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 
-#include "Feature.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/JSON.h"
 #include "llvm/Support/raw_ostream.h"
diff --git 
a/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel 
b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
new file mode 100644
index 00..0e25dd1c166560
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
@@ -0,0 +1,45 @@
+# This file is licensed 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
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])
+
+cc_library(
+name = "clangd_library",
+srcs = [
+"JSONTransport.cpp",
+"Protocol.cpp",
+"URI.cpp",
+"index/SymbolID.cpp",
+"support/Logger.cpp",
+"support/Trace.cpp",
+"support/MemoryTree.cpp",
+"support/Context.cpp",
+"support/Cancellation.cpp",
+"support/ThreadCrashReporter.cpp",
+"support/Shutdown.cpp",
+],
+hdrs = [
+"Transport.h",
+"Protocol.h",
+"URI.h",
+"LSPBinder.h",
+"index/SymbolID.h",
+"support/Function.h",
+"support/Cancellation.h",
+"support/ThreadCrashReporter.h",
+"support/Logger.h",
+"support/Trace.h",
+"support/MemoryTree.h",
+"support/Context.h",
+"support/Shutdown.h",
+],
+includes = ["."],
+deps = [
+"//llvm:Support",
+"//clang:basic",
+"//clang:index",
+],
+)

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-12 Thread Alex Hoppen via cfe-commits


@@ -538,11 +564,222 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return llvm::Error::success();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.

ahoppen wrote:

Why don’t we support `foo : `? Or what am I missing here? `[bar foo : 1]` is 
perfectly valid AFAICT.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-12 Thread Alex Hoppen via cfe-commits


@@ -538,11 +564,222 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return llvm::Error::success();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool isMatchingSelectorName(const syntax::Token , const syntax::Token 
,
+const SourceManager ,
+llvm::StringRef SelectorName) {
+  if (SelectorName.empty())
+return Cur.kind() == tok::colon;
+  return isSelectorLike(Cur, Next) && Cur.text(SM) == SelectorName;
+}
+
+// Scan through Tokens to find ranges for each selector fragment in Sel at the
+// top level (not nested in any () or {} or []). The search will terminate upon
+// seeing Terminator or a ; at the top level.
+std::optional
+findAllSelectorPieces(llvm::ArrayRef Tokens,
+  const SourceManager , Selector Sel,
+  tok::TokenKind Terminator) {
+
+  unsigned NumArgs = Sel.getNumArgs();
+  llvm::SmallVector Closes;
+  std::vector SelectorPieces;
+  unsigned Last = Tokens.size() - 1;
+  for (unsigned Index = 0; Index < Last; ++Index) {
+const auto  = Tokens[Index];
+
+if (Closes.empty()) {
+  auto PieceCount = SelectorPieces.size();
+  if (PieceCount < NumArgs &&
+  isMatchingSelectorName(Tok, Tokens[Index + 1], SM,
+ Sel.getNameForSlot(PieceCount))) {
+// If 'foo:' instead of ':' (empty selector), we need to skip the ':'
+// token after the name.
+if (!Sel.getNameForSlot(PieceCount).empty())
+  ++Index;
+SelectorPieces.push_back(
+halfOpenToRange(SM, Tok.range(SM).toCharRange(SM)));
+continue;
+  }
+  // If we've found all pieces but the current token looks like another
+  // selector piece, it means the method being renamed is a strict prefix 
of
+  // the selector we've found - should be skipped.
+  if (SelectorPieces.size() >= NumArgs &&
+  isSelectorLike(Tok, Tokens[Index + 1]))
+return std::nullopt;
+}
+
+if (Closes.empty() && Tok.kind() == Terminator)
+  return SelectorPieces.size() == NumArgs
+ ? std::optional(SymbolRange(SelectorPieces))
+ : std::nullopt;
+
+switch (Tok.kind()) {
+case tok::l_square:
+  Closes.push_back(tok::r_square);
+  break;
+case tok::l_paren:
+  Closes.push_back(tok::r_paren);
+  break;
+case tok::l_brace:
+  Closes.push_back(tok::r_brace);
+  break;
+case tok::r_square:
+case tok::r_paren:
+case tok::r_brace:
+  if (Closes.empty() || Closes.back() != Tok.kind())
+return std::nullopt;
+  Closes.pop_back();
+  break;
+case tok::semi:
+  // top level ; terminates all statements.
+  if (Closes.empty())
+return SelectorPieces.size() == NumArgs
+   ? std::optional(SymbolRange(SelectorPieces))
+   : std::nullopt;
+  break;
+default:
+  break;
+}
+  }
+  return std::nullopt;
+}
+
+/// Collects all ranges of the given identifier/selector in the source code.
+///
+/// If a selector is given, this does a full lex of the given source code in
+/// order to identify all selector fragments (e.g. in method exprs/decls) since
+/// they are non-contiguous.
+std::vector collectRenameIdentifierRanges(
+llvm::StringRef Identifier, llvm::StringRef Content,
+const LangOptions , std::optional Selector) {
+  std::vector Ranges;
+  if (!Selector) {
+auto IdentifierRanges =
+collectIdentifierRanges(Identifier, Content, LangOpts);
+for (const auto  : IdentifierRanges)
+  Ranges.emplace_back(R);
+return Ranges;
+  }
+  // FIXME: InMemoryFileAdapter crashes unless the buffer is null terminated!

ahoppen wrote:

In my rename PR I found that this is no longer an issue. See 
https://github.com/apple/llvm-project/pull/7915#discussion_r1442402332

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-12 Thread Alex Hoppen via cfe-commits


@@ -538,11 +564,222 @@ std::optional checkName(const NamedDecl 
,
 Conflict->getLocation().printToString(ASTCtx.getSourceManager())};
 }
   }
-  if (Result)
+  if (Result) {
 InvalidNameMetric.record(1, toString(Result->K));
+return makeError(*Result);
+  }
+  return llvm::Error::success();
+}
+
+bool isSelectorLike(const syntax::Token , const syntax::Token ) {
+  return Cur.kind() == tok::identifier && Next.kind() == tok::colon &&
+ // We require the selector name and : to be contiguous.
+ // e.g. support `foo:` but not `foo :`.
+ Cur.endLocation() == Next.location();
+}
+
+bool isMatchingSelectorName(const syntax::Token , const syntax::Token 
,
+const SourceManager ,
+llvm::StringRef SelectorName) {
+  if (SelectorName.empty())
+return Cur.kind() == tok::colon;
+  return isSelectorLike(Cur, Next) && Cur.text(SM) == SelectorName;
+}
+
+// Scan through Tokens to find ranges for each selector fragment in Sel at the
+// top level (not nested in any () or {} or []). The search will terminate upon

ahoppen wrote:

I think the `not nested in any () or {} or []` is quite misleading. Based on 
this comment, I would have expected `doStuff` in `[someObject someArgLabel: 
[foo doStuff: 1]]` or 

```objectivec
- (void) test {
  [foo doStuff: 1];
}
```

to not be found because it’s nested in `{}` or `[]`.

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-12 Thread Alex Hoppen via cfe-commits

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


[clang-tools-extra] Add support for renaming objc methods, even those with multiple selector pieces (PR #76466)

2024-02-12 Thread Alex Hoppen via cfe-commits

https://github.com/ahoppen commented:

The outstanding comments from last review are:
- Use `SymbolName` instead of `StringRef`
  - https://github.com/llvm/llvm-project/pull/76466#discussion_r1476409221
  - https://github.com/llvm/llvm-project/pull/76466#discussion_r1476427027
- Don’t re-lex the source file in `collectRenameIdentifierRanges`
  - https://github.com/llvm/llvm-project/pull/76466#discussion_r1476471971
- Use index or AST data to find edits in the current file. AFAICT we do use 
index-data for the multi-file rename case in `adjustRenameRanges` but I AFAICT 
no semantic information is used for the current file.
  - https://github.com/llvm/llvm-project/pull/76466/files#r1479029824
  - I think a good test case to add would be
```cpp
// Input
R"cpp(
  @interface Foo
  - (void)performA^ction:(int)action with:(int)value;
  @end
  @implementation Foo
  - (void)performAction:(int)action with:(int)value {
[self performAction:action with:value];
  }
  @end
  @interface Bar
  - (void)performAction:(int)action with:(int)value;
  @end
  @implementation Bar
  - (void)performAction:(int)action with:(int)value {
  }
  @end
)cpp",
// New name
"performNewAction:by:",
// Expected
R"cpp(
  @interface Foo
  - (void)performNewAction:(int)action by:(int)value;
  @end
  @implementation Foo
  - (void)performNewAction:(int)action by:(int)value {
[self performNewAction:action by:value];
  }
  @end
  @interface Bar
  - (void)performAction:(int)action with:(int)value;
  @end
  @implementation Bar
  - (void)performAction:(int)action with:(int)value {
  }
)cpp",
```

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


[clang-tools-extra] [llvm] Add bazel support for clangd as a library. (PR #81556)

2024-02-12 Thread via cfe-commits

github-actions[bot] wrote:

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


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


[clang-tools-extra] [llvm] Add bazel support for clangd as a library. (PR #81556)

2024-02-12 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: None (josh11b)


Changes

Both creates a `BUILD.bazel` file for the `clangd` directory in the project 
overlay, and removes an unnecessary `#include "Feature.h"` to reduce the 
dependencies from `Transport.h`.

This upstreams the patch that allows 
https://github.com/carbon-language/carbon-lang/tree/trunk/language_server to 
use `clangd` as a library. This was created as part of a Summer of Code project 
building a prototype Carbon language server. If this is not an appropriate 
architecture, I'm very open to alternative paths forward.

Thanks!

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/Transport.h (-1) 
- (added) utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel 
(+45) 


``diff
diff --git a/clang-tools-extra/clangd/Transport.h 
b/clang-tools-extra/clangd/Transport.h
index 4e80ea95b8537d..f17441cfc1ef22 100644
--- a/clang-tools-extra/clangd/Transport.h
+++ b/clang-tools-extra/clangd/Transport.h
@@ -18,7 +18,6 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 
-#include "Feature.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/JSON.h"
 #include "llvm/Support/raw_ostream.h"
diff --git 
a/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel 
b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
new file mode 100644
index 00..0e25dd1c166560
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
@@ -0,0 +1,45 @@
+# This file is licensed 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
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])
+
+cc_library(
+name = "clangd_library",
+srcs = [
+"JSONTransport.cpp",
+"Protocol.cpp",
+"URI.cpp",
+"index/SymbolID.cpp",
+"support/Logger.cpp",
+"support/Trace.cpp",
+"support/MemoryTree.cpp",
+"support/Context.cpp",
+"support/Cancellation.cpp",
+"support/ThreadCrashReporter.cpp",
+"support/Shutdown.cpp",
+],
+hdrs = [
+"Transport.h",
+"Protocol.h",
+"URI.h",
+"LSPBinder.h",
+"index/SymbolID.h",
+"support/Function.h",
+"support/Cancellation.h",
+"support/ThreadCrashReporter.h",
+"support/Logger.h",
+"support/Trace.h",
+"support/MemoryTree.h",
+"support/Context.h",
+"support/Shutdown.h",
+],
+includes = ["."],
+deps = [
+"//llvm:Support",
+"//clang:basic",
+"//clang:index",
+],
+)

``




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


[clang-tools-extra] [llvm] Add bazel support for clangd as a library. (PR #81556)

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


[clang-tools-extra] [llvm] Add bazel support for clangd as a library. (PR #81556)

2024-02-12 Thread via cfe-commits

https://github.com/josh11b created 
https://github.com/llvm/llvm-project/pull/81556

Both creates a `BUILD.bazel` file for the `clangd` directory in the project 
overlay, and removes an unnecessary `#include "Feature.h"` to reduce the 
dependencies from `Transport.h`.

This upstreams the patch that allows 
https://github.com/carbon-language/carbon-lang/tree/trunk/language_server to 
use `clangd` as a library. This was created as part of a Summer of Code project 
building a prototype Carbon language server. If this is not an appropriate 
architecture, I'm very open to alternative paths forward.

Thanks!

>From 25c2f4f22adda315205f12c5d62dbc839395c9c3 Mon Sep 17 00:00:00 2001
From: Josh L 
Date: Mon, 12 Feb 2024 22:59:21 +
Subject: [PATCH] Add bazel support for clangd as a library.

---
 clang-tools-extra/clangd/Transport.h  |  1 -
 .../clang-tools-extra/clangd/BUILD.bazel  | 45 +++
 2 files changed, 45 insertions(+), 1 deletion(-)
 create mode 100644 
utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel

diff --git a/clang-tools-extra/clangd/Transport.h 
b/clang-tools-extra/clangd/Transport.h
index 4e80ea95b8537d..f17441cfc1ef22 100644
--- a/clang-tools-extra/clangd/Transport.h
+++ b/clang-tools-extra/clangd/Transport.h
@@ -18,7 +18,6 @@
 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_TRANSPORT_H
 
-#include "Feature.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Support/JSON.h"
 #include "llvm/Support/raw_ostream.h"
diff --git 
a/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel 
b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
new file mode 100644
index 00..0e25dd1c166560
--- /dev/null
+++ b/utils/bazel/llvm-project-overlay/clang-tools-extra/clangd/BUILD.bazel
@@ -0,0 +1,45 @@
+# This file is licensed 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
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])
+
+cc_library(
+name = "clangd_library",
+srcs = [
+"JSONTransport.cpp",
+"Protocol.cpp",
+"URI.cpp",
+"index/SymbolID.cpp",
+"support/Logger.cpp",
+"support/Trace.cpp",
+"support/MemoryTree.cpp",
+"support/Context.cpp",
+"support/Cancellation.cpp",
+"support/ThreadCrashReporter.cpp",
+"support/Shutdown.cpp",
+],
+hdrs = [
+"Transport.h",
+"Protocol.h",
+"URI.h",
+"LSPBinder.h",
+"index/SymbolID.h",
+"support/Function.h",
+"support/Cancellation.h",
+"support/ThreadCrashReporter.h",
+"support/Logger.h",
+"support/Trace.h",
+"support/MemoryTree.h",
+"support/Context.h",
+"support/Shutdown.h",
+],
+includes = ["."],
+deps = [
+"//llvm:Support",
+"//clang:basic",
+"//clang:index",
+],
+)

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


[clang] [-Wunsafe-buffer-usage] Introduce std::array fixits (PR #80084)

2024-02-12 Thread via cfe-commits

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


[clang] 644ac2a - [-Wunsafe-buffer-usage] Introduce std::array fixits (#80084)

2024-02-12 Thread via cfe-commits

Author: jkorous-apple
Date: 2024-02-12T15:52:20-08:00
New Revision: 644ac2a018c9bf83c9ba256074e552ad7f1fe941

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

LOG: [-Wunsafe-buffer-usage] Introduce std::array fixits (#80084)

Array subscript on a const size array is not bounds-checked. The idiomatic
replacement is std::array which is bounds-safe in hardened mode of libc++.

This commit extends the fixit-producing machine to consider std::array as a
transformation target type and teaches it to handle the array subscript on const
size arrays with a trivial (empty) fixit.

Added: 
clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-local-var-array.cpp

Modified: 
clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Analysis/UnsafeBufferUsage.cpp
clang/lib/Sema/AnalysisBasedWarnings.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug.cpp
clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp

Removed: 




diff  --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h 
b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
index aca1ad998822c5..5d16dcc824c50c 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
@@ -42,6 +42,43 @@ class VariableGroupsManager {
   virtual VarGrpRef getGroupOfParms() const =0;
 };
 
+// FixitStrategy is a map from variables to the way we plan to emit fixes for
+// these variables. It is figured out gradually by trying 
diff erent fixes
+// for 
diff erent variables depending on gadgets in which these variables
+// participate.
+class FixitStrategy {
+public:
+  enum class Kind {
+Wontfix,  // We don't plan to emit a fixit for this variable.
+Span, // We recommend replacing the variable with std::span.
+Iterator, // We recommend replacing the variable with std::span::iterator.
+Array,// We recommend replacing the variable with std::array.
+Vector// We recommend replacing the variable with std::vector.
+  };
+
+private:
+  using MapTy = llvm::DenseMap;
+
+  MapTy Map;
+
+public:
+  FixitStrategy() = default;
+  FixitStrategy(const FixitStrategy &) = delete; // Let's avoid copies.
+  FixitStrategy =(const FixitStrategy &) = delete;
+  FixitStrategy(FixitStrategy &&) = default;
+  FixitStrategy =(FixitStrategy &&) = default;
+
+  void set(const VarDecl *VD, Kind K) { Map[VD] = K; }
+
+  Kind lookup(const VarDecl *VD) const {
+auto I = Map.find(VD);
+if (I == Map.end())
+  return Kind::Wontfix;
+
+return I->second;
+  }
+};
+
 /// The interface that lets the caller handle unsafe buffer usage analysis
 /// results by overriding this class's handle... methods.
 class UnsafeBufferUsageHandler {
@@ -75,9 +112,11 @@ class UnsafeBufferUsageHandler {
   ///
   /// `D` is the declaration of the callable under analysis that owns 
`Variable`
   /// and all of its group mates.
-  virtual void handleUnsafeVariableGroup(const VarDecl *Variable,
- const VariableGroupsManager 
,
- FixItList &, const Decl *D) = 0;
+  virtual void
+  handleUnsafeVariableGroup(const VarDecl *Variable,
+const VariableGroupsManager ,
+FixItList &, const Decl *D,
+const FixitStrategy ) = 0;
 
 #ifndef NDEBUG
 public:

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 83b89d1449f420..754733a6c5fffd 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -12128,9 +12128,9 @@ def warn_unsafe_buffer_operation : Warning<
 def note_unsafe_buffer_operation : Note<
   "used%select{| in pointer arithmetic| in buffer access}0 here">;
 def note_unsafe_buffer_variable_fixit_group : Note<
-  "change type of %0 to '%select{std::span|std::array|std::span::iterator}1' 
to preserve bounds information%select{|, and change %2 to 
'%select{std::span|std::array|std::span::iterator}1' to propagate bounds 
information between them}3">;
+  "change type of %0 to '%select{std::span' to preserve bounds 
information|std::array' to label it for hardening|std::span::iterator' to 
preserve bounds information}1%select{|, and change %2 to 
'%select{std::span|std::array|std::span::iterator}1' to propagate bounds 
information between them}3">;
 def note_unsafe_buffer_variable_fixit_together : Note<
-  "change type of %0 to '%select{std::span|std::array|std::span::iterator}1' 
to preserve bounds information"
+  "change type of %0 to '%select{std::span' to 

[clang] [-Wunsafe-buffer-usage] Introduce std::array fixits (PR #80084)

2024-02-12 Thread via cfe-commits


@@ -61,6 +61,7 @@ void testArraySubscripts(int *p, int **pp) {
   );
 
 int a[10];  // expected-warning{{'a' is an unsafe buffer that does 
not perform bounds checks}}
+// expected-note@-1{{change type of 'a' to 
'std::array' to harden it}}

jkorous-apple wrote:

Went with "to label it for hardening".

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


[clang] [-Wunsafe-buffer-usage] Introduce std::array fixits (PR #80084)

2024-02-12 Thread via cfe-commits

https://github.com/jkorous-apple updated 
https://github.com/llvm/llvm-project/pull/80084

>From 463a9904c1ae85fbdc0bd6029c6effea3fb16ea6 Mon Sep 17 00:00:00 2001
From: Jan Korous 
Date: Tue, 23 Jan 2024 16:16:10 -0800
Subject: [PATCH 01/17] [-Wunsafe-buffer-usage] Move Strategy class to the
 header

It needs to be used from handleUnsafeVariableGroup function.
---
 .../Analysis/Analyses/UnsafeBufferUsage.h |  37 +++
 clang/lib/Analysis/UnsafeBufferUsage.cpp  | 238 --
 2 files changed, 140 insertions(+), 135 deletions(-)

diff --git a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h 
b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
index aca1ad998822c5..622c094f5b1eb1 100644
--- a/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
+++ b/clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
@@ -42,6 +42,43 @@ class VariableGroupsManager {
   virtual VarGrpRef getGroupOfParms() const =0;
 };
 
+// FixitStrategy is a map from variables to the way we plan to emit fixes for
+// these variables. It is figured out gradually by trying different fixes
+// for different variables depending on gadgets in which these variables
+// participate.
+class FixitStrategy {
+public:
+  enum class Kind {
+Wontfix,  // We don't plan to emit a fixit for this variable.
+Span, // We recommend replacing the variable with std::span.
+Iterator, // We recommend replacing the variable with std::span::iterator.
+Array,// We recommend replacing the variable with std::array.
+Vector// We recommend replacing the variable with std::vector.
+  };
+
+private:
+  using MapTy = llvm::DenseMap;
+
+  MapTy Map;
+
+public:
+  FixitStrategy() = default;
+  FixitStrategy(const FixitStrategy &) = delete; // Let's avoid copies.
+  FixitStrategy =(const FixitStrategy &) = delete;
+  FixitStrategy(FixitStrategy &&) = default;
+  FixitStrategy =(FixitStrategy &&) = default;
+
+  void set(const VarDecl *VD, Kind K) { Map[VD] = K; }
+
+  Kind lookup(const VarDecl *VD) const {
+auto I = Map.find(VD);
+if (I == Map.end())
+  return Kind::Wontfix;
+
+return I->second;
+  }
+};
+
 /// The interface that lets the caller handle unsafe buffer usage analysis
 /// results by overriding this class's handle... methods.
 class UnsafeBufferUsageHandler {
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 823cd2a7b99691..924d677786275d 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -407,9 +407,6 @@ using DeclUseList = SmallVector;
 
 // Convenience typedef.
 using FixItList = SmallVector;
-
-// Defined below.
-class Strategy;
 } // namespace
 
 namespace {
@@ -486,7 +483,7 @@ class FixableGadget : public Gadget {
   /// Returns a fixit that would fix the current gadget according to
   /// the current strategy. Returns std::nullopt if the fix cannot be produced;
   /// returns an empty list if no fixes are necessary.
-  virtual std::optional getFixits(const Strategy &) const {
+  virtual std::optional getFixits(const FixitStrategy &) const {
 return std::nullopt;
   }
 
@@ -737,7 +734,8 @@ class PointerInitGadget : public FixableGadget {
 return stmt(PtrInitStmt);
   }
 
-  virtual std::optional getFixits(const Strategy ) const override;
+  virtual std::optional
+  getFixits(const FixitStrategy ) const override;
 
   virtual const Stmt *getBaseStmt() const override {
 // FIXME: This needs to be the entire DeclStmt, assuming that this method
@@ -789,7 +787,8 @@ class PointerAssignmentGadget : public FixableGadget {
 return stmt(isInUnspecifiedUntypedContext(PtrAssignExpr));
   }
 
-  virtual std::optional getFixits(const Strategy ) const override;
+  virtual std::optional
+  getFixits(const FixitStrategy ) const override;
 
   virtual const Stmt *getBaseStmt() const override {
 // FIXME: This should be the binary operator, assuming that this method
@@ -892,7 +891,8 @@ class ULCArraySubscriptGadget : public FixableGadget {
 return expr(isInUnspecifiedLvalueContext(Target));
   }
 
-  virtual std::optional getFixits(const Strategy ) const override;
+  virtual std::optional
+  getFixits(const FixitStrategy ) const override;
 
   virtual const Stmt *getBaseStmt() const override { return Node; }
 
@@ -932,7 +932,8 @@ class UPCStandalonePointerGadget : public FixableGadget {
 return stmt(isInUnspecifiedPointerContext(target));
   }
 
-  virtual std::optional getFixits(const Strategy ) const override;
+  virtual std::optional
+  getFixits(const FixitStrategy ) const override;
 
   virtual const Stmt *getBaseStmt() const override { return Node; }
 
@@ -976,7 +977,8 @@ class PointerDereferenceGadget : public FixableGadget {
 
   virtual const Stmt *getBaseStmt() const final { return Op; }
 
-  virtual std::optional getFixits(const Strategy ) const override;
+  virtual std::optional
+  getFixits(const FixitStrategy ) const override;
 };
 
 // 

[clang] [llvm] [Clang][SME] Detect always_inline used with mismatched streaming attributes (PR #77936)

2024-02-12 Thread Dinar Temirbulatov via cfe-commits

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

LGTM.

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


[clang] [clang-tools-extra] [codegen] Emit missing cleanups when an expression contains a branch (PR #80698)

2024-02-12 Thread Eli Friedman via cfe-commits


@@ -592,10 +590,14 @@ void AggExprEmitter::EmitArrayInit(Address DestPtr, 
llvm::ArrayType *AType,
   // observed to be unnecessary.
   if (endOfInit.isValid()) Builder.CreateStore(element, endOfInit);
 }
-
-LValue elementLV = CGF.MakeAddrLValue(
-Address(element, llvmElementType, elementAlign), elementType);
+Address address = Address(element, llvmElementType, elementAlign);
+LValue elementLV = CGF.MakeAddrLValue(address, elementType);
 EmitInitializationToLValue(Args[i], elementLV);
+// Schedule to emit element cleanup if we see a branch in the array
+// initialisation expression.
+if (CGF.needsBranchCleanup(dtorKind))
+  CGF.pushDestroy(BranchInExprCleanup, address, elementType,

efriedma-quic wrote:

Any thoughts on pushing a cleanup for each array element, vs. using a single 
cleanup which iterates over the elements, like we do for exceptions?

Is there any chance an ArrayFiller needs a branch cleanup?  Off the top of my 
head, I don't think it's possible because branches exits can only happen in 
code explicitly written in the current function, but that's a subtle invariant.

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


[clang] [clang-tools-extra] [codegen] Emit missing cleanups when an expression contains a branch (PR #80698)

2024-02-12 Thread Eli Friedman via cfe-commits

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


[clang] [clang-tools-extra] [codegen] Emit missing cleanups when an expression contains a branch (PR #80698)

2024-02-12 Thread Eli Friedman via cfe-commits


@@ -627,9 +627,11 @@ CodeGenFunction::getJumpDestForLabel(const LabelDecl *D) {
   if (Dest.isValid()) return Dest;
 
   // Create, but don't insert, the new block.
+  // FIXME: We do not know `BranchInExprDepth` for the destination and 
currently
+  // emit *all* the BranchInExpr cleanups.

efriedma-quic wrote:

Can you briefly describe what you expect the fix for this to look like, if you 
have some idea?

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


[clang] [clang-tools-extra] [codegen] Emit missing cleanups when an expression contains a branch (PR #80698)

2024-02-12 Thread Eli Friedman via cfe-commits

https://github.com/efriedma-quic commented:

Do we need to add handling for `new int[](co_await foo())` 
(CodeGenFunction::EmitNewArrayInitializer)?

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


[clang] [llvm] [RFC][AMDGPU] Use `bf16` instead of `i16` for bfloat (PR #80908)

2024-02-12 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/80908

>From df3dbb6b9c257157c4afb407e40447a25c27a2a8 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Mon, 12 Feb 2024 18:03:57 -0500
Subject: [PATCH] [RFC][WIP][AMDGPU] Use `bf16` instead of `i16` for bfloat

Currently it looks like we generally use `i16` to represent `bf16` in those 
tablegen
files. I'm not sure of the reason behind it. My wild guess is the type `bf16` 
was
not available when we enabled the support. This patch is trying to use `bf16`
directly in those tablegen files, aiming at fixing #79369. Of course for #79369
a workaround can be to treat all `INT16` variants as `BFloat` in 
`getOpFltSemantics`,
but it doesn't look good IMHO.

Since I'm fairly new to AMDGPU backend, I'd appreciate it if you can point out
where I don't understand correctly.
---
 clang/lib/CodeGen/CGBuiltin.cpp   |  4 -
 llvm/include/llvm/IR/IntrinsicsAMDGPU.td  |  8 +-
 llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp  |  5 +-
 .../AMDGPU/AsmParser/AMDGPUAsmParser.cpp  | 71 ++
 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.cpp | 59 +++
 .../AMDGPU/MCTargetDesc/AMDGPUInstPrinter.h   |  2 +
 .../MCTargetDesc/AMDGPUMCCodeEmitter.cpp  |  7 ++
 llvm/lib/Target/AMDGPU/SIDefines.h|  7 ++
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp|  8 ++
 llvm/lib/Target/AMDGPU/SIInstrInfo.td | 58 ---
 llvm/lib/Target/AMDGPU/SIRegisterInfo.td  | 22 +-
 .../Target/AMDGPU/Utils/AMDGPUBaseInfo.cpp| 74 ---
 llvm/lib/Target/AMDGPU/Utils/AMDGPUBaseInfo.h | 15 
 llvm/lib/Target/AMDGPU/VOP3Instructions.td|  2 +-
 .../AMDGPU/llvm.amdgcn.fdot2.bf16.bf16.ll | 36 -
 llvm/test/MC/AMDGPU/bf16_imm.s| 10 +++
 16 files changed, 323 insertions(+), 65 deletions(-)
 create mode 100644 llvm/test/MC/AMDGPU/bf16_imm.s

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index a7a410dab1a018..daf651917f2a96 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -5908,8 +5908,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   }
 }
 
-assert(ArgValue->getType()->canLosslesslyBitCastTo(PTy) &&
-   "Must be able to losslessly bit cast to param");
 // Cast vector type (e.g., v256i32) to x86_amx, this only happen
 // in amx intrinsics.
 if (PTy->isX86_AMXTy())
@@ -5939,8 +5937,6 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 }
   }
 
-  assert(V->getType()->canLosslesslyBitCastTo(RetTy) &&
- "Must be able to losslessly bit cast result type");
   // Cast x86_amx to vector type (e.g., v256i32), this only happen
   // in amx intrinsics.
   if (V->getType()->isX86_AMXTy())
diff --git a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td 
b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
index 202fa4e8f4ea81..6795fb7aa0edb8 100644
--- a/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
+++ b/llvm/include/llvm/IR/IntrinsicsAMDGPU.td
@@ -2819,11 +2819,11 @@ def int_amdgcn_fdot2_f16_f16 :
 def int_amdgcn_fdot2_bf16_bf16 :
   ClangBuiltin<"__builtin_amdgcn_fdot2_bf16_bf16">,
   DefaultAttrsIntrinsic<
-[llvm_i16_ty],   // %r
+[llvm_bfloat_ty],   // %r
 [
-  llvm_v2i16_ty, // %a
-  llvm_v2i16_ty, // %b
-  llvm_i16_ty// %c
+  llvm_v2bf16_ty, // %a
+  llvm_v2bf16_ty, // %b
+  llvm_bfloat_ty// %c
 ],
 [IntrNoMem, IntrSpeculatable]
   >;
diff --git a/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp 
b/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
index c1d8e890a66edb..828229f3e569e3 100644
--- a/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
+++ b/llvm/lib/CodeGen/GlobalISel/IRTranslator.cpp
@@ -1562,8 +1562,9 @@ bool IRTranslator::translateBitCast(const User ,
 
 bool IRTranslator::translateCast(unsigned Opcode, const User ,
  MachineIRBuilder ) {
-  if (U.getType()->getScalarType()->isBFloatTy() ||
-  U.getOperand(0)->getType()->getScalarType()->isBFloatTy())
+  if (Opcode != TargetOpcode::G_BITCAST &&
+  (U.getType()->getScalarType()->isBFloatTy() ||
+   U.getOperand(0)->getType()->getScalarType()->isBFloatTy()))
 return false;
   Register Op = getOrCreateVReg(*U.getOperand(0));
   Register Res = getOrCreateVReg(U);
diff --git a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp 
b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
index 79ad6ddf7861fc..09f25215beb9e5 100644
--- a/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
+++ b/llvm/lib/Target/AMDGPU/AsmParser/AMDGPUAsmParser.cpp
@@ -475,6 +475,8 @@ class AMDGPUOperand : public MCParsedAsmOperand {
 
   bool isSSrcF64() const { return isSCSrc_b64() || isLiteralImm(MVT::f64); }
 
+  bool isSSrc_bf16() const { return isSCSrcB16() || isLiteralImm(MVT::bf16); }
+
   bool isSSrc_f16() const { return 

[clang] [llvm] [AMDGPU] Emit a waitcnt instruction after each memory instruction (PR #79236)

2024-02-12 Thread Jun Wang via cfe-commits


@@ -605,12 +606,197 @@ class SIGfx12CacheControl : public SIGfx11CacheControl {
   bool IsNonTemporal) const override;
 };
 
+class SIPreciseMemorySupport {
+protected:
+  const GCNSubtarget 
+  const SIInstrInfo *TII = nullptr;
+
+  IsaVersion IV;
+
+  SIPreciseMemorySupport(const GCNSubtarget ) : ST(ST) {
+TII = ST.getInstrInfo();
+IV = getIsaVersion(ST.getCPU());
+  }
+
+public:
+  static std::unique_ptr create(const GCNSubtarget 
);
+
+  virtual bool handleNonAtomic(MachineBasicBlock::iterator ) = 0;
+  /// Handles atomic instruction \p MI with \p ret indicating whether \p MI
+  /// returns a result.
+  virtual bool handleAtomic(MachineBasicBlock::iterator , bool ret) = 0;
+};
+
+class SIGfx9PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx9PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+class SIGfx10And11PreciseMemorySupport : public SIPreciseMemorySupport {
+public:
+  SIGfx10And11PreciseMemorySupport(const GCNSubtarget )
+  : SIPreciseMemorySupport(ST) {}
+  bool handleNonAtomic(MachineBasicBlock::iterator ) override;
+  bool handleAtomic(MachineBasicBlock::iterator , bool ret) override;
+};
+
+std::unique_ptr
+SIPreciseMemorySupport::create(const GCNSubtarget ) {
+  GCNSubtarget::Generation Generation = ST.getGeneration();
+  if (Generation < AMDGPUSubtarget::GFX10)

jwanggit86 wrote:

Pls take a look at the updated code. I'll be working on gfx12 in the meantime.

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


  1   2   3   4   5   >