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

2023-09-25 Thread Felix via cfe-commits

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


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

2023-09-25 Thread Felix via cfe-commits

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


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

2023-09-25 Thread Felix via cfe-commits

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


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

2023-09-25 Thread Felix via cfe-commits

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


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

2023-09-25 Thread Felix via cfe-commits

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


[clang-tools-extra] [MLIR][Presburger] Define matrix inverse for rational matrices (PR #67382)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir-presburger


Changes

A new class, FracMatrix, has been created for rational matrices.
It inherits from MatrixFraction with no new data attributes and one new 
method, `inverse()`.
Gaussian elimination is used in the inverse implementation.
A basic test for inverses has also been added.

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


5 Files Affected:

- (modified) mlir/include/mlir/Analysis/Presburger/Fraction.h (+1-1) 
- (modified) mlir/include/mlir/Analysis/Presburger/Matrix.h (+26) 
- (modified) mlir/lib/Analysis/Presburger/Matrix.cpp (+66) 
- (modified) mlir/unittests/Analysis/Presburger/MatrixTest.cpp (+11) 
- (modified) mlir/unittests/Analysis/Presburger/Utils.h (+2-2) 


``diff
diff --git a/mlir/include/mlir/Analysis/Presburger/Fraction.h 
b/mlir/include/mlir/Analysis/Presburger/Fraction.h
index 74127a900d53ed2..f633192a870c8d4 100644
--- a/mlir/include/mlir/Analysis/Presburger/Fraction.h
+++ b/mlir/include/mlir/Analysis/Presburger/Fraction.h
@@ -102,7 +102,7 @@ inline bool operator>=(const Fraction , const Fraction 
) {
 inline Fraction reduce(const Fraction ) {
   if (f == Fraction(0))
 return Fraction(0, 1);
-  MPInt g = gcd(f.num, f.den);
+  MPInt g = gcd(abs(f.num), abs(f.den));
   return Fraction(f.num / g, f.den / g);
 }
 
diff --git a/mlir/include/mlir/Analysis/Presburger/Matrix.h 
b/mlir/include/mlir/Analysis/Presburger/Matrix.h
index f05a4fb2ffbb70d..b9048334c39f1f3 100644
--- a/mlir/include/mlir/Analysis/Presburger/Matrix.h
+++ b/mlir/include/mlir/Analysis/Presburger/Matrix.h
@@ -244,6 +244,32 @@ class IntMatrix : public Matrix
 
 };
 
+// An inherited class for rational matrices, with no new data attributes.
+// This is only used for the matrix-related method which apply only
+// to fractions (inverse).
+class FracMatrix : public Matrix
+{
+public:
+  FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0,
+unsigned reservedColumns = 0) :
+Matrix(rows, columns, reservedRows, reservedColumns) {};
+
+  FracMatrix(Matrix m) :
+Matrix(m.getNumRows(), m.getNumColumns(), 
m.getNumReservedRows(), m.getNumReservedColumns())
+  {
+for (unsigned i = 0; i < m.getNumRows(); i++)
+  for (unsigned j = 0; j < m.getNumColumns(); j++)
+at(i, j) = m(i, j);
+  };
+  
+  /// Return the identity matrix of the specified dimension.
+  static FracMatrix identity(unsigned dimension);
+
+  // Return the inverse of the matrix, leaving the calling object unmodified.
+  FracMatrix inverse();
+
+};
+
 } // namespace presburger
 } // namespace mlir
 
