[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Balazs Benics via cfe-commits


@@ -0,0 +1,162 @@
+// EntryPointStats.h - Tracking statistics per entry point --*- C++ -*-//

steakhal wrote:

The line length seems odd. It's much smaller than 81 characters.
Same observation goes at the end of this comment block.

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


[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Arseniy Zaostrovnykh via cfe-commits

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


[clang] Optimize Cache Insertion with try_emplace for Reduced Lookups (PR #131402)

2025-03-15 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff fbf0276b6a7a7a4508c373cf87fc349569652659 
28f6d8b6677e32f45f5fa55c7c73df5a841d7127 --extensions h -- 
clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
``





View the diff from clang-format here.


``diff
diff --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index a24ba86dae..08e6a2e678 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -248,15 +248,15 @@ public:
  const CachedFileSystemEntry &Entry) {
 assert(llvm::sys::path::is_absolute_gnu(Filename));
 
-  auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
-  Filename, &Entry, nullptr).first->getValue();
-
-  if (!CachedEntry) {
-assert((!CachedEntry && CachedRealPath) && "entry already present");
-CachedEntry = &Entry;
-  }
-
-  return *CachedEntry;
+auto &[CachedEntry, CachedRealPath] =
+Cache.try_emplace(Filename, &Entry, nullptr).first->getValue();
+
+if (!CachedEntry) {
+  assert((!CachedEntry && CachedRealPath) && "entry already present");
+  CachedEntry = &Entry;
+}
+
+return *CachedEntry;
   }
 
   /// Returns real path associated with the filename or nullptr if none is
@@ -273,14 +273,14 @@ public:
   insertRealPathForFilename(StringRef Filename,
 const CachedRealPath &RealPath) {
 assert(llvm::sys::path::is_absolute_gnu(Filename));
-auto &[CachedEntry, CachedRealPath] = Cache.try_emplace(
-  Filename, nullptr, &RealPath).first->getValue();
-
+auto &[CachedEntry, CachedRealPath] =
+Cache.try_emplace(Filename, nullptr, &RealPath).first->getValue();
+
 if (!CachedRealPath) {
   assert((!CachedRealPath && CachedEntry) && "real path already present");
   CachedRealPath = &RealPath;
 }
-
+
 return *CachedRealPath;
   }
 };

``




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


[clang] [NFC][Static Analyzer] Rename and discuss about `NotNullConstraint` & `NotNullBufferConstraint` (PR #131374)

2025-03-15 Thread via cfe-commits

github-actions[bot] wrote:




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



You can test this locally with the following command:


``bash
git-clang-format --diff dafb566710cd03b7fbb4b187a91f32be9452fd8c 
fdc265eeca36dc877f56389d8dba39b517e6 --extensions cpp -- 
clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index 3542b7c8aa..7956fdc947 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -418,8 +418,8 @@ class StdLibraryFunctionsChecker
 
   public:
 BufferNullnessConstraint(ArgNo ArgN, ArgNo SizeArg1N,
-std::optional SizeArg2N,
-bool CannotBeNull = true)
+ std::optional SizeArg2N,
+ bool CannotBeNull = true)
 : ValueConstraint(ArgN), SizeArg1N(SizeArg1N), SizeArg2N(SizeArg2N),
   CannotBeNull(CannotBeNull) {}
 
@@ -1224,9 +1224,10 @@ void 
StdLibraryFunctionsChecker::BufferNullnessConstraint::describe(
 Out << "is not NULL";
 }
 
-bool 
StdLibraryFunctionsChecker::BufferNullnessConstraint::describeArgumentValue(
-const CallEvent &Call, ProgramStateRef State, const Summary &Summary,
-llvm::raw_ostream &Out) const {
+bool StdLibraryFunctionsChecker::BufferNullnessConstraint::
+describeArgumentValue(const CallEvent &Call, ProgramStateRef State,
+  const Summary &Summary,
+  llvm::raw_ostream &Out) const {
   assert(!CannotBeNull && "This function is used when the value is NULL");
   Out << "is NULL";
   return true;
@@ -1800,7 +1801,7 @@ void StdLibraryFunctionsChecker::initFunctionSummaries(
   auto NotNullBuffer = [&](ArgNo ArgN, ArgNo SizeArg1N,
std::optional SizeArg2N = std::nullopt) {
 return std::make_shared(ArgN, SizeArg1N,
- SizeArg2N);
+  SizeArg2N);
   };
 
   std::optional FileTy = lookupTy("FILE");

``




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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Andy Kaylor (andykaylor)


Changes

This adds support for the cir.unary operation.

---

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


11 Files Affected:

- (modified) clang/include/clang/CIR/Dialect/IR/CIROps.td (+49) 
- (modified) clang/include/clang/CIR/MissingFeatures.h (+9) 
- (modified) clang/lib/CIR/CodeGen/CIRGenExpr.cpp (+48) 
- (modified) clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp (+223) 
- (modified) clang/lib/CIR/CodeGen/CIRGenFunction.cpp (+2) 
- (modified) clang/lib/CIR/CodeGen/CIRGenFunction.h (+4) 
- (modified) clang/lib/CIR/CodeGen/CIRGenValue.h (+1) 
- (modified) clang/lib/CIR/Dialect/IR/CIRDialect.cpp (+41) 
- (modified) clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp (+124-1) 
- (modified) clang/lib/CIR/Lowering/DirectToLLVM/LowerToLLVM.h (+10) 
- (added) clang/test/CIR/CodeGen/unary.cpp (+392) 


``diff
diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 77c43e5ace64a..52c78ffe42647 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -468,6 +468,55 @@ def BrOp : CIR_Op<"br",
   }];
 }
 
+//===--===//
+// UnaryOp
+//===--===//
+
+def UnaryOpKind_Inc   : I32EnumAttrCase<"Inc",   1, "inc">;
+def UnaryOpKind_Dec   : I32EnumAttrCase<"Dec",   2, "dec">;
+def UnaryOpKind_Plus  : I32EnumAttrCase<"Plus",  3, "plus">;
+def UnaryOpKind_Minus : I32EnumAttrCase<"Minus", 4, "minus">;
+def UnaryOpKind_Not   : I32EnumAttrCase<"Not",   5, "not">;
+
+def UnaryOpKind : I32EnumAttr<
+"UnaryOpKind",
+"unary operation kind",
+[UnaryOpKind_Inc,
+ UnaryOpKind_Dec,
+ UnaryOpKind_Plus,
+ UnaryOpKind_Minus,
+ UnaryOpKind_Not,
+ ]> {
+  let cppNamespace = "::cir";
+}
+
+// FIXME: Pure won't work when we add overloading.
+def UnaryOp : CIR_Op<"unary", [Pure, SameOperandsAndResultType]> {
+  let summary = "Unary operations";
+  let description = [{
+`cir.unary` performs the unary operation according to
+the specified opcode kind: [inc, dec, plus, minus, not].
+
+It requires one input operand and has one result, both types
+should be the same.
+
+```mlir
+%7 = cir.unary(inc, %1) : i32 -> i32
+%8 = cir.unary(dec, %2) : i32 -> i32
+```
+  }];
+
+  let results = (outs CIR_AnyType:$result);
+  let arguments = (ins Arg:$kind, 
Arg:$input);
+
+  let assemblyFormat = [{
+  `(` $kind `,` $input `)` `:` type($input) `,` type($result) attr-dict
+  }];
+
+  let hasVerifier = 1;
+  let hasFolder = 1;
+}
+
 
//===--===//
 // GlobalOp
 
//===--===//
diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 6c3d74cf96c64..fcbb2ae3db6aa 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -72,6 +72,10 @@ struct MissingFeatures {
   static bool opFuncLinkage() { return false; }
   static bool opFuncVisibility() { return false; }
 
+  // Unary operator handling
+  static bool opUnarySignedOverflow() { return false; }
+  static bool opUnaryPromotionType() { return false; }
+
   // Misc
   static bool scalarConversionOpts() { return false; }
   static bool tryEmitAsConstant() { return false; }
@@ -86,6 +90,11 @@ struct MissingFeatures {
   static bool aggValueSlot() { return false; }
 
   static bool unsizedTypes() { return false; }
+  static bool sanitizers() { return false; }
+  static bool CGFPOptionsRAII() { return false; }
+
+  // Missing types
+  static bool vectorType() { return false; }
 };
 
 } // namespace cir
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 5b81fe172e645..24c0c8a18efd8 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -165,6 +165,54 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr 
*e) {
   return LValue();
 }
 
+LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
+  UnaryOperatorKind op = e->getOpcode();
+
+  // __extension__ doesn't affect lvalue-ness.
+  if (op == UO_Extension)
+return emitLValue(e->getSubExpr());
+
+  switch (op) {
+  case UO_Deref: {
+cgm.errorNYI(e->getSourceRange(), "UnaryOp dereference");
+return LValue();
+  }
+  case UO_Real:
+  case UO_Imag: {
+cgm.errorNYI(e->getSourceRange(), "UnaryOp real/imag");
+return LValue();
+  }
+  case UO_PreInc:
+  case UO_PreDec: {
+bool isInc = e->isIncrementOp();
+LValue lv = emitLValue(e->getSubExpr());
+
+assert(e->isPrefix() && "Prefix operator in unexpected state!");
+
+if (e->getType()->isAnyComplexT

[clang] [clang][modules] Fix filesystem races in `ModuleManager` (PR #131354)

2025-03-15 Thread Jan Svoboda via cfe-commits

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -92,6 +92,222 @@ class ScalarExprEmitter : public 
StmtVisitor {
 
   mlir::Value VisitCastExpr(CastExpr *E);
 
+  // Unary Operators.
+  mlir::Value VisitUnaryPostDec(const UnaryOperator *e) {
+LValue lv = cgf.emitLValue(e->getSubExpr());
+return emitScalarPrePostIncDec(e, lv, false, false);
+  }
+  mlir::Value VisitUnaryPostInc(const UnaryOperator *e) {
+LValue lv = cgf.emitLValue(e->getSubExpr());
+return emitScalarPrePostIncDec(e, lv, true, false);
+  }
+  mlir::Value VisitUnaryPreDec(const UnaryOperator *e) {
+LValue lv = cgf.emitLValue(e->getSubExpr());
+return emitScalarPrePostIncDec(e, lv, false, true);
+  }
+  mlir::Value VisitUnaryPreInc(const UnaryOperator *e) {
+LValue lv = cgf.emitLValue(e->getSubExpr());
+return emitScalarPrePostIncDec(e, lv, true, true);
+  }
+  mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv,
+  bool isInc, bool isPre) {
+if (cgf.getLangOpts().OpenMP)
+  cgf.cgm.errorNYI(e->getSourceRange(), "inc/dec OpenMP");
+
+QualType type = e->getSubExpr()->getType();
+
+mlir::Value value;
+mlir::Value input;
+
+if (type->getAs()) {
+  cgf.cgm.errorNYI(e->getSourceRange(), "Atomic inc/dec");
+  // TODO(cir): This is not correct, but it will produce reasonable code
+  // until atomic operations are implemented.
+  value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
+  input = value;
+} else {
+  value = cgf.emitLoadOfLValue(lv, e->getExprLoc()).getScalarVal();
+  input = value;
+}
+
+// NOTE: When possible, more frequent cases are handled first.
+
+// Special case of integer increment that we have to check first: bool++.
+// Due to promotion rules, we get:
+//   bool++ -> bool = bool + 1
+//  -> bool = (int)bool + 1
+//  -> bool = ((int)bool + 1 != 0)
+// An interesting aspect of this is that increment is always true.
+// Decrement does not have this property.
+if (isInc && type->isBooleanType()) {
+  value = builder.create(cgf.getLoc(e->getExprLoc()),
+  cgf.convertType(type),
+  builder.getCIRBoolAttr(true));
+} else if (type->isIntegerType()) {
+  QualType promotedType;
+  bool canPerformLossyDemotionCheck = false;
+  if (cgf.getContext().isPromotableIntegerType(type)) {
+promotedType = cgf.getContext().getPromotedIntegerType(type);
+assert(promotedType != type && "Shouldn't promote to the same type.");
+canPerformLossyDemotionCheck = true;
+canPerformLossyDemotionCheck &=
+cgf.getContext().getCanonicalType(type) !=
+cgf.getContext().getCanonicalType(promotedType);
+canPerformLossyDemotionCheck &=
+type->isIntegerType() && promotedType->isIntegerType();
+
+// TODO(cir): Currently, we store bitwidths in CIR types only for
+// integers. This might also be required for other types.
+auto srcCirTy = mlir::dyn_cast(cgf.convertType(type));
+auto promotedCirTy =
+mlir::dyn_cast(cgf.convertType(type));
+assert(srcCirTy && promotedCirTy && "Expected integer type");

erichkeane wrote:

If we're asserting here, those should just be `cast` above, and count on the 
`cast` assert. 

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


[clang] Move const qualification of array to its elements (PR #131366)

2025-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Serge Pavlov (spavloff)


Changes

Const-qualification of an array caused by constexpr specifier can produce 
QualType, where the const qualifier is set both as fast qualifier and as a 
qualifier of the array element type. It can result in a compiler crash, because 
such QualType does not compare equal to the same type but without extra 
qualification.

As a fix, the const qualifier is moved to the array element type when setting 
the implicit const.

It fixes https://github.com/llvm/llvm-project/issues/97005 (Clang crashed in 
ASTContext::getCommonSugaredType).

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


4 Files Affected:

- (modified) clang/lib/Sema/SemaType.cpp (+6-1) 
- (modified) clang/test/AST/ByteCode/constexpr.c (+1-1) 
- (modified) clang/test/Sema/constexpr.c (+1-1) 
- (added) clang/test/SemaCXX/constexpr-implicit-const-97005.cpp (+8) 


``diff
diff --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index 11943c0b53591..dee678aa69e83 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -5613,8 +5613,13 @@ static TypeSourceInfo 
*GetFullTypeForDeclarator(TypeProcessingState &state,
   //  A constexpr specifier used in an object declaration declares the object
   //  as const.
   if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr 
&&
-  T->isObjectType())
+  T->isObjectType()) {
 T.addConst();
+// C++ 9.3.3.4p3: Any type of the form "cv-qualifier-seq array of N U" is
+// adjusted to "array of N cv-qualifier-seq U".
+if (const ArrayType *AType = Context.getAsArrayType(T))
+  T = QualType(AType, 0);
+  }
 
   // C++2a [dcl.fct]p4:
   //   A parameter with volatile-qualified type is deprecated
diff --git a/clang/test/AST/ByteCode/constexpr.c 
b/clang/test/AST/ByteCode/constexpr.c
index af96bf3a06f37..a4a8bde266e76 100644
--- a/clang/test/AST/ByteCode/constexpr.c
+++ b/clang/test/AST/ByteCode/constexpr.c
@@ -82,7 +82,7 @@ constexpr TheA V19[3] = {};
 constexpr TheV V20[3] = {};
 // both-error@-1 {{constexpr variable cannot have type 'const TheV[3]' (aka 
'const volatile short[3]')}}
 constexpr TheR V21[3] = {};
-// both-error@-1 {{constexpr variable cannot have type 'const TheR[3]' (aka 
'float *restrict const[3]')}}
+// both-error@-1 {{constexpr variable cannot have type 'const TheR[3]' (aka 
'float *const restrict[3]')}}
 
 struct HasA {
   TheA f;
diff --git a/clang/test/Sema/constexpr.c b/clang/test/Sema/constexpr.c
index 3dcb0b3a7d95f..005e980563cc7 100644
--- a/clang/test/Sema/constexpr.c
+++ b/clang/test/Sema/constexpr.c
@@ -81,7 +81,7 @@ constexpr TheA V19[3] = {};
 constexpr TheV V20[3] = {};
 // expected-error@-1 {{constexpr variable cannot have type 'const TheV[3]' 
(aka 'const volatile short[3]')}}
 constexpr TheR V21[3] = {};
