[clang] [clang-format] Fix operator overload inconsistency in `BreakAfterAttributes: Always` (PR #74943)

2023-12-21 Thread Owen Pan via cfe-commits


@@ -583,20 +583,26 @@ bool ContinuationIndenter::mustBreak(const LineState 
) {
   return true;
   }
 
-  // If the return type spans multiple lines, wrap before the function name.
-  if (((Current.is(TT_FunctionDeclarationName) &&
-!State.Line->ReturnTypeWrapped &&
-// Don't break before a C# function when no break after return type.
-(!Style.isCSharp() ||
- Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
-// Don't always break between a JavaScript `function` and the function
-// name.
-!Style.isJavaScript()) ||
-   (Current.is(tok::kw_operator) && Previous.isNot(tok::coloncolon))) &&

owenca wrote:

Simply removing line 595 above seems to work:
```
  if (Current.is(TT_FunctionDeclarationName) &&
  !State.Line->ReturnTypeWrapped &&
  // Don't break before a C# function when no break after return type.
  (!Style.isCSharp() ||
   Style.AlwaysBreakAfterReturnType != FormatStyle::RTBS_None) &&
  // Don't always break between a JavaScript `function` and the function
  // name.
  !Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
  CurrentState.BreakBeforeParameter) {
return true;
  }
```

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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/76207

>From 0a46fedc497a124d3aca4295b8c18ae60df186e9 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 22 Dec 2023 14:47:48 +0800
Subject: [PATCH] [clang][analyzer] Improve modeling of `fileno` in the
 StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 30 ---
 clang/test/Analysis/stream-errno.c|  7 +++--
 clang/test/Analysis/stream-noopen.c   | 12 
 3 files changed, 35 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 254b36ed03968d..80ac910060720f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,7 +265,11 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -342,8 +345,8 @@ class StreamChecker : public Checker();
   ProgramStateRef StateNotFailed =
   State->BindExpr(CE, C.getLocationContext(), RetVal);
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
-SVB.makeZeroVal(C.getASTContext().LongTy),
-SVB.getConditionType())
-  .getAs();
+  auto Cond =
+  SVB.evalBinOp(State, BO_GE, RetVal,
+SVB.makeZeroVal(IsRetLongTy ? C.getASTContext().LongTy
+: C.getASTContext().IntTy),
+SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   StateNotFailed = StateNotFailed->assume(*Cond, true);
@@ -1078,7 +1084,9 @@ void StreamChecker::evalFtell(const FnDescription *Desc, 
const CallEvent ,
 return;
 
   ProgramStateRef StateFailed = State->BindExpr(
-  CE, C.getLocationContext(), SVB.makeIntVal(-1, 
C.getASTContext().LongTy));
+  CE, C.getLocationContext(),
+  SVB.makeIntVal(-1, IsRetLongTy ? C.getASTContext().LongTy
+ : C.getASTContext().IntTy));
 
   // This function does not affect the stream state.
   // Still we add success and failure state with the appropriate return value.
diff --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index bf0a61db2424f9..62befbc78e5a75 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -216,9 +216,10 @@ void check_fileno(void) {
   int N = fileno(F);
   if (N == -1) {
 clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
-if (errno) {} // no-warning
-fclose(F);
-return;
+if (errno) {}// no-warning
+  } else {
+clang_analyzer_eval(N >= 0); // expected-warning{{TRUE}}
   }
   if (errno) {} // expected-warning{{An undefined value may be read from 
'errno'}}
+  fclose(F);
 }
diff --git a/clang/test/Analysis/stream-noopen.c 
b/clang/test/Analysis/stream-noopen.c
index 2daf640c18a1d4..198b5dc45e35da 100644
--- a/clang/test/Analysis/stream-noopen.c
+++ b/clang/test/Analysis/stream-noopen.c
@@ -129,6 +129,18 @@ void check_ftell(FILE *F) {
   clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
 }
 
+void check_fileno(FILE *F) {
+  int Ret = fileno(F);
+  clang_analyzer_eval(F != NULL);// expected-warning{{TRUE}}
+  if (!(Ret >= 0)) {
+clang_analyzer_eval(Ret == -1);  // expected-warning{{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  }
+  clang_analyzer_eval(feof(F));  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(ferror(F));// expected-warning{{UNKNOWN}}
+}
+
 void test_rewind(FILE *F) {
   errno = 0;
   rewind(F);

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


[clang] e2d0f50 - [clang][NFC] Remove trailing whitespace characters

2023-12-21 Thread Ben Shi via cfe-commits

Author: Ben Shi
Date: 2023-12-22T15:34:13+08:00
New Revision: e2d0f50cd6f2887c32508faba54a9a9499576a4e

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

LOG: [clang][NFC] Remove trailing whitespace characters

Added: 


Modified: 
clang/lib/Serialization/ASTReaderStmt.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTReaderStmt.cpp 
b/clang/lib/Serialization/ASTReaderStmt.cpp
index cf37ffe4c38b5d..21aed570ba26ce 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2007,7 +2007,7 @@ void ASTStmtReader::VisitCXXDependentScopeMemberExpr(
   E->QualifierLoc = Record.readNestedNameSpecifierLoc();
   // not ImplicitAccess
   if (CurrentUnpackingBits->getNextBit())
-E->Base = Record.readSubExpr();  
+E->Base = Record.readSubExpr();
   else
 E->Base = nullptr;
 



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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread Ben Shi via cfe-commits

benshi001 wrote:

The reported format error is in another file, not related to my patch.

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


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

2023-12-21 Thread Nhat Nguyen via cfe-commits

https://github.com/changkhothuychung updated 
https://github.com/llvm/llvm-project/pull/75902

>From 0eb58740f33f2eef29c28e43e78118f9f0eea4b4 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= <“nhat7...@gmail.com”>
Date: Tue, 19 Dec 2023 00:03:28 -0800
Subject: [PATCH 1/4] return false if the value is too large

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

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6e..18631ec7dac152 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,6 +17132,9 @@ static bool ConvertAPValueToString(const APValue , 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
+  if (V.getInt() >= (1 << 64)) {
+return false;
+  }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());
   WriteCharTypePrefix(BTy->getKind(), OS);
   OS << '\'';

>From 5e6326fb1cf4f1591fe927c94b1d16d1a7be0e66 Mon Sep 17 00:00:00 2001
From: Nhat Nguyen 
Date: Thu, 21 Dec 2023 13:26:13 -0500
Subject: [PATCH 2/4] Update clang/lib/Sema/SemaDeclCXX.cpp

Co-authored-by: Yueh-Shun Li 
---
 clang/lib/Sema/SemaDeclCXX.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 18631ec7dac152..196e32a4a349f2 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,7 @@ static bool ConvertAPValueToString(const APValue , 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() >= (1 << 64)) {
+  if (V.getInt() > std::numeric_limits::max() || V.getInt() 
< std::numeric_limits::min()) {
 return false;
   }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());

>From b2794aba6969d694b55ab3a91ac1616f8469cd46 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= <“nhat7...@gmail.com”>
Date: Thu, 21 Dec 2023 10:34:00 -0800
Subject: [PATCH 3/4] clang format

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

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 196e32a4a349f2..323890b38daeec 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,8 @@ static bool ConvertAPValueToString(const APValue , 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() > std::numeric_limits::max() || V.getInt() 
< std::numeric_limits::min()) {
+  if (V.getInt() > std::numeric_limits::max() || 
+  V.getInt() < std::numeric_limits::min()) {
 return false;
   }
   uint32_t CodeUnit = static_cast(V.getInt().getZExtValue());

>From d5208f02c9b130b85c15b32c945f871d0216885a Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E2=80=9CNhat?= <“nhat7...@gmail.com”>
Date: Thu, 21 Dec 2023 23:14:44 -0800
Subject: [PATCH 4/4] clang format

---
 clang/lib/Sema/SemaDeclCXX.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 323890b38daeec..80e6cd9ee07420 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -17132,7 +17132,7 @@ static bool ConvertAPValueToString(const APValue , 
QualType T,
 case BuiltinType::WChar_U: {
   unsigned TyWidth = Context.getIntWidth(T);
   assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
-  if (V.getInt() > std::numeric_limits::max() || 
+  if (V.getInt() > std::numeric_limits::max() ||
   V.getInt() < std::numeric_limits::min()) {
 return false;
   }

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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread Ben Shi via cfe-commits

benshi001 wrote:

`fileno` and `ftell` are quite similar, 

1. both of them return `0` on success, and `-1` on failure. 
2. both of them set `errno` on failure.

The differences are
1. `fileno` returns `int` type but `ftell` returns `long` type.
2. `ftell` will not affect the value of `error` on success, but this is not 
mentioned for `fileno`.

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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Ben Shi (benshi001)


Changes



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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+19-11) 
- (modified) clang/test/Analysis/stream-errno.c (+4-3) 
- (modified) clang/test/Analysis/stream-noopen.c (+12) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 254b36ed03968d..80ac910060720f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,7 +265,11 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -342,8 +345,8 @@ class StreamChecker : public Checker();
   ProgramStateRef StateNotFailed =
   State->BindExpr(CE, C.getLocationContext(), RetVal);
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
-SVB.makeZeroVal(C.getASTContext().LongTy),
-SVB.getConditionType())
-  .getAs();
+  auto Cond =
+  SVB.evalBinOp(State, BO_GE, RetVal,
+SVB.makeZeroVal(IsRetLongTy ? C.getASTContext().LongTy
+: C.getASTContext().IntTy),
+SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   StateNotFailed = StateNotFailed->assume(*Cond, true);
@@ -1078,7 +1084,9 @@ void StreamChecker::evalFtell(const FnDescription *Desc, 
const CallEvent ,
 return;
 
   ProgramStateRef StateFailed = State->BindExpr(
-  CE, C.getLocationContext(), SVB.makeIntVal(-1, 
C.getASTContext().LongTy));
+  CE, C.getLocationContext(),
+  SVB.makeIntVal(-1, IsRetLongTy ? C.getASTContext().LongTy
+ : C.getASTContext().IntTy));
 
   // This function does not affect the stream state.
   // Still we add success and failure state with the appropriate return value.
diff --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index bf0a61db2424f9..62befbc78e5a75 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -216,9 +216,10 @@ void check_fileno(void) {
   int N = fileno(F);
   if (N == -1) {
 clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
-if (errno) {} // no-warning
-fclose(F);
-return;
+if (errno) {}// no-warning
+  } else {
+clang_analyzer_eval(N >= 0); // expected-warning{{TRUE}}
   }
   if (errno) {} // expected-warning{{An undefined value may be read from 
'errno'}}
+  fclose(F);
 }
diff --git a/clang/test/Analysis/stream-noopen.c 
b/clang/test/Analysis/stream-noopen.c
index 2daf640c18a1d4..198b5dc45e35da 100644
--- a/clang/test/Analysis/stream-noopen.c
+++ b/clang/test/Analysis/stream-noopen.c
@@ -129,6 +129,18 @@ void check_ftell(FILE *F) {
   clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
 }
 
+void check_fileno(FILE *F) {
+  int Ret = fileno(F);
+  clang_analyzer_eval(F != NULL);// expected-warning{{TRUE}}
+  if (!(Ret >= 0)) {
+clang_analyzer_eval(Ret == -1);  // expected-warning{{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  }
+  clang_analyzer_eval(feof(F));  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(ferror(F));// expected-warning{{UNKNOWN}}
+}
+
 void test_rewind(FILE *F) {
   errno = 0;
   rewind(F);

``




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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread via cfe-commits

llvmbot wrote:




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

Author: Ben Shi (benshi001)


Changes



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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+19-11) 
- (modified) clang/test/Analysis/stream-errno.c (+4-3) 
- (modified) clang/test/Analysis/stream-noopen.c (+12) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 254b36ed03968d..80ac910060720f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,7 +265,11 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -342,8 +345,8 @@ class StreamChecker : public Checker();
   ProgramStateRef StateNotFailed =
   State->BindExpr(CE, C.getLocationContext(), RetVal);
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
-SVB.makeZeroVal(C.getASTContext().LongTy),
-SVB.getConditionType())
-  .getAs();
+  auto Cond =
+  SVB.evalBinOp(State, BO_GE, RetVal,
+SVB.makeZeroVal(IsRetLongTy ? C.getASTContext().LongTy
+: C.getASTContext().IntTy),
+SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   StateNotFailed = StateNotFailed->assume(*Cond, true);
@@ -1078,7 +1084,9 @@ void StreamChecker::evalFtell(const FnDescription *Desc, 
const CallEvent ,
 return;
 
   ProgramStateRef StateFailed = State->BindExpr(
-  CE, C.getLocationContext(), SVB.makeIntVal(-1, 
C.getASTContext().LongTy));
+  CE, C.getLocationContext(),
+  SVB.makeIntVal(-1, IsRetLongTy ? C.getASTContext().LongTy
+ : C.getASTContext().IntTy));
 
   // This function does not affect the stream state.
   // Still we add success and failure state with the appropriate return value.
diff --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index bf0a61db2424f9..62befbc78e5a75 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -216,9 +216,10 @@ void check_fileno(void) {
   int N = fileno(F);
   if (N == -1) {
 clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
-if (errno) {} // no-warning
-fclose(F);
-return;
+if (errno) {}// no-warning
+  } else {
+clang_analyzer_eval(N >= 0); // expected-warning{{TRUE}}
   }
   if (errno) {} // expected-warning{{An undefined value may be read from 
'errno'}}
+  fclose(F);
 }
diff --git a/clang/test/Analysis/stream-noopen.c 
b/clang/test/Analysis/stream-noopen.c
index 2daf640c18a1d4..198b5dc45e35da 100644
--- a/clang/test/Analysis/stream-noopen.c
+++ b/clang/test/Analysis/stream-noopen.c
@@ -129,6 +129,18 @@ void check_ftell(FILE *F) {
   clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
 }
 
+void check_fileno(FILE *F) {
+  int Ret = fileno(F);
+  clang_analyzer_eval(F != NULL);// expected-warning{{TRUE}}
+  if (!(Ret >= 0)) {
+clang_analyzer_eval(Ret == -1);  // expected-warning{{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  }
+  clang_analyzer_eval(feof(F));  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(ferror(F));// expected-warning{{UNKNOWN}}
+}
+
 void test_rewind(FILE *F) {
   errno = 0;
   rewind(F);

``




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


[clang] [clang][analyzer] Improve modeling of `fileno` in the StreamChecker (PR #76207)

2023-12-21 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/76207

None

>From a7fed7e081981b1c7c6c41dd72f0bc0736260754 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Fri, 22 Dec 2023 14:47:48 +0800
Subject: [PATCH] [clang][analyzer] Improve modeling of `fileno` in the
 StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 30 ---
 clang/test/Analysis/stream-errno.c|  7 +++--
 clang/test/Analysis/stream-noopen.c   | 12 
 3 files changed, 35 insertions(+), 14 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 254b36ed03968d..80ac910060720f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -265,7 +265,11 @@ class StreamChecker : public Checker FnTestDescriptions = {
@@ -342,8 +345,8 @@ class StreamChecker : public Checker();
   ProgramStateRef StateNotFailed =
   State->BindExpr(CE, C.getLocationContext(), RetVal);
-  auto Cond = SVB.evalBinOp(State, BO_GE, RetVal,
-SVB.makeZeroVal(C.getASTContext().LongTy),
-SVB.getConditionType())
-  .getAs();
+  auto Cond =
+  SVB.evalBinOp(State, BO_GE, RetVal,
+SVB.makeZeroVal(IsRetLongTy ? C.getASTContext().LongTy
+: C.getASTContext().IntTy),
+SVB.getConditionType())
+  .getAs();
   if (!Cond)
 return;
   StateNotFailed = StateNotFailed->assume(*Cond, true);
@@ -1078,7 +1084,9 @@ void StreamChecker::evalFtell(const FnDescription *Desc, 
const CallEvent ,
 return;
 
   ProgramStateRef StateFailed = State->BindExpr(
-  CE, C.getLocationContext(), SVB.makeIntVal(-1, 
C.getASTContext().LongTy));
+  CE, C.getLocationContext(),
+  SVB.makeIntVal(-1, IsRetLongTy ? C.getASTContext().LongTy
+ : C.getASTContext().IntTy));
 
   // This function does not affect the stream state.
   // Still we add success and failure state with the appropriate return value.
diff --git a/clang/test/Analysis/stream-errno.c 
b/clang/test/Analysis/stream-errno.c
index bf0a61db2424f9..62befbc78e5a75 100644
--- a/clang/test/Analysis/stream-errno.c
+++ b/clang/test/Analysis/stream-errno.c
@@ -216,9 +216,10 @@ void check_fileno(void) {
   int N = fileno(F);
   if (N == -1) {
 clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
-if (errno) {} // no-warning
-fclose(F);
-return;
+if (errno) {}// no-warning
+  } else {
+clang_analyzer_eval(N >= 0); // expected-warning{{TRUE}}
   }
   if (errno) {} // expected-warning{{An undefined value may be read from 
'errno'}}
+  fclose(F);
 }
diff --git a/clang/test/Analysis/stream-noopen.c 
b/clang/test/Analysis/stream-noopen.c
index 2daf640c18a1d4..198b5dc45e35da 100644
--- a/clang/test/Analysis/stream-noopen.c
+++ b/clang/test/Analysis/stream-noopen.c
@@ -129,6 +129,18 @@ void check_ftell(FILE *F) {
   clang_analyzer_eval(ferror(F)); // expected-warning {{UNKNOWN}}
 }
 
+void check_fileno(FILE *F) {
+  int Ret = fileno(F);
+  clang_analyzer_eval(F != NULL);// expected-warning{{TRUE}}
+  if (!(Ret >= 0)) {
+clang_analyzer_eval(Ret == -1);  // expected-warning{{TRUE}}
+clang_analyzer_eval(errno != 0); // expected-warning{{TRUE}}
+if (errno) {}// no-warning
+  }
+  clang_analyzer_eval(feof(F));  // expected-warning{{UNKNOWN}}
+  clang_analyzer_eval(ferror(F));// expected-warning{{UNKNOWN}}
+}
+
 void test_rewind(FILE *F) {
   errno = 0;
   rewind(F);

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


[lld] [clang] [llvm] [compiler-rt] [mlir] [hwasan] Make stack variables output consistent with globals (PR #76197)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-21 Thread Noah Watkins via cfe-commits

dotnwat wrote:

This is a very nice check for us to have @rockwotj.

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


[clang] [clang-format] Fix a bug in annotating function declaration names (PR #76206)

2023-12-21 Thread Owen Pan via cfe-commits

owenca wrote:

See 
[here](https://discourse.llvm.org/t/why-are-the-breaks-sometimes-removed-when-alwaysbreakafterreturntype-is-all/75780/4?u=owenpan)
 for background info.

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


[clang] [clang-format] Fix a bug in annotating function declaration names (PR #76206)

2023-12-21 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Owen Pan (owenca)


Changes

Annotates function declaration names having unnamed parameters.

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


2 Files Affected:

- (modified) clang/lib/Format/TokenAnnotator.cpp (+2-1) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+7) 


``diff
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f3551af3424396..3ac3aa3c5e3a22 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3403,7 +3403,8 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   continue;
 }
 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
-Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
+Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis,
+ TT_TypeName)) {
   return true;
 }
 if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 8e6935319b2f3d..2cafc0438ffb46 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1718,6 +1718,13 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsFunctionDeclarationNames) {
   ASSERT_EQ(Tokens.size(), 14u) << Tokens;
   EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_FunctionTypeLParen);
+
+  auto Style = getLLVMStyle();
+  Style.TypeNames.push_back("time_t");
+  Tokens = annotate("int iso_time(time_t);", Style);
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[3], tok::identifier, TT_TypeName);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsCtorAndDtorDeclNames) {

``




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


[clang] [clang-format] Fix a bug in annotating function declaration names (PR #76206)

2023-12-21 Thread Owen Pan via cfe-commits

https://github.com/owenca created 
https://github.com/llvm/llvm-project/pull/76206

Annotates function declaration names having unnamed parameters.

>From 170d2e573904286ae6ee8fad9df6ea467eb54eb8 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Thu, 21 Dec 2023 21:27:47 -0800
Subject: [PATCH] [clang-format] Fix a bug in annotating function declaration
 names

Annotates function declaration names having unnamed parameters.
---
 clang/lib/Format/TokenAnnotator.cpp   | 3 ++-
 clang/unittests/Format/TokenAnnotatorTest.cpp | 7 +++
 2 files changed, 9 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index f3551af3424396..3ac3aa3c5e3a22 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -3403,7 +3403,8 @@ static bool isFunctionDeclarationName(bool IsCpp, const 
FormatToken ,
   continue;
 }
 if (Tok->is(tok::kw_const) || Tok->isSimpleTypeSpecifier() ||
-Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis)) {
+Tok->isOneOf(TT_PointerOrReference, TT_StartOfName, tok::ellipsis,
+ TT_TypeName)) {
   return true;
 }
 if (Tok->isOneOf(tok::l_brace, TT_ObjCMethodExpr) || Tok->Tok.isLiteral())
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 8e6935319b2f3d..2cafc0438ffb46 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1718,6 +1718,13 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsFunctionDeclarationNames) {
   ASSERT_EQ(Tokens.size(), 14u) << Tokens;
   EXPECT_TOKEN(Tokens[3], tok::identifier, TT_Unknown);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_FunctionTypeLParen);
+
+  auto Style = getLLVMStyle();
+  Style.TypeNames.push_back("time_t");
+  Tokens = annotate("int iso_time(time_t);", Style);
+  ASSERT_EQ(Tokens.size(), 7u) << Tokens;
+  EXPECT_TOKEN(Tokens[1], tok::identifier, TT_FunctionDeclarationName);
+  EXPECT_TOKEN(Tokens[3], tok::identifier, TT_TypeName);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsCtorAndDtorDeclNames) {

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


[llvm] [clang] [CMake] Move check for dlfcn.h and dladdr to clang (PR #76163)

2023-12-21 Thread NAKAMURA Takumi via cfe-commits

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

Thanks.

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


[llvm] [clang] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-21 Thread Brandon Wu via cfe-commits


@@ -349,16 +349,24 @@ multiclass VPseudoSiFiveVMACC;
 }
 
-multiclass VPseudoSiFiveVQMACC {
+multiclass VPseudoSiFiveVQMACCDOD {
   foreach m = MxListVF8 in
 let VLMul = m.value in
 defm NAME : VPseudoSiFiveVMACC;
 }
 
+multiclass VPseudoSiFiveVQMACCQOQ {
+  foreach i = [0, 1, 2, 3] in
+let VLMul = MxListVF4[i].value in
+defm NAME : VPseudoSiFiveVMACC;
+}
+
 multiclass VPseudoSiFiveVFWMACC {
-  foreach m = MxListFW in
-let VLMul = m.value in
-defm NAME : VPseudoSiFiveVMACC;
+  foreach i = [0, 1, 2, 3, 4] in
+let VLMul = MxListVF2[i].value in
+defm NAME : VPseudoSiFiveVMACC;

4vtomat wrote:

Yes, it's the same lol~


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


[clang] [flang] [flang][Driver] Support `-pthread` to the frontend. (PR #75739)

2023-12-21 Thread Kareem Ergawy via cfe-commits

ergawy wrote:

> Hi @ergawy , thanks for this contribution! Could you add a test that would 
> demonstrate compilation failing without `-pthread`?

Thanks for the suggestion. Actually I failed to do that . After looking into 
it, seem that for the GNU toolchain, the `-pthread` flag would be redundant. 
That reason is that the pthread API is defined by `libc` which is linked in by 
the driver by default.

I think I will abandon this PR then. Just need to double check once more. 

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


[llvm] [clang] Recommit [RISCV] Update the interface of sifive vqmaccqoq (#74284) (PR #75768)

2023-12-21 Thread Brandon Wu via cfe-commits


@@ -349,16 +349,24 @@ multiclass VPseudoSiFiveVMACC;
 }
 
-multiclass VPseudoSiFiveVQMACC {
+multiclass VPseudoSiFiveVQMACCDOD {
   foreach m = MxListVF8 in
 let VLMul = m.value in
 defm NAME : VPseudoSiFiveVMACC;
 }
 
+multiclass VPseudoSiFiveVQMACCQOQ {
+  foreach i = [0, 1, 2, 3] in
+let VLMul = MxListVF4[i].value in
+defm NAME : VPseudoSiFiveVMACChttps://github.com/llvm/llvm-project/pull/75768
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[llvm] [clang] [libcxx] [clang-tools-extra] [libcxx] adds ranges::fold_left_with_iter and ranges::fold_left (PR #75259)

2023-12-21 Thread via cfe-commits

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


[llvm] [clang-tools-extra] [clang] [libcxx] [libcxx] adds ranges::fold_left_with_iter and ranges::fold_left (PR #75259)

2023-12-21 Thread Konstantin Varlamov via cfe-commits


@@ -0,0 +1,104 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+// template 
+// struct in_value_result;
+
+#include 
+#include 
+#include 
+#include 
+
+#include "MoveOnly.h"
+
+struct A {
+  explicit A(int);
+};
+// no implicit conversion
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result>);
+
+struct B {
+  B(int);
+};
+// implicit conversion
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result>);
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result&>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result&>);
+
+struct C {
+  C(int&);
+};
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result&>);
+
+// has to be convertible via const&
+static_assert(std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+
+// should be move constructible
+static_assert(std::is_move_constructible_v>);
+static_assert(std::is_move_constructible_v>);
+
+// should not copy constructible with move-only type

var-const wrote:

I fully agree that adding this to a project-wide style guide would be very 
useful (to be clear, I don't mean to imply it has to be a comprehensive huge 
guide, even if it documents just a few randomly chosen aspects, it's already 
helpful and we can always expand later). We do have a ["Coding 
standards"](https://libcxx.llvm.org/Contributing.html#coding-standards) section 
in the `Contributing` document -- we might want to add a new page and link it 
from that section. Thanks for taking this on!

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


[clang] [Sema] Add -Wc++11-narrowing-const-reference (PR #76094)

2023-12-21 Thread Fangrui Song via cfe-commits

https://github.com/MaskRay updated 
https://github.com/llvm/llvm-project/pull/76094

>From 132a5293a89d15d3e38c768727723157427f49db Mon Sep 17 00:00:00 2001
From: Fangrui Song 
Date: Wed, 20 Dec 2023 10:57:15 -0800
Subject: [PATCH 1/2] [Sema] Add -Wc++11-narrowing-const-reference

https://github.com/llvm/llvm-project/pull/75332 diagnosed narrowing
involving const reference. Our depot has hundreds if not thousands of
breakages
(https://github.com/llvm/llvm-project/pull/75332#issuecomment-1864757240).
Add a subgroup of -Wc++11-narrowing to help users gradually fix their
issues without regressing the existing -Wc++11-narrowing diagnostics.
---
 clang/include/clang/Basic/DiagnosticGroups.td |  3 +-
 .../clang/Basic/DiagnosticSemaKinds.td| 12 +++
 clang/lib/Sema/SemaInit.cpp   | 31 +--
 .../dcl.decl/dcl.init/dcl.init.list/p7-0x.cpp |  3 ++
 clang/test/SemaCXX/GH63151.cpp|  3 +-
 5 files changed, 41 insertions(+), 11 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 7cf347e92d9972..6765721ae7002c 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -348,7 +348,8 @@ def CXX98CompatPedantic : DiagGroup<"c++98-compat-pedantic",
  CXXPre20CompatPedantic,
  CXXPre23CompatPedantic]>;
 
-def CXX11Narrowing : DiagGroup<"c++11-narrowing">;
+def CXX11NarrowingConstReference : 
DiagGroup<"c++11-narrowing-const-reference">;
+def CXX11Narrowing : DiagGroup<"c++11-narrowing", 
[CXX11NarrowingConstReference]>;
 
 def CXX11WarnInconsistentOverrideDestructor :
   DiagGroup<"inconsistent-missing-destructor-override">;
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index c100041ca400f2..aebb7d9b945c33 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -6158,12 +6158,24 @@ def err_illegal_initializer_type : Error<"illegal 
initializer type %0">;
 def ext_init_list_type_narrowing : ExtWarn<
   "type %0 cannot be narrowed to %1 in initializer list">,
   InGroup, DefaultError, SFINAEFailure;
+// *_narrowing_const_reference diagnostics have the same messages, but are
+// controlled by -Wc++11-narrowing-const-reference for narrowing involving a
+// const reference.
+def ext_init_list_type_narrowing_const_reference : ExtWarn<
+  "type %0 cannot be narrowed to %1 in initializer list">,
+  InGroup, DefaultError, SFINAEFailure;
 def ext_init_list_variable_narrowing : ExtWarn<
   "non-constant-expression cannot be narrowed from type %0 to %1 in "
   "initializer list">, InGroup, DefaultError, SFINAEFailure;
+def ext_init_list_variable_narrowing_const_reference : ExtWarn<
+  "non-constant-expression cannot be narrowed from type %0 to %1 in "
+  "initializer list">, InGroup, DefaultError, 
SFINAEFailure;
 def ext_init_list_constant_narrowing : ExtWarn<
   "constant expression evaluates to %0 which cannot be narrowed to type %1">,
   InGroup, DefaultError, SFINAEFailure;
+def ext_init_list_constant_narrowing_const_reference : ExtWarn<
+  "constant expression evaluates to %0 which cannot be narrowed to type %1">,
+  InGroup, DefaultError, SFINAEFailure;
 def warn_init_list_type_narrowing : Warning<
   "type %0 cannot be narrowed to %1 in initializer list in C++11">,
   InGroup, DefaultIgnore;
diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index 0fbd87ce34db90..8fc74f69c9f0ab 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -10410,40 +10410,53 @@ static void DiagnoseNarrowingInInitList(Sema ,
 // No narrowing occurred.
 return;
 
-  case NK_Type_Narrowing:
+  case NK_Type_Narrowing: {
 // This was a floating-to-integer conversion, which is always considered a
 // narrowing conversion even if the value is a constant and can be
 // represented exactly as an integer.
-S.Diag(PostInit->getBeginLoc(), NarrowingErrs(S.getLangOpts())
-? diag::ext_init_list_type_narrowing
-: diag::warn_init_list_type_narrowing)
+QualType T = EntityType.getNonReferenceType();
+S.Diag(PostInit->getBeginLoc(),
+   NarrowingErrs(S.getLangOpts())
+   ? (T == EntityType
+  ? diag::ext_init_list_type_narrowing
+  : diag::ext_init_list_type_narrowing_const_reference)
+   : diag::warn_init_list_type_narrowing)
 << PostInit->getSourceRange()
 << PreNarrowingType.getLocalUnqualifiedType()
-<< EntityType.getNonReferenceType().getLocalUnqualifiedType();
+<< T.getLocalUnqualifiedType();
 break;
+  }
 
-  case NK_Constant_Narrowing:
+  case NK_Constant_Narrowing: {
 // A constant value was narrowed.
+QualType 

[clang] [llvm] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2023-12-21 Thread Elvis Wang via cfe-commits

https://github.com/ElvisWang123 updated 
https://github.com/llvm/llvm-project/pull/75021

>From 22ff830f3bd113eebd6b8369c61700879ae02b4a Mon Sep 17 00:00:00 2001
From: Elvis Wang 
Date: Sun, 10 Dec 2023 18:34:37 -0800
Subject: [PATCH] [PGO] Add `-fdiagnostics-show-profile-count` option to show
 real loop count from instr-profile

The original `-fdiagnostics-show-hotness` option show the relative
number of the loop count which is calculate by the
`function_entry_count` and `branch_frequency`. We want to know the real
loop iteration count in the remark which is collect in the instrument
profile, adding a new option to expose the new feature.

- Add a new metadata `MD_prof_count` which contains the runtime loop
iterations count. For example:
```
loop.header:
  ...
  br  i1  %0, label %true, label %false, !prof.count !0
...
!0 = !{!"profile_count", !i64 0}
```

- If option `-fdiagnostics-show-profile-count` is set we will append the
`MD_prof_count` metadata at the branch instruction at the header of
loops.
- Show the profile count like hotness with remark. For example:
```
  remark: the cost-model indicates that interleaving is not beneficial
  (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
  38 |   for(int i = 0;  i < argc % 20; i++){
 |   ^
```
---
 clang/docs/UsersManual.rst| 24 ++
 .../clang/Basic/DiagnosticDriverKinds.td  |  3 +
 clang/include/clang/Driver/Options.td |  3 +
 clang/lib/CodeGen/CGStmt.cpp  | 27 ++-
 clang/lib/CodeGen/CodeGenAction.cpp   |  4 +
 clang/lib/CodeGen/CodeGenFunction.h   |  1 +
 clang/lib/CodeGen/CodeGenPGO.cpp  | 12 +++
 clang/lib/Driver/ToolChains/Clang.cpp |  5 ++
 clang/lib/Frontend/CompilerInvocation.cpp |  6 ++
 ...ization-remark-with-profile-count.proftext |  9 +++
 ...ization-remark-with-profile-count-new-pm.c | 41 +++
 .../Inputs/c-profile-count-metadata.proftext  | 32 
 clang/test/Profile/c-profile-count-metadata.c | 73 +++
 llvm/docs/LangRef.rst | 22 ++
 .../llvm/Analysis/OptimizationRemarkEmitter.h |  7 ++
 llvm/include/llvm/IR/DiagnosticInfo.h |  6 ++
 llvm/include/llvm/IR/FixedMetadataKinds.def   |  1 +
 llvm/include/llvm/IR/MDBuilder.h  |  3 +
 llvm/include/llvm/Remarks/Remark.h|  4 +
 .../Analysis/OptimizationRemarkEmitter.cpp| 22 ++
 llvm/lib/IR/LLVMRemarkStreamer.cpp|  1 +
 llvm/lib/IR/MDBuilder.cpp | 10 +++
 llvm/lib/Remarks/Remark.cpp   |  2 +
 llvm/lib/Remarks/YAMLRemarkSerializer.cpp |  7 +-
 24 files changed, 319 insertions(+), 6 deletions(-)
 create mode 100644 
clang/test/Frontend/Inputs/optimization-remark-with-profile-count.proftext
 create mode 100644 
clang/test/Frontend/optimization-remark-with-profile-count-new-pm.c
 create mode 100644 clang/test/Profile/Inputs/c-profile-count-metadata.proftext
 create mode 100644 clang/test/Profile/c-profile-count-metadata.c

diff --git a/clang/docs/UsersManual.rst b/clang/docs/UsersManual.rst
index f1b344ef5109b5..e3e4b585713df9 100644
--- a/clang/docs/UsersManual.rst
+++ b/clang/docs/UsersManual.rst
@@ -425,6 +425,30 @@ output format of the diagnostics that it generates.
If this option is not used, all the passes are included in the optimization
record.
 
+.. option:: -fdiagnostics-show-profile-count
+
+   Enable profile loop count information in diagnostic line.
+
+   This option controls whether Clang prints the profile loop count associated
+   with diagnostics in the presence of profile-guided optimization information.
+   This is currently supported with optimization remarks (see
+   :ref:`Options to Emit Optimization Reports `). The profile count 
information
+   allows users to focus on the hot optimization remarks that are likely to be
+   more relevant for run-time performance. The main difference between profile 
count
+   the hotness is the profile count is the real profile count from the runtime
+   profile and hotness is a relative number calculated by function entry count 
and
+   weight.
+
+   For example, in this output, the block containing the callsite of `foo` was
+   executed 3000 times according to the profile data:
+
+   ::
+
+s.c:38:3: remark: the cost-model indicates that interleaving is not 
beneficial (ProfileCount: 20) [-Rpass-analysis=loop-vectorize]
+  for(int i = 0;  i < 20; i++){
+  ^
+
+
 .. _opt_fdiagnostics-show-hotness:
 
 .. option:: -f[no-]diagnostics-show-hotness
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 676f1a62b49dd0..47ad1e058a1d82 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -420,6 +420,9 @@ def warn_drv_empty_joined_argument : Warning<
 def warn_drv_diagnostics_hotness_requires_pgo : Warning<
   "argument '%0' requires 

[clang] [llvm] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2023-12-21 Thread Elvis Wang via cfe-commits


@@ -2091,6 +2091,12 @@ bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions 
, ArgList ,
   bool UsingProfile =
   UsingSampleProfile || !Opts.ProfileInstrumentUsePath.empty();
 
+  if (Args.hasArg(options::OPT_fdiagnostics_show_profile_count) &&

ElvisWang123 wrote:

This option `options::OPT_fdiagnostics_show_profile_count` also appears in the 
`clang/lib/Driver/Toochains/clang.cpp` to enable the profile metadata appending 
to IR.

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


[clang-tools-extra] [clang-tidy] introduce a unused local non trival variable check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits

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


[llvm] [clang] [PGO]Add `-fdiagnostics-show-profile-count` option to show real loop count from instr-profile (PR #75021)

2023-12-21 Thread Elvis Wang via cfe-commits

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


[libc] [clang] [openmp] [flang] [libcxx] [llvm] [compiler-rt] [lldb] [mlir] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[libc] [clang] [openmp] [flang] [libcxx] [llvm] [compiler-rt] [lldb] [mlir] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Florian Mayer via cfe-commits

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


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


[mlir] [openmp] [libcxx] [compiler-rt] [llvm] [lldb] [libc] [clang] [flang] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> Remove this comment?
> 
> Line 780
> 
> ```
> // TODO(fmayer): figure out how to distinguish use-after-return and
> // stack-buffer-overflow.
> ```

done

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


[mlir] [openmp] [libcxx] [compiler-rt] [llvm] [lldb] [libc] [clang] [flang] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/76133

>From 89636904337efe75ef6e0743e4f098f0d5b5ab56 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 20 Dec 2023 23:58:05 -0800
Subject: [PATCH 1/4] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 compiler-rt/lib/hwasan/hwasan_report.cpp  | 26 ++-
 .../test/hwasan/TestCases/Linux/syscalls.cpp  |  2 +-
 .../hwasan/TestCases/heap-buffer-overflow.c   |  7 ++---
 3 files changed, 24 insertions(+), 11 deletions(-)

diff --git a/compiler-rt/lib/hwasan/hwasan_report.cpp 
b/compiler-rt/lib/hwasan/hwasan_report.cpp
index 5e8aa315801bcd..dc34cded48e12c 100644
--- a/compiler-rt/lib/hwasan/hwasan_report.cpp
+++ b/compiler-rt/lib/hwasan/hwasan_report.cpp
@@ -205,6 +205,7 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
   tag_t addr_tag, uptr untagged_addr) {
   uptr frames = Min((uptr)flags()->stack_history_size, sa->size());
   bool found_local = false;
+  InternalScopedString location;
   for (uptr i = 0; i < frames; i++) {
 const uptr *record_addr = &(*sa)[i];
 uptr record = *record_addr;
@@ -233,11 +234,16 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
 if (obj_offset >= local.size)
   continue;
 if (!found_local) {
-  Printf("Potentially referenced stack objects:\n");
+  Printf("\nPotentially referenced stack objects:\n");
   found_local = true;
 }
-Printf("  %s in %s %s:%d\n", local.name, local.function_name,
-   local.decl_file, local.decl_line);
+StackTracePrinter::GetOrInit()->RenderSourceLocation(
+, local.decl_file, local.decl_line, 0,
+common_flags()->symbolize_vs_style,
+common_flags()->strip_path_prefix);
+Printf("  %s in %s %s\n", local.name, local.function_name,
+   location.data());
+location.clear();
   }
   frame.Clear();
 }
@@ -363,7 +369,7 @@ static void PrintTagsAroundAddr(uptr addr, GetTag get_tag,
   InternalScopedString s;
   addr = MemToShadow(addr);
   s.AppendF(
-  "Memory tags around the buggy address (one tag corresponds to %zd "
+  "\nMemory tags around the buggy address (one tag corresponds to %zd "
   "bytes):\n",
   kShadowAlignment);
   PrintTagInfoAroundAddr(addr, kShadowLines, s,
@@ -648,19 +654,23 @@ void BaseReport::PrintHeapOrGlobalCandidate() const {
   if (candidate.heap.is_allocated) {
 uptr offset;
 const char *whence;
+const char *cause;
 if (candidate.heap.begin <= untagged_addr &&
 untagged_addr < candidate.heap.end) {
   offset = untagged_addr - candidate.heap.begin;
   whence = "inside";
+  cause = "heap-use-after-free";
 } else if (candidate.after) {
   offset = untagged_addr - candidate.heap.end;
   whence = "after";
+  cause = "heap-buffer-overflow";
 } else {
   offset = candidate.heap.begin - untagged_addr;
   whence = "before";
+  cause = "heap-buffer-underflow";
 }
 Printf("%s", d.Error());
-Printf("\nCause: heap-buffer-overflow\n");
+Printf("\nCause: %s\n", cause);
 Printf("%s", d.Default());
 Printf("%s", d.Location());
 Printf("%p is located %zd bytes %s a %zd-byte region [%p,%p)\n",
@@ -803,8 +813,10 @@ void BaseReport::PrintAddressDescription() const {
   }
 
   // Print the remaining threads, as an extra information, 1 line per thread.
-  if (flags()->print_live_threads_info)
+  if (flags()->print_live_threads_info) {
+Printf("\n");
 hwasanThreadList().VisitAllLiveThreads([&](Thread *t) { t->Announce(); });
+  }
 
   if (!num_descriptions_printed)
 // We exhausted our possibilities. Bail out.
@@ -1020,7 +1032,7 @@ void ReportTagMismatch(StackTrace *stack, uptr 
tagged_addr, uptr access_size,
 // See the frame breakdown defined in __hwasan_tag_mismatch (from
 // hwasan_tag_mismatch_{aarch64,riscv64}.S).
 void ReportRegisters(const uptr *frame, uptr pc) {
-  Printf("Registers where the failure occurred (pc %p):\n", pc);
+  Printf("\nRegisters where the failure occurred (pc %p):\n", pc);
 
   // We explicitly print a single line (4 registers/line) each iteration to
   // reduce the amount of logcat error messages printed. Each Printf() will
diff --git a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp 
b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
index 154b6989899352..eee43f458fac10 100644
--- a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
+++ b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
@@ -26,7 +26,7 @@ int main(int argc, char *argv[]) {
 
   __sanitizer_syscall_pre_recvmsg(0, buf - 1, 0);
   // CHECK: HWAddressSanitizer: tag-mismatch on address 

[clang] [openmp] [Clang][OpenMP] Fix mapping of structs to device (PR #75642)

2023-12-21 Thread Joseph Huber via cfe-commits

jhuber6 wrote:

> This fails for me on the host and the AMD GPU: GPU:
> 
> ```
> # | :217:1: note: possible intended match here
> # | dat.datum[dat.arr[0][0]] = 5
> ```
> 
> X86:
> 
> ```
> # | :134:1: note: possible intended match here
> # | dat.datum[dat.arr[0][0]] = 5461
> ```
> 
> The location that is printed (datum[1]) is uninitialized.

I see the same but forgot to say anything.

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


[mlir] [openmp] [libcxx] [compiler-rt] [llvm] [lldb] [libc] [clang] [flang] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/76133

>From 89636904337efe75ef6e0743e4f098f0d5b5ab56 Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 20 Dec 2023 23:58:05 -0800
Subject: [PATCH 1/3] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 compiler-rt/lib/hwasan/hwasan_report.cpp  | 26 ++-
 .../test/hwasan/TestCases/Linux/syscalls.cpp  |  2 +-
 .../hwasan/TestCases/heap-buffer-overflow.c   |  7 ++---
 3 files changed, 24 insertions(+), 11 deletions(-)

diff --git a/compiler-rt/lib/hwasan/hwasan_report.cpp 
b/compiler-rt/lib/hwasan/hwasan_report.cpp
index 5e8aa315801bcd..dc34cded48e12c 100644
--- a/compiler-rt/lib/hwasan/hwasan_report.cpp
+++ b/compiler-rt/lib/hwasan/hwasan_report.cpp
@@ -205,6 +205,7 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
   tag_t addr_tag, uptr untagged_addr) {
   uptr frames = Min((uptr)flags()->stack_history_size, sa->size());
   bool found_local = false;
+  InternalScopedString location;
   for (uptr i = 0; i < frames; i++) {
 const uptr *record_addr = &(*sa)[i];
 uptr record = *record_addr;
@@ -233,11 +234,16 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
 if (obj_offset >= local.size)
   continue;
 if (!found_local) {
-  Printf("Potentially referenced stack objects:\n");
+  Printf("\nPotentially referenced stack objects:\n");
   found_local = true;
 }
-Printf("  %s in %s %s:%d\n", local.name, local.function_name,
-   local.decl_file, local.decl_line);
+StackTracePrinter::GetOrInit()->RenderSourceLocation(
+, local.decl_file, local.decl_line, 0,
+common_flags()->symbolize_vs_style,
+common_flags()->strip_path_prefix);
+Printf("  %s in %s %s\n", local.name, local.function_name,
+   location.data());
+location.clear();
   }
   frame.Clear();
 }
@@ -363,7 +369,7 @@ static void PrintTagsAroundAddr(uptr addr, GetTag get_tag,
   InternalScopedString s;
   addr = MemToShadow(addr);
   s.AppendF(
-  "Memory tags around the buggy address (one tag corresponds to %zd "
+  "\nMemory tags around the buggy address (one tag corresponds to %zd "
   "bytes):\n",
   kShadowAlignment);
   PrintTagInfoAroundAddr(addr, kShadowLines, s,
@@ -648,19 +654,23 @@ void BaseReport::PrintHeapOrGlobalCandidate() const {
   if (candidate.heap.is_allocated) {
 uptr offset;
 const char *whence;
+const char *cause;
 if (candidate.heap.begin <= untagged_addr &&
 untagged_addr < candidate.heap.end) {
   offset = untagged_addr - candidate.heap.begin;
   whence = "inside";
+  cause = "heap-use-after-free";
 } else if (candidate.after) {
   offset = untagged_addr - candidate.heap.end;
   whence = "after";
+  cause = "heap-buffer-overflow";
 } else {
   offset = candidate.heap.begin - untagged_addr;
   whence = "before";
+  cause = "heap-buffer-underflow";
 }
 Printf("%s", d.Error());
-Printf("\nCause: heap-buffer-overflow\n");
+Printf("\nCause: %s\n", cause);
 Printf("%s", d.Default());
 Printf("%s", d.Location());
 Printf("%p is located %zd bytes %s a %zd-byte region [%p,%p)\n",
@@ -803,8 +813,10 @@ void BaseReport::PrintAddressDescription() const {
   }
 
   // Print the remaining threads, as an extra information, 1 line per thread.
-  if (flags()->print_live_threads_info)
+  if (flags()->print_live_threads_info) {
+Printf("\n");
 hwasanThreadList().VisitAllLiveThreads([&](Thread *t) { t->Announce(); });
+  }
 
   if (!num_descriptions_printed)
 // We exhausted our possibilities. Bail out.
@@ -1020,7 +1032,7 @@ void ReportTagMismatch(StackTrace *stack, uptr 
tagged_addr, uptr access_size,
 // See the frame breakdown defined in __hwasan_tag_mismatch (from
 // hwasan_tag_mismatch_{aarch64,riscv64}.S).
 void ReportRegisters(const uptr *frame, uptr pc) {
-  Printf("Registers where the failure occurred (pc %p):\n", pc);
+  Printf("\nRegisters where the failure occurred (pc %p):\n", pc);
 
   // We explicitly print a single line (4 registers/line) each iteration to
   // reduce the amount of logcat error messages printed. Each Printf() will
diff --git a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp 
b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
index 154b6989899352..eee43f458fac10 100644
--- a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
+++ b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
@@ -26,7 +26,7 @@ int main(int argc, char *argv[]) {
 
   __sanitizer_syscall_pre_recvmsg(0, buf - 1, 0);
   // CHECK: HWAddressSanitizer: tag-mismatch on address 

[clang] [openmp] [Clang][OpenMP] Fix mapping of structs to device (PR #75642)

2023-12-21 Thread Johannes Doerfert via cfe-commits

jdoerfert wrote:

This fails for me on the host and the AMD GPU:
GPU:
# | :217:1: note: possible intended match here
# | dat.datum[dat.arr[0][0]] = 5
X86:
# | :134:1: note: possible intended match here
# | dat.datum[dat.arr[0][0]] = 5461

The location that is printed (datum[1]) is uninitialized.


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


[llvm] [openmp] [libc] [compiler-rt] [lldb] [mlir] [flang] [libcxx] [clang] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Florian Mayer via cfe-commits

https://github.com/fmayer commented:

Remove this comment?

Line 780

```
// TODO(fmayer): figure out how to distinguish use-after-return and
// stack-buffer-overflow.
```

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


[llvm] [libc] [compiler-rt] [clang-tools-extra] [lldb] [flang] [libcxx] [clang] [RegAllocFast] Refactor dominates algorithm for large basic block (PR #72250)

2023-12-21 Thread via cfe-commits

https://github.com/HaohaiWen updated 
https://github.com/llvm/llvm-project/pull/72250

>From 581b28b6827855643bd5bdbca0cf9ccef0de2584 Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Tue, 14 Nov 2023 20:20:29 +0800
Subject: [PATCH 1/2] [RegAllocFast] Refactor dominates algorithm for large
 basic block

The original brute force dominates algorithm is O(n) complexity so it is
very slow for very large machine basic block which is very common with
O0. This patch added InstrPosIndexes to assign index for each
instruction and use it to determine dominance. The complexity is now
O(1).
---
 llvm/lib/CodeGen/RegAllocFast.cpp | 92 ++-
 1 file changed, 78 insertions(+), 14 deletions(-)

diff --git a/llvm/lib/CodeGen/RegAllocFast.cpp 
b/llvm/lib/CodeGen/RegAllocFast.cpp
index b216d729644626..acdc32f5902fa8 100644
--- a/llvm/lib/CodeGen/RegAllocFast.cpp
+++ b/llvm/lib/CodeGen/RegAllocFast.cpp
@@ -62,6 +62,71 @@ static RegisterRegAlloc fastRegAlloc("fast", "fast register 
allocator",
 
 namespace {
 
+/// Assign ascending index for instructions in machine basic block. The index
+/// can be used to determine dominance between instructions in same MBB.
+class InstrPosIndexes {
+public:
+  void init(const MachineBasicBlock ) {
+CurMBB = 
+Instr2PosIndex.clear();
+uint64_t LastIndex = 0;
+for (const MachineInstr  : MBB) {
+  LastIndex += InstrDist;
+  Instr2PosIndex[] = LastIndex;
+}
+  }
+
+  /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to 
assign
+  /// index without affecting existing instruction's index. Return true if all
+  /// instructions index has been reassigned.
+  bool getIndex(const MachineInstr , uint64_t ) {
+assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
+if (Instr2PosIndex.count()) {
+  Index = Instr2PosIndex[];
+  return false;
+}
+
+unsigned Distance = 1;
+MachineBasicBlock::const_iterator Start = MI.getIterator(),
+  End = std::next(Start);
+while (Start != CurMBB->begin() &&
+   !Instr2PosIndex.count(&*std::prev(Start))) {
+  --Start;
+  ++Distance;
+}
+while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
+  ++End;
+  ++Distance;
+}
+
+uint64_t LastIndex =
+Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
+uint64_t Step = End == CurMBB->end()
+? static_cast(InstrDist)
+: (Instr2PosIndex.at(&*End) - LastIndex - 1) / 
Distance;
+
+// Reassign index for all instructions if number of new inserted
+// instructions exceed slot or all instructions are new.
+if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
+  init(*CurMBB);
+  Index = Instr2PosIndex.at();
+  return true;
+}
+
+for (auto I = Start; I != End; ++I) {
+  LastIndex += Step;
+  Instr2PosIndex[&*I] = LastIndex;
+}
+Index = Instr2PosIndex.at();
+return false;
+  }
+
+private:
+  enum { InstrDist = 1024 };
+  const MachineBasicBlock *CurMBB = nullptr;
+  DenseMap Instr2PosIndex;
+};
+
 class RegAllocFast : public MachineFunctionPass {
 public:
   static char ID;
@@ -153,6 +218,9 @@ class RegAllocFast : public MachineFunctionPass {
   // Register masks attached to the current instruction.
   SmallVector RegMasks;
 
+  // Assign index for each instruction to quickly determine dominance.
+  InstrPosIndexes PosIndexes;
+
   void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
   bool isPhysRegFree(MCPhysReg PhysReg) const;
 
@@ -339,18 +407,13 @@ int RegAllocFast::getStackSpaceFor(Register VirtReg) {
   return FrameIdx;
 }
 
-static bool dominates(MachineBasicBlock ,
-  MachineBasicBlock::const_iterator A,
-  MachineBasicBlock::const_iterator B) {
-  auto MBBEnd = MBB.end();
-  if (B == MBBEnd)
-return true;
-
-  MachineBasicBlock::const_iterator I = MBB.begin();
-  for (; &*I != A && &*I != B; ++I)
-;
-
-  return &*I == A;
+static bool dominates(InstrPosIndexes , const MachineInstr ,
+  const MachineInstr ) {
+  uint64_t IndexA, IndexB;
+  PosIndexes.getIndex(A, IndexA);
+  if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
+PosIndexes.getIndex(A, IndexA);
+  return IndexA < IndexB;
 }
 
 /// Returns false if \p VirtReg is known to not live out of the current block.
@@ -371,7 +434,7 @@ bool RegAllocFast::mayLiveOut(Register VirtReg) {
 MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
 return true;
   } else {
-if (!SelfLoopDef || dominates(*MBB, DefInst.getIterator(), 
SelfLoopDef))
+if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
   SelfLoopDef = 
   }
 }
@@ -396,7 +459,7 @@ bool RegAllocFast::mayLiveOut(Register VirtReg) {
   // Try to handle some simple cases to avoid spilling and reloading every
   // value inside a self looping 

[llvm] [openmp] [libc] [compiler-rt] [lldb] [mlir] [flang] [libcxx] [clang] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Florian Mayer via cfe-commits


@@ -221,29 +221,55 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
   for (LocalInfo  : frame.locals) {
 if (!local.has_frame_offset || !local.has_size || 
!local.has_tag_offset)
   continue;
+if (!(local.name && internal_strlen(local.name)) &&
+!(local.function_name && internal_strlen(local.name)) &&
+!(local.decl_file && internal_strlen(local.decl_file)))
+  continue;
 tag_t obj_tag = base_tag ^ local.tag_offset;
 if (obj_tag != addr_tag)
   continue;
-// Calculate the offset from the object address to the faulting
-// address. Because we only store bits 4-19 of FP (bits 0-3 are
-// guaranteed to be zero), the calculation is performed mod 2^20 and 
may
-// harmlessly underflow if the address mod 2^20 is below the object
-// address.
-uptr obj_offset =
-(untagged_addr - fp - local.frame_offset) & (kRecordFPModulus - 1);
-if (obj_offset >= local.size)
-  continue;
+uptr local_beg = (fp + local.frame_offset) |

fmayer wrote:

 I am confused by this. Could you add a comment as on the LHS? Why isn't the 
`local_beg` not just `fp + local.frame_offset`?

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


[clang] [llvm] [libcxx] [lldb] [flang] [openmp] [mlir] [libc] [compiler-rt] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Florian Mayer via cfe-commits


@@ -221,29 +221,55 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
   for (LocalInfo  : frame.locals) {
 if (!local.has_frame_offset || !local.has_size || 
!local.has_tag_offset)
   continue;
+if (!(local.name && internal_strlen(local.name)) &&
+!(local.function_name && internal_strlen(local.name)) &&
+!(local.decl_file && internal_strlen(local.decl_file)))
+  continue;
 tag_t obj_tag = base_tag ^ local.tag_offset;
 if (obj_tag != addr_tag)
   continue;
-// Calculate the offset from the object address to the faulting
-// address. Because we only store bits 4-19 of FP (bits 0-3 are
-// guaranteed to be zero), the calculation is performed mod 2^20 and 
may
-// harmlessly underflow if the address mod 2^20 is below the object
-// address.
-uptr obj_offset =
-(untagged_addr - fp - local.frame_offset) & (kRecordFPModulus - 1);
-if (obj_offset >= local.size)
-  continue;
+uptr local_beg = (fp + local.frame_offset) |
+ (untagged_addr & ~(uptr(kRecordFPModulus) - 1));
+uptr local_end = local_beg + local.size;
+
 if (!found_local) {
   Printf("\nPotentially referenced stack objects:\n");
   found_local = true;
 }
+
+uptr offset;
+const char *whence;
+const char *cause;
+if (local_beg <= untagged_addr && untagged_addr < local_end) {
+  offset = untagged_addr - local_beg;
+  whence = "inside";
+  cause = "use-after-scope";
+} else if (untagged_addr >= local_end) {
+  offset = untagged_addr - local_end;
+  whence = "after";
+  cause = "stack-buffer-overflow";
+} else {
+  offset = local_beg - untagged_addr;
+  whence = "before";
+  cause = "stack-buffer-overflow";
+}
+Decorator d;
+Printf("%s", d.Error());
+Printf("Cause: %s\n", cause);
+Printf("%s", d.Default());
+Printf("%s", d.Location());
+Printf("%p is located %zd bytes %s a %zd-byte region [%p,%p)\n",
+   untagged_addr, offset, whence, local_end - local_beg, local_beg,
+   local_end);
+Printf("%s", d.Allocation());
 StackTracePrinter::GetOrInit()->RenderSourceLocation(

fmayer wrote:

FYI the offline symbolizer has this output format

```
self.print('')
self.print('Potentially referenced stack object:')
self.print('  %d bytes inside a variable "%s" in stack frame of 
function "%s"' % (obj_offset, local[2], local[0]))
self.print('  at %s' % (local[1],))
```

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


[llvm] [clang-tools-extra] [libcxx] [compiler-rt] [flang] [libc] [lldb] [clang] [RegAllocFast] Refactor dominates algorithm for large basic block (PR #72250)

2023-12-21 Thread via cfe-commits

https://github.com/HaohaiWen updated 
https://github.com/llvm/llvm-project/pull/72250

>From 581b28b6827855643bd5bdbca0cf9ccef0de2584 Mon Sep 17 00:00:00 2001
From: Haohai Wen 
Date: Tue, 14 Nov 2023 20:20:29 +0800
Subject: [PATCH 1/2] [RegAllocFast] Refactor dominates algorithm for large
 basic block

The original brute force dominates algorithm is O(n) complexity so it is
very slow for very large machine basic block which is very common with
O0. This patch added InstrPosIndexes to assign index for each
instruction and use it to determine dominance. The complexity is now
O(1).
---
 llvm/lib/CodeGen/RegAllocFast.cpp | 92 ++-
 1 file changed, 78 insertions(+), 14 deletions(-)

diff --git a/llvm/lib/CodeGen/RegAllocFast.cpp 
b/llvm/lib/CodeGen/RegAllocFast.cpp
index b216d729644626..acdc32f5902fa8 100644
--- a/llvm/lib/CodeGen/RegAllocFast.cpp
+++ b/llvm/lib/CodeGen/RegAllocFast.cpp
@@ -62,6 +62,71 @@ static RegisterRegAlloc fastRegAlloc("fast", "fast register 
allocator",
 
 namespace {
 
+/// Assign ascending index for instructions in machine basic block. The index
+/// can be used to determine dominance between instructions in same MBB.
+class InstrPosIndexes {
+public:
+  void init(const MachineBasicBlock ) {
+CurMBB = 
+Instr2PosIndex.clear();
+uint64_t LastIndex = 0;
+for (const MachineInstr  : MBB) {
+  LastIndex += InstrDist;
+  Instr2PosIndex[] = LastIndex;
+}
+  }
+
+  /// Set \p Index to index of \p MI. If \p MI is new inserted, it try to 
assign
+  /// index without affecting existing instruction's index. Return true if all
+  /// instructions index has been reassigned.
+  bool getIndex(const MachineInstr , uint64_t ) {
+assert(MI.getParent() == CurMBB && "MI is not in CurMBB");
+if (Instr2PosIndex.count()) {
+  Index = Instr2PosIndex[];
+  return false;
+}
+
+unsigned Distance = 1;
+MachineBasicBlock::const_iterator Start = MI.getIterator(),
+  End = std::next(Start);
+while (Start != CurMBB->begin() &&
+   !Instr2PosIndex.count(&*std::prev(Start))) {
+  --Start;
+  ++Distance;
+}
+while (End != CurMBB->end() && !Instr2PosIndex.count(&*(End))) {
+  ++End;
+  ++Distance;
+}
+
+uint64_t LastIndex =
+Start == CurMBB->begin() ? 0 : Instr2PosIndex.at(&*std::prev(Start));
+uint64_t Step = End == CurMBB->end()
+? static_cast(InstrDist)
+: (Instr2PosIndex.at(&*End) - LastIndex - 1) / 
Distance;
+
+// Reassign index for all instructions if number of new inserted
+// instructions exceed slot or all instructions are new.
+if (LLVM_UNLIKELY(!Step || (!LastIndex && Step == InstrDist))) {
+  init(*CurMBB);
+  Index = Instr2PosIndex.at();
+  return true;
+}
+
+for (auto I = Start; I != End; ++I) {
+  LastIndex += Step;
+  Instr2PosIndex[&*I] = LastIndex;
+}
+Index = Instr2PosIndex.at();
+return false;
+  }
+
+private:
+  enum { InstrDist = 1024 };
+  const MachineBasicBlock *CurMBB = nullptr;
+  DenseMap Instr2PosIndex;
+};
+
 class RegAllocFast : public MachineFunctionPass {
 public:
   static char ID;
@@ -153,6 +218,9 @@ class RegAllocFast : public MachineFunctionPass {
   // Register masks attached to the current instruction.
   SmallVector RegMasks;
 
+  // Assign index for each instruction to quickly determine dominance.
+  InstrPosIndexes PosIndexes;
+
   void setPhysRegState(MCPhysReg PhysReg, unsigned NewState);
   bool isPhysRegFree(MCPhysReg PhysReg) const;
 
@@ -339,18 +407,13 @@ int RegAllocFast::getStackSpaceFor(Register VirtReg) {
   return FrameIdx;
 }
 
-static bool dominates(MachineBasicBlock ,
-  MachineBasicBlock::const_iterator A,
-  MachineBasicBlock::const_iterator B) {
-  auto MBBEnd = MBB.end();
-  if (B == MBBEnd)
-return true;
-
-  MachineBasicBlock::const_iterator I = MBB.begin();
-  for (; &*I != A && &*I != B; ++I)
-;
-
-  return &*I == A;
+static bool dominates(InstrPosIndexes , const MachineInstr ,
+  const MachineInstr ) {
+  uint64_t IndexA, IndexB;
+  PosIndexes.getIndex(A, IndexA);
+  if (LLVM_UNLIKELY(PosIndexes.getIndex(B, IndexB)))
+PosIndexes.getIndex(A, IndexA);
+  return IndexA < IndexB;
 }
 
 /// Returns false if \p VirtReg is known to not live out of the current block.
@@ -371,7 +434,7 @@ bool RegAllocFast::mayLiveOut(Register VirtReg) {
 MayLiveAcrossBlocks.set(Register::virtReg2Index(VirtReg));
 return true;
   } else {
-if (!SelfLoopDef || dominates(*MBB, DefInst.getIterator(), 
SelfLoopDef))
+if (!SelfLoopDef || dominates(PosIndexes, DefInst, *SelfLoopDef))
   SelfLoopDef = 
   }
 }
@@ -396,7 +459,7 @@ bool RegAllocFast::mayLiveOut(Register VirtReg) {
   // Try to handle some simple cases to avoid spilling and reloading every
   // value inside a self looping 

[clang] 033ec09 - [Clang][Sema] Fix Wswitch-default bad warning in template (#76007)

2023-12-21 Thread via cfe-commits

Author: hstk30-hw
Date: 2023-12-22T09:00:41+08:00
New Revision: 033ec098be730bff04bfb929d254ce57e5ec8534

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

LOG: [Clang][Sema] Fix Wswitch-default bad warning in template (#76007)

https://github.com/llvm/llvm-project/pull/73077 added -Wswitch-default
diagnostic but it produced false positives in templates. This PR will
address that. https://github.com/llvm/llvm-project/issues/75943

Added: 
clang/test/Sema/switch-default.cpp

Modified: 
clang/lib/Sema/SemaStmt.cpp

Removed: 
clang/test/Sema/switch-default.c



diff  --git a/clang/lib/Sema/SemaStmt.cpp b/clang/lib/Sema/SemaStmt.cpp
index 63348d27a8c94a..f0b03db690843a 100644
--- a/clang/lib/Sema/SemaStmt.cpp
+++ b/clang/lib/Sema/SemaStmt.cpp
@@ -1271,6 +1271,9 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
 
   bool CaseListIsErroneous = false;
 
+  // FIXME: We'd better diagnose missing or duplicate default labels even
+  // in the dependent case. Because default labels themselves are never
+  // dependent.
   for (SwitchCase *SC = SS->getSwitchCaseList(); SC && !HasDependentValue;
SC = SC->getNextSwitchCase()) {
 
@@ -1327,9 +1330,6 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
 }
   }
 
-  if (!TheDefaultStmt)
-Diag(SwitchLoc, diag::warn_switch_default);
-
   if (!HasDependentValue) {
 // If we don't have a default statement, check whether the
 // condition is constant.
@@ -1344,6 +1344,7 @@ Sema::ActOnFinishSwitchStmt(SourceLocation SwitchLoc, 
Stmt *Switch,
   assert(!HasConstantCond ||
  (ConstantCondValue.getBitWidth() == CondWidth &&
   ConstantCondValue.isSigned() == CondIsSigned));
+  Diag(SwitchLoc, diag::warn_switch_default);
 }
 bool ShouldCheckConstantCond = HasConstantCond;
 

diff  --git a/clang/test/Sema/switch-default.c 
b/clang/test/Sema/switch-default.c
deleted file mode 100644
index 342a97ee68b1e2..00
--- a/clang/test/Sema/switch-default.c
+++ /dev/null
@@ -1,28 +0,0 @@
-// RUN: %clang_cc1 -fsyntax-only -verify -Wswitch-default %s
-
-int f1(int a) {
-  switch (a) {// expected-warning {{'switch' missing 'default' 
label}}
-case 1: a++; break;
-case 2: a += 2; break;
-  }
-  return a;
-}
-
-int f2(int a) {
-  switch (a) {// no-warning
-default:
-  ;
-  }
-  return a;
-}
-
-// Warn even completely covered Enum cases(GCC compatibility).
-enum E { A, B };
-enum E check_enum(enum E e) {
-  switch (e) {// expected-warning {{'switch' missing 'default' 
label}}
-case A: break;
-case B: break;
-  }
-  return e;
-}
-

diff  --git a/clang/test/Sema/switch-default.cpp 
b/clang/test/Sema/switch-default.cpp
new file mode 100644
index 00..32d03dae882733
--- /dev/null
+++ b/clang/test/Sema/switch-default.cpp
@@ -0,0 +1,53 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -std=c++11 -Wswitch-default %s
+
+int f1(int a) {
+  switch (a) {// expected-warning {{'switch' missing 'default' 
label}}
+case 1: a++; break;
+case 2: a += 2; break;
+  }
+  return a;
+}
+
+int f2(int a) {
+  switch (a) {// no-warning
+default:
+  ;
+  }
+  return a;
+}
+
+// Warn even completely covered Enum cases(GCC compatibility).
+enum E { A, B };
+enum E check_enum(enum E e) {
+  switch (e) {// expected-warning {{'switch' missing 'default' 
label}}
+case A: break;
+case B: break;
+  }
+  return e;
+}
+
+template
+int t1(Index i)
+{
+  switch (i) {  // expected-warning {{'switch' missing 'default' 
label}}
+case 0: return 0;
+case 1: return 1;
+  }
+  return 0;
+}
+
+template
+int t2(Index i)
+{
+  switch (i) {// no-warning
+case 0: return 0;
+case 1: return 1;
+default: return 2;
+  }
+  return 0;
+}
+
+int main() {
+  return t1(1);   // expected-note {{in instantiation of function template 
specialization 't1' requested here}}
+}
+



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


[clang] [Clang][Sema] Fix Wswitch-default bad warning in template (PR #76007)

2023-12-21 Thread via cfe-commits

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


[clang-tools-extra] [clang] [llvm] [libcxx] [libcxx] adds ranges::fold_left_with_iter and ranges::fold_left (PR #75259)

2023-12-21 Thread via cfe-commits


@@ -0,0 +1,118 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___ALGORITHM_FOLD_H
+#define _LIBCPP___ALGORITHM_FOLD_H
+
+#include <__concepts/assignable.h>
+#include <__concepts/convertible_to.h>
+#include <__concepts/invocable.h>
+#include <__concepts/movable.h>
+#include <__config>
+#include <__functional/invoke.h>
+#include <__functional/reference_wrapper.h>
+#include <__iterator/concepts.h>
+#include <__iterator/iterator_traits.h>
+#include <__iterator/next.h>
+#include <__ranges/access.h>
+#include <__ranges/concepts.h>
+#include <__ranges/dangling.h>
+#include <__type_traits/decay.h>
+#include <__type_traits/invoke.h>
+#include <__utility/forward.h>
+#include <__utility/move.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+
+namespace ranges {
+template 
+struct in_value_result {
+  _Ip in;
+  _Tp result;
+};
+
+template 
+using fold_left_with_iter_result = in_value_result<_Ip, _Tp>;
+
+template >
+concept __indirectly_binary_left_foldable_impl =
+convertible_to<_Rp, _Up> &&//
+movable<_Tp> &&//
+movable<_Up> &&//
+convertible_to<_Tp, _Up> &&//
+invocable<_Fp&, _Up, iter_reference_t<_Ip>> && //
+assignable_from<_Up&, invoke_result_t<_Fp&, _Up, iter_reference_t<_Ip>>>;
+
+template 
+concept __indirectly_binary_left_foldable =
+copy_constructible<_Fp> && //
+invocable<_Fp&, _Tp, iter_reference_t<_Ip>> && //
+__indirectly_binary_left_foldable_impl<_Fp, _Tp, _Ip, 
invoke_result_t<_Fp&, _Tp, iter_reference_t<_Ip>>>;
+
+struct __fold_left_with_iter {
+  template  _Sp, class _Tp, 
__indirectly_binary_left_foldable<_Tp, _Ip> _Fp>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI static constexpr auto
+  operator()(_Ip __first, _Sp __last, _Tp __init, _Fp __f) {
+using _Up = decay_t>>;
+
+if (__first == __last) {
+  return fold_left_with_iter_result<_Ip, _Up>{std::move(__first), 
_Up(std::move(__init))};
+}
+
+_Up __result = std::invoke(__f, std::move(__init), *__first);
+for (++__first; __first != __last; ++__first) {
+  __result = std::invoke(__f, std::move(__result), *__first);
+}
+
+return fold_left_with_iter_result<_Ip, _Up>{std::move(__first), 
std::move(__result)};
+  }
+
+  template > _Fp>
+  _LIBCPP_NODISCARD_EXT _LIBCPP_HIDE_FROM_ABI static constexpr auto 
operator()(_Rp&& __r, _Tp __init, _Fp __f) {
+auto __result = operator()(ranges::begin(__r), ranges::end(__r), 
std::move(__init), std::ref(__f));
+
+using _Up = decay_t>>;
+return fold_left_with_iter_result, _Up>{
+std::move(__result.in), std::move(__result.result)};
+  }
+};
+
+inline namespace __cpo {
+inline constexpr auto fold_left_with_iter = __fold_left_with_iter();
+} // namespace __cpo
+
+struct __fold_left {
+  template  _Sp, class _Tp, 
__indirectly_binary_left_foldable<_Tp, _Ip> _Fp>

EricWF wrote:

@var-const Sounds good! That conversation already happened, there was 
consensus, and now there is no longer. I would be happy to help re-establish 
consensus in a more inclusive forum.

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


[flang] [clang] [mlir] [llvm] [libcxx] [compiler-rt] [libc] [lldb] [openmp] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits


@@ -0,0 +1,25 @@
+// RUN: %clang_hwasan -g %s -o %t && not %run %t 2>&1 | FileCheck %s
+
+// Stack histories currently are not recorded on x86.
+// XFAIL: target=x86_64{{.*}}
+
+__attribute((noinline)) void buggy() {
+  char c[64];
+  char *volatile p = c;
+  p[-2] = 0;
+}
+
+int main() {
+  buggy();
+  // CHECK: WRITE of size 1 at
+  // CHECK: #0 {{.*}} in buggy{{.*}}stack-underflow.c:[[@LINE-6]]
+  // CHECK: Cause: stack tag-mismatch

vitalybuka wrote:

The first one is true, the second one is "Potentially"

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


[flang] [clang] [mlir] [llvm] [libcxx] [compiler-rt] [libc] [lldb] [openmp] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits


@@ -221,29 +221,55 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
   for (LocalInfo  : frame.locals) {
 if (!local.has_frame_offset || !local.has_size || 
!local.has_tag_offset)
   continue;
+if (!(local.name && internal_strlen(local.name)) &&
+!(local.function_name && internal_strlen(local.name)) &&
+!local.decl_file)

vitalybuka wrote:

will check

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


[flang] [clang] [mlir] [llvm] [libcxx] [compiler-rt] [libc] [lldb] [openmp] [hwasan] Classify stack overflow, and use after scope (PR #76133)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[compiler-rt] [flang] [llvm] [libc] [openmp] [clang] [lldb] [mlir] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[compiler-rt] [flang] [llvm] [libc] [openmp] [clang] [lldb] [mlir] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/76132

>From 8c5b5de0d4fda16cfa1c8c4281601b61a9ca774d Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 20 Dec 2023 23:58:01 -0800
Subject: [PATCH 1/4] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 compiler-rt/lib/hwasan/hwasan_report.cpp | 16 +++-
 .../test/hwasan/TestCases/Linux/syscalls.cpp |  2 +-
 .../test/hwasan/TestCases/heap-buffer-overflow.c |  7 ---
 3 files changed, 16 insertions(+), 9 deletions(-)

diff --git a/compiler-rt/lib/hwasan/hwasan_report.cpp 
b/compiler-rt/lib/hwasan/hwasan_report.cpp
index 5e8aa315801bcd..71155c9814c186 100644
--- a/compiler-rt/lib/hwasan/hwasan_report.cpp
+++ b/compiler-rt/lib/hwasan/hwasan_report.cpp
@@ -233,7 +233,7 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
 if (obj_offset >= local.size)
   continue;
 if (!found_local) {
-  Printf("Potentially referenced stack objects:\n");
+  Printf("\nPotentially referenced stack objects:\n");
   found_local = true;
 }
 Printf("  %s in %s %s:%d\n", local.name, local.function_name,
@@ -363,7 +363,7 @@ static void PrintTagsAroundAddr(uptr addr, GetTag get_tag,
   InternalScopedString s;
   addr = MemToShadow(addr);
   s.AppendF(
-  "Memory tags around the buggy address (one tag corresponds to %zd "
+  "\nMemory tags around the buggy address (one tag corresponds to %zd "
   "bytes):\n",
   kShadowAlignment);
   PrintTagInfoAroundAddr(addr, kShadowLines, s,
@@ -648,19 +648,23 @@ void BaseReport::PrintHeapOrGlobalCandidate() const {
   if (candidate.heap.is_allocated) {
 uptr offset;
 const char *whence;
+const char *cause;
 if (candidate.heap.begin <= untagged_addr &&
 untagged_addr < candidate.heap.end) {
   offset = untagged_addr - candidate.heap.begin;
   whence = "inside";
+  cause = "heap-use-after-free";
 } else if (candidate.after) {
   offset = untagged_addr - candidate.heap.end;
   whence = "after";
+  cause = "heap-buffer-overflow";
 } else {
   offset = candidate.heap.begin - untagged_addr;
   whence = "before";
+  cause = "heap-buffer-underflow";
 }
 Printf("%s", d.Error());
-Printf("\nCause: heap-buffer-overflow\n");
+Printf("\nCause: %s\n", cause);
 Printf("%s", d.Default());
 Printf("%s", d.Location());
 Printf("%p is located %zd bytes %s a %zd-byte region [%p,%p)\n",
@@ -803,8 +807,10 @@ void BaseReport::PrintAddressDescription() const {
   }
 
   // Print the remaining threads, as an extra information, 1 line per thread.
-  if (flags()->print_live_threads_info)
+  if (flags()->print_live_threads_info) {
+Printf("\n");
 hwasanThreadList().VisitAllLiveThreads([&](Thread *t) { t->Announce(); });
+  }
 
   if (!num_descriptions_printed)
 // We exhausted our possibilities. Bail out.
@@ -1020,7 +1026,7 @@ void ReportTagMismatch(StackTrace *stack, uptr 
tagged_addr, uptr access_size,
 // See the frame breakdown defined in __hwasan_tag_mismatch (from
 // hwasan_tag_mismatch_{aarch64,riscv64}.S).
 void ReportRegisters(const uptr *frame, uptr pc) {
-  Printf("Registers where the failure occurred (pc %p):\n", pc);
+  Printf("\nRegisters where the failure occurred (pc %p):\n", pc);
 
   // We explicitly print a single line (4 registers/line) each iteration to
   // reduce the amount of logcat error messages printed. Each Printf() will
diff --git a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp 
b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
index 154b6989899352..eee43f458fac10 100644
--- a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
+++ b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
@@ -26,7 +26,7 @@ int main(int argc, char *argv[]) {
 
   __sanitizer_syscall_pre_recvmsg(0, buf - 1, 0);
   // CHECK: HWAddressSanitizer: tag-mismatch on address [[PTR:0x[a-f0-9]+]]
-  // CHECK: Cause: heap-buffer-overflow
+  // CHECK: Cause: heap-buffer-underflow
   // CHECK: [[PTR]] is located 1 bytes before a 1000-byte region
 
   free(buf);
diff --git a/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c 
b/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
index 4e6638be584b0d..c1c7d458b9424f 100644
--- a/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
+++ b/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
@@ -29,7 +29,8 @@ int main(int argc, char **argv) {
   if (size == 100) {
 fprintf(stderr, "is a large allocated heap chunk; size: 1003520 offset: 
%d\n",
 offset);
-fprintf(stderr, "Cause: heap-buffer-overflow\n");
+fprintf(stderr, "Cause: heap-buffer-%s\n",
+offset == -30 ? "underflow" : "overflow");
 

[llvm] [lldb] [mlir] [libc] [compiler-rt] [flang] [clang] [openmp] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 Thread Florian Mayer via cfe-commits

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

Lgtm thanks

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


[llvm] [lldb] [mlir] [libc] [compiler-rt] [flang] [clang] [openmp] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 Thread Vitaly Buka via cfe-commits

https://github.com/vitalybuka updated 
https://github.com/llvm/llvm-project/pull/76132

>From 8c5b5de0d4fda16cfa1c8c4281601b61a9ca774d Mon Sep 17 00:00:00 2001
From: Vitaly Buka 
Date: Wed, 20 Dec 2023 23:58:01 -0800
Subject: [PATCH 1/3] =?UTF-8?q?[=F0=9D=98=80=F0=9D=97=BD=F0=9D=97=BF]=20ch?=
 =?UTF-8?q?anges=20to=20main=20this=20commit=20is=20based=20on?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

Created using spr 1.3.4

[skip ci]
---
 compiler-rt/lib/hwasan/hwasan_report.cpp | 16 +++-
 .../test/hwasan/TestCases/Linux/syscalls.cpp |  2 +-
 .../test/hwasan/TestCases/heap-buffer-overflow.c |  7 ---
 3 files changed, 16 insertions(+), 9 deletions(-)

diff --git a/compiler-rt/lib/hwasan/hwasan_report.cpp 
b/compiler-rt/lib/hwasan/hwasan_report.cpp
index 5e8aa315801bcd..71155c9814c186 100644
--- a/compiler-rt/lib/hwasan/hwasan_report.cpp
+++ b/compiler-rt/lib/hwasan/hwasan_report.cpp
@@ -233,7 +233,7 @@ static void PrintStackAllocations(const 
StackAllocationsRingBuffer *sa,
 if (obj_offset >= local.size)
   continue;
 if (!found_local) {
-  Printf("Potentially referenced stack objects:\n");
+  Printf("\nPotentially referenced stack objects:\n");
   found_local = true;
 }
 Printf("  %s in %s %s:%d\n", local.name, local.function_name,
@@ -363,7 +363,7 @@ static void PrintTagsAroundAddr(uptr addr, GetTag get_tag,
   InternalScopedString s;
   addr = MemToShadow(addr);
   s.AppendF(
-  "Memory tags around the buggy address (one tag corresponds to %zd "
+  "\nMemory tags around the buggy address (one tag corresponds to %zd "
   "bytes):\n",
   kShadowAlignment);
   PrintTagInfoAroundAddr(addr, kShadowLines, s,
@@ -648,19 +648,23 @@ void BaseReport::PrintHeapOrGlobalCandidate() const {
   if (candidate.heap.is_allocated) {
 uptr offset;
 const char *whence;
+const char *cause;
 if (candidate.heap.begin <= untagged_addr &&
 untagged_addr < candidate.heap.end) {
   offset = untagged_addr - candidate.heap.begin;
   whence = "inside";
+  cause = "heap-use-after-free";
 } else if (candidate.after) {
   offset = untagged_addr - candidate.heap.end;
   whence = "after";
+  cause = "heap-buffer-overflow";
 } else {
   offset = candidate.heap.begin - untagged_addr;
   whence = "before";
+  cause = "heap-buffer-underflow";
 }
 Printf("%s", d.Error());
-Printf("\nCause: heap-buffer-overflow\n");
+Printf("\nCause: %s\n", cause);
 Printf("%s", d.Default());
 Printf("%s", d.Location());
 Printf("%p is located %zd bytes %s a %zd-byte region [%p,%p)\n",
@@ -803,8 +807,10 @@ void BaseReport::PrintAddressDescription() const {
   }
 
   // Print the remaining threads, as an extra information, 1 line per thread.
-  if (flags()->print_live_threads_info)
+  if (flags()->print_live_threads_info) {
+Printf("\n");
 hwasanThreadList().VisitAllLiveThreads([&](Thread *t) { t->Announce(); });
+  }
 
   if (!num_descriptions_printed)
 // We exhausted our possibilities. Bail out.
@@ -1020,7 +1026,7 @@ void ReportTagMismatch(StackTrace *stack, uptr 
tagged_addr, uptr access_size,
 // See the frame breakdown defined in __hwasan_tag_mismatch (from
 // hwasan_tag_mismatch_{aarch64,riscv64}.S).
 void ReportRegisters(const uptr *frame, uptr pc) {
-  Printf("Registers where the failure occurred (pc %p):\n", pc);
+  Printf("\nRegisters where the failure occurred (pc %p):\n", pc);
 
   // We explicitly print a single line (4 registers/line) each iteration to
   // reduce the amount of logcat error messages printed. Each Printf() will
diff --git a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp 
b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
index 154b6989899352..eee43f458fac10 100644
--- a/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
+++ b/compiler-rt/test/hwasan/TestCases/Linux/syscalls.cpp
@@ -26,7 +26,7 @@ int main(int argc, char *argv[]) {
 
   __sanitizer_syscall_pre_recvmsg(0, buf - 1, 0);
   // CHECK: HWAddressSanitizer: tag-mismatch on address [[PTR:0x[a-f0-9]+]]
-  // CHECK: Cause: heap-buffer-overflow
+  // CHECK: Cause: heap-buffer-underflow
   // CHECK: [[PTR]] is located 1 bytes before a 1000-byte region
 
   free(buf);
diff --git a/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c 
b/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
index 4e6638be584b0d..c1c7d458b9424f 100644
--- a/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
+++ b/compiler-rt/test/hwasan/TestCases/heap-buffer-overflow.c
@@ -29,7 +29,8 @@ int main(int argc, char **argv) {
   if (size == 100) {
 fprintf(stderr, "is a large allocated heap chunk; size: 1003520 offset: 
%d\n",
 offset);
-fprintf(stderr, "Cause: heap-buffer-overflow\n");
+fprintf(stderr, "Cause: heap-buffer-%s\n",
+offset == -30 ? "underflow" : "overflow");
 

[llvm] [lldb] [mlir] [libc] [compiler-rt] [flang] [clang] [openmp] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 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 9d0e3a77eee290592620cf017c433bd7a751952d 
9e2f17c3a3624b8dbaff499612339210d66ff975 -- 
compiler-rt/test/hwasan/TestCases/strip_path_prefix.c 
compiler-rt/lib/hwasan/hwasan_report.cpp
``





View the diff from clang-format here.


``diff
diff --git a/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c 
b/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
index 39ee7f562f..5f1c7ab663 100644
--- a/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
+++ b/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
@@ -9,7 +9,7 @@
 
 int t;
 
-__attribute__((noinline)) char* buggy() {
+__attribute__((noinline)) char *buggy() {
   char *volatile p;
   char zzz = {};
   char yyy = {};
@@ -18,7 +18,7 @@ __attribute__((noinline)) char* buggy() {
 }
 
 int main() {
-  char* p = buggy();
+  char *p = buggy();
   return *p;
   // CHECK: READ of size 1 at
   // CHECK: #0 {{.*}} in main strip_path_prefix.c:[[@LINE-2]]

``




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


[llvm] [compiler-rt] [lldb] [mlir] [clang] [openmp] [flang] [libc] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 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 9d0e3a77eee290592620cf017c433bd7a751952d 
9e2f17c3a3624b8dbaff499612339210d66ff975 -- 
compiler-rt/test/hwasan/TestCases/strip_path_prefix.c 
compiler-rt/lib/hwasan/hwasan_report.cpp
``





View the diff from clang-format here.


``diff
diff --git a/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c 
b/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
index 39ee7f562f..5f1c7ab663 100644
--- a/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
+++ b/compiler-rt/test/hwasan/TestCases/strip_path_prefix.c
@@ -9,7 +9,7 @@
 
 int t;
 
-__attribute__((noinline)) char* buggy() {
+__attribute__((noinline)) char *buggy() {
   char *volatile p;
   char zzz = {};
   char yyy = {};
@@ -18,7 +18,7 @@ __attribute__((noinline)) char* buggy() {
 }
 
 int main() {
-  char* p = buggy();
+  char *p = buggy();
   return *p;
   // CHECK: READ of size 1 at
   // CHECK: #0 {{.*}} in main strip_path_prefix.c:[[@LINE-2]]

``




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


[llvm] [compiler-rt] [lldb] [mlir] [clang] [openmp] [flang] [libc] [hwasan] Respect strip_path_prefix printing locals (PR #76132)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,29 @@
+.. title:: clang-tidy - bugprone-unused-local-non-trivial-variable
+
+bugprone-unused-local-non-trivial-variable
+==
+
+Warns when a local non trivial variable is unused within a function.
+
+In the following example, `future2` would generate a warning that it is unused.
+
+.. code-block:: c++
+
+   std::future future1;
+   std::future future2;
+   // ...
+   MyObject foo = future1.get();
+   // future2 is not used.
+
+Options
+---
+
+.. option:: IncludeTypeRegex
+
+   Semicolon-separated list of regular expressions matching types of variables 
to check.
+   By default it 'std::.*mutex;std::future'.
+
+.. option:: ExcludeTypeRegex
+
+   A semicolon-separated list of regular expressions matching types that are 
excluded from the
+  'IncludeTypeRegex' matches. By default it is an empty list.

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -168,6 +168,19 @@ New checks
   extracted from an optional-like type and then used to create a new instance
   of the same optional-like type.
 
+- New :doc:`bugprone-unused-local-non-trivial-variable
+  ` check.
+
+  Warns when a local non trivial variable is unused within a function. By

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,29 @@
+.. title:: clang-tidy - bugprone-unused-local-non-trivial-variable
+
+bugprone-unused-local-non-trivial-variable
+==
+
+Warns when a local non trivial variable is unused within a function.
+
+In the following example, `future2` would generate a warning that it is unused.
+
+.. code-block:: c++
+
+   std::future future1;
+   std::future future2;
+   // ...
+   MyObject foo = future1.get();
+   // future2 is not used.
+
+Options
+---
+
+.. option:: IncludeTypeRegex
+
+   Semicolon-separated list of regular expressions matching types of variables 
to check.
+   By default it 'std::.*mutex;std::future'.

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits

https://github.com/rockwotj updated 
https://github.com/llvm/llvm-project/pull/76101

>From 90d92d028833d25c218a9f184b5e1407500c9d01 Mon Sep 17 00:00:00 2001
From: Tyler Rockwood 
Date: Thu, 21 Dec 2023 16:31:12 -0600
Subject: [PATCH] clang-tidy/bugprone: introduce
 unused-local-non-trivial-variable check

Signed-off-by: Tyler Rockwood 
---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../UnusedLocalNonTrivialVariableCheck.cpp| 89 +++
 .../UnusedLocalNonTrivialVariableCheck.h  | 44 +
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 ++
 .../unused-local-non-trivial-variable.rst | 29 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../unused-local-non-trivial-variable.cpp | 79 
 8 files changed, 251 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 7a910037368c83..435cb1e3fbcff3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
 #include "UnsafeFunctionsCheck.h"
+#include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
@@ -235,6 +236,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unique-ptr-array-mismatch");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
+CheckFactories.registerCheck(
+"bugprone-unused-local-non-trivial-variable");
 CheckFactories.registerCheck("bugprone-unused-raii");
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index d443fd8d1452f1..70e7fbc7ec0c14 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
   UnsafeFunctionsCheck.cpp
+  UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
new file mode 100644
index 00..2c61078e1d1cc1
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -0,0 +1,89 @@
+//===--- UnusedLocalNonTrivialVariableCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex = 
"std::.*mutex;std::future";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypeRegex(utils::options::parseStringList(
+  Options.get("IncludeTypeRegex", DefaultIncludeTypeRegex))),
+  ExcludeTypeRegex(utils::options::parseStringList(
+  Options.get("ExcludeTypeRegex", ""))) {}
+
+void UnusedLocalNonTrivialVariableCheck::storeOptions(
+ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "IncludeTypeRegex",
+utils::options::serializeStringList(IncludeTypeRegex));
+  

[clang-tools-extra] [libcxx] [clang] [llvm] [libcxx] adds ranges::fold_left_with_iter and ranges::fold_left (PR #75259)

2023-12-21 Thread via cfe-commits


@@ -0,0 +1,104 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+// template 
+// struct in_value_result;
+
+#include 
+#include 
+#include 
+#include 
+
+#include "MoveOnly.h"
+
+struct A {
+  explicit A(int);
+};
+// no implicit conversion
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result>);
+
+struct B {
+  B(int);
+};
+// implicit conversion
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result>);
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result&>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result&>);
+
+struct C {
+  C(int&);
+};
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result&>);
+
+// has to be convertible via const&
+static_assert(std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+
+// should be move constructible
+static_assert(std::is_move_constructible_v>);
+static_assert(std::is_move_constructible_v>);
+
+// should not copy constructible with move-only type
+static_assert(!std::is_copy_constructible_v>);
+static_assert(!std::is_copy_constructible_v>);
+
+struct NotConvertible {};
+// conversions should not work if there is no conversion
+static_assert(
+!std::is_convertible_v, 
std::ranges::in_value_result>);
+static_assert(
+!std::is_convertible_v, 
std::ranges::in_value_result>);
+
+template 
+struct ConvertibleFrom {
+  constexpr ConvertibleFrom(T c) : content{c} {}
+  T content;
+};
+
+constexpr bool test() {
+  {
+std::ranges::in_value_result res{10, 0.};
+assert(res.in == 10);
+assert(res.value == 0.);
+std::ranges::in_value_result, 
ConvertibleFrom> res2 = res;
+assert(res2.in.content == 10);
+assert(res2.value.content == 0.);
+  }

EricWF wrote:

Can we make clang-format do that for us? 

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


[clang-tools-extra] [libcxx] [clang] [llvm] [libcxx] adds ranges::fold_left_with_iter and ranges::fold_left (PR #75259)

2023-12-21 Thread via cfe-commits


@@ -0,0 +1,104 @@
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+// UNSUPPORTED: c++03, c++11, c++14, c++17, c++20
+
+// template 
+// struct in_value_result;
+
+#include 
+#include 
+#include 
+#include 
+
+#include "MoveOnly.h"
+
+struct A {
+  explicit A(int);
+};
+// no implicit conversion
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result>);
+
+struct B {
+  B(int);
+};
+// implicit conversion
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result>);
+static_assert(std::is_constructible_v, 
std::ranges::in_value_result&>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result>);
+static_assert(
+std::is_constructible_v, const 
std::ranges::in_value_result&>);
+
+struct C {
+  C(int&);
+};
+static_assert(!std::is_constructible_v, 
std::ranges::in_value_result&>);
+
+// has to be convertible via const&
+static_assert(std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+static_assert(
+std::is_convertible_v&&, 
std::ranges::in_value_result>);
+
+// should be move constructible
+static_assert(std::is_move_constructible_v>);
+static_assert(std::is_move_constructible_v>);
+
+// should not copy constructible with move-only type

EricWF wrote:

Attaching to this comment, because the comment about names is attached to the 
same line.

I think the project should document any policies we wish to enforce inside our 
documentation. That way we aren't depending on the visibility of conversations, 
and we have a place to scope our discussions of said policy. Changes to the 
policy can then happen in PR's changing the documentation.  Further, it better 
provides all contributors the ability to weigh in, hopefully at the time, but 
also after the fact.

To keep in with my suggestion, I will create a PR documenting our documenting 
policy to root this discussion under.

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


[libunwind] [clang-tools-extra] [clang] [llvm] [libunwind] Replace process_vm_readv with SYS_rt_sigprocmask (PR #74791)

2023-12-21 Thread Jordan R AW via cfe-commits

ajordanr-google wrote:

I don't have Commit Access (I so rarely actually commit to upstream), and I 
don't think I have yet the "track record of submitting high quality patches" :)

Can someone else merge this once the checks are green?

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


[clang] [llvm] Reapply "InstCombine: Introduce SimplifyDemandedUseFPClass"" (PR #74056)

2023-12-21 Thread Andy Kaylor via cfe-commits

andykaylor wrote:

For those who haven't already seen it, there was a related discussion here: 
https://discourse.llvm.org/t/should-isnan-be-optimized-out-in-fast-math-mode/5

I think that discussion could be fairly summarized by saying that no consensus 
was reached, and many people wished they had never entered the discussion.

Reviewing this discussion led me to do some experiments and I find that in C++ 
mode, using -ffinite-math-only cannot be mixed well with "#pragma 
float_control(precise, on)" or various methods for disabling optimizations 
altogether, because templates from the header files are instantiated outside 
the pragmas. That may be defensible behavior, but I suspect it would come as a 
surprise to people who think they can control fast-math behavior locally.

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


[libunwind] [clang-tools-extra] [clang] [llvm] [libunwind] Replace process_vm_readv with SYS_rt_sigprocmask (PR #74791)

2023-12-21 Thread Jordan R AW via cfe-commits


@@ -2974,6 +2966,37 @@ bool UnwindCursor::getFunctionName(char *buf, 
size_t bufLen,
  buf, bufLen, offset);
 }
 
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
+template 
+bool UnwindCursor::isReadableAddr(const pint_t addr) const {
+  // This code is heavily based on Abseil's 'address_is_readable.cc',
+  // which is Copyright Abseil Authors (2017).
+
+  const auto sigsetAddr = reinterpret_cast(addr);
+  // We have to check that addr is nullptr because sigprocmask allows that
+  // as an argument without failure.
+  if (!sigsetAddr)
+return false;
+  // We MUST use a raw syscall here, as wrappers may try to access
+  // sigsetAddr which may cause a SIGSEGV. A raw syscall however is
+  // safe. Additionally, we need to pass the kernel_sigset_size, which is
+  // different from libc sizeof(sigset_t). For the majority of architectures,
+  // it's 64 bits (_NSIG), and libc NSIG is _NSIG + 1.
+  const auto kernelSigsetSize = NSIG / 8;
+  const int Result = syscall(SYS_rt_sigprocmask, /*how=*/~0, sigsetAddr,
+ nullptr, kernelSigsetSize);
+  (void)Result;
+  // Because our "how" is invalid, this syscall should always fail, and our
+  // errno should always be EINVAL or an EFAULT. EFAULT is not guaranteed
+  // by the POSIX standard. Additionally, this relies on the Linux kernel
+  // to check copy_from_user before checking if the "how" argument is
+  // invalid.
+  assert(Result == -1);
+  assert(errno == EFAULT || errno == EINVAL);
+  return errno != EFAULT;

ajordanr-google wrote:

We should probably save and restore, as we do this above in 
`getInfoFromTBTable`. Good point. Done.

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


[clang] [libunwind] [llvm] [clang-tools-extra] [libunwind] Replace process_vm_readv with SYS_rt_sigprocmask (PR #74791)

2023-12-21 Thread Jordan R AW via cfe-commits


@@ -2974,6 +2966,37 @@ bool UnwindCursor::getFunctionName(char *buf, 
size_t bufLen,
  buf, bufLen, offset);
 }
 
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
+template 
+bool UnwindCursor::isReadableAddr(const pint_t addr) const {
+  // This code is heavily based on Abseil's 'address_is_readable.cc',
+  // which is Copyright Abseil Authors (2017).
+
+  const auto sigsetAddr = reinterpret_cast(addr);
+  // We have to check that addr is nullptr because sigprocmask allows that
+  // as an argument without failure.
+  if (!sigsetAddr)
+return false;
+  // We MUST use a raw syscall here, as wrappers may try to access
+  // sigsetAddr which may cause a SIGSEGV. A raw syscall however is
+  // safe. Additionally, we need to pass the kernel_sigset_size, which is
+  // different from libc sizeof(sigset_t). For the majority of architectures,
+  // it's 64 bits (_NSIG), and libc NSIG is _NSIG + 1.
+  const auto kernelSigsetSize = NSIG / 8;
+  const int Result = syscall(SYS_rt_sigprocmask, /*how=*/~0, sigsetAddr,
+ nullptr, kernelSigsetSize);
+  (void)Result;
+  // Because our "how" is invalid, this syscall should always fail, and our
+  // errno should always be EINVAL or an EFAULT. EFAULT is not guaranteed
+  // by the POSIX standard. Additionally, this relies on the Linux kernel

ajordanr-google wrote:

Done.

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


[llvm] [libunwind] [clang] [clang-tools-extra] [libunwind] Replace process_vm_readv with SYS_rt_sigprocmask (PR #74791)

2023-12-21 Thread Jordan R AW via cfe-commits


@@ -2974,6 +2966,37 @@ bool UnwindCursor::getFunctionName(char *buf, 
size_t bufLen,
  buf, bufLen, offset);
 }
 
+#if defined(_LIBUNWIND_CHECK_LINUX_SIGRETURN)
+template 
+bool UnwindCursor::isReadableAddr(const pint_t addr) const {
+  // This code is heavily based on Abseil's 'address_is_readable.cc',
+  // which is Copyright Abseil Authors (2017).

ajordanr-google wrote:

Done

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


[libunwind] [clang-tools-extra] [clang] [llvm] [libunwind] Replace process_vm_readv with SYS_rt_sigprocmask (PR #74791)

2023-12-21 Thread Jordan R AW via cfe-commits

https://github.com/ajordanr-google updated 
https://github.com/llvm/llvm-project/pull/74791

>From 1f4df1b82970c95684eed93c8f6bcaa6d6507b88 Mon Sep 17 00:00:00 2001
From: Jordan R Abrahams-Whitehead 
Date: Fri, 8 Dec 2023 00:09:59 +
Subject: [PATCH 01/13] [libunwind] Replace process_vm_readv with pipe

process_vm_readv is generally considered dangerous from a syscall
perspective, and is frequently blanket banned in seccomp filters such as
those in Chromium and ChromiumOS. We can get the same behaviour during
the invalid PC address case with pipes and write/read.

Testing to ensure that process_vm_readv does not appear, I ran the
output of check-unwind on an ARM64 device under strace. Previously,
bad_unwind_info in particular would use process_vm_readv, but with this
commit, it now uses pipe2:

```
strace test/Output/bad_unwind_info.pass.cpp.dir/t.tmp.exe \
  |& grep process_vm_readv
strace test/Output/bad_unwind_info.pass.cpp.dir/t.tmp.exe \
  |& grep pipe2
```
---
 libunwind/src/UnwindCursor.hpp | 50 --
 1 file changed, 29 insertions(+), 21 deletions(-)

diff --git a/libunwind/src/UnwindCursor.hpp b/libunwind/src/UnwindCursor.hpp
index 647a5a9c9d92d9..5e4e376220daa0 100644
--- a/libunwind/src/UnwindCursor.hpp
+++ b/libunwind/src/UnwindCursor.hpp
@@ -33,6 +33,7 @@
 #if defined(_LIBUNWIND_TARGET_LINUX) &&
\
 (defined(_LIBUNWIND_TARGET_AARCH64) || defined(_LIBUNWIND_TARGET_RISCV) || 
\
  defined(_LIBUNWIND_TARGET_S390X))
+#include 
 #include 
 #include 
 #include 
@@ -2700,19 +2701,18 @@ bool UnwindCursor::setInfoForSigReturn(Registers_arm64 &) {
   // [1] 
https://github.com/torvalds/linux/blob/master/arch/arm64/kernel/vdso/sigreturn.S
   const pint_t pc = static_cast(this->getReg(UNW_REG_IP));
   // The PC might contain an invalid address if the unwind info is bad, so
-  // directly accessing it could cause a segfault. Use process_vm_readv to read
-  // the memory safely instead. process_vm_readv was added in Linux 3.2, and
-  // AArch64 supported was added in Linux 3.7, so the syscall is guaranteed to
-  // be present. Unfortunately, there are Linux AArch64 environments where the
-  // libc wrapper for the syscall might not be present (e.g. Android 5), so 
call
-  // the syscall directly instead.
+  // directly accessing it could cause a segfault. Use pipe/write/read to read
+  // the memory safely instead.
+  int pipefd[2];
+  if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK) == -1)
+return false;
   uint32_t instructions[2];
-  struct iovec local_iov = {, sizeof instructions};
-  struct iovec remote_iov = {reinterpret_cast(pc), sizeof 
instructions};
-  long bytesRead =
-  syscall(SYS_process_vm_readv, getpid(), _iov, 1, _iov, 1, 
0);
+  const auto bufferSize = sizeof instructions;
+  if (write(pipefd[1], reinterpret_cast(pc), bufferSize) != bufferSize)
+return false;
+  const auto bytesRead = read(pipefd[0], instructions, bufferSize);
   // Look for instructions: mov x8, #0x8b; svc #0x0
-  if (bytesRead != sizeof instructions || instructions[0] != 0xd2801168 ||
+  if (bytesRead != bufferSize || instructions[0] != 0xd2801168 ||
   instructions[1] != 0xd401)
 return false;
 
@@ -2762,17 +2762,20 @@ int UnwindCursor::stepThroughSigReturn(Registers_arm64 &) {
 template 
 bool UnwindCursor::setInfoForSigReturn(Registers_riscv &) {
   const pint_t pc = static_cast(getReg(UNW_REG_IP));
+  int pipefd[2];
+  if (pipe2(pipefd, O_CLOEXEC | O_NONBLOCK) == -1)
+return false;
   uint32_t instructions[2];
-  struct iovec local_iov = {, sizeof instructions};
-  struct iovec remote_iov = {reinterpret_cast(pc), sizeof 
instructions};
-  long bytesRead =
-  syscall(SYS_process_vm_readv, getpid(), _iov, 1, _iov, 1, 
0);
+  const auto bufferSize = sizeof instructions;
+  if (write(pipefd[1], reinterpret_cast(pc), bufferSize) != bufferSize)
+return false;
+  const auto bytesRead = read(pipefd[0], instructions, bufferSize);
   // Look for the two instructions used in the sigreturn trampoline
   // __vdso_rt_sigreturn:
   //
   // 0x08b00893 li a7,0x8b
   // 0x0073 ecall
-  if (bytesRead != sizeof instructions || instructions[0] != 0x08b00893 ||
+  if (bytesRead != bufferSize || instructions[0] != 0x08b00893 ||
   instructions[1] != 0x0073)
 return false;
 
@@ -2822,13 +2825,18 @@ bool UnwindCursor::setInfoForSigReturn(Registers_s390x &) {
   // onto the stack.
   const pint_t pc = static_cast(this->getReg(UNW_REG_IP));
   // The PC might contain an invalid address if the unwind info is bad, so
-  // directly accessing it could cause a segfault. Use process_vm_readv to
+  // directly accessing it could cause a segfault. Use pipe/write/read to
   // read the memory safely instead.
   uint16_t inst;
-  struct iovec local_iov = {, sizeof inst};
-  struct iovec remote_iov = {reinterpret_cast(pc), sizeof inst};
-  long bytesRead = process_vm_readv(getpid(), _iov, 1, _iov, 1, 
0);
-  if (bytesRead == 

[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread via cfe-commits


@@ -0,0 +1,29 @@
+.. title:: clang-tidy - bugprone-unused-local-non-trivial-variable
+
+bugprone-unused-local-non-trivial-variable
+==
+
+Warns when a local non trivial variable is unused within a function.
+
+In the following example, `future2` would generate a warning that it is unused.
+
+.. code-block:: c++
+
+   std::future future1;
+   std::future future2;
+   // ...
+   MyObject foo = future1.get();
+   // future2 is not used.
+
+Options
+---
+
+.. option:: IncludeTypeRegex
+
+   Semicolon-separated list of regular expressions matching types of variables 
to check.
+   By default it 'std::.*mutex;std::future'.
+
+.. option:: ExcludeTypeRegex
+
+   A semicolon-separated list of regular expressions matching types that are 
excluded from the
+  'IncludeTypeRegex' matches. By default it is an empty list.

EugeneZelenko wrote:

Ditto.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread via cfe-commits


@@ -168,6 +168,19 @@ New checks
   extracted from an optional-like type and then used to create a new instance
   of the same optional-like type.
 
+- New :doc:`bugprone-unused-local-non-trivial-variable
+  ` check.
+
+  Warns when a local non trivial variable is unused within a function. By

EugeneZelenko wrote:

Release Notes should contain single statement.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread via cfe-commits


@@ -0,0 +1,29 @@
+.. title:: clang-tidy - bugprone-unused-local-non-trivial-variable
+
+bugprone-unused-local-non-trivial-variable
+==
+
+Warns when a local non trivial variable is unused within a function.
+
+In the following example, `future2` would generate a warning that it is unused.
+
+.. code-block:: c++
+
+   std::future future1;
+   std::future future2;
+   // ...
+   MyObject foo = future1.get();
+   // future2 is not used.
+
+Options
+---
+
+.. option:: IncludeTypeRegex
+
+   Semicolon-separated list of regular expressions matching types of variables 
to check.
+   By default it 'std::.*mutex;std::future'.

EugeneZelenko wrote:

Please use single back-ticks for option names and values.

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


[clang] [Sema] Provide `-fno-/-fvisibility-global-new-delete` option (PR #75364)

2023-12-21 Thread via cfe-commits

bd1976bris wrote:

I have updated the patch to use `-f[no-]forced-global-new-delete-visibility` as 
suggested.

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


[clang] [Sema] Provide `-fno-/-fvisibility-global-new-delete` option (PR #75364)

2023-12-21 Thread via cfe-commits

https://github.com/bd1976bris updated 
https://github.com/llvm/llvm-project/pull/75364

>From 97efed8c73aed4fdca5510013c844e84953ec256 Mon Sep 17 00:00:00 2001
From: Ben Dunbobbin 
Date: Tue, 12 Dec 2023 08:07:17 +
Subject: [PATCH 1/3] [Sema] Provide `-fno-/-fvisibility-global-new-delete`
 option

By default the implicitly declared replaceable global new and delete
operators are given a `default` visibility attribute. Previous work,
see: https://reviews.llvm.org/D53787, added
`-fvisibility-global-new-delete-hidden` to change this to a `hidden`
visibility attribute.

This change adds: `-fno/-fvisibility-global-new-delete` which controls
whether or not to add a visibility attribute to the implicit
declarations for these functions. Without the attribute the replaceable
global new and delete operators behave normally (like other functions)
with respect to visibility attributes, pragmas and options.

The command line help for these options is rendered as:

  -fvisibility-global-new-delete
  Add a visibility attribute to the implicit
  global C++ operator new and delete declarations

  -fno-visibility-global-new-delete
  Do not add a visibility attribute to the implicit
  global C++ operator new and delete declarations

The motivation is to allow users to specify
`-fno-visibility-global-new-delete` when they intend to replace these
functions either for a single linkage unit or set of linkage units.

`-fno-visibility-global-new-delete` can be applied globally to the
compilations in a build where `-fvisibility-global-new-delete-hidden`
cannot; as it conflicts with a common pattern where these functions are
dynamically imported.

`-fno-visibility-global-new-delete` makes sense as the default for PS5.
Users that want the normal toolchain behaviour will be able to supply
`-fvisibility-global-new-delete`.
---
 clang/include/clang/Basic/LangOptions.def |  3 +-
 clang/include/clang/Driver/Options.td |  6 +++
 clang/lib/Driver/ToolChains/Clang.cpp | 12 +
 clang/lib/Driver/ToolChains/PS4CPU.cpp|  6 +++
 clang/lib/Sema/SemaExprCXX.cpp|  9 ++--
 .../visibility-global-new-delete.cpp  | 13 +
 .../Driver/visibility-global-new-delete.cl| 47 +++
 7 files changed, 91 insertions(+), 5 deletions(-)
 create mode 100644 clang/test/CodeGenCXX/visibility-global-new-delete.cpp
 create mode 100644 clang/test/Driver/visibility-global-new-delete.cl

diff --git a/clang/include/clang/Basic/LangOptions.def 
b/clang/include/clang/Basic/LangOptions.def
index c3d5399905a3fd..1471fc11e11663 100644
--- a/clang/include/clang/Basic/LangOptions.def
+++ b/clang/include/clang/Basic/LangOptions.def
@@ -306,7 +306,8 @@ BENIGN_LANGOPT(IgnoreXCOFFVisibility, 1, 0, "All the 
visibility attributes that
 BENIGN_LANGOPT(VisibilityInlinesHiddenStaticLocalVar, 1, 0,
"hidden visibility for static local variables in inline C++ "
"methods when -fvisibility-inlines hidden is enabled")
-LANGOPT(GlobalAllocationFunctionVisibilityHidden , 1, 0, "hidden visibility 
for global operator new and delete declaration")
+LANGOPT(GlobalAllocationFunctionVisibility, 1, 1, "add a visibility attribute 
to the implicit global operator new and delete declarations")
+LANGOPT(GlobalAllocationFunctionVisibilityHidden, 1, 0, "hidden visibility for 
global operator new and delete declarations")
 LANGOPT(NewInfallible , 1, 0, "Treats throwing global C++ operator new as 
always returning valid memory (annotates with __attribute__((returns_nonnull)) 
and throw()). This is detectable in source.")
 BENIGN_LANGOPT(ParseUnknownAnytype, 1, 0, "__unknown_anytype")
 BENIGN_LANGOPT(DebuggerSupport , 1, 0, "debugger support")
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index db2190318c931a..a9f43b18df6fbf 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -3863,6 +3863,12 @@ defm visibility_inlines_hidden_static_local_var : 
BoolFOption<"visibility-inline
 def fvisibility_ms_compat : Flag<["-"], "fvisibility-ms-compat">, 
Group,
   HelpText<"Give global types 'default' visibility and global functions and "
"variables 'hidden' visibility by default">;
+defm visibility_global_new_delete : BoolFOption<"visibility-global-new-delete",
+  LangOpts<"GlobalAllocationFunctionVisibility">, DefaultTrue,
+  PosFlag,
+  NegFlag,
+  BothFlags<[], [ClangOption, CC1Option],
+  " a visibility attribute to the implicit global C++ operator new and 
delete declarations">>;
 def fvisibility_global_new_delete_hidden : Flag<["-"], 
"fvisibility-global-new-delete-hidden">, Group,
   HelpText<"Give global C++ operator new and delete declarations hidden 
visibility">,
   Visibility<[ClangOption, CC1Option]>,
diff --git a/clang/lib/Driver/ToolChains/Clang.cpp 
b/clang/lib/Driver/ToolChains/Clang.cpp

[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,28 @@
+.. title:: clang-tidy - misc-must-use
+
+misc-must-use
+=
+
+Allow strictly enforcing that variables are used for specific classes,
+even with they would not be normally warned using `-Wunused-variable` due 

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,48 @@
+// RUN: %check_clang_tidy %s misc-must-use %t -- \
+// RUN:   -config="{CheckOptions: [{key: 'misc-must-use.Types', value: 
'::async::Future'}]}"

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,40 @@
+//===--- MustUseCheck.h - clang-tidy *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MUSTUSECHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MUSTUSECHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::misc {
+
+/// Warns when not using a variable of a specific type within a function. This
+/// enforces a stronger check than clang's unused-variable warnings, as in C++
+/// this warning is not fired if the class has a custom destructor, or in
+/// templates. This check allows re-enabling unused variable warnings in all
+/// situations for specific classes.
+///
+/// The check supports this option:
+///   - 'Types': a semicolon-separated list of types to ensure must be used.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/misc/must-use.html
+class MustUseCheck : public ClangTidyCheck {
+public:
+  MustUseCheck(StringRef Name, ClangTidyContext *Context);
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
+

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,48 @@
+// RUN: %check_clang_tidy %s misc-must-use %t -- \
+// RUN:   -config="{CheckOptions: [{key: 'misc-must-use.Types', value: 
'::async::Future'}]}"
+
+namespace async {
+template
+class Future {
+public:
+T get() {
+return Pending;
+}
+private:
+T Pending;
+};
+
+
+} // namespace async
+
+// Warning is still emitted if there are type aliases.
+namespace a {
+template
+using Future = async::Future;
+} // namespace a
+
+void releaseUnits();
+struct Units {
+  ~Units() {
+releaseUnits();
+  }
+};
+a::Future acquireUnits();
+
+template
+T qux(T Generic) {
+async::Future PendingA = acquireUnits();
+auto PendingB = acquireUnits();
+// CHECK-MESSAGES: :[[@LINE-1]]:10: warning: variable 'PendingB' must be 
used [misc-must-use]
+PendingA.get();
+return Generic;
+}
+
+int bar(int Num) {
+a::Future PendingA = acquireUnits();
+a::Future PendingB = acquireUnits(); // not used at all, unused 
variable not fired because of destructor side effect
+// CHECK-MESSAGES: :[[@LINE-1]]:22: warning: variable 'PendingB' must be 
used [misc-must-use]
+auto Num2 = PendingA.get();
+auto Num3 = qux(Num);
+return Num * Num3;
+}

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,28 @@
+.. title:: clang-tidy - misc-must-use
+
+misc-must-use
+=
+
+Allow strictly enforcing that variables are used for specific classes,
+even with they would not be normally warned using `-Wunused-variable` due 
+templates or custom destructors.
+
+In the following example, `future2` normally would not trigger any unused 
variable checks,
+but using `{key: "misc-must-use.Types", value: "std::future"}` would cause 
`future2` to have

rockwotj wrote:

Thanks TIL, fixed.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,49 @@
+//===--- MustUseCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MustUseCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+
+namespace {
+AST_MATCHER(VarDecl, isLocalVar) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+} // namespace
+
+MustUseCheck::MustUseCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Types(utils::options::parseStringList(Options.get("Types", ""))) {}
+
+void MustUseCheck::registerMatchers(MatchFinder *Finder) {
+  if (Types.empty()) {
+return;
+  }
+  Finder->addMatcher(
+  varDecl(isLocalVar(), unless(isReferenced()),
+  hasType(hasUnqualifiedDesugaredType(recordType(hasDeclaration(
+  recordDecl(matchers::matchesAnyListedName(Types)))
+  .bind("var"),
+  this);
+}
+
+void MustUseCheck::check(const MatchFinder::MatchResult ) {
+  const auto *MatchedDecl = Result.Nodes.getNodeAs("var");
+  diag(MatchedDecl->getLocation(), "variable %0 must be used") << MatchedDecl;

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,40 @@
+//===--- MustUseCheck.h - clang-tidy *- C++ 
-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MUSTUSECHECK_H
+#define LLVM_CLANG_TOOLS_EXTRA_CLANG_TIDY_MISC_MUSTUSECHECK_H
+
+#include "../ClangTidyCheck.h"
+
+namespace clang::tidy::misc {
+
+/// Warns when not using a variable of a specific type within a function. This
+/// enforces a stronger check than clang's unused-variable warnings, as in C++
+/// this warning is not fired if the class has a custom destructor, or in
+/// templates. This check allows re-enabling unused variable warnings in all
+/// situations for specific classes.
+///
+/// The check supports this option:
+///   - 'Types': a semicolon-separated list of types to ensure must be used.
+///
+/// For the user-facing documentation see:
+/// http://clang.llvm.org/extra/clang-tidy/checks/misc/must-use.html
+class MustUseCheck : public ClangTidyCheck {
+public:
+  MustUseCheck(StringRef Name, ClangTidyContext *Context);
+  void registerMatchers(ast_matchers::MatchFinder *Finder) override;
+  void check(const ast_matchers::MatchFinder::MatchResult ) override;
+  void storeOptions(ClangTidyOptions::OptionMap ) override;
+

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -0,0 +1,49 @@
+//===--- MustUseCheck.cpp - clang-tidy 
===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "MustUseCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::misc {
+
+namespace {
+AST_MATCHER(VarDecl, isLocalVar) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+} // namespace
+
+MustUseCheck::MustUseCheck(StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  Types(utils::options::parseStringList(Options.get("Types", ""))) {}
+
+void MustUseCheck::registerMatchers(MatchFinder *Finder) {
+  if (Types.empty()) {

rockwotj wrote:

Done.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -54,6 +55,7 @@ class MiscModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "misc-misleading-identifier");
 CheckFactories.registerCheck("misc-misplaced-const");
+CheckFactories.registerCheck("misc-must-use");

rockwotj wrote:

SG added most of these checks, let me know if you think I should add any.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits

https://github.com/rockwotj updated 
https://github.com/llvm/llvm-project/pull/76101

>From 5afeaab9f148b10d951e37fd27cb32687f310a9c Mon Sep 17 00:00:00 2001
From: Tyler Rockwood 
Date: Thu, 21 Dec 2023 16:31:12 -0600
Subject: [PATCH] clang-tidy/bugprone: introduce
 unused-local-non-trivial-variable check

Signed-off-by: Tyler Rockwood 
---
 .../bugprone/BugproneTidyModule.cpp   |  3 +
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../UnusedLocalNonTrivialVariableCheck.cpp| 89 +++
 .../UnusedLocalNonTrivialVariableCheck.h  | 44 +
 clang-tools-extra/docs/ReleaseNotes.rst   | 13 +++
 .../unused-local-non-trivial-variable.rst | 29 ++
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../unused-local-non-trivial-variable.cpp | 79 
 8 files changed, 259 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-local-non-trivial-variable.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-local-non-trivial-variable.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 7a910037368c83..435cb1e3fbcff3 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -83,6 +83,7 @@
 #include "UnhandledSelfAssignmentCheck.h"
 #include "UniquePtrArrayMismatchCheck.h"
 #include "UnsafeFunctionsCheck.h"
+#include "UnusedLocalNonTrivialVariableCheck.h"
 #include "UnusedRaiiCheck.h"
 #include "UnusedReturnValueCheck.h"
 #include "UseAfterMoveCheck.h"
@@ -235,6 +236,8 @@ class BugproneModule : public ClangTidyModule {
 "bugprone-unique-ptr-array-mismatch");
 CheckFactories.registerCheck(
 "bugprone-unsafe-functions");
+CheckFactories.registerCheck(
+"bugprone-unused-local-non-trivial-variable");
 CheckFactories.registerCheck("bugprone-unused-raii");
 CheckFactories.registerCheck(
 "bugprone-unused-return-value");
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index d443fd8d1452f1..70e7fbc7ec0c14 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -79,6 +79,7 @@ add_clang_library(clangTidyBugproneModule
   UnhandledSelfAssignmentCheck.cpp
   UniquePtrArrayMismatchCheck.cpp
   UnsafeFunctionsCheck.cpp
+  UnusedLocalNonTrivialVariableCheck.cpp
   UnusedRaiiCheck.cpp
   UnusedReturnValueCheck.cpp
   UseAfterMoveCheck.cpp
diff --git 
a/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
new file mode 100644
index 00..2c61078e1d1cc1
--- /dev/null
+++ 
b/clang-tools-extra/clang-tidy/bugprone/UnusedLocalNonTrivialVariableCheck.cpp
@@ -0,0 +1,89 @@
+//===--- UnusedLocalNonTrivialVariableCheck.cpp - clang-tidy 
--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "UnusedLocalNonTrivialVariableCheck.h"
+#include "../utils/Matchers.h"
+#include "../utils/OptionsUtils.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ASTTypeTraits.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+
+using namespace clang::ast_matchers;
+using namespace clang::tidy::matchers;
+
+namespace clang::tidy::bugprone {
+
+namespace {
+static constexpr StringRef DefaultIncludeTypeRegex = 
"std::.*mutex;std::future";
+
+AST_MATCHER(VarDecl, isLocalVarDecl) { return Node.isLocalVarDecl(); }
+AST_MATCHER(VarDecl, isReferenced) { return Node.isReferenced(); }
+AST_MATCHER(Type, isReferenceType) { return Node.isReferenceType(); }
+} // namespace
+
+UnusedLocalNonTrivialVariableCheck::UnusedLocalNonTrivialVariableCheck(
+StringRef Name, ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeTypeRegex(utils::options::parseStringList(
+  Options.get("IncludeTypeRegex", DefaultIncludeTypeRegex))),
+  ExcludeTypeRegex(utils::options::parseStringList(
+  Options.get("ExcludeTypeRegex", ""))) {}
+
+void UnusedLocalNonTrivialVariableCheck::storeOptions(
+ClangTidyOptions::OptionMap ) {
+  Options.store(Opts, "IncludeTypeRegex",
+utils::options::serializeStringList(IncludeTypeRegex));
+  

[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Piotr Zegar via cfe-commits


@@ -54,6 +55,7 @@ class MiscModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "misc-misleading-identifier");
 CheckFactories.registerCheck("misc-misplaced-const");
+CheckFactories.registerCheck("misc-must-use");

PiotrZSL wrote:

I think isReferenced is newer, so stick to it. Fell free to merge those, check 
that i pointed out is old, so basicly the main thing that is missing in yuors 
is a validation of trivial type and support for inclusion/exclusion matchers.
and few tests, so just start with that. rename check and we go from this.

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


[clang] [Clang][Sema] Fix Wswitch-default bad warning in template (PR #76007)

2023-12-21 Thread Aaron Puchert via cfe-commits

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


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


[clang] [clang][CodeGen] Emit atomic IR in place of optimized libcalls. (PR #73176)

2023-12-21 Thread Eli Friedman via cfe-commits

efriedma-quic wrote:

When I said "inconsistencies", I just meant the way the responsibility for 
lowering atomics is split between LLVM and clang; I didn't mean anything was 
actually broken.

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


[clang] [compiler-rt] [hwasan] Separate sections in report (PR #76130)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[clang] [compiler-rt] [hwasan] Separate sections in report (PR #76130)

2023-12-21 Thread Florian Mayer via cfe-commits

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


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


[clang] [libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

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


[clang] [WIP][libc++] Add builtin to clear padding bytes (prework for P0528R3) (PR #75371)

2023-12-21 Thread via cfe-commits

https://github.com/huixie90 updated 
https://github.com/llvm/llvm-project/pull/75371

>From b7b97148c54dda550fcfb024236c32a6bdca16fd Mon Sep 17 00:00:00 2001
From: zoecarver 
Date: Sat, 2 Dec 2023 20:00:30 +
Subject: [PATCH 1/3] [Builtin] Add __builtin_zero_non_value_bits.

Adds `__builtin_zero_non_value_bits` to zero all padding bits of a struct. This 
builtin should match the behavior of those in NVCC and GCC (and MSVC?). There 
are some tests in this patch but hopefully we'll also get tests from other 
compilers (so all builtins can be as similar as possible).

I'm planning to add support for unions, bitfields (both as members and members 
of sub-objects), and booleans as follow up patches.

Differential Revision: https://reviews.llvm.org/D87974
---
 clang/include/clang/Basic/Builtins.def|   1 +
 clang/lib/CodeGen/CGBuiltin.cpp   |  96 +++
 clang/lib/Sema/SemaChecking.cpp   |  20 ++
 .../builtin-zero-non-value-bits-codegen.cpp   | 112 
 .../builtin-zero-non-value-bits.cpp   | 249 ++
 .../SemaCXX/builtin-zero-non-value-bits.cpp   |  15 ++
 6 files changed, 493 insertions(+)
 create mode 100644 
clang/test/CodeGenCXX/builtin-zero-non-value-bits-codegen.cpp
 create mode 100644 clang/test/CodeGenCXX/builtin-zero-non-value-bits.cpp
 create mode 100644 clang/test/SemaCXX/builtin-zero-non-value-bits.cpp

diff --git a/clang/include/clang/Basic/Builtins.def 
b/clang/include/clang/Basic/Builtins.def
index ec39e926889b93..ba944a6f04fdc0 100644
--- a/clang/include/clang/Basic/Builtins.def
+++ b/clang/include/clang/Basic/Builtins.def
@@ -633,6 +633,7 @@ BUILTIN(__builtin_vsscanf, "icC*RcC*Ra", "FS:1:")
 BUILTIN(__builtin_thread_pointer, "v*", "nc")
 BUILTIN(__builtin_launder, "v*v*", "ntE")
 LANGBUILTIN(__builtin_is_constant_evaluated, "b", "nE", CXX_LANG)
+LANGBUILTIN(__builtin_zero_non_value_bits, "v.", "n", CXX_LANG)
 
 // GCC exception builtins
 BUILTIN(__builtin_eh_return, "vzv*", "r") // FIXME: Takes intptr_t, not size_t!
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 65d9862621061d..34b272f9bddbc9 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2456,6 +2456,95 @@ static RValue 
EmitHipStdParUnsupportedBuiltin(CodeGenFunction *CGF,
   return RValue::get(CGF->Builder.CreateCall(UBF, Args));
 }
 
+static void RecursivelyZeroNonValueBits(CodeGenFunction , Value *Ptr,
+QualType Ty) {
+  auto *I8Ptr = CGF.Builder.CreateBitCast(Ptr, CGF.Int8PtrTy);
+  auto *Zero = ConstantInt::get(CGF.Int8Ty, 0);
+  auto WriteZeroAtOffset = [&](size_t Offset) {
+auto Index = ConstantInt::get(CGF.IntTy, Offset);
+auto Element = CGF.Builder.CreateGEP(I8Ptr, Index);
+CGF.Builder.CreateAlignedStore(
+Zero, Element,
+CharUnits::One().alignmentAtOffset(CharUnits::fromQuantity(Offset)));
+  };
+  auto GetStructLayout = [](llvm::Type *Ty) {
+auto ST = cast(Ty);
+return CGF.CGM.getModule().getDataLayout().getStructLayout(ST);
+  };
+
+  auto ST = cast(Ptr->getType()->getPointerElementType());
+  auto SL = GetStructLayout(ST);
+  auto R = cast(Ty->getAsRecordDecl());
+  const ASTRecordLayout  = CGF.getContext().getASTRecordLayout(R);
+  size_t RunningOffset = 0;
+  for (auto Base : R->bases()) {
+// Zero padding between base elements.
+auto BaseRecord = cast(Base.getType()->getAsRecordDecl());
+auto Offset = static_cast(
+ASTLayout.getBaseClassOffset(BaseRecord).getQuantity());
+for (; RunningOffset < Offset; ++RunningOffset) {
+  WriteZeroAtOffset(RunningOffset);
+}
+// Recursively zero out base classes.
+auto Index = SL->getElementContainingOffset(Offset);
+auto BaseElement = CGF.Builder.CreateStructGEP(Ptr, Index);
+RecursivelyZeroNonValueBits(CGF, BaseElement, Base.getType());
+// Use the LLVM StructType data layout so we pick up on packed types.
+auto SL = GetStructLayout(ST->getElementType(Index));
+auto Size = SL->getSizeInBytes();
+RunningOffset = Offset + Size;
+  }
+
+  size_t NumFields = std::distance(R->field_begin(), R->field_end());
+  auto CurrentField = R->field_begin();
+  for (size_t I = 0; I < NumFields; ++I, ++CurrentField) {
+// Size needs to be in bytes so we can compare it later.
+auto Offset = ASTLayout.getFieldOffset(I) / 8;
+for (; RunningOffset < Offset; ++RunningOffset) {
+  WriteZeroAtOffset(RunningOffset);
+}
+
+auto Index = SL->getElementContainingOffset(Offset);
+// If this field is an object, it may have non-zero padding.
+if (CurrentField->getType()->isRecordType()) {
+  auto Element = CGF.Builder.CreateStructGEP(Ptr, Index);
+  RecursivelyZeroNonValueBits(CGF, Element, CurrentField->getType());
+}
+
+// TODO: warn if non-constant array type.
+if (isa(CurrentField->getType()) &&
+CurrentField->getType()
+->getArrayElementTypeNoTypeQual()
+

[clang] [compiler-rt] [hwasan] Separate sections in report (PR #76130)

2023-12-21 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

> LGTM. Could you explain in the description why we are doing this?

done

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


[clang] [compiler-rt] [hwasan] Separate sections in report (PR #76130)

2023-12-21 Thread Vitaly Buka via cfe-commits

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -54,6 +55,7 @@ class MiscModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "misc-misleading-identifier");
 CheckFactories.registerCheck("misc-misplaced-const");
+CheckFactories.registerCheck("misc-must-use");

rockwotj wrote:

Is there a difference between isReferenced versus the following:

```
decl().bind("var"), 
hasAncestor(functionDecl(unless(hasDescendant(declRefExpr(to(decl(equalsBoundNode("var"
```

Sorry still new to AST matchers

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


[llvm] [flang] [clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-12-21 Thread Nikita Popov via cfe-commits

nikic wrote:

> > arrayidx
> 
> We should teach `foldCmpLoadFromIndexedGlobal` to handle constant GEPs with 
> i8 source element type.

There is a pending patch related to this: 
https://github.com/llvm/llvm-project/pull/67093

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


[llvm] [flang] [clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-12-21 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> arrayidx

We should teach `foldCmpLoadFromIndexedGlobal` to handle constant GEPs with i8 
source element type.


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


[llvm] [flang] [clang] [InstCombine] Canonicalize constant GEPs to i8 source element type (PR #68882)

2023-12-21 Thread Yingwei Zheng via cfe-commits

dtcxzyw wrote:

> @nikic Could you please have a look at 
> [dtcxzyw/llvm-opt-benchmark#17](https://github.com/dtcxzyw/llvm-opt-benchmark/pull/17)?
>  One regression:
> 
> ```
> diff --git a/bench/brotli/optimized/compound_dictionary.c.ll 
> b/bench/brotli/optimized/compound_dictionary.c.ll
> index 21fd37fd..b9894810 100644
> --- a/bench/brotli/optimized/compound_dictionary.c.ll
> +++ b/bench/brotli/optimized/compound_dictionary.c.ll
> @@ -3,9 +3,6 @@ source_filename = 
> "bench/brotli/original/compound_dictionary.c.ll"
>  target datalayout = 
> "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
>  target triple = "x86_64-unknown-linux-gnu"
>  
> -%struct.PreparedDictionary = type { i32, i32, i32, i32, i32, i32 }
> -%struct.CompoundDictionary = type { i64, i64, [16 x ptr], [16 x ptr], [16 x 
> i64], i64, [16 x ptr] }
> -
>  ; Function Attrs: nounwind uwtable
>  define hidden ptr @CreatePreparedDictionary(ptr noundef %m, ptr noundef 
> %source, i64 noundef %source_size) local_unnamed_addr #0 {
>  entry:
> @@ -168,25 +165,29 @@ cond.true119.i:   ; 
> preds = %for.end106.i
>  
>  cond.end123.i:; preds = %cond.true119.i, 
> %for.end106.i
>%cond124.i = phi ptr [ %call121.i, %cond.true119.i ], [ null, 
> %for.end106.i ]
> -  %arrayidx125.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 1
> +  %arrayidx125.i = getelementptr inbounds i8, ptr %cond124.i, i64 24
>%arrayidx127.i = getelementptr inbounds i32, ptr %arrayidx125.i, i64 
> %idxprom.i
>%arrayidx129.i = getelementptr inbounds i16, ptr %arrayidx127.i, i64 
> %idxprom26.i
>%arrayidx131.i = getelementptr inbounds i32, ptr %arrayidx129.i, i64 
> %conv113.i
>store i32 -558043677, ptr %cond124.i, align 4
> -  %num_items.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 0, i32 1
> +  %num_items.i = getelementptr inbounds i8, ptr %cond124.i, i64 4
>store i32 %add100.i, ptr %num_items.i, align 4
>%conv132.i = trunc i64 %source_size to i32
> -  %source_size133.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 0, i32 2
> +  %source_size133.i = getelementptr inbounds i8, ptr %cond124.i, i64 8
>store i32 %conv132.i, ptr %source_size133.i, align 4
> -  %hash_bits134.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 0, i32 3
> +  %hash_bits134.i = getelementptr inbounds i8, ptr %cond124.i, i64 12
>store i32 40, ptr %hash_bits134.i, align 4
> -  %bucket_bits135.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 0, i32 4
> +  %bucket_bits135.i = getelementptr inbounds i8, ptr %cond124.i, i64 16
>store i32 %bucket_bits.0.lcssa, ptr %bucket_bits135.i, align 4
> -  %slot_bits136.i = getelementptr inbounds %struct.PreparedDictionary, ptr 
> %cond124.i, i64 0, i32 5
> +  %slot_bits136.i = getelementptr inbounds i8, ptr %cond124.i, i64 20
>store i32 %slot_bits.0.lcssa, ptr %slot_bits136.i, align 4
>store ptr %source, ptr %arrayidx131.i, align 1
>br label %for.body140.i
>  
> +for.cond151.preheader.i:  ; preds = %for.body140.i
> +  %invariant.gep.i = getelementptr i8, ptr %arrayidx129.i, i64 -4
> +  br label %for.body154.i
> +
>  for.body140.i:; preds = %for.body140.i, 
> %cond.end123.i
>%indvars.iv145.i = phi i64 [ 0, %cond.end123.i ], [ %indvars.iv.next146.i, 
> %for.body140.i ]
>%total_items.1139.i = phi i32 [ 0, %cond.end123.i ], [ %add145.i, 
> %for.body140.i ]
> @@ -198,10 +199,10 @@ for.body140.i:; 
> preds = %for.body140.i, %con
>store i32 0, ptr %arrayidx144.i, align 4
>%indvars.iv.next146.i = add nuw nsw i64 %indvars.iv145.i, 1
>%exitcond150.not.i = icmp eq i64 %indvars.iv.next146.i, %idxprom.i
> -  br i1 %exitcond150.not.i, label %for.body154.i, label %for.body140.i, 
> !llvm.loop !9
> +  br i1 %exitcond150.not.i, label %for.cond151.preheader.i, label 
> %for.body140.i, !llvm.loop !9
>  
> -for.body154.i:; preds = %for.body140.i, 
> %for.inc204.i
> -  %indvars.iv152.i = phi i64 [ %indvars.iv.next153.i, %for.inc204.i ], [ 0, 
> %for.body140.i ]
> +for.body154.i:; preds = %for.inc204.i, 
> %for.cond151.preheader.i
> +  %indvars.iv152.i = phi i64 [ 0, %for.cond151.preheader.i ], [ 
> %indvars.iv.next153.i, %for.inc204.i ]
>%5 = trunc i64 %indvars.iv152.i to i32
>%and155.i = and i32 %sub3.i, %5
>%arrayidx158.i = getelementptr inbounds i16, ptr %arrayidx25.i, i64 
> %indvars.iv152.i
> @@ -243,7 +244,7 @@ for.body194.i:; preds 
> = %for.body194.i, %if.
>%pos.0.in140.i = phi ptr [ %arrayidx189.i, %if.end177.i ], [ 
> %arrayidx198.i, %for.body194.i ]
>%pos.0.i = load i32, ptr %pos.0.in140.i, align 4
>%inc195.i = add nuw nsw i64 %cursor.0142.i, 1
> 

[llvm] [clang-tools-extra] [flang] [clang] [flang] Add EXECUTE_COMMAND_LINE runtime and lowering intrinsics implementation (PR #74077)

2023-12-21 Thread Yi Wu via cfe-commits


@@ -173,5 +173,141 @@ RT_API_ATTRS void ShallowCopy(const Descriptor , const 
Descriptor ) {
   ShallowCopy(to, from, to.IsContiguous(), from.IsContiguous());
 }
 
+RT_API_ATTRS const char *EnsureNullTerminated(
+const char *str, size_t length, Terminator ) {
+  if (length <= std::strlen(str)) {
+char *newCmd{(char *)AllocateMemoryOrCrash(terminator, length + 1)};
+std::memcpy(newCmd, str, length);
+newCmd[length] = '\0';
+return newCmd;
+  } else {
+return str;
+  }
+}
+
+RT_API_ATTRS std::size_t LengthWithoutTrailingSpaces(const Descriptor ) {
+  std::size_t s{d.ElementBytes() - 1};
+  while (*d.OffsetElement(s) == ' ') {
+--s;
+  }
+  return s + 1;
+}
+
+// Returns the length of the \p string. Assumes \p string is valid.
+RT_API_ATTRS std::int64_t StringLength(const char *string) {
+  return static_cast(std::strlen(string));
+}
+
+// Assumes Descriptor \p value is not nullptr.
+RT_API_ATTRS bool IsValidCharDescriptor(const Descriptor *value) {
+  return value && value->IsAllocated() &&
+  value->type() == TypeCode(TypeCategory::Character, 1) &&
+  value->rank() == 0;
+}
+
+// Assumes Descriptor \p intVal is not nullptr.
+RT_API_ATTRS bool IsValidIntDescriptor(const Descriptor *intVal) {
+  auto typeCode{intVal->type().GetCategoryAndKind()};
+  // Check that our descriptor is allocated and is a scalar integer with
+  // kind != 1 (i.e. with a large enough decimal exponent range).
+  return intVal->IsAllocated() && intVal->rank() == 0 &&
+  intVal->type().IsInteger() && typeCode && typeCode->second != 1;
+}
+
+// Assume Descriptor \p value is valid: pass IsValidCharDescriptor check.
+RT_API_ATTRS void FillWithSpaces(const Descriptor , std::size_t offset) {

yi-wu-arm wrote:

there is an if check, compare with `ElementBytes()`, moved back to 
`command.cpp` since it is only used there.

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


[clang-tools-extra] [clang-tidy] introduce a must use check (PR #76101)

2023-12-21 Thread Tyler Rockwood via cfe-commits


@@ -54,6 +55,7 @@ class MiscModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "misc-misleading-identifier");
 CheckFactories.registerCheck("misc-misplaced-const");
+CheckFactories.registerCheck("misc-must-use");

rockwotj wrote:

Merging that check and mine STGM (as well as the naming of your check). Do you 
have source for your check you'd like to point to? Otherwise I'm happy to add 
in a lot of these.

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


[llvm] [clang-tools-extra] [flang] [clang] [flang] Add EXECUTE_COMMAND_LINE runtime and lowering intrinsics implementation (PR #74077)

2023-12-21 Thread Yi Wu via cfe-commits


@@ -173,5 +173,141 @@ RT_API_ATTRS void ShallowCopy(const Descriptor , const 
Descriptor ) {
   ShallowCopy(to, from, to.IsContiguous(), from.IsContiguous());
 }
 
+RT_API_ATTRS const char *EnsureNullTerminated(
+const char *str, size_t length, Terminator ) {
+  if (length <= std::strlen(str)) {
+char *newCmd{(char *)AllocateMemoryOrCrash(terminator, length + 1)};
+std::memcpy(newCmd, str, length);
+newCmd[length] = '\0';
+return newCmd;
+  } else {
+return str;
+  }
+}
+
+RT_API_ATTRS std::size_t LengthWithoutTrailingSpaces(const Descriptor ) {
+  std::size_t s{d.ElementBytes() - 1};
+  while (*d.OffsetElement(s) == ' ') {
+--s;
+  }
+  return s + 1;
+}
+
+// Returns the length of the \p string. Assumes \p string is valid.
+RT_API_ATTRS std::int64_t StringLength(const char *string) {
+  return static_cast(std::strlen(string));
+}
+
+// Assumes Descriptor \p value is not nullptr.
+RT_API_ATTRS bool IsValidCharDescriptor(const Descriptor *value) {
+  return value && value->IsAllocated() &&
+  value->type() == TypeCode(TypeCategory::Character, 1) &&
+  value->rank() == 0;
+}
+
+// Assumes Descriptor \p intVal is not nullptr.
+RT_API_ATTRS bool IsValidIntDescriptor(const Descriptor *intVal) {

yi-wu-arm wrote:

correct, comment removed

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


[llvm] [clang-tools-extra] [flang] [clang] [flang] Add EXECUTE_COMMAND_LINE runtime and lowering intrinsics implementation (PR #74077)

2023-12-21 Thread Yi Wu via cfe-commits


@@ -411,6 +412,48 @@ RT_API_ATTRS void ShallowCopy(const Descriptor , const 
Descriptor ,
 bool toIsContiguous, bool fromIsContiguous);
 RT_API_ATTRS void ShallowCopy(const Descriptor , const Descriptor );
 
+RT_API_ATTRS const char *EnsureNullTerminated(
+const char *str, size_t length, Terminator );
+
+RT_API_ATTRS std::size_t LengthWithoutTrailingSpaces(const Descriptor );
+
+// Returns the length of the \p string. Assumes \p string is valid.
+RT_API_ATTRS std::int64_t StringLength(const char *string);
+
+// Assumes Descriptor \p value is not nullptr.
+RT_API_ATTRS bool IsValidCharDescriptor(const Descriptor *value);
+
+// Assumes Descriptor \p intVal is not nullptr.
+RT_API_ATTRS bool IsValidIntDescriptor(const Descriptor *intVal);
+
+// Assume Descriptor \p value is valid: pass IsValidCharDescriptor check.
+RT_API_ATTRS void FillWithSpaces(
+const Descriptor , std::size_t offset = 0);
+
+RT_API_ATTRS std::int32_t CopyToDescriptor(const Descriptor ,
+const char *rawValue, std::int64_t rawValueLength, const Descriptor 
*errmsg,
+std::size_t offset = 0);
+
+void CopyCharToDescriptor(

yi-wu-arm wrote:

add comment.
```cpp
// Copy a null-terminated character array \p rawValue to descriptor \p value.
// The copy starts at the given \p offset, if not present then start at 0.
// If descriptor `errmsg` is provided, error messages will be stored to it.
// Returns stats specified in standard.
```
the returned stats code is only used in `command.cpp` but functionality of 
copying is used in both `command.cpp` and `execute.cpp`

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


[clang] [AArch64][SME2] Add builtins for FDOT, BFDOT, SUDOT, USDOT, SDOT, UDOT. (PR #75737)

2023-12-21 Thread Dinar Temirbulatov via cfe-commits

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


  1   2   3   4   >