diff --git a/mlir/lib/Analysis/Presburger/Matrix.cpp 
b/mlir/lib/Analysis/Presburger/Matrix.cpp
index f0bcb09fb28f7b1..c0fbc688be2e1b2 100644
--- a/mlir/lib/Analysis/Presburger/Matrix.cpp
+++ b/mlir/lib/Analysis/Presburger/Matrix.cpp
@@ -390,4 +390,70 @@ MPInt IntMatrix::normalizeRow(unsigned row, unsigned cols) 
{
 
 MPInt IntMatrix::normalizeRow(unsigned row) {
   return normalizeRow(row, getNumColumns());
+}
+
+
+FracMatrix FracMatrix::identity(unsigned dimension) {
+  FracMatrix matrix(dimension, dimension);
+  for (unsigned i = 0; i < dimension; ++i)
+matrix(i, i) = 1;
+  return matrix;
+}
+
+FracMatrix FracMatrix::inverse()
+{
+// We use Gaussian elimination on the rows of [M | I]
+// to find the integer inverse. We proceed left-to-right,
+// top-to-bottom. M is assumed to be a dim x dim matrix.
+
+unsigned dim = getNumRows();
+
+// Construct the augmented matrix [M | I]
+FracMatrix augmented(dim, dim + dim);
+for (unsigned i = 0; i < dim; i++)
+{
+augmented.fillRow(i, 0);
+for (unsigned j = 0; j < dim; j++)
+augmented(i, j) = at(i, j);
+augmented(i, dim+i).num = 1;
+augmented(i, dim+i).den = 1;
+}
+Fraction a, b;
+for (unsigned i = 0; i < dim; i++)
+{
+if (augmented(i, i) == Fraction(0, 1))
+for (unsigned j = i+1; j < dim; j++)
+if (augmented(j, i) != Fraction(0, 1))
+{
+augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
+break;
+}
+
+b = augmented(i, i);
+for (unsigned j = 0; j < dim; j++)
+{
+if (i == j || augmented(j, i) == 0) continue;
+a = augmented(j, i);
+// Rj -> Rj - (b/a)Ri
+augmented.addToRow(j, augmented.getRow(i), - a / b);
+// Now (Rj)i = 0
+}
+}
+
+// Now only diagonal elements are nonzero, but they are
+// not necessarily 1.
+for (unsigned i = 0; i < dim; i++)
+{
+a = augmented(i, i);
+for (unsigned j = dim; j < dim + dim; j++)
+augmented(i, j) = augmented(i, j) / a;
+}
+
+// Copy the right half of the augmented matrix.
+FracMatrix inverse(dim, dim);
+for (unsigned i = 0; i < dim; i++)
+for (unsigned j = 0; j < dim; j++)
+inverse(i, 

[clang] [MLIR][Presburger] Define matrix inverse for rational matrices (PR #67382)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-mlir-presburger


Changes

A new class, FracMatrix, has been created for rational matrices.
It inherits from MatrixFraction with no new data attributes and one new 
method, `inverse()`.
Gaussian elimination is used in the inverse implementation.
A basic test for inverses has also been added.

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


5 Files Affected:

- (modified) mlir/include/mlir/Analysis/Presburger/Fraction.h (+1-1) 
- (modified) mlir/include/mlir/Analysis/Presburger/Matrix.h (+26) 
- (modified) mlir/lib/Analysis/Presburger/Matrix.cpp (+66) 
- (modified) mlir/unittests/Analysis/Presburger/MatrixTest.cpp (+11) 
- (modified) mlir/unittests/Analysis/Presburger/Utils.h (+2-2) 


``diff
diff --git a/mlir/include/mlir/Analysis/Presburger/Fraction.h 
b/mlir/include/mlir/Analysis/Presburger/Fraction.h
index 74127a900d53ed2..f633192a870c8d4 100644
--- a/mlir/include/mlir/Analysis/Presburger/Fraction.h
+++ b/mlir/include/mlir/Analysis/Presburger/Fraction.h
@@ -102,7 +102,7 @@ inline bool operator>=(const Fraction , const Fraction 
) {
 inline Fraction reduce(const Fraction ) {
   if (f == Fraction(0))
 return Fraction(0, 1);
-  MPInt g = gcd(f.num, f.den);
+  MPInt g = gcd(abs(f.num), abs(f.den));
   return Fraction(f.num / g, f.den / g);
 }
 
diff --git a/mlir/include/mlir/Analysis/Presburger/Matrix.h 
b/mlir/include/mlir/Analysis/Presburger/Matrix.h
index f05a4fb2ffbb70d..b9048334c39f1f3 100644
--- a/mlir/include/mlir/Analysis/Presburger/Matrix.h
+++ b/mlir/include/mlir/Analysis/Presburger/Matrix.h
@@ -244,6 +244,32 @@ class IntMatrix : public Matrix
 
 };
 
+// An inherited class for rational matrices, with no new data attributes.
+// This is only used for the matrix-related method which apply only
+// to fractions (inverse).
+class FracMatrix : public Matrix
+{
+public:
+  FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0,
+unsigned reservedColumns = 0) :
+Matrix(rows, columns, reservedRows, reservedColumns) {};
+
+  FracMatrix(Matrix m) :
+Matrix(m.getNumRows(), m.getNumColumns(), 
m.getNumReservedRows(), m.getNumReservedColumns())
+  {
+for (unsigned i = 0; i < m.getNumRows(); i++)
+  for (unsigned j = 0; j < m.getNumColumns(); j++)
+at(i, j) = m(i, j);
+  };
+  
+  /// Return the identity matrix of the specified dimension.
+  static FracMatrix identity(unsigned dimension);
+
+  // Return the inverse of the matrix, leaving the calling object unmodified.
+  FracMatrix inverse();
+
+};
+
 } // namespace presburger
 } // namespace mlir
 
diff --git a/mlir/lib/Analysis/Presburger/Matrix.cpp 
b/mlir/lib/Analysis/Presburger/Matrix.cpp
index f0bcb09fb28f7b1..c0fbc688be2e1b2 100644
--- a/mlir/lib/Analysis/Presburger/Matrix.cpp
+++ b/mlir/lib/Analysis/Presburger/Matrix.cpp
@@ -390,4 +390,70 @@ MPInt IntMatrix::normalizeRow(unsigned row, unsigned cols) 
{
 
 MPInt IntMatrix::normalizeRow(unsigned row) {
   return normalizeRow(row, getNumColumns());
+}
+
+
+FracMatrix FracMatrix::identity(unsigned dimension) {
+  FracMatrix matrix(dimension, dimension);
+  for (unsigned i = 0; i < dimension; ++i)
+matrix(i, i) = 1;
+  return matrix;
+}
+
+FracMatrix FracMatrix::inverse()
+{
+// We use Gaussian elimination on the rows of [M | I]
+// to find the integer inverse. We proceed left-to-right,
+// top-to-bottom. M is assumed to be a dim x dim matrix.
+
+unsigned dim = getNumRows();
+
+// Construct the augmented matrix [M | I]
+FracMatrix augmented(dim, dim + dim);
+for (unsigned i = 0; i < dim; i++)
+{
+augmented.fillRow(i, 0);
+for (unsigned j = 0; j < dim; j++)
+augmented(i, j) = at(i, j);
+augmented(i, dim+i).num = 1;
+augmented(i, dim+i).den = 1;
+}
+Fraction a, b;
+for (unsigned i = 0; i < dim; i++)
+{
+if (augmented(i, i) == Fraction(0, 1))
+for (unsigned j = i+1; j < dim; j++)
+if (augmented(j, i) != Fraction(0, 1))
+{
+augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
+break;
+}
+
+b = augmented(i, i);
+for (unsigned j = 0; j < dim; j++)
+{
+if (i == j || augmented(j, i) == 0) continue;
+a = augmented(j, i);
+// Rj -> Rj - (b/a)Ri
+augmented.addToRow(j, augmented.getRow(i), - a / b);
+// Now (Rj)i = 0
+}
+}
+
+// Now only diagonal elements are nonzero, but they are
+// not necessarily 1.
+for (unsigned i = 0; i < dim; i++)
+{
+a = augmented(i, i);
+for (unsigned j = dim; j < dim + dim; j++)
+augmented(i, j) = augmented(i, j) / a;
+}
+
+// Copy the right half of the augmented matrix.
+FracMatrix inverse(dim, dim);
+for (unsigned i = 0; i < dim; i++)
+for (unsigned j = 0; j < dim; j++)
+inverse(i, 

[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-25 Thread Congcong Cai via cfe-commits

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

>From cfedbe3fb2f2f331b3f9ee1f4f3e2fcd348797e2 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Mon, 11 Sep 2023 09:15:41 +0800
Subject: [PATCH 1/6] [Sema] add cast from IncompleteArrayType to
 ConstantArrayType in TryReferenceListInitialization

Fixed: https://github.com/llvm/llvm-project/issues/62945
c++20 supports "Permit conversions to arrays of unknown bound".
This need additional cast from IncompleteArrayType to ConstantArrayType
in TryReferenceListInitialization
---
 clang/lib/Sema/SemaInit.cpp   | 9 +
 clang/test/CodeGenCXX/cxx20-p0388-unbound-ary.cpp | 9 +
 2 files changed, 18 insertions(+)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 93f05e2e47285e4..966d35226eec748 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4532,6 +4532,15 @@ static void TryReferenceListInitialization(Sema ,
   if (T1Quals.hasAddressSpace())
 Sequence.AddQualificationConversionStep(
 cv1T1, DestType->isRValueReferenceType() ? VK_XValue : VK_LValue);
+  else if (S.getLangOpts().CPlusPlus20 &&
+   isa(T1->getUnqualifiedDesugaredType()) &&
+   DestType->isRValueReferenceType()) {
+// [dcl.init.list] p3.10
+// unless T is “reference to array of unknown bound of U”, in which 
case
+// the type of the prvalue is the type of x in the declaration U x[] H,
+// where H is the initializer list.
+Sequence.AddQualificationConversionStep(cv1T1, VK_XValue);
+  }
 } else
   Sequence.SetFailed(
   
InitializationSequence::FK_NonConstLValueReferenceBindingToTemporary);
diff --git a/clang/test/CodeGenCXX/cxx20-p0388-unbound-ary.cpp 
b/clang/test/CodeGenCXX/cxx20-p0388-unbound-ary.cpp
index 78f35a024a54014..a29f4d720c1de4e 100644
--- a/clang/test/CodeGenCXX/cxx20-p0388-unbound-ary.cpp
+++ b/clang/test/CodeGenCXX/cxx20-p0388-unbound-ary.cpp
@@ -23,4 +23,13 @@ auto (int ()[1]) {
 
   return r2;
 }
+
+// CHECK-LABEL: @_ZN3One3fooEi
+// CHECK-NEXT: entry:
+// CHECK-NEXT: ret void
+void foo(int a) {
+  auto f = [](int(&&)[]) {};
+  f({a});
+}
+
 } // namespace One

>From 0d149d1e07783d2cf7b869623c6c055b9184ce8e Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Thu, 14 Sep 2023 00:28:28 +0800
Subject: [PATCH 2/6] Update clang/lib/Sema/SemaInit.cpp

Co-authored-by: Mariya Podchishchaeva 
---
 clang/lib/Sema/SemaInit.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 966d35226eec748..d8a035b60dcb6e5 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -4535,7 +4535,7 @@ static void TryReferenceListInitialization(Sema ,
   else if (S.getLangOpts().CPlusPlus20 &&
isa(T1->getUnqualifiedDesugaredType()) &&
DestType->isRValueReferenceType()) {
-// [dcl.init.list] p3.10
+// C++20 [dcl.init.list]p3.10:
 // unless T is “reference to array of unknown bound of U”, in which 
case
 // the type of the prvalue is the type of x in the declaration U x[] H,
 // where H is the initializer list.

>From fecee704039f5c9cb964a646f0d5f27edd6101f6 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 15 Sep 2023 09:46:52 +0800
Subject: [PATCH 3/6] fix

---
 clang/lib/Sema/SemaInit.cpp | 21 -
 1 file changed, 12 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index d8a035b60dcb6e5..da006e98e81b99a 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -18,6 +18,7 @@
 #include "clang/AST/TypeLoc.h"
 #include "clang/Basic/CharInfo.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Basic/Specifiers.h"
 #include "clang/Basic/TargetInfo.h"
 #include "clang/Sema/Designator.h"
 #include "clang/Sema/EnterExpressionEvaluationContext.h"
@@ -4527,20 +4528,22 @@ static void TryReferenceListInitialization(Sema ,
   if (Sequence) {
 if (DestType->isRValueReferenceType() ||
 (T1Quals.hasConst() && !T1Quals.hasVolatile())) {
+  if (S.getLangOpts().CPlusPlus20 &&
+  isa(T1->getUnqualifiedDesugaredType()) &&
+  DestType->isRValueReferenceType()) {
+// C++20 [dcl.init.list]p3.10:
+// List-initialization of an object or reference of type T is defined 
as
+// follows:
+// ..., unless T is “reference to array of unknown bound of U”, in 
which
+// case the type of the prvalue is the type of x in the declaration U
+// x[] H, where H is the initializer list.
+Sequence.AddQualificationConversionStep(cv1T1, clang::VK_PRValue);
+  }
   Sequence.AddReferenceBindingStep(cv1T1IgnoreAS,
/*BindingTemporary=*/true);
   if (T1Quals.hasAddressSpace())
 

[clang] [llvm][tblgen] Add `Source Filename` for `emitSourceFileHeader` (PR #65744)

2023-09-25 Thread Shao-Ce SUN via cfe-commits
" + sys::path::filename(Record.getInputFilename()),"
In-Reply-To: 


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


[clang] b0e28eb - [llvm][tblgen] Add `Source Filename` for `emitSourceFileHeader` (#65744)

2023-09-25 Thread via cfe-commits

Author: Shao-Ce SUN
Date: 2023-09-26T13:40:56+08:00
New Revision: b0e28eb832710964067a17d845de15ada2da2b9c

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

LOG: [llvm][tblgen] Add `Source Filename` for `emitSourceFileHeader` (#65744)

I think this is very helpful for reading generated `.inc` files.

Added: 


Modified: 
clang/utils/TableGen/ClangASTNodesEmitter.cpp
clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
clang/utils/TableGen/ClangAttrEmitter.cpp
clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
clang/utils/TableGen/ClangOpenCLBuiltinEmitter.cpp
clang/utils/TableGen/ClangSyntaxEmitter.cpp
clang/utils/TableGen/ClangTypeNodesEmitter.cpp
lldb/utils/TableGen/LLDBOptionDefEmitter.cpp
lldb/utils/TableGen/LLDBPropertyDefEmitter.cpp
llvm/include/llvm/TableGen/TableGenBackend.h
llvm/lib/TableGen/TableGenBackend.cpp
llvm/utils/TableGen/AsmMatcherEmitter.cpp
llvm/utils/TableGen/AsmWriterEmitter.cpp
llvm/utils/TableGen/VTEmitter.cpp
mlir/tools/mlir-tblgen/DialectGen.cpp
mlir/tools/mlir-tblgen/EnumsGen.cpp
mlir/tools/mlir-tblgen/LLVMIRIntrinsicGen.cpp
mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp
mlir/tools/mlir-tblgen/RewriterGen.cpp
mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp

Removed: 




diff  --git a/clang/utils/TableGen/ClangASTNodesEmitter.cpp 
b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
index 2b8d7a9efdf10c9..16a1c74b9d91ad6 100644
--- a/clang/utils/TableGen/ClangASTNodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
@@ -169,7 +169,7 @@ void ClangASTNodesEmitter::deriveChildTree() {
 void ClangASTNodesEmitter::run(raw_ostream ) {
   deriveChildTree();
 
-  emitSourceFileHeader("List of AST nodes of a particular kind", OS);
+  emitSourceFileHeader("List of AST nodes of a particular kind", OS, Records);
 
   // Write the preamble
   OS << "#ifndef ABSTRACT_" << macroHierarchyName() << "\n";
@@ -205,7 +205,7 @@ void clang::EmitClangASTNodes(RecordKeeper , raw_ostream 
,
 void clang::EmitClangDeclContext(RecordKeeper , raw_ostream ) {
   // FIXME: Find a .td file format to allow for this to be represented better.
 
-  emitSourceFileHeader("List of AST Decl nodes", OS);
+  emitSourceFileHeader("List of AST Decl nodes", OS, Records);
 
   OS << "#ifndef DECL_CONTEXT\n";
   OS << "#  define DECL_CONTEXT(DECL)\n";

diff  --git a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp 
b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
index 19613880641efe9..de8dda60681ff87 100644
--- a/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
+++ b/clang/utils/TableGen/ClangASTPropertiesEmitter.cpp
@@ -593,7 +593,7 @@ void ASTPropsEmitter::emitWriteOfProperty(StringRef 
writerName,
 template 
 static void emitASTReader(RecordKeeper , raw_ostream ,
   StringRef description) {
-  emitSourceFileHeader(description, out);
+  emitSourceFileHeader(description, out, records);
 
   ASTPropsEmitter(records, out).emitNodeReaderClass();
 }
@@ -607,7 +607,7 @@ void clang::EmitClangTypeReader(RecordKeeper , 
raw_ostream ) {
 template 
 static void emitASTWriter(RecordKeeper , raw_ostream ,
   StringRef description) {
-  emitSourceFileHeader(description, out);
+  emitSourceFileHeader(description, out, records);
 
   ASTPropsEmitter(records, out).emitNodeWriterClass();
 }
@@ -852,7 +852,7 @@ void ASTPropsEmitter::emitBasicReaderWriterFile(const 
ReaderWriterInfo ) {
 /// Emit an .inc file that defines some helper classes for reading
 /// basic values.
 void clang::EmitClangBasicReader(RecordKeeper , raw_ostream ) {
-  emitSourceFileHeader("Helper classes for BasicReaders", out);
+  emitSourceFileHeader("Helper classes for BasicReaders", out, records);
 
   // Use any property, we won't be using those properties.
   auto info = ReaderWriterInfo::forReader();
@@ -862,7 +862,7 @@ void clang::EmitClangBasicReader(RecordKeeper , 
raw_ostream ) {
 /// Emit an .inc file that defines some helper classes for writing
 /// basic values.
 void clang::EmitClangBasicWriter(RecordKeeper , raw_ostream ) {
-  emitSourceFileHeader("Helper classes for BasicWriters", out);
+  emitSourceFileHeader("Helper classes for BasicWriters", out, records);
 
   // Use any property, we won't be using those properties.
   auto info = ReaderWriterInfo::forWriter();

diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 00bcbe1153518c8..a015ec36a30dc9e 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -2921,7 +2921,7 @@ static void 

[clang] [clang][Interp] Add IntegralAP for arbitrary-precision integers (PR #65844)

2023-09-25 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= ,
Timm =?utf-8?q?B=C3=A4der?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

Ping

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


[clang] [clang][Interp] Three-way comparisons (PR #65901)

2023-09-25 Thread Timm Baeder via cfe-commits

tbaederr wrote:

Ping

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


[clang] 38dd67c - [clang-format][NFC] Minor cleanup of the parser and annotator

2023-09-25 Thread Owen Pan via cfe-commits

Author: Owen Pan
Date: 2023-09-25T22:20:02-07:00
New Revision: 38dd67c8b3dbce4311e32a68d1100bd9f850c43e

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

LOG: [clang-format][NFC] Minor cleanup of the parser and annotator

Added: 


Modified: 
clang/lib/Format/TokenAnnotator.cpp
clang/lib/Format/UnwrappedLineParser.cpp

Removed: 




diff  --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 138f7e8562dcc39..5becb86c0f37081 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -4141,8 +4141,7 @@ bool TokenAnnotator::spaceRequiredBetween(const 
AnnotatedLine ,
 (Style.SpacesInSquareBrackets &&
  Right.MatchingParen->isOneOf(TT_ArraySubscriptLSquare,
   TT_StructuredBindingLSquare,
-  TT_LambdaLSquare)) ||
-Right.MatchingParen->is(TT_AttributeParen));
+  TT_LambdaLSquare)));
   }
   if (Right.is(tok::l_square) &&
   !Right.isOneOf(TT_ObjCMethodExpr, TT_LambdaLSquare,

diff  --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 020ca3cff9bfbcd..53310d44c709af5 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -2660,7 +2660,7 @@ void UnwrappedLineParser::handleAttributes() {
   // Handle AttributeMacro, e.g. `if (x) UNLIKELY`.
   if (FormatTok->is(TT_AttributeMacro))
 nextToken();
-  if (FormatTok->is(tok::l_square))
+  else if (FormatTok->is(tok::l_square))
 handleCppAttributes();
 }
 



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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-09-25 Thread Timm Baeder via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


tbaederr wrote:

> > > I have concerns about Lexing twice every single file for which we display 
> > > a warning.
> > 
> > 
> > Sure. Because of performance, memory usage or code complexity?
> 
> Performance, mostly

In a debug build with sanitizers enabled, I get this when compiling 
`SemaExpr.cpp` from clang with a `static_assert(false)` added at the end:

```
/home/tbaeder/code/llvm-project/clang/lib/Sema/SemaExpr.cpp:21870:15: error: 
static assertion failed
Lexed 21870 lines and 174105 Tokens
That took 660402 microseconds
That took 660 milliseconds
That took 0 seconds
```
That doesn't seem too bad to me? I can try again with an optimized build if you 
want.

> > So, my general procedure for diagnostics is that they shouldn't complicate 
> > the non-diagnostic code. And when we emit a diagnostic, performance is 
> > basically out the window anyway (printing to stdout is _slow_ and the way 
> > we emit code snippets is also slow, etc.)
> 
> That is generally true, but how far do want to push that logic? Lexing is 
> going to be fairly expensive on most source files. I'd expect it to be much 
> more (cpu) expensive than a call to print.

Of course it's more expensive, I was just trying to make a point :) I expect 
this to be only visible in situations where very few errors are ever shown, 
i.e. when an actual human compiles a project. Build servers redirect the output 
to a file anyway, which disables any sort of colored output.



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


[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Timm Baeder via cfe-commits


@@ -2352,26 +2352,61 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
-static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
+static bool diagnoseInvalidPriority(Sema , uint32_t Priority,
+const ParsedAttr ,
+SourceLocation PriorityLoc) {
+  // Only perform the priority check if the attribute is outside of a system
+  // header. Values <= 100 are reserved for the implementation, and libc++
+  // benefits from being able to specify values in that range.
+  if ((Priority < 101 || Priority > 65535) &&
+  !S.getSourceManager().isInSystemHeader(A.getLoc())) {
+S.Diag(A.getLoc(), diag::err_attribute_argument_out_of_range)
+<< PriorityLoc << A << 101 << 65535;
+A.setInvalid();
+return true;
+  }
+  return false;
+}
+
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t Priority = CtorDtorAttr::DefaultPriority;
   if (S.getLangOpts().HLSL && AL.getNumArgs()) {
 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
 return;
   }
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
 
-  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
-}
+  // If we're given an argument for the priority, check that it's valid.
+  if (AL.getNumArgs()) {
+if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Priority))
+  return;
 
-static void handleDestructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = DestructorAttr::DefaultPriority;
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
+// Ensure the priority is in a reasonable range.
+if (diagnoseInvalidPriority(S, Priority, AL,
+AL.getArgAsExpr(0)->getExprLoc()))
+  return;
+  }
+
+  // Ensure the function we're attaching to is something that is sensible to
+  // automatically call before or after main(); it should accept no arguments
+  // and return no value (but it is not an error because it is theoretically
+  // possible to call the function during normal program execution and pass it
+  // valid values). It also cannot be a member function. We allow K C
+  // functions because that's a difficult edge case where it depends on how the
+  // function is defined as to whether it does or does not expect arguments.
+  auto *FD = cast(D);
+  if (!FD->getReturnType()->isVoidType() ||
+  (FD->hasPrototype() && FD->getNumParams() != 0)) {
+S.Diag(AL.getLoc(), diag::err_ctor_dtor_attr_on_non_void_func)
+<< AL << FD->getSourceRange();
 return;
+  } else if (auto *MD = dyn_cast(FD); MD && MD->isInstance()) {

tbaederr wrote:

```suggestion
  } else if (const auto *MD = dyn_cast(FD); MD && 
MD->isInstance()) {
```

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


[clang] [Driver] Fix detection of libc++ with empty sysroot. (PR #66947)

2023-09-25 Thread Vladimir Vereschaka via cfe-commits

vvereschaka wrote:

@sam-mccall ,
your 7ca8c21af36acb117529e797b3d36e85a286ca47 commit breaks `Clang-Unit :: 
Driver/./ClangDriverTests.exe/ToolChainTest/VFSGnuLibcxxPathNoSysroot` 
(`Clang-Unit::67`) test on the windows toolchain builders
* https://lab.llvm.org/buildbot/#/builders/119/builds/15230
* https://lab.llvm.org/buildbot/#/builders/60/builds/14031 

The problem remains for more than 3 days already. Would you fix it as soon as 
it possible or revert your changes?


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


[clang-tools-extra] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-25 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

I guess this ends up producing a CK_NoOp CastExpr?  That's probably okay, but 
can we amend the documentation for CK_NoOp to give this as an example?

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


[clang] [Sema] add cast from IncompleteArrayType to ConstantArrayType in TryReferenceListInitialization (PR #65918)

2023-09-25 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

I guess this ends up producing a CK_NoOp CastExpr?  That's probably okay, but 
can we amend the documentation for CK_NoOp to give this as an example?

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


[libunwind] [libunwind][nfc] Avoid type warning of debug printf (PR #67390)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-libunwind


Changes

Avoid type warning of debug printf since VE uses 64 bits SjLj.

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


1 Files Affected:

- (modified) libunwind/src/Unwind-sjlj.c (+12-6) 


``diff
diff --git a/libunwind/src/Unwind-sjlj.c b/libunwind/src/Unwind-sjlj.c
index 4d9a02699cddd78..f24088a0e98ae99 100644
--- a/libunwind/src/Unwind-sjlj.c
+++ b/libunwind/src/Unwind-sjlj.c
@@ -42,12 +42,18 @@ struct _Unwind_FunctionContext {
 
   // set by personality handler to be parameters passed to landing pad function
   uint64_tresumeParameters[4];
+
+  // specify format for debug dump of resumeLocation and resumeParameters[]
+#define SJLJ_PRI_PTR PRIxPTR
 #else
   // set by calling function before registering to be the landing pad
   uint32_tresumeLocation;
 
   // set by personality handler to be parameters passed to landing pad function
   uint32_tresumeParameters[4];
+
+  // specify format for debug dump of resumeLocation and resumeParameters[]
+#define SJLJ_PRI_PTR PRIuPTR
 #endif
 
   // set by calling function before registering
@@ -427,9 +433,9 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetGR(struct 
_Unwind_Context *context,
 /// Called by personality handler during phase 2 to alter register values.
 _LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context *context, int 
index,
  uintptr_t new_value) {
-  _LIBUNWIND_TRACE_API("_Unwind_SetGR(context=%p, reg=%d, value=0x%" PRIuPTR
-   ")",
-   (void *)context, index, new_value);
+  _LIBUNWIND_TRACE_API(
+  "_Unwind_SetGR(context=%p, reg=%d, value=0x%" SJLJ_PRI_PTR ")",
+  (void *)context, index, new_value);
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   ufc->resumeParameters[index] = new_value;
 }
@@ -438,7 +444,7 @@ _LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context 
*context, int index,
 /// Called by personality handler during phase 2 to get instruction pointer.
 _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIP(struct _Unwind_Context *context) {
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
-  _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" PRIu32,
+  _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" SJLJ_PRI_PTR,
(void *)context, ufc->resumeLocation + 1);
   return ufc->resumeLocation + 1;
 }
@@ -451,7 +457,7 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct 
_Unwind_Context *context,
   int *ipBefore) {
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   *ipBefore = 0;
-  _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p, %p) => 0x%" PRIu32,
+  _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p, %p) => 0x%" SJLJ_PRI_PTR,
(void *)context, (void *)ipBefore,
ufc->resumeLocation + 1);
   return ufc->resumeLocation + 1;
@@ -461,7 +467,7 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct 
_Unwind_Context *context,
 /// Called by personality handler during phase 2 to alter instruction pointer.
 _LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *context,
  uintptr_t new_value) {
-  _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%" PRIuPTR ")",
+  _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%" SJLJ_PRI_PTR ")",
(void *)context, new_value);
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   ufc->resumeLocation = new_value - 1;

``




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


[libunwind] [libunwind][nfc] Avoid type warning of debug printf (PR #67390)

2023-09-25 Thread Kazushi Marukawa via cfe-commits

https://github.com/kaz7 created https://github.com/llvm/llvm-project/pull/67390

Avoid type warning of debug printf since VE uses 64 bits SjLj.

>From 18e3568db4a3a11c794f077e9effd0a713dbd2dc Mon Sep 17 00:00:00 2001
From: "Kazushi (Jam) Marukawa" 
Date: Sun, 24 Sep 2023 08:08:24 +0200
Subject: [PATCH] [libunwind][nfc] Avoid type warning of debug printf

Avoid type warning of debug printf since VE uses 64 bits SjLj.
---
 libunwind/src/Unwind-sjlj.c | 18 --
 1 file changed, 12 insertions(+), 6 deletions(-)

diff --git a/libunwind/src/Unwind-sjlj.c b/libunwind/src/Unwind-sjlj.c
index 4d9a02699cddd78..f24088a0e98ae99 100644
--- a/libunwind/src/Unwind-sjlj.c
+++ b/libunwind/src/Unwind-sjlj.c
@@ -42,12 +42,18 @@ struct _Unwind_FunctionContext {
 
   // set by personality handler to be parameters passed to landing pad function
   uint64_tresumeParameters[4];
+
+  // specify format for debug dump of resumeLocation and resumeParameters[]
+#define SJLJ_PRI_PTR PRIxPTR
 #else
   // set by calling function before registering to be the landing pad
   uint32_tresumeLocation;
 
   // set by personality handler to be parameters passed to landing pad function
   uint32_tresumeParameters[4];
+
+  // specify format for debug dump of resumeLocation and resumeParameters[]
+#define SJLJ_PRI_PTR PRIuPTR
 #endif
 
   // set by calling function before registering
@@ -427,9 +433,9 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetGR(struct 
_Unwind_Context *context,
 /// Called by personality handler during phase 2 to alter register values.
 _LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context *context, int 
index,
  uintptr_t new_value) {
-  _LIBUNWIND_TRACE_API("_Unwind_SetGR(context=%p, reg=%d, value=0x%" PRIuPTR
-   ")",
-   (void *)context, index, new_value);
+  _LIBUNWIND_TRACE_API(
+  "_Unwind_SetGR(context=%p, reg=%d, value=0x%" SJLJ_PRI_PTR ")",
+  (void *)context, index, new_value);
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   ufc->resumeParameters[index] = new_value;
 }
@@ -438,7 +444,7 @@ _LIBUNWIND_EXPORT void _Unwind_SetGR(struct _Unwind_Context 
*context, int index,
 /// Called by personality handler during phase 2 to get instruction pointer.
 _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIP(struct _Unwind_Context *context) {
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
-  _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" PRIu32,
+  _LIBUNWIND_TRACE_API("_Unwind_GetIP(context=%p) => 0x%" SJLJ_PRI_PTR,
(void *)context, ufc->resumeLocation + 1);
   return ufc->resumeLocation + 1;
 }
@@ -451,7 +457,7 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct 
_Unwind_Context *context,
   int *ipBefore) {
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   *ipBefore = 0;
-  _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p, %p) => 0x%" PRIu32,
+  _LIBUNWIND_TRACE_API("_Unwind_GetIPInfo(context=%p, %p) => 0x%" SJLJ_PRI_PTR,
(void *)context, (void *)ipBefore,
ufc->resumeLocation + 1);
   return ufc->resumeLocation + 1;
@@ -461,7 +467,7 @@ _LIBUNWIND_EXPORT uintptr_t _Unwind_GetIPInfo(struct 
_Unwind_Context *context,
 /// Called by personality handler during phase 2 to alter instruction pointer.
 _LIBUNWIND_EXPORT void _Unwind_SetIP(struct _Unwind_Context *context,
  uintptr_t new_value) {
-  _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%" PRIuPTR ")",
+  _LIBUNWIND_TRACE_API("_Unwind_SetIP(context=%p, value=0x%" SJLJ_PRI_PTR ")",
(void *)context, new_value);
   _Unwind_FunctionContext_t ufc = (_Unwind_FunctionContext_t) context;
   ufc->resumeLocation = new_value - 1;

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


[clang] [llvm][tblgen] Add `Source Filename` for `emitSourceFileHeader` (PR #65744)

2023-09-25 Thread Shao-Ce SUN via cfe-commits
" + sys::path::filename(Record.getInputFilename()),"
In-Reply-To: 


https://github.com/sunshaoce updated 
https://github.com/llvm/llvm-project/pull/65744

>From 8fd7007fa437a0eefb66015861f76f65095c31bc Mon Sep 17 00:00:00 2001
From: Shao-Ce SUN 
Date: Sat, 23 Sep 2023 11:38:33 +0800
Subject: [PATCH 1/3] [llvm][tblgen] Add `SourcePath` for
 `emitSourceFileHeader`

---
 llvm/include/llvm/TableGen/TableGenBackend.h | 3 ++-
 llvm/lib/TableGen/TableGenBackend.cpp| 7 ++-
 llvm/utils/TableGen/VTEmitter.cpp| 3 ++-
 3 files changed, 10 insertions(+), 3 deletions(-)

diff --git a/llvm/include/llvm/TableGen/TableGenBackend.h 
b/llvm/include/llvm/TableGen/TableGenBackend.h
index 39f1e14bc950841..7bbd163b0433aca 100644
--- a/llvm/include/llvm/TableGen/TableGenBackend.h
+++ b/llvm/include/llvm/TableGen/TableGenBackend.h
@@ -50,7 +50,8 @@ template  class OptClass : Opt {
 
 /// emitSourceFileHeader - Output an LLVM style file header to the specified
 /// raw_ostream.
-void emitSourceFileHeader(StringRef Desc, raw_ostream );
+void emitSourceFileHeader(StringRef Desc, raw_ostream ,
+  StringRef SourcePath = "");
 
 } // End llvm namespace
 
diff --git a/llvm/lib/TableGen/TableGenBackend.cpp 
b/llvm/lib/TableGen/TableGenBackend.cpp
index 705c3a17a765750..164443a347dcc53 100644
--- a/llvm/lib/TableGen/TableGenBackend.cpp
+++ b/llvm/lib/TableGen/TableGenBackend.cpp
@@ -40,7 +40,8 @@ static void printLine(raw_ostream , const Twine , 
char Fill,
   OS << Suffix << '\n';
 }
 
-void llvm::emitSourceFileHeader(StringRef Desc, raw_ostream ) {
+void llvm::emitSourceFileHeader(StringRef Desc, raw_ostream ,
+StringRef SourcePath) {
   printLine(OS, "/*===- TableGen'erated file ", '-', "*- C++ -*-===*\\");
   StringRef Prefix("|* ");
   StringRef Suffix(" *|");
@@ -59,4 +60,8 @@ void llvm::emitSourceFileHeader(StringRef Desc, raw_ostream 
) {
   printLine(OS, Prefix, ' ', Suffix);
   printLine(OS, "\\*===", '-', "===*/");
   OS << '\n';
+
+  // Print the path of source file
+  if (!SourcePath.empty())
+OS << "// Generated from: " << SourcePath << "\n\n";
 }
diff --git a/llvm/utils/TableGen/VTEmitter.cpp 
b/llvm/utils/TableGen/VTEmitter.cpp
index d398a7e7b58f40a..03fa3d64b41fe6c 100644
--- a/llvm/utils/TableGen/VTEmitter.cpp
+++ b/llvm/utils/TableGen/VTEmitter.cpp
@@ -30,7 +30,8 @@ class VTEmitter {
 } // End anonymous namespace.
 
 void VTEmitter::run(raw_ostream ) {
-  emitSourceFileHeader("ValueTypes Source Fragment", OS);
+  emitSourceFileHeader("ValueTypes Source Fragment", OS,
+   Records.getInputFilename());
 
   std::array VTsByNumber = {};
   auto ValueTypes = Records.getAllDerivedDefinitions("ValueType");

>From 0d138680a7d663b8373834223cc6665dc9e3a6ba Mon Sep 17 00:00:00 2001
From: Shao-Ce SUN 
Date: Sun, 24 Sep 2023 00:52:02 +0800
Subject: [PATCH 2/3] add more tests

---
 clang/utils/TableGen/ClangASTNodesEmitter.cpp |  4 +-
 .../TableGen/ClangASTPropertiesEmitter.cpp|  8 ++--
 clang/utils/TableGen/ClangAttrEmitter.cpp | 48 +++
 .../ClangCommentCommandInfoEmitter.cpp| 10 ++--
 ...mentHTMLNamedCharacterReferenceEmitter.cpp |  5 +-
 .../TableGen/ClangCommentHTMLTagsEmitter.cpp  |  4 +-
 .../TableGen/ClangOpenCLBuiltinEmitter.cpp|  6 +--
 clang/utils/TableGen/ClangSyntaxEmitter.cpp   |  4 +-
 .../utils/TableGen/ClangTypeNodesEmitter.cpp  |  2 +-
 lldb/utils/TableGen/LLDBOptionDefEmitter.cpp  |  2 +-
 .../utils/TableGen/LLDBPropertyDefEmitter.cpp |  4 +-
 llvm/include/llvm/TableGen/TableGenBackend.h  |  3 +-
 llvm/lib/TableGen/TableGenBackend.cpp |  6 +--
 llvm/utils/TableGen/AsmMatcherEmitter.cpp |  2 +-
 llvm/utils/TableGen/AsmWriterEmitter.cpp  |  2 +-
 llvm/utils/TableGen/VTEmitter.cpp |  3 +-
 mlir/tools/mlir-tblgen/DialectGen.cpp |  4 +-
 mlir/tools/mlir-tblgen/EnumsGen.cpp   |  4 +-
 mlir/tools/mlir-tblgen/LLVMIRIntrinsicGen.cpp |  2 +-
 mlir/tools/mlir-tblgen/OpDefinitionsGen.cpp   |  4 +-
 mlir/tools/mlir-tblgen/RewriterGen.cpp|  2 +-
 mlir/tools/mlir-tblgen/SPIRVUtilsGen.cpp  | 22 +
 22 files changed, 81 insertions(+), 70 deletions(-)

diff --git a/clang/utils/TableGen/ClangASTNodesEmitter.cpp 
b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
index 2b8d7a9efdf10c9..16a1c74b9d91ad6 100644
--- a/clang/utils/TableGen/ClangASTNodesEmitter.cpp
+++ b/clang/utils/TableGen/ClangASTNodesEmitter.cpp
@@ -169,7 +169,7 @@ void ClangASTNodesEmitter::deriveChildTree() {
 void ClangASTNodesEmitter::run(raw_ostream ) {
   deriveChildTree();
 
-  emitSourceFileHeader("List of AST nodes of a particular kind", OS);
+  emitSourceFileHeader("List of AST nodes of a particular kind", OS, Records);
 
   // Write the preamble
   OS << "#ifndef ABSTRACT_" << macroHierarchyName() << "\n";
@@ -205,7 +205,7 @@ void clang::EmitClangASTNodes(RecordKeeper , raw_ostream 
,
 void clang::EmitClangDeclContext(RecordKeeper , raw_ostream ) {
   // FIXME: 

[clang] [llvm][tblgen] Add `Source Filename` for `emitSourceFileHeader` (PR #65744)

2023-09-25 Thread Shao-Ce SUN via cfe-commits
" + sys::path::filename(Record.getInputFilename()),"
In-Reply-To: 


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


[clang] c84f9f9 - Reformat

2023-09-25 Thread NAKAMURA Takumi via cfe-commits

Author: NAKAMURA Takumi
Date: 2023-09-26T12:29:21+09:00
New Revision: c84f9f9a81e496acbef0855cbbb0858c817576dc

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

LOG: Reformat

Added: 


Modified: 
clang/utils/TableGen/ClangAttrEmitter.cpp
clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
llvm/lib/TableGen/TableGenBackend.cpp

Removed: 




diff  --git a/clang/utils/TableGen/ClangAttrEmitter.cpp 
b/clang/utils/TableGen/ClangAttrEmitter.cpp
index 7ea09058c3d39f2..00bcbe1153518c8 100644
--- a/clang/utils/TableGen/ClangAttrEmitter.cpp
+++ b/clang/utils/TableGen/ClangAttrEmitter.cpp
@@ -3587,7 +3587,8 @@ void EmitClangAttrHasAttrImpl(RecordKeeper , 
raw_ostream ) {
 
 void EmitClangAttrSpellingListIndex(RecordKeeper , raw_ostream ) {
   emitSourceFileHeader("Code to translate 
diff erent attribute spellings "
-   "into internal identifiers", OS);
+   "into internal identifiers",
+   OS);
 
   OS << "  switch (getParsedKind()) {\n";
   OS << "case IgnoredAttribute:\n";
@@ -4680,8 +4681,7 @@ void EmitClangAttrNodeTraverse(RecordKeeper , 
raw_ostream ) {
   }
 }
 
-void EmitClangAttrParserStringSwitches(RecordKeeper ,
-   raw_ostream ) {
+void EmitClangAttrParserStringSwitches(RecordKeeper , raw_ostream ) 
{
   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
   emitClangAttrArgContextList(Records, OS);
   emitClangAttrIdentifierArgList(Records, OS);

diff  --git a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp 
b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
index a988a5631acabce..a70e95408c89292 100644
--- a/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentCommandInfoEmitter.cpp
@@ -20,9 +20,11 @@
 
 using namespace llvm;
 
-void clang::EmitClangCommentCommandInfo(RecordKeeper , raw_ostream 
) {
+void clang::EmitClangCommentCommandInfo(RecordKeeper ,
+raw_ostream ) {
   emitSourceFileHeader("A list of commands useable in documentation "
-   "comments", OS);
+   "comments",
+   OS);
 
   OS << "namespace {\n"
 "const CommandInfo Commands[] = {\n";
@@ -112,9 +114,11 @@ static std::string MangleName(StringRef Str) {
   return Mangled;
 }
 
-void clang::EmitClangCommentCommandList(RecordKeeper , raw_ostream 
) {
+void clang::EmitClangCommentCommandList(RecordKeeper ,
+raw_ostream ) {
   emitSourceFileHeader("A list of commands useable in documentation "
-   "comments", OS);
+   "comments",
+   OS);
 
   OS << "#ifndef COMMENT_COMMAND\n"
  << "#  define COMMENT_COMMAND(NAME)\n"

diff  --git 
a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp 
b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
index 15671a99a3fc217..04c6275304795ad 100644
--- a/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLNamedCharacterReferenceEmitter.cpp
@@ -71,7 +71,8 @@ void 
clang::EmitClangCommentHTMLNamedCharacterReferences(RecordKeeper ,
   }
 
   emitSourceFileHeader("HTML named character reference to UTF-8 "
-   "translation", OS);
+   "translation",
+   OS);
 
   OS << "StringRef translateHTMLNamedCharacterReferenceToUTF8(\n"
 " StringRef Name) {\n";

diff  --git a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp 
b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
index 78bbbd1cba57668..a3a124f10f76e8a 100644
--- a/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
+++ b/clang/utils/TableGen/ClangCommentHTMLTagsEmitter.cpp
@@ -61,4 +61,3 @@ void clang::EmitClangCommentHTMLTagsProperties(RecordKeeper 
,
   OS << "  return false;\n"
  << "}\n\n";
 }
-

diff  --git a/llvm/lib/TableGen/TableGenBackend.cpp 
b/llvm/lib/TableGen/TableGenBackend.cpp
index 135ec643bc3a7df..705c3a17a765750 100644
--- a/llvm/lib/TableGen/TableGenBackend.cpp
+++ b/llvm/lib/TableGen/TableGenBackend.cpp
@@ -55,7 +55,7 @@ void llvm::emitSourceFileHeader(StringRef Desc, raw_ostream 
) {
   } while (Pos < Desc.size());
   printLine(OS, Prefix, ' ', Suffix);
   printLine(OS, Prefix + "Automatically generated file, do not edit!", ' ',
-Suffix);
+Suffix);
   printLine(OS, Prefix, ' ', Suffix);
   printLine(OS, "\\*===", '-', "===*/");
   OS << '\n';




[clang] [llvm][tblgen] Add `SourcePath` for `emitSourceFileHeader` (PR #65744)

2023-09-25 Thread NAKAMURA Takumi via cfe-commits
" + sys::path::filename(Record.getInputFilename()),"
In-Reply-To: 


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

Looks good. 
At the moment, this doesn't emit `path` but `file name`.
Since I'll push reformatting, could you rebase, squash, and retitle before 
pushing?

I guess we could emit more fancy paths with `-I` include paths. It may be done 
in the future.

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


[PATCH] D147844: [clang][Sema]Print diagnostic warning about precedence when integer expression is used without parentheses in an conditional operator expression

2023-09-25 Thread NagaChaitanya Vellanki via Phabricator via cfe-commits
chaitanyav updated this revision to Diff 557346.
chaitanyav added a comment.

Rebase with upstream and update code as per comments


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D147844/new/

https://reviews.llvm.org/D147844

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Analysis/uninit-vals.c
  clang/test/Sema/integer-overflow.c
  clang/test/Sema/parentheses.c
  clang/test/Sema/parentheses.cpp
  clang/test/SemaCXX/array-bounds.cpp
  clang/test/SemaCXX/integer-overflow.cpp
  libcxx/include/__chrono/duration.h
  libcxx/include/strstream
  libcxx/test/libcxx/algorithms/nth_element_stability.pass.cpp
  libcxx/test/libcxx/algorithms/partial_sort_stability.pass.cpp
  libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
  libcxxabi/src/cxa_personality.cpp

Index: libcxxabi/src/cxa_personality.cpp
===
--- libcxxabi/src/cxa_personality.cpp
+++ libcxxabi/src/cxa_personality.cpp
@@ -718,9 +718,7 @@
 if (actionEntry == 0)
 {
 // Found a cleanup
-results.reason = actions & _UA_SEARCH_PHASE
- ? _URC_CONTINUE_UNWIND
- : _URC_HANDLER_FOUND;
+results.reason = (actions & _UA_SEARCH_PHASE) ? _URC_CONTINUE_UNWIND : _URC_HANDLER_FOUND;
 return;
 }
 // Convert 1-based byte offset into
@@ -832,9 +830,8 @@
 // End of action list. If this is phase 2 and we have found
 // a cleanup (ttypeIndex=0), return _URC_HANDLER_FOUND;
 // otherwise return _URC_CONTINUE_UNWIND.
-results.reason = hasCleanup && actions & _UA_CLEANUP_PHASE
- ? _URC_HANDLER_FOUND
- : _URC_CONTINUE_UNWIND;
+results.reason =
+(hasCleanup && (actions & _UA_CLEANUP_PHASE)) ? _URC_HANDLER_FOUND : _URC_CONTINUE_UNWIND;
 return;
 }
 // Go to next action
@@ -1250,10 +1247,9 @@
 {
 const __shim_type_info* excpType =
 static_cast(new_exception_header->exceptionType);
-adjustedPtr =
-__getExceptionClass(_exception_header->unwindHeader) == kOurDependentExceptionClass ?
-((__cxa_dependent_exception*)new_exception_header)->primaryException :
-new_exception_header + 1;
+adjustedPtr = (__getExceptionClass(_exception_header->unwindHeader) == kOurDependentExceptionClass)
+  ? ((__cxa_dependent_exception*)new_exception_header)->primaryException
+  : new_exception_header + 1;
 if (!exception_spec_can_catch(ttypeIndex, classInfo, ttypeEncoding,
   excpType, adjustedPtr,
   unwind_exception, base))
Index: libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
===
--- libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
+++ libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
@@ -32,7 +32,7 @@
   std::vector v;
   v.resize(kSize);
   for (int i = 0; i < kSize; ++i) {
-v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1);
+v[i].value = kSize / 2 - i * ((i % 2) ? -1 : 1);
   }
   std::less comp;
   std::__sort_dispatch(v.begin(), v.end(), comp);
@@ -44,7 +44,7 @@
   std::vector v;
   v.resize(kSize);
   for (int i = 0; i < kSize; ++i) {
-v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1);
+v[i].value = kSize / 2 - i * ((i % 2) ? -1 : 1);
   }
   auto deterministic_v = deterministic();
   std::sort(v.begin(), v.end());
@@ -62,7 +62,7 @@
   std::vector v;
   v.resize(kSize);
   for (int i = 0; i < kSize; ++i) {
-v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1);
+v[i].value = kSize / 2 - i * ((i % 2) ? -1 : 1);
   }
   auto snapshot_v = v;
   auto snapshot_custom_v = v;
Index: libcxx/test/libcxx/algorithms/partial_sort_stability.pass.cpp
===
--- libcxx/test/libcxx/algorithms/partial_sort_stability.pass.cpp
+++ libcxx/test/libcxx/algorithms/partial_sort_stability.pass.cpp
@@ -32,7 +32,7 @@
   std::vector v;
   v.resize(kSize);
   for (int i = 0; i < kSize; ++i) {
-v[i].value = (i % 2 ? 1 : kSize / 2 + i);
+v[i].value = ((i % 2) ? 1 : kSize / 2 + i);
   }
   auto comp = std::less();
   std::__partial_sort_impl(v.begin(), v.begin() + kSize / 2, v.end(), comp);
@@ -44,7 +44,7 @@
   std::vector v;
   v.resize(kSize);
   for (int i = 0; i < kSize; ++i) {
-v[i].value = (i % 2 ? 1 : kSize / 2 + i);
+v[i].value = ((i % 2) ? 1 : kSize / 2 + i);
   }
   auto 

[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-09-25 Thread Jim Lin via cfe-commits


@@ -165,6 +167,10 @@ def SP : GPRRegisterClass<(add X2)>;
 def SR07 : GPRRegisterClass<(add (sequence "X%u", 8, 9),
  (sequence "X%u", 18, 23))>;
 
+def GPRRA : RegisterClass<"RISCV", [XLenVT], 32, (add X1, X5)> {

tclin914 wrote:

Is GPRX1X5 better?

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


[PATCH] D158641: [AArch64] Fix FMV ifunc resolver usage on old Android APIs. Rename internal compiler-rt FMV functions.

2023-09-25 Thread Elliott Hughes via Phabricator via cfe-commits
enh accepted this revision.
enh added a comment.

yeah, lgtm from the Android side too, unless rprichard has more comments?


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158641/new/

https://reviews.llvm.org/D158641

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


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

2023-09-25 Thread Felix via cfe-commits


@@ -116,6 +116,10 @@ std::pair 
PPCXCOFFObjectWriter::getRelocTypeAndSignSize(
   return {XCOFF::RelocationType::R_TLS_IE, SignAndSizeForFKData};
 case MCSymbolRefExpr::VK_PPC_AIX_TLSLE:
   return {XCOFF::RelocationType::R_TLS_LE, SignAndSizeForFKData};
+case MCSymbolRefExpr::VK_PPC_AIX_TLSLD:

orcguru wrote:

I think there could be concern regarding this setting, and I observed obj 
output and the asm-as output is a little bit different on "IsSigned" setting on 
relocations for symbol ".__tls_get_mod", for example:

obj mode output processed by "llvm-readobj --relocs --expand-relocs"
```
  Section (index: 1) .text {
Relocation {
  Virtual Address: 0xE
  Symbol: _$TLSML (11)
  IsSigned: No
  FixupBitValue: 0
  Length: 16
  Type: R_TOC (0x3)
}
Relocation {
  Virtual Address: 0x10
  Symbol: .__tls_get_mod (1)
  IsSigned: No
  FixupBitValue: 0
  Length: 26
  Type: R_RBA (0x18)
}
Relocation {
  Virtual Address: 0x16
  Symbol: a (13)
  IsSigned: No
  FixupBitValue: 0
  Length: 16
  Type: R_TOC (0x3)
}
...
```

asm mode output assembled by "as -a64 -many ", and then processed by 
"llvm-readobj --relocs --expand-relocs"
```
  Section (index: 1) .text {
Relocation {
  Virtual Address: 0x16
  Symbol: a (13)
  IsSigned: No
  FixupBitValue: 0
  Length: 16
  Type: R_TOC (0x3)
}
Relocation {
  Virtual Address: 0x1A
  Symbol: _$TLSML (15)
  IsSigned: No
  FixupBitValue: 0
  Length: 16
  Type: R_TOC (0x3)
}
Relocation {
  Virtual Address: 0x1C
  Symbol: .__tls_get_mod (3)
  IsSigned: Yes
  FixupBitValue: 0
  Length: 26
  Type: R_RBA (0x18)
}
...
```

Notice they have different setting regarding "IsSigned" on the relocation for 
the ".__tls_get_mod" symbol.

I took another look into the behavior of general-dynamic, and then I saw the 
same difference there:

obj mode
```
Relocation {
  Virtual Address: 0x1C
  Symbol: .__tls_get_addr (1)
  IsSigned: No
  FixupBitValue: 0
  Length: 26
  Type: R_RBA (0x18)
}
```

asm mode
```
Relocation {
  Virtual Address: 0x1C
  Symbol: .__tls_get_addr (3)
  IsSigned: Yes
  FixupBitValue: 0
  Length: 26
  Type: R_RBA (0x18)
}
```

Looks like LD is aligned with GD in this particular behavior, so this may not 
be an issue.

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


[libunwind] [runtimes] Remove explicit -isysroot from the testing configurations on macOS (PR #66265)

2023-09-25 Thread Petr Hosek via cfe-commits

petrhosek wrote:

> How do you build on Apple platforms then? Don't you need access to a SDK? I'm 
> a bit confused about what you're doing -- do you need to use the native 
> platform SDK when you're building Fuchsia? What SDK are you passing as 
> `--sysroot` when testing libc++?

We use `-isysroot` with the Xcode SDK. That doesn't require selecting active 
developer directory. You only need to select active developer directory if you 
are going to run binaries from the Xcode SDK (or other binaries that assume so 
like `xcrun`) which we don't since all our tools come from LLVM.

In the future, we hope to switch to LLVM libc on all platforms to make our 
build truly hermetic. At that point, we won't be using Xcode SDK at all and at 
that point forcing the use of `xcrun` is going to be even more undesirable.

> I know that, but as I already explained over in 
> https://reviews.llvm.org/D151056, making everyone's config more complicated 
> isn't the path we want to take. We should never have been setting the 
> sysroot, it was only a workaround for 
> https://gitlab.kitware.com/cmake/cmake/-/issues/19180 and that should have 
> been done another way initially.
>
> These config files were designed to be really simple and to be easily created 
> for custom needs. This was an answer to the incredible amount of 
> platform-specific complexity that the previous test configuration system had, 
> and what I'm doing right now is push back to avoid going down that path again.

That's reasonable, but these configs still implicitly encode assumptions, such 
as the fact your host environment is usable for building binaries. For example, 
if you don't specify `--sysroot=`, the compiler will use `/`, but if your host 
sysroot doesn't have the necessary files (i.e. headers and libraries), building 
tests will fail.

In our case, the fact that the host environment isn't usable for building 
binaries is intentional, we always build against an explicit sysroot (using 
`--sysroot`, `-isysroot` or `/winsysroot` depending on a platform) to ensure 
our build is hermetic as was suggested in 
https://blog.llvm.org/2019/11/deterministic-builds-with-clang-and-lld.html, see 
the "Getting to universal determinism" which says:

>  Getting to universal determinism
> You then need to modify your build files to use `--sysroot` (Linux), 
> `-isysroot` (macOS), `-imsvc` (Windows) to use these hermetic SDKs for 
> builds. They need to be somewhere below your source root to not regress build 
> directory name invariance.
> You also want to make sure your build doesn’t depend on environment 
> variables, as already mentioned in the “Getting to incremental determinism”, 
> since environments between different machines can be very different and 
> difficult to control.

> Is there a reason why you don't have a `fuchsia-*.cfg.in` configuration file?

We plan to introduce one, but this issue is not about building and running 
tests on Fuchsia, the issue is building and running tests for other platforms 
we build and distribute runtimes for like Linux, macOS and Windows.

> > We also need to restrict the `xcrun` change only to `apple-*.cfg.in` 
> > configurations.
> 
> No, it is needed whenever the build host is an Apple platform, which is more 
> general than the `apple-*.cfg.in` configurations. The normal LLVM 
> configuration also needs to run under xcrun when it is being built on macOS, 
> cause that's how you get to the SDK.

You seem to be assuming there's a single way to build the binaries for any 
given platform, but that's generally not the case:

* On macOS, you can either (1) run the binary under `xcrun`, which sets the 
`SDKROOT` environment variable, or you can (2) use the `-isysroot` flag. These 
can be used interchangeably, see: 
https://github.com/llvm/llvm-project/blob/5d86176f4868771527e2b7469c1bc87f09c96f0a/clang/lib/Driver/ToolChains/Darwin.cpp#L2144-L2161
* On Windows, you can (1) set the environment variables by running the 
`vcvars*.bat` file that's provided by VS SDK, or you can (2) use the 
`/winsysroot` flag which was created to simplify using hermetic SDK and avoid 
relying on environment variables: https://reviews.llvm.org/D95534

I'm fine choosing picking defaults, like using `xcrun`, but I don't think we 
should be forcing those onto all users with no way to opt out as is currently 
the case in this patch.

> I will land this tomorrow unless there is additional discussion. It looks 
> like #67201 would allow you to solve your problem without creating a custom 
> `.cfg.in` file, which is great. But even regardless of #67201, the intended 
> way to use the libc++ test suite is to create a `.cfg.in` file that suits 
> your needs if the general ones don't, not to add more configuration options 
> to the general ones.

#67201 is an improvement but is not an idiomatic CMake. The idiomatic way to 
set sysroot in CMake is through `CMAKE_SYSROOT=/path/to/sysroot`, not 
`CMAKE_CXX_FLAGS_INIT="--sysroot=/path/to/sysroot"`. 

[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Richard Smith via cfe-commits


@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}

zygoloid wrote:

or maybe https://godbolt.org/z/sEjTM5z31

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


[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Richard Smith via cfe-commits


@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}

zygoloid wrote:

https://godbolt.org/z/fKjTzfG6v is the best I've found so far.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits

erichkeane wrote:

> So it looks like this breaks the ast-dump-attr.cpp test, so that needs fixing.
> 
> Also, there is quite a bit of changes happening around the SemaDeclAttr.cpp 
> changes by @AaronBallman, so the two need to be merged in some way.

"Merged" could be: 1-rebased on the other, but ONE Of the two things needs to 
happen.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -2352,26 +2352,37 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t priority = Attr::DefaultPriority;
+  Expr *E = nullptr;
+  if (AL.getNumArgs()) {

erichkeane wrote:

We also should ensure we don't have more than 1 argument.


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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -5661,10 +5662,20 @@ void 
CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
   setNonAliasAttributes(GD, Fn);
   SetLLVMFunctionAttributesForDefinition(D, Fn);
 
-  if (const ConstructorAttr *CA = D->getAttr())
-AddGlobalCtor(Fn, CA->getPriority());
+  auto getPrio = [this](auto *Attr) -> int {
+Expr *E = Attr->getPriority();
+if (!E)
+  return Attr->DefaultPriority;
+if (auto CE = E->getIntegerConstantExpr(getContext()))
+  return CE->getExtValue();
+return Attr->DefaultPriority;

erichkeane wrote:

This condition seems to me should be an assertion, right?  

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -1422,9 +1424,11 @@ def Deprecated : InheritableAttr {
 
 def Destructor : InheritableAttr {
   let Spellings = [GCC<"destructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];

erichkeane wrote:

```suggestion
  let AdditionalMembers = [{ static constexpr int DefaultPriority = 65535; }];
```

Also wonder if these should be `unsigned`?

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits

https://github.com/erichkeane commented:

So it looks like this breaks the ast-dump-attr.cpp test, so that needs fixing.

Also, there is quite a bit of changes happening around the SemaDeclAttr.cpp 
changes by @AaronBallman, so the two need to be merged in some way.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -10,3 +13,14 @@ struct Foo {
 bar();
   }
 };
+
+template 

erichkeane wrote:

Please write a test where the argument is NTTP dependent on another template 
argument.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -1156,9 +1156,11 @@ def ConstInit : InheritableAttr {
 
 def Constructor : InheritableAttr {
   let Spellings = [GCC<"constructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];

erichkeane wrote:

@AaronBallman : I see in your other patch (#67360) you're using this as a magic 
number!  Might be useful to get on the same page as this author.
```suggestion
  let AdditionalMembers = [{ static constexpr int DefaultPriority = 65535; }];
```

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Erich Keane via cfe-commits

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


[clang] [Driver] Move assertion check before checking Output.isFilename (PR #67210)

2023-09-25 Thread Brad Smith via cfe-commits

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


[clang] 8a4b9e9 - [Driver] Move assertion check before checking Output.isFilename (#67210)

2023-09-25 Thread via cfe-commits

Author: Brad Smith
Date: 2023-09-25T20:19:25-04:00
New Revision: 8a4b9e9965dfdc7758153341561ff1e457a5346c

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

LOG: [Driver] Move assertion check before checking Output.isFilename (#67210)

Added: 


Modified: 
clang/lib/Driver/ToolChains/Cuda.cpp
clang/lib/Driver/ToolChains/DragonFly.cpp
clang/lib/Driver/ToolChains/Flang.cpp
clang/lib/Driver/ToolChains/FreeBSD.cpp
clang/lib/Driver/ToolChains/Gnu.cpp
clang/lib/Driver/ToolChains/Hexagon.cpp
clang/lib/Driver/ToolChains/NetBSD.cpp
clang/lib/Driver/ToolChains/OpenBSD.cpp
clang/lib/Driver/ToolChains/PS4CPU.cpp
clang/lib/Driver/ToolChains/Solaris.cpp
clang/lib/Driver/ToolChains/XCore.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/Cuda.cpp 
b/clang/lib/Driver/ToolChains/Cuda.cpp
index 97472a302715bb9..e95ff98e6c940f1 100644
--- a/clang/lib/Driver/ToolChains/Cuda.cpp
+++ b/clang/lib/Driver/ToolChains/Cuda.cpp
@@ -572,14 +572,14 @@ void NVPTX::Linker::ConstructJob(Compilation , const 
JobAction ,
  const char *LinkingOutput) const {
   const auto  =
   static_cast(getToolChain());
+  ArgStringList CmdArgs;
+
   assert(TC.getTriple().isNVPTX() && "Wrong platform");
 
-  ArgStringList CmdArgs;
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
-  } else {
-assert(Output.isNothing() && "Invalid output.");
   }
 
   if (mustEmitDebugInfo(Args) == EmitSameDebugInfoAsHost)

diff  --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 82c975990a32511..a1e4937231572b7 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -85,11 +85,10 @@ void dragonfly::Linker::ConstructJob(Compilation , const 
JobAction ,
 CmdArgs.push_back("elf_i386");
   }
 
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
-  } else {
-assert(Output.isNothing() && "Invalid output.");
   }
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 11c9d90c701f0ce..10f785ce7ab9075 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -565,11 +565,10 @@ void Flang::ConstructJob(Compilation , const JobAction 
,
 }
   }
 
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
-  } else {
-assert(Output.isNothing() && "Invalid output.");
   }
 
   assert(Input.isFilename() && "Invalid input.");

diff  --git a/clang/lib/Driver/ToolChains/FreeBSD.cpp 
b/clang/lib/Driver/ToolChains/FreeBSD.cpp
index 67a8bb863b3b6b0..ff4d94c56f0d0ff 100644
--- a/clang/lib/Driver/ToolChains/FreeBSD.cpp
+++ b/clang/lib/Driver/ToolChains/FreeBSD.cpp
@@ -227,11 +227,10 @@ void freebsd::Linker::ConstructJob(Compilation , const 
JobAction ,
 }
   }
 
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
-  } else {
-assert(Output.isNothing() && "Invalid output.");
   }
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,

diff  --git a/clang/lib/Driver/ToolChains/Gnu.cpp 
b/clang/lib/Driver/ToolChains/Gnu.cpp
index 1b4a94d72cc0a66..5949d9872c54f72 100644
--- a/clang/lib/Driver/ToolChains/Gnu.cpp
+++ b/clang/lib/Driver/ToolChains/Gnu.cpp
@@ -117,11 +117,11 @@ void tools::gcc::Common::ConstructJob(Compilation , 
const JobAction ,
 break;
   }
 
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 CmdArgs.push_back(Output.getFilename());
   } else {
-assert(Output.isNothing() && "Unexpected output");
 CmdArgs.push_back("-fsyntax-only");
   }
 

diff  --git a/clang/lib/Driver/ToolChains/Hexagon.cpp 
b/clang/lib/Driver/ToolChains/Hexagon.cpp
index 0d6980c003a72b5..e7dca1053dc8d8a 100644
--- a/clang/lib/Driver/ToolChains/Hexagon.cpp
+++ b/clang/lib/Driver/ToolChains/Hexagon.cpp
@@ -218,11 +218,11 @@ void hexagon::Assembler::ConstructJob(Compilation , 
const JobAction ,
 
   addSanitizerRuntimes(HTC, Args, CmdArgs);
 
+  assert((Output.isFilename() || Output.isNothing()) && "Invalid output.");
   if (Output.isFilename()) {
 CmdArgs.push_back("-o");
 

[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -2352,26 +2352,61 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
-static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
+static bool diagnoseInvalidPriority(Sema , uint32_t Priority,
+const ParsedAttr ,
+SourceLocation PriorityLoc) {
+  // Only perform the priority check if the attribute is outside of a system
+  // header. Values <= 100 are reserved for the implementation, and libc++
+  // benefits from being able to specify values in that range.
+  if ((Priority < 101 || Priority > 65535) &&
+  !S.getSourceManager().isInSystemHeader(A.getLoc())) {
+S.Diag(A.getLoc(), diag::err_attribute_argument_out_of_range)
+<< PriorityLoc << A << 101 << 65535;
+A.setInvalid();
+return true;
+  }
+  return false;
+}
+
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t Priority = CtorDtorAttr::DefaultPriority;
   if (S.getLangOpts().HLSL && AL.getNumArgs()) {
 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
 return;
   }
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
 
-  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
-}
+  // If we're given an argument for the priority, check that it's valid.
+  if (AL.getNumArgs()) {
+if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Priority))
+  return;
 
-static void handleDestructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = DestructorAttr::DefaultPriority;
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
+// Ensure the priority is in a reasonable range.
+if (diagnoseInvalidPriority(S, Priority, AL,
+AL.getArgAsExpr(0)->getExprLoc()))
+  return;
+  }
+
+  // Ensure the function we're attaching to is something that is sensible to
+  // automatically call before or after main(); it should accept no arguments
+  // and return no value (but it is not an error because it is theoretically
+  // possible to call the function during normal program execution and pass it
+  // valid values). It also cannot be a member function. We allow K C
+  // functions because that's a difficult edge case where it depends on how the
+  // function is defined as to whether it does or does not expect arguments.
+  auto *FD = cast(D);
+  if (!FD->getReturnType()->isVoidType() ||
+  (FD->hasPrototype() && FD->getNumParams() != 0)) {
+S.Diag(AL.getLoc(), diag::err_ctor_dtor_attr_on_non_void_func)
+<< AL << FD->getSourceRange();
 return;
+  } else if (auto *MD = dyn_cast(FD); MD && MD->isInstance()) {
+S.Diag(AL.getLoc(), diag::err_ctor_dtor_member_func)
+<< AL << FD->getSourceRange();
+return;
+  }
 
-  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
+  D->addAttr(::new (S.Context) CtorDtorAttr(S.Context, AL, Priority));

erichkeane wrote:

I thought we were preferring to use the AttrName::Create methods these days?  
Can we switch to that?

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


[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -2352,26 +2352,61 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
-static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
+static bool diagnoseInvalidPriority(Sema , uint32_t Priority,
+const ParsedAttr ,
+SourceLocation PriorityLoc) {
+  // Only perform the priority check if the attribute is outside of a system
+  // header. Values <= 100 are reserved for the implementation, and libc++
+  // benefits from being able to specify values in that range.
+  if ((Priority < 101 || Priority > 65535) &&
+  !S.getSourceManager().isInSystemHeader(A.getLoc())) {
+S.Diag(A.getLoc(), diag::err_attribute_argument_out_of_range)
+<< PriorityLoc << A << 101 << 65535;
+A.setInvalid();
+return true;
+  }
+  return false;
+}
+
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t Priority = CtorDtorAttr::DefaultPriority;
   if (S.getLangOpts().HLSL && AL.getNumArgs()) {
 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
 return;
   }
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
 
-  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
-}
+  // If we're given an argument for the priority, check that it's valid.
+  if (AL.getNumArgs()) {
+if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Priority))
+  return;
 
-static void handleDestructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = DestructorAttr::DefaultPriority;
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
+// Ensure the priority is in a reasonable range.
+if (diagnoseInvalidPriority(S, Priority, AL,
+AL.getArgAsExpr(0)->getExprLoc()))
+  return;
+  }
+
+  // Ensure the function we're attaching to is something that is sensible to
+  // automatically call before or after main(); it should accept no arguments
+  // and return no value (but it is not an error because it is theoretically
+  // possible to call the function during normal program execution and pass it
+  // valid values). It also cannot be a member function. We allow K C
+  // functions because that's a difficult edge case where it depends on how the
+  // function is defined as to whether it does or does not expect arguments.
+  auto *FD = cast(D);
+  if (!FD->getReturnType()->isVoidType() ||

erichkeane wrote:

As before, I think the 'no params' makes sense for obvious reasons.  I think 
making the 'non-void' should be a warning, and perhaps a 2nd warning if it is 
no-discard.

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


[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Erich Keane via cfe-commits


@@ -171,6 +171,11 @@ Attribute Changes in Clang
   automatic diagnostic to use parameters of types that the format style
   supports but that are never the result of default argument promotion, such as
   ``float``. (`#59824: `_)
+- The ``constructor`` and ``destructor`` attributes now diagnose when:
+  - the priority is not between 101 and 65535, inclusive,
+  - the function it is applied to accepts arguments or has a non-void return

erichkeane wrote:

I don't think the 'non-void' return type should be diagnosed unless it is 
'nodiscard'.  Marking something like 
'closeAllHandlesAndReturnAStatusIIntendToIgnore` as a destructor isn't harmful 
IMO.

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


[clang] Recommit "Implement [[msvc::no_unique_address]] (#65675)" (PR #67199)

2023-09-25 Thread Amy Huang via cfe-commits


@@ -1798,11 +1798,24 @@ def ArmMveStrictPolymorphism : TypeAttr, 
TargetSpecificAttr {
   let Documentation = [ArmMveStrictPolymorphismDocs];
 }
 
-def NoUniqueAddress : InheritableAttr, TargetSpecificAttr 
{
-  let Spellings = [CXX11<"", "no_unique_address", 201803>];
+def NoUniqueAddress : InheritableAttr {
+  let Subjects = SubjectList<[NonBitField], ErrorDiag>;
+  // No spellings because instances of this attribute are created by
+  // MSNoUniqueAddress and ItaniumNoUniqueAddress
+  let Spellings = [];
+  let Documentation = [InternalOnly];
+}
+
+def MSNoUniqueAddress : InheritableAttr, 
TargetSpecificAttr {
   let Subjects = SubjectList<[NonBitField], ErrorDiag>;
+  let Spellings = [CXX11<"msvc", "no_unique_address", 201803>];
+  let Documentation = [MSNoUniqueAddressDocs];
+}
+
+def ItaniumNoUniqueAddress : InheritableAttr, 
TargetSpecificAttr {

amykhuang wrote:

Yeah, that makes sense; would it be better to name it "NoUniqueAddress" and 
then name the "parent" attribute something like "NoUniqueAddressGroup"?

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


[clang] [Driver] Move assertion check before checking Output.isFilename (PR #67210)

2023-09-25 Thread Fangrui Song via cfe-commits

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


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


[clang] [clang][modules] Adopt `FileEntryRef` in the `HeaderFileInfo` block in PCM files (PR #67383)

2023-09-25 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 feb7b1914d513c709b9e024dfed709bb889cc853 
e2201a10fe76be3de8efd0faca0f381f504b08d3 -- 
clang/include/clang/Basic/FileManager.h clang/lib/Basic/FileManager.cpp 
clang/lib/Serialization/ASTWriter.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 1d939a3f5e7a..ef9d5462f1c7 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -2021,7 +2021,7 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch ) 
{
 // from a different module; in that case, we rely on the module(s)
 // containing the header to provide this information.
 const HeaderFileInfo *HFI =
-HS.getExistingFileInfo(*File, /*WantExternal*/!Chain);
+HS.getExistingFileInfo(*File, /*WantExternal*/ !Chain);
 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
   continue;
 
@@ -2037,12 +2037,13 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch 
) {
 
 bool Included = PP->alreadyIncluded(*File);
 
-HeaderFileInfoTrait::key_type Key = {
-  Filename, File->getSize(), getTimestampForOutput(*File)
-};
+HeaderFileInfoTrait::key_type Key = {Filename, File->getSize(),
+ getTimestampForOutput(*File)};
 HeaderFileInfoTrait::data_type Data = {
-  *HFI, Included, HS.getModuleMap().findResolvedModulesForHeader(*File), {}
-};
+*HFI,
+Included,
+HS.getModuleMap().findResolvedModulesForHeader(*File),
+{}};
 Generator.insert(Key, Data, GeneratorTrait);
 ++NumHeaderSearchEntries;
   }

``




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


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-25 Thread Pranav Kant via cfe-commits


@@ -1076,6 +1076,8 @@ static void InitializePredefinedMacros(const TargetInfo 
,
   DefineFloatMacros(Builder, "FLT", (), "F");
   DefineFloatMacros(Builder, "DBL", (), "");
   DefineFloatMacros(Builder, "LDBL", (), "L");
+  if (TI.hasFloat128Type())
+DefineFloatMacros(Builder, "FLT128", (), "Q");

pranavk wrote:

I am not adding any new float type or any literal suffix (unlike other revision 
you pointed by Ray). This is only adding float macros for which I modified the 
test that was expecting it.

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


[clang] [clang][modules] Adopt `FileEntryRef` in the `HeaderFileInfo` block in PCM files (PR #67383)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

This patch adopts `FileEntryRef` in the `HeaderFileInfo`-writing part of 
`ASTWriter`.

First, this patch removes the loop over `FileManager::VirtualFileEntries`. It's 
redundant, since all virtual file entries have a non-virtual/real counterpart 
that's already present in `UIDToFiles`.

Second, since we now no longer rely on 
`FileEntry::getLastRef()`/`FileEntry::getName()`, this patch takes care to 
establish which path gets used for each UID by picking the `FileEntryRef` with 
the most "``" name (instead of just relying on the `StringMap` iteration 
order).

Note that which `FileEntry`/`FileEntryRef` objects we pick for each UID for 
serialization into the `llvm::OnDiskChainedHashTable` doesn't really matter. 
The hash function only includes the file size and modification time. The file 
name only plays role during resolution of hash collisions, in which case it 
goes through `FileManager` and resolves to a `FileEntry` that gets 
pointer-compared with the queried `FileEntry`.

(Reincarnation of [D143414](https://reviews.llvm.org/D143414) and 
[D142780](https://reviews.llvm.org/D142780).)


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


3 Files Affected:

- (modified) clang/include/clang/Basic/FileManager.h (+3-3) 
- (modified) clang/lib/Basic/FileManager.cpp (+12-15) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+10-10) 


``diff
diff --git a/clang/include/clang/Basic/FileManager.h 
b/clang/include/clang/Basic/FileManager.h
index 115558bfeee4ed5..56cb093dd8c376f 100644
--- a/clang/include/clang/Basic/FileManager.h
+++ b/clang/include/clang/Basic/FileManager.h
@@ -311,9 +311,9 @@ class FileManager : public RefCountedBase {
   bool makeAbsolutePath(SmallVectorImpl ) const;
 
   /// Produce an array mapping from the unique IDs assigned to each
-  /// file to the corresponding FileEntry pointer.
-  void GetUniqueIDMapping(
-SmallVectorImpl ) const;
+  /// file to the corresponding FileEntryRef.
+  void
+  GetUniqueIDMapping(SmallVectorImpl ) const;
 
   /// Retrieve the canonical name for a given directory.
   ///
diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp
index c80fbfd7433f5be..3b834610dd55ef8 100644
--- a/clang/lib/Basic/FileManager.cpp
+++ b/clang/lib/Basic/FileManager.cpp
@@ -612,24 +612,21 @@ FileManager::getNoncachedStatValue(StringRef Path,
 }
 
 void FileManager::GetUniqueIDMapping(
-SmallVectorImpl ) const {
+SmallVectorImpl ) const {
   UIDToFiles.clear();
   UIDToFiles.resize(NextFileUID);
 
-  // Map file entries
-  for (llvm::StringMap,
-   llvm::BumpPtrAllocator>::const_iterator
-   FE = SeenFileEntries.begin(),
-   FEEnd = SeenFileEntries.end();
-   FE != FEEnd; ++FE)
-if (llvm::ErrorOr Entry = FE->getValue()) {
-  if (const auto *FE = Entry->V.dyn_cast())
-UIDToFiles[FE->getUID()] = FE;
-}
-
-  // Map virtual file entries
-  for (const auto  : VirtualFileEntries)
-UIDToFiles[VFE->getUID()] = VFE;
+  for (const auto  : SeenFileEntries) {
+// Only return existing non-virtual files.
+if (!Entry.getValue() || !Entry.getValue()->V.is())
+  continue;
+FileEntryRef FE(Entry);
+// Add this file if it's the first one with the UID, or if its name is
+// better than the existing one.
+OptionalFileEntryRef  = UIDToFiles[FE.getUID()];
+if (!ExistingFE || FE.getName() < ExistingFE->getName())
+  ExistingFE = FE;
+  }
 }
 
 StringRef FileManager::getCanonicalName(DirectoryEntryRef Dir) {
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 216ca94111e156b..1d939a3f5e7a819 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -167,23 +167,23 @@ std::set GetAffectingModuleMaps(const 
Preprocessor ,
 
   const HeaderSearch  = PP.getHeaderSearchInfo();
 
-  SmallVector FilesByUID;
+  SmallVector FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
 
   if (FilesByUID.size() > HS.header_file_size())
 FilesByUID.resize(HS.header_file_size());
 
   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
-const FileEntry *File = FilesByUID[UID];
+OptionalFileEntryRef File = FilesByUID[UID];
 if (!File)
   continue;
 
 const HeaderFileInfo *HFI =
-HS.getExistingFileInfo(File, /*WantExternal*/ false);
+HS.getExistingFileInfo(*File, /*WantExternal*/ false);
 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
   continue;
 
-for (const auto  : HS.findResolvedModulesForHeader(File)) {
+for (const auto  : HS.findResolvedModulesForHeader(*File)) {
   if (!KH.getModule())
 continue;
   ModulesToProcess.push_back(KH.getModule());
@@ -2003,14 +2003,14 @@ void ASTWriter::WriteHeaderSearch(const HeaderSearch 
) {
 }
   }
 
-  SmallVector FilesByUID;
+  

[clang] [clang][modules] Adopt `FileEntryRef` in the `HeaderFileInfo` block in PCM files (PR #67383)

2023-09-25 Thread Jan Svoboda via cfe-commits

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

This patch adopts `FileEntryRef` in the `HeaderFileInfo`-writing part of 
`ASTWriter`.

First, this patch removes the loop over `FileManager::VirtualFileEntries`. It's 
redundant, since all virtual file entries have a non-virtual/real counterpart 
that's already present in `UIDToFiles`.

Second, since we now no longer rely on 
`FileEntry::getLastRef()`/`FileEntry::getName()`, this patch takes care to 
establish which path gets used for each UID by picking the `FileEntryRef` with 
the most "`<`" name (instead of just relying on the `StringMap` iteration 
order).

Note that which `FileEntry`/`FileEntryRef` objects we pick for each UID for 
serialization into the `llvm::OnDiskChainedHashTable` doesn't really matter. 
The hash function only includes the file size and modification time. The file 
name only plays role during resolution of hash collisions, in which case it 
goes through `FileManager` and resolves to a `FileEntry` that gets 
pointer-compared with the queried `FileEntry`.

(Reincarnation of [D143414](https://reviews.llvm.org/D143414) and 
[D142780](https://reviews.llvm.org/D142780).)


>From e2201a10fe76be3de8efd0faca0f381f504b08d3 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Mon, 25 Sep 2023 16:37:49 -0700
Subject: [PATCH] [clang][modules] Adopt `FileEntryRef` in the `HeaderFileInfo`
 block in PCM files

---
 clang/include/clang/Basic/FileManager.h |  6 +++---
 clang/lib/Basic/FileManager.cpp | 27 +++--
 clang/lib/Serialization/ASTWriter.cpp   | 20 +-
 3 files changed, 25 insertions(+), 28 deletions(-)

diff --git a/clang/include/clang/Basic/FileManager.h 
b/clang/include/clang/Basic/FileManager.h
index 115558bfeee4ed5..56cb093dd8c376f 100644
--- a/clang/include/clang/Basic/FileManager.h
+++ b/clang/include/clang/Basic/FileManager.h
@@ -311,9 +311,9 @@ class FileManager : public RefCountedBase {
   bool makeAbsolutePath(SmallVectorImpl ) const;
 
   /// Produce an array mapping from the unique IDs assigned to each
-  /// file to the corresponding FileEntry pointer.
-  void GetUniqueIDMapping(
-SmallVectorImpl ) const;
+  /// file to the corresponding FileEntryRef.
+  void
+  GetUniqueIDMapping(SmallVectorImpl ) const;
 
   /// Retrieve the canonical name for a given directory.
   ///
diff --git a/clang/lib/Basic/FileManager.cpp b/clang/lib/Basic/FileManager.cpp
index c80fbfd7433f5be..3b834610dd55ef8 100644
--- a/clang/lib/Basic/FileManager.cpp
+++ b/clang/lib/Basic/FileManager.cpp
@@ -612,24 +612,21 @@ FileManager::getNoncachedStatValue(StringRef Path,
 }
 
 void FileManager::GetUniqueIDMapping(
-SmallVectorImpl ) const {
+SmallVectorImpl ) const {
   UIDToFiles.clear();
   UIDToFiles.resize(NextFileUID);
 
-  // Map file entries
-  for (llvm::StringMap,
-   llvm::BumpPtrAllocator>::const_iterator
-   FE = SeenFileEntries.begin(),
-   FEEnd = SeenFileEntries.end();
-   FE != FEEnd; ++FE)
-if (llvm::ErrorOr Entry = FE->getValue()) {
-  if (const auto *FE = Entry->V.dyn_cast())
-UIDToFiles[FE->getUID()] = FE;
-}
-
-  // Map virtual file entries
-  for (const auto  : VirtualFileEntries)
-UIDToFiles[VFE->getUID()] = VFE;
+  for (const auto  : SeenFileEntries) {
+// Only return existing non-virtual files.
+if (!Entry.getValue() || !Entry.getValue()->V.is())
+  continue;
+FileEntryRef FE(Entry);
+// Add this file if it's the first one with the UID, or if its name is
+// better than the existing one.
+OptionalFileEntryRef  = UIDToFiles[FE.getUID()];
+if (!ExistingFE || FE.getName() < ExistingFE->getName())
+  ExistingFE = FE;
+  }
 }
 
 StringRef FileManager::getCanonicalName(DirectoryEntryRef Dir) {
diff --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index 216ca94111e156b..1d939a3f5e7a819 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -167,23 +167,23 @@ std::set GetAffectingModuleMaps(const 
Preprocessor ,
 
   const HeaderSearch  = PP.getHeaderSearchInfo();
 
-  SmallVector FilesByUID;
+  SmallVector FilesByUID;
   HS.getFileMgr().GetUniqueIDMapping(FilesByUID);
 
   if (FilesByUID.size() > HS.header_file_size())
 FilesByUID.resize(HS.header_file_size());
 
   for (unsigned UID = 0, LastUID = FilesByUID.size(); UID != LastUID; ++UID) {
-const FileEntry *File = FilesByUID[UID];
+OptionalFileEntryRef File = FilesByUID[UID];
 if (!File)
   continue;
 
 const HeaderFileInfo *HFI =
-HS.getExistingFileInfo(File, /*WantExternal*/ false);
+HS.getExistingFileInfo(*File, /*WantExternal*/ false);
 if (!HFI || (HFI->isModuleHeader && !HFI->isCompilingModuleHeader))
   continue;
 
-for (const auto  : HS.findResolvedModulesForHeader(File)) {
+for (const auto  : HS.findResolvedModulesForHeader(*File)) {
  

[clang] [CodeGen] Avoid potential sideeffects from XOR (PR #67193)

2023-09-25 Thread Bill Wendling via cfe-commits

https://github.com/bwendling updated 
https://github.com/llvm/llvm-project/pull/67193

>From 6db37f7f76347a7821d9a95c0fdac4e250df2e78 Mon Sep 17 00:00:00 2001
From: Bill Wendling 
Date: Fri, 22 Sep 2023 12:35:09 -0700
Subject: [PATCH 1/2] [CodeGen] Avoid potential sideeffects from XOR

XOR may change flag values (e.g. for X86 gprs). In the case where that's
not desirable, specify that buildClearRegister() should use MOV instead.
---
 llvm/include/llvm/CodeGen/TargetInstrInfo.h  |  7 +++--
 llvm/lib/Target/AArch64/AArch64InstrInfo.cpp | 14 +
 llvm/lib/Target/AArch64/AArch64InstrInfo.h   |  4 +--
 llvm/lib/Target/X86/X86InstrInfo.cpp | 31 +---
 llvm/lib/Target/X86/X86InstrInfo.h   |  4 +--
 5 files changed, 38 insertions(+), 22 deletions(-)

diff --git a/llvm/include/llvm/CodeGen/TargetInstrInfo.h 
b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
index 04859a50d6fdeb4..7c2bd83d1d623ef 100644
--- a/llvm/include/llvm/CodeGen/TargetInstrInfo.h
+++ b/llvm/include/llvm/CodeGen/TargetInstrInfo.h
@@ -2057,10 +2057,13 @@ class TargetInstrInfo : public MCInstrInfo {
 "Target didn't implement TargetInstrInfo::insertOutlinedCall!");
   }
 
-  /// Insert an architecture-specific instruction to clear a register.
+  /// Insert an architecture-specific instruction to clear a register. If you
+  /// need to avoid sideeffects (e.g. XOR on x86), set \p NoSideEffects to \p
+  /// true.
   virtual void buildClearRegister(Register Reg, MachineBasicBlock ,
   MachineBasicBlock::iterator Iter,
-  DebugLoc ) const {
+  DebugLoc ,
+  bool NoSideEffects = false) const {
 llvm_unreachable(
 "Target didn't implement TargetInstrInfo::buildClearRegister!");
   }
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp 
b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
index a1e6a8177c10013..3b1e301e576a1b1 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
@@ -8337,21 +8337,23 @@ bool 
AArch64InstrInfo::shouldOutlineFromFunctionByDefault(
 
 void AArch64InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock ,
   MachineBasicBlock::iterator Iter,
-  DebugLoc ) const {
+  DebugLoc ,
+  bool NoSideEffects) const {
   const MachineFunction  = *MBB.getParent();
   const AArch64Subtarget  = MF.getSubtarget();
   const AArch64RegisterInfo  = *STI.getRegisterInfo();
 
   if (TRI.isGeneralPurposeRegister(MF, Reg)) {
-BuildMI(MBB, Iter, DL, get(AArch64::MOVi64imm), Reg)
-  .addImm(0);
+BuildMI(MBB, Iter, DL, get(AArch64::MOVZXi), Reg)
+.addImm(0)
+.addImm(0);
   } else if (STI.hasSVE()) {
 BuildMI(MBB, Iter, DL, get(AArch64::DUP_ZI_D), Reg)
-  .addImm(0)
-  .addImm(0);
+.addImm(0)
+.addImm(0);
   } else {
 BuildMI(MBB, Iter, DL, get(AArch64::MOVIv2d_ns), Reg)
-  .addImm(0);
+.addImm(0);
   }
 }
 
diff --git a/llvm/lib/Target/AArch64/AArch64InstrInfo.h 
b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
index 4a4d87c1b1f6ba5..5c5e7e4fe39068a 100644
--- a/llvm/lib/Target/AArch64/AArch64InstrInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64InstrInfo.h
@@ -320,8 +320,8 @@ class AArch64InstrInfo final : public AArch64GenInstrInfo {
   bool shouldOutlineFromFunctionByDefault(MachineFunction ) const override;
 
   void buildClearRegister(Register Reg, MachineBasicBlock ,
-  MachineBasicBlock::iterator Iter,
-  DebugLoc ) const override;
+  MachineBasicBlock::iterator Iter, DebugLoc ,
+  bool NoSideEffects = false) const override;
 
   /// Returns the vector element size (B, H, S or D) of an SVE opcode.
   uint64_t getElementSizeForOpcode(unsigned Opc) const;
diff --git a/llvm/lib/Target/X86/X86InstrInfo.cpp 
b/llvm/lib/Target/X86/X86InstrInfo.cpp
index 73675a868239ea1..24a7d632f951385 100644
--- a/llvm/lib/Target/X86/X86InstrInfo.cpp
+++ b/llvm/lib/Target/X86/X86InstrInfo.cpp
@@ -9796,27 +9796,34 @@ X86InstrInfo::insertOutlinedCall(Module , 
MachineBasicBlock ,
   return It;
 }
 
-void X86InstrInfo::buildClearRegister(Register Reg,
-  MachineBasicBlock ,
+void X86InstrInfo::buildClearRegister(Register Reg, MachineBasicBlock ,
   MachineBasicBlock::iterator Iter,
-  DebugLoc ) const {
+  DebugLoc , bool NoSideEffects) const {
   const MachineFunction  = *MBB.getParent();
   const X86Subtarget  = MF.getSubtarget();
   const TargetRegisterInfo  = getRegisterInfo();
 
   if (ST.hasMMX() && X86::VR64RegClass.contains(Reg))
-// FIXME: Ignore MMX registers?
+  

[clang] [clang-analysis]Fix false positive in mutation check when using pointer to member function (PR #66846)

2023-09-25 Thread Congcong Cai via cfe-commits

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


[clang-tools-extra] [clang-analysis]Fix false positive in mutation check when using pointer to member function (PR #66846)

2023-09-25 Thread Congcong Cai via cfe-commits

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


[clang] feb7b19 - [clang-analysis]Fix false positive in mutation check when using pointer to member function (#66846)

2023-09-25 Thread via cfe-commits

Author: Congcong Cai
Date: 2023-09-26T07:40:15+08:00
New Revision: feb7b1914d513c709b9e024dfed709bb889cc853

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

LOG: [clang-analysis]Fix false positive in mutation check when using pointer to 
member function (#66846)

Fixes: #66204

Added: 


Modified: 
clang-tools-extra/docs/ReleaseNotes.rst
clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
clang/docs/ReleaseNotes.rst
clang/lib/Analysis/ExprMutationAnalyzer.cpp
clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Removed: 




diff  --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 466c9b08c578890..8fc28c090341802 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -246,6 +246,10 @@ Changes in existing checks
   customizable namespace. This further allows for testing the libc when the
   system-libc is also LLVM's libc.
 
+- Improved :doc:`misc-const-correctness
+  ` check to avoid false positive 
when
+  using pointer to member function.
+  
 - Improved :doc:`misc-include-cleaner
   ` check by adding option
   `DeduplicateFindings` to output one finding per symbol occurrence.

diff  --git 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
index 186e3cf5a179b24..cb6bfcc1dccba39 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/misc/const-correctness-values.cpp
@@ -976,3 +976,16 @@ void auto_usage_variants() {
   auto _td1 = auto_td0;
   auto *auto_td2 = _td0;
 }
+
+using PointerToMemberFunction = int (Value::*)();
+void member_pointer(Value , PointerToMemberFunction m) {
+  Value _pointer_tmp = x;
+  (member_pointer_tmp.*m)();
+}
+
+using PointerToConstMemberFunction = int (Value::*)() const;
+void member_pointer_const(Value , PointerToConstMemberFunction m) {
+  Value _pointer_tmp = x;
+  // CHECK-MESSAGES:[[@LINE-1]]:3: warning: variable 'member_pointer_tmp' of 
type 'Value &' can be declared 'const'
+  (member_pointer_tmp.*m)();
+}

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 688454d6b562ec3..8a136aae5489a8c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -502,6 +502,9 @@ Static Analyzer
   bitwise shift operators produce undefined behavior (because some operand is
   negative or too large).
 
+- Fix false positive in mutation check when using pointer to member function.
+  (`#66204: `_).
+
 - The ``alpha.security.taint.TaintPropagation`` checker no longer propagates
   taint on ``strlen`` and ``strnlen`` calls, unless these are marked
   explicitly propagators in the user-provided taint configuration file.

diff  --git a/clang/lib/Analysis/ExprMutationAnalyzer.cpp 
b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
index 90803830ff41949..f2e1beb025423cf 100644
--- a/clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ b/clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -100,6 +100,20 @@ AST_MATCHER(CXXTypeidExpr, isPotentiallyEvaluated) {
   return Node.isPotentiallyEvaluated();
 }
 
+AST_MATCHER(CXXMemberCallExpr, isConstCallee) {
+  const Decl *CalleeDecl = Node.getCalleeDecl();
+  const auto *VD = dyn_cast_or_null(CalleeDecl);
+  if (!VD)
+return false;
+  const QualType T = VD->getType().getCanonicalType();
+  const auto *MPT = dyn_cast(T);
+  const auto *FPT = MPT ? cast(MPT->getPointeeType())
+: dyn_cast(T);
+  if (!FPT)
+return false;
+  return FPT->isConst();
+}
+
 AST_MATCHER_P(GenericSelectionExpr, hasControllingExpr,
   ast_matchers::internal::Matcher, InnerMatcher) {
   if (Node.isTypePredicate())
@@ -274,8 +288,8 @@ const Stmt *ExprMutationAnalyzer::findDirectMutation(const 
Expr *Exp) {
   const auto NonConstMethod = cxxMethodDecl(unless(isConst()));
 
   const auto AsNonConstThis = expr(anyOf(
-  cxxMemberCallExpr(callee(NonConstMethod),
-on(canResolveToExpr(equalsNode(Exp,
+  cxxMemberCallExpr(on(canResolveToExpr(equalsNode(Exp))),
+unless(isConstCallee())),
   cxxOperatorCallExpr(callee(NonConstMethod),
   hasArgument(0, canResolveToExpr(equalsNode(Exp,
   // In case of a templated type, calling overloaded operators is not
@@ -391,7 +405,9 @@ const Stmt *ExprMutationAnalyzer::findMemberMutation(const 
Expr *Exp) {
   match(findAll(expr(anyOf(memberExpr(hasObjectExpression(
canResolveToExpr(equalsNode(Exp,

[PATCH] D147655: Implement mangling rules for C++20 concepts and requires-expressions.

2023-09-25 Thread Richard Smith - zygoloid via Phabricator via cfe-commits
rsmith added a comment.

In D147655#4650666 , @rjmccall wrote:

> Yeah, the more I think about this, the more I think that while (1) Apple 
> should upstream its use of an older default, regardless (2) the existence of 
> any targets at all with an older default means that tests like this always 
> need to be using `-fclang-abi-compat=latest`.

Seems reasonable. I went ahead and made that change in 
rG940850066290a484144db80f09e6c19709f5fe49 
.

I think we could probably limit this to just the test using 
`%itanium_abi_triple`, but there's also an affected test specifying 
`-triple=x86_64-apple-darwin9`, so that might not be enough for your needs. 
Also, I suppose some vendors might want to carry a patch that changes the 
default globally rather than on a per-target basis. So I just changed all the 
tests that touch the new mangling.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D147655/new/

https://reviews.llvm.org/D147655

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


[clang] 7421dd5 - Don't specify the same flag twice.

2023-09-25 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2023-09-25T16:38:17-07:00
New Revision: 7421dd55a16f18919a568499e4c0888ed3a5e8b5

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

LOG: Don't specify the same flag twice.

Added: 


Modified: 
clang/test/CodeGenCXX/mangle-concept.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/mangle-concept.cpp 
b/clang/test/CodeGenCXX/mangle-concept.cpp
index 63e201d73e3bd0d..bbd2cf6555e3ec5 100644
--- a/clang/test/CodeGenCXX/mangle-concept.cpp
+++ b/clang/test/CodeGenCXX/mangle-concept.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-fclang-abi-compat=latest -emit-llvm -triple %itanium_abi_triple -o - %s | 
FileCheck %s
-// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-fclang-abi-compat=latest -emit-llvm -triple %itanium_abi_triple -o - %s 
-fclang-abi-compat=16 | FileCheck %s --check-prefix=CLANG16
+// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-emit-llvm -triple %itanium_abi_triple -o - %s -fclang-abi-compat=latest | 
FileCheck %s
+// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-emit-llvm -triple %itanium_abi_triple -o - %s -fclang-abi-compat=16 | 
FileCheck %s --check-prefix=CLANG16
 // expected-no-diagnostics
 
 namespace test1 {



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


[clang] 9408500 - Add -fclang-abi-compat=latest to a bunch of tests for manglings that changed since v17.

2023-09-25 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2023-09-25T16:34:38-07:00
New Revision: 940850066290a484144db80f09e6c19709f5fe49

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

LOG: Add -fclang-abi-compat=latest to a bunch of tests for manglings that 
changed since v17.

Per discussion on https://reviews.llvm.org/D147655, various vendors use
a different default.

Added: 


Modified: 
clang/test/CodeGenCXX/mangle-concept.cpp
clang/test/CodeGenCXX/mangle-exprs.cpp
clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
clang/test/CodeGenCXX/mangle-requires.cpp
clang/test/CodeGenCXX/mangle-template.cpp
clang/test/CodeGenCXX/matrix-type.cpp
clang/test/OpenMP/tile_codegen.cpp

Removed: 




diff  --git a/clang/test/CodeGenCXX/mangle-concept.cpp 
b/clang/test/CodeGenCXX/mangle-concept.cpp
index efab169903395ac..63e201d73e3bd0d 100644
--- a/clang/test/CodeGenCXX/mangle-concept.cpp
+++ b/clang/test/CodeGenCXX/mangle-concept.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-emit-llvm -triple %itanium_abi_triple -o - %s | FileCheck %s
-// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-emit-llvm -triple %itanium_abi_triple -o - %s -fclang-abi-compat=16 | 
FileCheck %s --check-prefix=CLANG16
+// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-fclang-abi-compat=latest -emit-llvm -triple %itanium_abi_triple -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -verify -frelaxed-template-template-args -std=c++20 
-fclang-abi-compat=latest -emit-llvm -triple %itanium_abi_triple -o - %s 
-fclang-abi-compat=16 | FileCheck %s --check-prefix=CLANG16
 // expected-no-diagnostics
 
 namespace test1 {

diff  --git a/clang/test/CodeGenCXX/mangle-exprs.cpp 
b/clang/test/CodeGenCXX/mangle-exprs.cpp
index 6ebca562caad58f..b666eaadf457688 100644
--- a/clang/test/CodeGenCXX/mangle-exprs.cpp
+++ b/clang/test/CodeGenCXX/mangle-exprs.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -std=c++11 -emit-llvm %s -o - -triple=x86_64-apple-darwin9 
| FileCheck %s
+// RUN: %clang_cc1 -std=c++11 -fclang-abi-compat=latest -emit-llvm %s -o - 
-triple=x86_64-apple-darwin9 | FileCheck %s
 
 namespace std {
   typedef decltype(sizeof(int)) size_t;

diff  --git a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp 
b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
index 78fa7c378c88d50..4fd4a51bc3ee18e 100644
--- a/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
+++ b/clang/test/CodeGenCXX/mangle-nttp-anon-union.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
FileCheck %s
-// RUN: %clang_cc1 -std=c++20 -emit-llvm %s -o - -triple=x86_64-linux-gnu | 
llvm-cxxfilt -n | FileCheck %s --check-prefix DEMANGLED
+// RUN: %clang_cc1 -std=c++20 -fclang-abi-compat=latest -emit-llvm %s -o - 
-triple=x86_64-linux-gnu | FileCheck %s
+// RUN: %clang_cc1 -std=c++20 -fclang-abi-compat=latest -emit-llvm %s -o - 
-triple=x86_64-linux-gnu | llvm-cxxfilt -n | FileCheck %s --check-prefix 
DEMANGLED
 
 template
 struct wrapper1 {

diff  --git a/clang/test/CodeGenCXX/mangle-requires.cpp 
b/clang/test/CodeGenCXX/mangle-requires.cpp
index 9897b440a664478..9e2bdde03407a99 100644
--- a/clang/test/CodeGenCXX/mangle-requires.cpp
+++ b/clang/test/CodeGenCXX/mangle-requires.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -verify -std=c++2a -emit-llvm -triple %itanium_abi_triple 
-o - %s | FileCheck %s
+// RUN: %clang_cc1 -verify -std=c++2a -fclang-abi-compat=latest -emit-llvm 
-triple %itanium_abi_triple -o - %s | FileCheck %s
 // expected-no-diagnostics
 
 template  concept SmallerThan = sizeof(T) < N;

diff  --git a/clang/test/CodeGenCXX/mangle-template.cpp 
b/clang/test/CodeGenCXX/mangle-template.cpp
index 52aefa8dfc2b97e..8415bacbb9fc6d4 100644
--- a/clang/test/CodeGenCXX/mangle-template.cpp
+++ b/clang/test/CodeGenCXX/mangle-template.cpp
@@ -1,5 +1,5 @@
-// RUN: %clang_cc1 -verify -Wno-return-type -Wno-main -std=c++11 -emit-llvm 
-triple %itanium_abi_triple -o - %s | FileCheck %s
-// RUN: %clang_cc1 -verify -Wno-return-type -Wno-main -std=c++20 -emit-llvm 
-triple x86_64-linux-gnu -o - %s | FileCheck %s --check-prefixes=CHECK,CXX20
+// RUN: %clang_cc1 -verify -Wno-return-type -Wno-main -std=c++11 
-fclang-abi-compat=latest -emit-llvm -triple %itanium_abi_triple -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -verify -Wno-return-type -Wno-main -std=c++20 
-fclang-abi-compat=latest -emit-llvm -triple x86_64-linux-gnu -o - %s | 
FileCheck %s --check-prefixes=CHECK,CXX20
 // expected-no-diagnostics
 
 namespace test1 {

diff  --git a/clang/test/CodeGenCXX/matrix-type.cpp 
b/clang/test/CodeGenCXX/matrix-type.cpp
index 4d94c281ae8c45c..79bceabb115f835 100644
--- a/clang/test/CodeGenCXX/matrix-type.cpp
+++ b/clang/test/CodeGenCXX/matrix-type.cpp
@@ -1,4 

[clang] [MLIR][Presburger] Define matrix inverse for rational matrices (PR #67382)

2023-09-25 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 c74398649f28ab78c74bacfe82e69224377008e7 
69cce307842ab6bfbca10f44d3826623379a0385 -- 
mlir/include/mlir/Analysis/Presburger/Fraction.h 
mlir/include/mlir/Analysis/Presburger/Matrix.h 
mlir/lib/Analysis/Presburger/Matrix.cpp 
mlir/unittests/Analysis/Presburger/MatrixTest.cpp 
mlir/unittests/Analysis/Presburger/Utils.h
``





View the diff from clang-format here.


``diff
diff --git a/mlir/include/mlir/Analysis/Presburger/Matrix.h 
b/mlir/include/mlir/Analysis/Presburger/Matrix.h
index b9048334c39f..74e6cb7d 100644
--- a/mlir/include/mlir/Analysis/Presburger/Matrix.h
+++ b/mlir/include/mlir/Analysis/Presburger/Matrix.h
@@ -247,27 +247,25 @@ public:
 // An inherited class for rational matrices, with no new data attributes.
 // This is only used for the matrix-related method which apply only
 // to fractions (inverse).
-class FracMatrix : public Matrix
-{
+class FracMatrix : public Matrix {
 public:
   FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0,
-unsigned reservedColumns = 0) :
-Matrix(rows, columns, reservedRows, reservedColumns) {};
+ unsigned reservedColumns = 0)
+  : Matrix(rows, columns, reservedRows, reservedColumns){};
 
-  FracMatrix(Matrix m) :
-Matrix(m.getNumRows(), m.getNumColumns(), 
m.getNumReservedRows(), m.getNumReservedColumns())
-  {
+  FracMatrix(Matrix m)
+  : Matrix(m.getNumRows(), m.getNumColumns(),
+ m.getNumReservedRows(), m.getNumReservedColumns()) {
 for (unsigned i = 0; i < m.getNumRows(); i++)
   for (unsigned j = 0; j < m.getNumColumns(); j++)
 at(i, j) = m(i, j);
   };
-  
+
   /// Return the identity matrix of the specified dimension.
   static FracMatrix identity(unsigned dimension);
 
   // Return the inverse of the matrix, leaving the calling object unmodified.
   FracMatrix inverse();
-
 };
 
 } // namespace presburger
diff --git a/mlir/lib/Analysis/Presburger/Matrix.cpp 
b/mlir/lib/Analysis/Presburger/Matrix.cpp
index c0fbc688be2e..de5e2bbe285a 100644
--- a/mlir/lib/Analysis/Presburger/Matrix.cpp
+++ b/mlir/lib/Analysis/Presburger/Matrix.cpp
@@ -392,7 +392,6 @@ MPInt IntMatrix::normalizeRow(unsigned row) {
   return normalizeRow(row, getNumColumns());
 }
 
-
 FracMatrix FracMatrix::identity(unsigned dimension) {
   FracMatrix matrix(dimension, dimension);
   for (unsigned i = 0; i < dimension; ++i)
@@ -400,60 +399,55 @@ FracMatrix FracMatrix::identity(unsigned dimension) {
   return matrix;
 }
 
-FracMatrix FracMatrix::inverse()
-{
-// We use Gaussian elimination on the rows of [M | I]
-// to find the integer inverse. We proceed left-to-right,
-// top-to-bottom. M is assumed to be a dim x dim matrix.
+FracMatrix FracMatrix::inverse() {
+  // We use Gaussian elimination on the rows of [M | I]
+  // to find the integer inverse. We proceed left-to-right,
+  // top-to-bottom. M is assumed to be a dim x dim matrix.
 
-unsigned dim = getNumRows();
+  unsigned dim = getNumRows();
 
-// Construct the augmented matrix [M | I]
-FracMatrix augmented(dim, dim + dim);
-for (unsigned i = 0; i < dim; i++)
-{
-augmented.fillRow(i, 0);
-for (unsigned j = 0; j < dim; j++)
-augmented(i, j) = at(i, j);
-augmented(i, dim+i).num = 1;
-augmented(i, dim+i).den = 1;
-}
-Fraction a, b;
-for (unsigned i = 0; i < dim; i++)
-{
-if (augmented(i, i) == Fraction(0, 1))
-for (unsigned j = i+1; j < dim; j++)
-if (augmented(j, i) != Fraction(0, 1))
-{
-augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
-break;
-}
-
-b = augmented(i, i);
-for (unsigned j = 0; j < dim; j++)
-{
-if (i == j || augmented(j, i) == 0) continue;
-a = augmented(j, i);
-// Rj -> Rj - (b/a)Ri
-augmented.addToRow(j, augmented.getRow(i), - a / b);
-// Now (Rj)i = 0
+  // Construct the augmented matrix [M | I]
+  FracMatrix augmented(dim, dim + dim);
+  for (unsigned i = 0; i < dim; i++) {
+augmented.fillRow(i, 0);
+for (unsigned j = 0; j < dim; j++)
+  augmented(i, j) = at(i, j);
+augmented(i, dim + i).num = 1;
+augmented(i, dim + i).den = 1;
+  }
+  Fraction a, b;
+  for (unsigned i = 0; i < dim; i++) {
+if (augmented(i, i) == Fraction(0, 1))
+  for (unsigned j = i + 1; j < dim; j++)
+if (augmented(j, i) != Fraction(0, 1)) {
+  augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
+  break;
 }
+
+b = augmented(i, i);
+for (unsigned j = 0; j < dim; j++) {
+  if (i == j || augmented(j, i) == 0)
+continue;
+  a = augmented(j, 

[clang-tools-extra] [MLIR][Presburger] Define matrix inverse for rational matrices (PR #67382)

2023-09-25 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 c74398649f28ab78c74bacfe82e69224377008e7 
69cce307842ab6bfbca10f44d3826623379a0385 -- 
mlir/include/mlir/Analysis/Presburger/Fraction.h 
mlir/include/mlir/Analysis/Presburger/Matrix.h 
mlir/lib/Analysis/Presburger/Matrix.cpp 
mlir/unittests/Analysis/Presburger/MatrixTest.cpp 
mlir/unittests/Analysis/Presburger/Utils.h
``





View the diff from clang-format here.


``diff
diff --git a/mlir/include/mlir/Analysis/Presburger/Matrix.h 
b/mlir/include/mlir/Analysis/Presburger/Matrix.h
index b9048334c39f..74e6cb7d 100644
--- a/mlir/include/mlir/Analysis/Presburger/Matrix.h
+++ b/mlir/include/mlir/Analysis/Presburger/Matrix.h
@@ -247,27 +247,25 @@ public:
 // An inherited class for rational matrices, with no new data attributes.
 // This is only used for the matrix-related method which apply only
 // to fractions (inverse).
-class FracMatrix : public Matrix
-{
+class FracMatrix : public Matrix {
 public:
   FracMatrix(unsigned rows, unsigned columns, unsigned reservedRows = 0,
-unsigned reservedColumns = 0) :
-Matrix(rows, columns, reservedRows, reservedColumns) {};
+ unsigned reservedColumns = 0)
+  : Matrix(rows, columns, reservedRows, reservedColumns){};
 
-  FracMatrix(Matrix m) :
-Matrix(m.getNumRows(), m.getNumColumns(), 
m.getNumReservedRows(), m.getNumReservedColumns())
-  {
+  FracMatrix(Matrix m)
+  : Matrix(m.getNumRows(), m.getNumColumns(),
+ m.getNumReservedRows(), m.getNumReservedColumns()) {
 for (unsigned i = 0; i < m.getNumRows(); i++)
   for (unsigned j = 0; j < m.getNumColumns(); j++)
 at(i, j) = m(i, j);
   };
-  
+
   /// Return the identity matrix of the specified dimension.
   static FracMatrix identity(unsigned dimension);
 
   // Return the inverse of the matrix, leaving the calling object unmodified.
   FracMatrix inverse();
-
 };
 
 } // namespace presburger
diff --git a/mlir/lib/Analysis/Presburger/Matrix.cpp 
b/mlir/lib/Analysis/Presburger/Matrix.cpp
index c0fbc688be2e..de5e2bbe285a 100644
--- a/mlir/lib/Analysis/Presburger/Matrix.cpp
+++ b/mlir/lib/Analysis/Presburger/Matrix.cpp
@@ -392,7 +392,6 @@ MPInt IntMatrix::normalizeRow(unsigned row) {
   return normalizeRow(row, getNumColumns());
 }
 
-
 FracMatrix FracMatrix::identity(unsigned dimension) {
   FracMatrix matrix(dimension, dimension);
   for (unsigned i = 0; i < dimension; ++i)
@@ -400,60 +399,55 @@ FracMatrix FracMatrix::identity(unsigned dimension) {
   return matrix;
 }
 
-FracMatrix FracMatrix::inverse()
-{
-// We use Gaussian elimination on the rows of [M | I]
-// to find the integer inverse. We proceed left-to-right,
-// top-to-bottom. M is assumed to be a dim x dim matrix.
+FracMatrix FracMatrix::inverse() {
+  // We use Gaussian elimination on the rows of [M | I]
+  // to find the integer inverse. We proceed left-to-right,
+  // top-to-bottom. M is assumed to be a dim x dim matrix.
 
-unsigned dim = getNumRows();
+  unsigned dim = getNumRows();
 
-// Construct the augmented matrix [M | I]
-FracMatrix augmented(dim, dim + dim);
-for (unsigned i = 0; i < dim; i++)
-{
-augmented.fillRow(i, 0);
-for (unsigned j = 0; j < dim; j++)
-augmented(i, j) = at(i, j);
-augmented(i, dim+i).num = 1;
-augmented(i, dim+i).den = 1;
-}
-Fraction a, b;
-for (unsigned i = 0; i < dim; i++)
-{
-if (augmented(i, i) == Fraction(0, 1))
-for (unsigned j = i+1; j < dim; j++)
-if (augmented(j, i) != Fraction(0, 1))
-{
-augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
-break;
-}
-
-b = augmented(i, i);
-for (unsigned j = 0; j < dim; j++)
-{
-if (i == j || augmented(j, i) == 0) continue;
-a = augmented(j, i);
-// Rj -> Rj - (b/a)Ri
-augmented.addToRow(j, augmented.getRow(i), - a / b);
-// Now (Rj)i = 0
+  // Construct the augmented matrix [M | I]
+  FracMatrix augmented(dim, dim + dim);
+  for (unsigned i = 0; i < dim; i++) {
+augmented.fillRow(i, 0);
+for (unsigned j = 0; j < dim; j++)
+  augmented(i, j) = at(i, j);
+augmented(i, dim + i).num = 1;
+augmented(i, dim + i).den = 1;
+  }
+  Fraction a, b;
+  for (unsigned i = 0; i < dim; i++) {
+if (augmented(i, i) == Fraction(0, 1))
+  for (unsigned j = i + 1; j < dim; j++)
+if (augmented(j, i) != Fraction(0, 1)) {
+  augmented.addToRow(i, augmented.getRow(j), Fraction(1, 1));
+  break;
 }
+
+b = augmented(i, i);
+for (unsigned j = 0; j < dim; j++) {
+  if (i == j || augmented(j, i) == 0)
+continue;
+  a = augmented(j, 

[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Shafik Yaghmour via cfe-commits


@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}

shafik wrote:

Yes, your modifications IIUC does trigger the crash: 
https://godbolt.org/z/a8e9WrM37

but it generates a lot more diagnostics, running the test with the modified 
code generates three additional diagnostics:

```console
error: 'expected-error' diagnostics seen but not expected: 
  File 
/Users/shafik/llvm_org_6/llvm-project/clang/test/SemaCXX/cxx1z-copy-omission.cpp
 Line 182: no viable constructor or deduction guide for deduction of template 
arguments of 'B3'
error: 'expected-note' diagnostics seen but not expected: 
  File 
/Users/shafik/llvm_org_6/llvm-project/clang/test/SemaCXX/cxx1z-copy-omission.cpp
 Line 179: candidate template ignored: couldn't infer template argument ''
  File 
/Users/shafik/llvm_org_6/llvm-project/clang/test/SemaCXX/cxx1z-copy-omission.cpp
 Line 177: candidate function template not viable: requires 1 argument, but 0 
were provided
3 errors generated.
```

When I first found the issue I spent some time trying to reduce it down but w/o 
success.

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


[clang] c743986 - Enter the function parameter mangling scope for a function encoding

2023-09-25 Thread Richard Smith via cfe-commits

Author: Richard Smith
Date: 2023-09-25T16:19:02-07:00
New Revision: c74398649f28ab78c74bacfe82e69224377008e7

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

LOG: Enter the function parameter mangling scope for a function encoding
before mangling the template argument list.

With an abbreviated function template, the template parameters can
contain constraints that refer to the function parameters, so we need to
bring the function parameters into scope earlier.

Fixes #67356.

Added: 


Modified: 
clang/lib/AST/ItaniumMangle.cpp
clang/test/CodeGenCXX/mangle-concept.cpp

Removed: 




diff  --git a/clang/lib/AST/ItaniumMangle.cpp b/clang/lib/AST/ItaniumMangle.cpp
index 4cb1ab56a1e618a..a11dbe22b196e41 100644
--- a/clang/lib/AST/ItaniumMangle.cpp
+++ b/clang/lib/AST/ItaniumMangle.cpp
@@ -841,8 +841,17 @@ void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) 
{
 
   AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
   if (ReturnTypeAbiTags.empty()) {
-// There are no tags for return type, the simplest case.
+// There are no tags for return type, the simplest case. Enter the function
+// parameter scope before mangling the name, because a template using
+// constrained `auto` can have references to its parameters within its
+// template argument list:
+//
+//   template void f(T x, C auto)
+// ... is mangled as ...
+//   template U> void f(T, U)
+FunctionTypeDepthState Saved = FunctionTypeDepth.push();
 mangleName(GD);
+FunctionTypeDepth.pop(Saved);
 mangleFunctionEncodingBareType(FD);
 return;
   }
@@ -855,7 +864,10 @@ void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) 
{
   CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
   // Output name of the function.
   FunctionEncodingMangler.disableDerivedAbiTags();
+
+  FunctionTypeDepthState Saved = FunctionTypeDepth.push();
   FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
+  FunctionTypeDepth.pop(Saved);
 
   // Remember length of the function name in the buffer.
   size_t EncodingPositionStart = FunctionEncodingStream.str().size();
@@ -873,7 +885,9 @@ void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
   AdditionalAbiTags.end());
 
   // Output name with implicit tags and function encoding from temporary 
buffer.
+  Saved = FunctionTypeDepth.push();
   mangleNameWithAbiTags(FD, );
+  FunctionTypeDepth.pop(Saved);
   Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
 
   // Function encoding could create new substitutions so we have to add

diff  --git a/clang/test/CodeGenCXX/mangle-concept.cpp 
b/clang/test/CodeGenCXX/mangle-concept.cpp
index 391cf09ede8555d..efab169903395ac 100644
--- a/clang/test/CodeGenCXX/mangle-concept.cpp
+++ b/clang/test/CodeGenCXX/mangle-concept.cpp
@@ -228,3 +228,15 @@ namespace gh67244 {
   // CHECK: define {{.*}} @_ZN7gh672441fITkNS_1CIifEEiEEvT_(
   template void f(int);
 }
+
+namespace gh67356 {
+  template concept C = true;
+  template void f(T t, C auto) {}
+  // CHECK: define {{.*}} @_ZN7gh673561fIiTkNS_1CIDtfL0p_EEEiEEvT_T0_(
+  template void f(int, int);
+
+  // Note, we use `fL0p` not `fp` above because:
+  template void g(T t, C decltype(f(t, u))> auto) {}
+  // CHECK: define {{.*}} 
@_ZN7gh673561gIiTkNS_1CIFDTcl1ffL0p_fp_EET_EEEiEEvS3_T0_(
+  template void g(int, int);
+}



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


[PATCH] D158296: [clang] Diagnose overly complex Record in __builtin_dump_struct

2023-09-25 Thread David Blaikie via Phabricator via cfe-commits
dblaikie added a comment.

@rsmith ping on this thread - wondering what you'd prefer the direction be here


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158296/new/

https://reviews.llvm.org/D158296

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


[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Richard Smith via cfe-commits


@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}

zygoloid wrote:

Do we need an invalid deduction guide here to hit this problem? If I'm 
understanding correctly, what's happening here is:

- The explicit deduction guide (that's not actually a deduction guide at all) 
triggers generation of implicit deduction guides.
- Generating an implicit deduction guide produces a warning.
- The warning has the implicit deduction guide on the stack, hitting the 
`unreachable`

If so, I think it would be clearer to write the test in a way that doesn't 
produce an error:
```suggestion
};

constexpr bool C3(...) { return true; }
B3 b3; // expected-note {{while building deduction guide here}}
```

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


[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Richard Smith via cfe-commits


@@ -5414,6 +5414,8 @@ def note_constraint_normalization_here : Note<
 def note_parameter_mapping_substitution_here : Note<
   "while substituting into concept arguments here; substitution failures not "
   "allowed in concept arguments">;
+def note_building_deduction_guide_here : Note<
+  "while building deduction guide here">;

zygoloid wrote:

Maybe we could make this a bit more descriptive:
```suggestion
  "while building implicit deduction guide first needed here">;
```
(Can we list the template name in this diagnostic too, "... deduction guide for 
%0 ..."? Might be nice, but I think it'll be pretty obvious most of the time, 
so it seems non-essential.)

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


[PATCH] D158641: [AArch64] Fix FMV ifunc resolver usage on old Android APIs. Rename internal compiler-rt FMV functions.

2023-09-25 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay accepted this revision.
MaskRay added a comment.
This revision is now accepted and ready to land.

The Clang Driver/CodeGen and compiler-rt changes look good to me. Of course 
please wait for an Android reviewer :)


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158641/new/

https://reviews.llvm.org/D158641

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


[clang] [Sema] Use underlying type of scoped enum for -Wformat diagnostics (PR #67378)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Right now, `-Wformat` for a scoped enum will suggest a cast based on the
format specifier being used. This can lead to incorrect results, e.g.
attempting to format a scoped enum with `%s` would suggest casting to
`char *` instead of fixing the specifier. Change the logic to treat the
scoped enum's underlying type as the intended type to be printed, and
suggest format specifier changes and casts based on that.


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


3 Files Affected:

- (modified) clang/lib/Sema/SemaChecking.cpp (+12-13) 
- (added) clang/test/FixIt/format-darwin-enum-class.cpp (+35) 
- (modified) clang/test/FixIt/format.cpp (+18-2) 


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 1d56c495e899722..5af52ea5564248d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11345,12 +11345,15 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   ImplicitMatch == ArgType::NoMatchTypeConfusion)
 Match = ImplicitMatch;
   assert(Match != ArgType::MatchPromotion);
+
   // Look through unscoped enums to their underlying type.
   bool IsEnum = false;
   bool IsScopedEnum = false;
+  QualType IntendedTy = ExprTy;
   if (auto EnumTy = ExprTy->getAs()) {
+IntendedTy = EnumTy->getDecl()->getIntegerType();
 if (EnumTy->isUnscopedEnumerationType()) {
-  ExprTy = EnumTy->getDecl()->getIntegerType();
+  ExprTy = IntendedTy;
   // This controls whether we're talking about the underlying type or not,
   // which we only want to do when it's an unscoped enum.
   IsEnum = true;
@@ -11362,7 +11365,6 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   // %C in an Objective-C context prints a unichar, not a wchar_t.
   // If the argument is an integer of some kind, believe the %C and suggest
   // a cast instead of changing the conversion specifier.
-  QualType IntendedTy = ExprTy;
   if (isObjCContext() &&
   FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
@@ -11398,8 +11400,10 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, 
IntendedTy, E);
 if (!CastTy.isNull()) {
   // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
-  // (long in ASTContext). Only complain to pedants.
-  if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
+  // (long in ASTContext). Only complain to pedants or when they're the
+  // underlying type of a scoped enum (which always needs a cast).
+  if (!IsScopedEnum &&
+  (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
   (AT.isSizeT() || AT.isPtrdiffT()) &&
   AT.matchesType(S.Context, CastTy))
 Match = ArgType::NoMatchPedantic;
@@ -11454,20 +11458,15 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   // should be printed as 'long' for 64-bit compatibility.)
   // Rather than emitting a normal format/argument mismatch, we want to
   // add a cast to the recommended type (and correct the format string
-  // if necessary).
+  // if necessary). We should also do so for scoped enumerations.
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
   CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
-  if (IsScopedEnum) {
-CastFix << AT.getRepresentativeType(S.Context).getAsString(
-S.Context.getPrintingPolicy());
-  } else {
-IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
-  }
+  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
   CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
-  if ((!AT.matchesType(S.Context, IntendedTy) && !IsScopedEnum) ||
+  if (AT.matchesType(S.Context, IntendedTy) != ArgType::Match ||
   ShouldNotPrintDirectly)
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
@@ -11495,7 +11494,7 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
 Hints.push_back(FixItHint::CreateInsertion(After, ")"));
   }
 
-  if (ShouldNotPrintDirectly) {
+  if (ShouldNotPrintDirectly && !IsScopedEnum) {
 // The expression has a type that should not be printed directly.
 // We extract the name from the typedef because we don't want to show
 // the underlying type in the diagnostic.
diff --git a/clang/test/FixIt/format-darwin-enum-class.cpp 
b/clang/test/FixIt/format-darwin-enum-class.cpp
new file mode 100644
index 000..5aa1a80d8614c20
--- /dev/null
+++ b/clang/test/FixIt/format-darwin-enum-class.cpp
@@ -0,0 +1,35 @@
+// RUN: %clang_cc1 -triple 

[clang] [Sema] Use underlying type of scoped enum for -Wformat diagnostics (PR #67378)

2023-09-25 Thread Shoaib Meenai via cfe-commits

https://github.com/smeenai created 
https://github.com/llvm/llvm-project/pull/67378

Right now, `-Wformat` for a scoped enum will suggest a cast based on the
format specifier being used. This can lead to incorrect results, e.g.
attempting to format a scoped enum with `%s` would suggest casting to
`char *` instead of fixing the specifier. Change the logic to treat the
scoped enum's underlying type as the intended type to be printed, and
suggest format specifier changes and casts based on that.


>From a1c307ddcc309b6b915feaad6d09f74ecc3f6e79 Mon Sep 17 00:00:00 2001
From: Shoaib Meenai 
Date: Mon, 25 Sep 2023 13:48:10 -0700
Subject: [PATCH] [Sema] Use underlying type of scoped enum for -Wformat
 diagnostics

Right now, `-Wformat` for a scoped enum will suggest a cast based on the
format specifier being used. This can lead to incorrect results, e.g.
attempting to format a scoped enum with `%s` would suggest casting to
`char *` instead of fixing the specifier. Change the logic to treat the
scoped enum's underlying type as the intended type to be printed, and
suggest format specifier changes and casts based on that.
---
 clang/lib/Sema/SemaChecking.cpp   | 25 +++--
 clang/test/FixIt/format-darwin-enum-class.cpp | 35 +++
 clang/test/FixIt/format.cpp   | 20 +--
 3 files changed, 65 insertions(+), 15 deletions(-)
 create mode 100644 clang/test/FixIt/format-darwin-enum-class.cpp

diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 1d56c495e899722..5af52ea5564248d 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11345,12 +11345,15 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   ImplicitMatch == ArgType::NoMatchTypeConfusion)
 Match = ImplicitMatch;
   assert(Match != ArgType::MatchPromotion);
+
   // Look through unscoped enums to their underlying type.
   bool IsEnum = false;
   bool IsScopedEnum = false;
+  QualType IntendedTy = ExprTy;
   if (auto EnumTy = ExprTy->getAs()) {
+IntendedTy = EnumTy->getDecl()->getIntegerType();
 if (EnumTy->isUnscopedEnumerationType()) {
-  ExprTy = EnumTy->getDecl()->getIntegerType();
+  ExprTy = IntendedTy;
   // This controls whether we're talking about the underlying type or not,
   // which we only want to do when it's an unscoped enum.
   IsEnum = true;
@@ -11362,7 +11365,6 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   // %C in an Objective-C context prints a unichar, not a wchar_t.
   // If the argument is an integer of some kind, believe the %C and suggest
   // a cast instead of changing the conversion specifier.
-  QualType IntendedTy = ExprTy;
   if (isObjCContext() &&
   FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
 if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
@@ -11398,8 +11400,10 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
 std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, 
IntendedTy, E);
 if (!CastTy.isNull()) {
   // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
-  // (long in ASTContext). Only complain to pedants.
-  if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
+  // (long in ASTContext). Only complain to pedants or when they're the
+  // underlying type of a scoped enum (which always needs a cast).
+  if (!IsScopedEnum &&
+  (CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
   (AT.isSizeT() || AT.isPtrdiffT()) &&
   AT.matchesType(S.Context, CastTy))
 Match = ArgType::NoMatchPedantic;
@@ -11454,20 +11458,15 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier ,
   // should be printed as 'long' for 64-bit compatibility.)
   // Rather than emitting a normal format/argument mismatch, we want to
   // add a cast to the recommended type (and correct the format string
-  // if necessary).
+  // if necessary). We should also do so for scoped enumerations.
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
   CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
-  if (IsScopedEnum) {
-CastFix << AT.getRepresentativeType(S.Context).getAsString(
-S.Context.getPrintingPolicy());
-  } else {
-IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
-  }
+  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
   CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
-  if ((!AT.matchesType(S.Context, IntendedTy) && !IsScopedEnum) ||
+  if (AT.matchesType(S.Context, IntendedTy) != ArgType::Match ||
   ShouldNotPrintDirectly)
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
@@ -11495,7 +11494,7 @@ 

[PATCH] D157547: Arm64EC entry/exit thunks, consolidated.

2023-09-25 Thread Eli Friedman via Phabricator via cfe-commits
efriedma updated this revision to Diff 557335.
efriedma added a comment.

Revised so guest exit thunks actually work.  Thanks for the tip about the 
symbols; I forgot to look at the object file in addition to the generated 
assembly.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D157547/new/

https://reviews.llvm.org/D157547

Files:
  clang/lib/CodeGen/CGCXX.cpp
  llvm/include/llvm/IR/CallingConv.h
  llvm/lib/CodeGen/AsmPrinter/AsmPrinter.cpp
  llvm/lib/Target/AArch64/AArch64.h
  llvm/lib/Target/AArch64/AArch64Arm64ECCallLowering.cpp
  llvm/lib/Target/AArch64/AArch64AsmPrinter.cpp
  llvm/lib/Target/AArch64/AArch64CallingConvention.h
  llvm/lib/Target/AArch64/AArch64CallingConvention.td
  llvm/lib/Target/AArch64/AArch64FastISel.cpp
  llvm/lib/Target/AArch64/AArch64FrameLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.cpp
  llvm/lib/Target/AArch64/AArch64ISelLowering.h
  llvm/lib/Target/AArch64/AArch64InstrInfo.cpp
  llvm/lib/Target/AArch64/AArch64InstrInfo.td
  llvm/lib/Target/AArch64/AArch64MCInstLower.cpp
  llvm/lib/Target/AArch64/AArch64RegisterInfo.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.h
  llvm/lib/Target/AArch64/AArch64TargetMachine.cpp
  llvm/lib/Target/AArch64/CMakeLists.txt
  llvm/lib/Target/AArch64/GISel/AArch64CallLowering.cpp
  llvm/lib/Target/AArch64/Utils/AArch64BaseInfo.h
  llvm/test/CodeGen/AArch64/arm64ec-dllimport.ll
  llvm/test/CodeGen/AArch64/arm64ec-reservedregs.ll
  llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
  llvm/test/CodeGen/AArch64/stack-protector-target.ll
  llvm/test/CodeGen/AArch64/win-alloca.ll

Index: llvm/test/CodeGen/AArch64/win-alloca.ll
===
--- llvm/test/CodeGen/AArch64/win-alloca.ll
+++ llvm/test/CodeGen/AArch64/win-alloca.ll
@@ -21,4 +21,4 @@
 ; CHECK-OPT: sub [[REG3:x[0-9]+]], sp, x15, lsl #4
 ; CHECK-OPT: mov sp, [[REG3]]
 ; CHECK: bl func2
-; CHECK-ARM64EC: bl __chkstk_arm64ec
+; CHECK-ARM64EC: bl "#__chkstk_arm64ec"
Index: llvm/test/CodeGen/AArch64/stack-protector-target.ll
===
--- llvm/test/CodeGen/AArch64/stack-protector-target.ll
+++ llvm/test/CodeGen/AArch64/stack-protector-target.ll
@@ -39,6 +39,6 @@
 ; WINDOWS-ARM64EC: adrp x8, __security_cookie
 ; WINDOWS-ARM64EC: ldr x8, [x8, :lo12:__security_cookie]
 ; WINDOWS-ARM64EC: str x8, [sp, #8]
-; WINDOWS-ARM64EC: bl  _Z7CapturePi
+; WINDOWS-ARM64EC: bl "#_Z7CapturePi"
 ; WINDOWS-ARM64EC: ldr x0, [sp, #8]
-; WINDOWS-ARM64EC: bl  __security_check_cookie_arm64ec
+; WINDOWS-ARM64EC: bl "#__security_check_cookie_arm64ec"
Index: llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
===
--- llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
+++ llvm/test/CodeGen/AArch64/arm64ec-varargs.ll
@@ -1,6 +1,6 @@
 ; NOTE: Assertions have been autogenerated by utils/update_llc_test_checks.py
-; RUN: llc -mtriple=arm64ec-pc-windows-msvc < %s | FileCheck %s
-; RUN: llc -mtriple=arm64ec-pc-windows-msvc < %s -global-isel=1 -global-isel-abort=0 | FileCheck %s
+; RUN: llc -mtriple=arm64ec-pc-windows-msvc -arm64ec-generate-thunks=false < %s | FileCheck %s
+; RUN: llc -mtriple=arm64ec-pc-windows-msvc -arm64ec-generate-thunks=false < %s -global-isel=1 -global-isel-abort=0 | FileCheck %s
 
 define void @varargs_callee(double %x, ...) nounwind {
 ; CHECK-LABEL: varargs_callee:
@@ -35,16 +35,20 @@
 ; CHECK-NEXT:sub sp, sp, #48
 ; CHECK-NEXT:mov x4, sp
 ; CHECK-NEXT:add x8, sp, #16
-; CHECK-NEXT:mov x9, #4617315517961601024
-; CHECK-NEXT:mov x0, #4607182418800017408
-; CHECK-NEXT:mov w1, #2
-; CHECK-NEXT:mov x2, #4613937818241073152
-; CHECK-NEXT:mov w3, #4
-; CHECK-NEXT:mov w5, #16
+; CHECK-NEXT:mov x9, #4617315517961601024 // =0x4014
+; CHECK-NEXT:mov x0, #4607182418800017408 // =0x3ff0
+; CHECK-NEXT:mov w1, #2 // =0x2
+; CHECK-NEXT:mov x2, #4613937818241073152 // =0x4008
+; CHECK-NEXT:mov w3, #4 // =0x4
+; CHECK-NEXT:mov w5, #16 // =0x10
 ; CHECK-NEXT:stp xzr, x30, [sp, #24] // 8-byte Folded Spill
 ; CHECK-NEXT:stp x8, xzr, [sp, #8]
 ; CHECK-NEXT:str x9, [sp]
-; CHECK-NEXT:bl varargs_callee
+; CHECK-NEXT:.weak_anti_dep varargs_callee
+; CHECK-NEXT:  .set varargs_callee, "#varargs_callee"@WEAKREF
+; CHECK-NEXT:.weak_anti_dep "#varargs_callee"
+; CHECK-NEXT:  .set "#varargs_callee", varargs_callee@WEAKREF
+; CHECK-NEXT:bl "#varargs_callee"
 ; CHECK-NEXT:ldr x30, [sp, #32] // 8-byte Folded Reload
 ; CHECK-NEXT:add sp, sp, #48
 ; CHECK-NEXT:ret
@@ -71,17 +75,21 @@
 ; CHECK-NEXT:sub sp, sp, #64
 ; CHECK-NEXT:movi v0.2d, #
 ; CHECK-NEXT:mov x4, sp
-; CHECK-NEXT:mov x8, #4618441417868443648
+; CHECK-NEXT:mov x8, #4618441417868443648 // =0x4018
 ; CHECK-NEXT:add x9, sp, #16
 ; 

[PATCH] D158641: [AArch64] Fix FMV ifunc resolver usage on old Android APIs. Rename internal compiler-rt FMV functions.

2023-09-25 Thread Pavel Iliin via Phabricator via cfe-commits
ilinpv added a comment.

The patch tested on NDK r26 bulding simple Function Multi Versioning project 
and running on Android API 25,29,30,33 - works fine.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158641/new/

https://reviews.llvm.org/D158641

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


[PATCH] D158641: [AArch64] Fix FMV ifunc resolver usage on old Android APIs. Rename internal compiler-rt FMV functions.

2023-09-25 Thread Pavel Iliin via Phabricator via cfe-commits
ilinpv updated this revision to Diff 557332.
ilinpv retitled this revision from "[AArch64][Android][DRAFT] Fix FMV ifunc 
resolver usage on old Android APIs." to "[AArch64] Fix FMV ifunc resolver usage 
on old Android APIs. Rename internal compiler-rt FMV functions.".
ilinpv edited the summary of this revision.
ilinpv added a comment.
Herald added a subscriber: dberris.

Use weak "memfd_create" to check for API 30, split and rename init cpu features 
functions ( __init_cpu_features, __init_cpu_features_resolver, 
__init_cpu_features_constructor )


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158641/new/

https://reviews.llvm.org/D158641

Files:
  clang/lib/CodeGen/CGBuiltin.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGen/attr-target-clones-aarch64.c
  clang/test/CodeGen/attr-target-version.c
  clang/test/CodeGenCXX/attr-target-clones-aarch64.cpp
  clang/test/CodeGenCXX/attr-target-version.cpp
  clang/test/Driver/aarch64-features.c
  compiler-rt/lib/builtins/cpu_model.c

Index: compiler-rt/lib/builtins/cpu_model.c
===
--- compiler-rt/lib/builtins/cpu_model.c
+++ compiler-rt/lib/builtins/cpu_model.c
@@ -1186,13 +1186,12 @@
   // As features grows new fields could be added
 } __aarch64_cpu_features __attribute__((visibility("hidden"), nocommon));
 
-void init_cpu_features_resolver(unsigned long hwcap, const __ifunc_arg_t *arg) {
+static void __init_cpu_features_constructor(unsigned long hwcap,
+const __ifunc_arg_t *arg) {
 #define setCPUFeature(F) __aarch64_cpu_features.features |= 1ULL << F
 #define getCPUFeature(id, ftr) __asm__("mrs %0, " #id : "=r"(ftr))
 #define extractBits(val, start, number)\
   (val & ((1ULL << number) - 1ULL) << start) >> start
-  if (__aarch64_cpu_features.features)
-return;
   unsigned long hwcap2 = 0;
   if (hwcap & _IFUNC_ARG_HWCAP)
 hwcap2 = arg->_hwcap2;
@@ -1374,7 +1373,24 @@
   setCPUFeature(FEAT_MAX);
 }
 
-void CONSTRUCTOR_ATTRIBUTE init_cpu_features(void) {
+void __init_cpu_features_resolver(unsigned long hwcap,
+  const __ifunc_arg_t *arg) {
+  if (__aarch64_cpu_features.features)
+return;
+#if defined(__ANDROID__)
+  // ifunc resolvers don't have hwcaps in arguments on Android API lower
+  // than 30. If so, set feature detection done and keep all CPU features
+  // unsupported (zeros). To detect this case in runtime we check existence
+  // of memfd_create function from Standard C library which was introduced in
+  // Android API 30.
+  int memfd_create(const char *, unsigned int) __attribute__((weak));
+  if (!memfd_create)
+return;
+#endif // defined(__ANDROID__)
+  __init_cpu_features_constructor(hwcap, arg);
+}
+
+void CONSTRUCTOR_ATTRIBUTE __init_cpu_features(void) {
   unsigned long hwcap;
   unsigned long hwcap2;
   // CPU features already initialized.
@@ -1399,7 +1415,7 @@
   arg._size = sizeof(__ifunc_arg_t);
   arg._hwcap = hwcap;
   arg._hwcap2 = hwcap2;
-  init_cpu_features_resolver(hwcap | _IFUNC_ARG_HWCAP, );
+  __init_cpu_features_constructor(hwcap | _IFUNC_ARG_HWCAP, );
 #undef extractBits
 #undef getCPUFeature
 #undef setCPUFeature
Index: clang/test/Driver/aarch64-features.c
===
--- clang/test/Driver/aarch64-features.c
+++ clang/test/Driver/aarch64-features.c
@@ -7,15 +7,17 @@
 // CHECK: fno-signed-char
 
 // Check Function Multi Versioning option and rtlib dependency.
-// RUN: %clang --target=aarch64-linux-android -rtlib=compiler-rt \
+// RUN: %clang --target=aarch64-linux-android23 -rtlib=compiler-rt \
 // RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV %s
-
+// RUN: %clang --target=aarch64-linux-android -rtlib=compiler-rt \
+// RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV-OFF %s
 // RUN: %clang --target=aarch64-linux-android -rtlib=compiler-rt -mno-fmv \
 // RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV-OFF %s
+// RUN: %clang --target=aarch64-linux-android22 -rtlib=compiler-rt \
+// RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV-OFF %s
 
 // RUN: %clang --target=aarch64-linux-gnu -rtlib=libgcc \
 // RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV-OFF %s
-
 // RUN: %clang --target=arm64-unknown-linux -rtlib=libgcc \
 // RUN: -### -c %s 2>&1 | FileCheck -check-prefix=CHECK-FMV-OFF %s
 
Index: clang/test/CodeGenCXX/attr-target-version.cpp
===
--- clang/test/CodeGenCXX/attr-target-version.cpp
+++ clang/test/CodeGenCXX/attr-target-version.cpp
@@ -78,7 +78,7 @@
 // CHECK-NEXT:ret i32 [[ADD3]]
 // CHECK-LABEL: @_ZN7MyClass3gooEi.resolver(
 // CHECK-NEXT:  resolver_entry:
-// CHECK-NEXT:call void @init_cpu_features_resolver()
+// CHECK-NEXT:call void @__init_cpu_features_resolver()
 // CHECK-NEXT:[[TMP0:%.*]] 

[libunwind] f958381 - [libunwind] Clarify comment added in #67205

2023-09-25 Thread Alex Richardson via cfe-commits

Author: Alex Richardson
Date: 2023-09-25T15:04:23-07:00
New Revision: f9583815e7e9bd5d57ef27232e6cbbc426e03824

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

LOG: [libunwind] Clarify comment added in #67205

See https://github.com/llvm/llvm-project/pull/67205#issuecomment-1734443684

Added: 


Modified: 
libunwind/test/configs/llvm-libunwind-merged.cfg.in
libunwind/test/configs/llvm-libunwind-shared.cfg.in
libunwind/test/configs/llvm-libunwind-static.cfg.in

Removed: 




diff  --git a/libunwind/test/configs/llvm-libunwind-merged.cfg.in 
b/libunwind/test/configs/llvm-libunwind-merged.cfg.in
index 624caec987e15b2..38b79840c9fe282 100644
--- a/libunwind/test/configs/llvm-libunwind-merged.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-merged.cfg.in
@@ -11,7 +11,7 @@ link_flags = []
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 

diff  --git a/libunwind/test/configs/llvm-libunwind-shared.cfg.in 
b/libunwind/test/configs/llvm-libunwind-shared.cfg.in
index bd7a153ac6d1d54..13896aeb13bc4a9 100644
--- a/libunwind/test/configs/llvm-libunwind-shared.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-shared.cfg.in
@@ -10,7 +10,7 @@ link_flags = []
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 

diff  --git a/libunwind/test/configs/llvm-libunwind-static.cfg.in 
b/libunwind/test/configs/llvm-libunwind-static.cfg.in
index 5956c32cc625b2b..50b64dc665a5af5 100644
--- a/libunwind/test/configs/llvm-libunwind-static.cfg.in
+++ b/libunwind/test/configs/llvm-libunwind-static.cfg.in
@@ -13,7 +13,7 @@ if @LIBUNWIND_ENABLE_THREADS@:
 if @LIBUNWIND_ENABLE_CET@:
 compile_flags.append('-fcf-protection=full')
 
-# On ELF platforms, add -Wl,--export-dynamic if supported by the linker.
+# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
 if len('@CMAKE_EXE_EXPORTS_CXX_FLAG@'):
 link_flags.append('@CMAKE_EXE_EXPORTS_CXX_FLAG@')
 



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


[clang] [clang] Predefined macros for float128 support (PR #67196)

2023-09-25 Thread Alexander Shaposhnikov via cfe-commits


@@ -1076,6 +1076,8 @@ static void InitializePredefinedMacros(const TargetInfo 
,
   DefineFloatMacros(Builder, "FLT", (), "F");
   DefineFloatMacros(Builder, "DBL", (), "");
   DefineFloatMacros(Builder, "LDBL", (), "L");
+  if (TI.hasFloat128Type())
+DefineFloatMacros(Builder, "FLT128", (), "Q");

alexander-shaposhnikov wrote:

This needs tests (see e.g. https://reviews.llvm.org/D111382, 
https://github.com/llvm/llvm-project/blob/main/clang/test/Preprocessor)

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


[libunwind] [libunwind] Pass -Wl,--export-dynamic on all supported platforms (PR #67205)

2023-09-25 Thread Alexander Richardson via cfe-commits

arichardson wrote:

> Can you as a small follow-up just update the comment to include that part? 
> E.g.
> 
Will do.

> ```
> # On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
> linker.
> ```
> 
> Side note: the much older way for doing this is actually `-rdynamic`.

It appears CMake actually still does this in one case:
```
Modules/Platform/Linux-TinyCC-C.cmake:set(CMAKE_EXE_EXPORTS_C_FLAG "-rdynamic ")
```

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


[clang] [NVPTX] Add support for maxclusterrank in launch_bounds (PR #66496)

2023-09-25 Thread Artem Belevich via cfe-commits

https://github.com/Artem-B approved this pull request.


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


[clang] [ASTMatchers] Fix classIsDerivedFrom for recusrive cases (PR #67307)

2023-09-25 Thread Caslyn Tonelli via cfe-commits

Caslyn wrote:

Hi @sam-mccall - thank you, and apologies for the false alarm.

After closer inspection, it looks like 
https://github.com/llvm/llvm-project/issues/66114#issuecomment-1732319259 
explains the particular failures we're seeing. Indeed, no relation to this PR - 
please consider this matter closed here.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen


Changes

Fixes #67154

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


6 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+6-2) 
- (modified) clang/lib/CodeGen/CodeGenModule.cpp (+14-3) 
- (modified) clang/lib/Sema/SemaDeclAttr.cpp (+22-11) 
- (modified) clang/test/CodeGenCXX/constructor-attr.cpp (+14) 
- (added) clang/test/CodeGenCXX/destructor-attr.cpp (+20) 
- (added) clang/test/Sema/ctor-dtor-attr.cpp (+13) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dd4d45171db4899..8c4e63bebf110cf 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1156,9 +1156,11 @@ def ConstInit : InheritableAttr {
 
 def Constructor : InheritableAttr {
   let Spellings = [GCC<"constructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];
 }
 
 def CPUSpecific : InheritableAttr {
@@ -1422,9 +1424,11 @@ def Deprecated : InheritableAttr {
 
 def Destructor : InheritableAttr {
   let Spellings = [GCC<"destructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];
 }
 
 def EmptyBases : InheritableAttr, TargetSpecificAttr {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 130cedcd4f2bf68..e93c36bbce95ec6 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -32,6 +32,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
@@ -5661,10 +5662,20 @@ void 
CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
   setNonAliasAttributes(GD, Fn);
   SetLLVMFunctionAttributesForDefinition(D, Fn);
 
-  if (const ConstructorAttr *CA = D->getAttr())
-AddGlobalCtor(Fn, CA->getPriority());
+  auto getPrio = [this](auto *Attr) -> int {
+Expr *E = Attr->getPriority();
+if (!E)
+  return Attr->DefaultPriority;
+if (auto CE = E->getIntegerConstantExpr(getContext()))
+  return CE->getExtValue();
+return Attr->DefaultPriority;
+  };
+
+  if (const ConstructorAttr *CA = D->getAttr()) {
+AddGlobalCtor(Fn, getPrio(CA));
+  }
   if (const DestructorAttr *DA = D->getAttr())
-AddGlobalDtor(Fn, DA->getPriority(), true);
+AddGlobalDtor(Fn, getPrio(DA), true);
   if (D->hasAttr())
 AddGlobalAnnotations(D, Fn);
   if (getLangOpts().OpenMP && D->hasAttr())
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 090a54eedaa07d0..d857f5e78ae97a3 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2352,26 +2352,37 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t priority = Attr::DefaultPriority;
+  Expr *E = nullptr;
+  if (AL.getNumArgs()) {
+E = AL.getArgAsExpr(0);
+if (E->isValueDependent()) {
+  if (!E->isTypeDependent() && !E->getType()->isIntegerType()) {
+S.Diag(getAttrLoc(AL), diag::err_attribute_argument_type)
+<<  << AANT_ArgumentIntegerConstant << E->getSourceRange();
+return;
+  }
+} else if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) {
+  return;
+}
+  }
+
+  D->addAttr(::new (S.Context) Attr(S.Context, AL, E));
+}
+
 static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
   if (S.getLangOpts().HLSL && AL.getNumArgs()) {
 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
 return;
   }
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
 
-  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
+  handleCtorDtorAttr(S, D, AL);
 }
 
 static void handleDestructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = DestructorAttr::DefaultPriority;
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
-
-  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
+  return handleCtorDtorAttr(S, D, AL);
 }
 
 template 
diff --git a/clang/test/CodeGenCXX/constructor-attr.cpp 
b/clang/test/CodeGenCXX/constructor-attr.cpp
index 

[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Shafik Yaghmour via cfe-commits

shafik wrote:

I was originally going to roll-up this fix as part of: 
https://reviews.llvm.org/D148474 but it felt distinct enough to fix on its own 
and then rebase the other PR afterwards.

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


[clang] [clang] All {con, de}structor attributes to use template args (PR #67376)

2023-09-25 Thread Alex Brachet via cfe-commits

https://github.com/abrachet created 
https://github.com/llvm/llvm-project/pull/67376

Fixes #67154

>From 5317e66d8997c0406994809901429d5a88c0e0c6 Mon Sep 17 00:00:00 2001
From: Alex Brachet 
Date: Mon, 25 Sep 2023 17:35:13 -0400
Subject: [PATCH] [clang] All {con,de}structor attributes to use template args

Fixes #67154
---
 clang/include/clang/Basic/Attr.td  |  8 --
 clang/lib/CodeGen/CodeGenModule.cpp| 17 +--
 clang/lib/Sema/SemaDeclAttr.cpp| 33 ++
 clang/test/CodeGenCXX/constructor-attr.cpp | 14 +
 clang/test/CodeGenCXX/destructor-attr.cpp  | 20 +
 clang/test/Sema/ctor-dtor-attr.cpp | 13 +
 6 files changed, 89 insertions(+), 16 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/destructor-attr.cpp
 create mode 100644 clang/test/Sema/ctor-dtor-attr.cpp

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index dd4d45171db4899..8c4e63bebf110cf 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1156,9 +1156,11 @@ def ConstInit : InheritableAttr {
 
 def Constructor : InheritableAttr {
   let Spellings = [GCC<"constructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];
 }
 
 def CPUSpecific : InheritableAttr {
@@ -1422,9 +1424,11 @@ def Deprecated : InheritableAttr {
 
 def Destructor : InheritableAttr {
   let Spellings = [GCC<"destructor">];
-  let Args = [DefaultIntArgument<"Priority", 65535>];
+  let Args = [ExprArgument<"Priority", 1>];
   let Subjects = SubjectList<[Function]>;
   let Documentation = [CtorDtorDocs];
+  let TemplateDependent = 1;
+  let AdditionalMembers = [{ static const int DefaultPriority = 65535; }];
 }
 
 def EmptyBases : InheritableAttr, TargetSpecificAttr {
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index 130cedcd4f2bf68..e93c36bbce95ec6 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -32,6 +32,7 @@
 #include "clang/AST/DeclCXX.h"
 #include "clang/AST/DeclObjC.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/AST/Expr.h"
 #include "clang/AST/Mangle.h"
 #include "clang/AST/RecursiveASTVisitor.h"
 #include "clang/AST/StmtVisitor.h"
@@ -5661,10 +5662,20 @@ void 
CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
   setNonAliasAttributes(GD, Fn);
   SetLLVMFunctionAttributesForDefinition(D, Fn);
 
-  if (const ConstructorAttr *CA = D->getAttr())
-AddGlobalCtor(Fn, CA->getPriority());
+  auto getPrio = [this](auto *Attr) -> int {
+Expr *E = Attr->getPriority();
+if (!E)
+  return Attr->DefaultPriority;
+if (auto CE = E->getIntegerConstantExpr(getContext()))
+  return CE->getExtValue();
+return Attr->DefaultPriority;
+  };
+
+  if (const ConstructorAttr *CA = D->getAttr()) {
+AddGlobalCtor(Fn, getPrio(CA));
+  }
   if (const DestructorAttr *DA = D->getAttr())
-AddGlobalDtor(Fn, DA->getPriority(), true);
+AddGlobalDtor(Fn, getPrio(DA), true);
   if (D->hasAttr())
 AddGlobalAnnotations(D, Fn);
   if (getLangOpts().OpenMP && D->hasAttr())
diff --git a/clang/lib/Sema/SemaDeclAttr.cpp b/clang/lib/Sema/SemaDeclAttr.cpp
index 090a54eedaa07d0..d857f5e78ae97a3 100644
--- a/clang/lib/Sema/SemaDeclAttr.cpp
+++ b/clang/lib/Sema/SemaDeclAttr.cpp
@@ -2352,26 +2352,37 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
+template 
+static void handleCtorDtorAttr(Sema , Decl *D, const ParsedAttr ) {
+  uint32_t priority = Attr::DefaultPriority;
+  Expr *E = nullptr;
+  if (AL.getNumArgs()) {
+E = AL.getArgAsExpr(0);
+if (E->isValueDependent()) {
+  if (!E->isTypeDependent() && !E->getType()->isIntegerType()) {
+S.Diag(getAttrLoc(AL), diag::err_attribute_argument_type)
+<<  << AANT_ArgumentIntegerConstant << E->getSourceRange();
+return;
+  }
+} else if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) {
+  return;
+}
+  }
+
+  D->addAttr(::new (S.Context) Attr(S.Context, AL, E));
+}
+
 static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
   if (S.getLangOpts().HLSL && AL.getNumArgs()) {
 S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
 return;
   }
-  if (AL.getNumArgs() &&
-  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
-return;
 
-  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
+  handleCtorDtorAttr(S, D, AL);
 }
 
 static void handleDestructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = DestructorAttr::DefaultPriority;
-  if 

[PATCH] D157547: Arm64EC entry/exit thunks, consolidated.

2023-09-25 Thread Jacek Caban via Phabricator via cfe-commits
jacek added a comment.

In D157547#4650643 , @efriedma wrote:

> Seems to be working for simple cases, but I'm not sure this is actually 
> working properly (I'm still seeing LNK1000 crashes).

I don't know if it's related to crashes that you're seeing, but those 
anti-dependency symbols look different than what MSVC produces. With the patch, 
I get:

$ cat extfunc.c
extern void extfunc(void);
void func(void) { extfunc(); }
$ clang -target arm64ec-windows -c extcall.c -o extcall.o
$ llvm-readobj --symbols extcall.o
...

  Symbol {
Name: #extfunc
Value: 0
Section: IMAGE_SYM_UNDEFINED (0)
BaseType: Null (0x0)
ComplexType: Null (0x0)
StorageClass: WeakExternal (0x69)
AuxSymbolCount: 1
AuxWeakExternal {
  Linked: .weak.#extfunc.default.#func (40)
  Search: AntiDependency (0x4)
}
  }

...

  Symbol {
Name: extfunc
Value: 0
Section: IMAGE_SYM_UNDEFINED (0)
BaseType: Null (0x0)
ComplexType: Null (0x0)
StorageClass: WeakExternal (0x69)
AuxSymbolCount: 1
AuxWeakExternal {
  Linked: #extfunc$exit_thunk (43)
  Search: AntiDependency (0x4)
}
  }

While an equivalent object file produced by MSVC has:

  Symbol {
Name: #extfunc
Value: 0
Section: IMAGE_SYM_UNDEFINED (0)
BaseType: Null (0x0)
ComplexType: Function (0x2)
StorageClass: WeakExternal (0x69)
AuxSymbolCount: 1
AuxWeakExternal {
  Linked: #extfunc$exit_thunk (14)
  Search: AntiDependency (0x4)
}
  }
  Symbol {
Name: extfunc
Value: 0
Section: IMAGE_SYM_UNDEFINED (0)
BaseType: Null (0x0)
ComplexType: Function (0x2)
StorageClass: WeakExternal (0x69)
AuxSymbolCount: 1
AuxWeakExternal {
  Linked: #extfunc (19)
  Search: AntiDependency (0x4)
}
  }

It's the mangled symbol that's linked to guest exit thunk, not unmangled one. 
Also there is no .weak.*.default.* involved.

BTW, I hope to get my WIP lld-link branch into usable state very soon and plan 
to publish it then. I'm able to link real-world code now, but it still requires 
a few hacks that I need to fix to make it work out of the box. Hopefully it 
will make testing and debugging such problems easier.


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D157547/new/

https://reviews.llvm.org/D157547

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


[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

In some cases where ill-formed code could be interpreted as a deduction guide 
we can crash because we reach an unreachable path. This fixes this issue by 
introducing a diagnostic instead.

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

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


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+2) 
- (modified) clang/lib/Sema/SemaTemplateInstantiate.cpp (+3-1) 
- (modified) clang/test/SemaCXX/cxx1z-copy-omission.cpp (+9) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f4eb02fd9570c2f..a6db3f3d0105742 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5414,6 +5414,8 @@ def note_constraint_normalization_here : Note<
 def note_parameter_mapping_substitution_here : Note<
   "while substituting into concept arguments here; substitution failures not "
   "allowed in concept arguments">;
+def note_building_deduction_guide_here : Note<
+  "while building deduction guide here">;
 def note_lambda_substitution_here : Note<
   "while substituting into a lambda expression here">;
 def note_instantiation_contexts_suppressed : Note<
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 00a36696cf90450..1ed3df5a011bcb6 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1075,7 +1075,9 @@ void Sema::PrintInstantiationStack() {
   << Active->InstantiationRange;
   break;
 case CodeSynthesisContext::BuildingDeductionGuides:
-  llvm_unreachable("unexpected deduction guide in instantiation stack");
+  Diags.Report(Active->PointOfInstantiation,
+   diag::note_building_deduction_guide_here);
+  break;
 }
   }
 }
diff --git a/clang/test/SemaCXX/cxx1z-copy-omission.cpp 
b/clang/test/SemaCXX/cxx1z-copy-omission.cpp
index a850cf6143cd480..819cba258915eef 100644
--- a/clang/test/SemaCXX/cxx1z-copy-omission.cpp
+++ b/clang/test/SemaCXX/cxx1z-copy-omission.cpp
@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}
+}

``




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


[clang] [Clang] Fix crash when ill-formed code is treated as a deduction guide (PR #67373)

2023-09-25 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik created 
https://github.com/llvm/llvm-project/pull/67373

In some cases where ill-formed code could be interpreted as a deduction guide 
we can crash because we reach an unreachable path. This fixes this issue by 
introducing a diagnostic instead.

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

>From 1877bccd38d15b74883d7bd24f4cacd477c9d820 Mon Sep 17 00:00:00 2001
From: Shafik Yaghmour 
Date: Mon, 25 Sep 2023 13:56:43 -0700
Subject: [PATCH] [Clang] Fix crash when ill-formed code is treated as a
 deduction guide

In some cases where ill-formed code could be interpreted as a deduction guide
we can crash because we reach an unreachable path. This fixes this issue by
introducing a diagnostic instead.

Fixes: https://github.com/llvm/llvm-project/issues/65522
---
 clang/include/clang/Basic/DiagnosticSemaKinds.td | 2 ++
 clang/lib/Sema/SemaTemplateInstantiate.cpp   | 4 +++-
 clang/test/SemaCXX/cxx1z-copy-omission.cpp   | 9 +
 3 files changed, 14 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index f4eb02fd9570c2f..a6db3f3d0105742 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -5414,6 +5414,8 @@ def note_constraint_normalization_here : Note<
 def note_parameter_mapping_substitution_here : Note<
   "while substituting into concept arguments here; substitution failures not "
   "allowed in concept arguments">;
+def note_building_deduction_guide_here : Note<
+  "while building deduction guide here">;
 def note_lambda_substitution_here : Note<
   "while substituting into a lambda expression here">;
 def note_instantiation_contexts_suppressed : Note<
diff --git a/clang/lib/Sema/SemaTemplateInstantiate.cpp 
b/clang/lib/Sema/SemaTemplateInstantiate.cpp
index 00a36696cf90450..1ed3df5a011bcb6 100644
--- a/clang/lib/Sema/SemaTemplateInstantiate.cpp
+++ b/clang/lib/Sema/SemaTemplateInstantiate.cpp
@@ -1075,7 +1075,9 @@ void Sema::PrintInstantiationStack() {
   << Active->InstantiationRange;
   break;
 case CodeSynthesisContext::BuildingDeductionGuides:
-  llvm_unreachable("unexpected deduction guide in instantiation stack");
+  Diags.Report(Active->PointOfInstantiation,
+   diag::note_building_deduction_guide_here);
+  break;
 }
   }
 }
diff --git a/clang/test/SemaCXX/cxx1z-copy-omission.cpp 
b/clang/test/SemaCXX/cxx1z-copy-omission.cpp
index a850cf6143cd480..819cba258915eef 100644
--- a/clang/test/SemaCXX/cxx1z-copy-omission.cpp
+++ b/clang/test/SemaCXX/cxx1z-copy-omission.cpp
@@ -171,3 +171,12 @@ namespace CtorTemplateBeatsNonTemplateConversionFn {
   Foo f(Derived d) { return d; } // expected-error {{invokes a deleted 
function}}
   Foo g(Derived d) { return Foo(d); } // ok, calls constructor
 }
+
+namespace GH65522 {
+template
+class B3 : A3 {
+  template()> // expected-warning 2{{use of function template 
name with no prior declaration in function call with explicit}}
+  B3();
+}; B3(); // expected-error {{deduction guide declaration without trailing 
return type}} \
+ // expected-note {{while building deduction guide here}}
+}

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


[PATCH] D158561: [-Wunsafe-buffer-usage] Add AST info to the unclaimed DRE debug notes for analysis

2023-09-25 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 557330.
ziqingluo-90 added a comment.

Address comments.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D158561/new/

https://reviews.llvm.org/D158561

Files:
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
  
clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
  clang/utils/analyze_safe_buffer_debug_notes.py

Index: clang/utils/analyze_safe_buffer_debug_notes.py
===
--- /dev/null
+++ clang/utils/analyze_safe_buffer_debug_notes.py
@@ -0,0 +1,39 @@
+import sys
+from collections import OrderedDict
+
+class Trie:
+def __init__(self, name):
+self.name = name
+self.children = OrderedDict()
+self.count = 1
+
+def add(self, name):
+if name in self.children:
+self.children[name].count += 1
+else:
+self.children[name] = Trie(name)
+return self.children[name]
+
+def print(self, depth):
+if depth > 0:
+print('|', end="")
+for i in range(depth):
+print('-', end="")
+if depth > 0:
+print(end=" ")
+print(self.name, '#', self.count)
+for key, child in self.children.items():
+child.print(depth + 1)
+
+
+Root = Trie("Root")
+
+if __name__ == "__main__":
+for line in sys.stdin:
+words = line.split('==>')
+words = [word.strip() for word in words]
+MyTrie = Root;
+for word in words:
+MyTrie = MyTrie.add(word)
+
+Root.print(0)
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/warn-unsafe-buffer-usage-debug-unclaimed.cpp
@@ -0,0 +1,48 @@
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 -verify=expected %s
+
+// RUN: %clang_cc1 -Wno-unused-value -Wunsafe-buffer-usage -fsafe-buffer-usage-suggestions \
+// RUN:-mllvm -debug-only=SafeBuffers \
+// RUN:-std=c++20 %s  \
+// RUN:2>&1 | grep 'The unclaimed DRE trace:' \
+// RUN: | sed 's/^The unclaimed DRE trace://' \
+// RUN: | PYTHON_EXE %S/../../../utils/analyze_safe_buffer_debug_notes.py \
+// RUN: | FileCheck %s
+
+// This debugging facility is only available in debug builds.
+//
+// REQUIRES: asserts
+
+void test_unclaimed_use(int *p) { // expected-warning{{'p' is an unsafe pointer used for buffer access}}
+  p++;   //  expected-note{{used in pointer arithmetic here}} \
+ expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+ The unclaimed DRE trace: DeclRefExpr, UnaryOperator(++), CompoundStmt}}
+  *((p + 1) + 1); // expected-warning{{unsafe pointer arithmetic}}  \
+ expected-note{{used in pointer arithmetic here}}			\
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, ImplicitCastExpr(LValueToRValue), BinaryOperator(+), ParenExpr, BinaryOperator(+), ParenExpr, UnaryOperator(*), CompoundStmt}}
+  p -= 1; // expected-note{{used in pointer arithmetic here}} \
+		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, BinaryOperator(-=), CompoundStmt}}
+  p--;// expected-note{{used in pointer arithmetic here}} \
+ 		 expected-note{{safe buffers debug: failed to produce fixit for 'p' : has an unclaimed use\n \
+  The unclaimed DRE trace: DeclRefExpr, UnaryOperator(--), CompoundStmt}}
+  p[5] = 5;   // expected-note{{used in buffer access here}}
+}
+
+// CHECK: Root # 1
+// CHECK: |- DeclRefExpr # 4
+// CHECK: |-- UnaryOperator(++) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- ImplicitCastExpr(LValueToRValue) # 1
+// CHECK: |--- BinaryOperator(+) # 1
+// CHECK: | ParenExpr # 1
+// CHECK: |- BinaryOperator(+) # 1
+// CHECK: |-- ParenExpr # 1
+// CHECK: |--- UnaryOperator(*) # 1
+// CHECK: | CompoundStmt # 1
+// CHECK: |-- BinaryOperator(-=) # 1
+// CHECK: |--- CompoundStmt # 1
+// CHECK: |-- UnaryOperator(--) # 1
+// CHECK: |--- CompoundStmt # 1
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
===
--- /dev/null
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-debug-unclaimed/lit.local.cfg
@@ -0,0 +1,6 @@
+# -*- Python -*-
+import sys
+
+python_executable = sys.executable

[clang] [ClangRepl] Type Directed Code Completion (PR #67349)

2023-09-25 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 8586cd5ad8a7fa4f84b5913cbeaf634d68500095 
dd3e3e6b8eb3f9f1f740d2a9fc8a62e1964f9153 -- 
clang/include/clang/Interpreter/CodeCompletion.h 
clang/lib/Interpreter/CodeCompletion.cpp clang/tools/clang-repl/ClangRepl.cpp 
clang/unittests/Interpreter/CodeCompletionTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/unittests/Interpreter/CodeCompletionTest.cpp 
b/clang/unittests/Interpreter/CodeCompletionTest.cpp
index fba6e0dbcd31..918b4e8167eb 100644
--- a/clang/unittests/Interpreter/CodeCompletionTest.cpp
+++ b/clang/unittests/Interpreter/CodeCompletionTest.cpp
@@ -287,8 +287,8 @@ TEST(CodeCompletionTest, NestedInvocations) {
 
 TEST(CodeCompletionTest, TemplateFunctions) {
   auto Interp = createInterpreter();
-  cantFail(Interp->ParseAndExecute(
-  "template  T id(T a) { return a;} "));
+  cantFail(
+  Interp->ParseAndExecute("template  T id(T a) { return a;} 
"));
   cantFail(Interp->ParseAndExecute("int apple = 84;"));
   {
 auto Err = llvm::Error::success();
@@ -298,7 +298,8 @@ TEST(CodeCompletionTest, TemplateFunctions) {
 EXPECT_EQ((bool)Err, false);
   }
 
-  cantFail(Interp->ParseAndExecute("template  T pickFirst(T a, T 
b) { return a;} "));
+  cantFail(Interp->ParseAndExecute(
+  "template  T pickFirst(T a, T b) { return a;} "));
   cantFail(Interp->ParseAndExecute("char pear = '4';"));
   {
 auto Err = llvm::Error::success();
@@ -309,5 +310,4 @@ TEST(CodeCompletionTest, TemplateFunctions) {
   }
 }
 
-
 } // anonymous namespace

``




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


[PATCH] D155775: [HIP][Clang][Driver][RFC] Add driver support for C++ Parallel Algorithm Offload

2023-09-25 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx updated this revision to Diff 557328.
AlexVlx added a comment.

Use double dash compiler flags only.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155775/new/

https://reviews.llvm.org/D155775

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/lib/Driver/ToolChains/AMDGPU.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/lib/Driver/ToolChains/HIPAMD.cpp
  clang/lib/Driver/ToolChains/ROCm.h
  clang/test/Driver/Inputs/hipstdpar/hipstdpar_lib.hpp
  clang/test/Driver/hipstdpar.c

Index: clang/test/Driver/hipstdpar.c
===
--- /dev/null
+++ clang/test/Driver/hipstdpar.c
@@ -0,0 +1,18 @@
+// RUN: not %clang -### --hipstdpar -nogpulib -nogpuinc --compile %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=HIPSTDPAR-MISSING-LIB %s
+// RUN: %clang -### --hipstdpar --hipstdpar-path=%S/Inputs/hipstdpar \
+// RUN:   --hipstdpar-thrust-path=%S/Inputs/hipstdpar/thrust \
+// RUN:   --hipstdpar-prim-path=%S/Inputs/hipstdpar/rocprim \
+// RUN:   -nogpulib -nogpuinc --compile %s 2>&1 | \
+// RUN:   FileCheck --check-prefix=HIPSTDPAR-COMPILE %s
+// RUN: touch %t.o
+// RUN: %clang -### --hipstdpar %t.o 2>&1 | FileCheck --check-prefix=HIPSTDPAR-LINK %s
+
+// HIPSTDPAR-MISSING-LIB: error: cannot find HIP Standard Parallelism Acceleration library; provide it via '--hipstdpar-path'
+// HIPSTDPAR-COMPILE: "-x" "hip"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/thrust}}"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/rocprim}}"
+// HIPSTDPAR-COMPILE: "-idirafter" "{{.*/Inputs/hipstdpar}}"
+// HIPSTDPAR-COMPILE: "-include" "hipstdpar_lib.hpp"
+// HIPSTDPAR-LINK: "-rpath"
+// HIPSTDPAR-LINK: "-l{{.*hip.*}}"
Index: clang/lib/Driver/ToolChains/ROCm.h
===
--- clang/lib/Driver/ToolChains/ROCm.h
+++ clang/lib/Driver/ToolChains/ROCm.h
@@ -77,6 +77,9 @@
   const Driver 
   bool HasHIPRuntime = false;
   bool HasDeviceLibrary = false;
+  bool HasHIPStdParLibrary = false;
+  bool HasRocThrustLibrary = false;
+  bool HasRocPrimLibrary = false;
 
   // Default version if not detected or specified.
   const unsigned DefaultVersionMajor = 3;
@@ -96,6 +99,13 @@
   std::vector RocmDeviceLibPathArg;
   // HIP runtime path specified by --hip-path.
   StringRef HIPPathArg;
+  // HIP Standard Parallel Algorithm acceleration library specified by
+  // --hipstdpar-path
+  StringRef HIPStdParPathArg;
+  // rocThrust algorithm library specified by --hipstdpar-thrust-path
+  StringRef HIPRocThrustPathArg;
+  // rocPrim algorithm library specified by --hipstdpar-prim-path
+  StringRef HIPRocPrimPathArg;
   // HIP version specified by --hip-version.
   StringRef HIPVersionArg;
   // Wheter -nogpulib is specified.
@@ -180,6 +190,9 @@
   /// Check whether we detected a valid ROCm device library.
   bool hasDeviceLibrary() const { return HasDeviceLibrary; }
 
+  /// Check whether we detected a valid HIP STDPAR Acceleration library.
+  bool hasHIPStdParLibrary() const { return HasHIPStdParLibrary; }
+
   /// Print information about the detected ROCm installation.
   void print(raw_ostream ) const;
 
Index: clang/lib/Driver/ToolChains/HIPAMD.cpp
===
--- clang/lib/Driver/ToolChains/HIPAMD.cpp
+++ clang/lib/Driver/ToolChains/HIPAMD.cpp
@@ -115,6 +115,8 @@
 "--no-undefined",
 "-shared",
 "-plugin-opt=-amdgpu-internalize-symbols"};
+  if (Args.hasArg(options::OPT_hipstdpar))
+LldArgs.push_back("-plugin-opt=-amdgpu-enable-hipstdpar");
 
   auto  = getToolChain();
   auto  = TC.getDriver();
@@ -246,6 +248,8 @@
   if (!DriverArgs.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc,
   false))
 CC1Args.append({"-mllvm", "-amdgpu-internalize-symbols"});
+  if (DriverArgs.hasArgNoClaim(options::OPT_hipstdpar))
+CC1Args.append({"-mllvm", "-amdgpu-enable-hipstdpar"});
 
   StringRef MaxThreadsPerBlock =
   DriverArgs.getLastArgValue(options::OPT_gpu_max_threads_per_block_EQ);
Index: clang/lib/Driver/ToolChains/Clang.cpp
===
--- clang/lib/Driver/ToolChains/Clang.cpp
+++ clang/lib/Driver/ToolChains/Clang.cpp
@@ -6563,6 +6563,11 @@
   CmdArgs.push_back("-fhip-new-launch-api");
 Args.addOptInFlag(CmdArgs, options::OPT_fgpu_allow_device_init,
   options::OPT_fno_gpu_allow_device_init);
+if (Args.hasFlag(options::OPT_fgpu_allow_device_init,
+ options::OPT_fno_gpu_allow_device_init, false))
+  CmdArgs.push_back("-fgpu-allow-device-init");
+Args.AddLastArg(CmdArgs, options::OPT_hipstdpar);
+Args.AddLastArg(CmdArgs, options::OPT_hipstdpar_interpose_alloc);
 Args.addOptInFlag(CmdArgs, 

[PATCH] D155769: [HIP][Clang][docs][RFC] Add documentation for C++ Parallel Algorithm Offload

2023-09-25 Thread Alex Voicu via Phabricator via cfe-commits
AlexVlx added inline comments.



Comment at: clang/docs/HIPSupport.rst:266
+
+- ``-hipstdpar`` / ``--hipstdpar`` enables algorithm offload, which depending 
on
+  phase, has the following effects:

MaskRay wrote:
> Newer long options that don't use the common prefix like `-f` are preferred 
> to only support `--foo`, not `-foo`.
> Many `--hip*` options don't support `-hip*`. Why add `-hipstdpar`?
Thanks for the review - to answer the question, it was only done for (apparent) 
symmetry, there's no strong incentive to have the single dash flavour; I will 
update both this and the driver patch to retain only the double dash flavours.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D155769/new/

https://reviews.llvm.org/D155769

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


[clang] [ClangRepl] Type Directed Code Completion (PR #67349)

2023-09-25 Thread Fred Fu via cfe-commits

https://github.com/capfredf updated 
https://github.com/llvm/llvm-project/pull/67349

>From 4b371d40d74d6297bdb5ecbe2eae0573e20d0569 Mon Sep 17 00:00:00 2001
From: Fred Fu 
Date: Tue, 29 Aug 2023 11:56:59 -0400
Subject: [PATCH 1/4] [ClangRepl] Type Directed Code Completion

Differential Revision: https://reviews.llvm.org/D159128
---
 .../clang/Interpreter/CodeCompletion.h|  11 +-
 clang/lib/Interpreter/CodeCompletion.cpp  | 147 +++--
 clang/lib/Sema/SemaLookup.cpp |   4 +
 clang/tools/clang-repl/ClangRepl.cpp  |  25 +--
 .../Interpreter/CodeCompletionTest.cpp| 195 +-
 5 files changed, 334 insertions(+), 48 deletions(-)

diff --git a/clang/include/clang/Interpreter/CodeCompletion.h 
b/clang/include/clang/Interpreter/CodeCompletion.h
index 9adcdf0dc3afac6..83f665b7a2db944 100644
--- a/clang/include/clang/Interpreter/CodeCompletion.h
+++ b/clang/include/clang/Interpreter/CodeCompletion.h
@@ -23,8 +23,13 @@ namespace clang {
 class CodeCompletionResult;
 class CompilerInstance;
 
-void codeComplete(CompilerInstance *InterpCI, llvm::StringRef Content,
-  unsigned Line, unsigned Col, const CompilerInstance 
*ParentCI,
-  std::vector );
+struct ReplCodeCompletion {
+  ReplCodeCompletion() = default;
+  std::string Prefix;
+  void codeComplete(CompilerInstance *InterpCI, llvm::StringRef Content,
+unsigned Line, unsigned Col,
+const CompilerInstance *ParentCI,
+std::vector );
+};
 } // namespace clang
 #endif
diff --git a/clang/lib/Interpreter/CodeCompletion.cpp 
b/clang/lib/Interpreter/CodeCompletion.cpp
index c40e11b9d1ece0a..9c812c28f677726 100644
--- a/clang/lib/Interpreter/CodeCompletion.cpp
+++ b/clang/lib/Interpreter/CodeCompletion.cpp
@@ -23,6 +23,9 @@
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Sema/CodeCompleteOptions.h"
 #include "clang/Sema/Sema.h"
+#include "llvm/Support/Debug.h"
+#define DEBUG_TYPE "REPLCC"
+
 
 namespace clang {
 
@@ -37,12 +40,22 @@ clang::CodeCompleteOptions getClangCompleteOpts() {
   return Opts;
 }
 
+class CodeCompletionSubContext {
+public:
+  virtual ~CodeCompletionSubContext(){};
+  virtual void
+  HandleCodeCompleteResults(class Sema , CodeCompletionResult *InResults,
+unsigned NumResults,
+std::vector ) = 0;
+};
+
 class ReplCompletionConsumer : public CodeCompleteConsumer {
 public:
-  ReplCompletionConsumer(std::vector )
+  ReplCompletionConsumer(std::vector , 
ReplCodeCompletion& CC)
   : CodeCompleteConsumer(getClangCompleteOpts()),
 CCAllocator(std::make_shared()),
-CCTUInfo(CCAllocator), Results(Results){};
+CCTUInfo(CCAllocator), Results(Results), CC(CC) {
+ }
 
   void ProcessCodeCompleteResults(class Sema , CodeCompletionContext Context,
   CodeCompletionResult *InResults,
@@ -56,26 +69,90 @@ class ReplCompletionConsumer : public CodeCompleteConsumer {
   std::shared_ptr CCAllocator;
   CodeCompletionTUInfo CCTUInfo;
   std::vector 
+  ReplCodeCompletion& CC;
 };
 
 void ReplCompletionConsumer::ProcessCodeCompleteResults(
 class Sema , CodeCompletionContext Context,
 CodeCompletionResult *InResults, unsigned NumResults) {
-  for (unsigned I = 0; I < NumResults; ++I) {
-auto  = InResults[I];
-switch (Result.Kind) {
-case CodeCompletionResult::RK_Declaration:
-  if (auto *ID = Result.Declaration->getIdentifier()) {
-Results.push_back(ID->getName().str());
+
+  // auto& a = S.Context.Idents.get("f1");
+  // LLVM_DEBUG(llvm::dbgs() << "\n F11 : " << a.getName() << "\n" );
+  auto Prefix = S.getPreprocessor().getCodeCompletionFilter();
+  CC.Prefix = Prefix;
+  switch (Context.getKind()) {
+  case CodeCompletionContext::CCC_DotMemberAccess: {
+// FIXME: check BaseType is dependent, or from a typo
+auto BaseType = Context.getBaseType();
+LLVM_DEBUG(llvm::dbgs() << "BaseType : " <<  BaseType.getAsString() << 
"\n" );
+for (unsigned I = 0; I < NumResults; ++I) {
+  auto  = InResults[I];
+  switch (Result.Kind) {
+  case CodeCompletionResult::RK_Declaration:
+if (auto *ID = Result.Declaration->getIdentifier()) {
+  if (const auto *Fun = 
llvm::dyn_cast(Result.Declaration)) {
+if (Fun->getParent()->getCanonicalDecl() == 
BaseType->getAsCXXRecordDecl()->getCanonicalDecl()) {
+  LLVM_DEBUG(llvm::dbgs() << "[In HandleCodeCompleteDOT] Name : " 
<< ID->getName() << "\n");
+  Results.push_back(ID->getName().str());
+}
+  }
+}
+break;
+  default:
+break;
   }
-  break;
-case CodeCompletionResult::RK_Keyword:
-  Results.push_back(Result.Keyword);
-  break;
-default:
-  break;
 }
+break;
   }
+  default:
+auto PreferredType = Context.getPreferredType();
+for (unsigned I = 0; I < 

[clang] [Clang][HIP] Remove 'clangPostLink' from SDL handling (PR #67366)

2023-09-25 Thread Joseph Huber via cfe-commits

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

>From 19b73b3461f2dde1d7df6ef247f46b221cc652d4 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Mon, 25 Sep 2023 15:41:54 -0500
Subject: [PATCH] [Clang][HIP] Remove 'clangPostLink' from SDL handling

Summary:
This feature is not needed anymore and is replaced by different
implementations. The code guarded by this flag also causes us to emit an
invalid argument to `-mlink-builtin-bitcode` that will cause errors if
ever actually executed. Remove this feature.
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp | 30 +-
 clang/lib/Driver/ToolChains/CommonArgs.h   | 10 +++-
 clang/lib/Driver/ToolChains/HIPAMD.cpp |  8 ++
 3 files changed, 18 insertions(+), 30 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 6041ef4aeb673ef..9777672ac1f4491 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2023,8 +2023,7 @@ void tools::addX86AlignBranchArgs(const Driver , const 
ArgList ,
 bool tools::SDLSearch(const Driver , const llvm::opt::ArgList ,
   llvm::opt::ArgStringList ,
   SmallVector LibraryPaths, std::string 
Lib,
-  StringRef Arch, StringRef Target, bool isBitCodeSDL,
-  bool postClangLink) {
+  StringRef Arch, StringRef Target, bool isBitCodeSDL) {
   SmallVector SDLs;
 
   std::string LibDeviceLoc = "/libdevice";
@@ -2083,8 +2082,6 @@ bool tools::SDLSearch(const Driver , const 
llvm::opt::ArgList ,
 for (auto SDL : SDLs) {
   auto FullName = Twine(LPath + SDL).str();
   if (llvm::sys::fs::exists(FullName)) {
-if (postClangLink)
-  CC1Args.push_back("-mlink-builtin-bitcode");
 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
 FoundSDL = true;
 break;
@@ -2104,8 +2101,7 @@ bool tools::GetSDLFromOffloadArchive(
 Compilation , const Driver , const Tool , const JobAction ,
 const InputInfoList , const llvm::opt::ArgList ,
 llvm::opt::ArgStringList , SmallVector 
LibraryPaths,
-StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
-bool postClangLink) {
+StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL) {
 
   // We don't support bitcode archive bundles for nvptx
   if (isBitCodeSDL && Arch.contains("nvptx"))
@@ -2203,8 +2199,6 @@ bool tools::GetSDLFromOffloadArchive(
   C.addCommand(std::make_unique(
   JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
   InputInfo(, C.getArgs().MakeArgString(OutputLib;
-  if (postClangLink)
-CC1Args.push_back("-mlink-builtin-bitcode");
 
   CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
 
@@ -2213,14 +2207,14 @@ bool tools::GetSDLFromOffloadArchive(
 
 // Wrapper function used by driver for adding SDLs during link phase.
 void tools::AddStaticDeviceLibsLinking(Compilation , const Tool ,
-const JobAction ,
-const InputInfoList ,
-const llvm::opt::ArgList ,
-llvm::opt::ArgStringList ,
-StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+   const JobAction ,
+   const InputInfoList ,
+   const llvm::opt::ArgList ,
+   llvm::opt::ArgStringList ,
+   StringRef Arch, StringRef Target,
+   bool isBitCodeSDL) {
   AddStaticDeviceLibs(, , , , C.getDriver(), DriverArgs, CC1Args,
-  Arch, Target, isBitCodeSDL, postClangLink);
+  Arch, Target, isBitCodeSDL);
 }
 
 // User defined Static Device Libraries(SDLs) can be passed to clang for
@@ -2252,7 +2246,7 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+bool isBitCodeSDL) {
 
   SmallVector LibraryPaths;
   // Add search directories from LIBRARY_PATH env variable
@@ -2308,10 +2302,10 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
   for (auto SDLName : SDLNames) {
 // This is the only call to SDLSearch
 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
-   isBitCodeSDL, postClangLink)) {
+   isBitCodeSDL)) {
   GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
 

[clang] [llvm-profdata] Do not create numerical strings for MD5 function names read from a Sample Profile. (PR #66164)

2023-09-25 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 618a22144db5e45da8c95dc22064103e1b5e5b71 
5cc1ae6b84361282c707a7789a512d0fd2a3b358 -- 
llvm/include/llvm/ProfileData/ProfileFuncRef.h 
llvm/include/llvm/ProfileData/SampleProf.h 
llvm/include/llvm/ProfileData/SampleProfReader.h 
llvm/include/llvm/ProfileData/SampleProfWriter.h 
llvm/include/llvm/Transforms/IPO/ProfiledCallGraph.h 
llvm/include/llvm/Transforms/IPO/SampleContextTracker.h 
llvm/lib/ProfileData/SampleProf.cpp llvm/lib/ProfileData/SampleProfReader.cpp 
llvm/lib/ProfileData/SampleProfWriter.cpp 
llvm/lib/Target/X86/X86InsertPrefetch.cpp 
llvm/lib/Transforms/IPO/SampleContextTracker.cpp 
llvm/lib/Transforms/IPO/SampleProfile.cpp 
llvm/tools/llvm-profdata/llvm-profdata.cpp 
llvm/tools/llvm-profgen/CSPreInliner.cpp llvm/tools/llvm-profgen/CSPreInliner.h 
llvm/tools/llvm-profgen/ProfileGenerator.cpp 
llvm/tools/llvm-profgen/ProfiledBinary.cpp 
llvm/tools/llvm-profgen/ProfiledBinary.h 
llvm/unittests/ProfileData/SampleProfTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/include/llvm/ProfileData/SampleProf.h 
b/llvm/include/llvm/ProfileData/SampleProf.h
index 1604b737e336..7dbe39084a07 100644
--- a/llvm/include/llvm/ProfileData/SampleProf.h
+++ b/llvm/include/llvm/ProfileData/SampleProf.h
@@ -305,7 +305,7 @@ struct LineLocation {
   }
 
   uint64_t getHashCode() const {
-return ((uint64_t) Discriminator << 32) | LineOffset;
+return ((uint64_t)Discriminator << 32) | LineOffset;
   }
 
   uint32_t LineOffset;
@@ -538,14 +538,14 @@ public:
 assert(!Name.empty() && "Name is empty");
   }
 
-  SampleContext(ProfileFuncRef Name)
-  : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
+  SampleContext(ProfileFuncRef Name)
+  : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
 
-  SampleContext(SampleContextFrames Context,
-ContextStateMask CState = RawContext)
-  : Attributes(ContextNone) {
-assert(!Context.empty() && "Context is empty");
-setContext(Context, CState);
+  SampleContext(SampleContextFrames Context,
+ContextStateMask CState = RawContext)
+  : Attributes(ContextNone) {
+assert(!Context.empty() && "Context is empty");
+setContext(Context, CState);
   }
 
   // Give a context string, decode and populate internal states like
@@ -591,8 +591,7 @@ public:
 
   // Decode context string for a frame to get function name and location.
   // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
-  static void decodeContextString(StringRef ContextStr,
-  ProfileFuncRef ,
+  static void decodeContextString(StringRef ContextStr, ProfileFuncRef ,
   LineLocation ) {
 // Get function name
 auto EntrySplit = ContextStr.split(':');
@@ -792,8 +791,7 @@ public:
 
   sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
   uint32_t Discriminator,
-  ProfileFuncRef FName,
-  uint64_t Num,
+  ProfileFuncRef FName, uint64_t Num,
   uint64_t Weight = 1) {
 return BodySamples[LineLocation(LineOffset, 
Discriminator)].addCalledTarget(
 FName, Num, Weight);
@@ -1069,9 +1067,7 @@ public:
   }
 
   /// Set the name of the function.
-  void setName(ProfileFuncRef FunctionName) {
-Context.setName(FunctionName);
-  }
+  void setName(ProfileFuncRef FunctionName) { Context.setName(FunctionName); }
 
   /// Return the function name.
   ProfileFuncRef getName() const { return Context.getName(); }
@@ -1207,9 +1203,7 @@ public:
 
   /// Return the GUID of the context's name. If the context is already using
   /// MD5, don't hash it again.
-  uint64_t getGUID() const {
-return getName().getHashCode();
-  }
+  uint64_t getGUID() const { return getName().getHashCode(); }
 
   // Find all the names in the current FunctionSamples including names in
   // all the inline instances and names of call targets.
diff --git a/llvm/include/llvm/ProfileData/SampleProfReader.h 
b/llvm/include/llvm/ProfileData/SampleProfReader.h
index 0f1ad8c4660e..ac006664accb 100644
--- a/llvm/include/llvm/ProfileData/SampleProfReader.h
+++ b/llvm/include/llvm/ProfileData/SampleProfReader.h
@@ -591,9 +591,7 @@ public:
 
   /// It includes all the names that have samples either in outline instance
   /// or inline instance.
-  std::vector *getNameTable() override {
-return 
-  }
+  std::vector *getNameTable() override { return  }
 
 protected:
   /// Read a numeric value of type T from the profile.
diff --git a/llvm/include/llvm/ProfileData/SampleProfWriter.h 

[clang-tools-extra] [llvm-profdata] Do not create numerical strings for MD5 function names read from a Sample Profile. (PR #66164)

2023-09-25 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 618a22144db5e45da8c95dc22064103e1b5e5b71 
5cc1ae6b84361282c707a7789a512d0fd2a3b358 -- 
llvm/include/llvm/ProfileData/ProfileFuncRef.h 
llvm/include/llvm/ProfileData/SampleProf.h 
llvm/include/llvm/ProfileData/SampleProfReader.h 
llvm/include/llvm/ProfileData/SampleProfWriter.h 
llvm/include/llvm/Transforms/IPO/ProfiledCallGraph.h 
llvm/include/llvm/Transforms/IPO/SampleContextTracker.h 
llvm/lib/ProfileData/SampleProf.cpp llvm/lib/ProfileData/SampleProfReader.cpp 
llvm/lib/ProfileData/SampleProfWriter.cpp 
llvm/lib/Target/X86/X86InsertPrefetch.cpp 
llvm/lib/Transforms/IPO/SampleContextTracker.cpp 
llvm/lib/Transforms/IPO/SampleProfile.cpp 
llvm/tools/llvm-profdata/llvm-profdata.cpp 
llvm/tools/llvm-profgen/CSPreInliner.cpp llvm/tools/llvm-profgen/CSPreInliner.h 
llvm/tools/llvm-profgen/ProfileGenerator.cpp 
llvm/tools/llvm-profgen/ProfiledBinary.cpp 
llvm/tools/llvm-profgen/ProfiledBinary.h 
llvm/unittests/ProfileData/SampleProfTest.cpp
``





View the diff from clang-format here.


``diff
diff --git a/llvm/include/llvm/ProfileData/SampleProf.h 
b/llvm/include/llvm/ProfileData/SampleProf.h
index 1604b737e336..7dbe39084a07 100644
--- a/llvm/include/llvm/ProfileData/SampleProf.h
+++ b/llvm/include/llvm/ProfileData/SampleProf.h
@@ -305,7 +305,7 @@ struct LineLocation {
   }
 
   uint64_t getHashCode() const {
-return ((uint64_t) Discriminator << 32) | LineOffset;
+return ((uint64_t)Discriminator << 32) | LineOffset;
   }
 
   uint32_t LineOffset;
@@ -538,14 +538,14 @@ public:
 assert(!Name.empty() && "Name is empty");
   }
 
-  SampleContext(ProfileFuncRef Name)
-  : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
+  SampleContext(ProfileFuncRef Name)
+  : Name(Name), State(UnknownContext), Attributes(ContextNone) {}
 
-  SampleContext(SampleContextFrames Context,
-ContextStateMask CState = RawContext)
-  : Attributes(ContextNone) {
-assert(!Context.empty() && "Context is empty");
-setContext(Context, CState);
+  SampleContext(SampleContextFrames Context,
+ContextStateMask CState = RawContext)
+  : Attributes(ContextNone) {
+assert(!Context.empty() && "Context is empty");
+setContext(Context, CState);
   }
 
   // Give a context string, decode and populate internal states like
@@ -591,8 +591,7 @@ public:
 
   // Decode context string for a frame to get function name and location.
   // `ContextStr` is in the form of `FuncName:StartLine.Discriminator`.
-  static void decodeContextString(StringRef ContextStr,
-  ProfileFuncRef ,
+  static void decodeContextString(StringRef ContextStr, ProfileFuncRef ,
   LineLocation ) {
 // Get function name
 auto EntrySplit = ContextStr.split(':');
@@ -792,8 +791,7 @@ public:
 
   sampleprof_error addCalledTargetSamples(uint32_t LineOffset,
   uint32_t Discriminator,
-  ProfileFuncRef FName,
-  uint64_t Num,
+  ProfileFuncRef FName, uint64_t Num,
   uint64_t Weight = 1) {
 return BodySamples[LineLocation(LineOffset, 
Discriminator)].addCalledTarget(
 FName, Num, Weight);
@@ -1069,9 +1067,7 @@ public:
   }
 
   /// Set the name of the function.
-  void setName(ProfileFuncRef FunctionName) {
-Context.setName(FunctionName);
-  }
+  void setName(ProfileFuncRef FunctionName) { Context.setName(FunctionName); }
 
   /// Return the function name.
   ProfileFuncRef getName() const { return Context.getName(); }
@@ -1207,9 +1203,7 @@ public:
 
   /// Return the GUID of the context's name. If the context is already using
   /// MD5, don't hash it again.
-  uint64_t getGUID() const {
-return getName().getHashCode();
-  }
+  uint64_t getGUID() const { return getName().getHashCode(); }
 
   // Find all the names in the current FunctionSamples including names in
   // all the inline instances and names of call targets.
diff --git a/llvm/include/llvm/ProfileData/SampleProfReader.h 
b/llvm/include/llvm/ProfileData/SampleProfReader.h
index 0f1ad8c4660e..ac006664accb 100644
--- a/llvm/include/llvm/ProfileData/SampleProfReader.h
+++ b/llvm/include/llvm/ProfileData/SampleProfReader.h
@@ -591,9 +591,7 @@ public:
 
   /// It includes all the names that have samples either in outline instance
   /// or inline instance.
-  std::vector *getNameTable() override {
-return 
-  }
+  std::vector *getNameTable() override { return  }
 
 protected:
   /// Read a numeric value of type T from the profile.
diff --git a/llvm/include/llvm/ProfileData/SampleProfWriter.h 

[clang] [Clang][HIP] Remove 'clangPostLink' from SDL handling (PR #67366)

2023-09-25 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 62f5636838ac80ebe8db9c31cdf9c5566db8f0c9 
8076d6182a44daf6fee0165922aa30d0fb1786d5 -- 
clang/lib/Driver/ToolChains/CommonArgs.cpp 
clang/lib/Driver/ToolChains/CommonArgs.h clang/lib/Driver/ToolChains/HIPAMD.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 6a0d35d0bef4..9777672ac1f4 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2207,12 +2207,12 @@ bool tools::GetSDLFromOffloadArchive(
 
 // Wrapper function used by driver for adding SDLs during link phase.
 void tools::AddStaticDeviceLibsLinking(Compilation , const Tool ,
-const JobAction ,
-const InputInfoList ,
-const llvm::opt::ArgList ,
-llvm::opt::ArgStringList ,
-StringRef Arch, StringRef Target,
-bool isBitCodeSDL) {
+   const JobAction ,
+   const InputInfoList ,
+   const llvm::opt::ArgList ,
+   llvm::opt::ArgStringList ,
+   StringRef Arch, StringRef Target,
+   bool isBitCodeSDL) {
   AddStaticDeviceLibs(, , , , C.getDriver(), DriverArgs, CC1Args,
   Arch, Target, isBitCodeSDL);
 }

``




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


[clang] [Clang][HIP] Remove 'clangPostLink' from SDL handling (PR #67366)

2023-09-25 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

Long term I'd like to move HIP to the new driver so we can delete all of this 
SDL handling code. That would require someone guiding me through how to test 
the toolchain on Windows so I can make the linker wrapper work with the Windows 
linker.

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


[libunwind] [libunwind] Pass -Wl,--export-dynamic on all supported platforms (PR #67205)

2023-09-25 Thread Joerg Sonnenberger via cfe-commits

jsonn wrote:

Can you as a small follow-up just update the comment to include that part? E.g.
```
# On ELF platforms, link tests with -Wl,--export-dynamic if supported by the 
linker.
```

Side note: the much older way for doing this is actually `-rdynamic`.

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


[clang] [Clang][HIP] Remove 'clangPostLink' from SDL handling (PR #67366)

2023-09-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-driver


Changes

Summary:
This feature is not needed anymore and is replaced by different
implementations. The code guarded by this flag also causes us to emit an
invalid argument to `-mlink-builtin-bitcode` that will cause errors if
ever actually executed. Remove this feature.


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


3 Files Affected:

- (modified) clang/lib/Driver/ToolChains/CommonArgs.cpp (+7-13) 
- (modified) clang/lib/Driver/ToolChains/CommonArgs.h (+4-6) 
- (modified) clang/lib/Driver/ToolChains/HIPAMD.cpp (+2-6) 


``diff
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 6041ef4aeb673ef..6a0d35d0bef4bfb 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2023,8 +2023,7 @@ void tools::addX86AlignBranchArgs(const Driver , const 
ArgList ,
 bool tools::SDLSearch(const Driver , const llvm::opt::ArgList ,
   llvm::opt::ArgStringList ,
   SmallVector LibraryPaths, std::string 
Lib,
-  StringRef Arch, StringRef Target, bool isBitCodeSDL,
-  bool postClangLink) {
+  StringRef Arch, StringRef Target, bool isBitCodeSDL) {
   SmallVector SDLs;
 
   std::string LibDeviceLoc = "/libdevice";
@@ -2083,8 +2082,6 @@ bool tools::SDLSearch(const Driver , const 
llvm::opt::ArgList ,
 for (auto SDL : SDLs) {
   auto FullName = Twine(LPath + SDL).str();
   if (llvm::sys::fs::exists(FullName)) {
-if (postClangLink)
-  CC1Args.push_back("-mlink-builtin-bitcode");
 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
 FoundSDL = true;
 break;
@@ -2104,8 +2101,7 @@ bool tools::GetSDLFromOffloadArchive(
 Compilation , const Driver , const Tool , const JobAction ,
 const InputInfoList , const llvm::opt::ArgList ,
 llvm::opt::ArgStringList , SmallVector 
LibraryPaths,
-StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
-bool postClangLink) {
+StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL) {
 
   // We don't support bitcode archive bundles for nvptx
   if (isBitCodeSDL && Arch.contains("nvptx"))
@@ -2203,8 +2199,6 @@ bool tools::GetSDLFromOffloadArchive(
   C.addCommand(std::make_unique(
   JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
   InputInfo(, C.getArgs().MakeArgString(OutputLib;
-  if (postClangLink)
-CC1Args.push_back("-mlink-builtin-bitcode");
 
   CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
 
@@ -2218,9 +2212,9 @@ void tools::AddStaticDeviceLibsLinking(Compilation , 
const Tool ,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+bool isBitCodeSDL) {
   AddStaticDeviceLibs(, , , , C.getDriver(), DriverArgs, CC1Args,
-  Arch, Target, isBitCodeSDL, postClangLink);
+  Arch, Target, isBitCodeSDL);
 }
 
 // User defined Static Device Libraries(SDLs) can be passed to clang for
@@ -2252,7 +2246,7 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+bool isBitCodeSDL) {
 
   SmallVector LibraryPaths;
   // Add search directories from LIBRARY_PATH env variable
@@ -2308,10 +2302,10 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
   for (auto SDLName : SDLNames) {
 // This is the only call to SDLSearch
 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
-   isBitCodeSDL, postClangLink)) {
+   isBitCodeSDL)) {
   GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
LibraryPaths, SDLName, Arch, Target,
-   isBitCodeSDL, postClangLink);
+   isBitCodeSDL);
 }
   }
 }
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.h 
b/clang/lib/Driver/ToolChains/CommonArgs.h
index 7585d24c3c0eb63..096152bfbdcf68a 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.h
+++ b/clang/lib/Driver/ToolChains/CommonArgs.h
@@ -59,19 +59,17 @@ void AddStaticDeviceLibsLinking(Compilation , const Tool 
,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-

[clang] [Clang][HIP] Remove 'clangPostLink' from SDL handling (PR #67366)

2023-09-25 Thread Joseph Huber via cfe-commits

https://github.com/jhuber6 created 
https://github.com/llvm/llvm-project/pull/67366

Summary:
This feature is not needed anymore and is replaced by different
implementations. The code guarded by this flag also causes us to emit an
invalid argument to `-mlink-builtin-bitcode` that will cause errors if
ever actually executed. Remove this feature.


>From 8076d6182a44daf6fee0165922aa30d0fb1786d5 Mon Sep 17 00:00:00 2001
From: Joseph Huber 
Date: Mon, 25 Sep 2023 15:41:54 -0500
Subject: [PATCH] [Clang][HIP] Remove 'clangPostLink' from SDL handling

Summary:
This feature is not needed anymore and is replaced by different
implementations. The code guarded by this flag also causes us to emit an
invalid argument to `-mlink-builtin-bitcode` that will cause errors if
ever actually executed. Remove this feature.
---
 clang/lib/Driver/ToolChains/CommonArgs.cpp | 20 +++-
 clang/lib/Driver/ToolChains/CommonArgs.h   | 10 --
 clang/lib/Driver/ToolChains/HIPAMD.cpp |  8 ++--
 3 files changed, 13 insertions(+), 25 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 6041ef4aeb673ef..6a0d35d0bef4bfb 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2023,8 +2023,7 @@ void tools::addX86AlignBranchArgs(const Driver , const 
ArgList ,
 bool tools::SDLSearch(const Driver , const llvm::opt::ArgList ,
   llvm::opt::ArgStringList ,
   SmallVector LibraryPaths, std::string 
Lib,
-  StringRef Arch, StringRef Target, bool isBitCodeSDL,
-  bool postClangLink) {
+  StringRef Arch, StringRef Target, bool isBitCodeSDL) {
   SmallVector SDLs;
 
   std::string LibDeviceLoc = "/libdevice";
@@ -2083,8 +2082,6 @@ bool tools::SDLSearch(const Driver , const 
llvm::opt::ArgList ,
 for (auto SDL : SDLs) {
   auto FullName = Twine(LPath + SDL).str();
   if (llvm::sys::fs::exists(FullName)) {
-if (postClangLink)
-  CC1Args.push_back("-mlink-builtin-bitcode");
 CC1Args.push_back(DriverArgs.MakeArgString(FullName));
 FoundSDL = true;
 break;
@@ -2104,8 +2101,7 @@ bool tools::GetSDLFromOffloadArchive(
 Compilation , const Driver , const Tool , const JobAction ,
 const InputInfoList , const llvm::opt::ArgList ,
 llvm::opt::ArgStringList , SmallVector 
LibraryPaths,
-StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL,
-bool postClangLink) {
+StringRef Lib, StringRef Arch, StringRef Target, bool isBitCodeSDL) {
 
   // We don't support bitcode archive bundles for nvptx
   if (isBitCodeSDL && Arch.contains("nvptx"))
@@ -2203,8 +2199,6 @@ bool tools::GetSDLFromOffloadArchive(
   C.addCommand(std::make_unique(
   JA, T, ResponseFileSupport::AtFileCurCP(), UBProgram, UBArgs, Inputs,
   InputInfo(, C.getArgs().MakeArgString(OutputLib;
-  if (postClangLink)
-CC1Args.push_back("-mlink-builtin-bitcode");
 
   CC1Args.push_back(DriverArgs.MakeArgString(OutputLib));
 
@@ -2218,9 +2212,9 @@ void tools::AddStaticDeviceLibsLinking(Compilation , 
const Tool ,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+bool isBitCodeSDL) {
   AddStaticDeviceLibs(, , , , C.getDriver(), DriverArgs, CC1Args,
-  Arch, Target, isBitCodeSDL, postClangLink);
+  Arch, Target, isBitCodeSDL);
 }
 
 // User defined Static Device Libraries(SDLs) can be passed to clang for
@@ -2252,7 +2246,7 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
 const llvm::opt::ArgList ,
 llvm::opt::ArgStringList ,
 StringRef Arch, StringRef Target,
-bool isBitCodeSDL, bool postClangLink) {
+bool isBitCodeSDL) {
 
   SmallVector LibraryPaths;
   // Add search directories from LIBRARY_PATH env variable
@@ -2308,10 +2302,10 @@ void tools::AddStaticDeviceLibs(Compilation *C, const 
Tool *T,
   for (auto SDLName : SDLNames) {
 // This is the only call to SDLSearch
 if (!SDLSearch(D, DriverArgs, CC1Args, LibraryPaths, SDLName, Arch, Target,
-   isBitCodeSDL, postClangLink)) {
+   isBitCodeSDL)) {
   GetSDLFromOffloadArchive(*C, D, *T, *JA, *Inputs, DriverArgs, CC1Args,
LibraryPaths, SDLName, Arch, Target,
-   isBitCodeSDL, postClangLink);
+   isBitCodeSDL);
 }
   }
 }
diff --git a/clang/lib/Driver/ToolChains/CommonArgs.h 
b/clang/lib/Driver/ToolChains/CommonArgs.h
index 

[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

2023-09-25 Thread Jan Svoboda via cfe-commits


@@ -50,6 +50,7 @@ int y = a2;
 // CHECK: In module 'a':
 // CHECK-NEXT: a.h:1:45: error:
 
+int z = b;
 // MISSING-B: could not find file '{{.*}}b.h'
 // MISSING-B-NOT: please delete the module cache

jansvoboda11 wrote:

This test relied on the fact that when diagnosing line 49, the `SLocEntry` for 
"b.h" got deserialized as a side-effect of the binary search for "a.h", thus 
generating the `MISSING-B` error message. Since we no longer fully deserialize 
the "b.h" `SLocEntry` during the binary search for "a.h", let's force its full 
deserialization by triggering new diagnostics pointing directly into "b.h".

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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-09-25 Thread via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


cor3ntin wrote:

> > I have concerns about Lexing twice every single file for which we display a 
> > warning.
> 
> Sure. Because of performance, memory usage or code complexity?
> 

Performance, mostly

> So, my general procedure for diagnostics is that they shouldn't complicate 
> the non-diagnostic code. And when we emit a diagnostic, performance is 
> basically out the window anyway (printing to stdout is _slow_ and the way we 
> emit code snippets is also slow, etc.)

That is generally true, but how far do want to push that logic? Lexing is going 
to be fairly expensive on most source files. I'd expect it to be much more 
(cpu) expensive than a call to print.

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


[clang] [clang][modules] Move `SLocEntry` search into `ASTReader` (PR #66966)

2023-09-25 Thread Jan Svoboda via cfe-commits

https://github.com/jansvoboda11 updated 
https://github.com/llvm/llvm-project/pull/66966

>From 4edf9d8559339a12108d9c4d1e2f3bb062a5a768 Mon Sep 17 00:00:00 2001
From: Jan Svoboda 
Date: Wed, 20 Sep 2023 17:30:45 -0700
Subject: [PATCH 1/6] [clang][modules] Move `SLocEntry` search into `ASTReader`

In `getFileID()` the `SourceManager` ends up doing a binary search over its 
buffer of `SLocEntries`. For modules, this binary search fully deserializes the 
entire `SLocEntry` block for visited each entry. This shows up in profiles of 
the dependency scanner, since that operation includes decompressing buffers 
associated with some entries.

This patch moves the binary search over loaded entries into `ASTReader`, which 
now only performs partial deserialization during the binary search, speeding up 
the scanner by ~3.3%.
---
 clang/include/clang/Basic/SourceManager.h |  3 +
 clang/include/clang/Serialization/ASTReader.h |  6 ++
 clang/lib/Basic/SourceManager.cpp | 70 +--
 clang/lib/Serialization/ASTReader.cpp | 63 +
 4 files changed, 75 insertions(+), 67 deletions(-)

diff --git a/clang/include/clang/Basic/SourceManager.h 
b/clang/include/clang/Basic/SourceManager.h
index 2f846502d6f3327..a4c7facddd53d64 100644
--- a/clang/include/clang/Basic/SourceManager.h
+++ b/clang/include/clang/Basic/SourceManager.h
@@ -533,6 +533,9 @@ class ExternalSLocEntrySource {
   /// entry from being loaded.
   virtual bool ReadSLocEntry(int ID) = 0;
 
+  /// Get the index ID for the loaded SourceLocation offset.
+  virtual int getSLocEntryID(SourceLocation::UIntTy SLocOffset) = 0;
+
   /// Retrieve the module import location and name for the given ID, if
   /// in fact it was loaded from a module (rather than, say, a precompiled
   /// header).
diff --git a/clang/include/clang/Serialization/ASTReader.h 
b/clang/include/clang/Serialization/ASTReader.h
index dc1eb21c27801fe..e643fcf4c930f09 100644
--- a/clang/include/clang/Serialization/ASTReader.h
+++ b/clang/include/clang/Serialization/ASTReader.h
@@ -2153,6 +2153,12 @@ class ASTReader
 
   /// Read the source location entry with index ID.
   bool ReadSLocEntry(int ID) override;
+  /// Get the index ID for the loaded SourceLocation offset.
+  int getSLocEntryID(SourceLocation::UIntTy SLocOffset) override;
+  /// Read the offset of the SLocEntry at the given index in the given module
+  /// file.
+  std::optional readSLocOffset(ModuleFile *F,
+   unsigned Index);
 
   /// Retrieve the module import location and module name for the
   /// given source manager entry ID.
diff --git a/clang/lib/Basic/SourceManager.cpp 
b/clang/lib/Basic/SourceManager.cpp
index 0521ac7b30339ab..f881afc2e46c5c6 100644
--- a/clang/lib/Basic/SourceManager.cpp
+++ b/clang/lib/Basic/SourceManager.cpp
@@ -864,74 +864,10 @@ FileID 
SourceManager::getFileIDLocal(SourceLocation::UIntTy SLocOffset) const {
 /// This function knows that the SourceLocation is in a loaded buffer, not a
 /// local one.
 FileID SourceManager::getFileIDLoaded(SourceLocation::UIntTy SLocOffset) const 
{
-  if (SLocOffset < CurrentLoadedOffset) {
-assert(0 && "Invalid SLocOffset or bad function choice");
-return FileID();
-  }
-
-  // Essentially the same as the local case, but the loaded array is sorted
-  // in the other direction (decreasing order).
-  // GreaterIndex is the one where the offset is greater, which is actually a
-  // lower index!
-  unsigned GreaterIndex = 0;
-  unsigned LessIndex = LoadedSLocEntryTable.size();
-  if (LastFileIDLookup.ID < 0) {
-// Prune the search space.
-int LastID = LastFileIDLookup.ID;
-if (getLoadedSLocEntryByID(LastID).getOffset() > SLocOffset)
-  GreaterIndex =
-  (-LastID - 2) + 1; // Exclude LastID, else we would have hit the 
cache
-else
-  LessIndex = -LastID - 2;
-  }
-
-  // First do a linear scan from the last lookup position, if possible.
-  unsigned NumProbes;
+  int ID = ExternalSLocEntries->getSLocEntryID(SLocOffset);
   bool Invalid = false;
-  for (NumProbes = 0; NumProbes < 8; ++NumProbes, ++GreaterIndex) {
-// Make sure the entry is loaded!
-const SrcMgr::SLocEntry  = getLoadedSLocEntry(GreaterIndex, );
-if (Invalid)
-  return FileID(); // invalid entry.
-if (E.getOffset() <= SLocOffset) {
-  FileID Res = FileID::get(-int(GreaterIndex) - 2);
-  LastFileIDLookup = Res;
-  NumLinearScans += NumProbes + 1;
-  return Res;
-}
-  }
-
-  // Linear scan failed. Do the binary search.
-  NumProbes = 0;
-  while (true) {
-++NumProbes;
-unsigned MiddleIndex = (LessIndex - GreaterIndex) / 2 + GreaterIndex;
-const SrcMgr::SLocEntry  = getLoadedSLocEntry(MiddleIndex, );
-if (Invalid)
-  return FileID(); // invalid entry.
-
-if (E.getOffset() > SLocOffset) {
-  if (GreaterIndex == MiddleIndex) {
-assert(0 && "binary search missed the entry");
-return FileID();
-  

[clang] [clang][NFC] Preprocessor only needs const LangOptions (PR #66874)

2023-09-25 Thread via cfe-commits

cor3ntin wrote:

@AaronBallman LGTM, WDYT?

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


[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Shafik Yaghmour via cfe-commits

https://github.com/shafik commented:

Should they be valid for `constexpr` functions?

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


[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

2023-09-25 Thread Shafik Yaghmour via cfe-commits


@@ -2352,26 +2352,61 @@ static void handleUnusedAttr(Sema , Decl *D, const 
ParsedAttr ) {
   D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
 }
 
-static void handleConstructorAttr(Sema , Decl *D, const ParsedAttr ) {
-  uint32_t priority = ConstructorAttr::DefaultPriority;
+static bool diagnoseInvalidPriority(Sema , uint32_t Priority,
+const ParsedAttr ,
+SourceLocation PriorityLoc) {
+  // Only perform the priority check if the attribute is outside of a system
+  // header. Values <= 100 are reserved for the implementation, and libc++
+  // benefits from being able to specify values in that range.
+  if ((Priority < 101 || Priority > 65535) &&

shafik wrote:

So `101` and `65535` are "magic" numbers that are used multiple times, can we 
name them please.

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


  1   2   3   4   >