-// expected-error@-1 {{constexpr variable cannot have type 'const TheR[3]' 
(aka 'float *restrict const[3]')}}
+// expected-error@-1 {{constexpr variable cannot have type 'const TheR[3]' 
(aka 'float *const restrict[3]')}}
 
 struct HasA {
   TheA f;
diff --git a/clang/test/SemaCXX/constexpr-implicit-const-97005.cpp 
b/clang/test/SemaCXX/constexpr-implicit-const-97005.cpp
new file mode 100644
index 0..78e9b11f4d61c
--- /dev/null
+++ b/clang/test/SemaCXX/constexpr-implicit-const-97005.cpp
@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 -triple x86_64-linux-gnu -ast-dump %s | FileCheck %s
+
+bool aaa;
+constexpr const unsigned char ccc[] = { 5 };
+constexpr const unsigned char ddd[1] = { 0 };
+auto bbb = (aaa ? ddd : ccc);
+
+// CHECK: DeclRefExpr {{.*}} 'const unsigned char[1]' {{.*}} 'ddd' 'const 
unsigned char[1]'

``




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


[clang] Remove redundant assertion & fix ClearStatName error (PR #130667)

2025-03-15 Thread Ayush Pareek via cfe-commits

https://github.com/ayushpareek2003 created 
https://github.com/llvm/llvm-project/pull/130667


Issue: Calling clearStatName() on an error object
The function clearStatName() is called inside constructors before checking 
whether MaybeStat contains an error. If MaybeStat is an error, calling 
copyWithNewName() can cause undefined behavior


Issue: Multiple assert condition in function getDirectiveTokens()
Since isError() and isDirectory() imply that Contents is nullptr, the last 
assertion is unnecessary

>From 94b213ad0edf8295451cdb315093cd73923714bb Mon Sep 17 00:00:00 2001
From: Ayush Pareek 
Date: Tue, 11 Mar 2025 02:23:49 +0530
Subject: [PATCH] Update DependencyScanningFilesystem.h

Issue: Calling clearStatName() on an error object
The function clearStatName() is called inside constructors before checking 
whether MaybeStat contains an error. If MaybeStat is an error, calling 
copyWithNewName() can cause undefined behavior

Since isError() and isDirectory() imply that Contents is nullptr, the last 
assertion is unnecessary
---
 .../DependencyScanning/DependencyScanningFilesystem.h| 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)

diff --git 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
index d12814e7c9253..b69a99cf12bcb 100644
--- 
a/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
+++ 
b/clang/include/clang/Tooling/DependencyScanning/DependencyScanningFilesystem.h
@@ -93,7 +93,7 @@ class CachedFileSystemEntry {
   getDirectiveTokens() const {
 assert(!isError() && "error");
 assert(!isDirectory() && "not a file");
-assert(Contents && "contents not initialized");
+// Since isError() and isDirectory() imply that Contents is nullptr, the 
last assertion is unnecessary
 if (auto *Directives = Contents->DepDirectives.load()) {
   if (Directives->has_value())
 return ArrayRef(**Directives);
@@ -126,7 +126,8 @@ class CachedFileSystemEntry {
 
 private:
   void clearStatName() {
-if (MaybeStat)
+  
+if (MaybeStat && MaybeStat->getName().empty())   //If MaybeStat is an 
error, calling copyWithNewName() can cause undefined behavior
   MaybeStat = llvm::vfs::Status::copyWithNewName(*MaybeStat, "");
   }
 

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


[clang] [clang][dataflow] Add test for crash repro and clean up const accessor handling (PR #129930)

2025-03-15 Thread Jan Voung via cfe-commits

https://github.com/jvoung commented:

Thanks!

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


[clang] [NFC][analyzer] Framework for multipart checkers (PR #130985)

2025-03-15 Thread Donát Nagy via cfe-commits

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


[clang-tools-extra] [llvm] [llvm] add support for mustache templating language (PR #105893)

2025-03-15 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `polly-x86_64-linux-plugin` 
running on `polly-x86_64-gce1` while building `llvm` at step 5 "build".

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


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

```
Step 5 (build) failure: 'ninja' (failure)
...
[594/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_morph.c.o
[595/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_obj.c.o
[596/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_map_simplify.c.o
[597/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_options.c.o
[598/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_point.c.o
[599/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_mat.c.o
[600/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_output.c.o
[601/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_printer.c.o
[602/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_range.c.o
[603/4171] Building CXX object 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o
FAILED: lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o 
ccache /usr/bin/c++ -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS 
-D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS 
-D__STDC_LIMIT_MACROS 
-I/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.obj/lib/Support 
-I/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support
 -I/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.obj/include 
-I/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/include 
-fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time 
-fno-lifetime-dse -Wall -Wextra -Wno-unused-parameter -Wwrite-strings 
-Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long 
-Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess 
-Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment 
-Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -O3 -DNDEBUG -UNDEBUG -std=c++17  
-fno-exceptions -funwind-tables -fno-rtti -MD -MT 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o -MF 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o.d -o 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o -c 
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:109:12:
 error: declaration of ‘{anonymous}::Accessor llvm::mustache::Token::Accessor’ 
changes meaning of ‘Accessor’ [-fpermissive]
  109 |   Accessor Accessor;
  |^~~~
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:19:7:
 note: ‘Accessor’ declared here as ‘using Accessor = class 
llvm::SmallVector >’
   19 | using Accessor = SmallVector;
  |   ^~~~
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:186:18:
 error: declaration of ‘const Accessor llvm::mustache::ASTNode::Accessor’ 
changes meaning of ‘Accessor’ [-fpermissive]
  186 |   const Accessor Accessor;
  |  ^~~~
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:19:7:
 note: ‘Accessor’ declared here as ‘using Accessor = class 
llvm::SmallVector >’
   19 | using Accessor = SmallVector;
  |   ^~~~
In file included from 
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:8:
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/include/llvm/Support/Mustache.h:
 In constructor 
‘llvm::mustache::Template::Template(llvm::mustache::Template&&)’:
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/include/llvm/Support/Mustache.h:123:12:
 warning: ‘llvm::mustache::Template::Tree’ will be initialized after [-Wreorder]
  123 |   ASTNode *Tree;
  |^~~~
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/include/llvm/Support/Mustache.h:120:26:
 warning:   ‘llvm::BumpPtrAllocator llvm::mustache::Template::AstAllocator’ 
[-Wreorder]
  120 |   llvm::BumpPtrAllocator AstAllocator;
  |  ^~~~
/home/worker/buildbot-workers/polly-x86_64-gce1/rundir/llvm.src/llvm/lib/Support/Mustache.cpp:769:1:
 warning:   when initialized here [-Wreorder]
  769 | Template::Template(Template &&Other) noexcept
  | ^~~~
[604/4171] Building C object 
tools/polly/lib/External/CMakeFiles/PollyISL.dir/isl/isl_reordering.c.o
[605/4171] Buildin

[clang] [Clang codegen][PPC] Produce AIX-specific "target features" only for AIX (PR #130864)

2025-03-15 Thread zhijian lin via cfe-commits


@@ -609,13 +609,15 @@ bool PPCTargetInfo::initFeatureMap(
   // Privileged instructions are off by default.
   Features["privileged"] = false;
 
-  // The code generated by the -maix-small-local-[exec|dynamic]-tls option is
-  // turned off by default.
-  Features["aix-small-local-exec-tls"] = false;
-  Features["aix-small-local-dynamic-tls"] = false;
+  if (getTriple().isOSAIX()) {

diggerlin wrote:

if I understand correct, we do not need to set 
Features["aix-small-local-exec-tls"] = false; for AIX too,  since we do not use 
the 
`HasAIXSmallLocalExecTLS`,`HasAIXShLibTLSModelOpt`,`HasAIXSmallLocalDynamicTLS` 
in the frontend 


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


[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Balazs Benics via cfe-commits

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


[clang] [Clang] Implement P0963R3 "Structured binding declaration as a condition" (PR #130228)

2025-03-15 Thread Younan Zhang via cfe-commits


@@ -5218,16 +5218,28 @@ static bool EvaluateVarDecl(EvalInfo &Info, const 
VarDecl *VD) {
   return true;
 }
 
+static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
+  const DecompositionDecl *DD);
+
 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
   bool OK = true;
 
   if (const VarDecl *VD = dyn_cast(D))
 OK &= EvaluateVarDecl(Info, VD);
 
-  if (const DecompositionDecl *DD = dyn_cast(D))
-for (auto *BD : DD->flat_bindings())
-  if (auto *VD = BD->getHoldingVar())
-OK &= EvaluateDecl(Info, VD);
+  if (const DecompositionDecl *DD = dyn_cast(D);
+  DD && !DD->isDecisionVariable())
+OK &= EvaluateDecompositionDeclInit(Info, DD);
+
+  return OK;
+}
+
+static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
+  const DecompositionDecl *DD) {
+  bool OK = true;
+  for (auto *BD : DD->flat_bindings())
+if (auto *VD = BD->getHoldingVar())
+  OK &= EvaluateDecl(Info, VD);

zyn0217 wrote:

We can't bail out early here: `EvaluateVarDecl()` might fail because 
`EvaluateInPlace()` might fail, and in that case, we still need to continue 
evaluating the initializers; otherwise, we'll crash. Here is an example

```cpp

namespace std {

template  struct tuple_size;

template  struct tuple_element;

} // namespace std


namespace constant {
  struct Q {};
  template constexpr int get(Q &&) { return N * N; }
}
template<> struct std::tuple_size { static const int value = 3; };
template struct std::tuple_element { typedef int type; };

namespace constant {
Q q;

constexpr bool f() {
  auto [a, b, c] = q;
  return a == 0 && b == 1 && c == 4;
}
static_assert(f());
}
```



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


[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Arseniy Zaostrovnykh via cfe-commits

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

>From 6b6d80d42d40d5917622cbc2bc0f2a454c34eca3 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Thu, 13 Mar 2025 18:42:39 +0100
Subject: [PATCH 01/10] [analyzer] Introduce per-entry-point statistics
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

So far CSA was relying on the LLVM Statistic package that allowed us to
gather some data about analysis of an entire translation unit. However,
the translation unit consists of a collection of loosely related entry
points. Aggregating data across multiple such entry points is often
counter productive.

This change introduces a new lightweight always-on facility to collect
Boolean or numerical statistics for each entry point and dump them in a
CSV format. Such format makes it easy to aggregate data across multiple
translation units and analyze it with common data-processing tools.

We break down the existing statistics that were collected on the per-TU
basis into values per entry point.

Additionally, we enable the statistics unconditionally (STATISTIC ->
ALWAYS_ENABLED_STATISTIC) to facilitate their use (you can gather the
data with a simple run-time flag rather than having to recompile the
analyzer). These statistics are very light and add virtually no
overhead.

@steakhal (Balázs Benics) started this design and I picked over the baton.

---
CPP-6160
---
 clang/docs/analyzer/developer-docs.rst|   1 +
 .../analyzer/developer-docs/Statistics.rst|  21 ++
 .../StaticAnalyzer/Core/AnalyzerOptions.def   |   6 +
 .../Core/PathSensitive/EntryPointStats.h  | 162 ++
 .../Checkers/AnalyzerStatsChecker.cpp |   9 +-
 clang/lib/StaticAnalyzer/Core/BugReporter.cpp |  28 +--
 clang/lib/StaticAnalyzer/Core/CMakeLists.txt  |   1 +
 clang/lib/StaticAnalyzer/Core/CoreEngine.cpp  |  16 +-
 .../StaticAnalyzer/Core/EntryPointStats.cpp   | 201 ++
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |  24 ++-
 .../Core/ExprEngineCallAndReturn.cpp  |  14 +-
 clang/lib/StaticAnalyzer/Core/WorkList.cpp|  10 +-
 .../Core/Z3CrosscheckVisitor.cpp  |  31 +--
 .../Frontend/AnalysisConsumer.cpp |  62 --
 clang/test/Analysis/analyzer-config.c |   1 +
 clang/test/Analysis/csv2json.py   |  98 +
 clang/test/lit.cfg.py |  10 +
 17 files changed, 617 insertions(+), 78 deletions(-)
 create mode 100644 clang/docs/analyzer/developer-docs/Statistics.rst
 create mode 100644 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h
 create mode 100644 clang/lib/StaticAnalyzer/Core/EntryPointStats.cpp
 create mode 100644 clang/test/Analysis/csv2json.py

diff --git a/clang/docs/analyzer/developer-docs.rst 
b/clang/docs/analyzer/developer-docs.rst
index 60c0e71ad847c..a925cf7ca02e1 100644
--- a/clang/docs/analyzer/developer-docs.rst
+++ b/clang/docs/analyzer/developer-docs.rst
@@ -12,3 +12,4 @@ Contents:
developer-docs/nullability
developer-docs/RegionStore
developer-docs/PerformanceInvestigation
+   developer-docs/Statistics
diff --git a/clang/docs/analyzer/developer-docs/Statistics.rst 
b/clang/docs/analyzer/developer-docs/Statistics.rst
new file mode 100644
index 0..d352bb6f01ebc
--- /dev/null
+++ b/clang/docs/analyzer/developer-docs/Statistics.rst
@@ -0,0 +1,21 @@
+==
+Metrics and Statistics
+==
+
+TODO: write this once the design is settled (@reviewer, don't look here yet)
+
+CSA enjoys two facilities to collect statistics per translation unit and per 
entry point.
+
+Mention the following tools:
+- STATISTIC macro
+- ALLWAYS_ENABLED_STATISTIC macro
+
+- STAT_COUNTER macro
+- STAT_MAX macro
+
+- BoolEPStat
+- UnsignedEPStat
+- CounterEPStat
+- UnsignedMaxEPStat
+
+- dump-se-metrics-to-csv="%t.csv"
diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 2aa00db411844..b88bce5e262a7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -353,6 +353,12 @@ ANALYZER_OPTION(bool, DisplayCTUProgress, 
"display-ctu-progress",
 "the analyzer's progress related to ctu.",
 false)
 
+ANALYZER_OPTION(
+StringRef, DumpSEStatsToCSV, "dump-se-stats-to-csv",
+"If provided, the analyzer will dump statistics per entry point "
+"into the specified CSV file.",
+"")
+
 ANALYZER_OPTION(bool, ShouldTrackConditions, "track-conditions",
 "Whether to track conditions that are a control dependency of "
 "an already tracked variable.",
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h
new file mode 100644
index 0..16c

[clang] [NFC][Static Analyzer] Rename and discuss about `NotNullConstraint` & `NotNullBufferConstraint` (PR #131374)

2025-03-15 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

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

Author: Ziqing Luo (ziqingluo-90)


Changes

NotNullConstraint is used to check both null and non-null of a pointer.  So the 
name, which was created originally for just checking non-nullness, becomes less 
suitable.
The same reason applies to `NotNullBufferConstraint`.

Other than the names, I have some concerns noted in comments below. I'd like to 
discuss them with Static Analyzer folks!

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
(+19-19) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
index fef19b4547555..3542b7c8aaf30 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StdLibraryFunctionsChecker.cpp
@@ -367,13 +367,13 @@ class StdLibraryFunctionsChecker
   };
 
   /// Check null or non-null-ness of an argument that is of pointer type.
-  class NotNullConstraint : public ValueConstraint {
+  class NullnessConstraint : public ValueConstraint {
 using ValueConstraint::ValueConstraint;
 // This variable has a role when we negate the constraint.
 bool CannotBeNull = true;
 
   public:
-NotNullConstraint(ArgNo ArgN, bool CannotBeNull = true)
+NullnessConstraint(ArgNo ArgN, bool CannotBeNull = true)
 : ValueConstraint(ArgN), CannotBeNull(CannotBeNull) {}
 
 ProgramStateRef apply(ProgramStateRef State, const CallEvent &Call,
@@ -389,9 +389,9 @@ class StdLibraryFunctionsChecker
llvm::raw_ostream &Out) const override;
 
 ValueConstraintPtr negate() const override {
-  NotNullConstraint Tmp(*this);
+  NullnessConstraint Tmp(*this);
   Tmp.CannotBeNull = !this->CannotBeNull;
-  return std::make_shared(Tmp);
+  return std::make_shared(Tmp);
 }
 
   protected:
@@ -407,9 +407,9 @@ class StdLibraryFunctionsChecker
   /// The argument is meant to be a buffer that has a size constraint, and it
   /// is allowed to have a NULL value if the size is 0. The size can depend on
   /// 1 or 2 additional arguments, if one of these is 0 the buffer is allowed 
to
-  /// be NULL. This is useful for functions like `fread` which have this 
special
-  /// property.
-  class NotNullBufferConstraint : public ValueConstraint {
+  /// be NULL. Otherwise, the buffer pointer must be non-null. This is useful
+  /// for functions like `fread` which have this special property.
+  class BufferNullnessConstraint : public ValueConstraint {
 using ValueConstraint::ValueConstraint;
 ArgNo SizeArg1N;
 std::optional SizeArg2N;
@@ -417,7 +417,7 @@ class StdLibraryFunctionsChecker
 bool CannotBeNull = true;
 
   public:
-NotNullBufferConstraint(ArgNo ArgN, ArgNo SizeArg1N,
+BufferNullnessConstraint(ArgNo ArgN, ArgNo SizeArg1N,
 std::optional SizeArg2N,
 bool CannotBeNull = true)
 : ValueConstraint(ArgN), SizeArg1N(SizeArg1N), SizeArg2N(SizeArg2N),
@@ -436,9 +436,9 @@ class StdLibraryFunctionsChecker
llvm::raw_ostream &Out) const override;
 
 ValueConstraintPtr negate() const override {
-  NotNullBufferConstraint Tmp(*this);
+  BufferNullnessConstraint Tmp(*this);
   Tmp.CannotBeNull = !this->CannotBeNull;
-  return std::make_shared(Tmp);
+  return std::make_shared(Tmp);
 }
 
   protected:
@@ -1151,7 +1151,7 @@ ProgramStateRef 
StdLibraryFunctionsChecker::ComparisonConstraint::apply(
   return State;
 }
 
-ProgramStateRef StdLibraryFunctionsChecker::NotNullConstraint::apply(
+ProgramStateRef StdLibraryFunctionsChecker::NullnessConstraint::apply(
 ProgramStateRef State, const CallEvent &Call, const Summary &Summary,
 CheckerContext &C) const {
   SVal V = getArgSVal(Call, getArgNo());
@@ -1165,7 +1165,7 @@ ProgramStateRef 
StdLibraryFunctionsChecker::NotNullConstraint::apply(
   return State->assume(L, CannotBeNull);
 }
 
-void StdLibraryFunctionsChecker::NotNullConstraint::describe(
+void StdLibraryFunctionsChecker::NullnessConstraint::describe(
 DescriptionKind DK, const CallEvent &Call, ProgramStateRef State,
 const Summary &Summary, llvm::raw_ostream &Out) const {
   assert(CannotBeNull &&
@@ -1176,7 +1176,7 @@ void 
StdLibraryFunctionsChecker::NotNullConstraint::describe(
 Out << "is not NULL";
 }
 
-bool StdLibraryFunctionsChecker::NotNullConstraint::describeArgumentValue(
+bool StdLibraryFunctionsChecker::NullnessConstraint::describeArgumentValue(
 const CallEvent &Call, ProgramStateRef State, const Summary &Summary,
 llvm::raw_ostream &Out) const {
   assert(!CannotBeNull && "This function is used when the value is NULL");
@@ -1184,7 +1184,7 @@ bool 
StdLibraryFunctionsChecker::NotNullCo

[clang] [llvm] [ARM][Clang] Make `+nosimd` functional for AArch32 Targets (PR #130623)

2025-03-15 Thread Jack Styles via cfe-commits


@@ -85,6 +85,9 @@ Changes to the AMDGPU Backend
 
 Changes to the ARM Backend
 --
+* The `+nosimd` attribute is now fully supported. Previously, this had no 
effect when being used with
+AArch32 targets, however this will now disable NEON instructions being 
generated. The `simd` option is 
+also now printed when the `--print-supported-extensions` option is used.

Stylie777 wrote:

Thanks, I must have put it here as the change has to be made in LLVM but you 
are correct, `+nosimd` is a clang option rather than LLVM. I have updated this.

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


[clang] 9ecb0f5 - [Clang][diagnostics] Improve the diagnostics for chained comparisons (#129285)

2025-03-15 Thread via cfe-commits

Author: Amr Hesham
Date: 2025-03-06T18:55:18+01:00
New Revision: 9ecb0f58ebb4faa2410dd8ee1fe4d2187aa3fbfc

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

LOG: [Clang][diagnostics] Improve the diagnostics for chained comparisons 
(#129285)

Improve the diagnostics for chained comparisons to report actual
expressions and operators

Fixes #129069

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticSemaKinds.td
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/bool-compare.c
clang/test/Sema/parentheses.cpp
clang/test/SemaCXX/bool-compare.cpp
clang/test/SemaCXX/cxx2a-adl-only-template-id.cpp
clang/test/SemaTemplate/typo-dependent-name.cpp
clang/test/SemaTemplate/typo-template-name.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 86bf836b4a999..2faca8da5d77e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -229,6 +229,8 @@ Improvements to Clang's diagnostics
   :doc:`ThreadSafetyAnalysis` still does not perform alias analysis. The
   feature will be default-enabled with ``-Wthread-safety`` in a future release.
 
+- Improve the diagnostics for chained comparisons to report actual expressions 
and operators (#GH129069).
+
 - Improve the diagnostics for shadows template parameter to report correct 
location (#GH129060).
 
 Improvements to Clang's time-trace

diff  --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index d712de654a1c4..723cc1b518f40 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -7160,7 +7160,7 @@ def note_precedence_conditional_first : Note<
   "place parentheses around the '?:' expression to evaluate it first">;
 
 def warn_consecutive_comparison : Warning<
-  "comparisons like 'X<=Y<=Z' don't have their mathematical meaning">,
+  "chained comparison 'X %0 Y %1 Z' does not behave the same as a mathematical 
expression">,
   InGroup, DefaultError;
 
 def warn_enum_constant_in_bool_context : Warning<

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index c2f297886a38b..7904ba966b38d 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -14924,7 +14924,8 @@ ExprResult Sema::CreateBuiltinBinOp(SourceLocation 
OpLoc,
 
 if (const auto *BI = dyn_cast(LHSExpr);
 BI && BI->isComparisonOp())
-  Diag(OpLoc, diag::warn_consecutive_comparison);
+  Diag(OpLoc, diag::warn_consecutive_comparison)
+  << BI->getOpcodeStr() << BinaryOperator::getOpcodeStr(Opc);
 
 break;
   case BO_EQ:

diff  --git a/clang/test/Sema/bool-compare.c b/clang/test/Sema/bool-compare.c
index 861f47864ddd9..11ed156328b2e 100644
--- a/clang/test/Sema/bool-compare.c
+++ b/clang/test/Sema/bool-compare.c
@@ -85,7 +85,7 @@ void f(int x, int y, int z) {
   if ((ayy Y < Z' does 
not behave the same as a mathematical expression}}
   if ((a z)  {} // no warning
   if((a(zy)  {} // expected-error {{comparisons like 'X<=Y<=Z' don't have 
their mathematical meaning}}
+  if (zy)  {} // expected-error {{chained comparison 'X < Y > Z' does 
not behave the same as a mathematical expression}}
   if (z > (a(a z);  // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
-  (void)(x < y <= z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
-  (void)(x <= y > z); // expected-warning {{comparisons like 'X<=Y<=Z' don't 
have their mathematical meaning}}
+  (void)(x < y < z);  // expected-warning {{chained comparison 'X < Y < Z' 
does not behave the same as a mathematical expression}}
+  (void)(x < y > z);  // expected-warning {{chained comparison 'X < Y > Z' 
does not behave the same as a mathematical expression}}
+  (void)(x < y <= z); // expected-warning {{chained comparison 'X < Y <= Z' 
does not behave the same as a mathematical expression}}
+  (void)(x <= y > z); // expected-warning {{chained comparison 'X <= Y > Z' 
does not behave the same as a mathematical expression}}
   (void)((x < y) < z);  // no-warning
   (void)((x < y) >= z); // no-warning
 

diff  --git a/clang/test/SemaCXX/bool-compare.cpp 
b/clang/test/SemaCXX/bool-compare.cpp
index 077d55ff9367d..1d856f2865ab6 100644
--- a/clang/test/SemaCXX/bool-compare.cpp
+++ b/clang/test/SemaCXX/bool-compare.cpp
@@ -98,7 +98,7 @@ void f(int x, int y, int z) {
   if ((ayy Y < Z' does 
not behave the same as a mathematical expression}}
   if ((a z)  {} // no warning
   if((a(zy)  {} // expected-error {{comparisons like 'X<=Y<=Z' don't have 
their mathematical meaning}}
+  if (zy)  {} // expected-error {{chained comparison 'X < Y > Z' does 
not b

[clang] [clang][CIR] Add missing dependency on MLIR headers (PR #131057)

2025-03-15 Thread via cfe-commits


@@ -11,6 +11,9 @@ add_clang_library(clangCIRFrontendAction
   DEPENDS
   MLIRCIROpsIncGen
   MLIRCIROpInterfacesIncGen
+  # Add mlir-generic-headers dependency as the header CIRGenAction.h needs to
+  # include BuiltinOps.h
+  mlir-generic-headers

darkbuck wrote:

> MLIRBuiltinLocationAttributesIncGen



> Why not `MLIRBuiltinLocationAttributesIncGen`?

narrow down to `MLIRBuiltinOpsIncGen`

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


[clang] [Feature]: merge host and kernel dependencies for heterogeneous compilation (PR #119513)

2025-03-15 Thread via cfe-commits

https://github.com/zhouronghua updated 
https://github.com/llvm/llvm-project/pull/119513

>From a93c012998c02abfe57c00c98ec20501a3641520 Mon Sep 17 00:00:00 2001
From: "ronghua.zhou" 
Date: Fri, 14 Feb 2025 01:04:51 +
Subject: [PATCH] [Feature]: support for the BC library file into the compile
 dependencies

---
 clang/lib/Driver/ToolChains/Clang.cpp   |  19 +++-
 clang/lib/Frontend/CompilerInstance.cpp |  10 ++-
 clang/lib/Frontend/DependencyFile.cpp   | 111 ++--
 3 files changed, 130 insertions(+), 10 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 55ec3db0ee994..e27c1fe95af42 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -1056,8 +1056,23 @@ void Clang::AddPreprocessingOptions(Compilation &C, 
const JobAction &JA,
 DepFile = getDependencyFileName(Args, Inputs);
 C.addFailureResultFile(DepFile, &JA);
   }
-  CmdArgs.push_back("-dependency-file");
-  CmdArgs.push_back(DepFile);
+  // for host compile, we changed the dep file name to *.d.CUID.host
+  // so it will not overide kernel dep file,
+  // and merge it with *.d (kernel dep) file in DependencyFile.cpp
+  // for example, abc.d -> abc.d.2282B80C.host
+  auto AT = getToolChain().getAuxTriple();
+  if (!AT && std::string(DepFile) != "-") {
+SmallString<128> NewDepFile(DepFile);
+NewDepFile.append(
+"." + llvm::utohexstr(llvm::sys::Process::GetRandomNumber()) +
+".host");
+CmdArgs.push_back("-dependency-file");
+CmdArgs.push_back(Args.MakeArgString(NewDepFile));
+// else keep the original dep file name
+  } else {
+CmdArgs.push_back("-dependency-file");
+CmdArgs.push_back(DepFile);
+  }
 }
 
 bool HasTarget = false;
diff --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index c11c857ea0606..60ac343391e18 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -494,8 +494,14 @@ void 
CompilerInstance::createPreprocessor(TranslationUnitKind TUKind) {
 
   // Handle generating dependencies, if requested.
   const DependencyOutputOptions &DepOpts = getDependencyOutputOpts();
-  if (!DepOpts.OutputFile.empty())
-addDependencyCollector(std::make_shared(DepOpts));
+  if (!DepOpts.OutputFile.empty()) {
+auto DFG = std::make_shared(DepOpts);
+for (auto F : getCodeGenOpts().LinkBitcodeFiles) {
+  DFG->maybeAddDependency(F.Filename, false, false, false, false);
+}
+addDependencyCollector(DFG);
+  }
+
   if (!DepOpts.DOTOutputFile.empty())
 AttachDependencyGraphGen(*PP, DepOpts.DOTOutputFile,
  getHeaderSearchOpts().Sysroot);
diff --git a/clang/lib/Frontend/DependencyFile.cpp 
b/clang/lib/Frontend/DependencyFile.cpp
index 15fa7de35df97..46aae8e7bf7ee 100644
--- a/clang/lib/Frontend/DependencyFile.cpp
+++ b/clang/lib/Frontend/DependencyFile.cpp
@@ -10,6 +10,9 @@
 //
 
//===--===//
 
+#include 
+#include 
+
 #include "clang/Basic/FileManager.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Frontend/DependencyOutputOptions.h"
@@ -343,6 +346,76 @@ static void PrintFilename(raw_ostream &OS, StringRef 
Filename,
   }
 }
 
+static std::vector SplitLines(llvm::StringRef &Dep) {
+  std::vector Deps;
+
+  for (const auto &line : llvm::split(KernelDepContent, '\n'))
+// Remove empty lines and comment lines
+if (!tmpline.empty() && tmpline[0] != '#')
+  Deps.insert(line);
+
+  return Deps;
+}
+
+static std::string GetKernelDepFileName(std::string &HostDepFileName) {
+
+  // merge host dependency file (*.d.CUID.host)
+  // to kernel dependency file (*.d) for tops target
+  // for example, abc.d -> abc.d.2282B80C.host
+  const int CUIDLEN = 9;
+  llvm::StringRef SubStr = ".host";
+  SmallString<128> OutputFileS(HostDepFileName);
+  size_t Pos = OutputFileS.find(SubStr);
+  // for tops target, trim .CUID.host in dep file name
+  if (Pos != llvm::StringRef::npos)
+// abc.d.2282B80C.host -> abc.d
+return OutputFileS.substr(0, Pos - CUIDLEN);
+  else
+return "";
+}
+
+static void TryMergeDependencyFile(std::vector &KD,
+   std::vector &HD,
+   std::string &KDFN) {
+  // both kernel and host dep file is empty
+  if (HD.empty() && KD.empty())
+return;
+
+  // Write merged dep file
+  llvm::raw_fd_ostream DF(KDFN, EC, llvm::sys::fs::OF_Text);
+  if (EC) {
+Diags.Report(diag::err_fe_error_opening) << KDFN << EC.message();
+return;
+  }
+  if (HD.empty())
+for (const auto &DL : KD)
+  DF << DL << "\n";
+  else if (KD.empty())
+for (const auto &DL : HD)
+  DF << DL << "\n";
+  else {
+if (KD.front() != HD.front())
+  Diags.Report(diag::err_fe_error_opening)
+

[clang] [llvm] [analysis] Software Bill of Mitigations (PR #130103)

2025-03-15 Thread Matthew Levy via cfe-commits

https://github.com/matthewlevy97 created 
https://github.com/llvm/llvm-project/pull/130103

The goal of this stack is to provide a metric to audit the deployed mitigations 
in a binary and where they are enabled at function level granularity. This will 
enable tracking of where we do and don't have mitigations, versus the current 
approach of tracking where flags are passed.

Two flags are added to control this behavior:
1) Compile time `-fmitigation-analysis` to generate the metadata pertaining to 
mitigation enablement/disablement
2) Link time `-enable-mitigation-analysis` to generate the output JSON when 
building with LTO

>From fb04b7bf5f2b668bf354632fc53e7521f44880c9 Mon Sep 17 00:00:00 2001
From: Matt Levy 
Date: Wed, 5 Mar 2025 12:36:02 -0500
Subject: [PATCH 1/2] [clang][CodeGen] Software Bill of Mitigations Metadata

The goal of this stack is to create a high fidelity mapping of mitigations to 
their possible insertion points and their actual insertion points. This would 
let us track where we do and don't have mitigations rather than the current 
approach of tracking where we have the flag.

There are some challenges posed by this like:
- Some mitigations are not emitted by the compiler, but the preprocessor
- Some mitigations are lowered later during IR -> MIR (stack cookies)
---
 clang/include/clang/Basic/CodeGenOptions.def |  1 +
 clang/include/clang/Driver/Options.td|  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp  | 10 +++
 clang/lib/CodeGen/CGClass.cpp|  3 +
 clang/lib/CodeGen/CGDecl.cpp |  4 +
 clang/lib/CodeGen/CGExpr.cpp |  5 ++
 clang/lib/CodeGen/CGExprCXX.cpp  |  6 ++
 clang/lib/CodeGen/CMakeLists.txt |  1 +
 clang/lib/CodeGen/CodeGenModule.cpp  | 22 +
 clang/lib/CodeGen/MitigationTagging.cpp  | 84 
 clang/lib/CodeGen/MitigationTagging.h| 45 +++
 clang/lib/Driver/ToolChains/Clang.cpp|  3 +
 12 files changed, 190 insertions(+)
 create mode 100644 clang/lib/CodeGen/MitigationTagging.cpp
 create mode 100644 clang/lib/CodeGen/MitigationTagging.h

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index a7f5f1abbb825..76a46ac3e592b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -191,6 +191,7 @@ CODEGENOPT(NoTypeCheck   , 1, 0) ///< Set when 
-Wa,--no-type-check is enable
 CODEGENOPT(MisExpect , 1, 0) ///< Set when -Wmisexpect is enabled
 CODEGENOPT(EnableSegmentedStacks , 1, 0) ///< Set when -fsplit-stack is 
enabled.
 CODEGENOPT(StackClashProtector, 1, 0) ///< Set when -fstack-clash-protection 
is enabled.
+CODEGENOPT(MitigationAnalysis, 1, 0) ///< Set when -fmitigation-analysis is 
enabled.
 CODEGENOPT(NoImplicitFloat   , 1, 0) ///< Set when -mno-implicit-float is 
enabled.
 CODEGENOPT(NullPointerIsValid , 1, 0) ///< Assume Null pointer deference is 
defined.
 CODEGENOPT(OpenCLCorrectlyRoundedDivSqrt, 1, 0) ///< 
-cl-fp32-correctly-rounded-divide-sqrt
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d0414aba35209..e50bb5c1c2cb4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3891,6 +3891,12 @@ defm split_stack : BoolFOption<"split-stack",
   CodeGenOpts<"EnableSegmentedStacks">, DefaultFalse,
   NegFlag,
   PosFlag>;
+defm mitigation_analysis : BoolFOption<"mitigation-analysis",
+  CodeGenOpts<"MitigationAnalysis">, DefaultFalse,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption], " mitigation analysis">>,
+  DocBrief<"Instrument mitigations (CFI, Stack Protectors, Auto-Var-Init, 
StackClashProtection) to analyze their coverage">;
 def fstack_protector_all : Flag<["-"], "fstack-protector-all">, Group,
   HelpText<"Enable stack protectors for all functions">;
 defm stack_clash_protection : BoolFOption<"stack-clash-protection",
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index ab8f19b25fa66..4e180bb1a87cf 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -21,6 +21,7 @@
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
+#include "MitigationTagging.h"
 #include "PatternInit.h"
 #include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
@@ -83,6 +84,8 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst 
*AI, Value *Size,
   switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
 // Nothing to initialize.
+AttachMitigationMetadataToFunction(CGF, MitigationKey::AUTO_VAR_INIT,
+   false);
 return;
   case LangOptions::TrivialAutoVarInitKind::Zero:
 Byte = CGF.Builder.getInt8(0x00);
@@ -94,6 +97,7 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst 
*AI, Value *Size,
 break;
   }

[clang] [clang][AMDGPU] Enable module splitting by default (PR #128509)

2025-03-15 Thread Pierre van Houtryve via cfe-commits

Pierre-vh wrote:

I'll get it tested internally ASAP. I wasn't confident in the driver changes so 
I was waiting for more feedback before doing it
I'll update once I get results

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


[clang] 431eaa8 - [HLSL] make semantic matching case insensitive (#129773)

2025-03-15 Thread via cfe-commits

Author: Sarah Spall
Date: 2025-03-10T11:19:45-07:00
New Revision: 431eaa8deb4ea1cbe079a29126f9559e4716f00d

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

LOG: [HLSL] make semantic matching case insensitive (#129773)

Make semantic matching case insensitive
update tests to reflect semantic printed as all lower case in error
messages
add new tests to show case insensitivity
Closes #128063

Added: 
clang/test/TableGen/HLSLAttribute-errors.td

Modified: 
clang/include/clang/Basic/Attr.td
clang/lib/Basic/Attributes.cpp
clang/lib/Sema/SemaHLSL.cpp
clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
clang/utils/TableGen/ClangAttrEmitter.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 4b4337cf460f3..4d34346460561 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -4717,21 +4717,21 @@ def HLSLNumThreads: InheritableAttr {
 }
 
 def HLSLSV_GroupThreadID: HLSLAnnotationAttr {
-  let Spellings = [HLSLAnnotation<"SV_GroupThreadID">];
+  let Spellings = [HLSLAnnotation<"sv_groupthreadid">];
   let Subjects = SubjectList<[ParmVar, Field]>;
   let LangOpts = [HLSL];
   let Documentation = [HLSLSV_GroupThreadIDDocs];
 }
 
 def HLSLSV_GroupID: HLSLAnnotationAttr {
-  let Spellings = [HLSLAnnotation<"SV_GroupID">];
+  let Spellings = [HLSLAnnotation<"sv_groupid">];
   let Subjects = SubjectList<[ParmVar, Field]>;
   let LangOpts = [HLSL];
   let Documentation = [HLSLSV_GroupIDDocs];
 }
 
 def HLSLSV_GroupIndex: HLSLAnnotationAttr {
-  let Spellings = [HLSLAnnotation<"SV_GroupIndex">];
+  let Spellings = [HLSLAnnotation<"sv_groupindex">];
   let Subjects = SubjectList<[ParmVar, GlobalVar]>;
   let LangOpts = [HLSL];
   let Documentation = [HLSLSV_GroupIndexDocs];
@@ -4783,7 +4783,7 @@ def HLSLPackOffset: HLSLAnnotationAttr {
 }
 
 def HLSLSV_DispatchThreadID: HLSLAnnotationAttr {
-  let Spellings = [HLSLAnnotation<"SV_DispatchThreadID">];
+  let Spellings = [HLSLAnnotation<"sv_dispatchthreadid">];
   let Subjects = SubjectList<[ParmVar, Field]>;
   let LangOpts = [HLSL];
   let Documentation = [HLSLSV_DispatchThreadIDDocs];

diff  --git a/clang/lib/Basic/Attributes.cpp b/clang/lib/Basic/Attributes.cpp
index 2035d4c0a5768..6a070a99c8d96 100644
--- a/clang/lib/Basic/Attributes.cpp
+++ b/clang/lib/Basic/Attributes.cpp
@@ -143,13 +143,17 @@ static SmallString<64> normalizeName(const IdentifierInfo 
*Name,
   StringRef ScopeName = normalizeAttrScopeName(Scope, SyntaxUsed);
   StringRef AttrName = normalizeAttrName(Name, ScopeName, SyntaxUsed);
 
+  std::string StrAttrName = AttrName.str();
+  if (SyntaxUsed == AttributeCommonInfo::AS_HLSLAnnotation)
+StrAttrName = AttrName.lower();
+
   SmallString<64> FullName = ScopeName;
   if (!ScopeName.empty()) {
 assert(SyntaxUsed == AttributeCommonInfo::AS_CXX11 ||
SyntaxUsed == AttributeCommonInfo::AS_C23);
 FullName += "::";
   }
-  FullName += AttrName;
+  FullName += StrAttrName;
 
   return FullName;
 }

diff  --git a/clang/lib/Sema/SemaHLSL.cpp b/clang/lib/Sema/SemaHLSL.cpp
index 2e6a333f3d768..124dbc2771f94 100644
--- a/clang/lib/Sema/SemaHLSL.cpp
+++ b/clang/lib/Sema/SemaHLSL.cpp
@@ -752,7 +752,7 @@ void SemaHLSL::DiagnoseAttrStageMismatch(
 HLSLShaderAttr::ConvertEnvironmentTypeToStr(ST));
   });
   Diag(A->getLoc(), diag::err_hlsl_attr_unsupported_in_stage)
-  << A << llvm::Triple::getEnvironmentTypeName(Stage)
+  << A->getAttrName() << llvm::Triple::getEnvironmentTypeName(Stage)
   << (AllowedStages.size() != 1) << join(StageStrings, ", ");
 }
 

diff  --git a/clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl 
b/clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
index 6781f9241df24..a2203692b582b 100644
--- a/clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
+++ b/clang/test/SemaHLSL/Semantics/valid_entry_parameter.hlsl
@@ -24,6 +24,12 @@ void CSMain3(uint3 : SV_DispatchThreadID) {
 // CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:20 'uint3'
 // CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
 }
+[numthreads(8,8,1)]
+void CSMain4(uint3 : SV_DispatchThreadId) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 CSMain4 
'void (uint3)'
+// CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:20 'uint3'
+// CHECK-NEXT: HLSLSV_DispatchThreadIDAttr
+}
 
 [numthreads(8,8,1)]
 void CSMain_GID(uint ID : SV_GroupID) {
@@ -49,6 +55,12 @@ void CSMain3_GID(uint3 : SV_GroupID) {
 // CHECK-NEXT: ParmVarDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> col:24 'uint3'
 // CHECK-NEXT: HLSLSV_GroupIDAttr
 }
+[numthreads(8,8,1)]
+void CSMain4_GID(uint3 : Sv_GroupId) {
+// CHECK: FunctionDecl 0x{{[0-9a-fA-F]+}} <{{.*}}> line:[[@LINE-1]]:6 
CSMai

[clang] [HLSL] select scalar overloads for vector conditions (PR #129396)

2025-03-15 Thread Chris B via cfe-commits

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


[clang] [llvm] [Support] Introduce new `AdvisoryLock` interface (PR #130989)

2025-03-15 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 created 
https://github.com/llvm/llvm-project/pull/130989

This PR abstracts the `LockFileManager` API into new `AdvisoryLock` interface. 
This is so that we can create an alternative implementation for Clang 
implicitly-built modules that is optimized for single-process environment.

>From cd0b9a8b878c4ecd929552c836f3d4665e926ef4 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Wed, 12 Mar 2025 09:37:27 -0700
Subject: [PATCH] [Support] Introduce new `AdvisoryLock` interface

This PR abstracts the `LockFileManager` API into new `AdvisoryLock` interface. 
This is so that we can create an alternative implementation for Clang 
implicitly-built modules that is optimized for single-process environment.
---
 clang/lib/Frontend/CompilerInstance.cpp  |  8 +--
 llvm/include/llvm/Support/AdvisoryLock.h | 54 
 llvm/include/llvm/Support/LockFileManager.h  | 33 
 llvm/lib/Support/LockFileManager.cpp | 11 ++--
 llvm/lib/Target/AMDGPU/AMDGPUSplitModule.cpp |  8 +--
 5 files changed, 76 insertions(+), 38 deletions(-)
 create mode 100644 llvm/include/llvm/Support/AdvisoryLock.h

diff --git a/clang/lib/Frontend/CompilerInstance.cpp 
b/clang/lib/Frontend/CompilerInstance.cpp
index 44f4f48ef94e8..ef09cd9cc43d7 100644
--- a/clang/lib/Frontend/CompilerInstance.cpp
+++ b/clang/lib/Frontend/CompilerInstance.cpp
@@ -1503,18 +1503,18 @@ static bool compileModuleAndReadASTBehindLock(
 // Someone else is responsible for building the module. Wait for them to
 // finish.
 switch (Lock.waitForUnlock()) {
-case llvm::LockFileManager::Res_Success:
+case llvm::WaitForUnlockResult::Success:
   break; // The interesting case.
-case llvm::LockFileManager::Res_OwnerDied:
+case llvm::WaitForUnlockResult::OwnerDied:
   continue; // try again to get the lock.
-case llvm::LockFileManager::Res_Timeout:
+case llvm::WaitForUnlockResult::Timeout:
   // Since ModuleCache takes care of correctness, we try waiting for
   // another process to complete the build so clang does not do it done
   // twice. If case of timeout, build it ourselves.
   Diags.Report(ModuleNameLoc, diag::remark_module_lock_timeout)
   << Module->Name;
   // Clear the lock file so that future invocations can make progress.
-  Lock.unsafeRemoveLockFile();
+  Lock.unsafeUnlockShared();
   continue;
 }
 
diff --git a/llvm/include/llvm/Support/AdvisoryLock.h 
b/llvm/include/llvm/Support/AdvisoryLock.h
new file mode 100644
index 0..57c993f48f240
--- /dev/null
+++ b/llvm/include/llvm/Support/AdvisoryLock.h
@@ -0,0 +1,54 @@
+//===--===//
+//
+// 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
+//
+//===--===//
+
+#ifndef LLVM_SUPPORT_ADVISORYLOCK_H
+#define LLVM_SUPPORT_ADVISORYLOCK_H
+
+#include "llvm/Support/Error.h"
+
+namespace llvm {
+/// Describes the result of waiting for the owner to release the lock.
+enum class WaitForUnlockResult {
+  /// The lock was released successfully.
+  Success,
+  /// Owner died while holding the lock.
+  OwnerDied,
+  /// Reached timeout while waiting for the owner to release the lock.
+  Timeout,
+};
+
+/// A synchronization primitive with weak mutual exclusion guarantees.
+/// Implementations of this interface may allow multiple threads/processes to
+/// acquire the lock simultaneously. Typically, threads/processes waiting for
+/// the lock to be unlocked will validate the computation produced valid 
result.
+class AdvisoryLock {
+public:
+  /// Tries to acquire the lock without blocking.
+  ///
+  /// \returns true if the lock was successfully acquired (owned lock), false 
if
+  /// the lock is already held by someone else (shared lock), or \c Error in
+  /// case of unexpected failure.
+  virtual Expected tryLock() = 0;
+
+  /// For a shared lock, wait until the owner releases the lock.
+  ///
+  /// \param MaxSeconds the maximum total wait time in seconds.
+  virtual WaitForUnlockResult waitForUnlockFor(unsigned MaxSeconds) = 0;
+  WaitForUnlockResult waitForUnlock() { return waitForUnlockFor(90); }
+
+  /// Unlocks a shared lock. This may allow another thread/process to acquire
+  /// the lock before the existing owner released it and notify waiting
+  /// threads/processes. This is an unsafe operation.
+  virtual std::error_code unsafeUnlockShared() = 0;
+
+  /// Unlocks the lock if previously acquired by \c tryLock().
+  virtual ~AdvisoryLock() = default;
+};
+} // end namespace llvm
+
+#endif
diff --git a/llvm/include/llvm/Support/LockFileManager.h 
b/llvm/include/llvm/Support/LockFileManager.h
index cf02b41a6f729..1653a7416f667 100644
--- a/llvm/include/llvm/Support/LockFileManage

[clang] [Clang] Fix immediate escalation of template function specializations. (PR #124404)

2025-03-15 Thread Michael Buch via cfe-commits

Michael137 wrote:

FYI, this is causing the LLDB `image dump ast` command to infinitely recurse 
when we have template functions in the AST. Not really super urgent because 
it's not a command most people use, and the root cause is probably due to the 
way LLDB constructs its AST. But thought I'd flag it here in case someone runs 
into this too

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


[clang] [Clang] Implement P0963R3 "Structured binding declaration as a condition" (PR #130228)

2025-03-15 Thread Younan Zhang via cfe-commits


@@ -5218,16 +5218,28 @@ static bool EvaluateVarDecl(EvalInfo &Info, const 
VarDecl *VD) {
   return true;
 }
 
+static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
+  const DecompositionDecl *DD);
+
 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
   bool OK = true;
 
   if (const VarDecl *VD = dyn_cast(D))
 OK &= EvaluateVarDecl(Info, VD);
 
-  if (const DecompositionDecl *DD = dyn_cast(D))
-for (auto *BD : DD->flat_bindings())
-  if (auto *VD = BD->getHoldingVar())
-OK &= EvaluateDecl(Info, VD);
+  if (const DecompositionDecl *DD = dyn_cast(D);
+  DD && !DD->isDecisionVariable())
+OK &= EvaluateDecompositionDeclInit(Info, DD);
+
+  return OK;
+}
+
+static bool EvaluateDecompositionDeclInit(EvalInfo &Info,
+  const DecompositionDecl *DD) {
+  bool OK = true;
+  for (auto *BD : DD->flat_bindings())
+if (auto *VD = BD->getHoldingVar())
+  OK &= EvaluateDecl(Info, VD);

zyn0217 wrote:

(The crash doesn't occur in C++23 mode)

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


[clang] [sanitizer][CFI] Add support to build CFI with sanitize-coverage (PR #131296)

2025-03-15 Thread Maxim Zhukov via cfe-commits

Mephistophiles wrote:

Hi @vitalybuka! Should I wait @kstoimenov approval?

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


[clang] [llvm] [OpenMP] Remove 'libomptarget.devicertl.a' fatbinary and use static library (PR #126143)

2025-03-15 Thread Joseph Huber via cfe-commits

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

>From 326befb8bdaafe1a2954b7aa956d26f1ec8c187f Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Thu, 6 Feb 2025 15:54:19 -0600
Subject: [PATCH] [OpenMP] Remove 'libomptarget.devicertl.a' fatbinary and use
 static library

Summary:
Currently, we build a single `libomptarget.devicertl.a` which is a
fatbinary. It is a host object file that contains the embedded archive
files for both the NVIDIA and AMDGPU targets. This was done primarily as
a convenience due to naming conflicts. Now that the clang driver for the
GPU targets can appropriate link via the per-target runtime-dir, we can
just make two separate static libraries and remove the indirection.

This patch creates two new static libraries that get installed into
```
/lib/amdgcn-amd-amdhsa/libomp.a
/lib/nvptx64-nvidia-cuda/libomp.a
```
for AMDGPU and NVPTX respectively. The link job created by the linker
wrapper now simply needs to do `-lomp` and it will search those
directories and link those static libraries. This requires far less
special handling.

This patch is a precursor to changing the build system entirely to be a
runtimes based one. Soon this target will be a standard `add_library`
and done through the GPU runtime targets.

NOTE that this actually does remove an additional optimization step.
Previously we merged all of the files into a single bitcode object and
forcibly internalized some definitions. This, instead, just treats them
like a normal static library. This may possibly affect performance for
some files, but I think it's better overall to use static library
semantics because it allows us to have an 'include-what-you-use'
relationship with the library.

Performance testing will be required. If we really need the merged blob
then we can simply pack that into a new static library.

omp -> omptarget
---
 clang/lib/Driver/ToolChains/Clang.cpp  |   5 +
 clang/lib/Driver/ToolChains/CommonArgs.cpp |   4 -
 clang/test/Driver/openmp-offload-gpu.c |   6 +-
 offload/DeviceRTL/CMakeLists.txt   | 160 +
 offload/DeviceRTL/src/exports  |  19 ---
 offload/test/lit.cfg   |  36 ++---
 6 files changed, 65 insertions(+), 165 deletions(-)
 delete mode 100644 offload/DeviceRTL/src/exports

diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp
index 4ebbd241d2f0b..ee582608e999e 100644
--- a/clang/lib/Driver/ToolChains/Clang.cpp
+++ b/clang/lib/Driver/ToolChains/Clang.cpp
@@ -9258,6 +9258,11 @@ void LinkerWrapper::ConstructJob(Compilation &C, const 
JobAction &JA,
   A->render(Args, LinkerArgs);
   }
 
+  // If this is OpenMP the device linker will need `-lompdevice`.
+  if (Kind == Action::OFK_OpenMP && !Args.hasArg(OPT_no_offloadlib) &&
+  (TC->getTriple().isAMDGPU() || TC->getTriple().isNVPTX()))
+LinkerArgs.emplace_back("-lompdevice");
+
   // Forward all of these to the appropriate toolchain.
   for (StringRef Arg : CompilerArgs)
 CmdArgs.push_back(Args.MakeArgString(
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index b43472a52038b..2e23f9e3f7397 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -1296,10 +1296,6 @@ bool tools::addOpenMPRuntime(const Compilation &C, 
ArgStringList &CmdArgs,
   if (IsOffloadingHost)
 CmdArgs.push_back("-lomptarget");
 
-  if (IsOffloadingHost &&
-  Args.hasFlag(options::OPT_offloadlib, options::OPT_no_offloadlib, true))
-CmdArgs.push_back("-lomptarget.devicertl");
-
   addArchSpecificRPath(TC, Args, CmdArgs);
 
   addOpenMPRuntimeLibraryPath(TC, Args, CmdArgs);
diff --git a/clang/test/Driver/openmp-offload-gpu.c 
b/clang/test/Driver/openmp-offload-gpu.c
index 1f7e2996068c4..807ea2c6e5f86 100644
--- a/clang/test/Driver/openmp-offload-gpu.c
+++ b/clang/test/Driver/openmp-offload-gpu.c
@@ -324,18 +324,18 @@
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--offload-arch=sm_52 --cuda-path=%S/Inputs/CUDA_102/usr/local/cuda \
 // RUN: -foffload-lto %s 2>&1 | FileCheck --check-prefix=CHECK-LTO-LIBRARY 
%s
 
-// CHECK-LTO-LIBRARY: {{.*}}-lomptarget{{.*}}-lomptarget.devicertl
+// CHECK-LTO-LIBRARY: --device-linker={{.*}}=-lomp{{.*}}-lomptarget{{.*}}
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--offload-arch=sm_52 --cuda-path=%S/Inputs/CUDA_102/usr/local/cuda \
 // RUN: 
--libomptarget-nvptx-bc-path=%S/Inputs/libomptarget/libomptarget-nvptx-test.bc 
%s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-NO-LTO-LIBRARY %s
 
-// CHECK-NO-LTO-LIBRARY: {{.*}}-lomptarget{{.*}}-lomptarget.devicertl
+// CHECK-NO-LTO-LIBRARY: --device-linker={{.*}}=-lomp{{.*}}-lomptarget{{.*}}
 
 // RUN:   %clang -### --target=x86_64-unknown-linux-gnu -fopenmp=libomp 
--offload-arch=sm_52 -nogpulib \
 // RUN: -foffload-lto %s

[clang] 39cf545 - [HLSL][Driver] Use temporary files correctly (#130436)

2025-03-15 Thread via cfe-commits

Author: Chris B
Date: 2025-03-10T10:13:33-05:00
New Revision: 39cf545756b358d02d9b828e5c51ebcb8ed6d19e

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

LOG: [HLSL][Driver] Use temporary files correctly (#130436)

This updates the DXV and Metal Converter actions to properly use
temporary files created by the driver. I've abstracted away a check to
determine if an action is the last in the sequence because we may have
between 1 and 3 actions depending on the arguments and environment.

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
clang/lib/Driver/ToolChains/HLSL.cpp
clang/lib/Driver/ToolChains/HLSL.h
clang/test/Driver/HLSL/metal-converter.hlsl
clang/test/Driver/dxc_dxv_path.hlsl

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 08ae8173db6df..9457a19255f21 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4669,7 +4669,7 @@ void Driver::BuildActions(Compilation &C, DerivedArgList 
&Args,
   Actions.push_back(C.MakeAction(
   LastAction, types::TY_DX_CONTAINER));
 }
-if (Args.getLastArg(options::OPT_metal)) {
+if (TC.requiresBinaryTranslation(Args)) {
   Action *LastAction = Actions.back();
   // Metal shader converter runs on DXIL containers, which can either be
   // validated (in which case they are TY_DX_CONTAINER), or unvalidated
@@ -5219,8 +5219,14 @@ void Driver::BuildJobs(Compilation &C) const {
 unsigned NumOutputs = 0;
 unsigned NumIfsOutputs = 0;
 for (const Action *A : C.getActions()) {
+  // The actions below do not increase the number of outputs, when 
operating
+  // on DX containers.
+  if (A->getType() == types::TY_DX_CONTAINER &&
+  (A->getKind() == clang::driver::Action::BinaryAnalyzeJobClass ||
+   A->getKind() == clang::driver::Action::BinaryTranslatorJobClass))
+continue;
+
   if (A->getType() != types::TY_Nothing &&
-  A->getType() != types::TY_DX_CONTAINER &&
   !(A->getKind() == Action::IfsMergeJobClass ||
 (A->getType() == clang::driver::types::TY_IFS_CPP &&
  A->getKind() == clang::driver::Action::CompileJobClass &&
@@ -6221,11 +6227,27 @@ const char *Driver::GetNamedOutputPath(Compilation &C, 
const JobAction &JA,
 return C.addResultFile(C.getArgs().MakeArgString(FcValue.str()), &JA);
   }
 
-  if (JA.getType() == types::TY_Object &&
-  C.getArgs().hasArg(options::OPT_dxc_Fo)) {
+  if ((JA.getType() == types::TY_Object &&
+   C.getArgs().hasArg(options::OPT_dxc_Fo)) ||
+  JA.getType() == types::TY_DX_CONTAINER) {
 StringRef FoValue = C.getArgs().getLastArgValue(options::OPT_dxc_Fo);
-// TODO: Should we use `MakeCLOutputFilename` here? If so, we can probably
-// handle this as part of the SLASH_Fo handling below.
+// If we are targeting DXIL and not validating or translating, we should 
set
+// the final result file. Otherwise we should emit to a temporary.
+if (C.getDefaultToolChain().getTriple().isDXIL()) {
+  const auto &TC = static_cast(
+  C.getDefaultToolChain());
+  // Fo can be empty here if the validator is running for a compiler flow
+  // that is using Fc or just printing disassembly.
+  if (TC.isLastJob(C.getArgs(), JA.getKind()) && !FoValue.empty())
+return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA);
+  StringRef Name = llvm::sys::path::filename(BaseInput);
+  std::pair Split = Name.split('.');
+  const char *Suffix = types::getTypeTempSuffix(JA.getType(), true);
+  return CreateTempFile(C, Split.first, Suffix, false);
+}
+// We don't have SPIRV-val integrated (yet), so for now we can assume this
+// is the final output.
+assert(C.getDefaultToolChain().getTriple().isSPIRV());
 return C.addResultFile(C.getArgs().MakeArgString(FoValue.str()), &JA);
   }
 

diff  --git a/clang/lib/Driver/ToolChains/HLSL.cpp 
b/clang/lib/Driver/ToolChains/HLSL.cpp
index 62e4d14390b90..22498bff1f251 100644
--- a/clang/lib/Driver/ToolChains/HLSL.cpp
+++ b/clang/lib/Driver/ToolChains/HLSL.cpp
@@ -186,12 +186,9 @@ void tools::hlsl::Validator::ConstructJob(Compilation &C, 
const JobAction &JA,
   ArgStringList CmdArgs;
   assert(Inputs.size() == 1 && "Unable to handle multiple inputs.");
   const InputInfo &Input = Inputs[0];
-  assert(Input.isFilename() && "Unexpected verify input");
-  // Grabbing the output of the earlier cc1 run.
   CmdArgs.push_back(Input.getFilename());
-  // Use the same name as output.
   CmdArgs.push_back("-o");
-  CmdArgs.push_back(Input.getFilename());
+  CmdArgs.push_back(Output.getFilename());
 
   const char *Exec = Args.MakeArgString(DxvPath);
   C.addCommand(std::make_unique(JA, *this, 
Respon

[clang] [alpha.webkit.UncountedCallArgsChecker] Treat an explicit construction of Ref from a Ref return value safe. (PR #130911)

2025-03-15 Thread Ryosuke Niwa via cfe-commits


@@ -70,6 +70,8 @@ bool tryToFindPtrOrigin(
   if (isCtorOfSafePtr(ConversionFunc))
 return callback(E, true);
 }
+if (isa(E) && isSafePtrType(cast->getType()))
+  return callback(E, true);

rniwa wrote:

We typically don't pass arguments as RefPtr / Ref except a few cases where we 
pass in as RefPtr&& / Ref&&. I guess we can add a test for it though.

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


[clang] [HLSL] Make sure `isSigned` flag is set on target type for `TypedBuffer` resources with signed int vectors (PR #130223)

2025-03-15 Thread Helena Kotas via cfe-commits


@@ -59,8 +59,14 @@ llvm::Type *DirectXTargetCodeGenInfo::getHLSLType(
 SmallVector Ints = {/*IsWriteable*/ ResAttrs.ResourceClass ==
  llvm::dxil::ResourceClass::UAV,
  /*IsROV*/ ResAttrs.IsROV};
-if (!ResAttrs.RawBuffer)
-  Ints.push_back(/*IsSigned*/ ContainedTy->isSignedIntegerType());
+if (!ResAttrs.RawBuffer) {
+  const clang::Type *ElemType = ContainedTy->getUnqualifiedDesugaredType();
+  if (ElemType->isVectorType())

hekota wrote:

No, vectors cannot be nested, only arrays.

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


[clang] [llvm] [VectorCombine] Shrink loads used in shufflevector rebroadcasts (PR #128938)

2025-03-15 Thread Leon Clark via cfe-commits

https://github.com/PeddleSpam updated 
https://github.com/llvm/llvm-project/pull/128938

>From f1c09277af268256fce71df9a858959b69385ef1 Mon Sep 17 00:00:00 2001
From: Leon Clark 
Date: Wed, 26 Feb 2025 15:59:02 +
Subject: [PATCH 1/6] [AggressiveInstCombine] Shrink loads used in
 shufflevector rebroadcasts.

Attempt to shrink the size of vector loads where only some of the incoming 
lanes are used for rebroadcasts in shufflevector instructions.
---
 .../load-shufflevector.ll | 345 ++
 1 file changed, 345 insertions(+)
 create mode 100644 
llvm/test/Transforms/AggressiveInstCombine/load-shufflevector.ll

diff --git a/llvm/test/Transforms/AggressiveInstCombine/load-shufflevector.ll 
b/llvm/test/Transforms/AggressiveInstCombine/load-shufflevector.ll
new file mode 100644
index 0..3f6c8334e61cf
--- /dev/null
+++ b/llvm/test/Transforms/AggressiveInstCombine/load-shufflevector.ll
@@ -0,0 +1,345 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py 
UTC_ARGS: --version 5
+; RUN: opt -passes=aggressive-instcombine -S < %s | FileCheck %s
+
+define <8 x half> @shuffle_v4_v8f16_r0_1(ptr addrspace(1) nocapture readonly 
%arg0) local_unnamed_addr {
+; CHECK-LABEL: define <8 x half> @shuffle_v4_v8f16_r0_1(
+; CHECK-SAME: ptr addrspace(1) readonly captures(none) [[ARG0:%.*]]) 
local_unnamed_addr {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:[[VAL0:%.*]] = load <4 x half>, ptr addrspace(1) [[ARG0]], 
align 32
+; CHECK-NEXT:[[TMP1:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <8 x i32> 
+; CHECK-NEXT:ret <8 x half> [[TMP1]]
+;
+entry:
+  %val0 = load <4 x half>, ptr addrspace(1) %arg0, align 32
+  %val1 = shufflevector <4 x half> %val0, <4 x half> poison, <8 x i32> 
+  ret <8 x half> %val1
+}
+
+define <8 x half> @shuffle_v4_v8f16_r0_2(ptr addrspace(1) nocapture readonly 
%arg0) local_unnamed_addr {
+; CHECK-LABEL: define <8 x half> @shuffle_v4_v8f16_r0_2(
+; CHECK-SAME: ptr addrspace(1) readonly captures(none) [[ARG0:%.*]]) 
local_unnamed_addr {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:[[VAL0:%.*]] = load <4 x half>, ptr addrspace(1) [[ARG0]], 
align 32
+; CHECK-NEXT:[[TMP1:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <8 x i32> 
+; CHECK-NEXT:ret <8 x half> [[TMP1]]
+;
+entry:
+  %val0 = load <4 x half>, ptr addrspace(1) %arg0, align 32
+  %val1 = shufflevector <4 x half> %val0, <4 x half> poison, <8 x i32> 
+  ret <8 x half> %val1
+}
+
+define <4 x half> @shuffle_v4_v4f16_r1_2(ptr addrspace(1) nocapture readonly 
%arg0) local_unnamed_addr {
+; CHECK-LABEL: define <4 x half> @shuffle_v4_v4f16_r1_2(
+; CHECK-SAME: ptr addrspace(1) readonly captures(none) [[ARG0:%.*]]) 
local_unnamed_addr {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:[[VAL0:%.*]] = load <4 x half>, ptr addrspace(1) [[ARG0]], 
align 32
+; CHECK-NEXT:[[TMP1:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <4 x i32> 
+; CHECK-NEXT:ret <4 x half> [[TMP1]]
+;
+entry:
+  %val0 = load <4 x half>, ptr addrspace(1) %arg0, align 32
+  %val1 = shufflevector <4 x half> %val0, <4 x half> poison, <4 x i32> 
+  ret <4 x half> %val1
+}
+
+define <8 x half> @shuffle_v4_v8f16_r1_2(ptr addrspace(1) nocapture readonly 
%arg0) local_unnamed_addr {
+; CHECK-LABEL: define <8 x half> @shuffle_v4_v8f16_r1_2(
+; CHECK-SAME: ptr addrspace(1) readonly captures(none) [[ARG0:%.*]]) 
local_unnamed_addr {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:[[VAL0:%.*]] = load <4 x half>, ptr addrspace(1) [[ARG0]], 
align 32
+; CHECK-NEXT:[[TMP1:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <8 x i32> 
+; CHECK-NEXT:ret <8 x half> [[TMP1]]
+;
+entry:
+  %val0 = load <4 x half>, ptr addrspace(1) %arg0, align 32
+  %val1 = shufflevector <4 x half> %val0, <4 x half> poison, <8 x i32> 
+  ret <8 x half> %val1
+}
+
+define <8 x half> @shuffle_v4_v8f16_cond_r0_1(ptr addrspace(1) nocapture 
readonly %arg0, i1 %cond) local_unnamed_addr {
+; CHECK-LABEL: define <8 x half> @shuffle_v4_v8f16_cond_r0_1(
+; CHECK-SAME: ptr addrspace(1) readonly captures(none) [[ARG0:%.*]], i1 
[[COND:%.*]]) local_unnamed_addr {
+; CHECK-NEXT:  [[ENTRY:.*:]]
+; CHECK-NEXT:[[VAL0:%.*]] = load <4 x half>, ptr addrspace(1) [[ARG0]], 
align 32
+; CHECK-NEXT:br i1 [[COND]], label %[[THEN:.*]], label %[[ELSE:.*]]
+; CHECK:   [[THEN]]:
+; CHECK-NEXT:[[VAL1:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <8 x i32> zeroinitializer
+; CHECK-NEXT:br label %[[FINALLY:.*]]
+; CHECK:   [[ELSE]]:
+; CHECK-NEXT:[[VAL2:%.*]] = shufflevector <4 x half> [[VAL0]], <4 x half> 
poison, <8 x i32> 
+; CHECK-NEXT:br label %[[FINALLY]]
+; CHECK:   [[FINALLY]]:
+; CHECK-NEXT:[[VAL3:%.*]] = phi <8 x half> [ [[VAL1]], %[[THEN]] ], [ 
[[VAL2]], %[[ELSE]] ]
+; CHECK-NEXT:ret <8 x half> [[VAL3]]
+;
+entry:
+  %val0 = load <4 x half>, ptr addrspace(1) %arg0, align 32
+  br i1 %cond, label %then, label %else
+
+then

[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Arseniy Zaostrovnykh via cfe-commits


@@ -688,6 +695,36 @@ AnalysisConsumer::getModeForDecl(Decl *D, AnalysisMode 
Mode) {
   return Mode;
 }
 
+template 
+static clang::Decl *preferDefinitionImpl(clang::Decl *D) {
+  if (auto *X = dyn_cast(D))
+if (auto *Def = X->getDefinition())
+  return Def;
+  return D;
+}
+
+template <> clang::Decl *preferDefinitionImpl(clang::Decl *D) {
+  if (const auto *X = dyn_cast(D)) {
+for (auto *I : X->redecls())
+  if (I->hasBody())
+return I;
+  }
+  return D;
+}
+
+static Decl *getDefinitionOrCanonicalDecl(Decl *D) {
+  assert(D);
+  D = D->getCanonicalDecl();
+  D = preferDefinitionImpl(D);
+  D = preferDefinitionImpl(D);
+  D = preferDefinitionImpl(D);
+  D = preferDefinitionImpl(D);
+  assert(D);
+  return D;
+}
+

necto wrote:

removed
8e58d6c649ee Remove unnecesary canonicalization

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


[clang] [HLSL] error on out of bounds vector accesses (PR #128952)

2025-03-15 Thread Sarah Spall via cfe-commits

https://github.com/spall updated 
https://github.com/llvm/llvm-project/pull/128952

>From 656d6e87466bfc85246f7abaedfe6549e566717b Mon Sep 17 00:00:00 2001
From: Sarah Spall 
Date: Wed, 26 Feb 2025 14:37:06 -0800
Subject: [PATCH 1/7] error on out of bounds vector accesses

---
 .../clang/Basic/DiagnosticSemaKinds.td|  5 
 clang/include/clang/Sema/Sema.h   |  1 +
 clang/lib/Sema/SemaChecking.cpp   | 24 +++
 .../Language/VectorOutOfRange-errors.hlsl | 19 +++
 4 files changed, 49 insertions(+)
 create mode 100644 clang/test/SemaHLSL/Language/VectorOutOfRange-errors.hlsl

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 51301d95e55b9..0989b4c05b86f 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -10635,6 +10635,11 @@ def err_block_on_vm : Error<
 def err_sizeless_nonlocal : Error<
   "non-local variable with sizeless type %0">;
 
+def err_vector_index_out_of_range : Error<
+  "vector element index %0 is out of bounds">;
+def warn_vector_index_out_of_range : Warning<
+  "vector element index %0 is out of bounds">;
+
 def err_vec_builtin_non_vector : Error<
  "%select{first two|all}1 arguments to %0 must be vectors">;
 def err_vec_builtin_incompatible_vector : Error<
diff --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 476abe86cb2d2..fad3cbddc555b 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -2468,6 +2468,7 @@ class Sema final : public SemaBase {
 const ArraySubscriptExpr *ASE = nullptr,
 bool AllowOnePastEnd = true, bool IndexNegated = 
false);
   void CheckArrayAccess(const Expr *E);
+  void CheckVectorAccess(const Expr *BaseExpr, const Expr *IndexExpr);
 
   bool CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
 const FunctionProtoType *Proto);
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f9926c6b4adab..1cbf428f18366 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -14017,6 +14017,24 @@ void Sema::CheckCastAlign(Expr *Op, QualType T, 
SourceRange TRange) {
 << TRange << Op->getSourceRange();
 }
 
+void Sema::CheckVectorAccess(const Expr *BaseExpr, const Expr *IndexExpr) {
+  const VectorType *VTy = BaseExpr->getType()->getAs();
+  if (!VTy)
+return;
+
+  Expr::EvalResult Result;
+  if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
+return;
+
+  unsigned DiagID = getLangOpts().HLSL ? diag::err_vector_index_out_of_range
+   : diag::warn_vector_index_out_of_range;
+
+  llvm::APSInt index = Result.Val.getInt();
+  if (index.isNegative() || index >= VTy->getNumElements())
+Diag(BaseExpr->getBeginLoc(), DiagID) << toString(index, 10, true);
+  return;
+}
+
 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
 const ArraySubscriptExpr *ASE,
 bool AllowOnePastEnd, bool IndexNegated) {
@@ -14031,6 +14049,12 @@ void Sema::CheckArrayAccess(const Expr *BaseExpr, 
const Expr *IndexExpr,
   const Type *EffectiveType =
   BaseExpr->getType()->getPointeeOrArrayElementType();
   BaseExpr = BaseExpr->IgnoreParenCasts();
+
+  if (BaseExpr->getType()->isVectorType()) {
+CheckVectorAccess(BaseExpr, IndexExpr);
+return;
+  }
+
   const ConstantArrayType *ArrayTy =
   Context.getAsConstantArrayType(BaseExpr->getType());
 
diff --git a/clang/test/SemaHLSL/Language/VectorOutOfRange-errors.hlsl 
b/clang/test/SemaHLSL/Language/VectorOutOfRange-errors.hlsl
new file mode 100644
index 0..02b5693f4076c
--- /dev/null
+++ b/clang/test/SemaHLSL/Language/VectorOutOfRange-errors.hlsl
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -finclude-default-header -triple 
dxil-pc-shadermodel6.6-library %s -verify
+
+export void fn1() {
+  int2 A = {1,2};
+  int X = A[-1];
+  // expected-error@-1 {{vector element index '-1' is out of bounds}}
+}
+
+export void fn2() {
+  int4 A = {1,2,3,4};
+  int X = A[4];
+  // expected-error@-1 {{vector element index '4' is out of bounds}}
+}
+
+export void fn3() {
+  bool2 A = {true,true};
+  bool X = A[-1];
+  // expected-error@-1 {{vector element index '-1' is out of bounds}}
+}

>From f44e697beb1dfa6a028a8015f3d9587968f3600c Mon Sep 17 00:00:00 2001
From: Sarah Spall 
Date: Wed, 26 Feb 2025 15:58:44 -0800
Subject: [PATCH 2/7] add warning flag for vector out of bounds warning. fix
 test

---
 clang/include/clang/Basic/DiagnosticGroups.td | 1 +
 clang/include/clang/Basic/DiagnosticSemaKinds.td  | 3 ++-
 clang/test/SemaHLSL/Language/VectorOutOfRange-errors.hlsl | 6 +++---
 3 files changed, 6 insertions(+), 4 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/c

[clang] [CIR] Upstream CastOp and scalar conversions (PR #130690)

2025-03-15 Thread Morris Hafner via cfe-commits


@@ -78,6 +78,111 @@ class LLVMLoweringInfo {
 class CIR_Op traits = []> :
 Op, LLVMLoweringInfo;
 
+//===--===//
+// CastOp
+//===--===//
+
+// The enumaration value isn't in sync with clang.

mmha wrote:

I tried to get the enums in sync. Good news is I found a couple of unused 
casting kinds wrt. complex numbers which I removed. Bad news is I found one 
casting kind (bool to float) that's specific to CIR: llvm/clangir#290. I moved 
it to the bottom on the list so the enum values of classic CG and CIR match up.

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


[clang] C89 doesn't have `math.h` functions (PR #129979)

2025-03-15 Thread Vinay Deshmukh via cfe-commits

https://github.com/vinay-deshmukh updated 
https://github.com/llvm/llvm-project/pull/129979

>From e9c7869550d9fd1eba4d4d42ee644540e6b6d445 Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Tue, 4 Mar 2025 22:30:34 -0500
Subject: [PATCH 1/9] add failing test

---
 clang/test/C/drs/c89_with_c99_functions.c | 7 +++
 1 file changed, 7 insertions(+)
 create mode 100644 clang/test/C/drs/c89_with_c99_functions.c

diff --git a/clang/test/C/drs/c89_with_c99_functions.c 
b/clang/test/C/drs/c89_with_c99_functions.c
new file mode 100644
index 0..d848727001562
--- /dev/null
+++ b/clang/test/C/drs/c89_with_c99_functions.c
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -std=c89 -verify %s
+
+// From: https://github.com/llvm/llvm-project/issues/15522#issue-1071059939
+int logf = 5;
+int main() {
+return logf;
+}

>From 966aa6a735722063d7ea9727e36136f4f39c3d88 Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Wed, 5 Mar 2025 22:09:02 -0500
Subject: [PATCH 2/9] Update test to `expect-no-diagnostics`

---
 clang/test/C/drs/c89_with_c99_functions.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/test/C/drs/c89_with_c99_functions.c 
b/clang/test/C/drs/c89_with_c99_functions.c
index d848727001562..de525313fbba5 100644
--- a/clang/test/C/drs/c89_with_c99_functions.c
+++ b/clang/test/C/drs/c89_with_c99_functions.c
@@ -1,4 +1,5 @@
 // RUN: %clang_cc1 -std=c89 -verify %s
+// expected-no-diagnostics
 
 // From: https://github.com/llvm/llvm-project/issues/15522#issue-1071059939
 int logf = 5;

>From 28c58718d76be9c62635cdeffebc9d812b192e50 Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Wed, 5 Mar 2025 22:13:50 -0500
Subject: [PATCH 3/9] Add exclusion for C89 / math.h functions

---
 clang/lib/Basic/Builtins.cpp | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp
index e7829a461bbc5..cfcbefdce2a24 100644
--- a/clang/lib/Basic/Builtins.cpp
+++ b/clang/lib/Basic/Builtins.cpp
@@ -14,6 +14,7 @@
 #include "BuiltinTargetFeatures.h"
 #include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LangOptions.h"
+#include "clang/Basic/LangStandard.h"
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/ADT/StringRef.h"
 using namespace clang;
@@ -148,7 +149,7 @@ static bool builtinIsSupported(const llvm::StringTable 
&Strings,
   if (!LangOpts.Coroutines && (BuiltinInfo.Langs & COR_LANG))
 return false;
   /* MathBuiltins Unsupported */
-  if (LangOpts.NoMathBuiltin && BuiltinInfo.Header.ID == HeaderDesc::MATH_H)
+  if ((LangOpts.NoMathBuiltin || /*C89*/ LangOpts.LangStd == 
LangStandard::lang_c89)&& BuiltinInfo.Header.ID == HeaderDesc::MATH_H)
 return false;
   /* GnuMode Unsupported */
   if (!LangOpts.GNUMode && (BuiltinInfo.Langs & GNU_LANG))

>From 6e790580b3859cd68ca6ea87c1601979047310ab Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Wed, 5 Mar 2025 22:25:07 -0500
Subject: [PATCH 4/9] clang-format

---
 clang/lib/Basic/Builtins.cpp | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp
index cfcbefdce2a24..81f85bb5454e4 100644
--- a/clang/lib/Basic/Builtins.cpp
+++ b/clang/lib/Basic/Builtins.cpp
@@ -149,7 +149,9 @@ static bool builtinIsSupported(const llvm::StringTable 
&Strings,
   if (!LangOpts.Coroutines && (BuiltinInfo.Langs & COR_LANG))
 return false;
   /* MathBuiltins Unsupported */
-  if ((LangOpts.NoMathBuiltin || /*C89*/ LangOpts.LangStd == 
LangStandard::lang_c89)&& BuiltinInfo.Header.ID == HeaderDesc::MATH_H)
+  if ((LangOpts.NoMathBuiltin ||
+   /*C89*/ LangOpts.LangStd == LangStandard::lang_c89) &&
+  BuiltinInfo.Header.ID == HeaderDesc::MATH_H)
 return false;
   /* GnuMode Unsupported */
   if (!LangOpts.GNUMode && (BuiltinInfo.Langs & GNU_LANG))

>From 160d719b7ed5997d39accb110df873e6200991d4 Mon Sep 17 00:00:00 2001
From: Vinay Deshmukh <32487576+vinay-deshm...@users.noreply.github.com>
Date: Sun, 9 Mar 2025 14:14:37 -0400
Subject: [PATCH 5/9] exclude c99 symbols from builtins when std=c89

---
 clang/lib/Basic/Builtins.cpp  | 20 ++--
 clang/test/C/drs/c89_with_c99_functions.c | 14 ++
 2 files changed, 28 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp
index 81f85bb5454e4..70ea34da1f9e6 100644
--- a/clang/lib/Basic/Builtins.cpp
+++ b/clang/lib/Basic/Builtins.cpp
@@ -17,6 +17,7 @@
 #include "clang/Basic/LangStandard.h"
 #include "clang/Basic/TargetInfo.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/ADT/StringTable.h"
 using namespace clang;
 
 const char *HeaderDesc::getName() const {
@@ -136,6 +137,18 @@ bool Builtin::Context::isBuiltinFunc(llvm::StringRef 
FuncName) {
   return false;
 }
 
+static bool isSymbolAvai

[clang] [alpha.webkit.UncountedCallArgsChecker] Fix a false negative when a call argument is a local variable. (PR #129974)

2025-03-15 Thread Ryosuke Niwa via cfe-commits

rniwa wrote:

On hindsight, the existing code is correct. We're lying on local variable 
checker to check the liveness of a local variable. Call arguments checker was 
just relying on that.

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


[clang-tools-extra] [llvm] [llvm] add support for mustache templating language (PR #105893)

2025-03-15 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `bolt-x86_64-ubuntu-clang` 
running on `bolt-worker` while building `llvm` at step 5 "build-clang-bolt".

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


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

```
Step 5 (build-clang-bolt) failure: build (failure)
...
-- Detecting CXX compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/g++ - skipped
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for include file elf.h
-- Looking for include file elf.h - found
-- Configuring done
-- Generating done
-- Build files have been written to: 
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/build/tools/bolt/bolt_rt-bins
1.055 [2634/2/541] Building CXX object 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o
FAILED: lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o 
ccache /usr/bin/g++ -DGTEST_HAS_RTTI=0 -D_DEBUG -D_GLIBCXX_ASSERTIONS 
-D_GNU_SOURCE -D__STDC_CONSTANT_MACROS -D__STDC_FORMAT_MACROS 
-D__STDC_LIMIT_MACROS 
-I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/build/lib/Support 
-I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support
 -I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/build/include 
-I/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/include 
-fPIC -fno-semantic-interposition -fvisibility-inlines-hidden -Werror=date-time 
-fno-lifetime-dse -Wall -Wextra -Wno-unused-parameter -Wwrite-strings 
-Wcast-qual -Wno-missing-field-initializers -pedantic -Wno-long-long 
-Wimplicit-fallthrough -Wno-uninitialized -Wno-nonnull -Wno-class-memaccess 
-Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type 
-Wdelete-non-virtual-dtor -Wsuggest-override -Wno-comment 
-Wno-misleading-indentation -Wctad-maybe-unsupported -fdiagnostics-color 
-ffunction-sections -fdata-sections -O3 -DNDEBUG -UNDEBUG -std=c++17  
-fno-exceptions -funwind-tables -fno-rtti -MD -MT 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o -MF 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o.d -o 
lib/Support/CMakeFiles/LLVMSupport.dir/Mustache.cpp.o -c 
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:109:12:
 error: declaration of ‘{anonymous}::Accessor llvm::mustache::Token::Accessor’ 
changes meaning of ‘Accessor’ [-fpermissive]
  109 |   Accessor Accessor;
  |^~~~
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:19:7:
 note: ‘Accessor’ declared here as ‘using Accessor = class 
llvm::SmallVector >’
   19 | using Accessor = SmallVector;
  |   ^~~~
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:186:18:
 error: declaration of ‘const Accessor llvm::mustache::ASTNode::Accessor’ 
changes meaning of ‘Accessor’ [-fpermissive]
  186 |   const Accessor Accessor;
  |  ^~~~
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:19:7:
 note: ‘Accessor’ declared here as ‘using Accessor = class 
llvm::SmallVector >’
   19 | using Accessor = SmallVector;
  |   ^~~~
In file included from 
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:8:
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/include/llvm/Support/Mustache.h:
 In constructor 
‘llvm::mustache::Template::Template(llvm::mustache::Template&&)’:
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/include/llvm/Support/Mustache.h:123:12:
 warning: ‘llvm::mustache::Template::Tree’ will be initialized after [-Wreorder]
  123 |   ASTNode *Tree;
  |^~~~
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/include/llvm/Support/Mustache.h:120:26:
 warning:   ‘llvm::BumpPtrAllocator llvm::mustache::Template::AstAllocator’ 
[-Wreorder]
  120 |   llvm::BumpPtrAllocator AstAllocator;
  |  ^~~~
/home/worker/bolt-worker2/bolt-x86_64-ubuntu-clang/llvm-project/llvm/lib/Support/Mustache.cpp:769:1:
 warning:   when initialized here [-Wreorder]
  769 | Template::Template(Template &&Other) noexcept
  | ^~~~
1.385 [2634/1/542] Performing build step for 'bolt_rt'
0.075 [2/2/1] Building CXX object CMakeFiles/bolt_rt_hugify.dir/hugify.cpp.o
0.115 [1/2/2] Linking CXX static library lib/libbolt_rt_hugify.a
0.638 [1/1/3] Building CXX object CMakeFiles/bolt_rt_instr.dir/instr.cpp.o
0.679 [0/1/4] Linking CXX static library lib/libbolt_rt_instr.a
ninja: build stopped: subcommand failed.

```



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

[clang] c84d8e8 - [clang][modules] Introduce new `ModuleCache` interface (#131193)

2025-03-15 Thread via cfe-commits

Author: Jan Svoboda
Date: 2025-03-14T11:32:39-07:00
New Revision: c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d

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

LOG: [clang][modules] Introduce new `ModuleCache` interface (#131193)

This PR adds new `ModuleCache` interface to Clang's implicitly-built
modules machinery. The main motivation for this change is to create a
second implementation that uses a more efficient kind of
`llvm::AdvisoryLock` during dependency scanning.

In addition to the lock abstraction, the `ModuleCache` interface also
manages the existing `InMemoryModuleCache` instance. I found that
compared to keeping these separate/independent, the code is a bit
simpler now, since these are two tightly coupled concepts. I can
envision a more efficient implementation of the `InMemoryModuleCache`
for the single-process case too, which will be much easier to implement
with the current setup.

This is not intended to be a functional change.

Added: 
clang/include/clang/Serialization/ModuleCache.h
clang/lib/Serialization/ModuleCache.cpp

Modified: 
clang-tools-extra/clangd/ModulesBuilder.cpp
clang/include/clang/Frontend/ASTUnit.h
clang/include/clang/Frontend/CompilerInstance.h
clang/include/clang/Serialization/ASTReader.h
clang/include/clang/Serialization/ASTWriter.h
clang/include/clang/Serialization/ModuleManager.h
clang/lib/Frontend/ASTUnit.cpp
clang/lib/Frontend/CompilerInstance.cpp
clang/lib/Frontend/PrecompiledPreamble.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/CMakeLists.txt
clang/lib/Serialization/GeneratePCH.cpp
clang/lib/Serialization/ModuleManager.cpp
clang/unittests/Frontend/FrontendActionTest.cpp
clang/unittests/Lex/HeaderSearchTest.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/ModulesBuilder.cpp 
b/clang-tools-extra/clangd/ModulesBuilder.cpp
index 08a7b250a8119..39cf57f5fe724 100644
--- a/clang-tools-extra/clangd/ModulesBuilder.cpp
+++ b/clang-tools-extra/clangd/ModulesBuilder.cpp
@@ -12,7 +12,7 @@
 #include "clang/Frontend/FrontendAction.h"
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Serialization/ASTReader.h"
-#include "clang/Serialization/InMemoryModuleCache.h"
+#include "clang/Serialization/ModuleCache.h"
 #include "llvm/ADT/ScopeExit.h"
 #include 
 
@@ -206,9 +206,9 @@ bool IsModuleFileUpToDate(PathRef ModuleFilePath,
   Preprocessor PP(std::make_shared(), *Diags, LangOpts,
   SourceMgr, HeaderInfo, ModuleLoader);
 
-  IntrusiveRefCntPtr ModuleCache = new 
InMemoryModuleCache;
+  IntrusiveRefCntPtr ModCache = createCrossProcessModuleCache();
   PCHContainerOperations PCHOperations;
-  ASTReader Reader(PP, *ModuleCache, /*ASTContext=*/nullptr,
+  ASTReader Reader(PP, *ModCache, /*ASTContext=*/nullptr,
PCHOperations.getRawReader(), {});
 
   // We don't need any listener here. By default it will use a validator

diff  --git a/clang/include/clang/Frontend/ASTUnit.h 
b/clang/include/clang/Frontend/ASTUnit.h
index 1f98c6ab328ba..248bbe1657f8b 100644
--- a/clang/include/clang/Frontend/ASTUnit.h
+++ b/clang/include/clang/Frontend/ASTUnit.h
@@ -70,7 +70,7 @@ class FileManager;
 class FrontendAction;
 class HeaderSearch;
 class InputKind;
-class InMemoryModuleCache;
+class ModuleCache;
 class PCHContainerOperations;
 class PCHContainerReader;
 class Preprocessor;
@@ -110,7 +110,7 @@ class ASTUnit {
   IntrusiveRefCntPtr   Diagnostics;
   IntrusiveRefCntPtr FileMgr;
   IntrusiveRefCntPtr   SourceMgr;
-  IntrusiveRefCntPtr ModuleCache;
+  IntrusiveRefCntPtr ModCache;
   std::unique_ptr   HeaderInfo;
   IntrusiveRefCntPtr  Target;
   std::shared_ptr   PP;

diff  --git a/clang/include/clang/Frontend/CompilerInstance.h 
b/clang/include/clang/Frontend/CompilerInstance.h
index 8b539dfc92960..4960d40ca7c37 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -51,8 +51,8 @@ class DiagnosticsEngine;
 class DiagnosticConsumer;
 class FileManager;
 class FrontendAction;
-class InMemoryModuleCache;
 class Module;
+class ModuleCache;
 class Preprocessor;
 class Sema;
 class SourceManager;
@@ -97,7 +97,7 @@ class CompilerInstance : public ModuleLoader {
   IntrusiveRefCntPtr SourceMgr;
 
   /// The cache of PCM files.
-  IntrusiveRefCntPtr ModuleCache;
+  IntrusiveRefCntPtr ModCache;
 
   /// The preprocessor.
   std::shared_ptr PP;
@@ -209,7 +209,7 @@ class CompilerInstance : public ModuleLoader {
   explicit CompilerInstance(
   std::shared_ptr PCHContainerOps =
   std::make_shared(),
-  InMemoryModuleCache *SharedModuleCache = nullptr);
+  ModuleCache *ModCache = nullptr);
 

[clang] [C2y] Implement WG14 N3411 (PR #130180)

2025-03-15 Thread Aaron Ballman via cfe-commits


@@ -3192,23 +3192,22 @@ bool Lexer::LexEndOfFile(Token &Result, const char 
*CurPtr) {
   if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
 DiagnosticsEngine &Diags = PP->getDiagnostics();
 SourceLocation EndLoc = getSourceLocation(BufferEnd);
-unsigned DiagID;
+unsigned DiagID = diag::warn_no_newline_eof;
 
 if (LangOpts.CPlusPlus11) {
   // C++11 [lex.phases] 2.2 p2
   // Prefer the C++98 pedantic compatibility warning over the generic,
   // non-extension, user-requested "missing newline at EOF" warning.
-  if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
+  if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc))
 DiagID = diag::warn_cxx98_compat_no_newline_eof;
-  } else {
-DiagID = diag::warn_no_newline_eof;
-  }
 } else {
-  DiagID = diag::ext_no_newline_eof;
+  // This is conforming in C2y, but is an extension in earlier language
+  // modes.
+  if (!LangOpts.C2y)
+DiagID = diag::ext_no_newline_eof;

AaronBallman wrote:

`-pedantic` exists to diagnose extensions and this is definitively an 
extension. So that's a GCC bug IMO. :-)

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


[clang] [analyzer] Introduce per-entry-point statistics (PR #131175)

2025-03-15 Thread Arseniy Zaostrovnykh via cfe-commits

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

>From 6b6d80d42d40d5917622cbc2bc0f2a454c34eca3 Mon Sep 17 00:00:00 2001
From: Arseniy Zaostrovnykh 
Date: Thu, 13 Mar 2025 18:42:39 +0100
Subject: [PATCH 01/11] [analyzer] Introduce per-entry-point statistics
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

So far CSA was relying on the LLVM Statistic package that allowed us to
gather some data about analysis of an entire translation unit. However,
the translation unit consists of a collection of loosely related entry
points. Aggregating data across multiple such entry points is often
counter productive.

This change introduces a new lightweight always-on facility to collect
Boolean or numerical statistics for each entry point and dump them in a
CSV format. Such format makes it easy to aggregate data across multiple
translation units and analyze it with common data-processing tools.

We break down the existing statistics that were collected on the per-TU
basis into values per entry point.

Additionally, we enable the statistics unconditionally (STATISTIC ->
ALWAYS_ENABLED_STATISTIC) to facilitate their use (you can gather the
data with a simple run-time flag rather than having to recompile the
analyzer). These statistics are very light and add virtually no
overhead.

@steakhal (Balázs Benics) started this design and I picked over the baton.

---
CPP-6160
---
 clang/docs/analyzer/developer-docs.rst|   1 +
 .../analyzer/developer-docs/Statistics.rst|  21 ++
 .../StaticAnalyzer/Core/AnalyzerOptions.def   |   6 +
 .../Core/PathSensitive/EntryPointStats.h  | 162 ++
 .../Checkers/AnalyzerStatsChecker.cpp |   9 +-
 clang/lib/StaticAnalyzer/Core/BugReporter.cpp |  28 +--
 clang/lib/StaticAnalyzer/Core/CMakeLists.txt  |   1 +
 clang/lib/StaticAnalyzer/Core/CoreEngine.cpp  |  16 +-
 .../StaticAnalyzer/Core/EntryPointStats.cpp   | 201 ++
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp  |  24 ++-
 .../Core/ExprEngineCallAndReturn.cpp  |  14 +-
 clang/lib/StaticAnalyzer/Core/WorkList.cpp|  10 +-
 .../Core/Z3CrosscheckVisitor.cpp  |  31 +--
 .../Frontend/AnalysisConsumer.cpp |  62 --
 clang/test/Analysis/analyzer-config.c |   1 +
 clang/test/Analysis/csv2json.py   |  98 +
 clang/test/lit.cfg.py |  10 +
 17 files changed, 617 insertions(+), 78 deletions(-)
 create mode 100644 clang/docs/analyzer/developer-docs/Statistics.rst
 create mode 100644 
clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h
 create mode 100644 clang/lib/StaticAnalyzer/Core/EntryPointStats.cpp
 create mode 100644 clang/test/Analysis/csv2json.py

diff --git a/clang/docs/analyzer/developer-docs.rst 
b/clang/docs/analyzer/developer-docs.rst
index 60c0e71ad847c..a925cf7ca02e1 100644
--- a/clang/docs/analyzer/developer-docs.rst
+++ b/clang/docs/analyzer/developer-docs.rst
@@ -12,3 +12,4 @@ Contents:
developer-docs/nullability
developer-docs/RegionStore
developer-docs/PerformanceInvestigation
+   developer-docs/Statistics
diff --git a/clang/docs/analyzer/developer-docs/Statistics.rst 
b/clang/docs/analyzer/developer-docs/Statistics.rst
new file mode 100644
index 0..d352bb6f01ebc
--- /dev/null
+++ b/clang/docs/analyzer/developer-docs/Statistics.rst
@@ -0,0 +1,21 @@
+==
+Metrics and Statistics
+==
+
+TODO: write this once the design is settled (@reviewer, don't look here yet)
+
+CSA enjoys two facilities to collect statistics per translation unit and per 
entry point.
+
+Mention the following tools:
+- STATISTIC macro
+- ALLWAYS_ENABLED_STATISTIC macro
+
+- STAT_COUNTER macro
+- STAT_MAX macro
+
+- BoolEPStat
+- UnsignedEPStat
+- CounterEPStat
+- UnsignedMaxEPStat
+
+- dump-se-metrics-to-csv="%t.csv"
diff --git a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def 
b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
index 2aa00db411844..b88bce5e262a7 100644
--- a/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
+++ b/clang/include/clang/StaticAnalyzer/Core/AnalyzerOptions.def
@@ -353,6 +353,12 @@ ANALYZER_OPTION(bool, DisplayCTUProgress, 
"display-ctu-progress",
 "the analyzer's progress related to ctu.",
 false)
 
+ANALYZER_OPTION(
+StringRef, DumpSEStatsToCSV, "dump-se-stats-to-csv",
+"If provided, the analyzer will dump statistics per entry point "
+"into the specified CSV file.",
+"")
+
 ANALYZER_OPTION(bool, ShouldTrackConditions, "track-conditions",
 "Whether to track conditions that are a control dependency of "
 "an already tracked variable.",
diff --git 
a/clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h 
b/clang/include/clang/StaticAnalyzer/Core/PathSensitive/EntryPointStats.h
new file mode 100644
index 0..16c

[clang] [OffloadBundler] Expose function to parse compressed bundle headers (PR #130284)

2025-03-15 Thread Juan Manuel Martinez Caamaño via cfe-commits

https://github.com/jmmartinez updated 
https://github.com/llvm/llvm-project/pull/130284

From 27adc9ef08bf2ac98319885fb461975f37a98bc2 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Juan=20Manuel=20Martinez=20Caama=C3=B1o?= 
Date: Fri, 7 Mar 2025 12:29:31 +0100
Subject: [PATCH 1/2] [OffloadBundler] Expose API to parse compressed bundle
 headers

In COMGR we hash the header of compressed bundles. For this we take the
first bytes of the buffer (according to the maximum header size) and
hash them.

To have a more stable API, and to be able to pick only the hash field (which is
the only one we are actually interested in) of the header, we propose
a version independant header version that is common to all versions.
---
 clang/include/clang/Driver/OffloadBundler.h |  50 ++
 clang/lib/Driver/OffloadBundler.cpp | 178 +---
 2 files changed, 127 insertions(+), 101 deletions(-)

diff --git a/clang/include/clang/Driver/OffloadBundler.h 
b/clang/include/clang/Driver/OffloadBundler.h
index 31c11e25ecd9f..2b5bf710f80b1 100644
--- a/clang/include/clang/Driver/OffloadBundler.h
+++ b/clang/include/clang/Driver/OffloadBundler.h
@@ -107,50 +107,20 @@ struct OffloadTargetInfo {
 // - Compressed Data (variable length).
 class CompressedOffloadBundle {
 private:
-  static inline const size_t MagicSize = 4;
-  static inline const size_t VersionFieldSize = sizeof(uint16_t);
-  static inline const size_t MethodFieldSize = sizeof(uint16_t);
-  // Legacy size fields for V1/V2
-  static inline const size_t FileSizeFieldSizeV2 = sizeof(uint32_t);
-  static inline const size_t UncompressedSizeFieldSizeV2 = sizeof(uint32_t);
-  // New size fields for V3
-  static inline const size_t FileSizeFieldSizeV3 = sizeof(uint64_t);
-  static inline const size_t UncompressedSizeFieldSizeV3 = sizeof(uint64_t);
-  static inline const size_t HashFieldSize = sizeof(uint64_t);
-
-  // Keep V1 header size for backward compatibility
-  static inline const size_t V1HeaderSize =
-  MagicSize + VersionFieldSize + MethodFieldSize +
-  UncompressedSizeFieldSizeV2 + HashFieldSize;
-
-  // Keep V2 header size for backward compatibility
-  static inline const size_t V2HeaderSize =
-  MagicSize + VersionFieldSize + FileSizeFieldSizeV2 + MethodFieldSize +
-  UncompressedSizeFieldSizeV2 + HashFieldSize;
-
-  // Add V3 header size with 64-bit fields
-  static inline const size_t V3HeaderSize =
-  MagicSize + VersionFieldSize + FileSizeFieldSizeV3 + MethodFieldSize +
-  UncompressedSizeFieldSizeV3 + HashFieldSize;
-
   static inline const llvm::StringRef MagicNumber = "CCOB";
 
 public:
-  static inline const uint16_t DefaultVersion = 2;
+  struct CompressedBundleHeader {
+unsigned Version;
+llvm::compression::Format CompressionFormat;
+std::optional FileSize;
+size_t UncompressedFileSize;
+uint64_t Hash;
 
-  // Helper method to get header size based on version
-  static size_t getHeaderSize(uint16_t Version) {
-switch (Version) {
-case 1:
-  return V1HeaderSize;
-case 2:
-  return V2HeaderSize;
-case 3:
-  return V3HeaderSize;
-default:
-  llvm_unreachable("Unsupported version");
-}
-  }
+static llvm::Expected tryParse(llvm::StringRef);
+  };
+
+  static inline const uint16_t DefaultVersion = 2;
 
   static llvm::Expected>
   compress(llvm::compression::Params P, const llvm::MemoryBuffer &Input,
diff --git a/clang/lib/Driver/OffloadBundler.cpp 
b/clang/lib/Driver/OffloadBundler.cpp
index 12d763e5c65b6..6a6adc277f032 100644
--- a/clang/lib/Driver/OffloadBundler.cpp
+++ b/clang/lib/Driver/OffloadBundler.cpp
@@ -29,6 +29,7 @@
 #include "llvm/Object/Binary.h"
 #include "llvm/Object/ObjectFile.h"
 #include "llvm/Support/Casting.h"
+#include "llvm/Support/Compiler.h"
 #include "llvm/Support/Compression.h"
 #include "llvm/Support/Debug.h"
 #include "llvm/Support/EndianStream.h"
@@ -1121,13 +1122,116 @@ 
CompressedOffloadBundle::compress(llvm::compression::Params P,
   llvm::StringRef(FinalBuffer.data(), FinalBuffer.size()));
 }
 
+// Use packed structs to avoid padding, such that the structs map the 
serialized
+// format.
+LLVM_PACKED_START
+union RawCompressedBundleHeader {
+  struct CommonFields {
+uint32_t Magic;
+uint16_t Version;
+uint16_t Method;
+  };
+
+  struct V1Header {
+CommonFields Common;
+uint32_t UncompressedFileSize;
+uint64_t Hash;
+  };
+
+  struct V2Header {
+CommonFields Common;
+uint32_t FileSize;
+uint32_t UncompressedFileSize;
+uint64_t Hash;
+  };
+
+  struct V3Header {
+CommonFields Common;
+uint64_t FileSize;
+uint64_t UncompressedFileSize;
+uint64_t Hash;
+  };
+
+  CommonFields Common;
+  V1Header V1;
+  V2Header V2;
+  V3Header V3;
+};
+LLVM_PACKED_END
+
+// Helper method to get header size based on version
+static size_t getHeaderSize(uint16_t Version) {
+  switch (Version) {
+  case 1:
+return sizeof(RawCompressedBundleHeader::V1Header);
+  case 2:
+return sizeof(R

[clang] [clang] Avoid doing C++20 aggregate init during copy-initialization (PR #131320)

2025-03-15 Thread via cfe-commits


@@ -6714,7 +6714,8 @@ void InitializationSequence::InitializeFrom(Sema &S,
 OverloadCandidateSet::iterator Best;
 OverloadingResult OR = getFailedCandidateSet().BestViableFunction(
 S, Kind.getLocation(), Best);
-if (OR != OverloadingResult::OR_Deleted) {
+if (OR != OverloadingResult::OR_Deleted &&
+Kind.getKind() == InitializationKind::IK_Direct) {

cor3ntin wrote:

Presumably, this is https://eel.is/c++draft/dcl.init.general#16.6.2.sentence-1
Why do you think copy should not be valid here?

Afaik, the core issue @frederick-vs-ja mentioned here, 
https://github.com/llvm/llvm-project/issues/88089#issuecomment-2044223386, only 
applies to the array case. 


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


[clang] [CIR] Upstream initial support for CIR flattening (PR #130648)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -0,0 +1,77 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+// This file implements lowering of CIR attributes and operations directly to
+// LLVMIR.
+//
+//===--===//
+
+#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
+#include "mlir/IR/DialectRegistry.h"
+#include "mlir/Target/LLVMIR/LLVMTranslationInterface.h"
+#include "mlir/Target/LLVMIR/ModuleTranslation.h"
+#include "clang/CIR/Dialect/IR/CIRAttrs.h"
+#include "clang/CIR/Dialect/IR/CIRDialect.h"
+#include "clang/CIR/MissingFeatures.h"
+#include "llvm/ADT/ArrayRef.h"
+#include "llvm/IR/Constant.h"
+#include "llvm/IR/GlobalVariable.h"
+
+using namespace llvm;
+
+namespace cir {
+namespace direct {
+
+/// Implementation of the dialect interface that converts CIR attributes to 
LLVM
+/// IR metadata.
+class CIRDialectLLVMIRTranslationInterface
+: public mlir::LLVMTranslationDialectInterface {
+public:
+  using LLVMTranslationDialectInterface::LLVMTranslationDialectInterface;
+#if 0

erichkeane wrote:

Oh?  Can we just remove this and add it when we need it?

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


[clang] [clang] Add value_type attr, use it to add noalias when pass-by-value. (PR #95004)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -9242,3 +9242,15 @@ Declares that a function potentially allocates heap 
memory, and prevents any pot
 of ``nonallocating`` by the compiler.
   }];
 }
+
+def ValueTypeDocs : Documentation {
+  let Category = DocCatDecl;
+  let Content = [{
+The ``value_type`` attribute can be used to mark user-defined types as 'value
+types'. When objects of value types are passed value to functions, the objects
+are always considered to be formally copied into a new object. This means the
+argument itself must be the only value referencing the passed object. This
+allows the optimizer to assume that no other pointers may alias the object when
+it is passed indirectly to a function..

erichkeane wrote:

```suggestion
it is passed indirectly to a function.
```

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


[clang] [clang][bytecode] Fix builtin_memcmp buffer sizes for pointers (PR #130570)

2025-03-15 Thread Timm Baeder via cfe-commits


@@ -0,0 +1,120 @@
+// RUN: %clang_cc1 -std=c++2c -fexperimental-new-constant-interpreter 
-verify=expected,both %s
+// RUN: %clang_cc1 -std=c++2c  -verify=ref,both %s
+
+// both-no-diagnostics
+
+namespace std {
+inline namespace {

tbaederr wrote:

Just a reduced test case. Anything special about this line?

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Morris Hafner via cfe-commits


@@ -568,6 +568,128 @@ mlir::LogicalResult 
CIRToLLVMGlobalOpLowering::matchAndRewrite(
   return mlir::success();
 }
 
+mlir::LogicalResult CIRToLLVMUnaryOpLowering::matchAndRewrite(
+cir::UnaryOp op, OpAdaptor adaptor,
+mlir::ConversionPatternRewriter &rewriter) const {
+  assert(op.getType() == op.getInput().getType() &&
+ "Unary operation's operand type and result type are different");
+  mlir::Type type = op.getType();
+  mlir::Type elementType = type;
+  bool isVector = false;
+  assert(!cir::MissingFeatures::vectorType());
+  mlir::Type llvmType = getTypeConverter()->convertType(type);
+  mlir::Location loc = op.getLoc();
+
+  auto createIntConstant = [&](int64_t value) -> mlir::Value {

mmha wrote:

I just had to create a boolean constant. I don't think this will be the last 
instance of that, so maybe having utility functions for some fundamental types 
is a good idea.

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


[clang] [llvm] [Support] Return `LockFileManager` errors right away (PR #130627)

2025-03-15 Thread Ben Langmuir via cfe-commits


@@ -248,39 +236,14 @@ LockFileManager::LockFileManager(StringRef FileName)
 
 // There is a lock file that nobody owns; try to clean it up and get
 // ownership.
-if ((EC = sys::fs::remove(LockFileName))) {
-  std::string S("failed to remove lockfile ");
-  S.append(std::string(UniqueLockFileName));
-  setError(EC, S);
-  return;
-}
-  }
-}
-
-LockFileManager::LockFileState LockFileManager::getState() const {
-  if (Owner)
-return LFS_Shared;
-
-  if (ErrorCode)
-return LFS_Error;
-
-  return LFS_Owned;
-}
-
-std::string LockFileManager::getErrorMessage() const {
-  if (ErrorCode) {
-std::string Str(ErrorDiagMsg);
-std::string ErrCodeMsg = ErrorCode.message();
-raw_string_ostream OSS(Str);
-if (!ErrCodeMsg.empty())
-  OSS << ": " << ErrCodeMsg;
-return Str;
+if ((EC = sys::fs::remove(LockFileName)))
+  return createStringError(EC, "failed to remove lockfile " +
+   UniqueLockFileName);
   }
-  return "";
 }
 
 LockFileManager::~LockFileManager() {
-  if (getState() != LFS_Owned)
+  if (Owner)

benlangmuir wrote:

I don't think we have enough information to know whether we own the lock or not 
here anymore. All `if (Owner)` tells us is if we know that someone else owns 
it.  We need to additionally consider tryLock was never called or it failed 
part way.

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


[clang] [llvm] Reapply "Use global TimerGroups for both new pass manager and old pass manager timers" (#131173) (PR #131217)

2025-03-15 Thread Alan Zhao via cfe-commits

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


[clang] [Clang] Fix segmentation fault caused by `VarBypassDetector` stack overflow on deeply nested expressions (PR #124128)

2025-03-15 Thread Boaz Brickner via cfe-commits

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


[clang-tools-extra] [clang-tidy][NFC]clean ConstCorrectnessCheck (PR #130493)

2025-03-15 Thread Piotr Zegar via cfe-commits

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


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


[clang] [llvm] [analysis] Software Bill of Mitigations (PR #130103)

2025-03-15 Thread Matthew Levy via cfe-commits

https://github.com/matthewlevy97 updated 
https://github.com/llvm/llvm-project/pull/130103

>From fb04b7bf5f2b668bf354632fc53e7521f44880c9 Mon Sep 17 00:00:00 2001
From: Matt Levy 
Date: Wed, 5 Mar 2025 12:36:02 -0500
Subject: [PATCH 1/5] [clang][CodeGen] Software Bill of Mitigations Metadata

The goal of this stack is to create a high fidelity mapping of mitigations to 
their possible insertion points and their actual insertion points. This would 
let us track where we do and don't have mitigations rather than the current 
approach of tracking where we have the flag.

There are some challenges posed by this like:
- Some mitigations are not emitted by the compiler, but the preprocessor
- Some mitigations are lowered later during IR -> MIR (stack cookies)
---
 clang/include/clang/Basic/CodeGenOptions.def |  1 +
 clang/include/clang/Driver/Options.td|  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp  | 10 +++
 clang/lib/CodeGen/CGClass.cpp|  3 +
 clang/lib/CodeGen/CGDecl.cpp |  4 +
 clang/lib/CodeGen/CGExpr.cpp |  5 ++
 clang/lib/CodeGen/CGExprCXX.cpp  |  6 ++
 clang/lib/CodeGen/CMakeLists.txt |  1 +
 clang/lib/CodeGen/CodeGenModule.cpp  | 22 +
 clang/lib/CodeGen/MitigationTagging.cpp  | 84 
 clang/lib/CodeGen/MitigationTagging.h| 45 +++
 clang/lib/Driver/ToolChains/Clang.cpp|  3 +
 12 files changed, 190 insertions(+)
 create mode 100644 clang/lib/CodeGen/MitigationTagging.cpp
 create mode 100644 clang/lib/CodeGen/MitigationTagging.h

diff --git a/clang/include/clang/Basic/CodeGenOptions.def 
b/clang/include/clang/Basic/CodeGenOptions.def
index a7f5f1abbb825..76a46ac3e592b 100644
--- a/clang/include/clang/Basic/CodeGenOptions.def
+++ b/clang/include/clang/Basic/CodeGenOptions.def
@@ -191,6 +191,7 @@ CODEGENOPT(NoTypeCheck   , 1, 0) ///< Set when 
-Wa,--no-type-check is enable
 CODEGENOPT(MisExpect , 1, 0) ///< Set when -Wmisexpect is enabled
 CODEGENOPT(EnableSegmentedStacks , 1, 0) ///< Set when -fsplit-stack is 
enabled.
 CODEGENOPT(StackClashProtector, 1, 0) ///< Set when -fstack-clash-protection 
is enabled.
+CODEGENOPT(MitigationAnalysis, 1, 0) ///< Set when -fmitigation-analysis is 
enabled.
 CODEGENOPT(NoImplicitFloat   , 1, 0) ///< Set when -mno-implicit-float is 
enabled.
 CODEGENOPT(NullPointerIsValid , 1, 0) ///< Assume Null pointer deference is 
defined.
 CODEGENOPT(OpenCLCorrectlyRoundedDivSqrt, 1, 0) ///< 
-cl-fp32-correctly-rounded-divide-sqrt
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index d0414aba35209..e50bb5c1c2cb4 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3891,6 +3891,12 @@ defm split_stack : BoolFOption<"split-stack",
   CodeGenOpts<"EnableSegmentedStacks">, DefaultFalse,
   NegFlag,
   PosFlag>;
+defm mitigation_analysis : BoolFOption<"mitigation-analysis",
+  CodeGenOpts<"MitigationAnalysis">, DefaultFalse,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption], " mitigation analysis">>,
+  DocBrief<"Instrument mitigations (CFI, Stack Protectors, Auto-Var-Init, 
StackClashProtection) to analyze their coverage">;
 def fstack_protector_all : Flag<["-"], "fstack-protector-all">, Group,
   HelpText<"Enable stack protectors for all functions">;
 defm stack_clash_protection : BoolFOption<"stack-clash-protection",
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index ab8f19b25fa66..4e180bb1a87cf 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -21,6 +21,7 @@
 #include "CodeGenFunction.h"
 #include "CodeGenModule.h"
 #include "ConstantEmitter.h"
+#include "MitigationTagging.h"
 #include "PatternInit.h"
 #include "TargetInfo.h"
 #include "clang/AST/ASTContext.h"
@@ -83,6 +84,8 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst 
*AI, Value *Size,
   switch (CGF.getLangOpts().getTrivialAutoVarInit()) {
   case LangOptions::TrivialAutoVarInitKind::Uninitialized:
 // Nothing to initialize.
+AttachMitigationMetadataToFunction(CGF, MitigationKey::AUTO_VAR_INIT,
+   false);
 return;
   case LangOptions::TrivialAutoVarInitKind::Zero:
 Byte = CGF.Builder.getInt8(0x00);
@@ -94,6 +97,7 @@ static void initializeAlloca(CodeGenFunction &CGF, AllocaInst 
*AI, Value *Size,
 break;
   }
   }
+  AttachMitigationMetadataToFunction(CGF, MitigationKey::AUTO_VAR_INIT, true);
   if (CGF.CGM.stopAutoInit())
 return;
   auto *I = CGF.Builder.CreateMemSet(AI, Byte, Size, AlignmentInBytes);
@@ -4642,6 +4646,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
 AI->setAlignment(SuitableAlignmentInBytes);
 if (BuiltinID != Builtin::BI__builtin_alloca_uninitialized)
   initializeAlloca(*this, AI, Size, SuitableAlignmentInBytes);
+else
+  AttachMitigationMetadataToFunction(*t

[clang] [AstMatcher]`templateArgumentCountIs` support `FunctionDecl` (PR #130416)

2025-03-15 Thread Congcong Cai via cfe-commits

https://github.com/HerrCai0907 updated 
https://github.com/llvm/llvm-project/pull/130416

>From b28bd17fd58c6f41b3d860cb490cdbfeef8b8c3e Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Sat, 8 Mar 2025 21:33:02 +0800
Subject: [PATCH] [AstMatcher]`templateArgumentCountIs` support `FunctionDecl`

`hasTemplateArgument` and `templateArgumentCountIs` are always used together. 
It is more convenient to make then support `FunctionDecl`.
---
 clang/include/clang/ASTMatchers/ASTMatchers.h | 1 +
 1 file changed, 1 insertion(+)

diff --git a/clang/include/clang/ASTMatchers/ASTMatchers.h 
b/clang/include/clang/ASTMatchers/ASTMatchers.h
index 0f7e3a8a01762..03d522072f6c1 100644
--- a/clang/include/clang/ASTMatchers/ASTMatchers.h
+++ b/clang/include/clang/ASTMatchers/ASTMatchers.h
@@ -1090,6 +1090,7 @@ AST_POLYMORPHIC_MATCHER_P2(
 AST_POLYMORPHIC_MATCHER_P(
 templateArgumentCountIs,
 AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl,
+VarTemplateSpecializationDecl, 
FunctionDecl,
 TemplateSpecializationType),
 unsigned, N) {
   return internal::getTemplateSpecializationArgs(Node).size() == N;

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


[clang] [llvm] [ARM][Clang] Make `+nosimd` functional for AArch32 Targets (PR #130623)

2025-03-15 Thread Jonathan Thackray via cfe-commits


@@ -85,6 +85,9 @@ Changes to the AMDGPU Backend
 
 Changes to the ARM Backend
 --
+* The `+nosimd` attribute is now fully supported. Previously, this had no 
effect when being used with
+AArch32 targets, however will now disable NEON instructions being generated. 
The `simd` is also now

jthackray wrote:

```suggestion
AArch32 targets, however this will now disable NEON instructions being 
generated. The `simd` option is also now
```

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


[clang] [Clang] Treat `ext_vector_type` as a regular type attribute (PR #130177)

2025-03-15 Thread Erich Keane via cfe-commits

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


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


[clang] [llvm] [ARM][Clang] Make `+nosimd` functional for AArch32 Targets (PR #130623)

2025-03-15 Thread David Green via cfe-commits


@@ -334,8 +334,8 @@ ARM_CPU_NAME("cortex-r7", ARMV7R, FK_VFPV3_D16_FP16, false,
  (ARM::AEK_MP | ARM::AEK_HWDIVARM))
 ARM_CPU_NAME("cortex-r8", ARMV7R, FK_VFPV3_D16_FP16, false,
  (ARM::AEK_MP | ARM::AEK_HWDIVARM))
-ARM_CPU_NAME("cortex-r52", ARMV8R, FK_NEON_FP_ARMV8, false, ARM::AEK_NONE)
-ARM_CPU_NAME("cortex-r52plus", ARMV8R, FK_NEON_FP_ARMV8, false, ARM::AEK_NONE)
+ARM_CPU_NAME("cortex-r52", ARMV8R, FK_NEON_FP_ARMV8, false, ARM::AEK_SIMD)
+ARM_CPU_NAME("cortex-r52plus", ARMV8R, FK_NEON_FP_ARMV8, false, ARM::AEK_SIMD)

davemgreen wrote:

I think I would have expected neon vs non-neon to come from the fpu option / 
default, under Arm. We (essentially) default to -mfpu=auto but it can get quite 
complex with all the different ways of specifying it.

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


[clang-tools-extra] [clangd] Use `SymbolName` to represent Objective-C selectors (PR #82061)

2025-03-15 Thread David Goldman via cfe-commits

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

Thanks for the fix! Looks good besides some minor nits.

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


[clang] [Clang] [Tests] Add some more tests around non-local/non-variable declarations in C for loops (PR #131199)

2025-03-15 Thread via cfe-commits

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


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


[clang] [clang-tools-extra] [clang][modules] Introduce new `ModuleCache` interface (PR #131193)

2025-03-15 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder `lldb-arm-ubuntu` running 
on `linaro-lldb-arm-ubuntu` while building `clang-tools-extra,clang` at step 6 
"test".

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


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

```
Step 6 (test) failure: build (failure)
...
PASS: lldb-api :: tools/lldb-dap/exception/cpp/TestDAP_exception_cpp.py (1155 
of 2920)
UNSUPPORTED: lldb-api :: 
tools/lldb-dap/extendedStackTrace/TestDAP_extendedStackTrace.py (1156 of 2920)
PASS: lldb-api :: tools/lldb-dap/disconnect/TestDAP_disconnect.py (1157 of 2920)
PASS: lldb-api :: 
tools/lldb-dap/instruction-breakpoint/TestDAP_instruction_breakpoint.py (1158 
of 2920)
PASS: lldb-api :: tools/lldb-dap/io/TestDAP_io.py (1159 of 2920)
PASS: lldb-api :: tools/lldb-dap/locations/TestDAP_locations.py (1160 of 2920)
PASS: lldb-api :: tools/lldb-dap/memory/TestDAP_memory.py (1161 of 2920)
PASS: lldb-api :: tools/lldb-dap/evaluate/TestDAP_evaluate.py (1162 of 2920)
PASS: lldb-api :: tools/lldb-dap/module/TestDAP_module.py (1163 of 2920)
PASS: lldb-api :: tools/lldb-dap/output/TestDAP_output.py (1164 of 2920)
FAIL: lldb-api :: tools/lldb-dap/launch/TestDAP_launch.py (1165 of 2920)
 TEST 'lldb-api :: tools/lldb-dap/launch/TestDAP_launch.py' 
FAILED 
Script:
--
/usr/bin/python3.10 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/dotest.py 
-u CXXFLAGS -u CFLAGS --env 
LLVM_LIBS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib --env 
LLVM_INCLUDE_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/include --env 
LLVM_TOOLS_DIR=/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --arch 
armv8l --build-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex 
--lldb-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-lldb/lldb-api
 --clang-module-cache-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/lldb-test-build.noindex/module-cache-clang/lldb-api
 --executable /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/lldb 
--compiler /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/clang 
--dsymutil /home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin/dsymutil 
--make /usr/bin/gmake --llvm-tools-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./bin --lldb-obj-root 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/tools/lldb --lldb-libs-dir 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/build/./lib 
/home/tcwg-buildbot/worker/lldb-arm-ubuntu/llvm-project/lldb/test/API/tools/lldb-dap/launch
 -p TestDAP_launch.py
--
Exit Code: 1

Command Output (stdout):
--
lldb version 21.0.0git (https://github.com/llvm/llvm-project.git revision 
c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d)
  clang revision c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d
  llvm revision c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d
Skipping the following test categories: ['libc++', 'dsym', 'gmodules', 
'debugserver', 'objc']
= DEBUG ADAPTER PROTOCOL LOGS =
1741979330.845331192 <-- (stdin/stdout) 
{"command":"initialize","type":"request","arguments":{"adapterID":"lldb-native","clientID":"vscode","columnsStartAt1":true,"linesStartAt1":true,"locale":"en-us","pathFormat":"path","supportsRunInTerminalRequest":true,"supportsVariablePaging":true,"supportsVariableType":true,"supportsStartDebuggingRequest":true,"sourceInitFile":false},"seq":1}
1741979330.847774267 --> (stdin/stdout) {"body":{"__lldb":{"version":"lldb 
version 21.0.0git (https://github.com/llvm/llvm-project.git revision 
c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d)\n  clang revision 
c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d\n  llvm revision 
c84d8e8f1c406ab34d56efd4a9f8c5fbce70af2d"},"completionTriggerCharacters":["."," 
","\t"],"exceptionBreakpointFilters":[{"default":false,"filter":"cpp_catch","label":"C++
 Catch"},{"default":false,"filter":"cpp_throw","label":"C++ 
Throw"},{"default":false,"filter":"objc_catch","label":"Objective-C 
Catch"},{"default":false,"filter":"objc_throw","label":"Objective-C 
Throw"}],"supportTerminateDebuggee":true,"supportsBreakpointLocationsRequest":true,"supportsCompletionsRequest":true,"supportsConditionalBreakpoints":true,"supportsConfigurationDoneRequest":true,"supportsDataBreakpoints":true,"supportsDelayedStackTraceLoading":true,"supportsDisassembleRequest":true,"supportsEvaluateForHovers":true,"supportsExceptionInfoRequest":true,"supportsExceptionOptions":true,"supportsFunctionBreakpoints":true,"supportsGotoTargetsRequest":false,"supportsHitConditionalBreakpoints":true,"supportsInstructionBreakpoints":true,"supportsLoadedSourcesRequest":false,"supportsLogPoints":true,"supportsModulesRequest":true,"supportsProgressReporting":true,"supportsReadMemoryRequest":true,"supportsRestartFrame":false,"supportsRestartRequest":true,"supportsRunInTerminalRequest":true,"supportsSetVariable":true,"supportsStepBack":false,"suppor

[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -468,6 +468,55 @@ def BrOp : CIR_Op<"br",
   }];
 }
 
+//===--===//
+// UnaryOp
+//===--===//
+
+def UnaryOpKind_Inc   : I32EnumAttrCase<"Inc",   1, "inc">;
+def UnaryOpKind_Dec   : I32EnumAttrCase<"Dec",   2, "dec">;
+def UnaryOpKind_Plus  : I32EnumAttrCase<"Plus",  3, "plus">;
+def UnaryOpKind_Minus : I32EnumAttrCase<"Minus", 4, "minus">;
+def UnaryOpKind_Not   : I32EnumAttrCase<"Not",   5, "not">;
+
+def UnaryOpKind : I32EnumAttr<
+"UnaryOpKind",
+"unary operation kind",
+[UnaryOpKind_Inc,
+ UnaryOpKind_Dec,
+ UnaryOpKind_Plus,
+ UnaryOpKind_Minus,
+ UnaryOpKind_Not,
+ ]> {
+  let cppNamespace = "::cir";
+}
+
+// FIXME: Pure won't work when we add overloading.

erichkeane wrote:

Would love to see the answer for this from @lanza  and @bcardosolopes 

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


[clang] [clang-format] Fix a bug in wrapping function return type (PR #129374)

2025-03-15 Thread Owen Pan via cfe-commits


@@ -5091,8 +5091,10 @@ UnwrappedLineParser::parseMacroCall() {
 void UnwrappedLineParser::pushToken(FormatToken *Tok) {
   Line->Tokens.push_back(UnwrappedLineNode(Tok));
   if (MustBreakBeforeNextToken) {

owenca wrote:

I renamed it to 
[`AtEndOfPPLine`](https://github.com/owenca/llvm-project/blob/a6ccda28f7569c1a03620d7520de7cfadc11f4a5/clang/lib/Format/UnwrappedLineParser.h#L304)
 instead.

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


[clang] [clang-tools-extra] [clang] improve class type sugar preservation in pointers to members (PR #130537)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -3524,14 +3524,16 @@ class MemberPointerType : public Type, public 
llvm::FoldingSetNode {
   QualType PointeeType;
 
   /// The class of which the pointee is a member. Must ultimately be a
-  /// RecordType, but could be a typedef or a template parameter too.
-  const Type *Class;
+  /// CXXRecordType, but could be a typedef or a template parameter too.
+  NestedNameSpecifier *Qualifier;

erichkeane wrote:

`Qualifier` is perhaps a bad choice of name here.  We use it too much to mean 
`cvr` qualifiers that using it here is distracting/confusing.  I'll note that 
`Class` was not a great name either though  

MAYBE something like `ObjectSpecifier` or something?  BUT completely open to 
bikeshedding.

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Andy Kaylor via cfe-commits


@@ -0,0 +1,392 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir 
-Wno-unused-value -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir 
-Wno-unused-value -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s --check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s --check-prefix=OGCG

andykaylor wrote:

Well, you know, I needed some abbreviation, and this seemed as good as anything 
else in addition to being fun.

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


[clang] [sanitizer][CFI] Add support to build CFI with sanitize-coverage (PR #131296)

2025-03-15 Thread Vitaly Buka via cfe-commits

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


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


[clang] [clang] Add value_type attr, use it to add noalias when pass-by-value. (PR #95004)

2025-03-15 Thread Florian Hahn via cfe-commits

fhahn wrote:

Just rebased the PR and 
> > I feel like this is a property that needs to propagate through types
> 
> You mean, similar to the way trivial_abi works? That makes sense.

I am not sure about propagating. I added some documentation to make the spec of 
the attribute clearer. 

Specifically, it requires the objects of the type to be considered copied into 
new objects when passing to functions, i.e. code using the type isn't allowed 
to rely on previous pointers to the actual object e.g. via copy elision or NRVO.

Similarly, I think the guarantees are also different to `trivial_abi`, as there 
could be other pointers to the same object even if it is trivial via copy 
elision or NRVO. There's a thread where this problem in general has been 
discussed extensively a while ago 
https://lists.llvm.org/pipermail/cfe-dev/2020-July/066357.html


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


[clang] [Clang] Force expressions with UO_Not to not be non-negative (PR #126846)

2025-03-15 Thread Jan Patrick Lehr via cfe-commits

jplehr wrote:

> Hi, I think this broke two of our buildbots -- for reasons I don't quite 
> understand, but reverting fixed the issue locally. Can you please take a look 
> at it?
> 
> https://lab.llvm.org/buildbot/#/builders/10/builds/980 
> https://lab.llvm.org/buildbot/#/builders/73/builds/14304

I realized that `libc` compiles with `-Werror` and it appears that ours are the 
only libc bots that are affected.
So, I guess, the issue is on our end. Thank you.

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


[clang] [clang] Fix darwin-related tests' REQUIRES annotation (PR #130138)

2025-03-15 Thread Simon Tatham via cfe-commits

https://github.com/statham-arm commented:

I've done as much of the review as I can. The syntax in the `REQUIRES` lines 
looks sensible to me, and I see why _most_ of these tests would depend on clang 
being configured to target its host Darwin platform by default:
* `apple-arm64-arch.c`, `compilation_database_multiarch.c`, 
`darwin-ld-platform-version-macos-requires-darwin.c` and 
`xros-driver-requires-darwin-host.c` specifically check for `apple` or `macos` 
in the compiler output without having provided one in the input command line, 
so it makes sense that they wouldn't behave like that if clang's host was 
Darwin but its default target was something else.

I'm less sure I understand `mtargetos-darwin.c`, because I don't know what 
`-mtargetos=...` means. I guess that's supposed to be a modification to the 
_detail_ of the OS component of the target triple, and doesn't have the side 
effect of setting it to  Darwin in the first place?

And I know I don't understand what `pch-from-libclang.c` has to do with Darwin 
host _or_ target, but the FIXME in the comment suggests that nobody else knows 
that either, so perhaps that doesn't block the commit.

Can you confirm my understanding of `-mtargetos`?

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


[clang] Warn about virtual methods in `final` classes (PR #131188)

2025-03-15 Thread Hans Wennborg via cfe-commits

zmodem wrote:

> What do you think about implementing the suggestion about checking if virtual 
> methods actually get overridden or not?

Since we could only do it for classes with internal linkage, I think it's 
probably not very valuable.

Warning about virtual functions that are not overriding anything and cannot be 
overridden because `final` seems high value though.

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


[clang] [alpha.webkit.UncountedCallArgsChecker] os_log functions should be treated as safe. (PR #131500)

2025-03-15 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/131500

…os_log functions should be treated as safe in call arguments checkers.

Also treat __builtin_* functions and __libcpp_verbose_abort functions as 
"trivial" for the purpose in call argument checkers.

>From 38660deefa24a6014d60c63428b45006d18a1488 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 15 Mar 2025 23:02:55 -0700
Subject: [PATCH] [alpha.webkit.UncountedCallArgsChecker] os_log functions
 should be treated as safe.

os_log functions should be treated as safe in call arguments checkers.

Also treat __builtin_* functions and __libcpp_verbose_abort functions as 
"trivial"
for the purpose in call argument checkers.
---
 .../Checkers/WebKit/PtrTypesSemantics.cpp | 11 +--
 .../Checkers/WebKit/PtrTypesSemantics.h   |  3 +++
 .../Checkers/WebKit/RawPtrRefCallArgsChecker.cpp  |  3 +++
 .../Analysis/Checkers/WebKit/mock-system-header.h |  2 +-
 .../Analysis/Checkers/WebKit/uncounted-obj-arg.cpp|  6 +-
 5 files changed, 21 insertions(+), 4 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index bfa58a11c6199..8724ff3c15acc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -424,6 +424,14 @@ bool isPtrConversion(const FunctionDecl *F) {
   return false;
 }
 
+bool isTrivialBuiltinFunction(const FunctionDecl *F) {
+  if (!F)
+return false;
+  auto Name = F->getName();
+  return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" ||
+ Name.starts_with("os_log") || Name.starts_with("_os_log");
+}
+
 bool isSingleton(const FunctionDecl *F) {
   assert(F);
   // FIXME: check # of params == 1
@@ -601,8 +609,7 @@ class TrivialFunctionAnalysisVisitor
 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
 Name == "isWebThread" || Name == "isUIThread" ||
 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
-Name == "bitwise_cast" || Name.find("__builtin") == 0 ||
-Name == "__libcpp_verbose_abort")
+Name == "bitwise_cast" || isTrivialBuiltinFunction(Callee))
   return true;
 
 return IsFunctionTrivial(Callee);
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 60bfd1a8dd480..096675fb912f2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -142,6 +142,9 @@ std::optional isGetterOfSafePtr(const 
clang::CXXMethodDecl *Method);
 /// pointer types.
 bool isPtrConversion(const FunctionDecl *F);
 
+/// \returns true if \p F is a builtin function which is considered trivial.
+bool isTrivialBuiltinFunction(const FunctionDecl *F);
+
 /// \returns true if \p F is a static singleton function.
 bool isSingleton(const FunctionDecl *F);
 
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
index d59d03f110776..39e9cd023d1f7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
@@ -246,6 +246,9 @@ class RawPtrRefCallArgsChecker
 if (Callee && TFA.isTrivial(Callee) && !Callee->isVirtualAsWritten())
   return true;
 
+if (isTrivialBuiltinFunction(Callee))
+  return true;
+
 if (CE->getNumArgs() == 0)
   return false;
 
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-system-header.h 
b/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
index 73d6e3dbf4643..e993fd697ffab 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
@@ -28,4 +28,4 @@ enum os_log_type_t : uint8_t {
 
 typedef struct os_log_s *os_log_t;
 os_log_t os_log_create(const char *subsystem, const char *category);
-void os_log_msg(os_log_t oslog, os_log_type_t type, const char *msg);
+void os_log_msg(os_log_t oslog, os_log_type_t type, const char *msg, ...);
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index 0279e2c68ec6d..69842264af56b 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -695,9 +695,13 @@ RefPtr object();
 void someFunction(const RefCounted&);
 
 void test2() {
-someFunction(*object());
+  someFunction(*object());
 }
 
 void system_header() {
   callMethod(object);
 }
+
+void log(RefCountable* obj) {
+  os_log_msg(os_log_create("WebKit", "DOM"), OS_LOG_TYPE_INFO, "obj: %p next: 
%p", obj, obj->next());
+}
\ No newline at end of file


[clang] Skip more WebKit checker tests on targets where builtin is not supported. (PR #131501)

2025-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes



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


2 Files Affected:

- (modified) 
clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm (+1) 
- (modified) clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm 
(+1) 


``diff
diff --git 
a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
index 99f488b578910..dd7208a534ea1 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -fobjc-arc -verify %s
 
 #include "objc-mock-types.h"
diff --git a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
index 111342bc0e388..79e0bdb7c577b 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -verify %s
 
 #include "objc-mock-types.h"

``




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


[clang] Skip more WebKit checker tests on targets where builtin is not supported. (PR #131501)

2025-03-15 Thread Ryosuke Niwa via cfe-commits

https://github.com/rniwa created 
https://github.com/llvm/llvm-project/pull/131501

None

>From a03593710d4c39b484490573d257162742c83ca1 Mon Sep 17 00:00:00 2001
From: Ryosuke Niwa 
Date: Sat, 15 Mar 2025 23:11:03 -0700
Subject: [PATCH] Skip more WebKit checker tests on targets where builtin is
 not supported.

---
 .../Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm| 1 +
 clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm | 1 +
 2 files changed, 2 insertions(+)

diff --git 
a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
index 99f488b578910..dd7208a534ea1 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -fobjc-arc -verify %s
 
 #include "objc-mock-types.h"
diff --git a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
index 111342bc0e388..79e0bdb7c577b 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -verify %s
 
 #include "objc-mock-types.h"

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


[clang] [clang] Fix UEFI Target info (PR #127290)

2025-03-15 Thread Tristan Ross via cfe-commits

RossComputerGuy wrote:

Alright, if it does fix it then we should get this moving so libc pre-commits 
working with UEFI isn't blocked.

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


[clang] 0689d23 - [C++20][Modules] Prevent premature calls to PassInterestingDeclsToConsumer() within FinishedDeserializing(). (#129982)

2025-03-15 Thread via cfe-commits

Author: Michael Park
Date: 2025-03-15T23:03:20-07:00
New Revision: 0689d23ab3089eb9920b8f5caa92e423fe3475f8

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

LOG: [C++20][Modules] Prevent premature calls to 
PassInterestingDeclsToConsumer() within FinishedDeserializing(). (#129982)

`ASTReader::FinishedDeserializing` uses `NumCurrentElementsDeserializing` to 
keep track of nested `Deserializing` RAII actions. The `FinishedDeserializing` 
only performs actions if it is the top-level `Deserializing` layer. This works 
fine in general, but there is a problematic edge case.

If a call to `redecls()` in `FinishedDeserializing` performs deserialization, 
we re-enter `FinishedDeserializing` while in the middle of the previous 
`FinishedDeserializing` call.

The known problematic part of this is that this inner `FinishedDeserializing` 
can go all the way to `PassInterestingDeclsToConsumer`, which operates on 
`PotentiallyInterestingDecls` data structure which contain decls that should be 
handled by the previous `FinishedDeserializing` stage.

The other shared data structures are also somewhat concerning at a high-level 
in that the inner `FinishedDeserializing` would be handling pending actions 
that are not "within its scope", but this part is not known to be problematic.

We already have a guard within `PassInterestingDeclsToConsumer` because we can 
end up with recursive deserialization within `PassInterestingDeclsToConsumer`. 
The implemented solution is to apply this guard to the portion of 
`FinishedDeserializing` that performs further deserialization as well. This 
ensures that recursive deserialization does not trigger 
`PassInterestingDeclsToConsumer` which may operate on entries that are not 
ready to be passed.

Added: 
clang/test/Modules/pr121245.cpp
clang/test/Modules/pr129982.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Serialization/ASTReader.h
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 07b8214246901..2a1c5ee2d788e 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -278,6 +278,9 @@ Bug Fixes in This Version
   considered an error in C23 mode and are allowed as an extension in earlier 
language modes.
 
 - Remove the ``static`` specifier for the value of ``_FUNCTION_`` for static 
functions, in MSVC compatibility mode.
+- Fixed a modules crash where exception specifications were not propagated 
properly (#GH121245, relanded in #GH129982)
+- Fixed a problematic case with recursive deserialization within 
``FinishedDeserializing()`` where
+  ``PassInterestingDeclsToConsumer()`` was called before the declarations were 
safe to be passed. (#GH129982)
 
 Bug Fixes to Compiler Builtins
 ^^

diff  --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index 143b798a8348a..2779b3d1cf2ea 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -1176,11 +1176,11 @@ class ASTReader
   /// Number of Decl/types that are currently deserializing.
   unsigned NumCurrentElementsDeserializing = 0;
 
-  /// Set true while we are in the process of passing deserialized
-  /// "interesting" decls to consumer inside FinishedDeserializing().
-  /// This is used as a guard to avoid recursively repeating the process of
+  /// Set false while we are in a state where we cannot safely pass 
deserialized
+  /// "interesting" decls to the consumer inside FinishedDeserializing().
+  /// This is used as a guard to avoid recursively entering the process of
   /// passing decls to consumer.
-  bool PassingDeclsToConsumer = false;
+  bool CanPassDeclsToConsumer = true;
 
   /// The set of identifiers that were read while the AST reader was
   /// (recursively) loading declarations.

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index 8e9978829c512..2c73501821bff 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -10182,12 +10182,12 @@ void ASTReader::visitTopLevelModuleMaps(
 }
 
 void ASTReader::finishPendingActions() {
-  while (
-  !PendingIdentifierInfos.empty() || !PendingDeducedFunctionTypes.empty() 
||
-  !PendingDeducedVarTypes.empty() || !PendingIncompleteDeclChains.empty() 
||
-  !PendingDeclChains.empty() || !PendingMacroIDs.empty() ||
-  !PendingDeclContextInfos.empty() || !PendingUpdateRecords.empty() ||
-  !PendingObjCExtensionIvarRedeclarations.empty()) {
+  while (!PendingIdentifierInfos.empty() ||
+ !PendingDeducedFunctionTypes.empty() ||
+ !P

[clang] [C++20][Modules] Prevent premature calls to PassInterestingDeclsToConsumer() within FinishedDeserializing(). (PR #129982)

2025-03-15 Thread Michael Park via cfe-commits

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


[clang] f4043f4 - Skip more WebKit checker tests on targets where builtin is not supported. (#131501)

2025-03-15 Thread via cfe-commits

Author: Ryosuke Niwa
Date: 2025-03-15T23:39:30-07:00
New Revision: f4043f451d0e8c30c8a9826ce87a6e76f3ace468

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

LOG: Skip more WebKit checker tests on targets where builtin is not supported. 
(#131501)

Added: 


Modified: 
clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm

Removed: 




diff  --git 
a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
index 99f488b578910..dd7208a534ea1 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use-arc.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -fobjc-arc -verify %s
 
 #include "objc-mock-types.h"

diff  --git a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm 
b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
index 111342bc0e388..79e0bdb7c577b 100644
--- a/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
+++ b/clang/test/Analysis/Checkers/WebKit/retain-ptr-ctor-adopt-use.mm
@@ -1,3 +1,4 @@
+// UNSUPPORTED: target={{.*}}-zos{{.*}}, target={{.*}}-aix{{.*}}
 // RUN: %clang_analyze_cc1 
-analyzer-checker=alpha.webkit.RetainPtrCtorAdoptChecker -verify %s
 
 #include "objc-mock-types.h"



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


[clang] Skip more WebKit checker tests on targets where builtin is not supported. (PR #131501)

2025-03-15 Thread Ryosuke Niwa via cfe-commits

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


[clang] [alpha.webkit.UncountedCallArgsChecker] os_log functions should be treated as safe. (PR #131500)

2025-03-15 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ryosuke Niwa (rniwa)


Changes

…os_log functions should be treated as safe in call arguments checkers.

Also treat __builtin_* functions and __libcpp_verbose_abort functions as 
"trivial" for the purpose in call argument checkers.

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


5 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
(+9-2) 
- (modified) clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h (+3) 
- (modified) 
clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp (+3) 
- (modified) clang/test/Analysis/Checkers/WebKit/mock-system-header.h (+1-1) 
- (modified) clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp (+5-1) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
index bfa58a11c6199..8724ff3c15acc 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.cpp
@@ -424,6 +424,14 @@ bool isPtrConversion(const FunctionDecl *F) {
   return false;
 }
 
+bool isTrivialBuiltinFunction(const FunctionDecl *F) {
+  if (!F)
+return false;
+  auto Name = F->getName();
+  return Name.starts_with("__builtin") || Name == "__libcpp_verbose_abort" ||
+ Name.starts_with("os_log") || Name.starts_with("_os_log");
+}
+
 bool isSingleton(const FunctionDecl *F) {
   assert(F);
   // FIXME: check # of params == 1
@@ -601,8 +609,7 @@ class TrivialFunctionAnalysisVisitor
 Name == "isMainThreadOrGCThread" || Name == "isMainRunLoop" ||
 Name == "isWebThread" || Name == "isUIThread" ||
 Name == "mayBeGCThread" || Name == "compilerFenceForCrash" ||
-Name == "bitwise_cast" || Name.find("__builtin") == 0 ||
-Name == "__libcpp_verbose_abort")
+Name == "bitwise_cast" || isTrivialBuiltinFunction(Callee))
   return true;
 
 return IsFunctionTrivial(Callee);
diff --git a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
index 60bfd1a8dd480..096675fb912f2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/PtrTypesSemantics.h
@@ -142,6 +142,9 @@ std::optional isGetterOfSafePtr(const 
clang::CXXMethodDecl *Method);
 /// pointer types.
 bool isPtrConversion(const FunctionDecl *F);
 
+/// \returns true if \p F is a builtin function which is considered trivial.
+bool isTrivialBuiltinFunction(const FunctionDecl *F);
+
 /// \returns true if \p F is a static singleton function.
 bool isSingleton(const FunctionDecl *F);
 
diff --git 
a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
index d59d03f110776..39e9cd023d1f7 100644
--- a/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/WebKit/RawPtrRefCallArgsChecker.cpp
@@ -246,6 +246,9 @@ class RawPtrRefCallArgsChecker
 if (Callee && TFA.isTrivial(Callee) && !Callee->isVirtualAsWritten())
   return true;
 
+if (isTrivialBuiltinFunction(Callee))
+  return true;
+
 if (CE->getNumArgs() == 0)
   return false;
 
diff --git a/clang/test/Analysis/Checkers/WebKit/mock-system-header.h 
b/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
index 73d6e3dbf4643..e993fd697ffab 100644
--- a/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
+++ b/clang/test/Analysis/Checkers/WebKit/mock-system-header.h
@@ -28,4 +28,4 @@ enum os_log_type_t : uint8_t {
 
 typedef struct os_log_s *os_log_t;
 os_log_t os_log_create(const char *subsystem, const char *category);
-void os_log_msg(os_log_t oslog, os_log_type_t type, const char *msg);
+void os_log_msg(os_log_t oslog, os_log_type_t type, const char *msg, ...);
diff --git a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp 
b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
index 0279e2c68ec6d..69842264af56b 100644
--- a/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
+++ b/clang/test/Analysis/Checkers/WebKit/uncounted-obj-arg.cpp
@@ -695,9 +695,13 @@ RefPtr object();
 void someFunction(const RefCounted&);
 
 void test2() {
-someFunction(*object());
+  someFunction(*object());
 }
 
 void system_header() {
   callMethod(object);
 }
+
+void log(RefCountable* obj) {
+  os_log_msg(os_log_create("WebKit", "DOM"), OS_LOG_TYPE_INFO, "obj: %p next: 
%p", obj, obj->next());
+}
\ No newline at end of file

``




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


[clang] [clang] Fix UEFI Target info (PR #127290)

2025-03-15 Thread via cfe-commits

Prabhuk wrote:

> Would this unblock #131376?

I believe it will. @petrhosek can you PTAL?

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


[clang-tools-extra] [clang-tidy] offer option to check sugared types in avoid-c-arrays check (PR #131468)

2025-03-15 Thread via cfe-commits

stmuench wrote:

> Release notes entry missing.
> 
> Now, to be honest I do not like idea behind those changes. Simply because if 
> diagnostic is raised for example for an surrogate type, there is no way to 
> apply fixes, and as this check is "modernize", main purpose of it is to apply 
> fixes.
> 
> Personally I run into situation in my code base where this check is too 
> aggressive and should be relaxed.
> 
> Example:
> 
> ```
> #include 
> 
> template > void f(T &&value) {}
> 
> void test() {
>   int t[10];
>   f(t);
> }
> ```
> 
> ```
> /root/1.cpp:3:50: warning: do not declare C-style arrays, use 'std::array' 
> instead 
> [cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays]
> 3 | template > void f(T 
> &&value) {}
>   |  ^
> /root/1.cpp:6:3: warning: do not declare C-style arrays, use 'std::array' 
> instead 
> [cppcoreguidelines-avoid-c-arrays,hicpp-avoid-c-arrays,modernize-avoid-c-arrays]
> 6 |   int t[10];
>   |   ^
> ```
> 
> In above code check is executed in template instance even that 
> TK_IgnoreUnlessSpelledInSource is set. With your change it will be even worst.
> 
> Thing is that if check would properly handled implicit code then "template 
> parameters" would never be catch. At the end check should point places in 
> code where actually arrays are defined, otherwise if you would put array into 
> type alias, then you would get warning in every place that type alias is 
> used, and that's stupid as there is only one place where such array can be 
> fixed, and that is a definition of that type alias.
> 
> Due to above I do not like this change.

Many thanks for your prompt review and pointing out the flaws in my 
implementation. I fully agree that solely for modernization, this new setting 
in conjunction with the increased amount of diagnostics would not make sense. 
And that's why it's disabled by default and people would have to opt-in 
explicitly.
The main intention of this new mode was to help people recognize usages of 
C-style arrays in their code even where it's not clear immediately, e.g. when 
using types from externel headers. This would be very helpful when you are 
working in a project where the use of C-style arrays is discouraged or not even 
allowed.
Don't you think that this would be a helpful enhancement then?

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Andy Kaylor via cfe-commits

https://github.com/andykaylor created 
https://github.com/llvm/llvm-project/pull/131369

This adds support for the cir.unary operation.

>From d51bb762224f70b2b879198e2466ca0d258f9eae Mon Sep 17 00:00:00 2001
From: Andy Kaylor 
Date: Mon, 10 Mar 2025 15:07:50 -0700
Subject: [PATCH] [CIR] Upstream initial support for unary op

This adds support for the cir.unary operation.
---
 clang/include/clang/CIR/Dialect/IR/CIROps.td  |  49 +++
 clang/include/clang/CIR/MissingFeatures.h |   9 +
 clang/lib/CIR/CodeGen/CIRGenExpr.cpp  |  48 +++
 clang/lib/CIR/CodeGen/CIRGenExprScalar.cpp| 223 ++
 clang/lib/CIR/CodeGen/CIRGenFunction.cpp  |   2 +
 clang/lib/CIR/CodeGen/CIRGenFunction.h|   4 +
 clang/lib/CIR/CodeGen/CIRGenValue.h   |   1 +
 clang/lib/CIR/Dialect/IR/CIRDialect.cpp   |  41 ++
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.cpp | 125 +-
 .../CIR/Lowering/DirectToLLVM/LowerToLLVM.h   |  10 +
 clang/test/CIR/CodeGen/unary.cpp  | 392 ++
 11 files changed, 903 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CIR/CodeGen/unary.cpp

diff --git a/clang/include/clang/CIR/Dialect/IR/CIROps.td 
b/clang/include/clang/CIR/Dialect/IR/CIROps.td
index 77c43e5ace64a..52c78ffe42647 100644
--- a/clang/include/clang/CIR/Dialect/IR/CIROps.td
+++ b/clang/include/clang/CIR/Dialect/IR/CIROps.td
@@ -468,6 +468,55 @@ def BrOp : CIR_Op<"br",
   }];
 }
 
+//===--===//
+// UnaryOp
+//===--===//
+
+def UnaryOpKind_Inc   : I32EnumAttrCase<"Inc",   1, "inc">;
+def UnaryOpKind_Dec   : I32EnumAttrCase<"Dec",   2, "dec">;
+def UnaryOpKind_Plus  : I32EnumAttrCase<"Plus",  3, "plus">;
+def UnaryOpKind_Minus : I32EnumAttrCase<"Minus", 4, "minus">;
+def UnaryOpKind_Not   : I32EnumAttrCase<"Not",   5, "not">;
+
+def UnaryOpKind : I32EnumAttr<
+"UnaryOpKind",
+"unary operation kind",
+[UnaryOpKind_Inc,
+ UnaryOpKind_Dec,
+ UnaryOpKind_Plus,
+ UnaryOpKind_Minus,
+ UnaryOpKind_Not,
+ ]> {
+  let cppNamespace = "::cir";
+}
+
+// FIXME: Pure won't work when we add overloading.
+def UnaryOp : CIR_Op<"unary", [Pure, SameOperandsAndResultType]> {
+  let summary = "Unary operations";
+  let description = [{
+`cir.unary` performs the unary operation according to
+the specified opcode kind: [inc, dec, plus, minus, not].
+
+It requires one input operand and has one result, both types
+should be the same.
+
+```mlir
+%7 = cir.unary(inc, %1) : i32 -> i32
+%8 = cir.unary(dec, %2) : i32 -> i32
+```
+  }];
+
+  let results = (outs CIR_AnyType:$result);
+  let arguments = (ins Arg:$kind, 
Arg:$input);
+
+  let assemblyFormat = [{
+  `(` $kind `,` $input `)` `:` type($input) `,` type($result) attr-dict
+  }];
+
+  let hasVerifier = 1;
+  let hasFolder = 1;
+}
+
 
//===--===//
 // GlobalOp
 
//===--===//
diff --git a/clang/include/clang/CIR/MissingFeatures.h 
b/clang/include/clang/CIR/MissingFeatures.h
index 6c3d74cf96c64..fcbb2ae3db6aa 100644
--- a/clang/include/clang/CIR/MissingFeatures.h
+++ b/clang/include/clang/CIR/MissingFeatures.h
@@ -72,6 +72,10 @@ struct MissingFeatures {
   static bool opFuncLinkage() { return false; }
   static bool opFuncVisibility() { return false; }
 
+  // Unary operator handling
+  static bool opUnarySignedOverflow() { return false; }
+  static bool opUnaryPromotionType() { return false; }
+
   // Misc
   static bool scalarConversionOpts() { return false; }
   static bool tryEmitAsConstant() { return false; }
@@ -86,6 +90,11 @@ struct MissingFeatures {
   static bool aggValueSlot() { return false; }
 
   static bool unsizedTypes() { return false; }
+  static bool sanitizers() { return false; }
+  static bool CGFPOptionsRAII() { return false; }
+
+  // Missing types
+  static bool vectorType() { return false; }
 };
 
 } // namespace cir
diff --git a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp 
b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
index 5b81fe172e645..24c0c8a18efd8 100644
--- a/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenExpr.cpp
@@ -165,6 +165,54 @@ LValue CIRGenFunction::emitDeclRefLValue(const DeclRefExpr 
*e) {
   return LValue();
 }
 
+LValue CIRGenFunction::emitUnaryOpLValue(const UnaryOperator *e) {
+  UnaryOperatorKind op = e->getOpcode();
+
+  // __extension__ doesn't affect lvalue-ness.
+  if (op == UO_Extension)
+return emitLValue(e->getSubExpr());
+
+  switch (op) {
+  case UO_Deref: {
+cgm.errorNYI(e->getSourceRange(), "UnaryOp dereference");
+return LValue();
+  }
+  case UO_Real:
+  case UO_Imag: {
+cgm.errorNYI(e->getSourceRange(), "UnaryOp real/imag");
+return LValue();
+  }
+  case UO_PreInc:
+  case UO_PreDec: {
+bool isInc = e->isIncrementOp();
+LVa

[clang] [clang][CIR] Add missing dependency on MLIR headers (PR #131057)

2025-03-15 Thread via cfe-commits

https://github.com/darkbuck updated 
https://github.com/llvm/llvm-project/pull/131057

>From 255050e6d1e3ebbf25b30c17a10be14d29e5dae7 Mon Sep 17 00:00:00 2001
From: Michael Liao 
Date: Tue, 4 Mar 2025 12:47:24 -0500
Subject: [PATCH] [clang][CIR] Add missing dependency on MLIR headers

- Add dependency on MLIRBuiltinOpsIncGen as
  "clang/CIR/FrontendAction/CIRGenAction.h" needs to include
  "mlir/IR/BuiltinOps.h"
---
 clang/lib/CIR/FrontendAction/CMakeLists.txt | 1 +
 clang/lib/FrontendTool/CMakeLists.txt   | 3 +++
 2 files changed, 4 insertions(+)

diff --git a/clang/lib/CIR/FrontendAction/CMakeLists.txt 
b/clang/lib/CIR/FrontendAction/CMakeLists.txt
index 6d5a8758468f6..1ebac07f44662 100644
--- a/clang/lib/CIR/FrontendAction/CMakeLists.txt
+++ b/clang/lib/CIR/FrontendAction/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangCIRFrontendAction
   DEPENDS
   MLIRCIROpsIncGen
   MLIRCIROpInterfacesIncGen
+  MLIRBuiltinOpsIncGen
 
   LINK_LIBS
   clangAST
diff --git a/clang/lib/FrontendTool/CMakeLists.txt 
b/clang/lib/FrontendTool/CMakeLists.txt
index d7a3699361f0a..7c83086a7da3b 100644
--- a/clang/lib/FrontendTool/CMakeLists.txt
+++ b/clang/lib/FrontendTool/CMakeLists.txt
@@ -15,6 +15,9 @@ set(link_libs
 set(deps)
 
 if(CLANG_ENABLE_CIR)
+  list(APPEND deps
+MLIRBuiltinOpsIncGen
+  )
   list(APPEND link_libs
 clangCIRFrontendAction
 MLIRIR

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


[clang] [clang] Fix inaccurate wording of warn_second_arg_of_va_start_not_last_named_param (PR #131238)

2025-03-15 Thread Aaron Ballman via cfe-commits

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

LGTM!

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


[clang] [clang][docs] Reflect the implementation status for P2280R4 (PR #127166)

2025-03-15 Thread A. Jiang via cfe-commits

frederick-vs-ja wrote:

Oh, there seem to be a few remaning bugs. Now I've added some FIXME comments to 
the most related test files. @Endilll 

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


[clang] cbbcc3d - [C2y] Claim conformance to WG14 N3460 (#131196)

2025-03-15 Thread via cfe-commits

Author: Aaron Ballman
Date: 2025-03-14T12:37:07-04:00
New Revision: cbbcc3d13b7747be4587e36ddc0699587ff31904

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

LOG: [C2y] Claim conformance to WG14 N3460 (#131196)

This moves some Annex G requirements for complex numbers into the main
body of the standard.

Added: 
clang/test/C/C2y/n3460.c
clang/test/C/C2y/n3460_1.c

Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/test/C/C2y/n3460.c b/clang/test/C/C2y/n3460.c
new file mode 100644
index 0..e21c60b418721
--- /dev/null
+++ b/clang/test/C/C2y/n3460.c
@@ -0,0 +1,51 @@
+// RUN: %clang_cc1 -verify -std=c2y -Wall %s
+
+/* WG14 N3460: Clang 12
+ * Complex operators
+ *
+ * This moves some Annex G requirements into the main body of the standard.
+ */
+
+// CMPLX(0.0, inf) * 2.0, the result should be CMPLX(0.0, inf), not CMPLX(nan, 
inf)
+static_assert(__builtin_complex(0.0, __builtin_inf()) * 2.0 ==
+  __builtin_complex(0.0, __builtin_inf()));
+
+// CMPLX(0.0, 1.0) * -0.0 is CMPLX(-0.0, -0.0), not CMPLX(-0.0, +0.0)
+static_assert(__builtin_complex(0.0, 1.0) * -0.0 ==
+  __builtin_complex(-0.0, -0.0));
+
+// Testing for -0.0 is a pain because -0.0 == +0.0, so forcefully generate a
+// diagnostic and check the note.
+static_assert(__builtin_complex(0.0, 1.0) * -0.0 == 1); /* expected-error 
{{static assertion failed due to requirement '__builtin_complex(0., 1.) * -0. 
== 1'}} \
+   expected-note 
{{expression evaluates to '(-0 + -0i) == 1'}}
+ */
+
+// CMPLX(0.0, inf) / 2.0, the result should be CMPLX(0.0, inf),
+// not CMPLX(nan, inf)
+static_assert(__builtin_complex(0.0, __builtin_inf()) / 2.0 ==
+  __builtin_complex(0.0, __builtin_inf()));
+
+// CMPLX(2.0, 3.0) * 2.0, the result should be CMPLX(4.0, 6.0)
+static_assert(__builtin_complex(2.0, 3.0) * 2.0 ==
+  __builtin_complex(4.0, 6.0));
+
+// CMPLX(2.0, 4.0) / 2.0, the result should be CMPLX(1.0, 2.0)
+static_assert(__builtin_complex(2.0, 4.0) / 2.0 ==
+  __builtin_complex(1.0, 2.0));
+
+// CMPLX(2.0, 3.0) * CMPLX(4.0, 5.0), the result should be
+// CMPLX(8.0 - 15.0, 12.0 + 10.0)
+static_assert(__builtin_complex(2.0, 3.0) * __builtin_complex(4.0, 5.0) ==
+  __builtin_complex(-7.0, 22.0));
+
+// CMPLX(2.0, 3.0) / CMPLX(4.0, 5.0), the result should be
+// CMPLX((8.0 + 15.0)/(4.0^2 + 5.0^2), (12.0 - 10.0)/(4.0^2 + 5.0^2))
+static_assert(__builtin_complex(2.0, 3.0) / __builtin_complex(4.0, 5.0) ==
+  __builtin_complex(23.0 / 41.0, 2.0 / 41.0));
+
+
+// 2.0 / CMPLX(2.0, 4.0), the result should be
+// CMPLX(4.0 /(2.0^2 + 4.0^2), -8.0/(2.0^2 + 4.0^2))
+static_assert(2.0 / __builtin_complex(2.0, 4.0) ==
+  __builtin_complex(4.0 / 20.0, -8.0 / 20.0));
+

diff  --git a/clang/test/C/C2y/n3460_1.c b/clang/test/C/C2y/n3460_1.c
new file mode 100644
index 0..2d50b3c23dae8
--- /dev/null
+++ b/clang/test/C/C2y/n3460_1.c
@@ -0,0 +1,80 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 5
+// RUN: %clang_cc1 -std=c2y -O0 -triple x86_64-unknown-unknown %s -emit-llvm 
-o - | FileCheck %s
+// This tests the codegen for the same test cases as in n3460.c.
+
+// CHECK-LABEL: define dso_local void @test(
+// CHECK-SAME: ) #[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  [[ENTRY:.*]]:
+// CHECK-NEXT:[[A:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[B:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[C:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[D:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[E:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[F:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[G:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[H:%.*]] = alloca { double, double }, align 8
+// CHECK-NEXT:[[A_REALP:%.*]] = getelementptr inbounds nuw { double, 
double }, ptr [[A]], i32 0, i32 0
+// CHECK-NEXT:[[A_IMAGP:%.*]] = getelementptr inbounds nuw { double, 
double }, ptr [[A]], i32 0, i32 1
+// CHECK-NEXT:store double 0.00e+00, ptr [[A_REALP]], align 8
+// CHECK-NEXT:store double 0x7FF0, ptr [[A_IMAGP]], align 8
+// CHECK-NEXT:[[B_REALP:%.*]] = getelementptr inbounds nuw { double, 
double }, ptr [[B]], i32 0, i32 0
+// CHECK-NEXT:[[B_IMAGP:%.*]] = getelementptr inbounds nuw { double, 
double }, ptr [[B]], i32 0, i32 1
+// CHECK-NEXT:store double -0.00e+00, ptr [[B_REALP]], align 8
+// CHECK-NEXT:store double -0.00e+00, ptr [[B_IMAGP]], align 8
+// CHECK-NEXT:[[C_REALP:%.*]] = getelementptr inboun

[clang] Warn about virtual methods in `final` classes (PR #131188)

2025-03-15 Thread Devon Loehr via cfe-commits

DKLoehr wrote:

Changed to not warn on `virtual...override`. I'm inclined to agree that it 
doesn't seem worth the effort to extend this to things that aren't actually 
overridden in practice.

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -468,6 +468,55 @@ def BrOp : CIR_Op<"br",
   }];
 }
 
+//===--===//
+// UnaryOp
+//===--===//
+
+def UnaryOpKind_Inc   : I32EnumAttrCase<"Inc",   1, "inc">;
+def UnaryOpKind_Dec   : I32EnumAttrCase<"Dec",   2, "dec">;
+def UnaryOpKind_Plus  : I32EnumAttrCase<"Plus",  3, "plus">;
+def UnaryOpKind_Minus : I32EnumAttrCase<"Minus", 4, "minus">;
+def UnaryOpKind_Not   : I32EnumAttrCase<"Not",   5, "not">;
+
+def UnaryOpKind : I32EnumAttr<
+"UnaryOpKind",
+"unary operation kind",
+[UnaryOpKind_Inc,
+ UnaryOpKind_Dec,
+ UnaryOpKind_Plus,
+ UnaryOpKind_Minus,
+ UnaryOpKind_Not,
+ ]> {
+  let cppNamespace = "::cir";
+}
+
+// FIXME: Pure won't work when we add overloading.

erichkeane wrote:

Does this mean operator overloading?  If so, why would we model that as unary 
operator?  In the CFE those get modeled as function calls, so do we intended to 
flatten that?

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


[clang] f3effc2 - [C2y] Claim conformance to N3347

2025-03-15 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2025-03-06T16:21:40-05:00
New Revision: f3effc24004a99c6167680a66b1f95bde3c268f4

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

LOG: [C2y] Claim conformance to N3347

This paper made it a constraint violation to have a tentative
definition with internal linkage which is not completed by the end of
the translation unit.

This has been diagnosed as an error since at least Clang 3.0, so no
changes are needed.

Added: 
clang/test/C/C2y/n3347.c

Modified: 
clang/www/c_status.html

Removed: 




diff  --git a/clang/test/C/C2y/n3347.c b/clang/test/C/C2y/n3347.c
new file mode 100644
index 0..ed816f3941725
--- /dev/null
+++ b/clang/test/C/C2y/n3347.c
@@ -0,0 +1,23 @@
+// RUN: %clang_cc1 -verify -std=c2y -Wall -pedantic %s
+
+/* WG14 N3347: Yes
+ * Slay Some Earthly Demons IX
+ *
+ * Declarations of a tentative definition with internal linkage must be
+ * complete by the end of the translation unit.
+ */
+
+struct foo; // #foo
+static struct foo f1; /* expected-warning {{tentative definition of variable 
with internal linkage has incomplete non-array type 'struct foo'}}
+ expected-error {{tentative definition has type 
'struct foo' that is never completed}}
+ expected-note@#foo 2 {{forward declaration of 'struct 
foo'}}
+   */
+
+extern struct foo f2; // Ok, does not have internal linkage
+
+struct bar; // #bar
+static struct bar b; /* expected-warning {{tentative definition of variable 
with internal linkage has incomplete non-array type 'struct bar'}}
+expected-note@#bar {{forward declaration of 'struct 
bar'}}
+  */
+struct bar { int x; };
+

diff  --git a/clang/www/c_status.html b/clang/www/c_status.html
index 41643f6d13913..4e912987b69c6 100644
--- a/clang/www/c_status.html
+++ b/clang/www/c_status.html
@@ -258,7 +258,7 @@ C2y implementation status
 
   Slay Some Earthly Demons IX
   https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3347.pdf";>N3347
-  Unknown
+  Yes

 
   stdarg.h wording... v3



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


[clang] [llvm] [RISCV] Add Zilsd and Zclsd Extensions (PR #131094)

2025-03-15 Thread Craig Topper via cfe-commits


@@ -0,0 +1,90 @@
+//===-- RISCVInstrInfoZclsd.td -*- tablegen 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+// This file describes the RISC-V instructions from the standard 'Zclsd',
+// Compressed Load/Store pair instructions extension.
+//===--===//
+// Instruction Class Templates
+//===--===//
+
+def GPRPairNoX0RV32Operand : AsmOperandClass {
+  let Name = "GPRPairNoX0RV32";
+  let ParserMethod = "parseGPRPair";
+  let PredicateMethod = "isGPRPairNoX0";
+  let RenderMethod = "addRegOperands";
+}
+
+def GPRPairNoX0RV32 : RegisterOperand {
+  let ParserMatchClass = GPRPairNoX0RV32Operand;
+}
+
+def GPRPairCRV32Operand : AsmOperandClass {
+  let Name = "GPRPairCRV32";
+  let ParserMethod = "parseGPRPair";
+  let PredicateMethod = "isGPRPairC";
+  let RenderMethod = "addRegOperands";
+}
+
+def GPRPairCRV32 : RegisterOperand {
+  let ParserMatchClass = GPRPairCRV32Operand;
+}
+
+let hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+class PairCStackLoad funct3, string OpcodeStr,
+ DAGOperand RC, DAGOperand opnd>
+: RVInst16CI;
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 1 in
+class PairCStackStore funct3, string OpcodeStr,
+  DAGOperand RC, DAGOperand opnd>
+: RVInst16CSS;
+
+let hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+class PairCLoad_ri funct3, string OpcodeStr,
+   DAGOperand RC, DAGOperand opnd>
+: RVInst16CL;
+
+let hasSideEffects = 0, mayLoad = 0, mayStore = 1 in
+class PairCStore_rri funct3, string OpcodeStr,
+ DAGOperand RC, DAGOperand opnd>
+: RVInst16CS;
+ 
+//===--===//
+// Instructions
+//===--===//
+
+let Predicates = [HasStdExtZclsd, IsRV32], DecoderNamespace = "ZcOverlap" in 
+def C_LDSP_RV32 : PairCStackLoad<0b011, "c.ldsp", GPRPairNoX0RV32, 
uimm9_lsb000>, 
+ Sched<[WriteLDD, ReadMemBase]> {

topperc wrote:

Align `Sched` with `PairCStackLoad` on previous line

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


[clang] [Clang][NFC] Rename SecondArgIsLastNamedArgument for clarity and consistency (PR #131346)

2025-03-15 Thread Imad Aldij via cfe-commits

https://github.com/imdj updated https://github.com/llvm/llvm-project/pull/131346

>From 6ecbeba21b4d9e2309b0468a90387e7c890ce109 Mon Sep 17 00:00:00 2001
From: Imad Aldij 
Date: Fri, 14 Mar 2025 17:58:07 +0200
Subject: [PATCH] [Clang] Rename SecondArgIsLastNamedArgument for clarity and
 consistency

---
 clang/lib/Sema/SemaChecking.cpp | 10 +-
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index e99e30d75df94..9fbde68b3ebe4 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4867,22 +4867,22 @@ bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr 
*TheCall) {
   // current function or method. In C23 mode, if the second argument is an
   // integer constant expression with value 0, then we don't bother with this
   // check.
-  bool SecondArgIsLastNamedArgument = false;
+  bool SecondArgIsLastNonVariadicArgument = false;
   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
   if (std::optional Val =
   TheCall->getArg(1)->getIntegerConstantExpr(Context);
   Val && LangOpts.C23 && *Val == 0)
 return false;
 
-  // These are valid if SecondArgIsLastNamedArgument is false after the next
-  // block.
+  // These are valid if SecondArgIsLastNonVariadicArgument is false after the
+  // next block.
   QualType Type;
   SourceLocation ParamLoc;
   bool IsCRegister = false;
 
   if (const DeclRefExpr *DR = dyn_cast(Arg)) {
 if (const ParmVarDecl *PV = dyn_cast(DR->getDecl())) {
-  SecondArgIsLastNamedArgument = PV == LastParam;
+  SecondArgIsLastNonVariadicArgument = PV == LastParam;
 
   Type = PV->getType();
   ParamLoc = PV->getLocation();
@@ -4891,7 +4891,7 @@ bool Sema::BuiltinVAStart(unsigned BuiltinID, CallExpr 
*TheCall) {
 }
   }
 
-  if (!SecondArgIsLastNamedArgument)
+  if (!SecondArgIsLastNonVariadicArgument)
 Diag(TheCall->getArg(1)->getBeginLoc(),
  diag::warn_second_arg_of_va_start_not_last_non_variadic_param);
   else if (IsCRegister || Type->isReferenceType() ||

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


[clang] [clang] Add builtins for `add` with `nuw` and/or `nsw` (PR #130354)

2025-03-15 Thread via cfe-commits


@@ -5037,6 +5037,66 @@ def ArithmeticFence : LangBuiltin<"ALL_LANGUAGES"> {
   let Prototype = "void(...)";
 }
 
+class SNUWTemplate :

macurtis-amd wrote:

I didn't see any infrastructure to handle the varying return type. How would I 
express that the return type is the same as the first argument type?

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


[clang] [CIR] Upstream initial support for unary op (PR #131369)

2025-03-15 Thread Erich Keane via cfe-commits


@@ -0,0 +1,392 @@
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir 
-Wno-unused-value -emit-cir %s -o %t.cir
+// RUN: FileCheck --input-file=%t.cir %s
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -fclangir 
-Wno-unused-value -emit-llvm %s -o %t-cir.ll
+// RUN: FileCheck --input-file=%t-cir.ll %s --check-prefix=LLVM
+// RUN: %clang_cc1 -triple x86_64-unknown-linux-gnu -Wno-unused-value 
-emit-llvm %s -o %t.ll
+// RUN: FileCheck --input-file=%t.ll %s --check-prefix=OGCG

erichkeane wrote:

Hah, just noticed 'OGCG' :D 

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


[clang] Warn about virtual methods in `final` classes (PR #131188)

2025-03-15 Thread Devon Loehr via cfe-commits

https://github.com/DKLoehr updated 
https://github.com/llvm/llvm-project/pull/131188

>From fbd474fb5ae3adeaf1644a4d44e916e4d7c66395 Mon Sep 17 00:00:00 2001
From: Devon Loehr 
Date: Thu, 13 Mar 2025 17:34:27 +
Subject: [PATCH 1/6] Initial warning commit

---
 clang/include/clang/Basic/DiagnosticGroups.td |  2 ++
 .../clang/Basic/DiagnosticSemaKinds.td|  3 +++
 clang/lib/Sema/SemaDeclCXX.cpp|  5 
 .../SemaCXX/unnecessary-virtual-specifier.cpp | 27 +++
 4 files changed, 37 insertions(+)
 create mode 100644 clang/test/SemaCXX/unnecessary-virtual-specifier.cpp

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index fac80fb4009aa..65593ddcb8608 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -372,6 +372,8 @@ def CXX11WarnInconsistentOverrideMethod :
 def CXX11WarnSuggestOverrideDestructor : 
DiagGroup<"suggest-destructor-override">;
 def CXX11WarnSuggestOverride : DiagGroup<"suggest-override">;
 
+def WarnUnnecessaryVirtualSpecifier : 
DiagGroup<"unnecessary-virtual-specifier">;
+
 // Original name of this warning in Clang
 def : DiagGroup<"c++0x-narrowing", [CXX11Narrowing]>;
 
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index 8e6e6e892cdd7..a87cf7e674b4c 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -2706,6 +2706,9 @@ def warn_final_dtor_non_final_class : Warning<
   InGroup;
 def note_final_dtor_non_final_class_silence : Note<
   "mark %0 as '%select{final|sealed}1' to silence this warning">;
+def warn_unnecessary_virtual_specifier : Warning<
+  "virtual method %0 is inside a 'final' class and can never be overridden">,
+  InGroup;
 
 // C++11 attributes
 def err_repeat_attribute : Error<"%0 attribute cannot be repeated">;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index dd779ee377309..1b2e494956d4b 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7193,10 +7193,15 @@ void Sema::CheckCompletedCXXClass(Scope *S, 
CXXRecordDecl *Record) {
 // class without overriding any.
 if (!M->isStatic())
   DiagnoseHiddenVirtualMethods(M);
+
 if (M->hasAttr())
   HasMethodWithOverrideControl = true;
 else if (M->size_overridden_methods() > 0)
   HasOverridingMethodWithoutOverrideControl = true;
+
+// See if a method is marked as virtual inside of a final class.
+if (M->isVirtualAsWritten() && Record->isEffectivelyFinal())
+  Diag(M->getLocation(), diag::warn_unnecessary_virtual_specifier) << 
M;
   }
 
   if (!isa(M))
diff --git a/clang/test/SemaCXX/unnecessary-virtual-specifier.cpp 
b/clang/test/SemaCXX/unnecessary-virtual-specifier.cpp
new file mode 100644
index 0..eb8397d9ade45
--- /dev/null
+++ b/clang/test/SemaCXX/unnecessary-virtual-specifier.cpp
@@ -0,0 +1,27 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -Wunnecessary-virtual-specifier 
-Wsuggest-override %s
+
+struct Foo final {
+  Foo() = default;
+   virtual ~Foo() = default;  // expected-warning 
{{virtual method}}
+   virtual Foo& operator=(Foo& other) = default;  // expected-warning 
{{virtual method}}
+   virtual Foo& operator=(Foo&& other) = default; // expected-warning 
{{virtual method}}
+   void f();
+  virtual void f(int);   // expected-warning {{virtual 
method}}
+  int g(int x) { return x; };
+  virtual int g(bool);   // expected-warning {{virtual 
method}}
+  static int s();
+};
+
+struct BarBase {
+  virtual ~BarBase() = delete;
+   virtual void virt() {}
+   virtual int virt(int);
+  int nonvirt();
+};
+
+struct Bar final : BarBase {
+  ~Bar() override = delete;
+   void virt() override {};
+   virtual int virt(int) override;// expected-warning 
{{virtual method}}
+  int nonvirt();
+};

>From 4a16ef81a4882785708a4973f78586119235e8f5 Mon Sep 17 00:00:00 2001
From: Devon Loehr 
Date: Thu, 13 Mar 2025 17:59:39 +
Subject: [PATCH 2/6] Add documentation

---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/include/clang/Basic/DiagnosticGroups.td | 11 ++-
 2 files changed, 13 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 8989124611e66..15858631c17b7 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -247,6 +247,9 @@ Improvements to Clang's diagnostics
 - The ``-Wsign-compare`` warning now treats expressions with bitwise not(~) 
and minus(-) as signed integers 
   except for the case where the operand is an unsigned integer
   and throws warning if they are compared with unsigned integers (##18878).
+- The ``-Wunnecessary-virtual-specifier`` warning has

[clang-tools-extra] [clang-tidy] add new check: modernize-use-scoped-lock (PR #126434)

2025-03-15 Thread Baranov Victor via cfe-commits


@@ -0,0 +1,326 @@
+//===--- UseScopedLockCheck.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 "UseScopedLockCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Decl.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/ADT/SmallVector.h"
+#include "llvm/ADT/Twine.h"
+#include 
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::modernize {
+
+namespace {
+
+bool isLockGuard(const QualType &Type) {
+  if (const auto *Record = Type->getAs()) {
+if (const RecordDecl *Decl = Record->getDecl()) {
+  return Decl->getName() == "lock_guard" && Decl->isInStdNamespace();
+}
+  }
+
+  if (const auto *TemplateSpecType =
+  Type->getAs()) {
+if (const TemplateDecl *Decl =
+TemplateSpecType->getTemplateName().getAsTemplateDecl()) {
+  return Decl->getName() == "lock_guard" && Decl->isInStdNamespace();
+}
+  }
+
+  return false;
+}
+
+llvm::SmallVector getLockGuardsFromDecl(const DeclStmt *DS) {
+  llvm::SmallVector LockGuards;
+
+  for (const Decl *Decl : DS->decls()) {
+if (const auto *VD = dyn_cast(Decl)) {
+  const QualType Type =
+  VD->getType().getUnqualifiedType().getCanonicalType();
+  if (isLockGuard(Type)) {
+LockGuards.push_back(VD);
+  }
+}
+  }
+
+  return LockGuards;
+}
+
+// Scans through the statements in a block and groups consecutive
+// 'std::lock_guard' variable declarations together.
+llvm::SmallVector>
+findLocksInCompoundStmt(const CompoundStmt *Block,
+const ast_matchers::MatchFinder::MatchResult &Result) {
+  // store groups of consecutive 'std::lock_guard' declarations
+  llvm::SmallVector> LockGuardGroups;
+  llvm::SmallVector CurrentLockGuardGroup;
+
+  auto AddAndClearCurrentGroup = [&]() {
+if (!CurrentLockGuardGroup.empty()) {
+  LockGuardGroups.push_back(CurrentLockGuardGroup);
+  CurrentLockGuardGroup.clear();
+}
+  };
+
+  for (const Stmt *Stmt : Block->body()) {
+if (const auto *DS = dyn_cast(Stmt)) {
+  llvm::SmallVector LockGuards = 
getLockGuardsFromDecl(DS);
+
+  if (!LockGuards.empty()) {
+CurrentLockGuardGroup.insert(
+CurrentLockGuardGroup.end(),
+std::make_move_iterator(LockGuards.begin()),
+std::make_move_iterator(LockGuards.end()));
+continue;
+  }
+}
+AddAndClearCurrentGroup();
+  }
+
+  AddAndClearCurrentGroup();
+
+  return LockGuardGroups;
+}
+
+TemplateSpecializationTypeLoc
+getTemplateLockGuardTypeLoc(const TypeSourceInfo *SourceInfo) {
+  const TypeLoc Loc = SourceInfo->getTypeLoc();
+
+  const auto ElaboratedLoc = Loc.getAs();
+  if (!ElaboratedLoc)
+return {};
+
+  return 
ElaboratedLoc.getNamedTypeLoc().getAs();
+}
+
+// Find the exact source range of the 'lock_guard' token
+SourceRange getLockGuardRange(const TypeSourceInfo *SourceInfo) {
+  const TypeLoc LockGuardTypeLoc = SourceInfo->getTypeLoc();
+
+  return SourceRange(LockGuardTypeLoc.getBeginLoc(),
+ LockGuardTypeLoc.getEndLoc());
+}
+
+// Find the exact source range of the 'lock_guard' name token
+SourceRange getLockGuardNameRange(const TypeSourceInfo *SourceInfo) {
+  const TemplateSpecializationTypeLoc TemplateLoc =
+  getTemplateLockGuardTypeLoc(SourceInfo);
+  if (!TemplateLoc)
+return {};
+
+  return SourceRange(TemplateLoc.getTemplateNameLoc(),
+ TemplateLoc.getLAngleLoc().getLocWithOffset(-1));
+}
+
+const StringRef UseScopedLockMessage =
+"use 'std::scoped_lock' instead of 'std::lock_guard'";
+
+} // namespace
+
+UseScopedLockCheck::UseScopedLockCheck(StringRef Name,
+   ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  WarnOnSingleLocks(Options.get("WarnOnSingleLocks", true)),
+  WarnOnUsingAndTypedef(Options.get("WarnOnUsingAndTypedef", true)) {}
+
+void UseScopedLockCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
+  Options.store(Opts, "WarnOnSingleLocks", WarnOnSingleLocks);
+  Options.store(Opts, "WarnOnUsingAndTypedef", WarnOnUsingAndTypedef);
+}
+
+void UseScopedLockCheck::registerMatchers(MatchFinder *Finder) {
+  const auto LockGuardClassDecl =
+  namedDecl(hasName("lock_guard"), isInStdNamespace());
+
+  const auto LockGuardType = qualType(anyOf(
+  hasUnqualifiedDesugaredType(
+  recordType(hasDeclaration(LockGuardClassDecl))),
+  elaboratedType(namesType(hasUnqualifiedDesugaredType(
+  templateSpecializationTyp

[clang-tools-extra] [clang-tidy] Add new check bugprone-capture-this-by-field (PR #130297)

2025-03-15 Thread Denis Mikhailov via cfe-commits

denzor200 wrote:

LGTM, please provide the change for one comment I left

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


[clang] [Clang] Do not emit nodiscard warnings for the base expr of static member access (PR #131450)

2025-03-15 Thread via cfe-commits

cor3ntin wrote:

/cherry-pick 9a1e390

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


[clang] [Clang] Do not emit nodiscard warnings for the base expr of static member access (PR #131450)

2025-03-15 Thread via cfe-commits

llvmbot wrote:

/pull-request llvm/llvm-project#131474

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


[clang] 9a1e390 - [Clang] Do not emit nodiscard warnings for the base expr of static member access (#131450)

2025-03-15 Thread via cfe-commits

Author: cor3ntin
Date: 2025-03-15T22:27:08+01:00
New Revision: 9a1e39062b2ab445f1f4424ecdc5ffb46e8cb9e0

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

LOG: [Clang] Do not emit nodiscard warnings for the base expr of static member 
access (#131450)

For an expression `nodiscard_function().static_member(), the nodiscard
warnings added by #120223, are not useful or actionable, and are
disruptive to some library implementations; we just remove them.

Fixes #131410

Added: 


Modified: 
clang/include/clang/Sema/Sema.h
clang/lib/Sema/SemaExprMember.cpp
clang/lib/Sema/SemaStmt.cpp
clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
clang/test/SemaCXX/ms-property.cpp

Removed: 




diff  --git a/clang/include/clang/Sema/Sema.h b/clang/include/clang/Sema/Sema.h
index 414f3c6eff038..657350fa843b9 100644
--- a/clang/include/clang/Sema/Sema.h
+++ b/clang/include/clang/Sema/Sema.h
@@ -10755,11 +10755,6 @@ class Sema final : public SemaBase {
SourceLocation EndLoc);
   void ActOnForEachDeclStmt(DeclGroupPtrTy Decl);
 
-  /// DiagnoseDiscardedExprMarkedNodiscard - Given an expression that is
-  /// semantically a discarded-value expression, diagnose if any [[nodiscard]]
-  /// value has been discarded.
-  void DiagnoseDiscardedExprMarkedNodiscard(const Expr *E);
-
   /// DiagnoseUnusedExprResult - If the statement passed in is an expression
   /// whose result is unused, warn.
   void DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID);

diff  --git a/clang/lib/Sema/SemaExprMember.cpp 
b/clang/lib/Sema/SemaExprMember.cpp
index 1d9efbeb5ccb5..b0872122ed740 100644
--- a/clang/lib/Sema/SemaExprMember.cpp
+++ b/clang/lib/Sema/SemaExprMember.cpp
@@ -1136,7 +1136,6 @@ Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType 
BaseExprType,
 if (Converted.isInvalid())
   return true;
 BaseExpr = Converted.get();
-DiagnoseDiscardedExprMarkedNodiscard(BaseExpr);
 return false;
   };
   auto ConvertBaseExprToGLValue = [&] {

diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 944e3300c83fc..112eaf758cf36 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -413,10 +413,6 @@ void DiagnoseUnused(Sema &S, const Expr *E, 
std::optional DiagID) {
 }
 } // namespace
 
-void Sema::DiagnoseDiscardedExprMarkedNodiscard(const Expr *E) {
-  DiagnoseUnused(*this, E, std::nullopt);
-}
-
 void Sema::DiagnoseUnusedExprResult(const Stmt *S, unsigned DiagID) {
   if (const LabelStmt *Label = dyn_cast_if_present(S))
 S = Label->getSubStmt();

diff  --git a/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp 
b/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
index 18f4bd5e9c0fa..0012ab976baa5 100644
--- a/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
+++ b/clang/test/CXX/dcl.dcl/dcl.attr/dcl.attr.nodiscard/p2.cpp
@@ -164,19 +164,21 @@ struct X {
 
 [[nodiscard]] X get_X();
 // cxx11-warning@-1 {{use of the 'nodiscard' attribute is a C++17 extension}}
+[[nodiscard]] X* get_Ptr();
+// cxx11-warning@-1 {{use of the 'nodiscard' attribute is a C++17 extension}}
 void f() {
+  get_X(); // expected-warning{{ignoring return value of function declared 
with 'nodiscard' attribute}}
+  (void) get_X();
   (void) get_X().variant_member;
   (void) get_X().anonymous_struct_member;
   (void) get_X().data_member;
   (void) get_X().static_data_member;
-  // expected-warning@-1 {{ignoring return value of function declared with 
'nodiscard' attribute}}
   (void) get_X().unscoped_enum;
-  // expected-warning@-1 {{ignoring return value of function declared with 
'nodiscard' attribute}}
   (void) get_X().scoped_enum;
-  // expected-warning@-1 {{ignoring return value of function declared with 
'nodiscard' attribute}}
   (void) get_X().implicit_object_member_function();
   (void) get_X().static_member_function();
-  // expected-warning@-1 {{ignoring return value of function declared with 
'nodiscard' attribute}}
+  (void) get_Ptr()->implicit_object_member_function();
+  (void) get_Ptr()->static_member_function();
 #if __cplusplus >= 202302L
   (void) get_X().explicit_object_member_function();
 #endif

diff  --git a/clang/test/SemaCXX/ms-property.cpp 
b/clang/test/SemaCXX/ms-property.cpp
index d5799a8a4d363..f1424b9cb12bc 100644
--- a/clang/test/SemaCXX/ms-property.cpp
+++ b/clang/test/SemaCXX/ms-property.cpp
@@ -2,6 +2,7 @@
 // RUN: %clang_cc1 -triple=x86_64-pc-win32 -fms-compatibility -emit-pch -o %t 
-verify %s
 // RUN: %clang_cc1 -triple=x86_64-pc-win32 -fms-compatibility -include-pch %t 
%s -ast-print -o - | FileCheck %s
 // RUN: %clang_cc1 -fdeclspec -fsyntax-only -verify %s -std=c++23
+// expected-no-diagnostics
 
 #ifndef HEADER
 #define HEADER
@@ -103,7 +104,6 @@ struct X {
 void f

[clang-tools-extra] [clang-tidy] Add new check bugprone-capture-this-by-field (PR #130297)

2025-03-15 Thread Denis Mikhailov via cfe-commits

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


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


  1   2   3   4   >