[clang] [flang] [clang][driver] Special care for -l flags in config files (PR #117573)

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

MaskRay wrote:

> I took a look and I think it may be too awkward to do, as we'd want to run 
> e.g. readelf afterwards. But an example is 
> `lld/test/ELF/as-needed-not-in-regular.s`. The idea being: if 
> `-Wl,--as-needed` is in the config file, do we correctly prune an unnecessary 
> library from a built object, or is the order wrong? We can check that with 
> `llvm-readelf`.

`-Wl,--as-needed` is a good example. 
(https://maskray.me/blog/2020-11-15-explain-gnu-linker-options#:~:text=as%2dneeded)

 The patch moves `-Wl,--as-needed` after user input files, while the user 
likely intended the input files to be covered by `-Wl,--as-needed` before a 
pairing `-Wl,--no-as-needed`. ISTM we need a notation to encode the position of 
user inputs.

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


[clang] [clang][bytecode][NFC] Remove APValue Result argument where unnecessary (PR #118199)

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

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

This is unneeded in almost all circumstances. We only return an APValue back to 
clang when the evaluation is finished, and that is always done by an 
EvalEmitter - which has its own implementation of the Ret instructions.

>From 04ce4a535c2ed725e040af30492e5ec87c1dce6c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 1 Dec 2024 09:25:04 +0100
Subject: [PATCH] [clang][bytecode][NFC] Remove APValue Result argument where
 unnecessary

This is unneeded in almost all circumstances. We only return an APValue
back to clang when the evaluation is finished, and that is always done
by an EvalEmitter - which has its own implementation of the Ret
instructions.
---
 clang/lib/AST/ByteCode/Context.cpp   |  7 +++
 clang/lib/AST/ByteCode/Context.h |  2 +-
 clang/lib/AST/ByteCode/Interp.cpp| 10 --
 clang/lib/AST/ByteCode/Interp.h  | 17 +
 clang/lib/AST/ByteCode/InterpBuiltin.cpp |  9 -
 clang/utils/TableGen/ClangOpcodesEmitter.cpp |  2 --
 6 files changed, 17 insertions(+), 30 deletions(-)

diff --git a/clang/lib/AST/ByteCode/Context.cpp 
b/clang/lib/AST/ByteCode/Context.cpp
index 7088cf02901c63..b52892cf69bfb6 100644
--- a/clang/lib/AST/ByteCode/Context.cpp
+++ b/clang/lib/AST/ByteCode/Context.cpp
@@ -34,8 +34,7 @@ bool Context::isPotentialConstantExpr(State &Parent, const 
FunctionDecl *FD) {
   if (!Func)
 return false;
 
-  APValue DummyResult;
-  if (!Run(Parent, Func, DummyResult))
+  if (!Run(Parent, Func))
 return false;
 
   return Func->isConstexpr();
@@ -213,13 +212,13 @@ const llvm::fltSemantics 
&Context::getFloatSemantics(QualType T) const {
   return Ctx.getFloatTypeSemantics(T);
 }
 
-bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
+bool Context::Run(State &Parent, const Function *Func) {
 
   {
 InterpState State(Parent, *P, Stk, *this);
 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
 Func->getArgSize());
-if (Interpret(State, Result)) {
+if (Interpret(State)) {
   assert(Stk.empty());
   return true;
 }
diff --git a/clang/lib/AST/ByteCode/Context.h b/clang/lib/AST/ByteCode/Context.h
index e0d4bafdebaf2b..ed539def99efd0 100644
--- a/clang/lib/AST/ByteCode/Context.h
+++ b/clang/lib/AST/ByteCode/Context.h
@@ -114,7 +114,7 @@ class Context final {
 
 private:
   /// Runs a function.
-  bool Run(State &Parent, const Function *Func, APValue &Result);
+  bool Run(State &Parent, const Function *Func);
 
   /// Current compilation context.
   ASTContext &Ctx;
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 329f1584be34bf..435af1201890c8 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -27,7 +27,7 @@
 using namespace clang;
 using namespace clang::interp;
 
-static bool RetValue(InterpState &S, CodePtr &Pt, APValue &Result) {
+static bool RetValue(InterpState &S, CodePtr &Pt) {
   llvm::report_fatal_error("Interpreter cannot return values");
 }
 
@@ -1205,11 +1205,10 @@ bool CallVar(InterpState &S, CodePtr OpPC, const 
Function *Func,
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();
 
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1270,11 +1269,10 @@ bool Call(InterpState &S, CodePtr OpPC, const Function 
*Func,
   S.Current = NewFrame.get();
 
   InterpStateCCOverride CCOverride(S, Func->getDecl()->isImmediateFunction());
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1598,7 +1596,7 @@ bool CheckBitCast(InterpState &S, CodePtr OpPC, bool 
HasIndeterminateBits,
 #if defined(_MSC_VER) && !defined(__clang__) && !defined(NDEBUG)
 #pragma optimize("", off)
 #endif
-bool Interpret(InterpState &S, APValue &Result) {
+bool Interpret(InterpState &S) {
   // The current stack frame when we started Interpret().
   // This is being used by the ops to determine wheter
   // to return from this function and thus terminate
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 47dcfca79f7356..25740c90d240ab 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -41,13 +41,6 @@ namespace interp {
 using APSInt = llvm::APSInt;
 using Fixe

[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] [clang][bytecode][NFC] Remove APValue Result argument where unnecessary (PR #118199)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This is unneeded in almost all circumstances. We only return an APValue back to 
clang when the evaluation is finished, and that is always done by an 
EvalEmitter - which has its own implementation of the Ret instructions.

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


6 Files Affected:

- (modified) clang/lib/AST/ByteCode/Context.cpp (+3-4) 
- (modified) clang/lib/AST/ByteCode/Context.h (+1-1) 
- (modified) clang/lib/AST/ByteCode/Interp.cpp (+4-6) 
- (modified) clang/lib/AST/ByteCode/Interp.h (+5-12) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltin.cpp (+4-5) 
- (modified) clang/utils/TableGen/ClangOpcodesEmitter.cpp (-2) 


``diff
diff --git a/clang/lib/AST/ByteCode/Context.cpp 
b/clang/lib/AST/ByteCode/Context.cpp
index 7088cf02901c63..b52892cf69bfb6 100644
--- a/clang/lib/AST/ByteCode/Context.cpp
+++ b/clang/lib/AST/ByteCode/Context.cpp
@@ -34,8 +34,7 @@ bool Context::isPotentialConstantExpr(State &Parent, const 
FunctionDecl *FD) {
   if (!Func)
 return false;
 
-  APValue DummyResult;
-  if (!Run(Parent, Func, DummyResult))
+  if (!Run(Parent, Func))
 return false;
 
   return Func->isConstexpr();
@@ -213,13 +212,13 @@ const llvm::fltSemantics 
&Context::getFloatSemantics(QualType T) const {
   return Ctx.getFloatTypeSemantics(T);
 }
 
-bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
+bool Context::Run(State &Parent, const Function *Func) {
 
   {
 InterpState State(Parent, *P, Stk, *this);
 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
 Func->getArgSize());
-if (Interpret(State, Result)) {
+if (Interpret(State)) {
   assert(Stk.empty());
   return true;
 }
diff --git a/clang/lib/AST/ByteCode/Context.h b/clang/lib/AST/ByteCode/Context.h
index e0d4bafdebaf2b..ed539def99efd0 100644
--- a/clang/lib/AST/ByteCode/Context.h
+++ b/clang/lib/AST/ByteCode/Context.h
@@ -114,7 +114,7 @@ class Context final {
 
 private:
   /// Runs a function.
-  bool Run(State &Parent, const Function *Func, APValue &Result);
+  bool Run(State &Parent, const Function *Func);
 
   /// Current compilation context.
   ASTContext &Ctx;
diff --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 329f1584be34bf..435af1201890c8 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -27,7 +27,7 @@
 using namespace clang;
 using namespace clang::interp;
 
-static bool RetValue(InterpState &S, CodePtr &Pt, APValue &Result) {
+static bool RetValue(InterpState &S, CodePtr &Pt) {
   llvm::report_fatal_error("Interpreter cannot return values");
 }
 
@@ -1205,11 +1205,10 @@ bool CallVar(InterpState &S, CodePtr OpPC, const 
Function *Func,
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();
 
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1270,11 +1269,10 @@ bool Call(InterpState &S, CodePtr OpPC, const Function 
*Func,
   S.Current = NewFrame.get();
 
   InterpStateCCOverride CCOverride(S, Func->getDecl()->isImmediateFunction());
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1598,7 +1596,7 @@ bool CheckBitCast(InterpState &S, CodePtr OpPC, bool 
HasIndeterminateBits,
 #if defined(_MSC_VER) && !defined(__clang__) && !defined(NDEBUG)
 #pragma optimize("", off)
 #endif
-bool Interpret(InterpState &S, APValue &Result) {
+bool Interpret(InterpState &S) {
   // The current stack frame when we started Interpret().
   // This is being used by the ops to determine wheter
   // to return from this function and thus terminate
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 47dcfca79f7356..25740c90d240ab 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -41,13 +41,6 @@ namespace interp {
 using APSInt = llvm::APSInt;
 using FixedPointSemantics = llvm::FixedPointSemantics;
 
-/// Convert a value to an APValue.
-template 
-bool ReturnValue(const InterpState &S, const T &V, APValue &R) {
-  R = V.toAPValue(S.getASTContext());
-  return true;
-}
-
 /// Checks if the variable has externally defined storage.
 bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr);
 
@@ -299,7 +292,7 @@ bool CheckFloatResult(InterpState &S, CodePtr OpP

[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] [flang] [clang][driver] Special care for -l flags in config files (PR #117573)

2024-12-01 Thread Sam James via cfe-commits

thesamesam wrote:

@pawosm-arm See also 
https://wiki.gentoo.org/wiki/Project:Quality_Assurance/As-needed#Importance_of_linking_order.
 It is common for distributions to enable `-Wl,--as-needed` via patches to the 
compiler or configuration files.

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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Zhikai Zeng (Backl1ght)


Changes

fix https://github.com/llvm/llvm-project/issues/107629

After some more debugging, I find out that we will check access here at 
https://github.com/llvm/llvm-project/blob/8e010ac5a173c9dee44b44324169a3e100a1a6fc/clang/lib/Sema/SemaInit.cpp#L7807

And for `f()` inside code below, `Found.getAccess()` is `AS_none` hence 
`CheckAddressOfMemberAccess` return `AR_accessible` directly.

```cpp
struct Base {
public:
  int f(int);
private:
  int f();  // expect-note {{declared private here}}
};

struct Derived : public Base {};

void f() {
  int(Derived::* public_f)(int) = &Derived::f;
  int(Derived::* private_f)() = &Derived::f;  // expect-error {{'f' is a 
private member of 'Base'}}
}
```

I think the `Found.getAccess()` is intended to be `AS_none` so I just add one 
more access check for the `UnresolvedLookupExpr` when `Found.getAccess()` is 
`AS_none`. If add the check unconditionally clang will report lots of duplicate 
errors and cause several unit tests to fail.

I also test the UB mentioned in 
https://github.com/llvm/llvm-project/issues/107629 and clang now display 4 
`false` as expecetd.

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+1) 
- (modified) clang/lib/Sema/SemaOverload.cpp (+3) 
- (modified) clang/test/CXX/class.access/p4.cpp (+14-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e44aefa90ab386..0de249ced8309a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -763,6 +763,7 @@ Bug Fixes to C++ Support
 - Fixed a bug where bounds of partially expanded pack indexing expressions 
were checked too early. (#GH116105)
 - Fixed an assertion failure caused by using ``consteval`` in condition in 
consumed analyses. (#GH117385)
 - Fix a crash caused by incorrect argument position in merging deduced 
template arguments. (#GH113659)
+- Fix a bug where private access specifier of overloaded function not 
respected. (#GH107629)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 4c9e37bd286dee..35389957adf32d 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -16305,6 +16305,9 @@ ExprResult Sema::FixOverloadedFunctionReference(Expr 
*E, DeclAccessPair Found,
   }
 
   if (UnresolvedLookupExpr *ULE = dyn_cast(E)) {
+if (Found.getAccess() == AS_none) {
+  CheckUnresolvedLookupAccess(ULE, Found);
+}
 // FIXME: avoid copy.
 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
 if (ULE->hasExplicitTemplateArgs()) {
diff --git a/clang/test/CXX/class.access/p4.cpp 
b/clang/test/CXX/class.access/p4.cpp
index ca98c9f90bd89e..6d4c8c004911db 100644
--- a/clang/test/CXX/class.access/p4.cpp
+++ b/clang/test/CXX/class.access/p4.cpp
@@ -21,11 +21,13 @@ namespace test0 {
   public:
 void foo(Public&);
   protected:
-void foo(Protected&); // expected-note 2 {{declared protected here}}
+void foo(Protected&); // expected-note 4 {{declared protected here}}
   private:
-void foo(Private&); // expected-note 2 {{declared private here}}
+void foo(Private&); // expected-note 4 {{declared private here}}
   };
 
+  class B : public A {};
+
   void test(A *op) {
 op->foo(PublicInst);
 op->foo(ProtectedInst); // expected-error {{'foo' is a protected member}}
@@ -35,6 +37,16 @@ namespace test0 {
 void (A::*b)(Protected&) = &A::foo; // expected-error {{'foo' is a 
protected member}}
 void (A::*c)(Private&) = &A::foo; // expected-error {{'foo' is a private 
member}}
   }
+
+  void test(B *op) {
+op->foo(PublicInst);
+op->foo(ProtectedInst); // expected-error {{'foo' is a protected member}}
+op->foo(PrivateInst); // expected-error {{'foo' is a private member}}
+
+void (B::*a)(Public&) = &B::foo;
+void (B::*b)(Protected&) = &B::foo; // expected-error {{'foo' is a 
protected member}}
+void (B::*c)(Private&) = &B::foo; // expected-error {{'foo' is a private 
member}}
+  }
 }
 
 // Member operators.

``




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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

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


[clang] [clang][bytecode] Support __builtin_reduce_add (PR #117672)

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

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

>From 1bb49850c392cdc535849f43ad14b02cbbb9dcc0 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Tue, 26 Nov 2024 06:33:12 +0100
Subject: [PATCH] [clang][bytecode] Support __builtin_reduce_add

---
 clang/lib/AST/ByteCode/InterpBuiltin.cpp  | 48 ++-
 clang/test/AST/ByteCode/builtin-functions.cpp | 45 +
 2 files changed, 91 insertions(+), 2 deletions(-)

diff --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index b450d8263c30bf..dc7d23f81d3f4e 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -89,13 +89,14 @@ static void pushInteger(InterpState &S, const APSInt &Val, 
QualType QT) {
   std::optional T = S.getContext().classify(QT);
   assert(T);
 
+  unsigned BitWidth = S.getASTContext().getTypeSize(QT);
   if (QT->isSignedIntegerOrEnumerationType()) {
 int64_t V = Val.getSExtValue();
-INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V)); });
+INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V, BitWidth)); });
   } else {
 assert(QT->isUnsignedIntegerOrEnumerationType());
 uint64_t V = Val.getZExtValue();
-INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V)); });
+INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V, BitWidth)); });
   }
 }
 
@@ -137,6 +138,8 @@ static bool retPrimValue(InterpState &S, CodePtr OpPC, 
APValue &Result,
 RET_CASE(PT_Uint32);
 RET_CASE(PT_Sint64);
 RET_CASE(PT_Uint64);
+RET_CASE(PT_IntAP);
+RET_CASE(PT_IntAPS);
   default:
 llvm_unreachable("Unsupported return type for builtin function");
   }
@@ -1684,6 +1687,42 @@ static bool interp__builtin_arithmetic_fence(InterpState 
&S, CodePtr OpPC,
   return true;
 }
 
+static bool interp__builtin_vector_reduce(InterpState &S, CodePtr OpPC,
+  const InterpFrame *Frame,
+  const Function *Func,
+  const CallExpr *Call) {
+  const Pointer &Arg = S.Stk.peek();
+  assert(Arg.getFieldDesc()->isPrimitiveArray());
+
+  unsigned ID = Func->getBuiltinID();
+  if (ID == Builtin::BI__builtin_reduce_add) {
+QualType ElemType = Arg.getFieldDesc()->getElemQualType();
+assert(Call->getType() == ElemType);
+PrimType ElemT = *S.getContext().classify(ElemType);
+unsigned NumElems = Arg.getNumElems();
+
+INT_TYPE_SWITCH(ElemT, {
+  T Sum = Arg.atIndex(0).deref();
+  unsigned BitWidth = Sum.bitWidth();
+  for (unsigned I = 1; I != NumElems; ++I) {
+T Elem = Arg.atIndex(I).deref();
+if (T::add(Sum, Elem, BitWidth, &Sum)) {
+  unsigned OverflowBits = BitWidth + 1;
+  (void)handleOverflow(
+  S, OpPC,
+  (Sum.toAPSInt(OverflowBits) + Elem.toAPSInt(OverflowBits)));
+  return false;
+}
+  }
+  pushInteger(S, Sum, Call->getType());
+});
+
+return true;
+  }
+
+  llvm_unreachable("Unsupported vector reduce builtin");
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
   const InterpFrame *Frame = S.Current;
@@ -2130,6 +2169,11 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BI__builtin_reduce_add:
+if (!interp__builtin_vector_reduce(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
   default:
 S.FFDiag(S.Current->getLocation(OpPC),
  diag::note_invalid_subexpr_in_const_expr)
diff --git a/clang/test/AST/ByteCode/builtin-functions.cpp 
b/clang/test/AST/ByteCode/builtin-functions.cpp
index b5d334178f8213..972d39ca509615 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -990,3 +990,48 @@ namespace BuiltinInImplicitCtor {
   } Foo;
   static_assert(Foo.a == 0, "");
 }
+
+
+typedef double vector4double __attribute__((__vector_size__(32)));
+typedef float vector4float __attribute__((__vector_size__(16)));
+typedef long long vector4long __attribute__((__vector_size__(32)));
+typedef int vector4int __attribute__((__vector_size__(16)));
+typedef unsigned long long vector4ulong __attribute__((__vector_size__(32)));
+typedef unsigned int vector4uint __attribute__((__vector_size__(16)));
+typedef short vector4short __attribute__((__vector_size__(8)));
+typedef char vector4char __attribute__((__vector_size__(4)));
+typedef double vector8double __attribute__((__vector_size__(64)));
+typedef float vector8float __attribute__((__vector_size__(32)));
+typedef long long vector8long __attribute__((__vector_size__(64)));
+typedef int vector8int __attribute__((__vector_size__(32)));
+typedef short vector8short __attribute__((__vector_size__(16)));
+typedef char vector8char __attribute__((__vector_size__(8)));
+
+namespace RecuceAdd {

[clang] [flang] [clang][driver] Special care for -l flags in config files (PR #117573)

2024-12-01 Thread Paul Osmialowski via cfe-commits

pawosm-arm wrote:

> I took a look and I think it may be too awkward to do, as we'd want to run 
> e.g. readelf afterwards. But an example is 
> `lld/test/ELF/as-needed-not-in-regular.s`. The idea being: if 
> `-Wl,--as-needed` is in the config file, do we correctly prune an unnecessary 
> library from a built object, or is the order wrong? We can check that with 
> `llvm-readelf`.

There are two problems here. First, following the readelf path goes too far 
into the linker competences, whatever is set for the linker, the linker is 
obliged to do, and the order of whatever is set for the linker is already 
tested by other `-Wl,` occurrences in the currently available test cases.

Yet your request also exposes another problem, and I can see that further 
comments also mention it. With my patch, there is no way to affect the user's 
command line linker input parameters. So if a config file is a mean for turning 
clang's behavior into the gcc's behavior (AFAIR, gcc always emits 
`-Wl,--as-needed` at the beginning of the linker invocation command line, while 
clang doesn't do that), this patch rejects such possibility. Something more 
clever is needed, the positional idea seems the right one, I could see it like 
this (a config file example, notice the pipe `|` character):

```
-Wall -Wl,--as-needed | -lm -Wl,-Bstatic -lhappy -Wl,-Bdynamic
```

...things after the pipe would be appended at the end of the parameters list 
and only when it is known that there will be the linking. But this would 
require a modification in the config file reading routine, the second list of 
config options would have to be created much earlier than my patch proposes.

Back to the drawing board then.


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


[clang] [llvm] [RISCV] Add Qualcomm uC Xqcia (Arithmetic) extension (PR #118113)

2024-12-01 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lld-x86_64-win` running on 
`as-worker-93` while building `clang,llvm` at step 7 
"test-build-unified-tree-check-all".

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


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

```
Step 7 (test-build-unified-tree-check-all) failure: test (failure)
 TEST 'LLVM-Unit :: Support/./SupportTests.exe/37/87' 
FAILED 
Script(shard):
--
GTEST_OUTPUT=json:C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe-LLVM-Unit-10980-37-87.json
 GTEST_SHUFFLE=0 GTEST_TOTAL_SHARDS=87 GTEST_SHARD_INDEX=37 
C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe
--

Script:
--
C:\a\lld-x86_64-win\build\unittests\Support\.\SupportTests.exe 
--gtest_filter=ProgramEnvTest.CreateProcessLongPath
--
C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(160): 
error: Expected equality of these values:
  0
  RC
Which is: -2

C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp(163): 
error: fs::remove(Twine(LongPath)): did not return errc::success.
error number: 13
error message: permission denied



C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:160
Expected equality of these values:
  0
  RC
Which is: -2

C:\a\lld-x86_64-win\llvm-project\llvm\unittests\Support\ProgramTest.cpp:163
fs::remove(Twine(LongPath)): did not return errc::success.
error number: 13
error message: permission denied







```



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


[clang-tools-extra] [clang-tidy][docs] improve documentation on cppcoreguidelines-narrowing-conversions (#111510) (PR #118209)

2024-12-01 Thread Jonas Toth via cfe-commits

https://github.com/JonasToth updated 
https://github.com/llvm/llvm-project/pull/118209

>From b10c536f66521249a374908f0bd0eb1fe2ff42ad Mon Sep 17 00:00:00 2001
From: Jonas Toth 
Date: Sun, 1 Dec 2024 12:02:13 +0100
Subject: [PATCH] [clang-tidy][docs] improve documentation on
 cppcoreguidelines-narrowing-conversions (#111510)

---
 .../narrowing-conversions.rst | 23 +++
 1 file changed, 23 insertions(+)

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
index 04260e75aa558f..f88f9101d00707 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
@@ -27,6 +27,29 @@ This check will flag:
  - All applications of binary operators with a narrowing conversions.
For example: ``int i; i+= 0.1;``.
 
+Note that arithmetic with integer types may perform implicit conversions if 
the used integer types are smaller than ``int``.
+These rules are documented under `"Integral Promotion" on this 
cppreference.com 
`_
+page. The following example demonstrates this behavior and can be explored 
with `cppinsights.io `_.
+
+.. code-block:: c++
+
+   // The following function definition demonstrates usage of arithmetic with 
integer types smaller than `int`
+   // and how the narrowing conversion happens implicitly.
+   void computation(short argument1, short argument2) {
+ // Arithmetic written by humans:
+ short result = argument1 + argument2;
+ // Arithmetic actually performed by C++:
+ short result = static_cast(static_cast(argument1) + 
static_cast(argument2));
+   }
+
+   void recommended_with_gsl(short argument1, short argument2) {
+ // This will throw an exception if the conversion will be lossy.
+ short result = gsl::narrow(argument1 + argument2);
+ // This will just cast through and may yield incorrect results if the sum 
is not representable
+ // by `short`.
+ short result = gsl::narrow_cast(argument1 + argument2);
+   }
+
 
 Options
 ---

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


[clang] [clang-format][CMake] Generate formatting options docs during build (PR #113739)

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

owenca wrote:

> Can you explicate on what your requirements are here? I don't see why just 
> wrapping the python script in CMake does anything tangible here. Having a 
> build target that modifies the source directory is also weird and something 
> that we should avoid if possible, in my opinion.

>From https://github.com/llvm/llvm-project/pull/111513#issuecomment-2408412143:
> Anyway, my current workflow is:
> 
> 1. Edit files in clang/lib/Format and clang/unittests/Format.
> 2. Edit clang/include/clang/Format/Format.h if needed.
> 3. Run ninja FormatTests.
> 4. Run cd clang/docs/tools && dump_format_style.py if Step 2 above wasn't 
> skipped.
> 5. Run the unit tests.
> 6. Run git commit -a.
> 
> It would be nice if I didn't have to run step 4 manually.

With #111513, I no longer need to remind myself to run the python script when 
testing a patch. Please note that we rarely need to do `ninja 
check-clang-format` to run the lit tests, which takes an extra hour or two.

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


[clang-tools-extra] [clang-tidy][docs] improve documentation on cppcoreguidelines-narrowing-conversions (#111510) (PR #118209)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




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

Author: Jonas Toth (JonasToth)


Changes

This PR improves the docs for this check to include an example of hidden 
narrowing conversions from the integer promotion rules in arithmetic.

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


1 Files Affected:

- (modified) 
clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
 (+15) 


``diff
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
index 04260e75aa558f..f4d1976ad4c688 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
@@ -27,6 +27,21 @@ This check will flag:
  - All applications of binary operators with a narrowing conversions.
For example: ``int i; i+= 0.1;``.
 
+Note that arithmetic with integer types may perform implicit conversions if 
the used integer types are smaller than ``int``.
+These rules are documented under `"Integral Promotion" on this 
cppreference.com 
`_
+page. The following example demonstrates this behavior and can be explored 
with `cppinsights.io `_.
+
+.. code-block:: c++
+
+   // The following function definition demonstrates usage of arithmetic with 
integer types smaller than `int`
+   // and how the narrowing conversion happens implicitly.
+   void computation(short argument1, short argument2) {
+ // Arithmetic written by humans:
+ short result = argument1 + argument2;
+ // Arithmetic actually performed by C++:
+ short result = static_cast(static_cast(argument1) + 
static_cast(argument2));
+   }
+
 
 Options
 ---

``




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


[clang-tools-extra] [clang-tidy][docs] improve documentation on cppcoreguidelines-narrowing-conversions (#111510) (PR #118209)

2024-12-01 Thread Jonas Toth via cfe-commits

https://github.com/JonasToth created 
https://github.com/llvm/llvm-project/pull/118209

This PR improves the docs for this check to include an example of hidden 
narrowing conversions from the integer promotion rules in arithmetic.

>From c662917b248335c85714e791f55e12e834baa87d Mon Sep 17 00:00:00 2001
From: Jonas Toth 
Date: Sun, 1 Dec 2024 12:02:13 +0100
Subject: [PATCH] [clang-tidy][docs] improve documentation on
 cppcoreguidelines-narrowing-conversions (#111510)

---
 .../cppcoreguidelines/narrowing-conversions.rst   | 15 +++
 1 file changed, 15 insertions(+)

diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
index 04260e75aa558f..f4d1976ad4c688 100644
--- 
a/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
+++ 
b/clang-tools-extra/docs/clang-tidy/checks/cppcoreguidelines/narrowing-conversions.rst
@@ -27,6 +27,21 @@ This check will flag:
  - All applications of binary operators with a narrowing conversions.
For example: ``int i; i+= 0.1;``.
 
+Note that arithmetic with integer types may perform implicit conversions if 
the used integer types are smaller than ``int``.
+These rules are documented under `"Integral Promotion" on this 
cppreference.com 
`_
+page. The following example demonstrates this behavior and can be explored 
with `cppinsights.io `_.
+
+.. code-block:: c++
+
+   // The following function definition demonstrates usage of arithmetic with 
integer types smaller than `int`
+   // and how the narrowing conversion happens implicitly.
+   void computation(short argument1, short argument2) {
+ // Arithmetic written by humans:
+ short result = argument1 + argument2;
+ // Arithmetic actually performed by C++:
+ short result = static_cast(static_cast(argument1) + 
static_cast(argument2));
+   }
+
 
 Options
 ---

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


[clang] [clang-format][CMake] Generate formatting options docs during build (PR #113739)

2024-12-01 Thread Aiden Grossman via cfe-commits

boomanaiden154 wrote:

> That and to also ensure that the edited Format.h doesn't break the python 
> script.

Makes sense. #118154 would cover that too.

> If we are to leave the generated part of the rst file in the repo, 
> https://github.com/llvm/llvm-project/pull/111513 would satisfy my 
> requirements nicely. Something like 
> https://github.com/llvm/llvm-project/pull/118154 may be a useful addition.

Can you explicate on what your requirements are here? I don't see why just 
wrapping the python script in CMake does anything tangible here. Having a build 
target that modifies the source directory is also weird and something that we 
should avoid if possible, in my opinion.

> That would be nice.

https://github.com/llvm/llvm-project/pull/118159

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


[clang] 6881c6d - [RISCV] Add Qualcomm uC Xqcia (Arithmetic) extension (#118113)

2024-12-01 Thread via cfe-commits

Author: Sudharsan Veeravalli
Date: 2024-12-01T17:06:22+05:30
New Revision: 6881c6d2a6ef2b9f1736afb124b2486d6b8bc603

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

LOG: [RISCV] Add Qualcomm uC Xqcia (Arithmetic) extension (#118113)

This extension adds 11 instructions that perform integer arithmetic.

The current spec can be found at:
https://github.com/quic/riscv-unified-db/releases/latest

This patch adds assembler only support.

Added: 
llvm/test/MC/RISCV/xqcia-invalid.s
llvm/test/MC/RISCV/xqcia-valid.s

Modified: 
clang/test/Driver/print-supported-extensions-riscv.c
llvm/docs/RISCVUsage.rst
llvm/docs/ReleaseNotes.md
llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
llvm/lib/Target/RISCV/MCTargetDesc/RISCVBaseInfo.h
llvm/lib/Target/RISCV/RISCVFeatures.td
llvm/lib/Target/RISCV/RISCVInstrInfoXqci.td
llvm/lib/TargetParser/RISCVISAInfo.cpp
llvm/test/CodeGen/RISCV/attributes.ll
llvm/unittests/TargetParser/RISCVISAInfoTest.cpp

Removed: 




diff  --git a/clang/test/Driver/print-supported-extensions-riscv.c 
b/clang/test/Driver/print-supported-extensions-riscv.c
index 70b7a96daf1daf..9df903115b57c1 100644
--- a/clang/test/Driver/print-supported-extensions-riscv.c
+++ b/clang/test/Driver/print-supported-extensions-riscv.c
@@ -188,6 +188,7 @@
 // CHECK-NEXT: smctr1.0   'Smctr' (Control Transfer 
Records Machine Level)
 // CHECK-NEXT: ssctr1.0   'Ssctr' (Control Transfer 
Records Supervisor Level)
 // CHECK-NEXT: svukte   0.3   'Svukte' 
(Address-Independent Latency of User-Mode Faults to Supervisor Addresses)
+// CHECK-NEXT: xqcia0.2   'Xqcia' (Qualcomm uC 
Arithmetic Extension)
 // CHECK-NEXT: xqcicsr  0.2   'Xqcicsr' (Qualcomm uC CSR 
Extension)
 // CHECK-NEXT: xqcisls  0.2   'Xqcisls' (Qualcomm uC 
Scaled Load Store Extension)
 // CHECK-EMPTY:

diff  --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 230bf66fcf461b..3978332b1149a9 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -426,6 +426,9 @@ The current vendor extensions supported are:
 ``Xwchc``
   LLVM implements `the custom compressed opcodes present in some QingKe cores` 
by WCH / Nanjing Qinheng Microelectronics. The vendor refers to these opcodes 
by the name "XW".
 
+``experimental-Xqcia``
+  LLVM implements `version 0.2 of the Qualcomm uC Arithmetic extension 
specification `__ by 
Qualcomm.  All instructions are prefixed with `qc.` as described in the 
specification. These instructions are only available for riscv32.
+
 ``experimental-Xqcicsr``
   LLVM implements `version 0.2 of the Qualcomm uC CSR extension specification 
`__ by Qualcomm.  All 
instructions are prefixed with `qc.` as described in the specification. These 
instructions are only available for riscv32.
 

diff  --git a/llvm/docs/ReleaseNotes.md b/llvm/docs/ReleaseNotes.md
index 6d50839d68953e..dc3f3aeb735f87 100644
--- a/llvm/docs/ReleaseNotes.md
+++ b/llvm/docs/ReleaseNotes.md
@@ -215,6 +215,8 @@ Changes to the RISC-V Backend
   extension.
 * Adds experimental assembler support for the Qualcomm uC 'Xqcisls` (Scaled 
Load Store)
   extension.
+* Adds experimental assembler support for the Qualcomm uC 'Xqcia` (Arithmetic)
+  extension.
 
 Changes to the WebAssembly Backend
 --

diff  --git a/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp 
b/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
index b843bb5ae43100..7c91dc07bbd3e5 100644
--- a/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
+++ b/llvm/lib/Target/RISCV/AsmParser/RISCVAsmParser.cpp
@@ -717,6 +717,7 @@ struct RISCVOperand final : public MCParsedAsmOperand {
   bool isUImm6() const { return IsUImm<6>(); }
   bool isUImm7() const { return IsUImm<7>(); }
   bool isUImm8() const { return IsUImm<8>(); }
+  bool isUImm11() const { return IsUImm<11>(); }
   bool isUImm16() const { return IsUImm<16>(); }
   bool isUImm20() const { return IsUImm<20>(); }
   bool isUImm32() const { return IsUImm<32>(); }
@@ -1563,6 +1564,8 @@ bool RISCVAsmParser::matchAndEmitInstruction(SMLoc IDLoc, 
unsigned &Opcode,
 return generateImmOutOfRangeError(
 Operands, ErrorInfo, -(1 << 9), (1 << 9) - 16,
 "immediate must be a multiple of 16 bytes and non-zero in the range");
+  case Match_InvalidUImm11:
+return generateImmOutOfRangeError(Operands, ErrorInfo, 0, (1 << 11) - 1);
   case Match_InvalidSImm12:
 return generateImmOutOfRangeError(
 Operands, ErrorInfo, -(1 <

[clang] [llvm] [RISCV] Add Qualcomm uC Xqcia (Arithmetic) extension (PR #118113)

2024-12-01 Thread Sudharsan Veeravalli via cfe-commits

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread Nikita Popov via cfe-commits

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

LGTM, thanks!

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread Nikita Popov via cfe-commits


@@ -1898,6 +1882,60 @@ static Instruction *foldSelectICmpEq(SelectInst &SI, 
ICmpInst *ICI,
   return nullptr;
 }
 
+/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
+/// This allows for better canonicalization.
+static Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
+   Value *FalseVal,
+   IRBuilderBase &Builder) {
+  BinaryOperator *BOp;
+  Constant *C1, *C2, *C3;
+  Value *X;
+  ICmpInst::Predicate Predicate;
+
+  if (!match(Cmp, m_ICmp(Predicate, m_Value(X), m_Constant(C1
+return nullptr;
+
+  if (!ICmpInst::isRelational(Predicate))
+return nullptr;
+
+  if (match(TrueVal, m_Constant())) {
+std::swap(FalseVal, TrueVal);
+Predicate = ICmpInst::getInversePredicate(Predicate);
+  }
+
+  if (!match(TrueVal, m_BinOp(BOp)) || !match(FalseVal, m_Constant(C3)))
+return nullptr;
+
+  unsigned Opcode = BOp->getOpcode();
+
+  if (Instruction::isIntDivRem(Opcode))
+return nullptr;
+
+  if (!match(BOp, m_OneUse(m_BinOp(m_Specific(X), m_Constant(C2)
+return nullptr;
+
+  Value *RHS;
+  SelectPatternFlavor SPF;
+  const DataLayout &Layout = BOp->getDataLayout();

nikic wrote:

```suggestion
  const DataLayout &DL = BOp->getDataLayout();
```
This one always gets the same name :)

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread Nikita Popov via cfe-commits


@@ -1898,6 +1882,60 @@ static Instruction *foldSelectICmpEq(SelectInst &SI, 
ICmpInst *ICI,
   return nullptr;
 }
 
+/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
+/// This allows for better canonicalization.
+static Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
+   Value *FalseVal,
+   IRBuilderBase &Builder) {
+  BinaryOperator *BOp;
+  Constant *C1, *C2, *C3;
+  Value *X;
+  ICmpInst::Predicate Predicate;
+
+  if (!match(Cmp, m_ICmp(Predicate, m_Value(X), m_Constant(C1
+return nullptr;
+
+  if (!ICmpInst::isRelational(Predicate))
+return nullptr;
+
+  if (match(TrueVal, m_Constant())) {
+std::swap(FalseVal, TrueVal);
+Predicate = ICmpInst::getInversePredicate(Predicate);
+  }
+
+  if (!match(TrueVal, m_BinOp(BOp)) || !match(FalseVal, m_Constant(C3)))
+return nullptr;
+
+  unsigned Opcode = BOp->getOpcode();
+
+  if (Instruction::isIntDivRem(Opcode))

nikic wrote:

This check deserves a comment -- am I understanding correctly that this is 
profitability heuristic, not a correctness check?

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread Nikita Popov via cfe-commits

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


[clang] fix access checking about function overloading (PR #107768)

2024-12-01 Thread Zhikai Zeng via cfe-commits

https://github.com/Backl1ght updated 
https://github.com/llvm/llvm-project/pull/107768

>From 694b7dd640676c83a25e79b1f4ba1cb8e6cbb87b Mon Sep 17 00:00:00 2001
From: Backl1ght 
Date: Sun, 1 Dec 2024 16:45:28 +0800
Subject: [PATCH] fix

---
 clang/docs/ReleaseNotes.rst|  1 +
 clang/lib/Sema/SemaOverload.cpp|  3 +++
 clang/test/CXX/class.access/p4.cpp | 16 ++--
 3 files changed, 18 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e44aefa90ab386..0de249ced8309a 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -763,6 +763,7 @@ Bug Fixes to C++ Support
 - Fixed a bug where bounds of partially expanded pack indexing expressions 
were checked too early. (#GH116105)
 - Fixed an assertion failure caused by using ``consteval`` in condition in 
consumed analyses. (#GH117385)
 - Fix a crash caused by incorrect argument position in merging deduced 
template arguments. (#GH113659)
+- Fix a bug where private access specifier of overloaded function not 
respected. (#GH107629)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index 4c9e37bd286dee..35389957adf32d 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -16305,6 +16305,9 @@ ExprResult Sema::FixOverloadedFunctionReference(Expr 
*E, DeclAccessPair Found,
   }
 
   if (UnresolvedLookupExpr *ULE = dyn_cast(E)) {
+if (Found.getAccess() == AS_none) {
+  CheckUnresolvedLookupAccess(ULE, Found);
+}
 // FIXME: avoid copy.
 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = nullptr;
 if (ULE->hasExplicitTemplateArgs()) {
diff --git a/clang/test/CXX/class.access/p4.cpp 
b/clang/test/CXX/class.access/p4.cpp
index ca98c9f90bd89e..6d4c8c004911db 100644
--- a/clang/test/CXX/class.access/p4.cpp
+++ b/clang/test/CXX/class.access/p4.cpp
@@ -21,11 +21,13 @@ namespace test0 {
   public:
 void foo(Public&);
   protected:
-void foo(Protected&); // expected-note 2 {{declared protected here}}
+void foo(Protected&); // expected-note 4 {{declared protected here}}
   private:
-void foo(Private&); // expected-note 2 {{declared private here}}
+void foo(Private&); // expected-note 4 {{declared private here}}
   };
 
+  class B : public A {};
+
   void test(A *op) {
 op->foo(PublicInst);
 op->foo(ProtectedInst); // expected-error {{'foo' is a protected member}}
@@ -35,6 +37,16 @@ namespace test0 {
 void (A::*b)(Protected&) = &A::foo; // expected-error {{'foo' is a 
protected member}}
 void (A::*c)(Private&) = &A::foo; // expected-error {{'foo' is a private 
member}}
   }
+
+  void test(B *op) {
+op->foo(PublicInst);
+op->foo(ProtectedInst); // expected-error {{'foo' is a protected member}}
+op->foo(PrivateInst); // expected-error {{'foo' is a private member}}
+
+void (B::*a)(Public&) = &B::foo;
+void (B::*b)(Protected&) = &B::foo; // expected-error {{'foo' is a 
protected member}}
+void (B::*c)(Private&) = &B::foo; // expected-error {{'foo' is a private 
member}}
+  }
 }
 
 // Member operators.

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


[clang] [Driver] Do not add gno-column-info when using sampling PGO (PR #117954)

2024-12-01 Thread Haohai Wen via cfe-commits

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


[clang] 22417ec - [Driver] Do not add gno-column-info when using sampling PGO (#117954)

2024-12-01 Thread via cfe-commits

Author: Haohai Wen
Date: 2024-12-01T20:54:38+08:00
New Revision: 22417ec6cca0ed8ccecb0c2b77011e591378fd2a

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

LOG: [Driver] Do not add gno-column-info when using sampling PGO (#117954)

Column info is important for sampling PGO to generate/load profile file.
On windows, it will be automatically added when using -gdwarf to
generate
profile file. It should also be generated when fprofile-sample-use= is
used.

Added: 


Modified: 
clang/lib/Driver/ToolChains/Clang.cpp
clang/test/Driver/codeview-column-info.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 217c1a845f0a47..b6d39a5186b794 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -4690,15 +4690,15 @@ renderDebugOptions(const ToolChain &TC, const Driver 
&D, const llvm::Triple &T,
   Args.ClaimAllArgs(options::OPT_g_flags_Group);
 
   // Column info is included by default for everything except SCE and
-  // CodeView. Clang doesn't track end columns, just starting columns, which,
-  // in theory, is fine for CodeView (and PDB).  In practice, however, the
-  // Microsoft debuggers don't handle missing end columns well, and the AIX
-  // debugger DBX also doesn't handle the columns well, so it's better not to
-  // include any column info.
+  // CodeView if not use sampling PGO. Clang doesn't track end columns, just
+  // starting columns, which, in theory, is fine for CodeView (and PDB).  In
+  // practice, however, the Microsoft debuggers don't handle missing end 
columns
+  // well, and the AIX debugger DBX also doesn't handle the columns well, so
+  // it's better not to include any column info.
   if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
 (void)checkDebugInfoOption(A, Args, D, TC);
   if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
-!EmitCodeView &&
+!(EmitCodeView && !getLastProfileSampleUseArg(Args)) &&
 (DebuggerTuning != llvm::DebuggerKind::SCE &&
  DebuggerTuning != llvm::DebuggerKind::DBX)))
 CmdArgs.push_back("-gno-column-info");

diff  --git a/clang/test/Driver/codeview-column-info.c 
b/clang/test/Driver/codeview-column-info.c
index 4cabefac06e648..0f1671a73acd57 100644
--- a/clang/test/Driver/codeview-column-info.c
+++ b/clang/test/Driver/codeview-column-info.c
@@ -14,5 +14,6 @@
 // CHECK: "-gno-column-info"
 
 // RUN: %clang_cl -### /Z7 -gcolumn-info -- %s 2>&1 | FileCheck 
--check-prefix=COLUMN %s
+// RUN: %clang_cl -### --target=x86_64-windows-msvc /Z7 
-fprofile-sample-use=%S/Inputs/file.prof -- %s 2>&1 | FileCheck 
--check-prefix=COLUMN %s
 
 // COLUMN-NOT: "-gno-column-info"



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


[clang] Reland [Clang] skip default argument instantiation for non-defining friend declarations to meet [dcl.fct.default] p4 (PR #115487)

2024-12-01 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk updated 
https://github.com/llvm/llvm-project/pull/115487

>From 5e24d212f797b5fa1b6da1526c807046373d3c21 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Fri, 8 Nov 2024 16:13:17 +0200
Subject: [PATCH 1/6] [Clang] skip default argument instantiation for
 non-defining friend declarations to meet [dcl.fct.default] p4

---
 clang/docs/ReleaseNotes.rst   |  2 +
 .../lib/Sema/SemaTemplateInstantiateDecl.cpp  |  4 ++
 clang/test/CXX/temp/temp.res/p4.cpp   | 43 +++
 3 files changed, 49 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d0c43ff11f7bae..e8cf6fc50a1290 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -636,6 +636,8 @@ Bug Fixes to C++ Support
   an implicitly instantiated class template specialization. (#GH51051)
 - Fixed an assertion failure caused by invalid enum forward declarations. 
(#GH112208)
 - Name independent data members were not correctly initialized from default 
member initializers. (#GH114069)
+- Fixed an assertion failure caused by invalid default argument substitutions 
in non-defining
+  friend declarations. (#GH113324).
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 5a001843e2ba46..200519c71c57ab 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4694,6 +4694,10 @@ bool Sema::InstantiateDefaultArgument(SourceLocation 
CallLoc, FunctionDecl *FD,
   ParmVarDecl *Param) {
   assert(Param->hasUninstantiatedDefaultArg());
 
+  if (FD->getFriendObjectKind() != Decl::FOK_None &&
+  !FD->getTemplateInstantiationPattern())
+return true;
+
   // Instantiate the expression.
   //
   // FIXME: Pass in a correct Pattern argument, otherwise
diff --git a/clang/test/CXX/temp/temp.res/p4.cpp 
b/clang/test/CXX/temp/temp.res/p4.cpp
index f54d8649f5da88..cf6c45b4c351c5 100644
--- a/clang/test/CXX/temp/temp.res/p4.cpp
+++ b/clang/test/CXX/temp/temp.res/p4.cpp
@@ -185,3 +185,46 @@ template struct S {
   friend void X::f(T::type);
 };
 }
+
+namespace GH113324 {
+template  struct S1 {
+  friend void f1(S1, int = 0); // expected-error {{friend declaration 
specifying a default argument must be a definition}}
+  friend void f2(S1 a, S1 = decltype(a){}); // expected-error {{friend 
declaration specifying a default argument must be a definition}}
+};
+
+template  using alias = int;
+template  struct S2 {
+  // FIXME: We miss diagnosing the default argument instantiation failure
+  // (forming reference to void)
+  friend void f3(S2, int a = alias(1)); // expected-error {{friend 
declaration specifying a default argument must be a definition}}
+};
+
+struct S3 {
+  friend void f4(S3, int = 42) { }
+};
+
+template  using __enable_if_t = int;
+template  struct S4 {
+  static const int value = v;
+};
+struct S5 {
+  template <__enable_if_t::value, int> = 0>
+  S5(const char *);
+};
+struct S6 {
+  template 
+  friend void f5(int, S6, a, b, S5 = "") { }
+};
+
+void test() {
+  f1(S1<>{});
+  f2(S1<>{});
+  f3(S2());
+
+  S3 s3;
+  f4(s3);
+
+  S6 s6;
+  auto result = f5(0, s6, [] {}, [] {}); // expected-error {{variable has 
incomplete type 'void}}
+}
+} // namespace GH113324

>From 3ad3b6c5f35730be32f4f6ba2dc8d19f53be0442 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Fri, 8 Nov 2024 16:53:39 +0200
Subject: [PATCH 2/6] update comments

---
 clang/lib/Sema/SemaTemplateInstantiateDecl.cpp | 7 +++
 1 file changed, 7 insertions(+)

diff --git a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp 
b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
index 200519c71c57ab..0bbab95001ad8e 100644
--- a/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
@@ -4694,6 +4694,13 @@ bool Sema::InstantiateDefaultArgument(SourceLocation 
CallLoc, FunctionDecl *FD,
   ParmVarDecl *Param) {
   assert(Param->hasUninstantiatedDefaultArg());
 
+  // FIXME: We don't track member specialization info for non-defining
+  // friend declarations, so we will not be able to later find the function
+  // pattern. As a workaround, don't instantiate the default argument in this
+  // case. This is correct per wording and only an error recovery issue, as per
+  // [dcl.fct.default]p4:
+  //   if a friend declaration D specifies a default argument expression,
+  //   that declaration shall be a definition.
   if (FD->getFriendObjectKind() != Decl::FOK_None &&
   !FD->getTemplateInstantiationPattern())
 return true;

>From 09215dea0212368ef54956d8464788cc4b88cc02 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Thu, 21 Nov 2024 16:56:11 +0200
Subject: [PATCH 3/6] move cases that cause code generation failures to the
 appropriate folder

---
 clang/test/CXX/temp/temp.res/p4.cpp | 23

[clang] Add `.cjs` extension handling for JavaScript Language. (PR #118188)

2024-12-01 Thread Jim B via cfe-commits

https://github.com/d3x0r updated 
https://github.com/llvm/llvm-project/pull/118188

>From 8ce527dc2cc7ac285f782648838664491abffc30 Mon Sep 17 00:00:00 2001
From: d3x0r 
Date: Sat, 30 Nov 2024 02:32:40 -0800
Subject: [PATCH 1/2] Add *.cjs handling for JavaScript Language.

---
 clang/lib/Format/Format.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/Format/Format.cpp b/clang/lib/Format/Format.cpp
index ee52972ce66f4a..dcaac4b0d42cc5 100644
--- a/clang/lib/Format/Format.cpp
+++ b/clang/lib/Format/Format.cpp
@@ -3950,6 +3950,7 @@ static FormatStyle::LanguageKind 
getLanguageByFileName(StringRef FileName) {
 return FormatStyle::LK_Java;
   if (FileName.ends_with_insensitive(".js") ||
   FileName.ends_with_insensitive(".mjs") ||
+  FileName.ends_with_insensitive(".cjs") ||
   FileName.ends_with_insensitive(".ts")) {
 return FormatStyle::LK_JavaScript; // (module) JavaScript or TypeScript.
   }

>From 3f28f82d1dc87006aceb0e0c7bd95c460d70ccd0 Mon Sep 17 00:00:00 2001
From: d3x0r 
Date: Sun, 1 Dec 2024 13:04:01 -0800
Subject: [PATCH 2/2] Also update docs, command line help info,
 git-clang-format

---
 clang/docs/ClangFormat.rst| 2 +-
 clang/tools/clang-format/ClangFormat.cpp  | 2 +-
 clang/tools/clang-format/git-clang-format | 2 +-
 3 files changed, 3 insertions(+), 3 deletions(-)

diff --git a/clang/docs/ClangFormat.rst b/clang/docs/ClangFormat.rst
index e17d741b0a00eb..10ddca8685e941 100644
--- a/clang/docs/ClangFormat.rst
+++ b/clang/docs/ClangFormat.rst
@@ -49,7 +49,7 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
  supported:
CSharp: .cs
Java: .java
-   JavaScript: .mjs .js .ts
+   JavaScript: .mjs .js .ts .cjs
Json: .json
Objective-C: .m .mm
Proto: .proto .protodevel
diff --git a/clang/tools/clang-format/ClangFormat.cpp 
b/clang/tools/clang-format/ClangFormat.cpp
index 5481bb6b87503c..a3e80964c68028 100644
--- a/clang/tools/clang-format/ClangFormat.cpp
+++ b/clang/tools/clang-format/ClangFormat.cpp
@@ -87,7 +87,7 @@ static cl::opt AssumeFileName(
  "supported:\n"
  "  CSharp: .cs\n"
  "  Java: .java\n"
- "  JavaScript: .mjs .js .ts\n"
+ "  JavaScript: .cjs .mjs .js .ts\n"
  "  Json: .json\n"
  "  Objective-C: .m .mm\n"
  "  Proto: .proto .protodevel\n"
diff --git a/clang/tools/clang-format/git-clang-format 
b/clang/tools/clang-format/git-clang-format
index 6a2a2a22ec5c2b..f965adae42f435 100755
--- a/clang/tools/clang-format/git-clang-format
+++ b/clang/tools/clang-format/git-clang-format
@@ -94,7 +94,7 @@ def main():
   # Other languages that clang-format supports
   'proto', 'protodevel',  # Protocol Buffers
   'java',  # Java
-  'mjs', 'js',  # JavaScript
+  'cjs', 'mjs', 'js',  # JavaScript
   'ts',  # TypeScript
   'cs',  # C Sharp
   'json',  # Json

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


[clang] [Clang] Change placeholder from `undef` to `poison` (PR #117064)

2024-12-01 Thread Pedro Lobo via cfe-commits

pedroclobo wrote:

cc @nunoplopes 

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


[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits

https://github.com/5chmidti updated 
https://github.com/llvm/llvm-project/pull/113837

>From 8170641109c09e55b1530081e103a1e919eb8bfc Mon Sep 17 00:00:00 2001
From: Julian Schmidt 
Date: Sun, 27 Oct 2024 21:49:34 +0100
Subject: [PATCH 1/6] [clang-tidy] do not expand macros in modernize-use-using
 fix

Previously, the implementation used the printed type, which contains the
macro arguments expanded (also deleting comments). Instead, this
check can be more surgical and keep the actual written type as is,
keeping macros unexpanded.

Fixes #33760, #37846
---
 .../clang-tidy/modernize/UseUsingCheck.cpp| 71 +++
 .../clang-tidy/modernize/UseUsingCheck.h  |  1 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 +
 .../checkers/modernize/use-using.cpp  | 36 --
 4 files changed, 93 insertions(+), 18 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
index 24eefdb082eb32..74764d95d90520 100644
--- a/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/UseUsingCheck.cpp
@@ -7,9 +7,12 @@
 
//===--===//
 
 #include "UseUsingCheck.h"
-#include "clang/AST/ASTContext.h"
+#include "../utils/LexerUtils.h"
 #include "clang/AST/DeclGroup.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
 #include "clang/Lex/Lexer.h"
+#include 
 
 using namespace clang::ast_matchers;
 namespace {
@@ -119,14 +122,55 @@ void UseUsingCheck::check(const MatchFinder::MatchResult 
&Result) {
 return;
   }
 
-  PrintingPolicy PrintPolicy(getLangOpts());
-  PrintPolicy.SuppressScope = true;
-  PrintPolicy.ConstantArraySizeAsWritten = true;
-  PrintPolicy.UseVoidForZeroParams = false;
-  PrintPolicy.PrintInjectedClassNameWithArguments = false;
+  const TypeLoc TL = MatchedDecl->getTypeSourceInfo()->getTypeLoc();
+
+  auto [Type, QualifierStr] = [MatchedDecl, &Result, this,
+   &TL]() -> std::pair {
+SourceRange TypeRange = TL.getSourceRange();
+
+// Function pointer case, get the left and right side of the identifier
+// without the identifier.
+if (TypeRange.fullyContains(MatchedDecl->getLocation())) {
+  return {(Lexer::getSourceText(
+   CharSourceRange::getCharRange(TL.getBeginLoc(),
+ MatchedDecl->getLocation()),
+   *Result.SourceManager, getLangOpts()) +
+   Lexer::getSourceText(
+   CharSourceRange::getCharRange(
+   Lexer::getLocForEndOfToken(MatchedDecl->getLocation(), 
0,
+  *Result.SourceManager,
+  getLangOpts()),
+   Lexer::getLocForEndOfToken(TL.getEndLoc(), 0,
+  *Result.SourceManager,
+  getLangOpts())),
+   *Result.SourceManager, getLangOpts()))
+  .str(),
+  ""};
+}
+
+StringRef ExtraReference = "";
+if (MainTypeEndLoc.isValid() && TypeRange.fullyContains(MainTypeEndLoc)) {
+  const SourceLocation Tok = utils::lexer::findPreviousAnyTokenKind(
+  MatchedDecl->getLocation(), *Result.SourceManager, getLangOpts(),
+  tok::TokenKind::star, tok::TokenKind::amp, tok::TokenKind::comma,
+  tok::TokenKind::kw_typedef);
+
+  ExtraReference = Lexer::getSourceText(
+  CharSourceRange::getCharRange(Tok, Tok.getLocWithOffset(1)),
+  *Result.SourceManager, getLangOpts());
 
-  std::string Type = MatchedDecl->getUnderlyingType().getAsString(PrintPolicy);
-  std::string Name = MatchedDecl->getNameAsString();
+  if (ExtraReference != "*" && ExtraReference != "&")
+ExtraReference = "";
+
+  if (MainTypeEndLoc.isValid())
+TypeRange.setEnd(MainTypeEndLoc);
+}
+return {Lexer::getSourceText(CharSourceRange::getTokenRange(TypeRange),
+ *Result.SourceManager, getLangOpts())
+.str(),
+ExtraReference.str()};
+  }();
+  StringRef Name = MatchedDecl->getName();
   SourceRange ReplaceRange = MatchedDecl->getSourceRange();
 
   // typedefs with multiple comma-separated definitions produce multiple
@@ -143,7 +187,8 @@ void UseUsingCheck::check(const MatchFinder::MatchResult 
&Result) {
 // This is the first (and possibly the only) TypedefDecl in a typedef. Save
 // Type and Name in case we find subsequent TypedefDecl's in this typedef.
 FirstTypedefType = Type;
-FirstTypedefName = Name;
+FirstTypedefName = Name.str();
+MainTypeEndLoc = TL.getEndLoc();
   } else {
 // This is additional TypedefDecl in a comma-separated typedef declaration.
 // Start replacement *after* prior replac

[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits


@@ -119,14 +122,55 @@ void UseUsingCheck::check(const MatchFinder::MatchResult 
&Result) {
 return;
   }
 
-  PrintingPolicy PrintPolicy(getLangOpts());
-  PrintPolicy.SuppressScope = true;
-  PrintPolicy.ConstantArraySizeAsWritten = true;
-  PrintPolicy.UseVoidForZeroParams = false;
-  PrintPolicy.PrintInjectedClassNameWithArguments = false;
+  const TypeLoc TL = MatchedDecl->getTypeSourceInfo()->getTypeLoc();
+
+  auto [Type, QualifierStr] = [MatchedDecl, &Result, this,
+   &TL]() -> std::pair {
+SourceRange TypeRange = TL.getSourceRange();
+
+// Function pointer case, get the left and right side of the identifier
+// without the identifier.
+if (TypeRange.fullyContains(MatchedDecl->getLocation())) {
+  return {(Lexer::getSourceText(
+   CharSourceRange::getCharRange(TL.getBeginLoc(),
+ MatchedDecl->getLocation()),
+   *Result.SourceManager, getLangOpts()) +
+   Lexer::getSourceText(
+   CharSourceRange::getCharRange(
+   Lexer::getLocForEndOfToken(MatchedDecl->getLocation(), 
0,
+  *Result.SourceManager,
+  getLangOpts()),
+   Lexer::getLocForEndOfToken(TL.getEndLoc(), 0,
+  *Result.SourceManager,
+  getLangOpts())),
+   *Result.SourceManager, getLangOpts()))
+  .str(),
+  ""};
+}

5chmidti wrote:

Is something like this what you had in mind?

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


[clang-tools-extra] [clang-tidy] use specified type verbatim in modernize-use-using fix (PR #113837)

2024-12-01 Thread Julian Schmidt via cfe-commits

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

I noticed some more issues that this is fixing, so I've added their examples as 
test-cases

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


[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

@llvm/pr-subscribers-clang-driver

Author: Zhaoxin Yang (ylzsx)


Changes

Mainly including the following LoongArch specific options: -m[no-]lsx, 
-m[no-]lasx, -msimd=, -m[no-]frecipe, -m[no-]lam-bh, -m[no-]lamcas, 
-m[no-]ld-seq-sa, -m[no-]div32,
-m[no-]annotate-tablejump

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


3 Files Affected:

- (modified) clang/include/clang/Driver/Options.td (+2-1) 
- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+8) 
- (added) flang/test/Driver/options-loongarch.f90 (+43) 


``diff
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9c356c9d2ea4ef..7b8e2660192580 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -240,7 +240,8 @@ def m_riscv_Features_Group : OptionGroup<"">,
 def m_ve_Features_Group : OptionGroup<"">,
   Group, DocName<"VE">;
 def m_loongarch_Features_Group : OptionGroup<"">,
- Group, DocName<"LoongArch">;
+ Group, DocName<"LoongArch">,
+ Visibility<[ClangOption, CLOption, 
FlangOption]>;
 
 def m_libc_Group : OptionGroup<"">, Group,
Flags<[HelpHidden]>;
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8c18c88fbde7f7..02323b90b65473 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -213,6 +213,14 @@ void Flang::AddLoongArch64TargetArgs(const ArgList &Args,
   D.Diag(diag::err_drv_argument_not_allowed_with) << "-mabi" << V;
 }
   }
+
+  if (const Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
+ options::OPT_mno_annotate_tablejump)) {
+if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-loongarch-annotate-tablejump");
+}
+  }
 }
 
 void Flang::AddPPCTargetArgs(const ArgList &Args,
diff --git a/flang/test/Driver/options-loongarch.f90 
b/flang/test/Driver/options-loongarch.f90
new file mode 100644
index 00..717bf6385b06d7
--- /dev/null
+++ b/flang/test/Driver/options-loongarch.f90
@@ -0,0 +1,43 @@
+!! This test tests options from clang, which are also supported by flang in 
LoongArch.
+
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlsx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lsx %s -### 2>&1 | 
FileCheck --check-prefixes=NOLSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,LASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=none %s -### 2>&1 | 
FileCheck --check-prefixes=NOLSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=lsx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=lasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,LASX %s
+! RUN: not %flang -c --target=loongarch64-unknown-linux -msimd=supper %s -### 
2>&1 | FileCheck --check-prefix=MSIMD-INVALID %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mfrecipe %s -### 2>&1 | 
FileCheck --check-prefix=FRECIPE %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-frecipe %s -### 2>&1 
| FileCheck --check-prefix=NOFRECIPE %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlam-bh %s -### 2>&1 | 
FileCheck --check-prefix=LAMBH %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lam-bh %s -### 2>&1 | 
FileCheck --check-prefix=NOLAMBH %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlamcas %s -### 2>&1 | 
FileCheck --check-prefix=LAMCAS %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lamcas %s -### 2>&1 | 
FileCheck --check-prefix=NOLAMCAS %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mld-seq-sa %s -### 2>&1 | 
FileCheck --check-prefix=LD-SEQ-SA %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-ld-seq-sa %s -### 
2>&1 | FileCheck --check-prefix=NOLD-SEQ-SA %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mdiv32 %s -### 2>&1 | 
FileCheck --check-prefix=DIV32 %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-div32 %s -### 2>&1 | 
FileCheck --check-prefix=NODIV32 %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mannotate-tablejump %s 
-### 2>&1 | FileCheck --check-prefix=ANOTATE %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-annotate-tablejump %s 
-### 2>&1 | FileCheck --check-prefix=NOANOTATE %s
+
+! MSIMD-INVALID: error: invalid argument 'supper' to -msimd=; must be one of: 
none, lsx, lasx
+! FRECIPE: "-target-feature" "+frecipe"
+! NOFRECIPE-NOT: "-target-feature" "+frecipe

[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread Zhaoxin Yang via cfe-commits

https://github.com/ylzsx created 
https://github.com/llvm/llvm-project/pull/118244

Mainly including the following LoongArch specific options: -m[no-]lsx, 
-m[no-]lasx, -msimd=, -m[no-]frecipe, -m[no-]lam-bh, -m[no-]lamcas, 
-m[no-]ld-seq-sa, -m[no-]div32,
-m[no-]annotate-tablejump

>From ee9aa4d20d83a43a0a112eff95d6e918c2f62a34 Mon Sep 17 00:00:00 2001
From: yangzhaoxin 
Date: Wed, 27 Nov 2024 17:48:37 +0800
Subject: [PATCH] [Flang][LoongArch] Enable clang command-line options in
 flang.

Mainly including the following LoongArch specific options:
-m[no-]lsx, -m[no-]lasx, -msimd=, -m[no-]frecipe, -m[no-]lam-bh,
-m[no-]lamcas, -m[no-]ld-seq-sa, -m[no-]div32,
-m[no-]annotate-tablejump
---
 clang/include/clang/Driver/Options.td   |  3 +-
 clang/lib/Driver/ToolChains/Flang.cpp   |  8 +
 flang/test/Driver/options-loongarch.f90 | 43 +
 3 files changed, 53 insertions(+), 1 deletion(-)
 create mode 100644 flang/test/Driver/options-loongarch.f90

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 9c356c9d2ea4ef..7b8e2660192580 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -240,7 +240,8 @@ def m_riscv_Features_Group : OptionGroup<"">,
 def m_ve_Features_Group : OptionGroup<"">,
   Group, DocName<"VE">;
 def m_loongarch_Features_Group : OptionGroup<"">,
- Group, DocName<"LoongArch">;
+ Group, DocName<"LoongArch">,
+ Visibility<[ClangOption, CLOption, 
FlangOption]>;
 
 def m_libc_Group : OptionGroup<"">, Group,
Flags<[HelpHidden]>;
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 8c18c88fbde7f7..02323b90b65473 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -213,6 +213,14 @@ void Flang::AddLoongArch64TargetArgs(const ArgList &Args,
   D.Diag(diag::err_drv_argument_not_allowed_with) << "-mabi" << V;
 }
   }
+
+  if (const Arg *A = Args.getLastArg(options::OPT_mannotate_tablejump,
+ options::OPT_mno_annotate_tablejump)) {
+if (A->getOption().matches(options::OPT_mannotate_tablejump)) {
+  CmdArgs.push_back("-mllvm");
+  CmdArgs.push_back("-loongarch-annotate-tablejump");
+}
+  }
 }
 
 void Flang::AddPPCTargetArgs(const ArgList &Args,
diff --git a/flang/test/Driver/options-loongarch.f90 
b/flang/test/Driver/options-loongarch.f90
new file mode 100644
index 00..717bf6385b06d7
--- /dev/null
+++ b/flang/test/Driver/options-loongarch.f90
@@ -0,0 +1,43 @@
+!! This test tests options from clang, which are also supported by flang in 
LoongArch.
+
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlsx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lsx %s -### 2>&1 | 
FileCheck --check-prefixes=NOLSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,LASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=none %s -### 2>&1 | 
FileCheck --check-prefixes=NOLSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=lsx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,NOLASX %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -msimd=lasx %s -### 2>&1 | 
FileCheck --check-prefixes=LSX,LASX %s
+! RUN: not %flang -c --target=loongarch64-unknown-linux -msimd=supper %s -### 
2>&1 | FileCheck --check-prefix=MSIMD-INVALID %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mfrecipe %s -### 2>&1 | 
FileCheck --check-prefix=FRECIPE %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-frecipe %s -### 2>&1 
| FileCheck --check-prefix=NOFRECIPE %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlam-bh %s -### 2>&1 | 
FileCheck --check-prefix=LAMBH %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lam-bh %s -### 2>&1 | 
FileCheck --check-prefix=NOLAMBH %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mlamcas %s -### 2>&1 | 
FileCheck --check-prefix=LAMCAS %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-lamcas %s -### 2>&1 | 
FileCheck --check-prefix=NOLAMCAS %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mld-seq-sa %s -### 2>&1 | 
FileCheck --check-prefix=LD-SEQ-SA %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-ld-seq-sa %s -### 
2>&1 | FileCheck --check-prefix=NOLD-SEQ-SA %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mdiv32 %s -### 2>&1 | 
FileCheck --check-prefix=DIV32 %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mno-div32 %s -### 2>&1 | 
FileCheck --check-prefix=NODIV32 %s
+! RUN: %flang -c --target=loongarch64-unknown-linux -mannotat

[clang] [llvm] [LoongArch] Support sc.q instruction for 128bit cmpxchg operation (PR #116771)

2024-12-01 Thread via cfe-commits

https://github.com/tangaac updated 
https://github.com/llvm/llvm-project/pull/116771

>From ee422d26ad2695d34b0bf471f6d4fa2c3bef8ca8 Mon Sep 17 00:00:00 2001
From: tangaac 
Date: Tue, 19 Nov 2024 17:43:31 +0800
Subject: [PATCH 1/3] [LoongArch] Support sc.q instruction for 128bit cmpxchg
 operation

---
 clang/include/clang/Driver/Options.td |   4 +
 clang/lib/Basic/Targets/LoongArch.cpp |   7 +-
 clang/lib/Basic/Targets/LoongArch.h   |   2 +
 .../lib/Driver/ToolChains/Arch/LoongArch.cpp  |   8 +
 clang/test/Driver/loongarch-march.c   |   8 +-
 clang/test/Driver/loongarch-mscq.c|  30 ++
 clang/test/Preprocessor/init-loongarch.c  |  31 +-
 .../TargetParser/LoongArchTargetParser.def|   3 +-
 .../llvm/TargetParser/LoongArchTargetParser.h |   3 +
 llvm/lib/Target/LoongArch/LoongArch.td|   9 +-
 .../LoongArchExpandAtomicPseudoInsts.cpp  | 107 +++
 .../LoongArch/LoongArchISelLowering.cpp   |  46 +++
 .../Target/LoongArch/LoongArchInstrInfo.td|  14 +
 .../TargetParser/LoongArchTargetParser.cpp|   1 +
 .../ir-instruction/atomic-cmpxchg-128.ll  | 287 ++
 15 files changed, 542 insertions(+), 18 deletions(-)
 create mode 100644 clang/test/Driver/loongarch-mscq.c
 create mode 100644 
llvm/test/CodeGen/LoongArch/ir-instruction/atomic-cmpxchg-128.ll

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 808f089914c9bb..96cef360bd5251 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5425,6 +5425,10 @@ def mdiv32 : Flag<["-"], "mdiv32">, 
Group,
   HelpText<"Use div.w[u] and mod.w[u] instructions with input not 
sign-extended.">;
 def mno_div32 : Flag<["-"], "mno-div32">, Group,
   HelpText<"Do not use div.w[u] and mod.w[u] instructions with input not 
sign-extended.">;
+def mscq : Flag<["-"], "mscq">, Group,
+  HelpText<"Enable sc.q instruction.">;
+def mno_scq : Flag<["-"], "mno-scq">, Group,
+  HelpText<"Disable sc.q instruction.">;
 def mannotate_tablejump : Flag<["-"], "mannotate-tablejump">, 
Group,
   HelpText<"Enable annotate table jump instruction to correlate it with the 
jump table.">;
 def mno_annotate_tablejump : Flag<["-"], "mno-annotate-tablejump">, 
Group,
diff --git a/clang/lib/Basic/Targets/LoongArch.cpp 
b/clang/lib/Basic/Targets/LoongArch.cpp
index d36186aa9c2fbf..bb0d0b68cfcb0a 100644
--- a/clang/lib/Basic/Targets/LoongArch.cpp
+++ b/clang/lib/Basic/Targets/LoongArch.cpp
@@ -206,7 +206,7 @@ void LoongArchTargetInfo::getTargetDefines(const 
LangOptions &Opts,
   // arch feature set will be used to include all sub-features belonging to
   // the V1.1 ISA version.
   if (HasFeatureFrecipe && HasFeatureLAM_BH && HasFeatureLAMCAS &&
-  HasFeatureLD_SEQ_SA && HasFeatureDiv32)
+  HasFeatureLD_SEQ_SA && HasFeatureDiv32 && HasFeatureSCQ)
 Builder.defineMacro("__loongarch_arch",
 Twine('"') + "la64v1.1" + Twine('"'));
   else
@@ -249,6 +249,9 @@ void LoongArchTargetInfo::getTargetDefines(const 
LangOptions &Opts,
   if (HasFeatureDiv32)
 Builder.defineMacro("__loongarch_div32", Twine(1));
 
+  if (HasFeatureSCQ)
+Builder.defineMacro("__loongarch_scq", Twine(1));
+
   StringRef ABI = getABI();
   if (ABI == "lp64d" || ABI == "lp64f" || ABI == "lp64s")
 Builder.defineMacro("__loongarch_lp64");
@@ -333,6 +336,8 @@ bool LoongArchTargetInfo::handleTargetFeatures(
   HasFeatureLD_SEQ_SA = true;
 else if (Feature == "+div32")
   HasFeatureDiv32 = true;
+else if (Feature == "+scq")
+  HasFeatureSCQ = true;
   }
   return true;
 }
diff --git a/clang/lib/Basic/Targets/LoongArch.h 
b/clang/lib/Basic/Targets/LoongArch.h
index abaa05aa42d438..5c34c84ff8d3e8 100644
--- a/clang/lib/Basic/Targets/LoongArch.h
+++ b/clang/lib/Basic/Targets/LoongArch.h
@@ -34,6 +34,7 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public 
TargetInfo {
   bool HasFeatureLAMCAS;
   bool HasFeatureLD_SEQ_SA;
   bool HasFeatureDiv32;
+  bool HasFeatureSCQ;
 
 public:
   LoongArchTargetInfo(const llvm::Triple &Triple, const TargetOptions &)
@@ -47,6 +48,7 @@ class LLVM_LIBRARY_VISIBILITY LoongArchTargetInfo : public 
TargetInfo {
 HasFeatureLAMCAS = false;
 HasFeatureLD_SEQ_SA = false;
 HasFeatureDiv32 = false;
+HasFeatureSCQ = false;
 LongDoubleWidth = 128;
 LongDoubleAlign = 128;
 LongDoubleFormat = &llvm::APFloat::IEEEquad();
diff --git a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp 
b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
index bbd9397aa2378a..4dd07f25bab0fb 100644
--- a/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/LoongArch.cpp
@@ -301,6 +301,14 @@ void loongarch::getLoongArchTargetFeatures(const Driver &D,
 else
   Features.push_back("-div32");
   }
+
+  // Select scq feature determined by -m[no-]scq.
+  if (const Arg *A = Args.getLastArg(options::OPT_mscq, option

[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 updated 
https://github.com/llvm/llvm-project/pull/118236

>From 37eb30a2b99daa1f30da3bd53e2a92588cbde0f9 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 1 Dec 2024 19:58:03 -0500
Subject: [PATCH] [clang] [Sema] Preserve nested name specifier prefix in
 MemberPointerType

---
 .../unittests/SemanticHighlightingTests.cpp   |  7 +++
 clang/lib/Sema/SemaType.cpp   | 15 +--
 2 files changed, 16 insertions(+), 6 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 30b9b1902aa9c7..1ec51d862d0a6f 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -1092,6 +1092,13 @@ sizeof...($TemplateParameter[[Elements]]);
 $Field_dependentName[[waldo]];
   }
 };
+)cpp",
+  // Pointer-to-member with nested-name-specifiers
+  R"cpp(
+  struct $Class_def[[Outer]] {
+struct $Class_def[[Inner]] {};
+  };
+  using $Typedef_decl[[Alias]] = void ($Class[[Outer]]::$Class[[Inner]]:: 
*)();
 )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index f32edc5ac06440..0e50d882445cf4 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5347,13 +5347,16 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
   // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  // TemplateSpecializationType or a RecordType, then the NNS prefix is
+  // NOT included in ClsType; hence we wrap ClsType into an
+  // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
+  // already is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization.
+  if (isa(NNSType) ||
+  (NNSPrefix && isa(NNSType)))
 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
 NNSPrefix, ClsType);
   break;

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits


@@ -5347,15 +5347,18 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
-  // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
+  // If ClsType is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization, it already stores the NNS prefix.
+  // Otherwise, wrap it in an Elaborated type to have a place to store
+  // the NNS prefix.
+  if (!(isa(NNSType) ||
+isa(NNSType) ||
+isa(NNSType))) {

HighCommander4 wrote:

@mizvekov Thanks for having a look!

I don't have any evidence of us actually getting an ElaboratedType or 
DependentNameType here, I was just basing this on the comment which mentioned 
these types.

I revised the patch to make a more targeted change (wrap `RecordType` when 
there is a qualifier present), which still addresses the original issue I was 
having in clangd, and (hopefully) passes tests. I would be grateful of your 
opinion about whether there is a more appropriate condition we should be using.

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Matheus Izvekov via cfe-commits


@@ -5347,15 +5347,18 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
-  // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
+  // If ClsType is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization, it already stores the NNS prefix.
+  // Otherwise, wrap it in an Elaborated type to have a place to store
+  // the NNS prefix.
+  if (!(isa(NNSType) ||
+isa(NNSType) ||
+isa(NNSType))) {

mizvekov wrote:

Yeah I think the existing comment is wrong / misleading.

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


[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread Lu Weining via cfe-commits


@@ -240,7 +240,8 @@ def m_riscv_Features_Group : OptionGroup<"">,
 def m_ve_Features_Group : OptionGroup<"">,
   Group, DocName<"VE">;
 def m_loongarch_Features_Group : OptionGroup<"">,
- Group, DocName<"LoongArch">;
+ Group, DocName<"LoongArch">,
+ Visibility<[ClangOption, CLOption, 
FlangOption]>;

SixWeining wrote:

Seems `CLOption` is not related to this change.

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Matheus Izvekov via cfe-commits


@@ -5347,13 +5347,16 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
   // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  // TemplateSpecializationType or a RecordType, then the NNS prefix is
+  // NOT included in ClsType; hence we wrap ClsType into an
+  // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
+  // already is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization.
+  if (isa(NNSType) ||
+  (NNSPrefix && isa(NNSType)))

mizvekov wrote:

It would also be cool to have an assertion here, that we are handling all cases.

I think the logic here would be something like:
```
if (isa...)
  // Rebuild DependentTemplateSpecializationType, adding the Prefix.
else
  // either the dependent case (TemplateSpecializationType), or the 
non-dependent one (RecordType).
 // assert(isa...)
``` 

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Matheus Izvekov via cfe-commits


@@ -5347,13 +5347,16 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
   // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  // TemplateSpecializationType or a RecordType, then the NNS prefix is
+  // NOT included in ClsType; hence we wrap ClsType into an
+  // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
+  // already is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization.
+  if (isa(NNSType) ||
+  (NNSPrefix && isa(NNSType)))

mizvekov wrote:

```suggestion
  isa(NNSType))
```
We use an ElaboratedType with null prefix to represent a type which was written 
without qualifiers, so it seems arbitrary to not add the elaboration in this 
case.

Also, can you at least add a FIXME / TODO explaining how a 
DependentTemplateSpecializationType needs to be handled here, as I explained in 
the other thread?

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread Nikita Popov via cfe-commits

nikic wrote:

Please also rebase, I expect https://github.com/llvm/llvm-project/pull/118195 
will results in some test changes.

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


[clang] [Xtensa] Default to unsigned char (PR #115967)

2024-12-01 Thread Alexander Richardson via cfe-commits

arichardson wrote:

> Hi @arichardson.
> 
> Thanks for this change. Acc to the doc which I have `The char type is 
> unsigned by default for Xtensa processors.` Our GCC Xtensa toolchain also 
> interprets char type as unsigned by default.

Thanks, do you believe we need a backwards compatibility flag for the ABI to be 
consistent with older clang or is this safe to land?

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


[clang] [clang][bytecode][NFC] Remove APValue Result argument where unnecessary (PR #118199)

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

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


[clang] 82ed9c0 - [clang][bytecode][NFC] Remove APValue Result argument where unnecessary (#118199)

2024-12-01 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-12-01T17:36:19+01:00
New Revision: 82ed9c0319c9f0373bcb633a03ce6d35ebac3661

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

LOG: [clang][bytecode][NFC] Remove APValue Result argument where unnecessary 
(#118199)

This is unneeded in almost all circumstances. We only return an APValue
back to clang when the evaluation is finished, and that is always done
by an EvalEmitter - which has its own implementation of the Ret
instructions.

Added: 


Modified: 
clang/lib/AST/ByteCode/Context.cpp
clang/lib/AST/ByteCode/Context.h
clang/lib/AST/ByteCode/Interp.cpp
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/utils/TableGen/ClangOpcodesEmitter.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Context.cpp 
b/clang/lib/AST/ByteCode/Context.cpp
index 7088cf02901c63..b52892cf69bfb6 100644
--- a/clang/lib/AST/ByteCode/Context.cpp
+++ b/clang/lib/AST/ByteCode/Context.cpp
@@ -34,8 +34,7 @@ bool Context::isPotentialConstantExpr(State &Parent, const 
FunctionDecl *FD) {
   if (!Func)
 return false;
 
-  APValue DummyResult;
-  if (!Run(Parent, Func, DummyResult))
+  if (!Run(Parent, Func))
 return false;
 
   return Func->isConstexpr();
@@ -213,13 +212,13 @@ const llvm::fltSemantics 
&Context::getFloatSemantics(QualType T) const {
   return Ctx.getFloatTypeSemantics(T);
 }
 
-bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
+bool Context::Run(State &Parent, const Function *Func) {
 
   {
 InterpState State(Parent, *P, Stk, *this);
 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
 Func->getArgSize());
-if (Interpret(State, Result)) {
+if (Interpret(State)) {
   assert(Stk.empty());
   return true;
 }

diff  --git a/clang/lib/AST/ByteCode/Context.h 
b/clang/lib/AST/ByteCode/Context.h
index e0d4bafdebaf2b..ed539def99efd0 100644
--- a/clang/lib/AST/ByteCode/Context.h
+++ b/clang/lib/AST/ByteCode/Context.h
@@ -114,7 +114,7 @@ class Context final {
 
 private:
   /// Runs a function.
-  bool Run(State &Parent, const Function *Func, APValue &Result);
+  bool Run(State &Parent, const Function *Func);
 
   /// Current compilation context.
   ASTContext &Ctx;

diff  --git a/clang/lib/AST/ByteCode/Interp.cpp 
b/clang/lib/AST/ByteCode/Interp.cpp
index 329f1584be34bf..435af1201890c8 100644
--- a/clang/lib/AST/ByteCode/Interp.cpp
+++ b/clang/lib/AST/ByteCode/Interp.cpp
@@ -27,7 +27,7 @@
 using namespace clang;
 using namespace clang::interp;
 
-static bool RetValue(InterpState &S, CodePtr &Pt, APValue &Result) {
+static bool RetValue(InterpState &S, CodePtr &Pt) {
   llvm::report_fatal_error("Interpreter cannot return values");
 }
 
@@ -1205,11 +1205,10 @@ bool CallVar(InterpState &S, CodePtr OpPC, const 
Function *Func,
   InterpFrame *FrameBefore = S.Current;
   S.Current = NewFrame.get();
 
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1270,11 +1269,10 @@ bool Call(InterpState &S, CodePtr OpPC, const Function 
*Func,
   S.Current = NewFrame.get();
 
   InterpStateCCOverride CCOverride(S, Func->getDecl()->isImmediateFunction());
-  APValue CallResult;
   // Note that we cannot assert(CallResult.hasValue()) here since
   // Ret() above only sets the APValue if the curent frame doesn't
   // have a caller set.
-  if (Interpret(S, CallResult)) {
+  if (Interpret(S)) {
 NewFrame.release(); // Frame was delete'd already.
 assert(S.Current == FrameBefore);
 return true;
@@ -1598,7 +1596,7 @@ bool CheckBitCast(InterpState &S, CodePtr OpPC, bool 
HasIndeterminateBits,
 #if defined(_MSC_VER) && !defined(__clang__) && !defined(NDEBUG)
 #pragma optimize("", off)
 #endif
-bool Interpret(InterpState &S, APValue &Result) {
+bool Interpret(InterpState &S) {
   // The current stack frame when we started Interpret().
   // This is being used by the ops to determine wheter
   // to return from this function and thus terminate

diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index 47dcfca79f7356..25740c90d240ab 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -41,13 +41,6 @@ namespace interp {
 using APSInt = llvm::APSInt;
 using FixedPointSemantics = llvm::FixedPointSemantics;
 
-/// Convert a value to an APValue.
-template 
-bool ReturnValue(const InterpState &S, const T &V, APValue &R) {
-  R = V.toAPValue(S.getASTContext());
- 

[clang] 31bde71 - [clang][bytecode] Support __builtin_reduce_add (#117672)

2024-12-01 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-12-01T17:39:11+01:00
New Revision: 31bde711c4098b3136edd1cb92dd4e0cc1d4d179

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

LOG: [clang][bytecode] Support __builtin_reduce_add (#117672)

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltin.cpp
clang/test/AST/ByteCode/builtin-functions.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltin.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
index 817adb3f48eb87..080fa891e641e3 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltin.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltin.cpp
@@ -89,13 +89,14 @@ static void pushInteger(InterpState &S, const APSInt &Val, 
QualType QT) {
   std::optional T = S.getContext().classify(QT);
   assert(T);
 
+  unsigned BitWidth = S.getASTContext().getTypeSize(QT);
   if (QT->isSignedIntegerOrEnumerationType()) {
 int64_t V = Val.getSExtValue();
-INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V)); });
+INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V, BitWidth)); });
   } else {
 assert(QT->isUnsignedIntegerOrEnumerationType());
 uint64_t V = Val.getZExtValue();
-INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V)); });
+INT_TYPE_SWITCH(*T, { S.Stk.push(T::from(V, BitWidth)); });
   }
 }
 
@@ -137,6 +138,8 @@ static bool retPrimValue(InterpState &S, CodePtr OpPC,
 RET_CASE(PT_Uint32);
 RET_CASE(PT_Sint64);
 RET_CASE(PT_Uint64);
+RET_CASE(PT_IntAP);
+RET_CASE(PT_IntAPS);
   default:
 llvm_unreachable("Unsupported return type for builtin function");
   }
@@ -1684,6 +1687,42 @@ static bool interp__builtin_arithmetic_fence(InterpState 
&S, CodePtr OpPC,
   return true;
 }
 
+static bool interp__builtin_vector_reduce(InterpState &S, CodePtr OpPC,
+  const InterpFrame *Frame,
+  const Function *Func,
+  const CallExpr *Call) {
+  const Pointer &Arg = S.Stk.peek();
+  assert(Arg.getFieldDesc()->isPrimitiveArray());
+
+  unsigned ID = Func->getBuiltinID();
+  if (ID == Builtin::BI__builtin_reduce_add) {
+QualType ElemType = Arg.getFieldDesc()->getElemQualType();
+assert(Call->getType() == ElemType);
+PrimType ElemT = *S.getContext().classify(ElemType);
+unsigned NumElems = Arg.getNumElems();
+
+INT_TYPE_SWITCH(ElemT, {
+  T Sum = Arg.atIndex(0).deref();
+  unsigned BitWidth = Sum.bitWidth();
+  for (unsigned I = 1; I != NumElems; ++I) {
+T Elem = Arg.atIndex(I).deref();
+if (T::add(Sum, Elem, BitWidth, &Sum)) {
+  unsigned OverflowBits = BitWidth + 1;
+  (void)handleOverflow(
+  S, OpPC,
+  (Sum.toAPSInt(OverflowBits) + Elem.toAPSInt(OverflowBits)));
+  return false;
+}
+  }
+  pushInteger(S, Sum, Call->getType());
+});
+
+return true;
+  }
+
+  llvm_unreachable("Unsupported vector reduce builtin");
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call, uint32_t BuiltinID) {
   const InterpFrame *Frame = S.Current;
@@ -2129,6 +2168,11 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, 
const Function *F,
   return false;
 break;
 
+  case Builtin::BI__builtin_reduce_add:
+if (!interp__builtin_vector_reduce(S, OpPC, Frame, F, Call))
+  return false;
+break;
+
   default:
 S.FFDiag(S.Current->getLocation(OpPC),
  diag::note_invalid_subexpr_in_const_expr)

diff  --git a/clang/test/AST/ByteCode/builtin-functions.cpp 
b/clang/test/AST/ByteCode/builtin-functions.cpp
index b5d334178f8213..972d39ca509615 100644
--- a/clang/test/AST/ByteCode/builtin-functions.cpp
+++ b/clang/test/AST/ByteCode/builtin-functions.cpp
@@ -990,3 +990,48 @@ namespace BuiltinInImplicitCtor {
   } Foo;
   static_assert(Foo.a == 0, "");
 }
+
+
+typedef double vector4double __attribute__((__vector_size__(32)));
+typedef float vector4float __attribute__((__vector_size__(16)));
+typedef long long vector4long __attribute__((__vector_size__(32)));
+typedef int vector4int __attribute__((__vector_size__(16)));
+typedef unsigned long long vector4ulong __attribute__((__vector_size__(32)));
+typedef unsigned int vector4uint __attribute__((__vector_size__(16)));
+typedef short vector4short __attribute__((__vector_size__(8)));
+typedef char vector4char __attribute__((__vector_size__(4)));
+typedef double vector8double __attribute__((__vector_size__(64)));
+typedef float vector8float __attribute__((__vector_size__(32)));
+typedef long long vector8long __attribute__((__vector_size__(64)));
+typedef int vector8int __attribute__((__vector_size__(32)));
+typedef short vector8short __attribute__((__vector_size__(16)));
+typedef char vector

[clang] [clang][bytecode] Support __builtin_reduce_add (PR #117672)

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

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


[clang] [clang][bytecode] Support vector-to-vector bitcasts (PR #118230)

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

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

None

>From 3bdcf86f356fb6579bebf35ed636b0eae9bf24fd Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sun, 1 Dec 2024 20:24:05 +0100
Subject: [PATCH] [clang][bytecode] Support vector-to-vector bitcasts

---
 clang/lib/AST/ByteCode/Compiler.cpp |  6 +++---
 clang/test/AST/ByteCode/altivec.c   | 19 +++
 clang/test/AST/ByteCode/vectors.cpp |  3 +--
 3 files changed, 23 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/AST/ByteCode/altivec.c

diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index f4cc284dfb6abf..754ab8f04a 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -448,8 +448,8 @@ bool Compiler::VisitCastExpr(const CastExpr *CE) {
 
 QualType SubExprTy = SubExpr->getType();
 std::optional FromT = classify(SubExprTy);
-// Casts from integer to vectors in C.
-if (FromT && CE->getType()->isVectorType())
+// Casts from integer/vector to vector.
+if (CE->getType()->isVectorType())
   return this->emitBuiltinBitCast(CE);
 
 std::optional ToT = classify(CE->getType());
@@ -6502,7 +6502,7 @@ bool Compiler::emitBuiltinBitCast(const CastExpr 
*E) {
   // we later assume it to be one (i.e. a PT_Ptr). However,
   // we call this function for other utility methods where
   // a bitcast might be useful, so convert it to a PT_Ptr in that case.
-  if (SubExpr->isGLValue()) {
+  if (SubExpr->isGLValue() || FromType->isVectorType()) {
 if (!this->visit(SubExpr))
   return false;
   } else if (std::optional FromT = classify(SubExpr)) {
diff --git a/clang/test/AST/ByteCode/altivec.c 
b/clang/test/AST/ByteCode/altivec.c
new file mode 100644
index 00..39caedc9949d20
--- /dev/null
+++ b/clang/test/AST/ByteCode/altivec.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature 
+altivec -target-feature +vsx -fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature 
+altivec -target-feature -vsx -fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec 
-fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec 
-target-feature -vsx -fsyntax-only -verify=expected,both %s
+
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature 
+altivec -target-feature +vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature 
+altivec -target-feature -vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec 
-fsyntax-only -verify=expected,both -fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec 
-target-feature -vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+
+// both-no-diagnostics.
+
+/// From test/Parser/altivec.c
+vector char v1 = (vector char)((vector int)(1, 2, 3, 4));
+vector char v2 = (vector char)((vector float)(1.0f, 2.0f, 3.0f, 4.0f));
+vector char v3 = (vector char)((vector int)('a', 'b', 'c', 'd'));
+vector int v4 = (vector int)(1, 2, 3, 4);
+vector float v5 = (vector float)(1.0f, 2.0f, 3.0f, 4.0f);
+vector char v6 = (vector char)((vector int)(1+2, -2, (int)(2.0 * 3), -(5-3)));
diff --git a/clang/test/AST/ByteCode/vectors.cpp 
b/clang/test/AST/ByteCode/vectors.cpp
index a0aace44f3c981..08e2ca2adbf5cd 100644
--- a/clang/test/AST/ByteCode/vectors.cpp
+++ b/clang/test/AST/ByteCode/vectors.cpp
@@ -55,10 +55,9 @@ namespace Vector {
   static_assert(__builtin_vectorelements(v2) == (32 / sizeof(double)), "");
 }
 
-/// FIXME: We need to support BitCasts between vector types.
 namespace {
   typedef float __attribute__((vector_size(16))) VI42;
-  constexpr VI42 A2 = A; // expected-error {{must be initialized by a constant 
expression}}
+  constexpr VI42 A2 = A;
 }
 
 namespace BoolToSignedIntegralCast{

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


[clang] [clang][bytecode] Support vector-to-vector bitcasts (PR #118230)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes



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


3 Files Affected:

- (modified) clang/lib/AST/ByteCode/Compiler.cpp (+3-3) 
- (added) clang/test/AST/ByteCode/altivec.c (+19) 
- (modified) clang/test/AST/ByteCode/vectors.cpp (+1-2) 


``diff
diff --git a/clang/lib/AST/ByteCode/Compiler.cpp 
b/clang/lib/AST/ByteCode/Compiler.cpp
index f4cc284dfb6abf..754ab8f04a 100644
--- a/clang/lib/AST/ByteCode/Compiler.cpp
+++ b/clang/lib/AST/ByteCode/Compiler.cpp
@@ -448,8 +448,8 @@ bool Compiler::VisitCastExpr(const CastExpr *CE) {
 
 QualType SubExprTy = SubExpr->getType();
 std::optional FromT = classify(SubExprTy);
-// Casts from integer to vectors in C.
-if (FromT && CE->getType()->isVectorType())
+// Casts from integer/vector to vector.
+if (CE->getType()->isVectorType())
   return this->emitBuiltinBitCast(CE);
 
 std::optional ToT = classify(CE->getType());
@@ -6502,7 +6502,7 @@ bool Compiler::emitBuiltinBitCast(const CastExpr 
*E) {
   // we later assume it to be one (i.e. a PT_Ptr). However,
   // we call this function for other utility methods where
   // a bitcast might be useful, so convert it to a PT_Ptr in that case.
-  if (SubExpr->isGLValue()) {
+  if (SubExpr->isGLValue() || FromType->isVectorType()) {
 if (!this->visit(SubExpr))
   return false;
   } else if (std::optional FromT = classify(SubExpr)) {
diff --git a/clang/test/AST/ByteCode/altivec.c 
b/clang/test/AST/ByteCode/altivec.c
new file mode 100644
index 00..39caedc9949d20
--- /dev/null
+++ b/clang/test/AST/ByteCode/altivec.c
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature 
+altivec -target-feature +vsx -fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature 
+altivec -target-feature -vsx -fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec 
-fsyntax-only -verify=expected,both %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec 
-target-feature -vsx -fsyntax-only -verify=expected,both %s
+
+// RUN: %clang_cc1 -triple=powerpc64-unknown-linux-gnu -target-feature 
+altivec -target-feature +vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc64le-unknown-linux-gnu -target-feature 
+altivec -target-feature -vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc-ibm-aix -target-feature +altivec 
-fsyntax-only -verify=expected,both -fexperimental-new-constant-interpreter %s
+// RUN: %clang_cc1 -triple=powerpc64-ibm-aix -target-feature +altivec 
-target-feature -vsx -fsyntax-only -verify=expected,both 
-fexperimental-new-constant-interpreter %s
+
+// both-no-diagnostics.
+
+/// From test/Parser/altivec.c
+vector char v1 = (vector char)((vector int)(1, 2, 3, 4));
+vector char v2 = (vector char)((vector float)(1.0f, 2.0f, 3.0f, 4.0f));
+vector char v3 = (vector char)((vector int)('a', 'b', 'c', 'd'));
+vector int v4 = (vector int)(1, 2, 3, 4);
+vector float v5 = (vector float)(1.0f, 2.0f, 3.0f, 4.0f);
+vector char v6 = (vector char)((vector int)(1+2, -2, (int)(2.0 * 3), -(5-3)));
diff --git a/clang/test/AST/ByteCode/vectors.cpp 
b/clang/test/AST/ByteCode/vectors.cpp
index a0aace44f3c981..08e2ca2adbf5cd 100644
--- a/clang/test/AST/ByteCode/vectors.cpp
+++ b/clang/test/AST/ByteCode/vectors.cpp
@@ -55,10 +55,9 @@ namespace Vector {
   static_assert(__builtin_vectorelements(v2) == (32 / sizeof(double)), "");
 }
 
-/// FIXME: We need to support BitCasts between vector types.
 namespace {
   typedef float __attribute__((vector_size(16))) VI42;
-  constexpr VI42 A2 = A; // expected-error {{must be initialized by a constant 
expression}}
+  constexpr VI42 A2 = A;
 }
 
 namespace BoolToSignedIntegralCast{

``




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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits

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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,165 @@
+//===--- UseIntegerSignComparisonCheck.cpp - clang-tidy 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UseIntegerSignComparisonCheck.h"
+#include "clang/AST/Expr.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/Lex/Lexer.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::ast_matchers::internal;
+
+namespace clang::tidy::modernize {
+UseIntegerSignComparisonCheck::UseIntegerSignComparisonCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeInserter(Options.getLocalOrGlobal("IncludeStyle",
+   utils::IncludeSorter::IS_LLVM),
+  areDiagsSelfContained()),
+  IsQtApplication(Options.get("IsQtApplication", false)),
+  StringsMatchHeader(Options.get("StringsMatchHeader", "")) {}
+
+void UseIntegerSignComparisonCheck::storeOptions(
+ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "IsQtApplication", IsQtApplication);
+  Options.store(Opts, "StringsMatchHeader", StringsMatchHeader);
+}
+
+void UseIntegerSignComparisonCheck::registerMatchers(MatchFinder *Finder) {
+  const auto SignedIntCastExpr = intCastExpression(true, "sIntCastExpression");
+  const auto UnSignedIntCastExpr =
+  intCastExpression(false, "uIntCastExpression");
+
+  // Flag all operators "==", "<=", ">=", "<", ">", "!="
+  // that are used between signed/unsigned
+  const auto CompareOperator =
+  expr(binaryOperator(hasAnyOperatorName("==", "<=", ">=", "<", ">", "!="),
+  anyOf(allOf(hasLHS(SignedIntCastExpr),
+  hasRHS(UnSignedIntCastExpr)),
+allOf(hasLHS(UnSignedIntCastExpr),
+  hasRHS(SignedIntCastExpr)
+  .bind("intComparison");
+
+  Finder->addMatcher(CompareOperator, this);
+}
+
+BindableMatcher UseIntegerSignComparisonCheck::intCastExpression(
+bool IsSigned, const std::string &CastBindName) const {
+  auto IntTypeExpr = expr();
+  if (IsSigned) {
+IntTypeExpr = expr(hasType(qualType(isInteger(), isSignedInteger(;
+  } else {
+IntTypeExpr =
+expr(hasType(qualType(isInteger(), unless(isSignedInteger();
+  }
+
+  const auto ImplicitCastExpr =
+  implicitCastExpr(hasSourceExpression(IntTypeExpr)).bind(CastBindName);
+
+  const auto CStyleCastExpr = cStyleCastExpr(has(ImplicitCastExpr));
+  const auto StaticCastExpr = cxxStaticCastExpr(has(ImplicitCastExpr));
+  const auto FunctionalCastExpr = cxxFunctionalCastExpr(has(ImplicitCastExpr));
+
+  return traverse(TK_AsIs, expr(anyOf(ImplicitCastExpr, CStyleCastExpr,
+  StaticCastExpr, FunctionalCastExpr)));
+}
+
+std::string
+UseIntegerSignComparisonCheck::parseOpCode(BinaryOperator::Opcode code) const {
+  switch (code) {
+  case BO_LT:
+return std::string("cmp_less");
+  case BO_GT:
+return std::string("cmp_greater");
+  case BO_LE:
+return std::string("cmp_less_equal");
+  case BO_GE:
+return std::string("cmp_greater_equal");
+  case BO_EQ:
+return std::string("cmp_equal");
+  case BO_NE:
+return std::string("cmp_not_equal");
+  default:
+return {};
+  }
+}
+
+void UseIntegerSignComparisonCheck::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  IncludeInserter.registerPreprocessor(PP);
+}
+
+void UseIntegerSignComparisonCheck::check(
+const MatchFinder::MatchResult &Result) {
+  const auto *SignedCastExpression =
+  Result.Nodes.getNodeAs("sIntCastExpression");
+  const auto *UnSignedCastExpression =
+  Result.Nodes.getNodeAs("uIntCastExpression");

5chmidti wrote:

Please address this comment

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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,36 @@
+.. title:: clang-tidy - modernize-use-integer-sign-comparison
+
+modernize-use-integer-sign-comparison
+=
+
+Replace comparisons between signed and unsigned integers with their safe
+C++20 ``std::cmp_*`` alternative, if available.
+
+The check provides a replacement only for C++20 or later, otherwise
+it highlights the problem and expects a user fixes it manually.
+
+Examples of fixes created by the check:
+
+.. code-block:: c++
+
+  uint func(int a, uint b) {
+return a == b;
+  }
+
+becomes
+
+.. code-block:: c++
+
+  #include 
+
+  uint func(int a, uint b) {
+return (std::cmp_equal(a, b));

5chmidti wrote:

Please remove the outer parentheses around the `cmp_equal`, as they are not 
added by the check

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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits

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

Just some small things to address

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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits


@@ -0,0 +1,36 @@
+.. title:: clang-tidy - modernize-use-integer-sign-comparison
+
+modernize-use-integer-sign-comparison
+=
+
+Replace comparisons between signed and unsigned integers with their safe
+C++20 ``std::cmp_*`` alternative, if available.
+
+The check provides a replacement only for C++20 or later, otherwise
+it highlights the problem and expects a user fixes it manually.

5chmidti wrote:

`expects the user to fix it manually.`

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


[clang-tools-extra] [clang-tidy] Create a check for signed and unsigned integers comparison (PR #113144)

2024-12-01 Thread Julian Schmidt via cfe-commits

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


[clang] [clang] Implement P3176R1: The Oxford variadic comma (PR #117524)

2024-12-01 Thread via cfe-commits

https://github.com/antangelo updated 
https://github.com/llvm/llvm-project/pull/117524

>From ffcae3a593f1324b5f5495b42bb0ec61a61c2055 Mon Sep 17 00:00:00 2001
From: antangelo 
Date: Mon, 25 Nov 2024 01:54:26 -0500
Subject: [PATCH 1/5] [clang] Implement P3176R1: The Oxford variadic comma

Emit a warning when a variadic parameter in a
parameter-declaration-clause is not preceded by a comma for C++26.
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/Basic/DiagnosticGroups.td |  4 ++-
 .../clang/Basic/DiagnosticParseKinds.td   |  3 ++
 clang/lib/Parse/ParseDecl.cpp |  8 +
 clang/test/CXX/drs/cwg722.cpp |  2 +-
 .../Parser/cxx2c-oxford-variadic-comma.cpp| 36 +++
 clang/www/cxx_status.html |  2 +-
 7 files changed, 54 insertions(+), 3 deletions(-)
 create mode 100644 clang/test/Parser/cxx2c-oxford-variadic-comma.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bd06fadfdc984..b8d5c4201aeaef 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -227,6 +227,8 @@ C++2c Feature Support
 - Added the ``__builtin_is_within_lifetime`` builtin, which supports
   `P2641R4 Checking if a union alternative is active 
`_
 
+- Implemented `P3176R1 The Oxford variadic comma `_
+
 C++23 Feature Support
 ^
 - Removed the restriction to literal types in constexpr functions in C++23 
mode.
diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index df9bf94b5d0398..7ad8ac0e7a2e46 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -211,6 +211,7 @@ def DeprecatedWritableStr : 
DiagGroup<"deprecated-writable-strings",
   [CXX11CompatDeprecatedWritableStr]>;
 def DeprecatedPragma : DiagGroup<"deprecated-pragma">;
 def DeprecatedType : DiagGroup<"deprecated-type">;
+def DeprecatedMissingCommaVariadicParam : 
DiagGroup<"deprecated-missing-comma-variadic-parameter">;
 // FIXME: Why is DeprecatedImplementations not in this group?
 def Deprecated : DiagGroup<"deprecated", [DeprecatedAnonEnumEnumConversion,
   DeprecatedArrayCompare,
@@ -235,7 +236,8 @@ def Deprecated : DiagGroup<"deprecated", 
[DeprecatedAnonEnumEnumConversion,
   DeprecatedType,
   DeprecatedVolatile,
   DeprecatedWritableStr,
-  DeprecatedRedundantConstexprStaticDef
+  
DeprecatedRedundantConstexprStaticDef,
+  DeprecatedMissingCommaVariadicParam
   ]>,
  DiagCategory<"Deprecations">;
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 77bf08453dea51..7c3961059d1d0d 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -413,6 +413,9 @@ def err_function_scope_depth_exceeded : Error<
   "function scope depth exceeded maximum of %0">, DefaultFatal;
 def err_missing_comma_before_ellipsis : Error<
   "C requires a comma prior to the ellipsis in a variadic function type">;
+def warn_deprecated_missing_comma_before_ellipsis : Warning<
+  "variadic parameters that are not preceded by a comma are deprecated">,
+  InGroup;
 def err_unexpected_typedef_ident : Error<
   "unexpected type name %0: expected identifier">;
 def warn_cxx98_compat_decltype : Warning<
diff --git a/clang/lib/Parse/ParseDecl.cpp b/clang/lib/Parse/ParseDecl.cpp
index aa5c2d28d429ac..d28a74662aefe0 100644
--- a/clang/lib/Parse/ParseDecl.cpp
+++ b/clang/lib/Parse/ParseDecl.cpp
@@ -8119,6 +8119,14 @@ void Parser::ParseParameterDeclarationClause(
 }
 
 if (TryConsumeToken(tok::ellipsis, EllipsisLoc)) {
+  if (getLangOpts().CPlusPlus26) {
+// C++26 [dcl.dcl.fct]p3:
+//   A parameter-declaration-clause of the form
+//   parameter-list '...' is deprecated
+Diag(EllipsisLoc, diag::warn_deprecated_missing_comma_before_ellipsis)
+<< FixItHint::CreateInsertion(EllipsisLoc, ", ");
+  }
+
   if (!getLangOpts().CPlusPlus) {
 // We have ellipsis without a preceding ',', which is ill-formed
 // in C. Complain and provide the fix.
diff --git a/clang/test/CXX/drs/cwg722.cpp b/clang/test/CXX/drs/cwg722.cpp
index e90d9af360d9d0..6e7d4569c55381 100644
--- a/clang/test/CXX/drs/cwg722.cpp
+++ b/clang/test/CXX/drs/cwg722.cpp
@@ -14,7 +14,7 @@ namespace std {
   using nullptr_t = decltype(nullptr);
 }
 
-void f(std::nullptr_t...);
+void f(std::nullptr_t, ...);
 std::nullptr_t g();
 void h() {
   std::n

[clang] [clang] Implement P3176R1: The Oxford variadic comma (PR #117524)

2024-12-01 Thread via cfe-commits


@@ -0,0 +1,49 @@
+// RUN: %clang_cc1 -std=c++2c -fsyntax-only -verify %s
+
+void a(...);
+
+void b(auto...);
+void c(auto, ...);
+
+void d(auto..); // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}} \
+// expected-warning {{'...' in this location creates a 
C-style varargs function}} \
+// expected-note {{preceding '...' declares a function 
parameter pack}} \
+// expected-note {{insert ',' before '...' to silence this 
warning}}
+void e(auto..., ...);
+
+void f(auto x...); // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}}
+void g(auto x, ...);
+
+void h(auto... x...); // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}} \
+  // expected-warning {{'...' in this location creates a 
C-style varargs function}} \
+  // expected-note {{preceding '...' declares a function 
parameter pack}} \
+  // expected-note {{insert ',' before '...' to silence 
this warning}}
+void i(auto... x, ...);
+
+template
+void j(Ts... t...) {}; // expected-warning {{declaration of a variadic 
function without a comma before '...' is deprecated}} \
+   // expected-warning {{'...' in this location creates a 
C-style varargs function}} \
+   // expected-note {{preceding '...' declares a function 
parameter pack}} \
+   // expected-note {{insert ',' before '...' to silence 
this warning}}
+template
+void k(Ts... t, ...) {}
+
+void l(int...); // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}}
+void m(int, ...);
+
+void n(int x...); // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}}
+void o(int x, ...);
+
+struct S {
+  void p(this S...) {} // expected-warning {{declaration of a variadic 
function without a comma before '...' is deprecated}}
+};
+
+template
+void q(Ts..) {} // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}} \
+// expected-warning {{'...' in this location creates a 
C-style varargs function}} \
+// expected-note {{preceding '...' declares a function 
parameter pack}} \
+// expected-note {{insert ',' before '...' to silence this 
warning}}
+
+template
+void r(T...) {} // expected-warning {{declaration of a variadic function 
without a comma before '...' is deprecated}}

antangelo wrote:

Thanks, I've added these test cases

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread via cfe-commits

llvmbot wrote:



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

@llvm/pr-subscribers-clang

Author: Nathan Ridge (HighCommander4)


Changes

Fixes https://github.com/llvm/llvm-project/issues/118198

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
(+7) 
- (modified) clang/lib/Sema/SemaType.cpp (+10-7) 


``diff
diff --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 30b9b1902aa9c7..1ec51d862d0a6f 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -1092,6 +1092,13 @@ sizeof...($TemplateParameter[[Elements]]);
 $Field_dependentName[[waldo]];
   }
 };
+)cpp",
+  // Pointer-to-member with nested-name-specifiers
+  R"cpp(
+  struct $Class_def[[Outer]] {
+struct $Class_def[[Inner]] {};
+  };
+  using $Typedef_decl[[Alias]] = void ($Class[[Outer]]::$Class[[Inner]]:: 
*)();
 )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index f32edc5ac06440..73c9362208b14b 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5347,15 +5347,18 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
-  // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
+  // If ClsType is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization, it already stores the NNS prefix.
+  // Otherwise, wrap it in an Elaborated type to have a place to store
+  // the NNS prefix.
+  if (!(isa(NNSType) ||
+isa(NNSType) ||
+isa(NNSType))) {
 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
 NNSPrefix, ClsType);
+  }
   break;
 }
   } else {

``




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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits

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


[clang] [Clang] Recover GLTemplateParameterList for generic lambdas in RebuildLambdaScopeInfo (PR #118176)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Younan Zhang (zyn0217)


Changes

The NTTP argument appearing inside a trailing return type of a generic lambda 
would have to check for potential lambda captures, where the function needs 
GLTemplateParameterList of the current LSI to tell whether the lambda is 
generic.

The lambda scope in this context is rebuilt by the 
LambdaScopeForCallOperatorInstantiationRAII when substituting the lambda 
operator during template argument deduction. Thus, I think the template 
parameter list should be preserved in the rebuilding process, as it seems 
otherwise innocuous to me.

Fixes #115931

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+18-3) 
- (modified) clang/test/SemaCXX/lambda-capture-type-deduction.cpp (+16) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8bd06fadfdc984..e8e8a8cff76e45 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -714,6 +714,8 @@ Bug Fixes to C++ Support
   assumption if they also occur inside of a dependent lambda. (#GH114787)
 - Clang now uses valid deduced type locations when diagnosing functions with 
trailing return type
   missing placeholder return type. (#GH78694)
+- Fixed an incorrect lambda scope of generic lambdas that caused Clang to 
crash when computing potential lambda
+  captures at the end of a full expression. (#GH115931)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index 74b0e5ad23bd48..75389d6ba7bfd8 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -15504,10 +15504,25 @@ LambdaScopeInfo 
*Sema::RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator) {
   LSI->CallOperator = CallOperator;
   LSI->Lambda = LambdaClass;
   LSI->ReturnType = CallOperator->getReturnType();
-  // This function in calls in situation where the context of the call operator
-  // is not entered, so we set AfterParameterList to false, so that
+  // When this function is called in situation where the context of the call
+  // operator is not entered, we set AfterParameterList to false, so that
   // `tryCaptureVariable` finds explicit captures in the appropriate context.
-  LSI->AfterParameterList = false;
+  //
+  // There is also at least a situation as in 
FinishTemplateArgumentDeduction(),
+  // where we would set the CurContext to the lambda operator before
+  // substituting into it. In this case the flag needs to be true such that
+  // tryCaptureVariable can correctly handle potential captures thereof.
+  LSI->AfterParameterList = CurContext == CallOperator;
+  // GLTemplateParameterList is necessary for getCurGenericLambda() which is
+  // used at the point of dealing with potential captures.
+  //
+  // We don't use LambdaClass->isGenericLambda() because this value doesn't
+  // flip for instantiated generic lambdas, where no FunctionTemplateDecls are
+  // associated. (Technically, we could recover that list from their
+  // instantiation patterns, but for now, the GLTemplateParameterList seems
+  // unnecessary in these cases.)
+  if (FunctionTemplateDecl *FTD = CallOperator->getDescribedFunctionTemplate())
+LSI->GLTemplateParameterList = FTD->getTemplateParameters();
   const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
 
   if (LCD == LCD_None)
diff --git a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp 
b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
index a86f3018989927..234cb6806f041a 100644
--- a/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
+++ b/clang/test/SemaCXX/lambda-capture-type-deduction.cpp
@@ -298,6 +298,22 @@ void __trans_tmp_1() {
 
 }
 
+namespace GH115931 {
+
+struct Range {};
+
+template 
+struct LengthPercentage {};
+
+void reflectSum() {
+  Range resultR;
+  [&] (auto) -> LengthPercentage { 
+return {};
+  }(0);
+}
+
+} // namespace GH115931
+
 namespace GH47400 {
 
 struct Foo {};

``




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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits

HighCommander4 wrote:

(Marked as Draft since there are test failures I need to investigate.)

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits

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

Fixes https://github.com/llvm/llvm-project/issues/118198

>From 675aec86732ff4c46250fa0b17cd571387ca4ade Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 1 Dec 2024 19:58:03 -0500
Subject: [PATCH] [clang] [Sema] Preserve nested name specifier prefix in
 MemberPointerType

---
 .../unittests/SemanticHighlightingTests.cpp |  7 +++
 clang/lib/Sema/SemaType.cpp | 17 ++---
 2 files changed, 17 insertions(+), 7 deletions(-)

diff --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 30b9b1902aa9c7..1ec51d862d0a6f 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -1092,6 +1092,13 @@ sizeof...($TemplateParameter[[Elements]]);
 $Field_dependentName[[waldo]];
   }
 };
+)cpp",
+  // Pointer-to-member with nested-name-specifiers
+  R"cpp(
+  struct $Class_def[[Outer]] {
+struct $Class_def[[Inner]] {};
+  };
+  using $Typedef_decl[[Alias]] = void ($Class[[Outer]]::$Class[[Inner]]:: 
*)();
 )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index f32edc5ac06440..73c9362208b14b 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5347,15 +5347,18 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
-  // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
+  // If ClsType is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization, it already stores the NNS prefix.
+  // Otherwise, wrap it in an Elaborated type to have a place to store
+  // the NNS prefix.
+  if (!(isa(NNSType) ||
+isa(NNSType) ||
+isa(NNSType))) {
 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
 NNSPrefix, ClsType);
+  }
   break;
 }
   } else {

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


[clang] [Clang] Recover GLTemplateParameterList for generic lambdas in RebuildLambdaScopeInfo (PR #118176)

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

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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Matheus Izvekov via cfe-commits


@@ -5347,15 +5347,18 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
-  // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
+  // If ClsType is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization, it already stores the NNS prefix.
+  // Otherwise, wrap it in an Elaborated type to have a place to store
+  // the NNS prefix.
+  if (!(isa(NNSType) ||
+isa(NNSType) ||
+isa(NNSType))) {

mizvekov wrote:

This seems to be testing for conditions which seem impossible, the NNS would be 
malformed otherwise.

For example, what would it mean for the NNS type to be an ElaboratedType? If 
the NNS has a prefix, which would take precedence, that prefix or the 
ElaboratedType's prefix? If there is no prefix, what sense would it convey 
beyond using the Elaborated prefix as its prefix instead?

For DependentNameType, that would be redundant with how we represent these as 
Identifier + prefix, so we should prefer that over forming a NNS with such type.

The DTST is an exception here, as we lack a NNS kind for an identifier + list 
of template arguments, but then such DTST should not store a NNS itself, 
otherwise again this would be a bug somewhere else, as that would be redundant 
/ confusing with the NNS' own prefix as explained above.

So if we are getting either an ElaboratedType or a DependentNameType here, 
there seems to be a bug elsewhere.

Regarding the explanation for DependentTemplateSpecialization: even if the type 
node itself can have a nested name, it should not be present when the node is 
used as the type for a NNS node itself.

We should handle a DTST here by rebuilding it, adding the NNSPrefix as the 
DTST's nested name.

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


[clang] [-Wunsafe-buffer-usage] Suppress warning when 2-D constant arrays are indexed (PR #118249)

2024-12-01 Thread Malavika Samak via cfe-commits

https://github.com/malavikasamak created 
https://github.com/llvm/llvm-project/pull/118249

Do not warn about unsafe buffer access, when 2-D constant arrays are accessed 
and the indices are within the bounds of the buffer. Warning in such cases is a 
false postive. Such a suppression aleady exists for 1-d arrays and it is now 
extended to 2-D arrays.

(rdar://137926311)

>From 1b21a2eab2fabbb9bdc2e540e48a38aab90fd028 Mon Sep 17 00:00:00 2001
From: MalavikaSamak 
Date: Fri, 29 Nov 2024 14:53:37 +0530
Subject: [PATCH] [-Wunsafe-buffer-usage] Suppress warning when 2-D constant
 arrays are indexed

Do not warn about unsafe buffer access, when 2-D constant arrays are accessed
and the indices are within the bounds of the buffer. Warning in such cases is
a false postive. Such a suppression aleady exists for 1-d arrays and it is now
extended to 2-D arrays.

(rdar://137926311)
---
 clang/lib/Analysis/UnsafeBufferUsage.cpp  | 64 ++-
 .../warn-unsafe-buffer-usage-array.cpp|  6 ++
 ...n-unsafe-buffer-usage-fixits-parm-main.cpp |  3 +-
 ...e-buffer-usage-fixits-parm-unsupported.cpp |  2 +-
 .../test/SemaCXX/warn-unsafe-buffer-usage.cpp | 33 --
 5 files changed, 68 insertions(+), 40 deletions(-)

diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 5f36ffa926b269..f1e3b28fc03249 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -433,20 +433,56 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //already duplicated
   //  - call both from Sema and from here
 
-  const auto *BaseDRE =
+  auto CheckBounds = [](const ArraySubscriptExpr *ASE, uint64_t limit) -> bool 
{
+if (const auto *IdxLit = dyn_cast(ASE->getIdx())) {
+  const APInt ArrIdx = IdxLit->getValue();
+  if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
+return true;
+}
+return false;
+  };
+
+  const auto *BaseASE =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts());
+  uint64_t size = 0;
+
+  if (BaseASE) {
+const auto *DRE =
+dyn_cast(BaseASE->getBase()->IgnoreParenImpCasts());
+
+if (!DRE)
+  return false;
+
+const auto *CATy = dyn_cast(
+DRE->getType()->getUnqualifiedDesugaredType());
+if (!CATy) {
+  return false;
+}
+size = CATy->getLimitedSize();
+
+if (!CheckBounds(BaseASE, size))
+  return false;
+
+CATy = Finder->getASTContext().getAsConstantArrayType(BaseASE->getType());
+if (!CATy) {
+  return false;
+}
+
+size = CATy->getLimitedSize();
+return CheckBounds(&Node, size);
+  }
+
+  const DeclRefExpr *BaseDRE =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
   const auto *SLiteral =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
-  uint64_t size;
 
   if (!BaseDRE && !SLiteral)
 return false;
 
   if (BaseDRE) {
-if (!BaseDRE->getDecl())
-  return false;
-const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
-BaseDRE->getDecl()->getType());
+const auto *CATy =
+Finder->getASTContext().getAsConstantArrayType(BaseDRE->getType());
 if (!CATy) {
   return false;
 }
@@ -455,15 +491,7 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
 size = SLiteral->getLength() + 1;
   }
 
-  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
-const APInt ArrIdx = IdxLit->getValue();
-// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's 
a
-// bug
-if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < size)
-  return true;
-  }
-
-  return false;
+  return CheckBounds(&Node, size);
 }
 
 AST_MATCHER_P(CallExpr, hasNumArgs, unsigned, Num) {
@@ -1172,6 +1200,12 @@ class ArraySubscriptGadget : public WarningGadget {
 if (const auto *DRE =
 dyn_cast(ASE->getBase()->IgnoreParenImpCasts())) {
   return {DRE};
+} else if (const auto *BaseASE = dyn_cast(
+   ASE->getBase()->IgnoreParenImpCasts())) {
+  if (const auto *DRE = dyn_cast(
+  BaseASE->getBase()->IgnoreParenImpCasts())) {
+return {DRE};
+  }
 }
 
 return {};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
index c6c93a27e4b969..41cdc122b7d2fa 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -52,3 +52,9 @@ void constant_id_string(unsigned idx) {
   unsafe_char = ""[1]; //expected-warning{{unsafe buffer access}} 
   unsafe_char = ""[idx]; //expected-warning{{unsafe buffer access}}
 }
+
+typedef float Float4x4[4][4];
+
+float multi_dimension_array(Float4x4& matrix) {
+  return matrix[1][1];
+}
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
index c6b095031e0e32..d1fd1c00a9ea34 100644
--

[clang] [-Wunsafe-buffer-usage] Suppress warning when 2-D constant arrays are indexed (PR #118249)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-analysis

Author: Malavika Samak (malavikasamak)


Changes

Do not warn about unsafe buffer access, when 2-D constant arrays are accessed 
and the indices are within the bounds of the buffer. Warning in such cases is a 
false postive. Such a suppression aleady exists for 1-d arrays and it is now 
extended to 2-D arrays.

(rdar://137926311)

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


5 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+49-15) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp (+6) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp 
(+1-2) 
- (modified) 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp (+1-1) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp (+11-22) 


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 5f36ffa926b269..f1e3b28fc03249 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -433,20 +433,56 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //already duplicated
   //  - call both from Sema and from here
 
-  const auto *BaseDRE =
+  auto CheckBounds = [](const ArraySubscriptExpr *ASE, uint64_t limit) -> bool 
{
+if (const auto *IdxLit = dyn_cast(ASE->getIdx())) {
+  const APInt ArrIdx = IdxLit->getValue();
+  if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
+return true;
+}
+return false;
+  };
+
+  const auto *BaseASE =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts());
+  uint64_t size = 0;
+
+  if (BaseASE) {
+const auto *DRE =
+dyn_cast(BaseASE->getBase()->IgnoreParenImpCasts());
+
+if (!DRE)
+  return false;
+
+const auto *CATy = dyn_cast(
+DRE->getType()->getUnqualifiedDesugaredType());
+if (!CATy) {
+  return false;
+}
+size = CATy->getLimitedSize();
+
+if (!CheckBounds(BaseASE, size))
+  return false;
+
+CATy = Finder->getASTContext().getAsConstantArrayType(BaseASE->getType());
+if (!CATy) {
+  return false;
+}
+
+size = CATy->getLimitedSize();
+return CheckBounds(&Node, size);
+  }
+
+  const DeclRefExpr *BaseDRE =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
   const auto *SLiteral =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
-  uint64_t size;
 
   if (!BaseDRE && !SLiteral)
 return false;
 
   if (BaseDRE) {
-if (!BaseDRE->getDecl())
-  return false;
-const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
-BaseDRE->getDecl()->getType());
+const auto *CATy =
+Finder->getASTContext().getAsConstantArrayType(BaseDRE->getType());
 if (!CATy) {
   return false;
 }
@@ -455,15 +491,7 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
 size = SLiteral->getLength() + 1;
   }
 
-  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
-const APInt ArrIdx = IdxLit->getValue();
-// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's 
a
-// bug
-if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < size)
-  return true;
-  }
-
-  return false;
+  return CheckBounds(&Node, size);
 }
 
 AST_MATCHER_P(CallExpr, hasNumArgs, unsigned, Num) {
@@ -1172,6 +1200,12 @@ class ArraySubscriptGadget : public WarningGadget {
 if (const auto *DRE =
 dyn_cast(ASE->getBase()->IgnoreParenImpCasts())) {
   return {DRE};
+} else if (const auto *BaseASE = dyn_cast(
+   ASE->getBase()->IgnoreParenImpCasts())) {
+  if (const auto *DRE = dyn_cast(
+  BaseASE->getBase()->IgnoreParenImpCasts())) {
+return {DRE};
+  }
 }
 
 return {};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
index c6c93a27e4b969..41cdc122b7d2fa 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -52,3 +52,9 @@ void constant_id_string(unsigned idx) {
   unsafe_char = ""[1]; //expected-warning{{unsafe buffer access}} 
   unsafe_char = ""[idx]; //expected-warning{{unsafe buffer access}}
 }
+
+typedef float Float4x4[4][4];
+
+float multi_dimension_array(Float4x4& matrix) {
+  return matrix[1][1];
+}
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
index c6b095031e0e32..d1fd1c00a9ea34 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
@@ -8,6 +8,5 @@
 // main function
 int main(int argc, char *argv[]) { // expected-warning{{'argv' is an unsafe 
pointer used for buffer access}}
   char tmp;
-  tmp = argv[5][5];// expected-note{{us

[clang] [-Wunsafe-buffer-usage] Suppress warning when 2-D constant arrays are indexed (PR #118249)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Malavika Samak (malavikasamak)


Changes

Do not warn about unsafe buffer access, when 2-D constant arrays are accessed 
and the indices are within the bounds of the buffer. Warning in such cases is a 
false postive. Such a suppression aleady exists for 1-d arrays and it is now 
extended to 2-D arrays.

(rdar://137926311)

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


5 Files Affected:

- (modified) clang/lib/Analysis/UnsafeBufferUsage.cpp (+49-15) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp (+6) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp 
(+1-2) 
- (modified) 
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp (+1-1) 
- (modified) clang/test/SemaCXX/warn-unsafe-buffer-usage.cpp (+11-22) 


``diff
diff --git a/clang/lib/Analysis/UnsafeBufferUsage.cpp 
b/clang/lib/Analysis/UnsafeBufferUsage.cpp
index 5f36ffa926b269..f1e3b28fc03249 100644
--- a/clang/lib/Analysis/UnsafeBufferUsage.cpp
+++ b/clang/lib/Analysis/UnsafeBufferUsage.cpp
@@ -433,20 +433,56 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
   //already duplicated
   //  - call both from Sema and from here
 
-  const auto *BaseDRE =
+  auto CheckBounds = [](const ArraySubscriptExpr *ASE, uint64_t limit) -> bool 
{
+if (const auto *IdxLit = dyn_cast(ASE->getIdx())) {
+  const APInt ArrIdx = IdxLit->getValue();
+  if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < limit)
+return true;
+}
+return false;
+  };
+
+  const auto *BaseASE =
+  dyn_cast(Node.getBase()->IgnoreParenImpCasts());
+  uint64_t size = 0;
+
+  if (BaseASE) {
+const auto *DRE =
+dyn_cast(BaseASE->getBase()->IgnoreParenImpCasts());
+
+if (!DRE)
+  return false;
+
+const auto *CATy = dyn_cast(
+DRE->getType()->getUnqualifiedDesugaredType());
+if (!CATy) {
+  return false;
+}
+size = CATy->getLimitedSize();
+
+if (!CheckBounds(BaseASE, size))
+  return false;
+
+CATy = Finder->getASTContext().getAsConstantArrayType(BaseASE->getType());
+if (!CATy) {
+  return false;
+}
+
+size = CATy->getLimitedSize();
+return CheckBounds(&Node, size);
+  }
+
+  const DeclRefExpr *BaseDRE =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
   const auto *SLiteral =
   dyn_cast(Node.getBase()->IgnoreParenImpCasts());
-  uint64_t size;
 
   if (!BaseDRE && !SLiteral)
 return false;
 
   if (BaseDRE) {
-if (!BaseDRE->getDecl())
-  return false;
-const auto *CATy = Finder->getASTContext().getAsConstantArrayType(
-BaseDRE->getDecl()->getType());
+const auto *CATy =
+Finder->getASTContext().getAsConstantArrayType(BaseDRE->getType());
 if (!CATy) {
   return false;
 }
@@ -455,15 +491,7 @@ AST_MATCHER(ArraySubscriptExpr, isSafeArraySubscript) {
 size = SLiteral->getLength() + 1;
   }
 
-  if (const auto *IdxLit = dyn_cast(Node.getIdx())) {
-const APInt ArrIdx = IdxLit->getValue();
-// FIXME: ArrIdx.isNegative() we could immediately emit an error as that's 
a
-// bug
-if (ArrIdx.isNonNegative() && ArrIdx.getLimitedValue() < size)
-  return true;
-  }
-
-  return false;
+  return CheckBounds(&Node, size);
 }
 
 AST_MATCHER_P(CallExpr, hasNumArgs, unsigned, Num) {
@@ -1172,6 +1200,12 @@ class ArraySubscriptGadget : public WarningGadget {
 if (const auto *DRE =
 dyn_cast(ASE->getBase()->IgnoreParenImpCasts())) {
   return {DRE};
+} else if (const auto *BaseASE = dyn_cast(
+   ASE->getBase()->IgnoreParenImpCasts())) {
+  if (const auto *DRE = dyn_cast(
+  BaseASE->getBase()->IgnoreParenImpCasts())) {
+return {DRE};
+  }
 }
 
 return {};
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
index c6c93a27e4b969..41cdc122b7d2fa 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-array.cpp
@@ -52,3 +52,9 @@ void constant_id_string(unsigned idx) {
   unsafe_char = ""[1]; //expected-warning{{unsafe buffer access}} 
   unsafe_char = ""[idx]; //expected-warning{{unsafe buffer access}}
 }
+
+typedef float Float4x4[4][4];
+
+float multi_dimension_array(Float4x4& matrix) {
+  return matrix[1][1];
+}
diff --git a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp 
b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
index c6b095031e0e32..d1fd1c00a9ea34 100644
--- a/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
+++ b/clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-main.cpp
@@ -8,6 +8,5 @@
 // main function
 int main(int argc, char *argv[]) { // expected-warning{{'argv' is an unsafe 
pointer used for buffer access}}
   char tmp;
-  tmp = argv[5][5];// expected-note{{used in buf

[clang] [-Wunsafe-buffer-usage] Suppress warning when 2-D constant arrays are indexed (PR #118249)

2024-12-01 Thread via cfe-commits

graphite-app[bot] wrote:

## Your org has enabled the Graphite merge queue for merging into main

Add the label “FP Bundles” to the PR and Graphite will automatically add it to 
the merge queue when it’s ready to merge.

You must have a Graphite account and log in to Graphite in order to use the 
merge queue. Sign up using [this 
link](https://app.graphite.dev/invite/github/llvm?ref=merge-queue-instructions-comment&prId=5670068095).

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


[clang] [Clang][OpenCL][AMDGPU] Allow a kernel to call another kernel (PR #115821)

2024-12-01 Thread Aniket Lal via cfe-commits


@@ -1780,6 +1786,15 @@ void CXXNameMangler::mangleDeviceStubName(const 
IdentifierInfo *II) {
   << II->getName();
 }
 
+void CXXNameMangler::mangleOCLDeviceStubName(const IdentifierInfo *II) {
+  //  ::=  __clang_ocl_kern_imp_
+  //   ::= [n]  
+  // ::= 
+  StringRef OCLDeviceStubNamePrefix = "__clang_ocl_kern_imp_";

lalaniket8 wrote:

names starting with double underscore are reserved, and shouldn't conflict with 
user defined names

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


[clang] [Clang][OpenCL][AMDGPU] Allow a kernel to call another kernel (PR #115821)

2024-12-01 Thread Aniket Lal via cfe-commits

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


[clang] [ast matcher] add `ExportDecl` in dynamically matchers (PR #118258)

2024-12-01 Thread via cfe-commits

graphite-app[bot] wrote:

## Your org has enabled the Graphite merge queue for merging into main

Add the label “FP Bundles” to the PR and Graphite will automatically add it to 
the merge queue when it’s ready to merge.

You must have a Graphite account and log in to Graphite in order to use the 
merge queue. Sign up using [this 
link](https://app.graphite.dev/invite/github/llvm?ref=merge-queue-instructions-comment&prId=5670269521).

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


[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread Lu Weining via cfe-commits

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

LGTM for the LoongArch bits.

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


[clang] [llvm] Implement operand bundles for floating-point operations (PR #109798)

2024-12-01 Thread Serge Pavlov via cfe-commits

spavloff wrote:

### Merge activity

* **Dec 2, 1:35 AM EST**: The merge label 'FP Bundles' was detected. This PR 
will be added to the [Graphite merge 
queue](https://app.graphite.dev/merges?org=llvm&repo=llvm-project) once it 
meets the requirements.


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


[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Nathan Ridge via cfe-commits


@@ -5347,13 +5347,16 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
   // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  // TemplateSpecializationType or a RecordType, then the NNS prefix is
+  // NOT included in ClsType; hence we wrap ClsType into an
+  // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
+  // already is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization.
+  if (isa(NNSType) ||
+  (NNSPrefix && isa(NNSType)))

HighCommander4 wrote:

> We use an ElaboratedType with null prefix to represent a type which was 
> written without qualifiers, so it seems arbitrary to not add the elaboration 
> in this case.

Wrapping RecordTypes into ElaboratedTypes with a null prefix was causing a 
bunch of failures on the first draft of the patch.

For example, on this line:

https://github.com/llvm/llvm-project/blob/8cb44859cc31929521c09fc6a8add66d53db44de/clang/test/CXX/conv/conv.mem/p4.cpp#L22

the change has the effect of changing the way the derived type is printed from 
`test1::Derived` to just `Derived`, I guess because when the diagnostic 
formatter encounters an `ElaboratedType` it says "I know how the type was 
printed in the source, I will print it the same way in the diagnostic".

Should we accept changes like this to diagnostic output?

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


[clang] c4a1e0e - [clang] Remove redundant integer values in template type diffing

2024-12-01 Thread Richard Trieu via cfe-commits

Author: Richard Trieu
Date: 2024-12-01T19:21:42-08:00
New Revision: c4a1e0efe6b0767dfb5861a7e8814d7db0c0de8a

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

LOG: [clang] Remove redundant integer values in template type diffing

Look through SubstNonTypeTemplateParmExpr to find an IntegerLiteral
node when attempting to determine if extra info is printed via
the aka mechanism.  This will avoid printing types such as
"array<5 aka 5>" and will only show "array<5>".

Added: 


Modified: 
clang/lib/AST/ASTDiagnostic.cpp
clang/test/Misc/diag-template-diffing-cxx98.cpp

Removed: 




diff  --git a/clang/lib/AST/ASTDiagnostic.cpp b/clang/lib/AST/ASTDiagnostic.cpp
index 4f677b60e60dae..7b873ee9833b34 100644
--- a/clang/lib/AST/ASTDiagnostic.cpp
+++ b/clang/lib/AST/ASTDiagnostic.cpp
@@ -1899,11 +1899,17 @@ class TemplateDiff {
 
 E = E->IgnoreImpCasts();
 
-if (isa(E)) return false;
+auto CheckIntegerLiteral = [](Expr *E) {
+  if (auto *TemplateExpr = dyn_cast(E))
+E = TemplateExpr->getReplacement();
+  return isa(E);
+};
+
+if (CheckIntegerLiteral(E)) return false;
 
 if (UnaryOperator *UO = dyn_cast(E))
   if (UO->getOpcode() == UO_Minus)
-if (isa(UO->getSubExpr()))
+if (CheckIntegerLiteral(UO->getSubExpr()))
   return false;
 
 if (isa(E))

diff  --git a/clang/test/Misc/diag-template-
diff ing-cxx98.cpp b/clang/test/Misc/diag-template-
diff ing-cxx98.cpp
index 7b1a08c6b86915..888b9f8b0e5e3d 100644
--- a/clang/test/Misc/diag-template-
diff ing-cxx98.cpp
+++ b/clang/test/Misc/diag-template-
diff ing-cxx98.cpp
@@ -47,3 +47,35 @@ namespace qualifiers {
 
   // CHECK: candidate template ignored: deduced conflicting types for 
parameter 'T' ('const vector<...>' vs. 'volatile vector<...>')
 }
+
+namespace integers {
+  template 
+  class wrapper{};
+
+  template 
+  class foo {
+   public:
+wrapper make();
+  };
+
+  wrapper<1> w1 = foo<2>().make();
+  // CHECK: no viable conversion from 'wrapper<2>' to 'wrapper<1>'
+
+  wrapper<1> w2 = foo<-3>().make();
+  // CHECK: no viable conversion from 'wrapper<-3>' to 'wrapper<1>'
+
+  template 
+  wrapper make();
+
+  wrapper<1> w3 = make<4>();
+  // CHECK: no viable conversion from 'wrapper<4>' to 'wrapper<1>'
+
+  template 
+  wrapper<-x> makeNegative();
+
+  wrapper<1> w4 = makeNegative<5>();
+  // CHECK: no viable conversion from 'wrapper<-5>' to 'wrapper<1>'
+
+  wrapper<1> w5 = makeNegative<-6>();
+  // CHECK: no viable conversion from 'wrapper<6>' to 'wrapper<1>'
+}



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


[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread Zhaoxin Yang via cfe-commits


@@ -240,7 +240,8 @@ def m_riscv_Features_Group : OptionGroup<"">,
 def m_ve_Features_Group : OptionGroup<"">,
   Group, DocName<"VE">;
 def m_loongarch_Features_Group : OptionGroup<"">,
- Group, DocName<"LoongArch">;
+ Group, DocName<"LoongArch">,
+ Visibility<[ClangOption, CLOption, 
FlangOption]>;

ylzsx wrote:

```
def m_Group : OptionGroup<"">, Group,
  DocName<"Target-dependent compilation options">,
  Visibility<[ClangOption, CLOption]>;
```

I wondor if it inherits from `m_Group` when `Visibility` is not specified. If 
so, it originally contained `CLOption`.

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


[clang] Add `.cjs` extension handling for JavaScript Language. (PR #118188)

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


@@ -87,7 +87,7 @@ static cl::opt AssumeFileName(
  "supported:\n"
  "  CSharp: .cs\n"
  "  Java: .java\n"
- "  JavaScript: .mjs .js .ts\n"
+ "  JavaScript: .cjs .mjs .js .ts\n"

owenca wrote:

```suggestion
 "  JavaScript: .js .mjs .cjs .ts\n"
```

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


[clang] Add `.cjs` extension handling for JavaScript Language. (PR #118188)

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


@@ -94,7 +94,7 @@ def main():
   # Other languages that clang-format supports
   'proto', 'protodevel',  # Protocol Buffers
   'java',  # Java
-  'mjs', 'js',  # JavaScript
+  'cjs', 'mjs', 'js',  # JavaScript

owenca wrote:

```suggestion
  'js', 'mjs', 'cjs',  # JavaScript
```

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


[clang] [clang-format] Add support for `.cjs` as JavaScript file extension (PR #118188)

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

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


[clang] Add `.cjs` extension handling for JavaScript Language. (PR #118188)

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


@@ -49,7 +49,7 @@ to format C/C++/Java/JavaScript/JSON/Objective-C/Protobuf/C# 
code.
  supported:
CSharp: .cs
Java: .java
-   JavaScript: .mjs .js .ts
+   JavaScript: .mjs .js .ts .cjs

owenca wrote:

```suggestion
   JavaScript: .js .mjs .cjs .ts
```

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


[clang] [llvm] Reimplement constrained 'trunc' using operand bundles (PR #118253)

2024-12-01 Thread Serge Pavlov via cfe-commits

spavloff wrote:

### Merge activity

* **Dec 2, 12:55 AM EST**: The merge label 'FP Bundles' was detected. This PR 
will be added to the [Graphite merge 
queue](https://app.graphite.dev/merges?org=llvm&repo=llvm-project) once it 
meets the requirements.


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


[clang] [llvm] Reimplement constrained 'trunc' using operand bundles (PR #118253)

2024-12-01 Thread via cfe-commits

https://github.com/graphite-app[bot] edited 
https://github.com/llvm/llvm-project/pull/118253
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [clang-tools-extra] [clang-tidy][use-internal-linkage]fix false positives for ExportDecl (PR #117901)

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

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


[clang] 010317e - [clang-tidy][use-internal-linkage]fix false positives for ExportDecl (#117901)

2024-12-01 Thread via cfe-commits

Author: Congcong Cai
Date: 2024-12-02T13:59:55+08:00
New Revision: 010317e1731d76b91c00ed1241583e518380d65f

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

LOG: [clang-tidy][use-internal-linkage]fix false positives for ExportDecl 
(#117901)

Fixed: #97190

Added: 

clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-module.cpp

Modified: 
clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/docs/clang-tidy/checks/misc/use-internal-linkage.rst
clang/docs/LibASTMatchersReference.html
clang/docs/ReleaseNotes.rst
clang/include/clang/ASTMatchers/ASTMatchers.h
clang/lib/ASTMatchers/ASTMatchersInternal.cpp
clang/unittests/ASTMatchers/ASTMatchersNodeTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
index 0c417f6374bc50..1e0f398a4a560b 100644
--- a/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
+++ b/clang-tools-extra/clang-tidy/misc/UseInternalLinkageCheck.cpp
@@ -118,8 +118,11 @@ void UseInternalLinkageCheck::registerMatchers(MatchFinder 
*Finder) {
 isExternStorageClass(), isExternC(),
 // 3. template
 isExplicitTemplateSpecialization(),
-// 4. friend
-hasAncestor(friendDecl();
+hasAncestor(decl(anyOf(
+// 4. friend
+friendDecl(),
+// 5. module export decl
+exportDecl()));
   Finder->addMatcher(
   functionDecl(Common, hasBody(),
unless(anyOf(cxxMethodDecl(),

diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index ec666aeb2ad8ab..453a91e3b504cd 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -248,7 +248,8 @@ Changes in existing checks
   ` check to insert ``static``
   keyword before type qualifiers such as ``const`` and ``volatile`` and fix
   false positives for function declaration without body and fix false positives
-  for global scoped overloaded ``operator new`` and ``operator delete``.
+  for C++20 export declarations and fix false positives for global scoped
+  overloaded ``operator new`` and ``operator delete``.
 
 - Improved :doc:`modernize-avoid-c-arrays
   ` check to suggest using 

diff  --git 
a/clang-tools-extra/docs/clang-tidy/checks/misc/use-internal-linkage.rst 
b/clang-tools-extra/docs/clang-tidy/checks/misc/use-internal-linkage.rst
index b8bbcc62706101..508b0cac09a912 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/misc/use-internal-linkage.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/misc/use-internal-linkage.rst
@@ -29,6 +29,11 @@ Example:
   void fn3(); // without function body in all declaration, maybe external 
linkage
   void fn3();
 
+  // export declarations
+  export void fn4() {}
+  export namespace t { void fn5() {} }
+  export int v2;
+
 Options
 ---
 

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-module.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-module.cpp
new file mode 100644
index 00..9b0d8cde429b6b
--- /dev/null
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/use-internal-linkage-module.cpp
@@ -0,0 +1,20 @@
+// RUN: %check_clang_tidy -std=c++20 %s misc-use-internal-linkage %t -- -- 
-I%S/Inputs/use-internal-linkage
+
+module;
+
+export module test;
+
+export void single_export_fn() {}
+export int single_export_var;
+
+export {
+  void group_export_fn1() {}
+  void group_export_fn2() {}
+  int group_export_var1;
+  int group_export_var2;
+}
+
+export namespace aa {
+void namespace_export_fn() {}
+int namespace_export_var;
+} // namespace aa

diff  --git a/clang/docs/LibASTMatchersReference.html 
b/clang/docs/LibASTMatchersReference.html
index c6307954d7f1bb..f18e9cf1341696 100644
--- a/clang/docs/LibASTMatchersReference.html
+++ b/clang/docs/LibASTMatchersReference.html
@@ -804,6 +804,17 @@ Node Matchers
 
 
 
+MatcherDecl>exportDeclMatcherExportDecl>...
+Matches any export 
declaration.
+
+Example matches following declarations.
+  export void foo();
+  export { void foo(); }
+  export namespace { void foo(); }
+  export int v;
+
+
+
 MatcherDecl>fieldDeclMatcherFieldDecl>...
 Matches field 
declarations.
 

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/do

[clang] [clang-tools-extra] [clang] [Sema] Preserve nested name specifier prefix in MemberPointerType (PR #118236)

2024-12-01 Thread Matheus Izvekov via cfe-commits


@@ -5347,13 +5347,16 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
 
 case NestedNameSpecifier::TypeSpec:
 case NestedNameSpecifier::TypeSpecWithTemplate:
-  ClsType = QualType(NNS->getAsType(), 0);
+  const Type *NNSType = NNS->getAsType();
+  ClsType = QualType(NNSType, 0);
   // Note: if the NNS has a prefix and ClsType is a nondependent
-  // TemplateSpecializationType, then the NNS prefix is NOT included
-  // in ClsType; hence we wrap ClsType into an ElaboratedType.
-  // NOTE: in particular, no wrap occurs if ClsType already is an
-  // Elaborated, DependentName, or DependentTemplateSpecialization.
-  if (isa(NNS->getAsType()))
+  // TemplateSpecializationType or a RecordType, then the NNS prefix is
+  // NOT included in ClsType; hence we wrap ClsType into an
+  // ElaboratedType. NOTE: in particular, no wrap occurs if ClsType
+  // already is an Elaborated, DependentName, or
+  // DependentTemplateSpecialization.
+  if (isa(NNSType) ||
+  (NNSPrefix && isa(NNSType)))

mizvekov wrote:

Yes exactly, this test change is correct, because the type was written as 
'Derived' and not 'test1::Derived', and the diagnostics are supposed to print 
the type as written. It would be inconsistent to print the type as written when 
it has any qualifier, but print it fully qualified when it does not have any.

We started doing this consistently since this patch: 
https://reviews.llvm.org/D112374

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


[clang] [llvm] Implement operand bundles for floating-point operations (PR #109798)

2024-12-01 Thread Serge Pavlov via cfe-commits

spavloff wrote:

PR https://github.com/llvm/llvm-project/pull/118253 demonstrates changes 
required to upgrade an intrinsic (`trunc` in this case) to using FP operand 
bundles. 

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


[clang] [flang] [Flang][LoongArch] Enable clang command-line options in flang. (PR #118244)

2024-12-01 Thread Lu Weining via cfe-commits


@@ -240,7 +240,8 @@ def m_riscv_Features_Group : OptionGroup<"">,
 def m_ve_Features_Group : OptionGroup<"">,
   Group, DocName<"VE">;
 def m_loongarch_Features_Group : OptionGroup<"">,
- Group, DocName<"LoongArch">;
+ Group, DocName<"LoongArch">,
+ Visibility<[ClangOption, CLOption, 
FlangOption]>;

SixWeining wrote:

Yes. It should be.

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


[clang] [ast matcher] add `ExportDecl` in dynamically matchers (PR #118258)

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

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

None

>From f9fbb478194a429f1879c176504b8596312b9baf Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 2 Dec 2024 14:08:47 +0800
Subject: [PATCH] [ast matcher] add `ExportDecl` in dynamically matchers

---
 clang/lib/ASTMatchers/Dynamic/Registry.cpp | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 8d36ad5c80b5d4..8edad28bc2e58f 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -604,6 +604,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(usingDecl);
   REGISTER_MATCHER(usingEnumDecl);
   REGISTER_MATCHER(usingDirectiveDecl);
+  REGISTER_MATCHER(exportDecl);
   REGISTER_MATCHER(valueDecl);
   REGISTER_MATCHER(varDecl);
   REGISTER_MATCHER(variableArrayType);

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


[clang] [ast matcher] add `ExportDecl` in dynamically matchers (PR #118258)

2024-12-01 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes



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


1 Files Affected:

- (modified) clang/lib/ASTMatchers/Dynamic/Registry.cpp (+1) 


``diff
diff --git a/clang/lib/ASTMatchers/Dynamic/Registry.cpp 
b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
index 8d36ad5c80b5d4..8edad28bc2e58f 100644
--- a/clang/lib/ASTMatchers/Dynamic/Registry.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Registry.cpp
@@ -604,6 +604,7 @@ RegistryMaps::RegistryMaps() {
   REGISTER_MATCHER(usingDecl);
   REGISTER_MATCHER(usingEnumDecl);
   REGISTER_MATCHER(usingDirectiveDecl);
+  REGISTER_MATCHER(exportDecl);
   REGISTER_MATCHER(valueDecl);
   REGISTER_MATCHER(varDecl);
   REGISTER_MATCHER(variableArrayType);

``




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


[clang] [flang] [clang][driver] Special care for -l flags in config files (PR #117573)

2024-12-01 Thread Paul Osmialowski via cfe-commits

pawosm-arm wrote:

> > I took a look and I think it may be too awkward to do, as we'd want to run 
> > e.g. readelf afterwards. But an example is 
> > `lld/test/ELF/as-needed-not-in-regular.s`. The idea being: if 
> > `-Wl,--as-needed` is in the config file, do we correctly prune an 
> > unnecessary library from a built object, or is the order wrong? We can 
> > check that with `llvm-readelf`.
> 
> There are two problems here. First, following the readelf path goes too far 
> into the linker competences, whatever is set for the linker, the linker is 
> obliged to do, and the order of whatever is set for the linker is already 
> tested by other `-Wl,` occurrences in the currently available test cases.
> 
> Yet your request also exposes another problem, and I can see that further 
> comments also mention it. With my patch, there is no way to affect the user's 
> command line linker input parameters. So if a config file is a mean for 
> turning clang's behavior into the gcc's behavior (AFAIR, gcc always emits 
> `-Wl,--as-needed` at the beginning of the linker invocation command line, 
> while clang doesn't do that), this patch rejects such possibility. Something 
> more clever is needed, the positional idea seems the right one, I could see 
> it like this (a config file example, notice the pipe `|` character):
> 
> ```
> -Wall -Wl,--as-needed | -lm -Wl,-Bstatic -lhappy -Wl,-Bdynamic
> ```
> 
> ...things after the pipe would be appended at the end of the parameters list 
> and only when it is known that there will be the linking. But this would 
> require a modification in the config file reading routine, the second list of 
> config options would have to be created much earlier than my patch proposes.
> 
> Back to the drawing board then.

Actually, it was easy to implement, I've presented it here.


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


[clang] [flang] [clang][driver] Special care for -l flags in config files (PR #117573)

2024-12-01 Thread Paul Osmialowski via cfe-commits

https://github.com/pawosm-arm updated 
https://github.com/llvm/llvm-project/pull/117573

>From b9dd5f9356d457ef1ad050083d650a1da21c4377 Mon Sep 17 00:00:00 2001
From: Pawel Osmialowski 
Date: Mon, 25 Nov 2024 14:46:55 +
Subject: [PATCH] [clang][driver] Special care for -l and -Wl, flags in config
 files

Currently, if a -l (or -Wl,) flag is added into a config file
(e.g. clang.cfg), it is situated before any object file in the
effective command line. If the library requested by given -l flag is
static, its symbols will not be made visible to any of the object
files provided by the user. Also, the presence of any of the linker
flags in a config file confuses the driver whenever the user invokes
clang without any parameters.

This patch attempts to solve both of the problems, by allowing a split
of the arguments list around the pipe character. The head part of the
list will be used as before, but the tail part will be appended after
the command line flags provided by the user and only when it is known
that the linking should occur.
---
 clang/include/clang/Driver/Driver.h   |  3 ++
 clang/lib/Driver/Driver.cpp   | 55 +++
 clang/test/Driver/Inputs/config-l.cfg |  1 +
 clang/test/Driver/config-file.c   | 26 +
 flang/test/Driver/Inputs/config-l.cfg |  1 +
 flang/test/Driver/config-file.f90 | 26 +
 6 files changed, 104 insertions(+), 8 deletions(-)
 create mode 100644 clang/test/Driver/Inputs/config-l.cfg
 create mode 100644 flang/test/Driver/Inputs/config-l.cfg

diff --git a/clang/include/clang/Driver/Driver.h 
b/clang/include/clang/Driver/Driver.h
index 9177d56718ee77..b21606b6f54b77 100644
--- a/clang/include/clang/Driver/Driver.h
+++ b/clang/include/clang/Driver/Driver.h
@@ -297,6 +297,9 @@ class Driver {
   /// Object that stores strings read from configuration file.
   llvm::StringSaver Saver;
 
+  /// Linker inputs originated from configuration file.
+  std::unique_ptr CfgLinkerInputs;
+
   /// Arguments originated from configuration file.
   std::unique_ptr CfgOptions;
 
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 7de8341b8d2d61..9ea22419d392b0 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -1039,34 +1039,63 @@ bool Driver::readConfigFile(StringRef FileName,
   }
 
   // Try reading the given file.
-  SmallVector NewCfgArgs;
-  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
+  SmallVector NewCfgFileArgs;
+  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgFileArgs)) {
 Diag(diag::err_drv_cannot_read_config_file)
 << FileName << toString(std::move(Err));
 return true;
   }
 
+  // Populate head and tail lists. The tail list is used only when linking.
+  SmallVector NewCfgHeadArgs, NewCfgTailArgs;
+  bool SeenPipe = false;
+  for (const char *Opt : NewCfgFileArgs) {
+if (!strcmp(Opt, "|")) {
+  SeenPipe = true;
+} else {
+  if (SeenPipe)
+NewCfgTailArgs.push_back(Opt);
+  else
+NewCfgHeadArgs.push_back(Opt);
+}
+  }
+
   // Read options from config file.
   llvm::SmallString<128> CfgFileName(FileName);
   llvm::sys::path::native(CfgFileName);
-  bool ContainErrors;
-  auto NewOptions = std::make_unique(
-  ParseArgStrings(NewCfgArgs, /*UseDriverMode=*/true, ContainErrors));
+  bool ContainErrors = false;
+  auto NewHeadOptions = std::make_unique(
+  ParseArgStrings(NewCfgHeadArgs, /*UseDriverMode=*/true, ContainErrors));
+  if (ContainErrors)
+return true;
+  auto NewTailOptions = std::make_unique(
+  ParseArgStrings(NewCfgTailArgs, /*UseDriverMode=*/true, ContainErrors));
   if (ContainErrors)
 return true;
 
   // Claim all arguments that come from a configuration file so that the driver
   // does not warn on any that is unused.
-  for (Arg *A : *NewOptions)
+  for (Arg *A : *NewHeadOptions)
+A->claim();
+  for (Arg *A : *NewTailOptions)
 A->claim();
 
   if (!CfgOptions)
-CfgOptions = std::move(NewOptions);
+CfgOptions = std::move(NewHeadOptions);
   else {
 // If this is a subsequent config file, append options to the previous one.
-for (auto *Opt : *NewOptions)
+for (auto *Opt : *NewHeadOptions)
   appendOneArg(*CfgOptions, Opt);
   }
+
+  if (!CfgLinkerInputs)
+CfgLinkerInputs = std::move(NewTailOptions);
+  else {
+// If this is a subsequent config file, append options to the previous one.
+for (auto *Opt : *NewTailOptions)
+  appendOneArg(*CfgLinkerInputs, Opt);
+  }
+
   ConfigFiles.push_back(std::string(CfgFileName));
   return false;
 }
@@ -1244,6 +1273,7 @@ Compilation *Driver::BuildCompilation(ArrayRef ArgList) {
   if (!ContainsError)
 ContainsError = loadConfigFiles();
   bool HasConfigFile = !ContainsError && (CfgOptions.get() != nullptr);
+  bool HasConfigLinkerIn = !ContainsError && CfgLinkerInputs;
 
   // All arguments, from both config file and command line.
   InputArgList Args = std::move(HasCo

[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread via cfe-commits

https://github.com/veera-sivarajan updated 
https://github.com/llvm/llvm-project/pull/116888

>From a0f38f1b37d7a5d9283e65cb9af07881c6fc5c14 Mon Sep 17 00:00:00 2001
From: Veera 
Date: Thu, 28 Nov 2024 18:07:30 +
Subject: [PATCH 1/2] Add Test

---
 .../InstCombine/canonicalize-const-to-bop.ll  | 414 ++
 1 file changed, 414 insertions(+)
 create mode 100644 
llvm/test/Transforms/InstCombine/canonicalize-const-to-bop.ll

diff --git a/llvm/test/Transforms/InstCombine/canonicalize-const-to-bop.ll 
b/llvm/test/Transforms/InstCombine/canonicalize-const-to-bop.ll
new file mode 100644
index 00..a23fc84aebd2e3
--- /dev/null
+++ b/llvm/test/Transforms/InstCombine/canonicalize-const-to-bop.ll
@@ -0,0 +1,414 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 5
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+define i8 @add_and_sgt(i8 %x) {
+; CHECK-LABEL: define i8 @add_and_sgt(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = add nsw i8 [[X]], 16
+; CHECK-NEXT:[[CMP:%.*]] = icmp sgt i8 [[X]], 8
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 [[ADD]], i8 24
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %add = add nsw i8 %x, 16
+  %cmp = icmp sgt i8 %x, 8
+  %s = select i1 %cmp, i8 %add, i8 24
+  ret i8 %s
+}
+
+define i8 @add_sgt_nuw(i8 %x) {
+; CHECK-LABEL: define i8 @add_sgt_nuw(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = add nuw i8 [[X]], 16
+; CHECK-NEXT:[[CMP:%.*]] = icmp sgt i8 [[X]], 8
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 [[ADD]], i8 24
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %add = add nuw i8 %x, 16
+  %cmp = icmp sgt i8 %x, 8
+  %s = select i1 %cmp, i8 %add, i8 24
+  ret i8 %s
+}
+
+define i8 @sub_and_ugt(i8 %x) {
+; CHECK-LABEL: define i8 @sub_and_ugt(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[SUB:%.*]] = add nsw i8 [[X]], -50
+; CHECK-NEXT:[[CMP:%.*]] = icmp ugt i8 [[X]], 100
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 50, i8 [[SUB]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %sub = sub nsw i8 %x, 50
+  %cmp = icmp ugt i8 %x, 100
+  %s = select i1 %cmp, i8 50, i8 %sub
+  ret i8 %s
+}
+
+define i8 @sub_ugt_nuw_nsw(i8 %x) {
+; CHECK-LABEL: define i8 @sub_ugt_nuw_nsw(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[SUB:%.*]] = add nsw i8 [[X]], -50
+; CHECK-NEXT:[[CMP:%.*]] = icmp ugt i8 [[X]], 100
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 50, i8 [[SUB]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %sub = sub nuw nsw i8 %x, 50
+  %cmp = icmp ugt i8 %x, 100
+  %s = select i1 %cmp, i8 50, i8 %sub
+  ret i8 %s
+}
+
+define i8 @mul_and_ult(i8 %x) {
+; CHECK-LABEL: define i8 @mul_and_ult(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = mul nsw i8 [[X]], 10
+; CHECK-NEXT:[[CMP:%.*]] = icmp ugt i8 [[X]], 10
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 100, i8 [[ADD]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %add = mul nsw i8 %x, 10
+  %cmp = icmp ult i8 10, %x
+  %s = select i1 %cmp, i8 100, i8 %add
+  ret i8 %s
+}
+
+define i8 @mul_and_non_strict_predicate(i8 %x) {
+; CHECK-LABEL: define i8 @mul_and_non_strict_predicate(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = mul nsw i8 [[X]], 10
+; CHECK-NEXT:[[CMP:%.*]] = icmp sgt i8 [[X]], 9
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 100, i8 [[ADD]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %add = mul nsw i8 %x, 10
+  %cmp = icmp sle i8 10, %x
+  %s = select i1 %cmp, i8 100, i8 %add
+  ret i8 %s
+}
+
+define i8 @mul_ult_noflags(i8 %x) {
+; CHECK-LABEL: define i8 @mul_ult_noflags(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = mul i8 [[X]], 10
+; CHECK-NEXT:[[CMP:%.*]] = icmp ugt i8 [[X]], 10
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 100, i8 [[ADD]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %add = mul i8 %x, 10
+  %cmp = icmp ult i8 10, %x
+  %s = select i1 %cmp, i8 100, i8 %add
+  ret i8 %s
+}
+
+define i8 @udiv_and_slt(i8 %x) {
+; CHECK-LABEL: define i8 @udiv_and_slt(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[SUB:%.*]] = udiv i8 [[X]], 10
+; CHECK-NEXT:[[CMP:%.*]] = icmp slt i8 [[X]], 100
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 10, i8 [[SUB]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %sub = udiv i8 %x, 10
+  %cmp = icmp slt i8 %x, 100
+  %s = select i1 %cmp, i8 10, i8 %sub
+  ret i8 %s
+}
+
+define i8 @udiv_slt_exact(i8 %x) {
+; CHECK-LABEL: define i8 @udiv_slt_exact(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[SUB:%.*]] = udiv exact i8 [[X]], 10
+; CHECK-NEXT:[[CMP:%.*]] = icmp slt i8 [[X]], 100
+; CHECK-NEXT:[[S:%.*]] = select i1 [[CMP]], i8 10, i8 [[SUB]]
+; CHECK-NEXT:ret i8 [[S]]
+;
+  %sub = udiv exact i8 %x, 10
+  %cmp = icmp slt i8 %x, 100
+  %s = select i1 %cmp, i8 10, i8 %sub
+  ret i8 %s
+}
+
+define i8 @canonicalize_icmp_operands(i8 %x) {
+; CHECK-LABEL: define i8 @canonicalize_icmp_operands(
+; CHECK-SAME: i8 [[X:%.*]]) {
+; CHECK-NEXT:[[ADD:%.*]] = add nsw i8 [[X]], 8
+; CHECK-NEXT:   

[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread via cfe-commits


@@ -1898,6 +1882,60 @@ static Instruction *foldSelectICmpEq(SelectInst &SI, 
ICmpInst *ICI,
   return nullptr;
 }
 
+/// Fold `X Pred C1 ? X BOp C2 : C1 BOp C2` to `min/max(X, C1) BOp C2`.
+/// This allows for better canonicalization.
+static Value *foldSelectWithConstOpToBinOp(ICmpInst *Cmp, Value *TrueVal,
+   Value *FalseVal,
+   IRBuilderBase &Builder) {
+  BinaryOperator *BOp;
+  Constant *C1, *C2, *C3;
+  Value *X;
+  ICmpInst::Predicate Predicate;
+
+  if (!match(Cmp, m_ICmp(Predicate, m_Value(X), m_Constant(C1
+return nullptr;
+
+  if (!ICmpInst::isRelational(Predicate))
+return nullptr;
+
+  if (match(TrueVal, m_Constant())) {
+std::swap(FalseVal, TrueVal);
+Predicate = ICmpInst::getInversePredicate(Predicate);
+  }
+
+  if (!match(TrueVal, m_BinOp(BOp)) || !match(FalseVal, m_Constant(C3)))
+return nullptr;
+
+  unsigned Opcode = BOp->getOpcode();
+
+  if (Instruction::isIntDivRem(Opcode))

veera-sivarajan wrote:

Yeah, it's a heuristic. I've added a comment.

https://github.com/llvm/llvm-project/pull/116888
___
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 cppcoreguidelines-narrowing-conversions false positives when narrowing integer to signed integer in C++20 (PR #116591)

2024-12-01 Thread Carlos Galvez via cfe-commits

carlosgalvezp wrote:

We probably should have proper guidelines for aliases. IMO, there should only 
be a "base -> coding guideline" kind of alias relationship, not the other way 
around. Coding guidelines should "cherry-pick" (and possibly 
configure/harden/make more strict) base checks. So in that sense yes, it would 
make sense to move the check to bugprone and alias to cppcoreguidelines. But I 
think that's a separate issue.

> but giving the user choice is a plus

Absolutely, I'm not arguing against that, I'm just saying that the _default_ 
choice should be what the guidelines say.

I still don't understand what problem we are trying to achieve, however. My 
impression from the PR (please correct me if I'm wrong) is that we want to 
ignore integer narrowing conversions in C++20, simply because they are 
well-defined. 

I believe a lot of people (myself included) will disagree with that - like I 
wrote above, the problem still remains that data is lost, which is exactly what 
this check is preventing. If one wants to ignore these warnings, one can 
disable the check or disable warnings on integer conversions which the existing 
option. Why is that not sufficient?

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


[clang] [llvm] [InstCombine] Fold `X Pred C2 ? X BOp C1 : C2 BOp C1` to `min/max(X, C2) BOp C1` (PR #116888)

2024-12-01 Thread via cfe-commits

veera-sivarajan wrote:

Rebased and updated the tests.

Please merge it for me. I don't have write access yet.

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


  1   2   >