[clang-tools-extra] [clang-tidy]Add new check bugprone-casting-through-void (PR #69465)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -0,0 +1,46 @@
+//===--- CastingThroughVoidCheck.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 "CastingThroughVoidCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/StringSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void CastingThroughVoidCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  explicitCastExpr(
+  hasDestinationType(
+  qualType(unless(hasCanonicalType(pointsTo(voidType()
+  .bind("target_type")),
+  hasSourceExpression(
+  explicitCastExpr(
+  hasSourceExpression(
+  expr(hasType(qualType().bind("source_type",
+  hasDestinationType(
+  qualType(pointsTo(voidType())).bind("void_type")))
+  .bind("cast"))),
+  this);
+}
+
+void CastingThroughVoidCheck::check(const MatchFinder::MatchResult &Result) {
+  const auto TT = *Result.Nodes.getNodeAs("target_type");
+  const auto ST = *Result.Nodes.getNodeAs("source_type");
+  const auto VT = *Result.Nodes.getNodeAs("void_type");
+  const auto *CE = Result.Nodes.getNodeAs("cast");
+  diag(CE->getSourceRange().getBegin(), "do not cast %0 to %1 through %2")

PiotrZSL wrote:

Consider using `CE->getExprLoc()`

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


[clang-tools-extra] [clang-tidy]Add new check bugprone-casting-through-void (PR #69465)

2023-10-20 Thread Piotr Zegar via cfe-commits

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

LGTM.

About `static_cast(reinterpret_cast(&i));`:
- I'm working now on a check for redundant casts, it will detect this one, so 
no need to do it in this check.

You may consider adding support for double and more pointers, but that's not so 
so necessary as it work only with reinterprert_cast:
```
void double_ptr(int *ptr) {
 reinterpret_cast(reinterpret_cast(&ptr));
}
```


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


[clang-tools-extra] [run-clang-tidy, clang-tidy-diff] Accept directory as value for -export-fixes (PR #69453)

2023-10-20 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] 5557d98 - [run-clang-tidy, clang-tidy-diff] Accept directory as value for -export-fixes (#69453)

2023-10-20 Thread via cfe-commits

Author: Amadeus Gebauer
Date: 2023-10-20T09:22:49+02:00
New Revision: 5557d983412c2e8cdffaf855463098f7771f6499

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

LOG: [run-clang-tidy,clang-tidy-diff] Accept directory as value for 
-export-fixes (#69453)

Adding an additional parameter to run_clang_tidy.py to accept a
directory where the clang-tidy fixes are saved to. This directory can
then be used to run `clang-apply-replacements`.

Closes #69450

Added: 


Modified: 
clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
clang-tools-extra/docs/ReleaseNotes.rst

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py b/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
index 06f2cebe7c09e60..6fb5eedf06d5dff 100755
--- a/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
+++ b/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
@@ -180,10 +180,12 @@ def main():
 if yaml:
 parser.add_argument(
 "-export-fixes",
-metavar="FILE",
+metavar="FILE_OR_DIRECTORY",
 dest="export_fixes",
-help="Create a yaml file to store suggested fixes in, "
-"which can be applied with clang-apply-replacements.",
+help="A directory or a yaml file to store suggested fixes in, "
+"which can be applied with clang-apply-replacements. If the "
+"parameter is a directory, the fixes of each compilation unit are "
+"stored in individual yaml files in the directory.",
 )
 parser.add_argument(
 "-extra-arg",
@@ -258,9 +260,25 @@ def main():
 max_task_count = multiprocessing.cpu_count()
 max_task_count = min(len(lines_by_file), max_task_count)
 
-tmpdir = None
-if yaml and args.export_fixes:
-tmpdir = tempfile.mkdtemp()
+combine_fixes = False
+export_fixes_dir = None
+delete_fixes_dir = False
+if args.export_fixes is not None:
+# if a directory is given, create it if it does not exist
+if args.export_fixes.endswith(os.path.sep) and not os.path.isdir(
+args.export_fixes
+):
+os.makedirs(args.export_fixes)
+
+if not os.path.isdir(args.export_fixes) and yaml:
+combine_fixes = True
+
+if os.path.isdir(args.export_fixes):
+export_fixes_dir = args.export_fixes
+
+if combine_fixes:
+export_fixes_dir = tempfile.mkdtemp()
+delete_fixes_dir = True
 
 # Tasks for clang-tidy.
 task_queue = queue.Queue(max_task_count)
@@ -302,10 +320,10 @@ def main():
 # Run clang-tidy on files containing changes.
 command = [args.clang_tidy_binary]
 command.append("-line-filter=" + line_filter_json)
-if yaml and args.export_fixes:
+if args.export_fixes is not None:
 # Get a temporary file. We immediately close the handle so 
clang-tidy can
 # overwrite it.
-(handle, tmp_name) = tempfile.mkstemp(suffix=".yaml", dir=tmpdir)
+(handle, tmp_name) = tempfile.mkstemp(suffix=".yaml", 
dir=export_fixes_dir)
 os.close(handle)
 command.append("-export-fixes=" + tmp_name)
 command.extend(common_clang_tidy_args)
@@ -324,17 +342,17 @@ def main():
 if failed_files:
 return_code = 1
 
-if yaml and args.export_fixes:
+if combine_fixes:
 print("Writing fixes to " + args.export_fixes + " ...")
 try:
-merge_replacement_files(tmpdir, args.export_fixes)
+merge_replacement_files(export_fixes_dir, args.export_fixes)
 except:
 sys.stderr.write("Error exporting fixes.\n")
 traceback.print_exc()
 return_code = 1
 
-if tmpdir:
-shutil.rmtree(tmpdir)
+if delete_fixes_dir:
+shutil.rmtree(export_fixes_dir)
 sys.exit(return_code)
 
 

diff  --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index 312d9241cfa57c5..aa628aa87800693 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -308,10 +308,12 @@ def main():
 if yaml:
 parser.add_argument(
 "-export-fixes",
-metavar="filename",
+metavar="file_or_directory",
 dest="export_fixes",
-help="Create a yaml file to store suggested fixes in, "
-"which can be applied with clang-apply-replacements.",
+help="A directory or a yaml file to store suggested fixes in, "
+"which can be applied with clang-apply-replacements. If the "
+"para

[clang-tools-extra] [clang-tidy] modernize-avoid-bind only return for non-void function (PR #69207)

2023-10-20 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

> Any particular reason for the `+-`? Maybe it can be resolved?

I'm just not too familiar with this check.
But current change looks fine, and could be merged.

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


[clang-tools-extra] Fix #68492: point to the correct const location (PR #69103)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -297,6 +297,10 @@ Changes in existing checks
   ` check to
   ignore false-positive for ``if constexpr`` in lambda expression.
 
+- Improved :doc:`readability-const-params-in-decls
+  ` place the hint check 
under

PiotrZSL wrote:

`Improved xyz check to place ...`
Currently it sound strange.

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


[clang-tools-extra] Fix #68492: point to the correct const location (PR #69103)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -297,6 +297,10 @@ Changes in existing checks
   ` check to
   ignore false-positive for ``if constexpr`` in lambda expression.
 
+- Improved :doc:`readability-const-params-in-decls
+  ` place the hint check 
under

PiotrZSL wrote:

Or it can be just Improved xyz diagnostics to highlight an ``const`` location.

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


[clang-tools-extra] Fix #68492: point to the correct const location (PR #69103)

2023-10-20 Thread Piotr Zegar via cfe-commits

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


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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -285,6 +285,10 @@ Changes in existing checks
   ` check to fix function pointer and
   forward declared ``typedef`` correctly.
 
+- Improved :doc:`modernize-use-using

PiotrZSL wrote:

merge with previous entry for this check.

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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -325,6 +329,7 @@ Changes in existing checks
   identify calls to static member functions with out-of-class inline 
definitions.
 
 
+

PiotrZSL wrote:

remove added empty line

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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.
+
+.. code-block:: c++
+
+  extern "C" {
+

PiotrZSL wrote:

remove empty line

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


[clang-tools-extra] Fix #35272: Don't replace typedefs in extern c scope (PR #69102)

2023-10-20 Thread Piotr Zegar via cfe-commits


@@ -28,6 +28,15 @@ After:
   using R_t = struct { int a; };
   using R_p = R_t*;
 
+The checker ignores `typedef` within `extern "C" { ... }` blocks.

PiotrZSL wrote:

Maybe this should be put into configuration option ? To give an option to 
preserve current behavior.

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


[clang-tools-extra] [Docs][LTO] Updated HowToSubmitABug.rst for LTO crashes (PR #68389)

2023-10-20 Thread Shivam Gupta via cfe-commits

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


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

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


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

>From 8e0d084529d159ee80dd3971f9a5bb112e24bb86 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 15 Sep 2023 15:51:39 +0200
Subject: [PATCH 01/20] [clang][Diagnostics] Highlight code snippets

Add some primitive syntax highlighting to our code snippet output.
---
 .../clang/Frontend/CodeSnippetHighlighter.h   |  46 +++
 clang/include/clang/Frontend/TextDiagnostic.h |   2 +
 clang/lib/Frontend/CMakeLists.txt |   1 +
 clang/lib/Frontend/CodeSnippetHighlighter.cpp | 120 ++
 clang/lib/Frontend/TextDiagnostic.cpp |  26 
 5 files changed, 195 insertions(+)
 create mode 100644 clang/include/clang/Frontend/CodeSnippetHighlighter.h
 create mode 100644 clang/lib/Frontend/CodeSnippetHighlighter.cpp

diff --git a/clang/include/clang/Frontend/CodeSnippetHighlighter.h 
b/clang/include/clang/Frontend/CodeSnippetHighlighter.h
new file mode 100644
index 000..776954b59e2e1a8
--- /dev/null
+++ b/clang/include/clang/Frontend/CodeSnippetHighlighter.h
@@ -0,0 +1,46 @@
+//===--- CodeSnippetHighlighter.h - Code snippet highlighting ---*- 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_FRONTEND_CODESNIPPETHIGHLIGHTER_H
+#define LLVM_CLANG_FRONTEND_CODESNIPPETHIGHLIGHTER_H
+
+#include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+namespace clang {
+
+struct StyleRange {
+  unsigned Start;
+  unsigned End;
+  const enum llvm::raw_ostream::Colors c;
+};
+
+class CodeSnippetHighlighter final {
+public:
+  CodeSnippetHighlighter() = default;
+
+  /// Produce StyleRanges for the given line.
+  /// The returned vector contains non-overlapping style ranges. They are 
sorted
+  /// from beginning of the line to the end.
+  std::vector highlightLine(llvm::StringRef SourceLine,
+const LangOptions &LangOpts);
+
+private:
+  bool Initialized = false;
+  /// Fills Keywords and Literals.
+  void ensureTokenData();
+
+  llvm::SmallSet Keywords;
+  llvm::SmallSet Literals;
+};
+
+} // namespace clang
+
+#endif
diff --git a/clang/include/clang/Frontend/TextDiagnostic.h 
b/clang/include/clang/Frontend/TextDiagnostic.h
index 7eb0ab0cdc9bca8..59fd4d4f9408d48 100644
--- a/clang/include/clang/Frontend/TextDiagnostic.h
+++ b/clang/include/clang/Frontend/TextDiagnostic.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
 #define LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
 
+#include "clang/Frontend/CodeSnippetHighlighter.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
 
 namespace clang {
@@ -33,6 +34,7 @@ namespace clang {
 /// printing coming out of libclang.
 class TextDiagnostic : public DiagnosticRenderer {
   raw_ostream &OS;
+  CodeSnippetHighlighter SnippetHighlighter;
 
 public:
   TextDiagnostic(raw_ostream &OS,
diff --git a/clang/lib/Frontend/CMakeLists.txt 
b/clang/lib/Frontend/CMakeLists.txt
index 1e5f0a859dfd568..f3547f771593093 100644
--- a/clang/lib/Frontend/CMakeLists.txt
+++ b/clang/lib/Frontend/CMakeLists.txt
@@ -42,6 +42,7 @@ add_clang_library(clangFrontend
   TextDiagnosticPrinter.cpp
   VerifyDiagnosticConsumer.cpp
   InterfaceStubFunctionsConsumer.cpp
+  CodeSnippetHighlighter.cpp
 
   DEPENDS
   ClangDriverOptions
diff --git a/clang/lib/Frontend/CodeSnippetHighlighter.cpp 
b/clang/lib/Frontend/CodeSnippetHighlighter.cpp
new file mode 100644
index 000..829a533ad2692e5
--- /dev/null
+++ b/clang/lib/Frontend/CodeSnippetHighlighter.cpp
@@ -0,0 +1,120 @@
+
+#include "clang/Frontend/CodeSnippetHighlighter.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang;
+
+void CodeSnippetHighlighter::ensureTokenData() {
+  if (Initialized)
+return;
+
+  // List of keywords, literals and types we want to highlight.
+  // These are best-effort, as is everything we do wrt. highlighting.
+  Keywords.insert("_Static_assert");
+  Keywords.insert("auto");
+  Keywords.insert("concept");
+  Keywords.insert("const");
+  Keywords.insert("consteval");
+  Keywords.insert("

[clang] [clang] Add clang::preferred_type attribute for bitfields (PR #69104)

2023-10-20 Thread Vlad Serebrennikov via cfe-commits

Endilll wrote:

> While I think that warning is accurate, I somewhat question the value of the 
> 'bool' as working on this type

I'm not sure what you mean by "working" here, but I'd like to highlight that we 
have hundreds of single-bit bit-fields across Clang that would benefit from 
`[[clang::preferred_type(bool)]]`.

> as, I'm not sure what it really means to put a non-enum here?

When it was `clang::debug_info_type`, the meaning was as simple as "I want the 
value of this bit-field to be interpreted as T". Now that we moved to 
`preferred_type`, there might be more interpretations.

> What types ARE we allowing in this now?

As I mentioned in 
https://github.com/llvm/llvm-project/pull/69104#discussion_r1365269451, I'm not 
putting any restrictions on type parameter of the attribute, which makes even 
more sense for more generic `preferred_type`.

But I'm confused by the fact you are raising this question. In 
https://github.com/llvm/llvm-project/pull/69104#discussion_r1364432624, you 
wrote:
> I can see potential value of a "OpaqueValueOfStruct" storage type thing, that 
> perhaps we should just 'trust' that the user is doing something sensible with 
> it.

I read that as you being in favor of trusting user to pass whatever type they 
want to `preferred_type`. I feel like I'm getting mixed signals from you on 
this topic, so it'd be nice if you can make yourself clear.

> I think the wording of the diagnostic is perhaps awkward, so we should 
> bikeshed that as well

Sure.

> though I'm on the fence about the diagnostic existing at all. On one hand, 
> this would be such a special case, as typically 'too large' for the type 
> isn't an issue for any reason. On the other, the 'bool' case is perhaps 
> uniquely an issue.

As we are going to attach semantic type information to our bit-fields, I see an 
opportunity to raise valid questions like "Why do you need 2 bits to hold a 
boolean value?". If intention is to reserve bits for future extensions, I 
believe it should be stated more explicitly via something along the lines of 
`enum E { False, True, Reserved = 3}`.

> What about if the person prefers the type be 'char', but has it be a size of 
> 9? THIS is a case where it is reasonable (consider cases where you need to 
> store the result of one of those calls to the C library that returns 'an int 
> that is either a char or -1').

I'd like to state upfront that I'm diagnosing only booleans, because I see how 
it can help maintaining Clang headers. Now, on `CHAR_BIT == 8` platform, your 
example results in 8 bits for value, and 1 bit of padding 
(http://eel.is/c++draft/class.bit#1.sentence-6). I find such bit-field somewhat 
strange (why can't padding be declared explicitly via unnamed bit-field?), but 
maybe I haven't seen enough bit-fields in my life to appreciate it.

> So I guess I'm really questioning how accurate/error-free we could make that 
> diagnostic.

In it's current form (only `bool` is checked), I consider it rather accurate. 
I'm yet to see a use case where `[[clang::preferred_type(bool)]] unsigned 
Predicate : 2` is the best solution available.

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


[clang] [clang]improve diagnosing redefined defaulted constructor with different exception specs (PR #69688)

2023-10-20 Thread Congcong Cai via cfe-commits

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

It is misleading when diagnosing 'ExplicitlySpecialMethod' is missing exception 
specification 'noexcept' for
```c++
struct ExplicitlySpecialMethod {
  ExplicitlySpecialMethod() = default;
};
ExplicitlySpecialMethod::ExplicitlySpecialMethod() {}
```
Fixes: #69094

>From 6bcedda8c78480a7fd0ff42831e08f18960ddd1c Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 20 Oct 2023 15:45:42 +0800
Subject: [PATCH] [clang]improve diagnosing redefined defaulted constructor
 with different exception specs

It is misleading when diagnosing 'ExplicitlySpecialMethod' is missing exception 
specification 'noexcept' for
```c++
struct ExplicitlySpecialMethod {
  ExplicitlySpecialMethod() = default;
};
ExplicitlySpecialMethod::ExplicitlySpecialMethod() {}
```
Fixes: #69094
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaDecl.cpp   | 25 ++-
 ...agnoise-prioritiy-exception-redefining.cpp |  9 +++
 3 files changed, 25 insertions(+), 12 deletions(-)
 create mode 100644 
clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..bf53dfe6c415245 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -325,6 +325,9 @@ Improvements to Clang's diagnostics
   |   ~^~~~
 - Clang now always diagnoses when using non-standard layout types in 
``offsetof`` .
   (`#64619: `_)
+- Clang nows diagnose redefined defaulted default constructor when redefined
+  defaulted default constructor with different exception specs.
+  (`#69094: `_)
 
 Bug Fixes in This Version
 -
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..c4979b51e68f5e2 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3922,18 +3922,6 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 
   if (getLangOpts().CPlusPlus) {
-// C++1z [over.load]p2
-//   Certain function declarations cannot be overloaded:
-// -- Function declarations that differ only in the return type,
-//the exception specification, or both cannot be overloaded.
-
-// Check the exception specifications match. This may recompute the type of
-// both Old and New if it resolved exception specifications, so grab the
-// types again after this. Because this updates the type, we do this before
-// any of the other checks below, which may update the "de facto" NewQType
-// but do not necessarily update the type of New.
-if (CheckEquivalentExceptionSpec(Old, New))
-  return true;
 OldQType = Context.getCanonicalType(Old->getType());
 NewQType = Context.getCanonicalType(New->getType());
 
@@ -4055,6 +4043,19 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 }
 
+// C++1z [over.load]p2
+//   Certain function declarations cannot be overloaded:
+// -- Function declarations that differ only in the return type,
+//the exception specification, or both cannot be overloaded.
+
+// Check the exception specifications match. This may recompute the type of
+// both Old and New if it resolved exception specifications, so grab the
+// types again after this. Because this updates the type, we do this before
+// any of the other checks below, which may update the "de facto" NewQType
+// but do not necessarily update the type of New.
+if (CheckEquivalentExceptionSpec(Old, New))
+  return true;
+
 // C++11 [dcl.attr.noreturn]p1:
 //   The first declaration of a function shall specify the noreturn
 //   attribute if any declaration of that function specifies the noreturn
diff --git a/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp 
b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
new file mode 100644
index 000..ad025bf041ce519
--- /dev/null
+++ b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fcxx-exceptions -std=c++11 %s
+
+struct ExplicitlySpecialMethod {
+  ExplicitlySpecialMethod() = default;
+};
+ExplicitlySpecialMethod::ExplicitlySpecialMethod() {} // 
expected-error{{definition of explicitly defaulted default constructor}}
+
+struct ImplicitlySpecialMethod {};
+ImplicitlySpecialMethod::ImplicitlySpecialMethod() {} // 
expected-error{{definition of implicitly declared default constructor}}

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-20 Thread Momchil Velikov via cfe-commits

momchil-velikov wrote:

Ping?

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


[clang] [AArch64] Stack probing for function prologues (PR #66524)

2023-10-20 Thread Momchil Velikov via cfe-commits

momchil-velikov wrote:

Ping?

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


[clang] [clang]improve diagnosing redefined defaulted constructor with different exception specs (PR #69688)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Congcong Cai (HerrCai0907)


Changes

It is misleading when diagnosing 'ExplicitlySpecialMethod' is missing exception 
specification 'noexcept' for
```c++
struct ExplicitlySpecialMethod {
  ExplicitlySpecialMethod() = default;
};
ExplicitlySpecialMethod::ExplicitlySpecialMethod() {}
```
Fixes: #69094

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Sema/SemaDecl.cpp (+13-12) 
- (added) clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp (+9) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..bf53dfe6c415245 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -325,6 +325,9 @@ Improvements to Clang's diagnostics
   |   ~^~~~
 - Clang now always diagnoses when using non-standard layout types in 
``offsetof`` .
   (`#64619: `_)
+- Clang nows diagnose redefined defaulted default constructor when redefined
+  defaulted default constructor with different exception specs.
+  (`#69094: `_)
 
 Bug Fixes in This Version
 -
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..c4979b51e68f5e2 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3922,18 +3922,6 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 
   if (getLangOpts().CPlusPlus) {
-// C++1z [over.load]p2
-//   Certain function declarations cannot be overloaded:
-// -- Function declarations that differ only in the return type,
-//the exception specification, or both cannot be overloaded.
-
-// Check the exception specifications match. This may recompute the type of
-// both Old and New if it resolved exception specifications, so grab the
-// types again after this. Because this updates the type, we do this before
-// any of the other checks below, which may update the "de facto" NewQType
-// but do not necessarily update the type of New.
-if (CheckEquivalentExceptionSpec(Old, New))
-  return true;
 OldQType = Context.getCanonicalType(Old->getType());
 NewQType = Context.getCanonicalType(New->getType());
 
@@ -4055,6 +4043,19 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 }
 
+// C++1z [over.load]p2
+//   Certain function declarations cannot be overloaded:
+// -- Function declarations that differ only in the return type,
+//the exception specification, or both cannot be overloaded.
+
+// Check the exception specifications match. This may recompute the type of
+// both Old and New if it resolved exception specifications, so grab the
+// types again after this. Because this updates the type, we do this before
+// any of the other checks below, which may update the "de facto" NewQType
+// but do not necessarily update the type of New.
+if (CheckEquivalentExceptionSpec(Old, New))
+  return true;
+
 // C++11 [dcl.attr.noreturn]p1:
 //   The first declaration of a function shall specify the noreturn
 //   attribute if any declaration of that function specifies the noreturn
diff --git a/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp 
b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
new file mode 100644
index 000..ad025bf041ce519
--- /dev/null
+++ b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fcxx-exceptions -std=c++11 %s
+
+struct ExplicitlySpecialMethod {
+  ExplicitlySpecialMethod() = default;
+};
+ExplicitlySpecialMethod::ExplicitlySpecialMethod() {} // 
expected-error{{definition of explicitly defaulted default constructor}}
+
+struct ImplicitlySpecialMethod {};
+ImplicitlySpecialMethod::ImplicitlySpecialMethod() {} // 
expected-error{{definition of implicitly declared default constructor}}

``




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


[clang] c9b17af - [Driver][DragonFly][NFC] Some cleaning up

2023-10-20 Thread Brad Smith via cfe-commits

Author: Brad Smith
Date: 2023-10-20T04:01:58-04:00
New Revision: c9b17af22835ace1b4cf35b958a197d8e2de0fd0

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

LOG: [Driver][DragonFly][NFC] Some cleaning up

Added: 


Modified: 
clang/lib/Driver/ToolChains/DragonFly.cpp

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/DragonFly.cpp 
b/clang/lib/Driver/ToolChains/DragonFly.cpp
index 3778c7773b6b90b..9dc8d9d4363bd71 100644
--- a/clang/lib/Driver/ToolChains/DragonFly.cpp
+++ b/clang/lib/Driver/ToolChains/DragonFly.cpp
@@ -20,21 +20,19 @@ using namespace clang::driver::toolchains;
 using namespace clang;
 using namespace llvm::opt;
 
-/// DragonFly Tools
-
-// For now, DragonFly Assemble does just about the same as for
-// FreeBSD, but this may change soon.
 void dragonfly::Assembler::ConstructJob(Compilation &C, const JobAction &JA,
 const InputInfo &Output,
 const InputInfoList &Inputs,
 const ArgList &Args,
 const char *LinkingOutput) const {
-  claimNoWarnArgs(Args);
+  const auto &ToolChain = static_cast(getToolChain());
   ArgStringList CmdArgs;
 
+  claimNoWarnArgs(Args);
+
   // When building 32-bit code on DragonFly/pc64, we have to explicitly
   // instruct as in the base system to assemble 32-bit code.
-  if (getToolChain().getArch() == llvm::Triple::x86)
+  if (ToolChain.getArch() == llvm::Triple::x86)
 CmdArgs.push_back("--32");
 
   Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA, 
options::OPT_Xassembler);
@@ -45,7 +43,7 @@ void dragonfly::Assembler::ConstructJob(Compilation &C, const 
JobAction &JA,
   for (const auto &II : Inputs)
 CmdArgs.push_back(II.getFilename());
 
-  const char *Exec = Args.MakeArgString(getToolChain().GetProgramPath("as"));
+  const char *Exec = Args.MakeArgString(ToolChain.GetProgramPath("as"));
   C.addCommand(std::make_unique(JA, *this,
  ResponseFileSupport::AtFileCurCP(),
  Exec, CmdArgs, Inputs, Output));
@@ -58,18 +56,23 @@ void dragonfly::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
  const char *LinkingOutput) const {
   const auto &ToolChain = static_cast(getToolChain());
   const Driver &D = ToolChain.getDriver();
+  const llvm::Triple::ArchType Arch = ToolChain.getArch();
   ArgStringList CmdArgs;
+  bool Static = Args.hasArg(options::OPT_static);
+  bool Shared = Args.hasArg(options::OPT_shared);
+  bool Profiling = Args.hasArg(options::OPT_pg);
+  bool Pie = Args.hasArg(options::OPT_pie);
 
   if (!D.SysRoot.empty())
 CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
 
   CmdArgs.push_back("--eh-frame-hdr");
-  if (Args.hasArg(options::OPT_static)) {
+  if (Static) {
 CmdArgs.push_back("-Bstatic");
   } else {
 if (Args.hasArg(options::OPT_rdynamic))
   CmdArgs.push_back("-export-dynamic");
-if (Args.hasArg(options::OPT_shared))
+if (Shared)
   CmdArgs.push_back("-shared");
 else if (!Args.hasArg(options::OPT_r)) {
   CmdArgs.push_back("-dynamic-linker");
@@ -81,7 +84,7 @@ void dragonfly::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 
   // When building 32-bit code on DragonFly/pc64, we have to explicitly
   // instruct ld in the base system to link 32-bit code.
-  if (getToolChain().getArch() == llvm::Triple::x86) {
+  if (Arch == llvm::Triple::x86) {
 CmdArgs.push_back("-m");
 CmdArgs.push_back("elf_i386");
   }
@@ -94,67 +97,66 @@ void dragonfly::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
 
   if (!Args.hasArg(options::OPT_nostdlib, options::OPT_nostartfiles,
options::OPT_r)) {
-if (!Args.hasArg(options::OPT_shared)) {
-  if (Args.hasArg(options::OPT_pg))
-CmdArgs.push_back(
-Args.MakeArgString(getToolChain().GetFilePath("gcrt1.o")));
+const char *crt1 = nullptr;
+const char *crtbegin = nullptr;
+if (!Shared) {
+  if (Profiling)
+crt1 = "gcrt1.o";
   else {
-if (Args.hasArg(options::OPT_pie))
-  CmdArgs.push_back(
-  Args.MakeArgString(getToolChain().GetFilePath("Scrt1.o")));
+if (Pie)
+  crt1 = "Scrt1.o";
 else
-  CmdArgs.push_back(
-  Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
+  crt1 = "crt1.o";
   }
 }
-
CmdArgs.push_back(Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
-if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
-  CmdArgs.push_back(
-  Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")))

[clang] [clang]improve diagnosing redefined defaulted constructor with different exception specs (PR #69688)

2023-10-20 Thread Congcong Cai via cfe-commits

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

>From 2629b346123f9838a4fc3d8b6fb6a98508773965 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Fri, 20 Oct 2023 15:45:42 +0800
Subject: [PATCH] [clang]improve diagnosing redefined defaulted constructor
 with different exception specs

It is misleading when diagnosing 'ExplicitlySpecialMethod' is missing exception 
specification 'noexcept' for
```c++
struct ExplicitlySpecialMethod {
  ExplicitlySpecialMethod() = default;
};
ExplicitlySpecialMethod::ExplicitlySpecialMethod() {}
```
Fixes: #69094
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/SemaDecl.cpp   | 25 ++-
 ...agnoise-prioritiy-exception-redefining.cpp |  9 +++
 3 files changed, 25 insertions(+), 12 deletions(-)
 create mode 100644 
clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..ae995a12cf0fd7d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -325,6 +325,9 @@ Improvements to Clang's diagnostics
   |   ~^~~~
 - Clang now always diagnoses when using non-standard layout types in 
``offsetof`` .
   (`#64619: `_)
+- Clang now diagnoses redefined defaulted constructor when redefined
+  defaulted constructor with different exception specs.
+  (`#69094: `_)
 
 Bug Fixes in This Version
 -
diff --git a/clang/lib/Sema/SemaDecl.cpp b/clang/lib/Sema/SemaDecl.cpp
index b363b0db79f164d..c4979b51e68f5e2 100644
--- a/clang/lib/Sema/SemaDecl.cpp
+++ b/clang/lib/Sema/SemaDecl.cpp
@@ -3922,18 +3922,6 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 
   if (getLangOpts().CPlusPlus) {
-// C++1z [over.load]p2
-//   Certain function declarations cannot be overloaded:
-// -- Function declarations that differ only in the return type,
-//the exception specification, or both cannot be overloaded.
-
-// Check the exception specifications match. This may recompute the type of
-// both Old and New if it resolved exception specifications, so grab the
-// types again after this. Because this updates the type, we do this before
-// any of the other checks below, which may update the "de facto" NewQType
-// but do not necessarily update the type of New.
-if (CheckEquivalentExceptionSpec(Old, New))
-  return true;
 OldQType = Context.getCanonicalType(Old->getType());
 NewQType = Context.getCanonicalType(New->getType());
 
@@ -4055,6 +4043,19 @@ bool Sema::MergeFunctionDecl(FunctionDecl *New, 
NamedDecl *&OldD, Scope *S,
   }
 }
 
+// C++1z [over.load]p2
+//   Certain function declarations cannot be overloaded:
+// -- Function declarations that differ only in the return type,
+//the exception specification, or both cannot be overloaded.
+
+// Check the exception specifications match. This may recompute the type of
+// both Old and New if it resolved exception specifications, so grab the
+// types again after this. Because this updates the type, we do this before
+// any of the other checks below, which may update the "de facto" NewQType
+// but do not necessarily update the type of New.
+if (CheckEquivalentExceptionSpec(Old, New))
+  return true;
+
 // C++11 [dcl.attr.noreturn]p1:
 //   The first declaration of a function shall specify the noreturn
 //   attribute if any declaration of that function specifies the noreturn
diff --git a/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp 
b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
new file mode 100644
index 000..ad025bf041ce519
--- /dev/null
+++ b/clang/test/SemaCXX/diagnoise-prioritiy-exception-redefining.cpp
@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fcxx-exceptions -std=c++11 %s
+
+struct ExplicitlySpecialMethod {
+  ExplicitlySpecialMethod() = default;
+};
+ExplicitlySpecialMethod::ExplicitlySpecialMethod() {} // 
expected-error{{definition of explicitly defaulted default constructor}}
+
+struct ImplicitlySpecialMethod {};
+ImplicitlySpecialMethod::ImplicitlySpecialMethod() {} // 
expected-error{{definition of implicitly declared default constructor}}

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


[clang] [Driver] Corrections for linker flags passed with relocatable linking on OpenBSD (PR #67254)

2023-10-20 Thread Brad Smith via cfe-commits

https://github.com/brad0 updated https://github.com/llvm/llvm-project/pull/67254

>From d16c447291c2c1127a6abc9b83942b47f2d9e145 Mon Sep 17 00:00:00 2001
From: Brad Smith 
Date: Sun, 24 Sep 2023 00:20:53 -0400
Subject: [PATCH] [Driver] Corrections for linker flags passed with relocatable
 linking on OpenBSD

The entry point symbol handling matches our GCC link spec..
%{!shared:%{!nostdlib:%{!r:%{!e*:-e __start

Remove usage of -Bdynamic as it is the default for the linker anyway.
---
 clang/lib/Driver/ToolChains/OpenBSD.cpp |  6 +++---
 clang/test/Driver/openbsd.c | 13 +++--
 2 files changed, 10 insertions(+), 9 deletions(-)

diff --git a/clang/lib/Driver/ToolChains/OpenBSD.cpp 
b/clang/lib/Driver/ToolChains/OpenBSD.cpp
index 2508ef57f827ccf..e874f245776c4fc 100644
--- a/clang/lib/Driver/ToolChains/OpenBSD.cpp
+++ b/clang/lib/Driver/ToolChains/OpenBSD.cpp
@@ -121,6 +121,7 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   bool Profiling = Args.hasArg(options::OPT_pg);
   bool Pie = Args.hasArg(options::OPT_pie);
   bool Nopie = Args.hasArg(options::OPT_nopie);
+  const bool Relocatable = Args.hasArg(options::OPT_r);
 
   // Silence warning for "clang -g foo.o -o foo"
   Args.ClaimAllArgs(options::OPT_g_Group);
@@ -138,7 +139,7 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   else if (Arch == llvm::Triple::mips64el)
 CmdArgs.push_back("-EL");
 
-  if (!Args.hasArg(options::OPT_nostdlib) && !Shared) {
+  if (!Args.hasArg(options::OPT_nostdlib) && !Shared && !Relocatable) {
 CmdArgs.push_back("-e");
 CmdArgs.push_back("__start");
   }
@@ -149,10 +150,9 @@ void openbsd::Linker::ConstructJob(Compilation &C, const 
JobAction &JA,
   } else {
 if (Args.hasArg(options::OPT_rdynamic))
   CmdArgs.push_back("-export-dynamic");
-CmdArgs.push_back("-Bdynamic");
 if (Shared) {
   CmdArgs.push_back("-shared");
-} else if (!Args.hasArg(options::OPT_r)) {
+} else if (!Relocatable) {
   CmdArgs.push_back("-dynamic-linker");
   CmdArgs.push_back("/usr/libexec/ld.so");
 }
diff --git a/clang/test/Driver/openbsd.c b/clang/test/Driver/openbsd.c
index c84b54f24fdc24c..713bf350ee188b7 100644
--- a/clang/test/Driver/openbsd.c
+++ b/clang/test/Driver/openbsd.c
@@ -8,7 +8,7 @@
 // RUN: %clang --target=i686-pc-openbsd -pg -pthread -### %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-PG %s
 // CHECK-PG: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-PG: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-nopie" "-o" "a.out" "{{.*}}gcrt0.o" 
"{{.*}}crtbegin.o" "{{.*}}.o" "-lcompiler_rt" "-lpthread_p" "-lc_p" 
"-lcompiler_rt" "{{.*}}crtend.o"
+// CHECK-PG: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-nopie" "-o" "a.out" "{{.*}}gcrt0.o" "{{.*}}crtbegin.o" 
"{{.*}}.o" "-lcompiler_rt" "-lpthread_p" "-lc_p" "-lcompiler_rt" 
"{{.*}}crtend.o"
 
 // Check CPU type for i386
 // RUN: %clang --target=i386-unknown-openbsd -### -c %s 2>&1 \
@@ -34,18 +34,19 @@
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64-LD %s
 // RUN: %clang --target=mips64el-unknown-openbsd -### %s 2>&1 \
 // RUN:   | FileCheck --check-prefix=CHECK-MIPS64EL-LD %s
-// CHECK-LD-R: "-r"
+// CHECK-LD-R-NOT: "-e"
 // CHECK-LD-R-NOT: "-dynamic-linker"
 // CHECK-LD-R-NOT: "-l
 // CHECK-LD-R-NOT: crt{{[^./\\]+}}.o
+// CHECK-LD-R: "-r"
 // CHECK-LD-S: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-s" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-S: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-s" 
"{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-LD-T: "-cc1" "-triple" "i686-pc-openbsd"
-// CHECK-LD-T: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-Bdynamic" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "-t" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-LD-T: ld{{.*}}" "-e" "__start" "--eh-frame-hdr" "-dynamic-linker" 
"{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" "-L{{.*}}" "-t" 
"{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-MIPS64-LD: "-cc1" "-triple" "mips64-unknown-openbsd"
-// CHECK-MIPS64-LD: ld{{.*}}" "-EB" "-e" "__start" "--eh-frame-hdr" 
"-Bdynamic" "-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" 
"{{.*}}crtbegin.o" "-L{{.*}}" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" 
"{{.*}}crtend.o"
+// CHECK-MIPS64-LD: ld{{.*}}" "-EB" "-e" "__start" "--eh-frame-hdr" 
"-dynamic-linker" "{{.*}}ld.so" "-o" "a.out" "{{.*}}crt0.o" "{{.*}}crtbegin.o" 
"-L{{.*}}" "{{.*}}.o" "-lcompiler_rt" "-lc" "-lcompiler_rt" "{{.*}}crtend.o"
 // CHECK-MIPS64EL-LD: "

[clang] [Driver] Corrections for linker flags passed with relocatable linking on OpenBSD (PR #67254)

2023-10-20 Thread Brad Smith via cfe-commits

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


[clang-tools-extra] [clang-tidy]Add new check bugprone-casting-through-void (PR #69465)

2023-10-20 Thread Congcong Cai via cfe-commits

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

>From 627f68e57b2526fb72285ef4831fc3c02a6ee6d0 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 18 Oct 2023 08:47:02 +0800
Subject: [PATCH 1/8] [clang-tidy]Add new check bugprone-casting-through-void

Fixes: #68532
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../bugprone/CastingThroughVoidCheck.cpp  | 46 +++
 .../bugprone/CastingThroughVoidCheck.h| 37 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +++
 .../checks/bugprone/casting-through-void.rst  | 11 +
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../bugprone/casting-through-void.cpp | 18 
 8 files changed, 123 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/casting-through-void.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/casting-through-void.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 543c522899d7a52..7a910037368c832 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -16,6 +16,7 @@
 #include "BadSignalToKillThreadCheck.h"
 #include "BoolPointerImplicitConversionCheck.h"
 #include "BranchCloneCheck.h"
+#include "CastingThroughVoidCheck.h"
 #include "ComparePointerToMemberVirtualFunctionCheck.h"
 #include "CopyConstructorInitCheck.h"
 #include "DanglingHandleCheck.h"
@@ -104,6 +105,8 @@ class BugproneModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "bugprone-bool-pointer-implicit-conversion");
 CheckFactories.registerCheck("bugprone-branch-clone");
+CheckFactories.registerCheck(
+"bugprone-casting-through-void");
 CheckFactories.registerCheck(
 "bugprone-compare-pointer-to-member-virtual-function");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 0df9e439b715e5a..d443fd8d1452f16 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangTidyBugproneModule
   BoolPointerImplicitConversionCheck.cpp
   BranchCloneCheck.cpp
   BugproneTidyModule.cpp
+  CastingThroughVoidCheck.cpp
   ComparePointerToMemberVirtualFunctionCheck.cpp
   CopyConstructorInitCheck.cpp
   DanglingHandleCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
new file mode 100644
index 000..7b9cd7dd51fc47f
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
@@ -0,0 +1,46 @@
+//===--- CastingThroughVoidCheck.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 "CastingThroughVoidCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/StringSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void CastingThroughVoidCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  explicitCastExpr(
+  hasDestinationType(qualType(pointsTo(qualType(unless(voidType()
+ .bind("target_type")),
+  hasSourceExpression(
+  explicitCastExpr(hasSourceExpression(expr(
+   hasType(qualType().bind("source_type",
+   hasDestinationType(pointsTo(voidType())
+  .bind("cast"),
+  this);
+}
+
+void CastingThroughVoidCheck::check(const MatchFinder::MatchResult &Result) {
+  ASTContext *Context = Result.Context;
+  const auto *CE = Result.Nodes.getNodeAs("cast");
+  const auto *TT = Result.Nodes.getNodeAs("target_type");
+  const auto *ST = Result.Nodes.getNodeAs("source_type");
+  if (Context->hasSameType(*TT, *ST))
+return;
+  diag(CE->getSourceRange().getBegin(), "do not cast %0 to %1 through void *",
+   DiagnosticIDs::Level::Warning)
+  << ST->getAsString() << TT->getAsString();
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bu

[clang] [clang-tidy]Add new check bugprone-casting-through-void (PR #69465)

2023-10-20 Thread Congcong Cai via cfe-commits

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

>From 627f68e57b2526fb72285ef4831fc3c02a6ee6d0 Mon Sep 17 00:00:00 2001
From: Congcong Cai 
Date: Wed, 18 Oct 2023 08:47:02 +0800
Subject: [PATCH 1/8] [clang-tidy]Add new check bugprone-casting-through-void

Fixes: #68532
---
 .../bugprone/BugproneTidyModule.cpp   |  3 ++
 .../clang-tidy/bugprone/CMakeLists.txt|  1 +
 .../bugprone/CastingThroughVoidCheck.cpp  | 46 +++
 .../bugprone/CastingThroughVoidCheck.h| 37 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 +++
 .../checks/bugprone/casting-through-void.rst  | 11 +
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../bugprone/casting-through-void.cpp | 18 
 8 files changed, 123 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/bugprone/casting-through-void.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/bugprone/casting-through-void.cpp

diff --git a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp 
b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
index 543c522899d7a52..7a910037368c832 100644
--- a/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/BugproneTidyModule.cpp
@@ -16,6 +16,7 @@
 #include "BadSignalToKillThreadCheck.h"
 #include "BoolPointerImplicitConversionCheck.h"
 #include "BranchCloneCheck.h"
+#include "CastingThroughVoidCheck.h"
 #include "ComparePointerToMemberVirtualFunctionCheck.h"
 #include "CopyConstructorInitCheck.h"
 #include "DanglingHandleCheck.h"
@@ -104,6 +105,8 @@ class BugproneModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "bugprone-bool-pointer-implicit-conversion");
 CheckFactories.registerCheck("bugprone-branch-clone");
+CheckFactories.registerCheck(
+"bugprone-casting-through-void");
 CheckFactories.registerCheck(
 "bugprone-compare-pointer-to-member-virtual-function");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
index 0df9e439b715e5a..d443fd8d1452f16 100644
--- a/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/bugprone/CMakeLists.txt
@@ -11,6 +11,7 @@ add_clang_library(clangTidyBugproneModule
   BoolPointerImplicitConversionCheck.cpp
   BranchCloneCheck.cpp
   BugproneTidyModule.cpp
+  CastingThroughVoidCheck.cpp
   ComparePointerToMemberVirtualFunctionCheck.cpp
   CopyConstructorInitCheck.cpp
   DanglingHandleCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
new file mode 100644
index 000..7b9cd7dd51fc47f
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/bugprone/CastingThroughVoidCheck.cpp
@@ -0,0 +1,46 @@
+//===--- CastingThroughVoidCheck.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 "CastingThroughVoidCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchFinder.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "llvm/ADT/StringSet.h"
+
+using namespace clang::ast_matchers;
+
+namespace clang::tidy::bugprone {
+
+void CastingThroughVoidCheck::registerMatchers(MatchFinder *Finder) {
+  Finder->addMatcher(
+  explicitCastExpr(
+  hasDestinationType(qualType(pointsTo(qualType(unless(voidType()
+ .bind("target_type")),
+  hasSourceExpression(
+  explicitCastExpr(hasSourceExpression(expr(
+   hasType(qualType().bind("source_type",
+   hasDestinationType(pointsTo(voidType())
+  .bind("cast"),
+  this);
+}
+
+void CastingThroughVoidCheck::check(const MatchFinder::MatchResult &Result) {
+  ASTContext *Context = Result.Context;
+  const auto *CE = Result.Nodes.getNodeAs("cast");
+  const auto *TT = Result.Nodes.getNodeAs("target_type");
+  const auto *ST = Result.Nodes.getNodeAs("source_type");
+  if (Context->hasSameType(*TT, *ST))
+return;
+  diag(CE->getSourceRange().getBegin(), "do not cast %0 to %1 through void *",
+   DiagnosticIDs::Level::Warning)
+  << ST->getAsString() << TT->getAsString();
+}
+
+} // namespace clang::tidy::bugprone
diff --git a/clang-tools-extra/clang-tidy/bu

[clang-tools-extra] [run-clang-tidy, clang-tidy-diff] Accept directory as value for -export-fixes (PR #69453)

2023-10-20 Thread via cfe-commits

dyung wrote:

Hi @amgebauer, not sure if you got the notification, but your change seems to 
be causing a test failure on two build bots, any idea why?
https://lab.llvm.org/buildbot/#/builders/139/builds/51852
https://lab.llvm.org/buildbot/#/builders/247/builds/10286

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


[clang] b9dae2f - [Clang][SVE2.1] Add builtins for svrevd

2023-10-20 Thread Caroline Concatto via cfe-commits

Author: Caroline Concatto
Date: 2023-10-20T08:35:13Z
New Revision: b9dae2fa22d3dd4d5c454c2b167428b027d7bc12

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

LOG: [Clang][SVE2.1] Add builtins for svrevd

As described in: https://github.com/ARM-software/acle/pull/257

Patch by: Rosie Sumpter 

Reviewed By: dtemirbulatov

Differential Revision: https://reviews.llvm.org/D151709

Added: 
clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c

Modified: 
clang/include/clang/Basic/arm_sve.td

Removed: 




diff  --git a/clang/include/clang/Basic/arm_sve.td 
b/clang/include/clang/Basic/arm_sve.td
index a1585443e5fd229..b5baafedd139602 100644
--- a/clang/include/clang/Basic/arm_sve.td
+++ b/clang/include/clang/Basic/arm_sve.td
@@ -1977,4 +1977,6 @@ def SVPSEL_S : SInst<"svpsel_lane_b32", "PPPm", "Pi", 
MergeNone, "", [], []>;
 def SVPSEL_D : SInst<"svpsel_lane_b64", "PPPm", "Pl", MergeNone, "", [], []>;
 
 def SVCNTP_COUNT : SInst<"svcntp_{d}", "n}i", "QcQsQiQl", MergeNone, 
"aarch64_sve_cntp_{d}", [IsOverloadNone], [ImmCheck<1, ImmCheck2_4_Mul2>]>;
+
+defm SVREVD : SInstZPZ<"svrevd", "csilUcUsUiUl", "aarch64_sve_revd">;
 }

diff  --git a/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c 
b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
new file mode 100644
index 000..14d515e6d12bb70
--- /dev/null
+++ b/clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
@@ -0,0 +1,390 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - %s | 
FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - -x c++ %s | 
FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - -x c++ %s | 
FileCheck %s -check-prefix=CPP-CHECK
+
+#include 
+
+#ifdef SVE_OVERLOADED_FORMS
+// A simple used,unused... macro, long enough to represent any SVE builtin.
+#define SVE_ACLE_FUNC(A1, A2_UNUSED, A3, A4_UNUSED) A1##A3
+#else
+#define SVE_ACLE_FUNC(A1, A2, A3, A4) A1##A2##A3##A4
+#endif
+
+// CHECK-LABEL: @test_svrevd_s8_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv16i8( zeroinitializer,  [[PG:%.*]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP0]]
+//
+// CPP-CHECK-LABEL: @_Z16test_svrevd_s8_zu10__SVBool_tu10__SVInt8_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv16i8( zeroinitializer,  [[PG:%.*]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP0]]
+//
+svint8_t test_svrevd_s8_z(svbool_t pg, svint8_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s8, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s16_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv8i1( [[PG:%.*]])
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv8i16( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP1]]
+//
+// CPP-CHECK-LABEL: @_Z17test_svrevd_s16_zu10__SVBool_tu11__SVInt16_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv8i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv8i16( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP1]]
+//
+svint16_t test_svrevd_s16_z(svbool_t pg, svint16_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s16, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s32_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv4i1( [[PG:%.*]])
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv4i32( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP1]]
+//
+// CPP-CHECK-LABEL: @_Z17test_svrevd_s32_zu10__SVBool_tu11__SVInt32_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  
@llvm.aarch64.sve.convert.from.svbool.nxv4i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:[[TMP1:%.*]] = tail call  
@llvm.aarch64.sve.revd.nxv4i32( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP1]]
+//
+svint32_t test_svrevd_s32_z(svbool_t pg, svint32_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s32, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s64_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%

[PATCH] D151709: [Clang][SVE2.1] Add builtins for svrevd

2023-10-20 Thread Caroline via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb9dae2fa22d3: [Clang][SVE2.1] Add builtins for svrevd 
(authored by CarolineConcatto).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151709

Files:
  clang/include/clang/Basic/arm_sve.td
  clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c

Index: clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
===
--- /dev/null
+++ clang/test/CodeGen/aarch64-sve2-intrinsics/acle_sve2_revd.c
@@ -0,0 +1,390 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
+// REQUIRES: aarch64-registered-target
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - %s | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK
+// RUN: %clang_cc1 -DSVE_OVERLOADED_FORMS -triple aarch64-none-linux-gnu \
+// RUN:   -target-feature +sve2p1 -S -O1 -Werror -emit-llvm -o - -x c++ %s | FileCheck %s -check-prefix=CPP-CHECK
+
+#include 
+
+#ifdef SVE_OVERLOADED_FORMS
+// A simple used,unused... macro, long enough to represent any SVE builtin.
+#define SVE_ACLE_FUNC(A1, A2_UNUSED, A3, A4_UNUSED) A1##A3
+#else
+#define SVE_ACLE_FUNC(A1, A2, A3, A4) A1##A2##A3##A4
+#endif
+
+// CHECK-LABEL: @test_svrevd_s8_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv16i8( zeroinitializer,  [[PG:%.*]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP0]]
+//
+// CPP-CHECK-LABEL: @_Z16test_svrevd_s8_zu10__SVBool_tu10__SVInt8_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv16i8( zeroinitializer,  [[PG:%.*]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP0]]
+//
+svint8_t test_svrevd_s8_z(svbool_t pg, svint8_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s8, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s16_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv8i1( [[PG:%.*]])
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv8i16( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP1]]
+//
+// CPP-CHECK-LABEL: @_Z17test_svrevd_s16_zu10__SVBool_tu11__SVInt16_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv8i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv8i16( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP1]]
+//
+svint16_t test_svrevd_s16_z(svbool_t pg, svint16_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s16, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s32_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv4i1( [[PG:%.*]])
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv4i32( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP1]]
+//
+// CPP-CHECK-LABEL: @_Z17test_svrevd_s32_zu10__SVBool_tu11__SVInt32_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv4i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv4i32( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP1]]
+//
+svint32_t test_svrevd_s32_z(svbool_t pg, svint32_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s32, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_s64_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv2i1( [[PG:%.*]])
+// CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv2i64( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP1]]
+//
+// CPP-CHECK-LABEL: @_Z17test_svrevd_s64_zu10__SVBool_tu11__SVInt64_t(
+// CPP-CHECK-NEXT:  entry:
+// CPP-CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.convert.from.svbool.nxv2i1( [[PG:%.*]])
+// CPP-CHECK-NEXT:[[TMP1:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv2i64( zeroinitializer,  [[TMP0]],  [[OP:%.*]])
+// CPP-CHECK-NEXT:ret  [[TMP1]]
+//
+svint64_t test_svrevd_s64_z(svbool_t pg, svint64_t op) {
+  return SVE_ACLE_FUNC(svrevd, _s64, _z, )(pg, op);
+}
+
+// CHECK-LABEL: @test_svrevd_u8_z(
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:[[TMP0:%.*]] = tail call  @llvm.aarch64.sve.revd.nxv16i8( zeroinitializer,  [[PG:%.*]],  [[OP:%.*]])
+// CHECK-NEXT:ret  [[TMP0]]
+//
+// CPP-CHECK-LABEL: @_Z16test_

[clang] [X86] Add regcall4 attribute to make a specific function respect regc… (PR #69628)

2023-10-20 Thread via cfe-commits

https://github.com/yubingex007-a11y updated 
https://github.com/llvm/llvm-project/pull/69628

>From 786b954e621ac53902ceff4640d1372ef1652699 Mon Sep 17 00:00:00 2001
From: Bing1 Yu 
Date: Fri, 20 Oct 2023 02:33:35 +0800
Subject: [PATCH 1/4] [X86] Add regcall4 attribute to make a specific function
 respect regcall ABIv4

---
 clang/include/clang/Basic/Attr.td | 5 +
 clang/lib/AST/TypePrinter.cpp | 1 +
 clang/lib/CodeGen/CGCall.cpp  | 3 ++-
 clang/lib/CodeGen/CodeGenModule.cpp   | 3 +++
 clang/test/CodeGen/regcall.c  | 2 +-
 llvm/lib/Target/X86/X86CallingConv.td | 2 +-
 6 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 5486b36133755cc..54d6d0619223f98 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1524,6 +1524,11 @@ def RegCall : DeclOrTypeAttr {
   let Documentation = [RegCallDocs];
 }
 
+def RegCall4 : DeclOrTypeAttr {
+  let Spellings = [GCC<"regcall4">, CustomKeyword<"__regcall4">];
+  let Documentation = [RegCallDocs];
+}
+
 def Final : InheritableAttr {
   let Spellings = [CustomKeyword<"final">, CustomKeyword<"sealed">];
   let Accessors = [Accessor<"isSpelledAsSealed", [CustomKeyword<"sealed">]>];
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index b9f6c0eeb450d2c..6ca95eefe4b0630 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -1861,6 +1861,7 @@ void TypePrinter::printAttributedAfter(const 
AttributedType *T,
   case attr::MSABI: OS << "ms_abi"; break;
   case attr::SysVABI: OS << "sysv_abi"; break;
   case attr::RegCall: OS << "regcall"; break;
+  case attr::RegCall4: OS << "regcall4"; break;
   case attr::Pcs: {
 OS << "pcs(";
QualType t = T->getEquivalentType();
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 150450e9165900f..82d25a98a271db9 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2458,7 +2458,8 @@ void CodeGenModule::ConstructAttributeList(StringRef Name,
   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-
   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
-
+  if (TargetDecl->hasAttr())
+FuncAttrs.addAttribute("regcall4");
   // Collect function IR attributes based on global settiings.
   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index b1a6683a66bd052..505167f5706fbaf 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2317,6 +2317,9 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
 return;
   }
 
+  if (D->hasAttr())
+B.addAttribute("regcall4");
+
   // Handle SME attributes that apply to function definitions,
   // rather than to function prototypes.
   if (D->hasAttr())
diff --git a/clang/test/CodeGen/regcall.c b/clang/test/CodeGen/regcall.c
index f10da87353fa114..dc37c0545f27389 100644
--- a/clang/test/CodeGen/regcall.c
+++ b/clang/test/CodeGen/regcall.c
@@ -9,7 +9,7 @@ void __regcall v1(int a, int b) {}
 // X86: define dso_local x86_regcallcc void @__regcall3__v1(i32 inreg noundef 
%a, i32 inreg noundef %b)
 // X64: define dso_local x86_regcallcc void @__regcall3__v1(i32 noundef %a, 
i32 noundef %b)
 
-void __attribute__((regcall)) v1b(int a, int b) {}
+void __attribute__((regcall4)) v1b(int a, int b) {}
 // X86: define dso_local x86_regcallcc void @__regcall3__v1b(i32 inreg noundef 
%a, i32 inreg noundef %b)
 // X64: define dso_local x86_regcallcc void @__regcall3__v1b(i32 noundef %a, 
i32 noundef %b)
 
diff --git a/llvm/lib/Target/X86/X86CallingConv.td 
b/llvm/lib/Target/X86/X86CallingConv.td
index 19a295cd109627e..df9f48c777cfa8b 100644
--- a/llvm/lib/Target/X86/X86CallingConv.td
+++ b/llvm/lib/Target/X86/X86CallingConv.td
@@ -25,7 +25,7 @@ class CCIfNotSubtarget
 
 /// CCIfRegCallv4 - Match if RegCall ABIv4 is respected.
 class CCIfRegCallv4
-: 
CCIf<"State.getMachineFunction().getFunction().getParent()->getModuleFlag(\"RegCallv4\")!=nullptr",
+: 
CCIf<"State.getMachineFunction().getFunction().getParent()->getModuleFlag(\"RegCallv4\")!=nullptr
 || State.getMachineFunction().getFunction().hasFnAttribute("regcall4")",
A>;
 
 /// CCIfIsVarArgOnWin - Match if isVarArg on Windows 32bits.

>From ed514a91cdc693242edd01356b6786b6e70d2343 Mon Sep 17 00:00:00 2001
From: Bing1 Yu 
Date: Fri, 20 Oct 2023 03:09:24 +0800
Subject: [PATCH 2/4] fix

---
 clang/lib/CodeGen/CGCall.cpp  | 4 ++--
 clang/lib/Sema/SemaDeclAttr.cpp   | 3 +++
 llvm/lib/Target/X86/X86CallingConv.td | 2 +-
 3 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 82d25a98a271db9..140091bbaac2a89 100644
--- a/clang/lib/CodeGen/CGCall.cpp

[clang] [X86] Add regcall4 attribute to make a specific function respect regc… (PR #69628)

2023-10-20 Thread via cfe-commits


@@ -9347,6 +9352,7 @@ ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 
const ParsedAttr &AL,
   case ParsedAttr::AT_ThisCall:
   case ParsedAttr::AT_Pascal:
   case ParsedAttr::AT_RegCall:
+  //case ParsedAttr::AT_RegCall4:

yubingex007-a11y wrote:

@mikerice1969 hi, if i uncomment here, and delete L9648-9650, regcall4 won't be 
added into Decl because hasDeclarator(D) is true:
```
static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
  if (hasDeclarator(D)) return;
```

do you know why this happened?

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -37,6 +37,25 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+bool ambiguous(A a, B b) { return a == b; } // This equality is now 
ambiguous in C++20.
+
+template bool operator!=(const P&, const S&);
+bool fine(A a, B b) { return a == b; } // Ok. Found a matching operator!=.
+
+  To reduce widespread breakages, as an extension, clang would accept this 
with a

ilya-biryukov wrote:

NIT: s/clang/Clang to match the rest of the document.

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

https://github.com/Venyla created 
https://github.com/llvm/llvm-project/pull/69693

[Screencast from 2023-10-16 
15-34-29.webm](https://github.com/sa-concept-refactoring/llvm-project/assets/7629727/bd2c8790-c40f-4834-8523-6d16fca0d498)

https://github.com/llvm/llvm-project/assets/6904387/95fa5ab1-efa0-4236-b4e4-3bc99f03b691"/>


>From 8629cfd872e1ec437d661dacfcb7dd28b4bd4834 Mon Sep 17 00:00:00 2001
From: Vina Zahnd 
Date: Fri, 20 Oct 2023 10:01:54 +0200
Subject: [PATCH] [clangd] Add tweak to inline concept requirements

Co-authored-by: Jeremy Stucki 
---
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../tweaks/InlineConceptRequirement.cpp   | 262 ++
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../tweaks/InlineConceptRequirement.cpp   |  94 +++
 4 files changed, 358 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/InlineConceptRequirement.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 526a073f619ea34..b01053faf738a90 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ExpandMacro.cpp
   ExtractFunction.cpp
   ExtractVariable.cpp
+  InlineConceptRequirement.cpp
   MemberwiseConstructor.cpp
   ObjCLocalizeStringLiteral.cpp
   ObjCMemberwiseInitializer.cpp
diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
new file mode 100644
index 000..b6c0237703c3474
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
@@ -0,0 +1,262 @@
+//===--- InlineConceptRequirement.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Inlines a concept requirement.
+///
+/// Before:
+///   template  void f(T) requires foo {}
+///^^
+/// After:
+///   template  void f(T) {}
+class InlineConceptRequirement : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+  auto title() const -> std::string override {
+return "Inline concept requirement";
+  }
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  const ConceptSpecializationExpr *ConceptSpecializationExpression;
+  const TemplateTypeParmDecl *TemplateTypeParameterDeclaration;
+  const syntax::Token *RequiresToken;
+
+  static auto getTemplateParameterIndexOfTemplateArgument(
+  const TemplateArgument &TemplateArgument) -> std::optional;
+  auto generateRequiresReplacement(ASTContext &)
+  -> std::variant;
+  auto generateRequiresTokenReplacement(const syntax::TokenBuffer &)
+  -> tooling::Replacement;
+  auto generateTemplateParameterReplacement(ASTContext &Context)
+  -> tooling::Replacement;
+
+  static auto findToken(const ParsedAST *, const SourceRange &,
+const tok::TokenKind) -> const syntax::Token *;
+
+  template 
+  static auto findNode(const SelectionTree::Node &Root)
+  -> std::tuple;
+
+  template 
+  static auto findExpression(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+
+  template 
+  static auto findDeclaration(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+};
+
+REGISTER_TWEAK(InlineConceptRequirement)
+
+auto InlineConceptRequirement::prepare(const Selection &Inputs) -> bool {
+  // Check if C++ version is 20 or higher
+  if (!Inputs.AST->getLangOpts().CPlusPlus20)
+return false;
+
+  const auto *Root = Inputs.ASTSelection.commonAncestor();
+  if (!Root)
+return false;
+
+  const SelectionTree::Node *ConceptSpecializationExpressionTreeNode;
+  std::tie(ConceptSpecializationExpression,
+   ConceptSpecializationExpressionTreeNode) =
+  findExpression(*Root);
+  if (!ConceptSpecializationExpression)
+return false;
+
+  // Only allow concepts that are direct children of 

[clang] [X86] Add regcall4 attribute to make a specific function respect regc… (PR #69628)

2023-10-20 Thread via cfe-commits

https://github.com/yubingex007-a11y updated 
https://github.com/llvm/llvm-project/pull/69628

>From 786b954e621ac53902ceff4640d1372ef1652699 Mon Sep 17 00:00:00 2001
From: Bing1 Yu 
Date: Fri, 20 Oct 2023 02:33:35 +0800
Subject: [PATCH 1/5] [X86] Add regcall4 attribute to make a specific function
 respect regcall ABIv4

---
 clang/include/clang/Basic/Attr.td | 5 +
 clang/lib/AST/TypePrinter.cpp | 1 +
 clang/lib/CodeGen/CGCall.cpp  | 3 ++-
 clang/lib/CodeGen/CodeGenModule.cpp   | 3 +++
 clang/test/CodeGen/regcall.c  | 2 +-
 llvm/lib/Target/X86/X86CallingConv.td | 2 +-
 6 files changed, 13 insertions(+), 3 deletions(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index 5486b36133755cc..54d6d0619223f98 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1524,6 +1524,11 @@ def RegCall : DeclOrTypeAttr {
   let Documentation = [RegCallDocs];
 }
 
+def RegCall4 : DeclOrTypeAttr {
+  let Spellings = [GCC<"regcall4">, CustomKeyword<"__regcall4">];
+  let Documentation = [RegCallDocs];
+}
+
 def Final : InheritableAttr {
   let Spellings = [CustomKeyword<"final">, CustomKeyword<"sealed">];
   let Accessors = [Accessor<"isSpelledAsSealed", [CustomKeyword<"sealed">]>];
diff --git a/clang/lib/AST/TypePrinter.cpp b/clang/lib/AST/TypePrinter.cpp
index b9f6c0eeb450d2c..6ca95eefe4b0630 100644
--- a/clang/lib/AST/TypePrinter.cpp
+++ b/clang/lib/AST/TypePrinter.cpp
@@ -1861,6 +1861,7 @@ void TypePrinter::printAttributedAfter(const 
AttributedType *T,
   case attr::MSABI: OS << "ms_abi"; break;
   case attr::SysVABI: OS << "sysv_abi"; break;
   case attr::RegCall: OS << "regcall"; break;
+  case attr::RegCall4: OS << "regcall4"; break;
   case attr::Pcs: {
 OS << "pcs(";
QualType t = T->getEquivalentType();
diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 150450e9165900f..82d25a98a271db9 100644
--- a/clang/lib/CodeGen/CGCall.cpp
+++ b/clang/lib/CodeGen/CGCall.cpp
@@ -2458,7 +2458,8 @@ void CodeGenModule::ConstructAttributeList(StringRef Name,
   // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-
   // * FunctionDecl attributes: __attribute__((no_builtin(...)))
   addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
-
+  if (TargetDecl->hasAttr())
+FuncAttrs.addAttribute("regcall4");
   // Collect function IR attributes based on global settiings.
   getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
 
diff --git a/clang/lib/CodeGen/CodeGenModule.cpp 
b/clang/lib/CodeGen/CodeGenModule.cpp
index b1a6683a66bd052..505167f5706fbaf 100644
--- a/clang/lib/CodeGen/CodeGenModule.cpp
+++ b/clang/lib/CodeGen/CodeGenModule.cpp
@@ -2317,6 +2317,9 @@ void 
CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
 return;
   }
 
+  if (D->hasAttr())
+B.addAttribute("regcall4");
+
   // Handle SME attributes that apply to function definitions,
   // rather than to function prototypes.
   if (D->hasAttr())
diff --git a/clang/test/CodeGen/regcall.c b/clang/test/CodeGen/regcall.c
index f10da87353fa114..dc37c0545f27389 100644
--- a/clang/test/CodeGen/regcall.c
+++ b/clang/test/CodeGen/regcall.c
@@ -9,7 +9,7 @@ void __regcall v1(int a, int b) {}
 // X86: define dso_local x86_regcallcc void @__regcall3__v1(i32 inreg noundef 
%a, i32 inreg noundef %b)
 // X64: define dso_local x86_regcallcc void @__regcall3__v1(i32 noundef %a, 
i32 noundef %b)
 
-void __attribute__((regcall)) v1b(int a, int b) {}
+void __attribute__((regcall4)) v1b(int a, int b) {}
 // X86: define dso_local x86_regcallcc void @__regcall3__v1b(i32 inreg noundef 
%a, i32 inreg noundef %b)
 // X64: define dso_local x86_regcallcc void @__regcall3__v1b(i32 noundef %a, 
i32 noundef %b)
 
diff --git a/llvm/lib/Target/X86/X86CallingConv.td 
b/llvm/lib/Target/X86/X86CallingConv.td
index 19a295cd109627e..df9f48c777cfa8b 100644
--- a/llvm/lib/Target/X86/X86CallingConv.td
+++ b/llvm/lib/Target/X86/X86CallingConv.td
@@ -25,7 +25,7 @@ class CCIfNotSubtarget
 
 /// CCIfRegCallv4 - Match if RegCall ABIv4 is respected.
 class CCIfRegCallv4
-: 
CCIf<"State.getMachineFunction().getFunction().getParent()->getModuleFlag(\"RegCallv4\")!=nullptr",
+: 
CCIf<"State.getMachineFunction().getFunction().getParent()->getModuleFlag(\"RegCallv4\")!=nullptr
 || State.getMachineFunction().getFunction().hasFnAttribute("regcall4")",
A>;
 
 /// CCIfIsVarArgOnWin - Match if isVarArg on Windows 32bits.

>From ed514a91cdc693242edd01356b6786b6e70d2343 Mon Sep 17 00:00:00 2001
From: Bing1 Yu 
Date: Fri, 20 Oct 2023 03:09:24 +0800
Subject: [PATCH 2/5] fix

---
 clang/lib/CodeGen/CGCall.cpp  | 4 ++--
 clang/lib/Sema/SemaDeclAttr.cpp   | 3 +++
 llvm/lib/Target/X86/X86CallingConv.td | 2 +-
 3 files changed, 6 insertions(+), 3 deletions(-)

diff --git a/clang/lib/CodeGen/CGCall.cpp b/clang/lib/CodeGen/CGCall.cpp
index 82d25a98a271db9..140091bbaac2a89 100644
--- a/clang/lib/CodeGen/CGCall.cpp

[clang] [X86] Add regcall4 attribute to make a specific function respect regcall ABIv4 (PR #69628)

2023-10-20 Thread via cfe-commits

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


[clang] [X86] Add regcall4 attribute to make a specific function respect regcall ABIv4 (PR #69628)

2023-10-20 Thread via cfe-commits

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


[clang] [X86] Add regcall4 attribute to make a specific function respect regcall ABIv4 (PR #69628)

2023-10-20 Thread via cfe-commits

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


[clang] [X86] Add regcall4 attribute to make a specific function respect regcall ABIv4 (PR #69628)

2023-10-20 Thread via cfe-commits

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -10085,10 +10085,14 @@ getImplicitObjectParamType(ASTContext &Context, const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
+static bool allowAmbiguityWithSelf(ASTContext &Context, const FunctionDecl *F1,

ilya-biryukov wrote:

Could you elaborate why `declaresSameEntity` is not enough and we need extra 
checks for parameter types?
I am asking because if it's not enough for regular functions, maybe there is a 
similar case for function templates.
And the name is a bit misleading as `F1` and `F2` can clearly be two different 
functions, so it is unclear what `self`  refers to.

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -37,6 +37,25 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+
+  .. code-block:: cpp
+
+struct P {};
+template bool operator==(const P&, const S&);
+
+struct A : public P {};
+struct B : public P {};
+
+bool ambiguous(A a, B b) { return a == b; } // This equality is now 
ambiguous in C++20.
+
+template bool operator!=(const P&, const S&);
+bool fine(A a, B b) { return a == b; } // Ok. Found a matching operator!=.
+
+  To reduce widespread breakages, as an extension, clang would accept this 
with a
+  ``-Wambiguous-reversed-operator`` warning.

ilya-biryukov wrote:

NIT: it reads as if it is a new warning, I suggest saying "Clang accepts this 
code with an existing warning -W"

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -7688,7 +7688,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)

ilya-biryukov wrote:

Is this a separate bug? Do you have a code example that manifests it 
independently?
I suggest to move this to a separate commit with its own test if it's not 
directly connected.

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


[clang] [X86] Add regcall4 attribute to make a specific function respect regcall ABIv4 (PR #69628)

2023-10-20 Thread via cfe-commits

yubingex007-a11y wrote:

there is question here should we really add a new calling conv CC_X86RegCall4 
in CFE.
currently i let regcall4 attr reuse CC_X86RegCall instead of creating 
CC_X86RegCall4 . 

@mikerice1969 

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


[clang-tools-extra] [run-clang-tidy, clang-tidy-diff] Accept directory as value for -export-fixes (PR #69453)

2023-10-20 Thread Amadeus Gebauer via cfe-commits

amgebauer wrote:

I have an idea about the reason. I will push a fix in a few moments. Thank you 
for the hint

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

https://github.com/Venyla updated 
https://github.com/llvm/llvm-project/pull/69693

>From 9e2a80fd1a7ae61ce71ba0caabd2c6a88c662889 Mon Sep 17 00:00:00 2001
From: Vina Zahnd 
Date: Fri, 20 Oct 2023 10:01:54 +0200
Subject: [PATCH] [clangd] Add tweak to inline concept requirements

Co-authored-by: Jeremy Stucki 
---
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../tweaks/InlineConceptRequirement.cpp   | 262 ++
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../tweaks/InlineConceptRequirement.cpp   |  94 +++
 4 files changed, 358 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/InlineConceptRequirement.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 526a073f619ea34..b01053faf738a90 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ExpandMacro.cpp
   ExtractFunction.cpp
   ExtractVariable.cpp
+  InlineConceptRequirement.cpp
   MemberwiseConstructor.cpp
   ObjCLocalizeStringLiteral.cpp
   ObjCMemberwiseInitializer.cpp
diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
new file mode 100644
index 000..b6c0237703c3474
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
@@ -0,0 +1,262 @@
+//===--- InlineConceptRequirement.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Inlines a concept requirement.
+///
+/// Before:
+///   template  void f(T) requires foo {}
+///^^
+/// After:
+///   template  void f(T) {}
+class InlineConceptRequirement : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+  auto title() const -> std::string override {
+return "Inline concept requirement";
+  }
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  const ConceptSpecializationExpr *ConceptSpecializationExpression;
+  const TemplateTypeParmDecl *TemplateTypeParameterDeclaration;
+  const syntax::Token *RequiresToken;
+
+  static auto getTemplateParameterIndexOfTemplateArgument(
+  const TemplateArgument &TemplateArgument) -> std::optional;
+  auto generateRequiresReplacement(ASTContext &)
+  -> std::variant;
+  auto generateRequiresTokenReplacement(const syntax::TokenBuffer &)
+  -> tooling::Replacement;
+  auto generateTemplateParameterReplacement(ASTContext &Context)
+  -> tooling::Replacement;
+
+  static auto findToken(const ParsedAST *, const SourceRange &,
+const tok::TokenKind) -> const syntax::Token *;
+
+  template 
+  static auto findNode(const SelectionTree::Node &Root)
+  -> std::tuple;
+
+  template 
+  static auto findExpression(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+
+  template 
+  static auto findDeclaration(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+};
+
+REGISTER_TWEAK(InlineConceptRequirement)
+
+auto InlineConceptRequirement::prepare(const Selection &Inputs) -> bool {
+  // Check if C++ version is 20 or higher
+  if (!Inputs.AST->getLangOpts().CPlusPlus20)
+return false;
+
+  const auto *Root = Inputs.ASTSelection.commonAncestor();
+  if (!Root)
+return false;
+
+  const SelectionTree::Node *ConceptSpecializationExpressionTreeNode;
+  std::tie(ConceptSpecializationExpression,
+   ConceptSpecializationExpressionTreeNode) =
+  findExpression(*Root);
+  if (!ConceptSpecializationExpression)
+return false;
+
+  // Only allow concepts that are direct children of function template
+  // declarations or function declarations. This excludes conjunctions of
+  // concepts which are not handled.
+  const auto *ParentDeclaration =
+  ConceptSpecializationExpressionTreeNode->Parent->ASTNode.get();
+  if (!is

[clang] [InstCombine] Add combines/simplifications for `llvm.ptrmask` (PR #67166)

2023-10-20 Thread Yingwei Zheng via cfe-commits


@@ -6411,6 +6411,41 @@ static Value *simplifyBinaryIntrinsic(Function *F, Value 
*Op0, Value *Op1,
   return Constant::getNullValue(ReturnType);
 break;
   }
+  case Intrinsic::ptrmask: {
+if (isa(Op0) || isa(Op1))
+  return PoisonValue::get(Op0->getType());
+
+// NOTE: We can't apply this simplifications based on the value of Op1
+// because we need to preserve provenance.
+if (Q.isUndefValue(Op0) || match(Op0, m_Zero()))
+  return Constant::getNullValue(Op0->getType());
+
+if (Op1->getType()->getScalarSizeInBits() ==
+Q.DL.getPointerTypeSizeInBits(Op0->getType())) {
+  if (match(Op1, m_PtrToInt(m_Specific(Op0
+return Op0;
+
+  // NOTE: We may have attributes associated with the return value of the
+  // llvm.ptrmask intrinsic that will be lost when we just return the
+  // operand. We should try to preserve them.
+  if (match(Op1, m_AllOnes()) || Q.isUndefValue(Op1))
+return Op0;
+
+  Constant *C;
+  if (match(Op1, m_ImmConstant(C))) {
+KnownBits PtrKnown =
+computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);

dtcxzyw wrote:

```suggestion
KnownBits PtrKnown = computeKnownBits(Op0, /*Depth=*/0, Q);
```
See also new ValueTracking helper functions introduced by 
be57381a4a08b0b6a89d5b5fdec0880b202e99f4.

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

https://github.com/Venyla updated 
https://github.com/llvm/llvm-project/pull/69693

>From 2b1f56a758d397649c94717f4a030c04a532bde7 Mon Sep 17 00:00:00 2001
From: Vina Zahnd 
Date: Fri, 20 Oct 2023 10:01:54 +0200
Subject: [PATCH] [clangd] Add tweak to inline concept requirements

Co-authored-by: Jeremy Stucki 
---
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../tweaks/InlineConceptRequirement.cpp   | 262 ++
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../tweaks/InlineConceptRequirement.cpp   |  94 +++
 4 files changed, 358 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/InlineConceptRequirement.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 526a073f619ea34..b01053faf738a90 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ExpandMacro.cpp
   ExtractFunction.cpp
   ExtractVariable.cpp
+  InlineConceptRequirement.cpp
   MemberwiseConstructor.cpp
   ObjCLocalizeStringLiteral.cpp
   ObjCMemberwiseInitializer.cpp
diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
new file mode 100644
index 000..b6c0237703c3474
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
@@ -0,0 +1,262 @@
+//===--- InlineConceptRequirement.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Inlines a concept requirement.
+///
+/// Before:
+///   template  void f(T) requires foo {}
+///^^
+/// After:
+///   template  void f(T) {}
+class InlineConceptRequirement : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+  auto title() const -> std::string override {
+return "Inline concept requirement";
+  }
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  const ConceptSpecializationExpr *ConceptSpecializationExpression;
+  const TemplateTypeParmDecl *TemplateTypeParameterDeclaration;
+  const syntax::Token *RequiresToken;
+
+  static auto getTemplateParameterIndexOfTemplateArgument(
+  const TemplateArgument &TemplateArgument) -> std::optional;
+  auto generateRequiresReplacement(ASTContext &)
+  -> std::variant;
+  auto generateRequiresTokenReplacement(const syntax::TokenBuffer &)
+  -> tooling::Replacement;
+  auto generateTemplateParameterReplacement(ASTContext &Context)
+  -> tooling::Replacement;
+
+  static auto findToken(const ParsedAST *, const SourceRange &,
+const tok::TokenKind) -> const syntax::Token *;
+
+  template 
+  static auto findNode(const SelectionTree::Node &Root)
+  -> std::tuple;
+
+  template 
+  static auto findExpression(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+
+  template 
+  static auto findDeclaration(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+};
+
+REGISTER_TWEAK(InlineConceptRequirement)
+
+auto InlineConceptRequirement::prepare(const Selection &Inputs) -> bool {
+  // Check if C++ version is 20 or higher
+  if (!Inputs.AST->getLangOpts().CPlusPlus20)
+return false;
+
+  const auto *Root = Inputs.ASTSelection.commonAncestor();
+  if (!Root)
+return false;
+
+  const SelectionTree::Node *ConceptSpecializationExpressionTreeNode;
+  std::tie(ConceptSpecializationExpression,
+   ConceptSpecializationExpressionTreeNode) =
+  findExpression(*Root);
+  if (!ConceptSpecializationExpression)
+return false;
+
+  // Only allow concepts that are direct children of function template
+  // declarations or function declarations. This excludes conjunctions of
+  // concepts which are not handled.
+  const auto *ParentDeclaration =
+  ConceptSpecializationExpressionTreeNode->Parent->ASTNode.get();
+  if (!is

[clang] [clang] Correct end for the `CastOperation.OpRange` (PR #69480)

2023-10-20 Thread Botond István Horváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/69480

From f75c2e75042d6d8f5a093967a56f3f59d7e541f7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Wed, 18 Oct 2023 18:05:01 +0200
Subject: [PATCH 1/3] Correct end for the CastOperation.OpRange

Set the correct end for the CastOperation.OpRange in CXXFunctionalCastExpr. Now 
it is the closing bracket's location instead of the parameter's location.
---
 clang/lib/Sema/SemaCast.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index 98b5879456e2175..87e6d1a2198fcea 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -3362,7 +3362,7 @@ ExprResult 
Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
   CastOperation Op(*this, Type, CastExpr);
   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
-  Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
+  Op.OpRange = SourceRange(Op.DestRange.getBegin(), RPLoc);
 
   Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
   if (Op.SrcExpr.isInvalid())

From c5b49768eaa4f4ceab110a9fc35a9fa0924409f3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Thu, 19 Oct 2023 13:47:47 +0200
Subject: [PATCH 2/3] Added a test to misc-source-ranges.cpp

---
 clang/test/Misc/misc-source-ranges.cpp | 8 +++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/test/Misc/misc-source-ranges.cpp 
b/clang/test/Misc/misc-source-ranges.cpp
index 7a9d9d057dac407..5bc50f7a4281072 100644
--- a/clang/test/Misc/misc-source-ranges.cpp
+++ b/clang/test/Misc/misc-source-ranges.cpp
@@ -1,7 +1,13 @@
-// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 
2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info 
-Wcast-function-type-strict %s 2>&1 | FileCheck %s
 
 struct S {
   char a : 12 - 12;
 };
 // CHECK: misc-source-ranges.cpp:[[@LINE-2]]:8:{[[@LINE-2]]:12-[[@LINE-2]]:19}
 
+using fun = long(*)(int&);
+fun foo(){
+  long (*f_ptr)(const int&);
+  return fun(f_ptr);
+}
+// CHECK: misc-source-ranges.cpp:[[@LINE-2]]:10:{[[@LINE-2]]:10-[[@LINE-2]]:20}

From bc65adadd2cb605b5655223a6781de746d534b2d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 11:12:59 +0200
Subject: [PATCH 3/3] Update ReleaseNotes.rst

---
 clang/docs/ReleaseNotes.rst | 19 +++
 1 file changed, 19 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index eee48431d716878..4b67a5dce0945d3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -326,6 +326,25 @@ Improvements to Clang's diagnostics
 - Clang now always diagnoses when using non-standard layout types in 
``offsetof`` .
   (`#64619: `_)
 
+- When describing a warning/error in a function-style type converson clang 
underscored only until
+  the end of the expression we convert from. Now clang underscores the until 
the closing bracket.
+
+  Before:
+
+  .. code-block:: text
+
+warning: cast from 'long (*)(const int &)' to 'decltype(fun_ptr)' (aka 
'long (*)(int &)') converts to incompatible function type 
[-Wcast-function-type-strict]
+24 | return decltype(fun_ptr)( f_ptr /*comment*/);
+   |^~~~
+
+  After:
+
+  .. code-block:: text
+
+warning: cast from 'long (*)(const int &)' to 'decltype(fun_ptr)' (aka 
'long (*)(int &)') converts to incompatible function type 
[-Wcast-function-type-strict]
+24 | return decltype(fun_ptr)( f_ptr /*comment*/);
+   |^
+
 Bug Fixes in This Version
 -
 - Fixed an issue where a class template specialization whose declaration is

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


[clang-tools-extra] [clang] Correct end for the `CastOperation.OpRange` (PR #69480)

2023-10-20 Thread Botond István Horváth via cfe-commits

https://github.com/HoBoIs updated 
https://github.com/llvm/llvm-project/pull/69480

From f75c2e75042d6d8f5a093967a56f3f59d7e541f7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Wed, 18 Oct 2023 18:05:01 +0200
Subject: [PATCH 1/3] Correct end for the CastOperation.OpRange

Set the correct end for the CastOperation.OpRange in CXXFunctionalCastExpr. Now 
it is the closing bracket's location instead of the parameter's location.
---
 clang/lib/Sema/SemaCast.cpp | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaCast.cpp b/clang/lib/Sema/SemaCast.cpp
index 98b5879456e2175..87e6d1a2198fcea 100644
--- a/clang/lib/Sema/SemaCast.cpp
+++ b/clang/lib/Sema/SemaCast.cpp
@@ -3362,7 +3362,7 @@ ExprResult 
Sema::BuildCXXFunctionalCastExpr(TypeSourceInfo *CastTypeInfo,
   assert(LPLoc.isValid() && "List-initialization shouldn't get here.");
   CastOperation Op(*this, Type, CastExpr);
   Op.DestRange = CastTypeInfo->getTypeLoc().getSourceRange();
-  Op.OpRange = SourceRange(Op.DestRange.getBegin(), CastExpr->getEndLoc());
+  Op.OpRange = SourceRange(Op.DestRange.getBegin(), RPLoc);
 
   Op.CheckCXXCStyleCast(/*FunctionalCast=*/true, /*ListInit=*/false);
   if (Op.SrcExpr.isInvalid())

From c5b49768eaa4f4ceab110a9fc35a9fa0924409f3 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Thu, 19 Oct 2023 13:47:47 +0200
Subject: [PATCH 2/3] Added a test to misc-source-ranges.cpp

---
 clang/test/Misc/misc-source-ranges.cpp | 8 +++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/clang/test/Misc/misc-source-ranges.cpp 
b/clang/test/Misc/misc-source-ranges.cpp
index 7a9d9d057dac407..5bc50f7a4281072 100644
--- a/clang/test/Misc/misc-source-ranges.cpp
+++ b/clang/test/Misc/misc-source-ranges.cpp
@@ -1,7 +1,13 @@
-// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 
2>&1 | FileCheck %s
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info 
-Wcast-function-type-strict %s 2>&1 | FileCheck %s
 
 struct S {
   char a : 12 - 12;
 };
 // CHECK: misc-source-ranges.cpp:[[@LINE-2]]:8:{[[@LINE-2]]:12-[[@LINE-2]]:19}
 
+using fun = long(*)(int&);
+fun foo(){
+  long (*f_ptr)(const int&);
+  return fun(f_ptr);
+}
+// CHECK: misc-source-ranges.cpp:[[@LINE-2]]:10:{[[@LINE-2]]:10-[[@LINE-2]]:20}

From bc65adadd2cb605b5655223a6781de746d534b2d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Botond=20Istv=C3=A1n=20Horv=C3=A1th?=
 <56926027+hob...@users.noreply.github.com>
Date: Fri, 20 Oct 2023 11:12:59 +0200
Subject: [PATCH 3/3] Update ReleaseNotes.rst

---
 clang/docs/ReleaseNotes.rst | 19 +++
 1 file changed, 19 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index eee48431d716878..4b67a5dce0945d3 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -326,6 +326,25 @@ Improvements to Clang's diagnostics
 - Clang now always diagnoses when using non-standard layout types in 
``offsetof`` .
   (`#64619: `_)
 
+- When describing a warning/error in a function-style type converson clang 
underscored only until
+  the end of the expression we convert from. Now clang underscores the until 
the closing bracket.
+
+  Before:
+
+  .. code-block:: text
+
+warning: cast from 'long (*)(const int &)' to 'decltype(fun_ptr)' (aka 
'long (*)(int &)') converts to incompatible function type 
[-Wcast-function-type-strict]
+24 | return decltype(fun_ptr)( f_ptr /*comment*/);
+   |^~~~
+
+  After:
+
+  .. code-block:: text
+
+warning: cast from 'long (*)(const int &)' to 'decltype(fun_ptr)' (aka 
'long (*)(int &)') converts to incompatible function type 
[-Wcast-function-type-strict]
+24 | return decltype(fun_ptr)( f_ptr /*comment*/);
+   |^
+
 Bug Fixes in This Version
 -
 - Fixed an issue where a class template specialization whose declaration is

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


[clang] [clang]improve diagnosing redefined defaulted constructor with different exception specs (PR #69688)

2023-10-20 Thread Timm Baeder via cfe-commits


@@ -0,0 +1,9 @@
+// RUN: %clang_cc1 -fsyntax-only -verify -fcxx-exceptions -std=c++11 %s

tbaederr wrote:

There's a typo in the name of this file.

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


[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-20 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- 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_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);
+
+// When invalidating regions, we also have to follow that by invalidating the
+// corresponding custom data in the program state.
+template 
+ProgramStateRef
+removeInformationStoredForDeadInstances(const CallEvent *Call,
+ProgramStateRef State,
+ArrayRef Regions) {
+  // If we do not know anything about the call we shall not continue.
+  // If the call is happens within a system header it is implementation detail.
+  // We should not take it into consideration.
+  if (!Call || Call->isInSystemHeader())
+return State;
+
+  for (const MemRegion *Region : Regions)
+State = State->remove(Region);
+
+  return State;
+}
+
+template 
+void handleConstructorAndAssignment(const CallEvent &Call, CheckerContext &C,
+const SVal &ThisSVal) {

spaits wrote:

There is going to be an std::any checker. There is shared code between the two. 
The value constructors and assignment operators are handled the same way. My 
plan for later is to develop a something frameworkish to handle all union like 
types.

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


[clang] Use the correct namespace for looking up matching operator!= (PR #68922)

2023-10-20 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/68922

>From 0c71b6bdd557ff4b9ad9a4ec4f0919e3460596b0 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 12 Oct 2023 21:35:52 +0200
Subject: [PATCH 1/5] Find opertor!= in the correct namespace

---
 clang/lib/Sema/SemaOverload.cpp   |  7 +-
 .../over.match.oper/p3-2a.cpp | 24 +++
 2 files changed, 25 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index ce78994e6553814..e1e0b4a888e49fa 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -960,12 +960,7 @@ static bool shouldAddReversedEqEq(Sema &S, SourceLocation 
OpLoc,
 return true;
   }
   // Otherwise the search scope is the namespace scope of which F is a member.
-  LookupResult NonMembers(S, NotEqOp, OpLoc,
-  Sema::LookupNameKind::LookupOperatorName);
-  S.LookupName(NonMembers,
-   S.getScopeForContext(EqFD->getEnclosingNamespaceContext()));
-  NonMembers.suppressAccessDiagnostics();
-  for (NamedDecl *Op : NonMembers) {
+  for (NamedDecl *Op : EqFD->getEnclosingNamespaceContext()->lookup(NotEqOp)) {
 auto *FD = Op->getAsFunction();
 if(auto* UD = dyn_cast(Op))
   FD = UD->getUnderlyingDecl()->getAsFunction();
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5c6804eb7726b5f..7142ed22ddb22ca 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -324,6 +324,30 @@ bool x = X() == X(); // expected-warning {{ambiguous}}
 }
 } // namespace P2468R2
 
+namespace ADL_GH68901{
+namespace A {
+struct S {};
+bool operator==(S, int); // expected-note {{no known conversion from 'int' to 
'S' for 1st argument}}
+bool operator!=(S, int);
+} // namespace A
+bool a = 0 == A::S(); // expected-error {{invalid operands to binary 
expression ('int' and 'A::S')}}
+
+namespace B {
+struct Derived {};
+struct Base : Derived {};
+
+bool operator==(Derived& a, Base& b);
+bool operator!=(Derived& a, Base& b);
+}  // namespace B
+
+void foo() {
+  // B::Base{} == B::Base{};
+  B::Base a,b;
+  bool v = a == b;
+}
+} //namespace ADL_GH68901
+
+
 #else // NO_ERRORS
 
 namespace problem_cases {

>From eb7ac047b269d71e4fc7afbbb8b8f65e857ff3a3 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 12 Oct 2023 21:48:20 +0200
Subject: [PATCH 2/5] Add release notes

---
 clang/docs/ReleaseNotes.rst | 4 
 1 file changed, 4 insertions(+)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 2d918967e7f0b02..c5b5f665ce9834c 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -64,6 +64,10 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
+- Fixed a bug in finding matching `operator!=` while adding reveresed 
`operator==` as
+  outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
+  Fixes (`#68901: `_).
+
 C++ Specific Potentially Breaking Changes
 -
 - The name mangling rules for function templates has been changed to take into

>From 73d48e546775290196c5a5fbe2922d26df29f013 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Fri, 13 Oct 2023 12:28:29 +0200
Subject: [PATCH 3/5] fix a typo

---
 clang/docs/ReleaseNotes.rst | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index c5b5f665ce9834c..88cbf1d864da400 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -64,7 +64,7 @@ C/C++ Language Potentially Breaking Changes
 ``__has_c_attribute(warn_unused_result)``,  202003, 0
 ``__has_c_attribute(gnu::warn_unused_result)``, 202003, 1
 
-- Fixed a bug in finding matching `operator!=` while adding reveresed 
`operator==` as
+- Fixed a bug in finding matching `operator!=` while adding reversed 
`operator==` as
   outlined in "The Equality Operator You Are Looking For" (`P2468 
`_).
   Fixes (`#68901: `_).
 

>From 8e26dd5732e4cef11a3f3c6e278147b11ae01ac8 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Mon, 16 Oct 2023 12:15:05 +0200
Subject: [PATCH 4/5] Add tests for function scope operators

---
 clang/lib/Sema/SemaOverload.cpp   | 12 +++
 .../over.match.oper/p3-2a.cpp | 32 +++
 2 files changed, 38 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index e1e0b4a888e4

[clang] [analyzer] Add std::variant checker (PR #66481)

2023-10-20 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- 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_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);

spaits wrote:

This header has shared code for std::variant checker and an std::any checker 
which I will try to publish later.

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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Amadeus Gebauer via cfe-commits

https://github.com/amgebauer created 
https://github.com/llvm/llvm-project/pull/69700

If PyYAML is not installed, the `-export-fixes` can be used to specify a 
directory (not a file).

Follows #69453

>From 947b71ca6498f2783f2b701ad8d03d63779e Mon Sep 17 00:00:00 2001
From: Amadeus Gebauer 
Date: Fri, 20 Oct 2023 11:27:17 +0200
Subject: [PATCH] [run-clang-tidy] Accept export directory if PyYAML is not
 installed

If yaml is not installed, the -export-fixes can be used to specify
a directory (not a file).

Follows !69453
---
 .../clang-tidy/tool/clang-tidy-diff.py   | 16 +++-
 .../clang-tidy/tool/run-clang-tidy.py| 16 +++-
 2 files changed, 30 insertions(+), 2 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py 
b/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
index 6fb5eedf06d5dff..8817e2914f6e25b 100755
--- a/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ b/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -187,6 +187,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="DIRECTORY",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-extra-arg",
 dest="extra_arg",
@@ -270,7 +279,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):
diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index aa628aa87800693..179759216196f88 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -315,6 +315,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="directory",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-j",
 type=int,
@@ -401,7 +410,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):

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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy

Author: Amadeus Gebauer (amgebauer)


Changes

If PyYAML is not installed, the `-export-fixes` can be used to specify a 
directory (not a file).

Follows #69453

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


2 Files Affected:

- (modified) clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py (+15-1) 
- (modified) clang-tools-extra/clang-tidy/tool/run-clang-tidy.py (+15-1) 


``diff
diff --git a/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py 
b/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
index 6fb5eedf06d5dff..8817e2914f6e25b 100755
--- a/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
+++ b/clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
@@ -187,6 +187,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="DIRECTORY",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-extra-arg",
 dest="extra_arg",
@@ -270,7 +279,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):
diff --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index aa628aa87800693..179759216196f88 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -315,6 +315,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="directory",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-j",
 type=int,
@@ -401,7 +410,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):

``




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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Utkarsh Saxena via cfe-commits


@@ -7688,7 +7688,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)

usx95 wrote:

All the tests mentioned in this PR are fixed by this change. These were 
previously not flagged by Clang.
With the rest of the change, the error produced by this is reduced to a warning.

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


Re: [PATCH] D138505: [clangd] Don't run slow clang-tidy checks by default

2023-10-20 Thread Sam McCall via cfe-commits
Very late, & by email since phab is down.

Going to land this based on "LG" comment & offline discussion, happy to do
followups if needed.

On Mon, Nov 28, 2022 at 10:08 PM Kadir Cetinkaya via Phabricator <
revi...@reviews.llvm.org> wrote:

> kadircet added a comment.
>
> thanks LG, i'd like to hear how we're planning to let downstream users
> customise the list of fast checks. otherwise they have to run with `Loose`
> at all times.
> the easiest i can think of is, generating their own `fastchecks.inc`
> fragment and #include that in addition to clangd's default list. Any other
> ideas on this one?
>

This is the plan I'd suggest.
Having to modify source is annoying, but there's always loose mode too.


> 
> Comment at: clang-tools-extra/clangd/ConfigCompile.cpp:488
> + llvm::formatv(
> + "Speed of clang-tidy check '{0}' is not known. "
> + "It will only run if ClangTidy.FastCheckFilter is Loose
> or None",
> 
> nit: s/Speed/Latency (or Performance?)
>
Done



> Comment at: clang-tools-extra/clangd/TidyProvider.cpp:312
> +  };
> +  auto It = Fast.find(Check);
> +  if (It == Fast.end())
> 
> nit: some c++17 magic if you want:
> ```
> if (auto It = Fast.find(Check); It != Fast.end())
>   return It->second;
> return llvm::None;
> ```
>
Done


> 
> Comment at: clang-tools-extra/clangd/tool/Check.cpp:88
> +llvm::cl::opt CheckWarnings{
> +"check-warnings",
> +llvm::cl::desc("Print warnings as well as errors"),
> 
> i think `print-warnings` is probably better than `check` we're not really
> checking anything.
>
There's only one namespace for all flags to clangd, "check-" is being used
as a namespacing prefix for those that control the behavior of --check
specifically.

I agree -print-warnings would read slightly better, but I think it's
important these flags are clearly distinguished/grouped.


> 
> Comment at: clang-tools-extra/clangd/tool/Check.cpp:92
>
>  // Print (and count) the error-level diagnostics (warnings are ignored).
>  unsigned showErrors(llvm::ArrayRef Diags) {
> 
> update the comment (or maybe even drop it?)
>
Done.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] b99f7e6 - [clangd] Don't run slow clang-tidy checks by default

2023-10-20 Thread Sam McCall via cfe-commits

Author: Sam McCall
Date: 2023-10-20T11:47:29+02:00
New Revision: b99f7e6954691efae2d60a1af21f8c1b71a0f786

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

LOG: [clangd] Don't run slow clang-tidy checks by default

This uses the fast-check allowlist added in the previous commit.
This is behind a config option to allow users/developers to enable checks
we haven't timed yet, and to allow the --check-tidy-time flag to work.

Fixes https://github.com/clangd/clangd/issues/1337

Differential Revision: https://reviews.llvm.org/D138505

Added: 


Modified: 
clang-tools-extra/clangd/Config.h
clang-tools-extra/clangd/ConfigCompile.cpp
clang-tools-extra/clangd/ConfigFragment.h
clang-tools-extra/clangd/ConfigYAML.cpp
clang-tools-extra/clangd/ParsedAST.cpp
clang-tools-extra/clangd/TidyProvider.cpp
clang-tools-extra/clangd/TidyProvider.h
clang-tools-extra/clangd/tool/Check.cpp
clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
clang-tools-extra/clangd/unittests/TidyProviderTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/Config.h 
b/clang-tools-extra/clangd/Config.h
index daae8d1c0c833eb..4371c80a6c5877f 100644
--- a/clang-tools-extra/clangd/Config.h
+++ b/clang-tools-extra/clangd/Config.h
@@ -93,6 +93,7 @@ struct Config {
 Strict,
 None,
   };
+  enum class FastCheckPolicy { Strict, Loose, None };
   /// Controls warnings and errors when parsing code.
   struct {
 bool SuppressAll = false;
@@ -103,6 +104,7 @@ struct Config {
   // A comma-separated list of globs specify which clang-tidy checks to 
run.
   std::string Checks;
   llvm::StringMap CheckOptions;
+  FastCheckPolicy FastCheckFilter = FastCheckPolicy::Strict;
 } ClangTidy;
 
 IncludesPolicy UnusedIncludes = IncludesPolicy::Strict;

diff  --git a/clang-tools-extra/clangd/ConfigCompile.cpp 
b/clang-tools-extra/clangd/ConfigCompile.cpp
index d4ff7ae3181bc3d..0c9fc27643be87a 100644
--- a/clang-tools-extra/clangd/ConfigCompile.cpp
+++ b/clang-tools-extra/clangd/ConfigCompile.cpp
@@ -324,11 +324,11 @@ struct FragmentCompiler {
 
   void compile(Fragment::IndexBlock &&F) {
 if (F.Background) {
-  if (auto Val = compileEnum("Background",
-   **F.Background)
- .map("Build", Config::BackgroundPolicy::Build)
- .map("Skip", Config::BackgroundPolicy::Skip)
- .value())
+  if (auto Val =
+  compileEnum("Background", 
*F.Background)
+  .map("Build", Config::BackgroundPolicy::Build)
+  .map("Skip", Config::BackgroundPolicy::Skip)
+  .value())
 Out.Apply.push_back(
 [Val](const Params &, Config &C) { C.Index.Background = *Val; });
 }
@@ -494,11 +494,31 @@ struct FragmentCompiler {
   diag(Error, "Invalid clang-tidy check name", Arg.Range);
   return;
 }
-if (!Str.contains('*') && !isRegisteredTidyCheck(Str)) {
-  diag(Warning,
-   llvm::formatv("clang-tidy check '{0}' was not found", Str).str(),
-   Arg.Range);
-  return;
+if (!Str.contains('*')) {
+  if (!isRegisteredTidyCheck(Str)) {
+diag(Warning,
+ llvm::formatv("clang-tidy check '{0}' was not found", Str).str(),
+ Arg.Range);
+return;
+  }
+  auto Fast = isFastTidyCheck(Str);
+  if (!Fast.has_value()) {
+diag(Warning,
+ llvm::formatv(
+ "Latency of clang-tidy check '{0}' is not known. "
+ "It will only run if ClangTidy.FastCheckFilter is Loose or 
None",
+ Str)
+ .str(),
+ Arg.Range);
+  } else if (!*Fast) {
+diag(Warning,
+ llvm::formatv(
+ "clang-tidy check '{0}' is slow. "
+ "It will only run if ClangTidy.FastCheckFilter is None",
+ Str)
+ .str(),
+ Arg.Range);
+  }
 }
 CurSpec += ',';
 if (!IsPositive)
@@ -534,6 +554,16 @@ struct FragmentCompiler {
   StringPair.first, StringPair.second);
   });
 }
+if (F.FastCheckFilter.has_value())
+  if (auto Val = compileEnum("FastCheckFilter",
+  *F.FastCheckFilter)
+ .map("Strict", Config::FastCheckPolicy::Strict)
+ .map("Loose", Config::FastCheckPolicy::Loose)
+ .map("None", Config::FastCheckPolicy::None)
+ .value())
+Out.Ap

[PATCH] D138505: [clangd] Don't run slow clang-tidy checks by default

2023-10-20 Thread Sam McCall via Phabricator via cfe-commits
This revision was not accepted when it landed; it landed in state "Needs 
Review".
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGb99f7e695469: [clangd] Don't run slow clang-tidy checks 
by default (authored by sammccall).

Changed prior to commit:
  https://reviews.llvm.org/D138505?vs=478274&id=557803#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D138505

Files:
  clang-tools-extra/clangd/Config.h
  clang-tools-extra/clangd/ConfigCompile.cpp
  clang-tools-extra/clangd/ConfigFragment.h
  clang-tools-extra/clangd/ConfigYAML.cpp
  clang-tools-extra/clangd/ParsedAST.cpp
  clang-tools-extra/clangd/TidyProvider.cpp
  clang-tools-extra/clangd/TidyProvider.h
  clang-tools-extra/clangd/tool/Check.cpp
  clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
  clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
  clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
  clang-tools-extra/clangd/unittests/TidyProviderTests.cpp

Index: clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
===
--- clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
+++ clang-tools-extra/clangd/unittests/TidyProviderTests.cpp
@@ -6,8 +6,10 @@
 //
 //===--===//
 
+#include "Feature.h"
 #include "TestFS.h"
 #include "TidyProvider.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gtest/gtest.h"
 
 namespace clang {
@@ -52,6 +54,22 @@
   EXPECT_EQ(*Sub2Options.Checks, "misc-*,bugprone-*");
   EXPECT_EQ(Sub2Options.CheckOptions.lookup("TestKey").Value, "3");
 }
+
+TEST(TidyProvider, IsFastTidyCheck) {
+  EXPECT_THAT(isFastTidyCheck("misc-const-correctness"), llvm::ValueIs(false));
+  EXPECT_THAT(isFastTidyCheck("bugprone-suspicious-include"),
+  llvm::ValueIs(true));
+  // Linked in (ParsedASTTests.cpp) but not measured.
+  EXPECT_EQ(isFastTidyCheck("replay-preamble-check"), std::nullopt);
+}
+
+#if CLANGD_TIDY_CHECKS
+TEST(TidyProvider, IsValidCheck) {
+  EXPECT_TRUE(isRegisteredTidyCheck("bugprone-argument-comment"));
+  EXPECT_FALSE(isRegisteredTidyCheck("bugprone-argument-clinic"));
+}
+#endif
+
 } // namespace
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
===
--- clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
+++ clang-tools-extra/clangd/unittests/ReplayPeambleTests.cpp
@@ -15,11 +15,13 @@
 #include "../../clang-tidy/ClangTidyModule.h"
 #include "../../clang-tidy/ClangTidyModuleRegistry.h"
 #include "AST.h"
+#include "Config.h"
 #include "Diagnostics.h"
 #include "ParsedAST.h"
 #include "SourceCode.h"
 #include "TestTU.h"
 #include "TidyProvider.h"
+#include "support/Context.h"
 #include "clang/AST/DeclTemplate.h"
 #include "clang/Basic/FileEntry.h"
 #include "clang/Basic/LLVM.h"
@@ -121,6 +123,11 @@
   // obj-c.
   TU.ExtraArgs = {"-isystem.", "-xobjective-c"};
 
+  // Allow the check to run even though not marked as fast.
+  Config Cfg;
+  Cfg.Diagnostics.ClangTidy.FastCheckFilter = Config::FastCheckPolicy::Loose;
+  WithContextValue WithCfg(Config::Key, std::move(Cfg));
+
   const auto &AST = TU.build();
   const auto &SM = AST.getSourceManager();
 
Index: clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
===
--- clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
+++ clang-tools-extra/clangd/unittests/ParsedASTTests.cpp
@@ -12,6 +12,8 @@
 //===--===//
 
 #include "../../clang-tidy/ClangTidyCheck.h"
+#include "../../clang-tidy/ClangTidyModule.h"
+#include "../../clang-tidy/ClangTidyModuleRegistry.h"
 #include "AST.h"
 #include "CompileCommands.h"
 #include "Compiler.h"
@@ -26,9 +28,11 @@
 #include "TidyProvider.h"
 #include "support/Context.h"
 #include "clang/AST/DeclTemplate.h"
+#include "clang/Basic/FileEntry.h"
 #include "clang/Basic/SourceLocation.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
 #include "clang/Tooling/Syntax/Tokens.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/Testing/Annotations/Annotations.h"
@@ -36,7 +40,9 @@
 #include "gmock/gmock-matchers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
+#include 
 #include 
+#include 
 
 namespace clang {
 namespace clangd {
Index: clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
===
--- clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
+++ clang-tools-extra/clangd/unittests/DiagnosticsTests.cpp
@@ -1808,29 +1808,13 @@
 }
 
 TEST(ParsedASTTest, ModuleSawDiag) {
-  static constexpr const llv

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

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


tbaederr wrote:

Regardless of the approach we take in the end - what do you think about tests 
for this? Should we have a flag similar to 
`-fdiagnostics-print-source-range-info` for the code style ranges?

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-20 Thread Sam Tebbs via cfe-commits


@@ -85,17 +90,32 @@ static bool isPrologueCFIInstruction(const MachineInstr 
&MI) {
  MI.getFlag(MachineInstr::FrameSetup);
 }
 
-static bool containsPrologue(const MachineBasicBlock &MBB) {
-  return llvm::any_of(MBB.instrs(), isPrologueCFIInstruction);
-}
-
 static bool containsEpilogue(const MachineBasicBlock &MBB) {
   return llvm::any_of(llvm::reverse(MBB), [](const auto &MI) {
 return MI.getOpcode() == TargetOpcode::CFI_INSTRUCTION &&
MI.getFlag(MachineInstr::FrameDestroy);
   });
 }
 
+static MachineBasicBlock *
+findPrologueEnd(MachineFunction &MF, MachineBasicBlock::iterator &PrologueEnd) 
{
+  MachineBasicBlock *PrologueBlock = nullptr;
+  for (auto It = po_begin(&MF.front()), End = po_end(&MF.front()); It != End;
+   ++It) {
+MachineBasicBlock *MBB = *It;
+llvm::for_each(MBB->instrs(), [&](MachineInstr &MI) {

SamTebbs33 wrote:

Does it make sense here to go through the reversed list of the instructions and 
stop after you find the first prologue CFI instruction?

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-20 Thread Sam Tebbs via cfe-commits


@@ -1,25 +1,33 @@
 // Check the correct function attributes are generated
-// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s 
--check-prefixes CHECK-AARCH64
 
 // CHECK: define{{.*}} void @large_stack() #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @large_stack() #[[A:.*]] {

SamTebbs33 wrote:

If you were to add CHECK as a check prefix for the AArch64 run line then we 
shouldn't need this change since it's identical to the line above.

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-20 Thread Momchil Velikov via cfe-commits


@@ -85,17 +90,32 @@ static bool isPrologueCFIInstruction(const MachineInstr 
&MI) {
  MI.getFlag(MachineInstr::FrameSetup);
 }
 
-static bool containsPrologue(const MachineBasicBlock &MBB) {
-  return llvm::any_of(MBB.instrs(), isPrologueCFIInstruction);
-}
-
 static bool containsEpilogue(const MachineBasicBlock &MBB) {
   return llvm::any_of(llvm::reverse(MBB), [](const auto &MI) {
 return MI.getOpcode() == TargetOpcode::CFI_INSTRUCTION &&
MI.getFlag(MachineInstr::FrameDestroy);
   });
 }
 
+static MachineBasicBlock *
+findPrologueEnd(MachineFunction &MF, MachineBasicBlock::iterator &PrologueEnd) 
{
+  MachineBasicBlock *PrologueBlock = nullptr;
+  for (auto It = po_begin(&MF.front()), End = po_end(&MF.front()); It != End;
+   ++It) {
+MachineBasicBlock *MBB = *It;
+llvm::for_each(MBB->instrs(), [&](MachineInstr &MI) {

momchil-velikov wrote:

Indeed, I'll do it.

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


[clang] [clang][AArch64] Pass down stack clash protection options to LLVM/Backend (PR #68993)

2023-10-20 Thread Momchil Velikov via cfe-commits


@@ -1,25 +1,33 @@
 // Check the correct function attributes are generated
-// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
-// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-linux -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple s390x-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64le-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple powerpc64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-linux-gnu -O0 -S -emit-llvm -o- %s 
-fstack-clash-protection -mstack-probe-size=8192 | FileCheck %s 
--check-prefixes CHECK-AARCH64
 
 // CHECK: define{{.*}} void @large_stack() #[[A:.*]] {
+// CHECK-AARCH64: define{{.*}} void @large_stack() #[[A:.*]] {

momchil-velikov wrote:

However that `CHECK`  at line 29 is not applicable for AArch64.
The way attributes are passed down to LLVM differs between AArch64 and other 
backends which support SCP. IMHO other backends should adopt the AArch64 way - 
then this test will contain only `CHECK` lines (corresponding to the current 
`CHECK-AARCH64` ones).

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


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

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


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

>From 8e0d084529d159ee80dd3971f9a5bb112e24bb86 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 15 Sep 2023 15:51:39 +0200
Subject: [PATCH 01/20] [clang][Diagnostics] Highlight code snippets

Add some primitive syntax highlighting to our code snippet output.
---
 .../clang/Frontend/CodeSnippetHighlighter.h   |  46 +++
 clang/include/clang/Frontend/TextDiagnostic.h |   2 +
 clang/lib/Frontend/CMakeLists.txt |   1 +
 clang/lib/Frontend/CodeSnippetHighlighter.cpp | 120 ++
 clang/lib/Frontend/TextDiagnostic.cpp |  26 
 5 files changed, 195 insertions(+)
 create mode 100644 clang/include/clang/Frontend/CodeSnippetHighlighter.h
 create mode 100644 clang/lib/Frontend/CodeSnippetHighlighter.cpp

diff --git a/clang/include/clang/Frontend/CodeSnippetHighlighter.h 
b/clang/include/clang/Frontend/CodeSnippetHighlighter.h
new file mode 100644
index 000..776954b59e2e1a8
--- /dev/null
+++ b/clang/include/clang/Frontend/CodeSnippetHighlighter.h
@@ -0,0 +1,46 @@
+//===--- CodeSnippetHighlighter.h - Code snippet highlighting ---*- 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_FRONTEND_CODESNIPPETHIGHLIGHTER_H
+#define LLVM_CLANG_FRONTEND_CODESNIPPETHIGHLIGHTER_H
+
+#include "clang/Basic/LangOptions.h"
+#include "llvm/ADT/SmallSet.h"
+#include "llvm/Support/raw_ostream.h"
+#include 
+
+namespace clang {
+
+struct StyleRange {
+  unsigned Start;
+  unsigned End;
+  const enum llvm::raw_ostream::Colors c;
+};
+
+class CodeSnippetHighlighter final {
+public:
+  CodeSnippetHighlighter() = default;
+
+  /// Produce StyleRanges for the given line.
+  /// The returned vector contains non-overlapping style ranges. They are 
sorted
+  /// from beginning of the line to the end.
+  std::vector highlightLine(llvm::StringRef SourceLine,
+const LangOptions &LangOpts);
+
+private:
+  bool Initialized = false;
+  /// Fills Keywords and Literals.
+  void ensureTokenData();
+
+  llvm::SmallSet Keywords;
+  llvm::SmallSet Literals;
+};
+
+} // namespace clang
+
+#endif
diff --git a/clang/include/clang/Frontend/TextDiagnostic.h 
b/clang/include/clang/Frontend/TextDiagnostic.h
index 7eb0ab0cdc9bca8..59fd4d4f9408d48 100644
--- a/clang/include/clang/Frontend/TextDiagnostic.h
+++ b/clang/include/clang/Frontend/TextDiagnostic.h
@@ -15,6 +15,7 @@
 #ifndef LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
 #define LLVM_CLANG_FRONTEND_TEXTDIAGNOSTIC_H
 
+#include "clang/Frontend/CodeSnippetHighlighter.h"
 #include "clang/Frontend/DiagnosticRenderer.h"
 
 namespace clang {
@@ -33,6 +34,7 @@ namespace clang {
 /// printing coming out of libclang.
 class TextDiagnostic : public DiagnosticRenderer {
   raw_ostream &OS;
+  CodeSnippetHighlighter SnippetHighlighter;
 
 public:
   TextDiagnostic(raw_ostream &OS,
diff --git a/clang/lib/Frontend/CMakeLists.txt 
b/clang/lib/Frontend/CMakeLists.txt
index 1e5f0a859dfd568..f3547f771593093 100644
--- a/clang/lib/Frontend/CMakeLists.txt
+++ b/clang/lib/Frontend/CMakeLists.txt
@@ -42,6 +42,7 @@ add_clang_library(clangFrontend
   TextDiagnosticPrinter.cpp
   VerifyDiagnosticConsumer.cpp
   InterfaceStubFunctionsConsumer.cpp
+  CodeSnippetHighlighter.cpp
 
   DEPENDS
   ClangDriverOptions
diff --git a/clang/lib/Frontend/CodeSnippetHighlighter.cpp 
b/clang/lib/Frontend/CodeSnippetHighlighter.cpp
new file mode 100644
index 000..829a533ad2692e5
--- /dev/null
+++ b/clang/lib/Frontend/CodeSnippetHighlighter.cpp
@@ -0,0 +1,120 @@
+
+#include "clang/Frontend/CodeSnippetHighlighter.h"
+#include "clang/Basic/DiagnosticOptions.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Lex/Lexer.h"
+#include "llvm/Support/raw_ostream.h"
+
+using namespace clang;
+
+void CodeSnippetHighlighter::ensureTokenData() {
+  if (Initialized)
+return;
+
+  // List of keywords, literals and types we want to highlight.
+  // These are best-effort, as is everything we do wrt. highlighting.
+  Keywords.insert("_Static_assert");
+  Keywords.insert("auto");
+  Keywords.insert("concept");
+  Keywords.insert("const");
+  Keywords.insert("consteval");
+  Keywords.insert("

[clang-tools-extra] [clangd] Allow "move function body out-of-line" in non-header files (PR #69704)

2023-10-20 Thread via cfe-commits

https://github.com/ckandeler created 
https://github.com/llvm/llvm-project/pull/69704

Moving the body of member functions out-of-line makes sense for classes defined 
in implementation files too.

>From 0b7df6c0a713c1c40f6c92d958fa6a96796ed80f Mon Sep 17 00:00:00 2001
From: Christian Kandeler 
Date: Thu, 19 Oct 2023 17:51:11 +0200
Subject: [PATCH] [clangd] Allow "move function body out-of-line" in non-header
 files

Moving the body of member functions out-of-line makes sense for classes
defined in implementation files too.
---
 .../clangd/refactor/tweaks/DefineOutline.cpp  | 33 ++-
 .../unittests/tweaks/DefineOutlineTests.cpp   | 32 +-
 2 files changed, 49 insertions(+), 16 deletions(-)

diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index b84ae04072f2c19..a52bd5ee46f0ce2 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -409,14 +409,9 @@ class DefineOutline : public Tweak {
   }
 
   bool prepare(const Selection &Sel) override {
-// Bail out if we are not in a header file.
-// FIXME: We might want to consider moving method definitions below class
-// definition even if we are inside a source file.
-if (!isHeaderFile(Sel.AST->getSourceManager().getFilename(Sel.Cursor),
-  Sel.AST->getLangOpts()))
-  return false;
-
+SameFile = !isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts());
 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
+
 // Bail out if the selection is not a in-line function definition.
 if (!Source || !Source->doesThisDeclarationHaveABody() ||
 Source->isOutOfLine())
@@ -443,6 +438,9 @@ class DefineOutline : public Tweak {
 return false;
 }
   }
+} else if (SameFile) {
+  // Bail out for free-standing functions in non-header file.
+  return false;
 }
 
 // Note that we don't check whether an implementation file exists or not in
@@ -453,8 +451,8 @@ class DefineOutline : public Tweak {
 
   Expected apply(const Selection &Sel) override {
 const SourceManager &SM = Sel.AST->getSourceManager();
-auto CCFile = getSourceFile(Sel.AST->tuPath(), Sel);
-
+auto CCFile = SameFile ? Sel.AST->tuPath().str()
+   : getSourceFile(Sel.AST->tuPath(), Sel);
 if (!CCFile)
   return error("Couldn't find a suitable implementation file.");
 assert(Sel.FS && "FS Must be set in apply");
@@ -499,17 +497,22 @@ class DefineOutline : public Tweak {
   HeaderUpdates = HeaderUpdates.merge(*DelInline);
 }
 
-auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
-if (!HeaderFE)
-  return HeaderFE.takeError();
-
-Effect->ApplyEdits.try_emplace(HeaderFE->first,
-   std::move(HeaderFE->second));
+if (SameFile) {
+  tooling::Replacements &R = Effect->ApplyEdits[*CCFile].Replacements;
+  R = R.merge(HeaderUpdates);
+} else {
+  auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
+  if (!HeaderFE)
+return HeaderFE.takeError();
+  Effect->ApplyEdits.try_emplace(HeaderFE->first,
+ std::move(HeaderFE->second));
+}
 return std::move(*Effect);
   }
 
 private:
   const FunctionDecl *Source = nullptr;
+  bool SameFile = false;
 };
 
 REGISTER_TWEAK(DefineOutline)
diff --git a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
index d1e60b070f20e95..8aaadb66943e1ee 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
@@ -19,7 +19,7 @@ TWEAK_TEST(DefineOutline);
 
 TEST_F(DefineOutlineTest, TriggersOnFunctionDecl) {
   FileName = "Test.cpp";
-  // Not available unless in a header file.
+  // Not available for free function unless in a header file.
   EXPECT_UNAVAILABLE(R"cpp(
 [[void [[f^o^o]]() [[{
   return;
@@ -349,6 +349,36 @@ TEST_F(DefineOutlineTest, ApplyTest) {
   }
 }
 
+TEST_F(DefineOutlineTest, InCppFile) {
+  FileName = "Test.cpp";
+
+  struct {
+llvm::StringRef Test;
+llvm::StringRef ExpectedSource;
+  } Cases[] = {
+  // Member function with some adornments
+  // FIXME: What's with the extra spaces?
+  {"#define OVERRIDE override\n"
+   "struct Base { virtual int func() const = 0; };\n"
+   "struct Derived : Base {\n"
+   "   inline int f^unc() const OVERRIDE { return 42; }\n"
+   "};\n"
+   "int main() {}\n",
+   "#define OVERRIDE override\n"
+   "struct Base { virtual int func() const = 0; };\n"
+   "struct Derived : Base {\n"
+   "int func() const OVERRIDE ;\n"
+   "};\n"
+   "int main() {}\n"
+   " int Derived::func()

[clang-tools-extra] [clangd] Allow "move function body out-of-line" in non-header files (PR #69704)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: None (ckandeler)


Changes

Moving the body of member functions out-of-line makes sense for classes defined 
in implementation files too.

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


2 Files Affected:

- (modified) clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp 
(+18-15) 
- (modified) clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp 
(+31-1) 


``diff
diff --git a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
index b84ae04072f2c19..a52bd5ee46f0ce2 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
+++ b/clang-tools-extra/clangd/refactor/tweaks/DefineOutline.cpp
@@ -409,14 +409,9 @@ class DefineOutline : public Tweak {
   }
 
   bool prepare(const Selection &Sel) override {
-// Bail out if we are not in a header file.
-// FIXME: We might want to consider moving method definitions below class
-// definition even if we are inside a source file.
-if (!isHeaderFile(Sel.AST->getSourceManager().getFilename(Sel.Cursor),
-  Sel.AST->getLangOpts()))
-  return false;
-
+SameFile = !isHeaderFile(Sel.AST->tuPath(), Sel.AST->getLangOpts());
 Source = getSelectedFunction(Sel.ASTSelection.commonAncestor());
+
 // Bail out if the selection is not a in-line function definition.
 if (!Source || !Source->doesThisDeclarationHaveABody() ||
 Source->isOutOfLine())
@@ -443,6 +438,9 @@ class DefineOutline : public Tweak {
 return false;
 }
   }
+} else if (SameFile) {
+  // Bail out for free-standing functions in non-header file.
+  return false;
 }
 
 // Note that we don't check whether an implementation file exists or not in
@@ -453,8 +451,8 @@ class DefineOutline : public Tweak {
 
   Expected apply(const Selection &Sel) override {
 const SourceManager &SM = Sel.AST->getSourceManager();
-auto CCFile = getSourceFile(Sel.AST->tuPath(), Sel);
-
+auto CCFile = SameFile ? Sel.AST->tuPath().str()
+   : getSourceFile(Sel.AST->tuPath(), Sel);
 if (!CCFile)
   return error("Couldn't find a suitable implementation file.");
 assert(Sel.FS && "FS Must be set in apply");
@@ -499,17 +497,22 @@ class DefineOutline : public Tweak {
   HeaderUpdates = HeaderUpdates.merge(*DelInline);
 }
 
-auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
-if (!HeaderFE)
-  return HeaderFE.takeError();
-
-Effect->ApplyEdits.try_emplace(HeaderFE->first,
-   std::move(HeaderFE->second));
+if (SameFile) {
+  tooling::Replacements &R = Effect->ApplyEdits[*CCFile].Replacements;
+  R = R.merge(HeaderUpdates);
+} else {
+  auto HeaderFE = Effect::fileEdit(SM, SM.getMainFileID(), HeaderUpdates);
+  if (!HeaderFE)
+return HeaderFE.takeError();
+  Effect->ApplyEdits.try_emplace(HeaderFE->first,
+ std::move(HeaderFE->second));
+}
 return std::move(*Effect);
   }
 
 private:
   const FunctionDecl *Source = nullptr;
+  bool SameFile = false;
 };
 
 REGISTER_TWEAK(DefineOutline)
diff --git a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp 
b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
index d1e60b070f20e95..8aaadb66943e1ee 100644
--- a/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
+++ b/clang-tools-extra/clangd/unittests/tweaks/DefineOutlineTests.cpp
@@ -19,7 +19,7 @@ TWEAK_TEST(DefineOutline);
 
 TEST_F(DefineOutlineTest, TriggersOnFunctionDecl) {
   FileName = "Test.cpp";
-  // Not available unless in a header file.
+  // Not available for free function unless in a header file.
   EXPECT_UNAVAILABLE(R"cpp(
 [[void [[f^o^o]]() [[{
   return;
@@ -349,6 +349,36 @@ TEST_F(DefineOutlineTest, ApplyTest) {
   }
 }
 
+TEST_F(DefineOutlineTest, InCppFile) {
+  FileName = "Test.cpp";
+
+  struct {
+llvm::StringRef Test;
+llvm::StringRef ExpectedSource;
+  } Cases[] = {
+  // Member function with some adornments
+  // FIXME: What's with the extra spaces?
+  {"#define OVERRIDE override\n"
+   "struct Base { virtual int func() const = 0; };\n"
+   "struct Derived : Base {\n"
+   "   inline int f^unc() const OVERRIDE { return 42; }\n"
+   "};\n"
+   "int main() {}\n",
+   "#define OVERRIDE override\n"
+   "struct Base { virtual int func() const = 0; };\n"
+   "struct Derived : Base {\n"
+   "int func() const OVERRIDE ;\n"
+   "};\n"
+   "int main() {}\n"
+   " int Derived::func() const  { return 42; }\n"},
+  };
+
+  for (const auto &Case : Cases) {
+SCOPED_TRACE(Case.Test);
+EXPECT_EQ(apply(Case.Test, nullptr), Case.ExpectedSource);
+  }
+}
+
 TEST_F(DefineOutlineTest, HandleMacros) {
   llvm::StringMap EditedFiles;
   Extr

[clang] 7c15dd6 - [clang-format] Add space in placement new expression

2023-10-20 Thread Owen Pan via cfe-commits

Author: Omar Ahmed
Date: 2023-10-20T03:16:28-07:00
New Revision: 7c15dd60ec4549f53f1a51c5302c61f8a025a4a5

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

LOG: [clang-format] Add space in placement new expression

Add AfterPlacementNew option to SpaceBeforeParensOptions to have more
control on placement new expressions.

Fixes #41501
Relates to #54703

Differential Revision: https://reviews.llvm.org/D127270

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/docs/tools/dump_format_style.py
clang/include/clang/Format/Format.h
clang/lib/Format/Format.cpp
clang/lib/Format/TokenAnnotator.cpp
clang/unittests/Format/ConfigParseTest.cpp
clang/unittests/Format/FormatTest.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index c5c72c68ee9b800..cfd57f5fa8153f4 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -5224,6 +5224,33 @@ the configuration (without a prefix: ``Auto``).
void operator++ (int a);vs.void operator++(int a);
object.operator++ (10);object.operator++(10);
 
+  * ``AfterPlacementOperatorStyle AfterPlacementOperator`` 
:versionbadge:`clang-format 18`
+
+Defines in which cases to put a space between ``new/delete`` operators
+and opening parentheses.
+
+Possible values:
+
+* ``APO_Never`` (in configuration: ``Never``)
+  Remove space after ``new/delete`` operators and before ``(``.
+
+  .. code-block:: c++
+
+ new(buf) T;
+ delete(buf) T;
+
+* ``APO_Always`` (in configuration: ``Always``)
+  Always add space after ``new/delete`` operators and before ``(``.
+
+  .. code-block:: c++
+
+ new (buf) T;
+ delete (buf) T;
+
+* ``APO_Leave`` (in configuration: ``Leave``)
+  Leave placement ``new/delete`` expressions as they are.
+
+
   * ``bool AfterRequiresInClause`` If ``true``, put space between requires 
keyword in a requires clause and
 opening parentheses, if there is one.
 

diff  --git a/clang/docs/tools/dump_format_style.py 
b/clang/docs/tools/dump_format_style.py
index 270ac34c03b39ca..75d4a044ef19f68 100755
--- a/clang/docs/tools/dump_format_style.py
+++ b/clang/docs/tools/dump_format_style.py
@@ -143,11 +143,18 @@ def __str__(self):
 
 
 class NestedField(object):
-def __init__(self, name, comment):
+def __init__(self, name, comment, version):
 self.name = name
 self.comment = comment.strip()
+self.version = version
 
 def __str__(self):
+if self.version:
+return "\n* ``%s`` :versionbadge:`clang-format %s`\n%s" % (
+self.name,
+self.version,
+doxygen2rst(indent(self.comment, 2, indent_first_line=False)),
+)
 return "\n* ``%s`` %s" % (
 self.name,
 doxygen2rst(indent(self.comment, 2, indent_first_line=False)),
@@ -165,18 +172,28 @@ def __str__(self):
 
 
 class NestedEnum(object):
-def __init__(self, name, enumtype, comment, values):
+def __init__(self, name, enumtype, comment, version, values):
 self.name = name
 self.comment = comment
 self.values = values
 self.type = enumtype
+self.version = version
 
 def __str__(self):
-s = "\n* ``%s %s``\n%s" % (
-to_yaml_type(self.type),
-self.name,
-doxygen2rst(indent(self.comment, 2)),
-)
+s = ""
+if self.version:
+s = "\n* ``%s %s`` :versionbadge:`clang-format %s`\n\n%s" % (
+to_yaml_type(self.type),
+self.name,
+self.version,
+doxygen2rst(indent(self.comment, 2)),
+)
+else:
+s = "\n* ``%s %s``\n%s" % (
+to_yaml_type(self.type),
+self.name,
+doxygen2rst(indent(self.comment, 2)),
+)
 s += indent("\nPossible values:\n\n", 2)
 s += indent("\n".join(map(str, self.values)), 2)
 return s
@@ -278,7 +295,9 @@ class State:
 InFieldComment,
 InEnum,
 InEnumMemberComment,
-) = range(8)
+InNestedEnum,
+InNestedEnumMemberComment,
+) = range(10)
 
 state = State.BeforeStruct
 
@@ -344,27 +363,38 @@ class State:
 state = State.InStruct
 nested_structs[nested_struct.name] = nested_struct
 elif state == State.InNestedFieldComment:
-if line.startswith("///"):
+if line.startswith(r"/// \version"):
+match = re.ma

[PATCH] D127270: [clang-format] Add space in placement new expression

2023-10-20 Thread Owen Pan via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rG7c15dd60ec45: [clang-format] Add space in placement new 
expression (authored by omarahmed, committed by owenpan).

Changed prior to commit:
  https://reviews.llvm.org/D127270?vs=445172&id=557807#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D127270

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/tools/dump_format_style.py
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/ConfigParseTest.cpp
  clang/unittests/Format/FormatTest.cpp

Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -11189,6 +11189,42 @@
"void delete(link p);",
"void new (link p);\n"
"void delete (link p);");
+
+  FormatStyle AfterPlacementOperator = getLLVMStyle();
+  AfterPlacementOperator.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  EXPECT_EQ(
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+  verifyFormat("new (buf) int;", AfterPlacementOperator);
+  verifyFormat("new(buf) int;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Never;
+  verifyFormat("struct A {\n"
+   "  int *a;\n"
+   "  A(int *p) : a(new(p) int) {\n"
+   "new(p) int;\n"
+   "int *b = new(p) int;\n"
+   "int *c = new(p) int(3);\n"
+   "delete(b);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
+
+  AfterPlacementOperator.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  verifyFormat("struct A {\n"
+   "  int *a;\n"
+   "  A(int *p) : a(new (p) int) {\n"
+   "new (p) int;\n"
+   "int *b = new (p) int;\n"
+   "int *c = new (p) int(3);\n"
+   "delete (b);\n"
+   "  }\n"
+   "};",
+   AfterPlacementOperator);
+  verifyFormat("void operator new(void *foo) ATTRIB;", AfterPlacementOperator);
 }
 
 TEST_F(FormatTest, UnderstandsUsesOfStarAndAmp) {
Index: clang/unittests/Format/ConfigParseTest.cpp
===
--- clang/unittests/Format/ConfigParseTest.cpp
+++ clang/unittests/Format/ConfigParseTest.cpp
@@ -591,6 +591,24 @@
   SpaceBeforeParens,
   FormatStyle::SBPO_ControlStatementsExceptControlMacros);
 
+  Style.SpaceBeforeParens = FormatStyle::SBPO_Custom;
+  Style.SpaceBeforeParensOptions.AfterPlacementOperator =
+  FormatStyle::SpaceBeforeParensCustom::APO_Always;
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Never",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Never);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Always",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Always);
+
+  CHECK_PARSE("SpaceBeforeParensOptions:\n"
+  "  AfterPlacementOperator: Leave",
+  SpaceBeforeParensOptions.AfterPlacementOperator,
+  FormatStyle::SpaceBeforeParensCustom::APO_Leave);
+
   // For backward compatibility:
   Style.SpacesInParens = FormatStyle::SIPO_Never;
   Style.SpacesInParensOptions = {};
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -4234,6 +4234,19 @@
   return Style.SpaceBeforeParensOptions.AfterIfMacros ||
  spaceRequiredBeforeParens(Right);
 }
+if (Style.SpaceBeforeParens == FormatStyle::SBPO_Custom &&
+Left.isOneOf(tok::kw_new, tok::kw_delete) &&
+Right.isNot(TT_OverloadedOperatorLParen) &&
+!(Line.MightBeFunctionDecl && Left.is(TT_FunctionDeclarationName))) {
+  if (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+  FormatStyle::SpaceBeforeParensCustom::APO_Always ||
+  (Style.SpaceBeforeParensOptions.AfterPlacementOperator ==
+   FormatStyle::SpaceBeforeParensCustom::APO_Leave &&
+   Right.hasWhitespaceBefore())) {
+return true;
+  }
+  return false;
+}
 if (Line.Type == LT_ObjCDecl)
   return true;
 

[PATCH] D123235: [OpenMP] atomic compare fail : Parser & AST support

2023-10-20 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 557808.
koops added a comment.

1. In class OMPFailClause, the was a duplication in the storage of parameter to 
the fail clause because the parameter was stored as FailParameterKind and 
MemoryOrderClause (FailMemoryOrderClause). There was a possibility of these two 
being out of sync along with confusion to the reader of the code. Hence storing 
FailMemoryOrderClause only. The FailParameterKind (of type ClauseKind) is now 
obtained from the FailMemoryOrderClause when needed.
2. In Visit(const OMPClause *C) there is a check for if (const auto *OMPC = 
dyn_cast(C)). This is mainly done to visit the parameter of the 
FailClause which is a memory Order Clause.


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

https://reviews.llvm.org/D123235

Files:
  clang/include/clang/AST/ASTNodeTraverser.h
  clang/include/clang/AST/OpenMPClause.h
  clang/include/clang/AST/RecursiveASTVisitor.h
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/OpenMPKinds.def
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/AST/OpenMPClause.cpp
  clang/lib/AST/StmtProfile.cpp
  clang/lib/Basic/OpenMPKinds.cpp
  clang/lib/CodeGen/CGStmtOpenMP.cpp
  clang/lib/Parse/ParseOpenMP.cpp
  clang/lib/Sema/SemaOpenMP.cpp
  clang/lib/Sema/TreeTransform.h
  clang/lib/Serialization/ASTReader.cpp
  clang/lib/Serialization/ASTWriter.cpp
  clang/test/OpenMP/atomic_ast_print.cpp
  clang/test/OpenMP/atomic_messages.cpp
  clang/tools/libclang/CIndex.cpp
  flang/lib/Semantics/check-omp-structure.cpp
  llvm/include/llvm/Frontend/OpenMP/OMP.td

Index: llvm/include/llvm/Frontend/OpenMP/OMP.td
===
--- llvm/include/llvm/Frontend/OpenMP/OMP.td
+++ llvm/include/llvm/Frontend/OpenMP/OMP.td
@@ -209,6 +209,7 @@
 def OMPC_Update : Clause<"update"> { let clangClass = "OMPUpdateClause"; }
 def OMPC_Capture : Clause<"capture"> { let clangClass = "OMPCaptureClause"; }
 def OMPC_Compare : Clause<"compare"> { let clangClass = "OMPCompareClause"; }
+def OMPC_Fail : Clause<"fail"> { let clangClass = "OMPFailClause"; }
 def OMPC_SeqCst : Clause<"seq_cst"> { let clangClass = "OMPSeqCstClause"; }
 def OMPC_AcqRel : Clause<"acq_rel"> { let clangClass = "OMPAcqRelClause"; }
 def OMPC_Acquire : Clause<"acquire"> { let clangClass = "OMPAcquireClause"; }
@@ -637,7 +638,8 @@
 VersionedClause,
 VersionedClause,
 VersionedClause,
-VersionedClause
+VersionedClause,
+VersionedClause
   ];
 }
 def OMP_Target : Directive<"target"> {
Index: flang/lib/Semantics/check-omp-structure.cpp
===
--- flang/lib/Semantics/check-omp-structure.cpp
+++ flang/lib/Semantics/check-omp-structure.cpp
@@ -2164,6 +2164,7 @@
 CHECK_SIMPLE_CLAUSE(Doacross, OMPC_doacross)
 CHECK_SIMPLE_CLAUSE(OmpxAttribute, OMPC_ompx_attribute)
 CHECK_SIMPLE_CLAUSE(OmpxBare, OMPC_ompx_bare)
+CHECK_SIMPLE_CLAUSE(Fail, OMPC_fail)
 
 CHECK_REQ_SCALAR_INT_CLAUSE(Grainsize, OMPC_grainsize)
 CHECK_REQ_SCALAR_INT_CLAUSE(NumTasks, OMPC_num_tasks)
Index: clang/tools/libclang/CIndex.cpp
===
--- clang/tools/libclang/CIndex.cpp
+++ clang/tools/libclang/CIndex.cpp
@@ -2402,6 +2402,8 @@
 
 void OMPClauseEnqueue::VisitOMPCompareClause(const OMPCompareClause *) {}
 
+void OMPClauseEnqueue::VisitOMPFailClause(const OMPFailClause *) {}
+
 void OMPClauseEnqueue::VisitOMPSeqCstClause(const OMPSeqCstClause *) {}
 
 void OMPClauseEnqueue::VisitOMPAcqRelClause(const OMPAcqRelClause *) {}
Index: clang/test/OpenMP/atomic_messages.cpp
===
--- clang/test/OpenMP/atomic_messages.cpp
+++ clang/test/OpenMP/atomic_messages.cpp
@@ -958,6 +958,25 @@
 // expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'capture' clause}}
 #pragma omp atomic compare compare capture capture
   { v = a; if (a > b) a = b; }
+// expected-error@+1 {{expected 'compare' clause with the 'fail' modifier}}
+#pragma omp atomic fail(seq_cst)
+  if(v == a) { v = a; }
+// expected-error@+2 {{expected '(' after 'fail'}}
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail
+  if(v < a) { v = a; }
+// expected-error@+1 {{expected a memory order clause}}
+#pragma omp atomic compare fail(capture)
+  if(v < a) { v = a; }
+ // expected-error@+2 {{expected ')' after 'atomic compare fail'}}
+ // expected-warning@+1 {{extra tokens at the end of '#pragma omp atomic' are ignored}}
+#pragma omp atomic compare fail(seq_cst | acquire)
+  if(v < a) { v = a; }
+// expected-error@+1 {{directive '#pragma omp atomic' cannot contain more than one 'fail' clause}}
+#pragma omp atomic compare fail(relaxed) fail(seq_cst)
+  if(v < a) { v = a; }
+
+
 #endif
   // expected-note@+1 {{in instantiation of function template specialization 'mixed' requested here}}
   return

[clang] [Clang][DebugInfo] Clang generates an extra spurious unnamed 'dbg.declare' (PR #69681)

2023-10-20 Thread Orlando Cazalet-Hyams via cfe-commits

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


[clang] [Clang][DebugInfo] Clang generates an extra spurious unnamed 'dbg.declare' (PR #69681)

2023-10-20 Thread Orlando Cazalet-Hyams via cfe-commits

https://github.com/OCHyams commented:

This SGTM.

I don't think the unnamed variable serves any useful purpose but may not being 
imaginative enough. I can't see any discussion on the topic when the code was 
added in [D119178](https://reviews.llvm.org/D119178) . CC the author, @shafik 
(or @adrian-prantl) - is there a use-case for the anonymous variable that 
covers the whole of the structured binding storage?

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


[clang] [Clang][DebugInfo] Clang generates an extra spurious unnamed 'dbg.declare' (PR #69681)

2023-10-20 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -2,10 +2,8 @@
 

OCHyams wrote:

Please can you add `--implicit-check-not="call void @llvm.dbg.declare"` to the 
`FileCheck` command?

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


[clang] [Clang][DebugInfo] Clang generates an extra spurious unnamed 'dbg.declare' (PR #69681)

2023-10-20 Thread Orlando Cazalet-Hyams via cfe-commits


@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone %s -o - | FileCheck 
%s
+
+struct Tuple {
+  int Fld_1;
+  int Fld_2;
+};
+__attribute__((optnone)) Tuple get() { return {10, 20}; }
+
+// CHECK-LABEL: define dso_local noundef i32 @main
+// CHECK:  %retval = alloca i32, align 4
+// CHECK-NEXT: [[T0:%.*]] = alloca %struct.Tuple, align 4
+// CHECK:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression())
+// CHECK:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression(DW_OP_plus_uconst, {{[0-9]+}}))
+// CHECK-NOT:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression())

OCHyams wrote:

It doesn't look like this test covers anything that 
`clang/test/CodeGenCXX/debug-info-structured-binding.cpp` doesn't already?

IMO no need to add this one. Please can you modify the other test to check that 
the DILocalVariables in the dbg.declares have the expected names (i.e., confirm 
there's no unnamed variable).

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

https://github.com/Venyla updated 
https://github.com/llvm/llvm-project/pull/69693

>From 1a49159a4d8186223c0cf87e9225aafe0fd6a2dd Mon Sep 17 00:00:00 2001
From: Vina Zahnd 
Date: Fri, 20 Oct 2023 10:01:54 +0200
Subject: [PATCH] [clangd] Add tweak to inline concept requirements

Co-authored-by: Jeremy Stucki 
---
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../tweaks/InlineConceptRequirement.cpp   | 262 ++
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../tweaks/InlineConceptRequirement.cpp   |  94 +++
 4 files changed, 358 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/InlineConceptRequirement.cpp

diff --git a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt 
b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
index 526a073f619ea34..b01053faf738a90 100644
--- a/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
+++ b/clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt
@@ -21,6 +21,7 @@ add_clang_library(clangDaemonTweaks OBJECT
   ExpandMacro.cpp
   ExtractFunction.cpp
   ExtractVariable.cpp
+  InlineConceptRequirement.cpp
   MemberwiseConstructor.cpp
   ObjCLocalizeStringLiteral.cpp
   ObjCMemberwiseInitializer.cpp
diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
new file mode 100644
index 000..b6c0237703c3474
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/InlineConceptRequirement.cpp
@@ -0,0 +1,262 @@
+//===--- InlineConceptRequirement.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Inlines a concept requirement.
+///
+/// Before:
+///   template  void f(T) requires foo {}
+///^^
+/// After:
+///   template  void f(T) {}
+class InlineConceptRequirement : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+  auto title() const -> std::string override {
+return "Inline concept requirement";
+  }
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  const ConceptSpecializationExpr *ConceptSpecializationExpression;
+  const TemplateTypeParmDecl *TemplateTypeParameterDeclaration;
+  const syntax::Token *RequiresToken;
+
+  static auto getTemplateParameterIndexOfTemplateArgument(
+  const TemplateArgument &TemplateArgument) -> std::optional;
+  auto generateRequiresReplacement(ASTContext &)
+  -> std::variant;
+  auto generateRequiresTokenReplacement(const syntax::TokenBuffer &)
+  -> tooling::Replacement;
+  auto generateTemplateParameterReplacement(ASTContext &Context)
+  -> tooling::Replacement;
+
+  static auto findToken(const ParsedAST *, const SourceRange &,
+const tok::TokenKind) -> const syntax::Token *;
+
+  template 
+  static auto findNode(const SelectionTree::Node &Root)
+  -> std::tuple;
+
+  template 
+  static auto findExpression(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+
+  template 
+  static auto findDeclaration(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+};
+
+REGISTER_TWEAK(InlineConceptRequirement)
+
+auto InlineConceptRequirement::prepare(const Selection &Inputs) -> bool {
+  // Check if C++ version is 20 or higher
+  if (!Inputs.AST->getLangOpts().CPlusPlus20)
+return false;
+
+  const auto *Root = Inputs.ASTSelection.commonAncestor();
+  if (!Root)
+return false;
+
+  const SelectionTree::Node *ConceptSpecializationExpressionTreeNode;
+  std::tie(ConceptSpecializationExpression,
+   ConceptSpecializationExpressionTreeNode) =
+  findExpression(*Root);
+  if (!ConceptSpecializationExpression)
+return false;
+
+  // Only allow concepts that are direct children of function template
+  // declarations or function declarations. This excludes conjunctions of
+  // concepts which are not handled.
+  const auto *ParentDeclaration =
+  ConceptSpecializationExpressionTreeNode->Parent->ASTNode.get();
+  if (!is

[clang] [clang-format] Annotate do while while (PR #69707)

2023-10-20 Thread Björn Schäpers via cfe-commits

https://github.com/HazardyKnusperkeks created 
https://github.com/llvm/llvm-project/pull/69707

So we can differentiate on the while keyword between a do-while-loop and a 
normal while-loop.

From be24095877e6ddd25e0884ad8aaf3eca4846f38d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Fri, 20 Oct 2023 13:00:39 +0200
Subject: [PATCH] [clang-format] Annotate do while while

So we can differentiate on the while keyword between a do-while-loop and a
normal while-loop.
---
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/UnwrappedLineParser.cpp  |  2 ++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 10 ++
 3 files changed, 13 insertions(+)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 606e9e790ad833b..acd24f836199da1 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -67,6 +67,7 @@ namespace format {
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(DoWhile)
\
   TYPE(ElseLBrace) 
\
   TYPE(ElseRBrace) 
\
   TYPE(EnumLBrace) 
\
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7bb487d020ea6f7..488d8dc07b1eae3 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3137,6 +3137,8 @@ void UnwrappedLineParser::parseDoWhile() {
 return;
   }
 
+  FormatTok->setFinalizedType(TT_DoWhile);
+
   // If in Whitesmiths mode, the line with the while() needs to be indented
   // to the same level as the block.
   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 4dbe2a532c5fdb2..290d0103bb3cf87 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2334,6 +2334,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsControlStatements) 
{
   EXPECT_TOKEN(Tokens[5], tok::r_brace, TT_ControlStatementRBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDoWhile) {
+  auto Tokens = annotate("do { ++i; } while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::kw_while, TT_DoWhile);
+
+  Tokens = annotate("do ++i; while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::kw_while, TT_DoWhile);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Amadeus Gebauer via cfe-commits

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


[clang] [clang-format] Annotate do while while (PR #69707)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-format

Author: Björn Schäpers (HazardyKnusperkeks)


Changes

So we can differentiate on the while keyword between a do-while-loop and a 
normal while-loop.

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


3 Files Affected:

- (modified) clang/lib/Format/FormatToken.h (+1) 
- (modified) clang/lib/Format/UnwrappedLineParser.cpp (+2) 
- (modified) clang/unittests/Format/TokenAnnotatorTest.cpp (+10) 


``diff
diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 606e9e790ad833b..acd24f836199da1 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -67,6 +67,7 @@ namespace format {
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(DoWhile)
\
   TYPE(ElseLBrace) 
\
   TYPE(ElseRBrace) 
\
   TYPE(EnumLBrace) 
\
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7bb487d020ea6f7..488d8dc07b1eae3 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3137,6 +3137,8 @@ void UnwrappedLineParser::parseDoWhile() {
 return;
   }
 
+  FormatTok->setFinalizedType(TT_DoWhile);
+
   // If in Whitesmiths mode, the line with the while() needs to be indented
   // to the same level as the block.
   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 4dbe2a532c5fdb2..290d0103bb3cf87 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2334,6 +2334,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsControlStatements) 
{
   EXPECT_TOKEN(Tokens[5], tok::r_brace, TT_ControlStatementRBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDoWhile) {
+  auto Tokens = annotate("do { ++i; } while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::kw_while, TT_DoWhile);
+
+  Tokens = annotate("do ++i; while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::kw_while, TT_DoWhile);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

``




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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Amadeus Gebauer via cfe-commits

amgebauer wrote:

Is there any way to trigger the failing tests within this PR?

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


[clang-tools-extra] [analyzer] Add std::variant checker (PR #66481)

2023-10-20 Thread Gábor Spaits via cfe-commits


@@ -0,0 +1,104 @@
+//===- TaggedUnionModeling.h -*- 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_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+#define LLVM_CLANG_LIB_STATICANALYZER_CHECKER_VARIANTLIKETYPEMODELING_H
+
+#include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
+#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
+#include "clang/StaticAnalyzer/Core/Checker.h"
+#include "clang/StaticAnalyzer/Core/CheckerManager.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallDescription.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
+#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/ADT/FoldingSet.h"
+#include 
+
+namespace clang {
+namespace ento {
+namespace tagged_union_modeling {
+
+// The implementation of all these functions can be found in the file
+// StdVariantChecker.cpp under the same directory as this file.
+CallEventRef<> getCaller(const CallEvent &Call, CheckerContext &C);
+bool isCopyConstructorCall(const CallEvent &Call);
+bool isCopyAssignmentCall(const CallEvent &Call);
+bool isMoveAssignmentCall(const CallEvent &Call);
+bool isMoveConstructorCall(const CallEvent &Call);
+bool isStdType(const Type *Type, const std::string &TypeName);
+bool isStdVariant(const Type *Type);
+bool calledFromSystemHeader(const CallEvent &Call, CheckerContext &C);
+
+// When invalidating regions, we also have to follow that by invalidating the
+// corresponding custom data in the program state.
+template 
+ProgramStateRef
+removeInformationStoredForDeadInstances(const CallEvent *Call,

spaits wrote:

This is called from the checkRegionChanges callback. That callback has a const 
CallEvent * parameter and that is passed here. I can modify my function to take 
a const CallEvent &, but it is only called from checkRegionChanges callbacks. 
Should I still modify it to reference?

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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Björn Schäpers via cfe-commits

https://github.com/HazardyKnusperkeks updated 
https://github.com/llvm/llvm-project/pull/68743

From be24095877e6ddd25e0884ad8aaf3eca4846f38d Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Fri, 20 Oct 2023 13:00:39 +0200
Subject: [PATCH 1/2] [clang-format] Annotate do while while

So we can differentiate on the while keyword between a do-while-loop and a
normal while-loop.
---
 clang/lib/Format/FormatToken.h|  1 +
 clang/lib/Format/UnwrappedLineParser.cpp  |  2 ++
 clang/unittests/Format/TokenAnnotatorTest.cpp | 10 ++
 3 files changed, 13 insertions(+)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 606e9e790ad833b..acd24f836199da1 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -67,6 +67,7 @@ namespace format {
   TYPE(DesignatedInitializerLSquare)   
\
   TYPE(DesignatedInitializerPeriod)
\
   TYPE(DictLiteral)
\
+  TYPE(DoWhile)
\
   TYPE(ElseLBrace) 
\
   TYPE(ElseRBrace) 
\
   TYPE(EnumLBrace) 
\
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7bb487d020ea6f7..488d8dc07b1eae3 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3137,6 +3137,8 @@ void UnwrappedLineParser::parseDoWhile() {
 return;
   }
 
+  FormatTok->setFinalizedType(TT_DoWhile);
+
   // If in Whitesmiths mode, the line with the while() needs to be indented
   // to the same level as the block.
   if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths)
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 4dbe2a532c5fdb2..290d0103bb3cf87 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -2334,6 +2334,16 @@ TEST_F(TokenAnnotatorTest, UnderstandsControlStatements) 
{
   EXPECT_TOKEN(Tokens[5], tok::r_brace, TT_ControlStatementRBrace);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsDoWhile) {
+  auto Tokens = annotate("do { ++i; } while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 14u) << Tokens;
+  EXPECT_TOKEN(Tokens[6], tok::kw_while, TT_DoWhile);
+
+  Tokens = annotate("do ++i; while ( i > 5 );");
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::kw_while, TT_DoWhile);
+}
+
 } // namespace
 } // namespace format
 } // namespace clang

From 141443c2df008fa6fb7f283a025135712cce92a7 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Sch=C3=A4pers?= 
Date: Tue, 10 Oct 2023 22:50:43 +0200
Subject: [PATCH 2/2] [clang-format] Don't align comments over scopes

We now stop aligning trailing comments on all closing braces, for
classes etc. we even check for the semicolon between the comment and the
brace.

Fixes #67906.
---
 clang/lib/Format/WhitespaceManager.cpp|  44 -
 clang/unittests/Format/FormatTestComments.cpp | 176 --
 2 files changed, 199 insertions(+), 21 deletions(-)

diff --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index dc81060671c1712..67e5dd4c04445eb 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1048,6 +1048,9 @@ void WhitespaceManager::alignChainedConditionals() {
 }
 
 void WhitespaceManager::alignTrailingComments() {
+  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
+return;
+
   const int Size = Changes.size();
   int MinColumn = 0;
   int StartOfSequence = 0;
@@ -1118,16 +1121,39 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+const bool DontAlignThisComment = [&] {
+  if (I == 0 || C.NewlinesBefore > 0)
+return false;
+  const auto *Tok = Changes[I - 1].Tok;
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->isNot(tok::r_brace)) {
+if (Tok->isNot(tok::r_paren) || !Tok->MatchingParen)
+  return false;
+auto BeforeParent = Tok->MatchingParen->getPreviousNonComment();
+return BeforeParent && BeforeParent->is(TT_DoWhile);
+  }
+
+  f

[clang] [clang-format] Annotate do while while (PR #69707)

2023-10-20 Thread Owen Pan via cfe-commits

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


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


[clang] [clang-format] Don't align comments over scopes (PR #68743)

2023-10-20 Thread Björn Schäpers via cfe-commits

HazardyKnusperkeks wrote:

Some pathological test cases added and handling do-while (relying on #69707).
Only a reply from @mydeveloperday open regarding the change of the existing 
test with function braces.

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Utkarsh Saxena via cfe-commits


@@ -10085,10 +10085,14 @@ getImplicitObjectParamType(ASTContext &Context, const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
+static bool allowAmbiguityWithSelf(ASTContext &Context, const FunctionDecl *F1,

usx95 wrote:

I added a todo to get rid of the parameter type checks. I do not see any test 
failures without it.
Since this could again be a potentially breaking change, I will try cleaning 
this up in a separate PR.

Changed the name to `allowAmbiguity`. 

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/69595

>From 4460b02508d21d98cf05103bece99fc5bd474ab0 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 19 Oct 2023 12:33:45 +0200
Subject: [PATCH 1/5] Reapply "Correctly compute conversion seq for args to fn
 with reversed param order (#68999)"

This reverts commit a3a0f59a1e1cb0ac02f06b19f730ea05a6541c96.
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/SemaOverload.cpp   |  2 +-
 .../over.match.oper/p3-2a.cpp | 35 +++
 3 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index eee48431d716878..f6ad453cb17f9d9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -117,6 +117,8 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
+- Fix a bug in conversion sequence of arguments to a function with reversed 
parameter order.
+  Fixes `GH `_.
 
 C++23 Feature Support
 ^
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index ce78994e6553814..c271cebb9eb638f 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7688,7 +7688,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)
  : (ThisConversions + I);
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5c6804eb7726b5f..02fe37dc1be5058 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -324,6 +324,41 @@ bool x = X() == X(); // expected-warning {{ambiguous}}
 }
 } // namespace P2468R2
 
+namespace GH53954{
+namespace test1 {
+struct P {
+template 
+friend bool operator==(const P&, const T&); // expected-note {{candidate}} 
\
+  // expected-note {{reversed 
parameter order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+
+namespace test2 {
+struct P {
+template 
+friend bool operator==(const T&, const P&); // expected-note {{candidate}} 
\
+// expected-note {{reversed 
parameter order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+
+namespace test3 {
+struct P {
+  template
+  bool operator==(const S &) const; // expected-note {{candidate}} \
+// expected-note {{reversed parameter 
order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+}
+
 #else // NO_ERRORS
 
 namespace problem_cases {

>From 12f5b5e43e51fbd966fc99d82c5d04019cfa3adf Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 19 Oct 2023 14:02:24 +0200
Subject: [PATCH 2/5] Do not hard error for ambiguity with reversed arguments
 for templated operators

---
 clang/docs/ReleaseNotes.rst   | 18 -
 clang/lib/Sema/SemaOverload.cpp   | 10 +++--
 .../over.match.oper/p3-2a.cpp | 40 ++-
 3 files changed, 54 insertions(+), 14 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f6ad453cb17f9d9..a38cd74b6165c84 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,22 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+  ```
+  struct P {};
+  template bool operator==(const P&, const S &);
+
+  struct A : public P {};
+  struct B : public P {};
+  // This equality is now ambiguous in C++20.
+  bool check(A a, B b) { return a == b; } 
+  ```
+  To reduce widespread breakages, as an extension, clang would accept this 
with a
+  `-Wambiguous-reversed-operator` warning.
+  Fixes `GH `_.
+
+
 
 C/C++ Language Potentially Breaking Changes
 ---
@@ -117,8 +133,6 @@ C++ Language Changes
 
 C++20 Feature Support
 ^^^

[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Utkarsh Saxena via cfe-commits

https://github.com/usx95 updated https://github.com/llvm/llvm-project/pull/69595

>From 4460b02508d21d98cf05103bece99fc5bd474ab0 Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 19 Oct 2023 12:33:45 +0200
Subject: [PATCH 1/6] Reapply "Correctly compute conversion seq for args to fn
 with reversed param order (#68999)"

This reverts commit a3a0f59a1e1cb0ac02f06b19f730ea05a6541c96.
---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/lib/Sema/SemaOverload.cpp   |  2 +-
 .../over.match.oper/p3-2a.cpp | 35 +++
 3 files changed, 38 insertions(+), 1 deletion(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index eee48431d716878..f6ad453cb17f9d9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -117,6 +117,8 @@ C++ Language Changes
 
 C++20 Feature Support
 ^
+- Fix a bug in conversion sequence of arguments to a function with reversed 
parameter order.
+  Fixes `GH `_.
 
 C++23 Feature Support
 ^
diff --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index ce78994e6553814..c271cebb9eb638f 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -7688,7 +7688,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)
  : (ThisConversions + I);
   Conversions[ConvIdx]
 = TryCopyInitialization(*this, Args[I], ParamType,
diff --git 
a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp 
b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
index 5c6804eb7726b5f..02fe37dc1be5058 100644
--- a/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
+++ b/clang/test/CXX/over/over.match/over.match.funcs/over.match.oper/p3-2a.cpp
@@ -324,6 +324,41 @@ bool x = X() == X(); // expected-warning {{ambiguous}}
 }
 } // namespace P2468R2
 
+namespace GH53954{
+namespace test1 {
+struct P {
+template 
+friend bool operator==(const P&, const T&); // expected-note {{candidate}} 
\
+  // expected-note {{reversed 
parameter order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+
+namespace test2 {
+struct P {
+template 
+friend bool operator==(const T&, const P&); // expected-note {{candidate}} 
\
+// expected-note {{reversed 
parameter order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+
+namespace test3 {
+struct P {
+  template
+  bool operator==(const S &) const; // expected-note {{candidate}} \
+// expected-note {{reversed parameter 
order}}
+};
+struct A : public P {};
+struct B : public P {};
+bool check(A a, B b) { return a == b; } // expected-error {{ '==' is 
ambiguous}}
+}
+}
+
 #else // NO_ERRORS
 
 namespace problem_cases {

>From 12f5b5e43e51fbd966fc99d82c5d04019cfa3adf Mon Sep 17 00:00:00 2001
From: Utkarsh Saxena 
Date: Thu, 19 Oct 2023 14:02:24 +0200
Subject: [PATCH 2/6] Do not hard error for ambiguity with reversed arguments
 for templated operators

---
 clang/docs/ReleaseNotes.rst   | 18 -
 clang/lib/Sema/SemaOverload.cpp   | 10 +++--
 .../over.match.oper/p3-2a.cpp | 40 ++-
 3 files changed, 54 insertions(+), 14 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index f6ad453cb17f9d9..a38cd74b6165c84 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -37,6 +37,22 @@ These changes are ones which we think may surprise users 
when upgrading to
 Clang |release| because of the opportunity they pose for disruption to existing
 code bases.
 
+- Fix a bug in reversed argument for templated operators.
+  This breaks code in C++20 which was previously accepted in C++17. Eg:
+  ```
+  struct P {};
+  template bool operator==(const P&, const S &);
+
+  struct A : public P {};
+  struct B : public P {};
+  // This equality is now ambiguous in C++20.
+  bool check(A a, B b) { return a == b; } 
+  ```
+  To reduce widespread breakages, as an extension, clang would accept this 
with a
+  `-Wambiguous-reversed-operator` warning.
+  Fixes `GH `_.
+
+
 
 C/C++ Language Potentially Breaking Changes
 ---
@@ -117,8 +133,6 @@ C++ Language Changes
 
 C++20 Feature Support
 ^^^

[clang] [clang] Fix designated initializers inside templates (PR #69712)

2023-10-20 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon created 
https://github.com/llvm/llvm-project/pull/69712

Skip anonymous members when rebuilding DesignatedInitExpr since designated 
inits for them are meant to be created during
`InitListChecker::CheckDesignatedInitializer` routine.

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

>From 60d90fc60363d1b45734fe4d6099f7a7db6f4497 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Fri, 20 Oct 2023 04:26:41 -0700
Subject: [PATCH] [clang] Fix designated initializers inside templates

Skip anonymous members when rebuilding DesignatedInitExpr since designated
inits for them are meant to be created during
`InitListChecker::CheckDesignatedInitializer` routine.

Fixes https://github.com/llvm/llvm-project/issues/65143
---
 clang/docs/ReleaseNotes.rst   |  3 +++
 clang/lib/Sema/TreeTransform.h|  6 +++--
 .../SemaCXX/cxx2b-designated-initializers.cpp | 23 +--
 3 files changed, 28 insertions(+), 4 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..ffb32c254b256dd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -412,6 +412,9 @@ Bug Fixes in This Version
 - Clang no longer permits using the `_BitInt` types as an underlying type for 
an
   enumeration as specified in the C23 Standard.
   Fixes (`#69619 `_)
+- Clang now accepts anonymous members initialized with designated initializers
+  inside templates.
+  Fixes (`#65143 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 8fafdd4f5caa1ed..094e5efa939f4d1 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -11783,8 +11783,6 @@ 
TreeTransform::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   bool ExprChanged = false;
   for (const DesignatedInitExpr::Designator &D : E->designators()) {
 if (D.isFieldDesignator()) {
-  Desig.AddDesignator(Designator::CreateFieldDesignator(
-  D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
   if (D.getFieldDecl()) {
 FieldDecl *Field = cast_or_null(
 getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
@@ -11792,12 +11790,16 @@ 
TreeTransform::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   // Rebuild the expression when the transformed FieldDecl is
   // different to the already assigned FieldDecl.
   ExprChanged = true;
+if (Field->isAnonymousStructOrUnion())
+  continue;
   } else {
 // Ensure that the designator expression is rebuilt when there isn't
 // a resolved FieldDecl in the designator as we don't want to assign
 // a FieldDecl to a pattern designator that will be instantiated again.
 ExprChanged = true;
   }
+  Desig.AddDesignator(Designator::CreateFieldDesignator(
+  D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
   continue;
 }
 
diff --git a/clang/test/SemaCXX/cxx2b-designated-initializers.cpp 
b/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
index 5588926f419a932..1d9b9183b3679f1 100644
--- a/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
+++ b/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
@@ -9,17 +9,36 @@ union S {
 };
 
 void f(int x, auto) {
-  const S result { // expected-error {{field designator (null) does not refer 
to any field in type 'const S'}}
+  const S result {
 .a = x
   };
 }
 
 void g(void) {
-  f(0, 0); // expected-note {{in instantiation of function template 
specialization 'PR61118::f' requested here}}
+  f(0, 0);
 }
 
 } // end namespace PR61118
 
+namespace GH65143 {
+struct Inner {
+  int a;
+};
+
+struct Outer {
+  struct {
+Inner inner;
+  };
+};
+
+template  void f() {
+  constexpr Outer x{.inner = {val}};
+  static_assert(x.inner.a == val);
+}
+
+void bar() { f<4>(); }
+}
+
 namespace GH62156 {
 union U1 {
int x;

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


[clang] [clang] Fix designated initializers inside templates (PR #69712)

2023-10-20 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mariya Podchishchaeva (Fznamznon)


Changes

Skip anonymous members when rebuilding DesignatedInitExpr since designated 
inits for them are meant to be created during
`InitListChecker::CheckDesignatedInitializer` routine.

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

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+3) 
- (modified) clang/lib/Sema/TreeTransform.h (+4-2) 
- (modified) clang/test/SemaCXX/cxx2b-designated-initializers.cpp (+21-2) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index fc8caf9221b9d29..ffb32c254b256dd 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -412,6 +412,9 @@ Bug Fixes in This Version
 - Clang no longer permits using the `_BitInt` types as an underlying type for 
an
   enumeration as specified in the C23 Standard.
   Fixes (`#69619 `_)
+- Clang now accepts anonymous members initialized with designated initializers
+  inside templates.
+  Fixes (`#65143 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 8fafdd4f5caa1ed..094e5efa939f4d1 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -11783,8 +11783,6 @@ 
TreeTransform::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   bool ExprChanged = false;
   for (const DesignatedInitExpr::Designator &D : E->designators()) {
 if (D.isFieldDesignator()) {
-  Desig.AddDesignator(Designator::CreateFieldDesignator(
-  D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
   if (D.getFieldDecl()) {
 FieldDecl *Field = cast_or_null(
 getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
@@ -11792,12 +11790,16 @@ 
TreeTransform::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   // Rebuild the expression when the transformed FieldDecl is
   // different to the already assigned FieldDecl.
   ExprChanged = true;
+if (Field->isAnonymousStructOrUnion())
+  continue;
   } else {
 // Ensure that the designator expression is rebuilt when there isn't
 // a resolved FieldDecl in the designator as we don't want to assign
 // a FieldDecl to a pattern designator that will be instantiated again.
 ExprChanged = true;
   }
+  Desig.AddDesignator(Designator::CreateFieldDesignator(
+  D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
   continue;
 }
 
diff --git a/clang/test/SemaCXX/cxx2b-designated-initializers.cpp 
b/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
index 5588926f419a932..1d9b9183b3679f1 100644
--- a/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
+++ b/clang/test/SemaCXX/cxx2b-designated-initializers.cpp
@@ -9,17 +9,36 @@ union S {
 };
 
 void f(int x, auto) {
-  const S result { // expected-error {{field designator (null) does not refer 
to any field in type 'const S'}}
+  const S result {
 .a = x
   };
 }
 
 void g(void) {
-  f(0, 0); // expected-note {{in instantiation of function template 
specialization 'PR61118::f' requested here}}
+  f(0, 0);
 }
 
 } // end namespace PR61118
 
+namespace GH65143 {
+struct Inner {
+  int a;
+};
+
+struct Outer {
+  struct {
+Inner inner;
+  };
+};
+
+template  void f() {
+  constexpr Outer x{.inner = {val}};
+  static_assert(x.inner.a == val);
+}
+
+void bar() { f<4>(); }
+}
+
 namespace GH62156 {
 union U1 {
int x;

``




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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Piotr Zegar via cfe-commits

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

LGTM

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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

> Is there any way to trigger the failing tests within this PR?

No, in worst case we can revert faulty change.

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -7688,7 +7688,7 @@ bool Sema::CheckNonDependentConversions(
 QualType ParamType = ParamTypes[I + Offset];
 if (!ParamType->isDependentType()) {
   unsigned ConvIdx = PO == OverloadCandidateParamOrder::Reversed
- ? 0
+ ? Args.size() - 1 - (ThisConversions + I)

ilya-biryukov wrote:

Thanks for clearing this up for me offline. After going through an example I 
finally got what was wrong here.
For reversed operators `Args.size()` is always 2. When `ThisConversions == 0` 
(i.e. non-methods), we were writing conversions for *both* arguments into 
`ConvIdx == 0`, after this change we correctly loop through both.
When `ThisConversions == 1`, both versions work the same.

Indeed, the tests you added already check this behavior. Thanks! Resolving this.

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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

Lets push this, if it wont help then we can revert oryginal change.

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


[clang-tools-extra] 49af650 - [run-clang-tidy] Accept export directory if PyYAML is not installed (#69700)

2023-10-20 Thread via cfe-commits

Author: Amadeus Gebauer
Date: 2023-10-20T13:40:38+02:00
New Revision: 49af6502c6dcb4a7f7520178bd14df396f78240c

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

LOG: [run-clang-tidy] Accept export directory if PyYAML is not installed 
(#69700)

If PyYAML is not installed, the `-export-fixes` can be used to specify a
directory (not a file).

Mentioning @PiotrZSL @dyung 

Follows #69453

Added: 


Modified: 
clang-tools-extra/clang-tidy/tool/clang-tidy-diff.py
clang-tools-extra/clang-tidy/tool/run-clang-tidy.py

Removed: 




diff  --git a/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py b/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
index 6fb5eedf06d5dff..8817e2914f6e25b 100755
--- a/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
+++ b/clang-tools-extra/clang-tidy/tool/clang-tidy-
diff .py
@@ -187,6 +187,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="DIRECTORY",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-extra-arg",
 dest="extra_arg",
@@ -270,7 +279,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):

diff  --git a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py 
b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
index aa628aa87800693..179759216196f88 100755
--- a/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
+++ b/clang-tools-extra/clang-tidy/tool/run-clang-tidy.py
@@ -315,6 +315,15 @@ def main():
 "parameter is a directory, the fixes of each compilation unit are "
 "stored in individual yaml files in the directory.",
 )
+else:
+parser.add_argument(
+"-export-fixes",
+metavar="directory",
+dest="export_fixes",
+help="A directory to store suggested fixes in, which can be 
applied "
+"with clang-apply-replacements. The fixes of each compilation unit 
are "
+"stored in individual yaml files in the directory.",
+)
 parser.add_argument(
 "-j",
 type=int,
@@ -401,7 +410,12 @@ def main():
 ):
 os.makedirs(args.export_fixes)
 
-if not os.path.isdir(args.export_fixes) and yaml:
+if not os.path.isdir(args.export_fixes):
+if not yaml:
+raise RuntimeError(
+"Cannot combine fixes in one yaml file. Either install 
PyYAML or specify an output directory."
+)
+
 combine_fixes = True
 
 if os.path.isdir(args.export_fixes):



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


[clang-tools-extra] [run-clang-tidy] Accept export directory if PyYAML is not installed (PR #69700)

2023-10-20 Thread Piotr Zegar via cfe-commits

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits

https://github.com/ilya-biryukov approved this pull request.

The change looks good, I believe the comments about potentially redundant 
checks and naming of the function could be addressed in a follow-up.

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


[clang] [clang] Handle templated operators with reversed arguments (PR #69595)

2023-10-20 Thread Ilya Biryukov via cfe-commits


@@ -10085,10 +10085,14 @@ getImplicitObjectParamType(ASTContext &Context, const 
FunctionDecl *F) {
   return M->getFunctionObjectParameterReferenceType();
 }
 
-static bool haveSameParameterTypes(ASTContext &Context, const FunctionDecl *F1,
+static bool allowAmbiguityWithSelf(ASTContext &Context, const FunctionDecl *F1,

ilya-biryukov wrote:

`allowAmbiguity` looks fine, thanks!

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


[clang] [clang][Interp] Implement builintin_expect (PR #69713)

2023-10-20 Thread Timm Baeder via cfe-commits

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

None

>From 12cb6e61a8e77a7800fda0ae4dd1148e76844da8 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Fri, 20 Oct 2023 14:16:22 +0200
Subject: [PATCH] [clang][Interp] Implement builintin_expect

---
 clang/lib/AST/Interp/InterpBuiltin.cpp| 69 +++
 clang/test/AST/Interp/builtin-functions.cpp   |  8 +++
 .../Sema/builtin-expect-with-probability.cpp  |  1 +
 3 files changed, 78 insertions(+)

diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index 7552c1b88cff60c..d5b694a97ca14a3 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -33,6 +33,19 @@ PrimType getIntPrimType(const InterpState &S) {
   llvm_unreachable("Int isn't 16 or 32 bit?");
 }
 
+PrimType getLongPrimType(const InterpState &S) {
+  const TargetInfo &TI = S.getCtx().getTargetInfo();
+  unsigned LongWidth = TI.getLongWidth();
+
+  if (LongWidth == 64)
+return PT_Sint64;
+  else if (LongWidth == 32)
+return PT_Sint32;
+  else if (LongWidth == 16)
+return PT_Sint16;
+  llvm_unreachable("long isn't 16, 32 or 64 bit?");
+}
+
 /// Peek an integer value from the stack into an APSInt.
 static APSInt peekToAPSInt(InterpStack &Stk, PrimType T, size_t Offset = 0) {
   if (Offset == 0)
@@ -59,6 +72,19 @@ static void pushInt(InterpState &S, int32_t Val) {
 llvm_unreachable("Int isn't 16 or 32 bit?");
 }
 
+/// Pushes \p Val to the stack, as a target-dependent 'long'.
+static void pushLong(InterpState &S, int64_t Val) {
+  PrimType LongType = getLongPrimType(S);
+  if (LongType == PT_Sint64)
+S.Stk.push>(Integral<64, true>::from(Val));
+  else if (LongType == PT_Sint32)
+S.Stk.push>(Integral<32, true>::from(Val));
+  else if (LongType == PT_Sint16)
+S.Stk.push>(Integral<16, true>::from(Val));
+  else
+llvm_unreachable("Long isn't 16, 32 or 64 bit?");
+}
+
 static bool retInt(InterpState &S, CodePtr OpPC, APValue &Result) {
   PrimType IntType = getIntPrimType(S);
   if (IntType == PT_Sint32)
@@ -68,6 +94,17 @@ static bool retInt(InterpState &S, CodePtr OpPC, APValue 
&Result) {
   llvm_unreachable("Int isn't 16 or 32 bit?");
 }
 
+static bool retLong(InterpState &S, CodePtr OpPC, APValue &Result) {
+  PrimType LongType = getLongPrimType(S);
+  if (LongType == PT_Sint64)
+return Ret(S, OpPC, Result);
+  else if (LongType == PT_Sint32)
+return Ret(S, OpPC, Result);
+  else if (LongType == PT_Sint16)
+return Ret(S, OpPC, Result);
+  llvm_unreachable("Int isn't 16 or 32 bit?");
+}
+
 static void pushSizeT(InterpState &S, uint64_t Val) {
   const TargetInfo &TI = S.getCtx().getTargetInfo();
   unsigned SizeTWidth = TI.getTypeWidth(TI.getSizeType());
@@ -409,6 +446,32 @@ static bool interp__builtin_popcount(InterpState &S, 
CodePtr OpPC,
   return true;
 }
 
+// __builtin_expect(long, long) or
+// __builtin_expect_with_probability(long, long, double)
+static bool interp__builtin_expect(InterpState &S, CodePtr OpPC,
+   const InterpFrame *Frame,
+   const Function *Func,
+   const CallExpr *Call) {
+  // The return value is simply the value of the first parameter.
+  // We ignore the probability.
+  unsigned NumArgs = Call->getNumArgs();
+  PrimType ArgT = *S.getContext().classify(Call->getArg(0)->getType());
+
+  assert(NumArgs == 2 || NumArgs == 3);
+
+  // The top of the stack is the probability (either as a long for 
builtin_expect()
+  // or as a float for builtin_expect_with_probability()), which we want to 
ignore
+  // entirely.
+  size_t LongSize = align(primSize(getLongPrimType(S))) * 2;
+  unsigned Offset = LongSize;
+  if (NumArgs == 3)
+Offset += align(primSize(PT_Float));
+
+  APSInt Val = peekToAPSInt(S.Stk, ArgT, Offset);
+  pushLong(S, Val.getSExtValue());
+  return true;
+}
+
 bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const Function *F,
   const CallExpr *Call) {
   InterpFrame *Frame = S.Current;
@@ -534,6 +597,12 @@ bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const 
Function *F,
   return retInt(S, OpPC, Dummy);
 break;
 
+  case Builtin::BI__builtin_expect:
+  case Builtin::BI__builtin_expect_with_probability:
+if (interp__builtin_expect(S, OpPC, Frame, F, Call))
+  return retLong(S, OpPC, Dummy);
+break;
+
   default:
 return false;
   }
diff --git a/clang/test/AST/Interp/builtin-functions.cpp 
b/clang/test/AST/Interp/builtin-functions.cpp
index 65361d67d68d578..d928b494a5204a6 100644
--- a/clang/test/AST/Interp/builtin-functions.cpp
+++ b/clang/test/AST/Interp/builtin-functions.cpp
@@ -282,3 +282,11 @@ namespace popcount {
   char popcount9[__builtin_popcountll(0xF0F0LL) == 8 ? 1 : -1];
   char popcount10[__builtin_popcountll(~0LL) == BITSIZE(long long) ? 1 : -1];
 }
+
+namespace expect {
+  constexpr int a() {
+return

[clang] [clang][Interp] Implement builintin_expect (PR #69713)

2023-10-20 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 ba8565fbcb975e2d067ce3ae5a7dbaae4953edd3 
12cb6e61a8e77a7800fda0ae4dd1148e76844da8 -- 
clang/lib/AST/Interp/InterpBuiltin.cpp 
clang/test/AST/Interp/builtin-functions.cpp 
clang/test/Sema/builtin-expect-with-probability.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/AST/Interp/InterpBuiltin.cpp 
b/clang/lib/AST/Interp/InterpBuiltin.cpp
index d5b694a97ca1..fb6c1dc7a257 100644
--- a/clang/lib/AST/Interp/InterpBuiltin.cpp
+++ b/clang/lib/AST/Interp/InterpBuiltin.cpp
@@ -450,8 +450,7 @@ static bool interp__builtin_popcount(InterpState &S, 
CodePtr OpPC,
 // __builtin_expect_with_probability(long, long, double)
 static bool interp__builtin_expect(InterpState &S, CodePtr OpPC,
const InterpFrame *Frame,
-   const Function *Func,
-   const CallExpr *Call) {
+   const Function *Func, const CallExpr *Call) 
{
   // The return value is simply the value of the first parameter.
   // We ignore the probability.
   unsigned NumArgs = Call->getNumArgs();
@@ -459,9 +458,9 @@ static bool interp__builtin_expect(InterpState &S, CodePtr 
OpPC,
 
   assert(NumArgs == 2 || NumArgs == 3);
 
-  // The top of the stack is the probability (either as a long for 
builtin_expect()
-  // or as a float for builtin_expect_with_probability()), which we want to 
ignore
-  // entirely.
+  // The top of the stack is the probability (either as a long for
+  // builtin_expect() or as a float for builtin_expect_with_probability()),
+  // which we want to ignore entirely.
   size_t LongSize = align(primSize(getLongPrimType(S))) * 2;
   unsigned Offset = LongSize;
   if (NumArgs == 3)

``




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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits




5chmidti wrote:

Clangd (actually large parts of llvm) don't use trailing return types, you will 
probably have to change those. This is a bit of a chore, so you could wait for 
another reviewer to confirm that for you.

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


[clang-tools-extra] [clangd] Add tweak to inline concept requirements (PR #69693)

2023-10-20 Thread via cfe-commits


@@ -0,0 +1,262 @@
+//===--- InlineConceptRequirement.cpp *- 
C++-*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+#include "ParsedAST.h"
+#include "SourceCode.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Inlines a concept requirement.
+///
+/// Before:
+///   template  void f(T) requires foo {}
+///^^
+/// After:
+///   template  void f(T) {}
+class InlineConceptRequirement : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+  auto title() const -> std::string override {
+return "Inline concept requirement";
+  }
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  const ConceptSpecializationExpr *ConceptSpecializationExpression;
+  const TemplateTypeParmDecl *TemplateTypeParameterDeclaration;
+  const syntax::Token *RequiresToken;
+
+  static auto getTemplateParameterIndexOfTemplateArgument(
+  const TemplateArgument &TemplateArgument) -> std::optional;
+  auto generateRequiresReplacement(ASTContext &)
+  -> std::variant;
+  auto generateRequiresTokenReplacement(const syntax::TokenBuffer &)
+  -> tooling::Replacement;
+  auto generateTemplateParameterReplacement(ASTContext &Context)
+  -> tooling::Replacement;
+
+  static auto findToken(const ParsedAST *, const SourceRange &,
+const tok::TokenKind) -> const syntax::Token *;
+
+  template 
+  static auto findNode(const SelectionTree::Node &Root)
+  -> std::tuple;
+
+  template 
+  static auto findExpression(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+
+  template 
+  static auto findDeclaration(const SelectionTree::Node &Root)
+  -> std::tuple {
+return findNode(Root);
+  }
+};
+
+REGISTER_TWEAK(InlineConceptRequirement)
+
+auto InlineConceptRequirement::prepare(const Selection &Inputs) -> bool {
+  // Check if C++ version is 20 or higher
+  if (!Inputs.AST->getLangOpts().CPlusPlus20)
+return false;
+
+  const auto *Root = Inputs.ASTSelection.commonAncestor();
+  if (!Root)
+return false;
+
+  const SelectionTree::Node *ConceptSpecializationExpressionTreeNode;
+  std::tie(ConceptSpecializationExpression,
+   ConceptSpecializationExpressionTreeNode) =
+  findExpression(*Root);
+  if (!ConceptSpecializationExpression)
+return false;
+
+  // Only allow concepts that are direct children of function template
+  // declarations or function declarations. This excludes conjunctions of
+  // concepts which are not handled.
+  const auto *ParentDeclaration =
+  ConceptSpecializationExpressionTreeNode->Parent->ASTNode.get();
+  if (!isa_and_nonnull(ParentDeclaration) &&
+  !isa_and_nonnull(ParentDeclaration))
+return false;
+
+  const FunctionTemplateDecl *FunctionTemplateDeclaration =
+  std::get<0>(findDeclaration(*Root));
+  if (!FunctionTemplateDeclaration)
+return false;
+
+  auto TemplateArguments =
+  ConceptSpecializationExpression->getTemplateArguments();
+  if (TemplateArguments.size() != 1)
+return false;
+
+  auto TemplateParameterIndex =
+  getTemplateParameterIndexOfTemplateArgument(TemplateArguments[0]);
+  if (!TemplateParameterIndex)
+return false;
+
+  TemplateTypeParameterDeclaration = dyn_cast_or_null(
+  FunctionTemplateDeclaration->getTemplateParameters()->getParam(
+  *TemplateParameterIndex));
+  if (!TemplateTypeParameterDeclaration->wasDeclaredWithTypename())
+return false;
+
+  RequiresToken =
+  findToken(Inputs.AST, FunctionTemplateDeclaration->getSourceRange(),
+tok::kw_requires);
+  if (!RequiresToken)
+return false;
+
+  return true;
+}
+
+auto InlineConceptRequirement::apply(const Selection &Inputs)
+-> Expected {
+  auto &Context = Inputs.AST->getASTContext();
+  auto &TokenBuffer = Inputs.AST->getTokens();
+
+  tooling::Replacements Replacements{};
+
+  if (auto Err =
+  Replacements.add(generateTemplateParameterReplacement(Context)))
+return Err;
+
+  auto RequiresReplacement = generateRequiresReplacement(Context);
+
+  if (std::holds_alternative(RequiresReplacement))
+return std::move(std::get(RequiresReplacement));
+
+  if (auto Err =
+  
Replacements.add(std::get(RequiresReplacement)))

  1   2   3   4   >