[clang] [clang][Docs] Document X86 interrupt attribute (PR #65662)

2023-09-16 Thread via cfe-commits

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


[clang] da35b2e - [clang][Docs] Document X86 interrupt attribute (#65662)

2023-09-16 Thread via cfe-commits

Author: antangelo
Date: 2023-09-17T01:26:26-04:00
New Revision: da35b2e57a164ec62278f1685d0c684c5bc2d666

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

LOG: [clang][Docs] Document X86 interrupt attribute (#65662)

Adds documentation for the X86 `__attribute__((interrupt))` attribute,
in a similar format to interrupt attributes of
other platforms.

Migrated from https://reviews.llvm.org/D159317

Added: 


Modified: 
clang/include/clang/Basic/Attr.td
clang/include/clang/Basic/AttrDocs.td

Removed: 




diff  --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index c95db7e8049d47a..21a3b5226623cf2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3125,7 +3125,7 @@ def AnyX86Interrupt : InheritableAttr, 
TargetSpecificAttr {
   let Subjects = SubjectList<[HasFunctionProto]>;
   let ParseKind = "Interrupt";
   let HasCustomParsing = 1;
-  let Documentation = [Undocumented];
+  let Documentation = [AnyX86InterruptDocs];
 }
 
 def AnyX86NoCallerSavedRegisters : InheritableAttr,

diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f11ea89d14bad0d..c3fe7cea29afbf1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4801,6 +4801,54 @@ Marking virtual functions as ``disable_tail_calls`` is 
legal.
   }];
 }
 
+def AnyX86InterruptDocs : Documentation {
+let Category = DocCatFunction;
+let Heading = "interrupt (X86)";
+let Content = [{
+Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
+targets. This attribute may be attached to a function definition and instructs
+the backend to generate appropriate function entry/exit code so that it can be
+used directly as an interrupt service routine.
+
+Interrupt handlers have access to the stack frame pushed onto the stack by the 
processor,
+and return using the ``IRET`` instruction. All registers in an interrupt 
handler are callee-saved.
+Exception handlers also have access to the error code pushed onto the stack by 
the processor,
+when applicable.
+
+An interrupt handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void f (struct stack_frame *frame) {
+   ...
+   }
+
+  Where ``struct stack_frame`` is a suitable struct matching the stack frame 
pushed by the
+  processor.
+
+An exception handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void g (struct stack_frame *frame, unsigned long code) {
+   ...
+   }
+
+  On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
+
+Exception handlers should only be used when an error code is pushed by the 
processor.
+Using the incorrect handler type will crash the system.
+
+Interrupt and exception handlers cannot be called by other functions and must 
have return type ``void``.
+
+Interrupt and exception handlers should only call functions with the 
'no_caller_saved_registers'
+attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid 
saving unused
+non-GPR registers.
+}];
+}
+
 def AnyX86NoCallerSavedRegistersDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{



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


[clang] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-16 Thread Jocelyn Castellano via cfe-commits

pandaninjas wrote:

Any idea why the CI is failing? It mentions line 86 not being constexpr because 
of assert, but it doesn't seem like I've done anything which should affect 
that...

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


[clang-tools-extra] [libc++] Prevent calling the projection more than three times (PR #66315)

2023-09-16 Thread Jocelyn Castellano via cfe-commits

pandaninjas wrote:

Any idea why the CI is failing? It mentions line 86 not being constexpr because 
of assert, but it doesn't seem like I've done anything which should affect 
that...

https://github.com/llvm/llvm-project/pull/66315
___
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 modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits


@@ -0,0 +1,25 @@
+.. title:: clang-tidy - modernize-use-std-numbers
+
+modernize-use-std-numbers
+=
+
+This check finds constants and function calls to math functions that can be 
replaced

EugeneZelenko wrote:

Please synchronize first statement with Release Notes.

https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits


@@ -168,6 +168,12 @@ New checks
 
   Replace ``enable_if`` with C++20 requires clauses.
 
+- New :doc:`modernize-use-std-numbers
+  ` check.
+
+  Finds constants and function calls to math functions that can be replaced
+  with c++20's mathematical constants ('numbers' header).

EugeneZelenko wrote:

Please use double back-ticks for `numbers`.

https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits


@@ -0,0 +1,377 @@
+//===--- UseStdNumbersCheck.cpp - clang_tidy -===//

EugeneZelenko wrote:

Please make it same length as similar line at bottom of comment.

https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits


@@ -0,0 +1,25 @@
+.. title:: clang-tidy - modernize-use-std-numbers
+
+modernize-use-std-numbers
+=
+
+This check finds constants and function calls to math functions that can be 
replaced
+with c++20's mathematical constants ('numbers' header) and offers fixit-hints.

EugeneZelenko wrote:

`fix-it`.

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


[clang] [clang][Docs] Document X86 interrupt attribute (PR #65662)

2023-09-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang


Changes

Adds documentation for the X86 `__attribute__((interrupt))` attribute, in a 
similar format to interrupt attributes of
other platforms.

Migrated from https://reviews.llvm.org/D159317
---
Full diff: https://github.com/llvm/llvm-project/pull/65662.diff


2 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+1-1) 
- (modified) clang/include/clang/Basic/AttrDocs.td (+48) 


``diff
diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index c95db7e8049d47a..21a3b5226623cf2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3125,7 +3125,7 @@ def AnyX86Interrupt : InheritableAttr, 
TargetSpecificAttr {
   let Subjects = SubjectList<[HasFunctionProto]>;
   let ParseKind = "Interrupt";
   let HasCustomParsing = 1;
-  let Documentation = [Undocumented];
+  let Documentation = [AnyX86InterruptDocs];
 }
 
 def AnyX86NoCallerSavedRegisters : InheritableAttr,
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f11ea89d14bad0d..c3fe7cea29afbf1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4801,6 +4801,54 @@ Marking virtual functions as ``disable_tail_calls`` is 
legal.
   }];
 }
 
+def AnyX86InterruptDocs : Documentation {
+let Category = DocCatFunction;
+let Heading = "interrupt (X86)";
+let Content = [{
+Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
+targets. This attribute may be attached to a function definition and instructs
+the backend to generate appropriate function entry/exit code so that it can be
+used directly as an interrupt service routine.
+
+Interrupt handlers have access to the stack frame pushed onto the stack by the 
processor,
+and return using the ``IRET`` instruction. All registers in an interrupt 
handler are callee-saved.
+Exception handlers also have access to the error code pushed onto the stack by 
the processor,
+when applicable.
+
+An interrupt handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void f (struct stack_frame *frame) {
+   ...
+   }
+
+  Where ``struct stack_frame`` is a suitable struct matching the stack frame 
pushed by the
+  processor.
+
+An exception handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void g (struct stack_frame *frame, unsigned long code) {
+   ...
+   }
+
+  On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
+
+Exception handlers should only be used when an error code is pushed by the 
processor.
+Using the incorrect handler type will crash the system.
+
+Interrupt and exception handlers cannot be called by other functions and must 
have return type ``void``.
+
+Interrupt and exception handlers should only call functions with the 
'no_caller_saved_registers'
+attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid 
saving unused
+non-GPR registers.
+}];
+}
+
 def AnyX86NoCallerSavedRegistersDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{

``




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


[clang] [clang][Docs] Document X86 interrupt attribute (PR #65662)

2023-09-16 Thread via cfe-commits

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

>From adab00268e5a6ca765dd2b70b2b3a7a332641ab9 Mon Sep 17 00:00:00 2001
From: Antonio Abbatangelo 
Date: Thu, 31 Aug 2023 16:40:06 -0400
Subject: [PATCH] [clang][Docs] Document X86 interrupt attribute

---
 clang/include/clang/Basic/Attr.td |  2 +-
 clang/include/clang/Basic/AttrDocs.td | 48 +++
 2 files changed, 49 insertions(+), 1 deletion(-)

diff --git a/clang/include/clang/Basic/Attr.td 
b/clang/include/clang/Basic/Attr.td
index c95db7e8049d47a..21a3b5226623cf2 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -3125,7 +3125,7 @@ def AnyX86Interrupt : InheritableAttr, 
TargetSpecificAttr {
   let Subjects = SubjectList<[HasFunctionProto]>;
   let ParseKind = "Interrupt";
   let HasCustomParsing = 1;
-  let Documentation = [Undocumented];
+  let Documentation = [AnyX86InterruptDocs];
 }
 
 def AnyX86NoCallerSavedRegisters : InheritableAttr,
diff --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index f11ea89d14bad0d..c3fe7cea29afbf1 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -4801,6 +4801,54 @@ Marking virtual functions as ``disable_tail_calls`` is 
legal.
   }];
 }
 
+def AnyX86InterruptDocs : Documentation {
+let Category = DocCatFunction;
+let Heading = "interrupt (X86)";
+let Content = [{
+Clang supports the GNU style ``__attribute__((interrupt))`` attribute on X86
+targets. This attribute may be attached to a function definition and instructs
+the backend to generate appropriate function entry/exit code so that it can be
+used directly as an interrupt service routine.
+
+Interrupt handlers have access to the stack frame pushed onto the stack by the 
processor,
+and return using the ``IRET`` instruction. All registers in an interrupt 
handler are callee-saved.
+Exception handlers also have access to the error code pushed onto the stack by 
the processor,
+when applicable.
+
+An interrupt handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void f (struct stack_frame *frame) {
+   ...
+   }
+
+  Where ``struct stack_frame`` is a suitable struct matching the stack frame 
pushed by the
+  processor.
+
+An exception handler must take the following arguments:
+
+  .. code-block:: c
+
+   __attribute__ ((interrupt))
+   void g (struct stack_frame *frame, unsigned long code) {
+   ...
+   }
+
+  On 32-bit targets, the ``code`` argument should be of type ``unsigned int``.
+
+Exception handlers should only be used when an error code is pushed by the 
processor.
+Using the incorrect handler type will crash the system.
+
+Interrupt and exception handlers cannot be called by other functions and must 
have return type ``void``.
+
+Interrupt and exception handlers should only call functions with the 
'no_caller_saved_registers'
+attribute, or should be compiled with the '-mgeneral-regs-only' flag to avoid 
saving unused
+non-GPR registers.
+}];
+}
+
 def AnyX86NoCallerSavedRegistersDocs : Documentation {
   let Category = DocCatFunction;
   let Content = [{

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


[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

2023-09-16 Thread Emilia Kond via cfe-commits

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


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


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-16 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 updated 
https://github.com/llvm/llvm-project/pull/66586

>From 47422fc341cc2a830aa7abec6d105018271f13bd Mon Sep 17 00:00:00 2001
From: Balint Cristian 
Date: Sun, 17 Sep 2023 03:00:59 +0300
Subject: [PATCH] [clang] Enable --print-supported-extensions for all targets

Signed-off-by: Balint Cristian 
---
 clang/docs/ReleaseNotes.rst   |  6 ++---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/Driver.cpp   |  9 ---
 .../test/Driver/print-supported-extensions.c  | 10 +++-
 clang/tools/driver/cc1_main.cpp   | 25 +++
 llvm/include/llvm/MC/MCSubtargetInfo.h|  6 +
 6 files changed, 22 insertions(+), 36 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index e9bfefd40bbbf82..40c0077f4bb51ca 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -283,10 +283,10 @@ Bug Fixes to C++ Support
 - Clang now properly handles out of line template specializations when there is
   a non-template inner-class between the function and the class template.
   (`#65810 `_)
-  
-- Clang now properly converts static lambda call operator to function 
+
+- Clang now properly converts static lambda call operator to function
   pointer on win32.
-  (`#62594 `_)  
+  (`#62594 `_)
 
 Bug Fixes to AST Handling
 ^
diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 553c7928c4f949e..431f2f5c4109232 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5277,7 +5277,7 @@ def print_supported_cpus : Flag<["-", "--"], 
"print-supported-cpus">,
   MarshallingInfoFlag>;
 def print_supported_extensions : Flag<["-", "--"], 
"print-supported-extensions">,
   Visibility<[ClangOption, CC1Option, CLOption]>,
-  HelpText<"Print supported -march extensions (RISC-V, AArch64 and ARM only)">,
+  HelpText<"Print supported -march extensions">,
   MarshallingInfoFlag>;
 def : Flag<["-"], "mcpu=help">, Alias;
 def : Flag<["-"], "mtune=help">, Alias;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 84b8fc7685fed42..8b73618fdc87a39 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4283,15 +4283,6 @@ void Driver::BuildActions(Compilation , DerivedArgList 
,
 // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions
 // and quits.
 if (Arg *A = Args.getLastArg(Opt)) {
-  if (Opt == options::OPT_print_supported_extensions &&
-  !C.getDefaultToolChain().getTriple().isRISCV() &&
-  !C.getDefaultToolChain().getTriple().isAArch64() &&
-  !C.getDefaultToolChain().getTriple().isARM()) {
-C.getDriver().Diag(diag::err_opt_not_valid_on_target)
-<< "--print-supported-extensions";
-return;
-  }
-
   // Use the -mcpu=? flag as the dummy input to cc1.
   Actions.clear();
   Action *InputAc = C.MakeAction(*A, types::TY_C);
diff --git a/clang/test/Driver/print-supported-extensions.c 
b/clang/test/Driver/print-supported-extensions.c
index 8daf4d8a34b8a60..d52c4a51281c95f 100644
--- a/clang/test/Driver/print-supported-extensions.c
+++ b/clang/test/Driver/print-supported-extensions.c
@@ -3,16 +3,12 @@
 
 // RUN: %if aarch64-registered-target %{ %clang --target=aarch64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
AARCH64 %}
-// AARCH64: All available -march extensions for AArch64
+// AARCH64: All available -march extensions for aarch64
 
 // RUN: %if riscv-registered-target %{ %clang --target=riscv64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
RISCV %}
-// RISCV: All available -march extensions for RISC-V
+// RISCV: All available -march extensions for riscv64
 
 // RUN: %if arm-registered-target %{ %clang --target=arm-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix ARM 
%}
-// ARM: All available -march extensions for ARM
-
-// RUN: %if x86-registered-target %{ not %clang --target=x86_64-linux-gnu \
-// RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix X86 
%}
-// X86: error: option '--print-supported-extensions' cannot be specified on 
this target
\ No newline at end of file
+// ARM: All available -march extensions for arm
diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index f0d7b5c3889dc1f..25c435054b6927b 100644
--- a/clang/tools/driver/cc1_main.cpp
+++ b/clang/tools/driver/cc1_main.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/LinkAllPasses.h"
+#include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/TargetRegistry.h"
 #include 

[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-16 Thread Balint Cristian via cfe-commits

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


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-16 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 updated 
https://github.com/llvm/llvm-project/pull/66586

>From 87c21561e1c087caeb6105f5824e809da85e67ac Mon Sep 17 00:00:00 2001
From: Balint Cristian 
Date: Sun, 17 Sep 2023 02:36:45 +0300
Subject: [PATCH] [clang] Enable --print-supported-extensions for all targets

Signed-off-by: Balint Cristian 
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/Driver.cpp   |  9 ---
 .../test/Driver/print-supported-extensions.c  | 10 +++-
 clang/tools/driver/cc1_main.cpp   | 25 +++
 llvm/include/llvm/MC/MCSubtargetInfo.h|  6 +
 5 files changed, 19 insertions(+), 33 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 553c7928c4f949e..431f2f5c4109232 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5277,7 +5277,7 @@ def print_supported_cpus : Flag<["-", "--"], 
"print-supported-cpus">,
   MarshallingInfoFlag>;
 def print_supported_extensions : Flag<["-", "--"], 
"print-supported-extensions">,
   Visibility<[ClangOption, CC1Option, CLOption]>,
-  HelpText<"Print supported -march extensions (RISC-V, AArch64 and ARM only)">,
+  HelpText<"Print supported -march extensions">,
   MarshallingInfoFlag>;
 def : Flag<["-"], "mcpu=help">, Alias;
 def : Flag<["-"], "mtune=help">, Alias;
diff --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 84b8fc7685fed42..8b73618fdc87a39 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4283,15 +4283,6 @@ void Driver::BuildActions(Compilation , DerivedArgList 
,
 // RISCVMarchHelp in RISCVISAInfo.cpp that prints out supported extensions
 // and quits.
 if (Arg *A = Args.getLastArg(Opt)) {
-  if (Opt == options::OPT_print_supported_extensions &&
-  !C.getDefaultToolChain().getTriple().isRISCV() &&
-  !C.getDefaultToolChain().getTriple().isAArch64() &&
-  !C.getDefaultToolChain().getTriple().isARM()) {
-C.getDriver().Diag(diag::err_opt_not_valid_on_target)
-<< "--print-supported-extensions";
-return;
-  }
-
   // Use the -mcpu=? flag as the dummy input to cc1.
   Actions.clear();
   Action *InputAc = C.MakeAction(*A, types::TY_C);
diff --git a/clang/test/Driver/print-supported-extensions.c 
b/clang/test/Driver/print-supported-extensions.c
index 8daf4d8a34b8a60..d52c4a51281c95f 100644
--- a/clang/test/Driver/print-supported-extensions.c
+++ b/clang/test/Driver/print-supported-extensions.c
@@ -3,16 +3,12 @@
 
 // RUN: %if aarch64-registered-target %{ %clang --target=aarch64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
AARCH64 %}
-// AARCH64: All available -march extensions for AArch64
+// AARCH64: All available -march extensions for aarch64
 
 // RUN: %if riscv-registered-target %{ %clang --target=riscv64-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix 
RISCV %}
-// RISCV: All available -march extensions for RISC-V
+// RISCV: All available -march extensions for riscv64
 
 // RUN: %if arm-registered-target %{ %clang --target=arm-linux-gnu \
 // RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix ARM 
%}
-// ARM: All available -march extensions for ARM
-
-// RUN: %if x86-registered-target %{ not %clang --target=x86_64-linux-gnu \
-// RUN:   --print-supported-extensions 2>&1 | FileCheck %s --check-prefix X86 
%}
-// X86: error: option '--print-supported-extensions' cannot be specified on 
this target
\ No newline at end of file
+// ARM: All available -march extensions for arm
diff --git a/clang/tools/driver/cc1_main.cpp b/clang/tools/driver/cc1_main.cpp
index f0d7b5c3889dc1f..25c435054b6927b 100644
--- a/clang/tools/driver/cc1_main.cpp
+++ b/clang/tools/driver/cc1_main.cpp
@@ -28,6 +28,7 @@
 #include "llvm/ADT/Statistic.h"
 #include "llvm/Config/llvm-config.h"
 #include "llvm/LinkAllPasses.h"
+#include "llvm/MC/MCSubtargetInfo.h"
 #include "llvm/MC/TargetRegistry.h"
 #include "llvm/Option/Arg.h"
 #include "llvm/Option/ArgList.h"
@@ -38,15 +39,12 @@
 #include "llvm/Support/ManagedStatic.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Process.h"
-#include "llvm/Support/RISCVISAInfo.h"
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/TimeProfiler.h"
 #include "llvm/Support/Timer.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/Target/TargetMachine.h"
-#include "llvm/TargetParser/AArch64TargetParser.h"
-#include "llvm/TargetParser/ARMTargetParser.h"
 #include 
 
 #ifdef CLANG_HAVE_RLIMITS
@@ -197,19 +195,14 @@ static int PrintSupportedExtensions(std::string 
TargetStr) {
   llvm::TargetOptions Options;
   std::unique_ptr TheTargetMachine(
   TheTarget->createTargetMachine(TargetStr, "", "", Options, 
std::nullopt));
-  const llvm::Triple  = TheTargetMachine->getTargetTriple();

[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-16 Thread Balint Cristian via cfe-commits

cbalint13 wrote:

@DavidSpickett ,

This PR list all flags for a specific target.

---

Additionally, beyond this PR:

* We can limit to list flags only for a desired e.g. -mcpu=XYZ, e.g. the user 
can query like:
```./bin/clang -target x86_64-linux-gnu -mcpu=sandybridge 
--print-supported-extensions```

* The cost for this would be simply iterating through 
```MCInfo->checkFeatures()``` for a specific ```-mcpu```.

Let me know if it would be interesting future, I'll be happy doing it in a 
subsecvent PR.

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


[PATCH] D152279: [Driver] Default -msmall-data-limit= to 0

2023-09-16 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D152279#4638173 , @asb wrote:

> In D152279#4612099 , @craig.topper 
> wrote:
>
>> In D152279#4612087 , @MaskRay 
>> wrote:
>>
>>> I am still interested in moving this forward. What should be done here? If 
>>> the decision is to keep the current odd default 8 for 
>>> `toolchains::RISCVToolChain`, I guess I'll have to take the compromise as 
>>> making a step forward is better than nothing.
>>
>> On 1 RV64 CPU I tried in our RTL simulator, changing from 8 to 0 reduced 
>> dhrystone score by 2.7%. Using 16, or 32 gave the same score as 8. Reducing 
>> 8 to 4 improved the score by 0.5%.
>
> Thanks for testing - do you have a view one way or another on this default? 
> I'm somewhat torn personally.

Is this patch blocked by anything?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D152279

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


[clang] [clang] Enable --print-supported-extensions for all targets (PR #66586)

2023-09-16 Thread Balint Cristian via cfe-commits

https://github.com/cbalint13 created 
https://github.com/llvm/llvm-project/pull/66586

This uses MCSubtargetInfo instead to cover all the architectures. This now also 
list descriptions along with the names.

The advantage fetching from MCSubtargetInfo is that we rely on tablegen 
architecture descriptions for all architectures.

---

* Output from `hexagon`:
```
$ ./bin/clang -target hexagon-linux-gnu --print-supported-extensions
clang version 18.0.0 (https://github.com/cbalint13/llvm-project 
8049db0990d1695a40de57f136af20ce5340b4a6)
Target: hexagon-unknown-linux-gnu
Thread model: posix
InstalledDir: /home/cbalint/work/GITHUB/llvm-project/build/./bin
All available -march extensions for hexagon

  audio(Hexagon Audio extension 
instructions)
  cabac(Emit the CABAC instruction)
  compound (Use compound instructions)
  duplex   (Enable generation of duplex 
instruction)
  hvx  (Hexagon HVX instructions)
  hvx-ieee-fp  (Hexagon HVX IEEE floating point 
instructions)
  hvx-length128b   (Hexagon HVX 128B instructions)
  hvx-length64b(Hexagon HVX 64B instructions)
  hvx-qfloat   (Hexagon HVX QFloating point 
instructions)
  hvxv60   (Hexagon HVX instructions)
  hvxv62   (Hexagon HVX instructions)
  hvxv65   (Hexagon HVX instructions)
{...}
```

* Output from `x86_64`:
```
$ ./bin/clang -target x86_64-linux-gnu --print-supported-extensions
clang version 18.0.0 (https://github.com/cbalint13/llvm-project 
8049db0990d1695a40de57f136af20ce5340b4a6)
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /home/cbalint/work/GITHUB/llvm-project/build/./bin
All available -march extensions for x86-64

  16bit-mode   (16-bit mode (i8086))
  32bit-mode   (32-bit mode (80386))
  3dnow(Enable 3DNow! instructions)
  3dnowa   (Enable 3DNow! Athlon instructions)
  64bit(Support 64-bit instructions)
  64bit-mode   (64-bit mode (x86_64))
  adx  (Support ADX instructions)
  aes  (Enable AES instructions)
  allow-light-256-bit  (Enable generation of 256-bit 
load/stores even 
  amx-bf16 (Support AMX-BF16 instructions)
  amx-complex  (Support AMX-COMPLEX instructions)
  amx-fp16 (Support AMX amx-fp16 instructions)
  amx-int8 (Support AMX-INT8 instructions)
  amx-tile (Support AMX-TILE instructions)
  avx  (Enable AVX instructions)
  avx2 (Enable AVX2 instructions)
  avx512bf16   (Support bfloat16 floating point)
  avx512bitalg (Enable AVX-512 Bit Algorithms)
  avx512bw (Enable AVX-512 Byte and Word 
Instructions)
  avx512cd (Enable AVX-512 Conflict Detection 
Instructions)
{...}
```

---

Cc @DavidSpickett ,  @DanielKristofKiss , @MaskRay 

I also reference here #66582 for past comments on extracting information from 
MCSubtargetInfo .


>From 09197ec356dec013d47c4938c942082f0acce3cf Mon Sep 17 00:00:00 2001
From: Balint Cristian 
Date: Sun, 17 Sep 2023 01:59:36 +0300
Subject: [PATCH] [clang] Enable --print-supported-extensions for all targets

Signed-off-by: Balint Cristian 
---
 clang/include/clang/Driver/Options.td |  2 +-
 clang/lib/Driver/Driver.cpp   |  9 ---
 .../test/Driver/print-supported-extensions.c  |  4 ---
 clang/tools/driver/cc1_main.cpp   | 25 +++
 llvm/include/llvm/MC/MCSubtargetInfo.h|  6 +
 5 files changed, 16 insertions(+), 30 deletions(-)

diff --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 553c7928c4f949e..431f2f5c4109232 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -5277,7 +5277,7 @@ def print_supported_cpus : Flag<["-", "--"], 
"print-supported-cpus">,
   MarshallingInfoFlag>;
 def print_supported_extensions : Flag<["-", "--"], 
"print-supported-extensions">,
   Visibility<[ClangOption, CC1Option, CLOption]>,
-  HelpText<"Print supported -march extensions (RISC-V, AArch64 and ARM only)">,
+  HelpText<"Print supported -march extensions">,
   MarshallingInfoFlag>;
 def : Flag<["-"], "mcpu=help">, Alias;
 def : Flag<["-"], "mtune=help">, Alias;

[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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

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


[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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


@@ -370,9 +364,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
+auto ParseDefault = [this, OpeningBrace, InRequiresExpression, IfKind,
  , , , ] {
-  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
+  parseStructuralElement(OpeningBrace, InRequiresExpression, IfKind,

owenca wrote:

Nope!

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


[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/66569

>From bf3160066ae83d43837f18825d00c963d0c29ca8 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 15 Sep 2023 21:59:47 -0700
Subject: [PATCH 1/2] [clang-format][NFC] Clean up signatures of some parser
 functions

Removed TT_CompoundRequirementLBrace and parameters CanContainBracedList and
NextLBracesType.
---
 clang/lib/Format/FormatToken.h   |  1 -
 clang/lib/Format/TokenAnnotator.cpp  |  2 +-
 clang/lib/Format/UnwrappedLineParser.cpp | 58 ++--
 clang/lib/Format/UnwrappedLineParser.h   | 13 ++
 4 files changed, 29 insertions(+), 45 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 1ea7ce6a564d8fa..0605ac9da7219f2 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -41,7 +41,6 @@ namespace format {
   TYPE(CaseLabelColon) 
\
   TYPE(CastRParen) 
\
   TYPE(ClassLBrace)
\
-  TYPE(CompoundRequirementLBrace)  
\
   /* ternary ?: expression */  
\
   TYPE(ConditionalExpr)
\
   /* the condition in an if statement */   
\
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 142168e074bbc27..138f7e8562dcc39 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1698,7 +1698,7 @@ class AnnotatingParser {
 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, 
TT_RequiresClause,
 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
-TT_CompoundRequirementLBrace, TT_BracedListLBrace)) {
+TT_BracedListLBrace)) {
   CurrentToken->setType(TT_Unknown);
 }
 CurrentToken->Role.reset();
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 0ff0656a92d7222..ef96dea4e7e59e4 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -335,22 +335,16 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 }
 
 /// \brief Parses a level, that is ???.
-/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
-/// \param CanContainBracedList If the content can contain (at any level) a
-/// braced list.
-/// \param NextLBracesType The type for left brace found in this level.
+/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level.
 /// \param IfKind The \p if statement kind in the level.
 /// \param IfLeftBrace The left brace of the \p if block in the level.
 /// \returns true if a simple block of if/else/for/while, or false otherwise.
 /// (A simple block has a single statement.)
 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
- bool CanContainBracedList,
- TokenType NextLBracesType,
  IfStmtKind *IfKind,
  FormatToken **IfLeftBrace) {
-  auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
-  ? TT_BracedListLBrace
-  : TT_Unknown;
+  const bool InRequiresExpression =
+  OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
   const bool IsPrecededByCommentOrPPDirective =
   !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
   FormatToken *IfLBrace = nullptr;
@@ -370,9 +364,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
+auto ParseDefault = [this, OpeningBrace, InRequiresExpression, IfKind,
  , , , ] {
-  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
+  parseStructuralElement(OpeningBrace, InRequiresExpression, IfKind,
  , HasDoWhile ? nullptr : ,
  HasLabel ? nullptr : );
   ++StatementCount;
@@ -385,8 +379,8 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   addUnwrappedLine();
   break;
 case tok::l_brace:
-  if (NextLBracesType != TT_Unknown) {
-FormatTok->setFinalizedType(NextLBracesType);
+  if (InRequiresExpression) {
+FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
   } else if (FormatTok->Previous &&
  

[clang] [Documentation] Replace recommonmark by myst-parser (PR #65664)

2023-09-16 Thread Andrei Lebedev via cfe-commits

andreil99 wrote:

@cor3ntin No, I did not update all the sphinx bots, only specific ones, as I 
mentioned above in 
https://github.com/llvm/llvm-project/pull/65664#issuecomment-1714983618
> I can update the publishing bots. For the bots running on 
> https://lab.llvm.org/buildbot/#/workers/92 we would need @gribozavr or 
> somebody with access to gribozavr3 worker.

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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

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


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


[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

2023-09-16 Thread Emilia Kond via cfe-commits


@@ -370,9 +364,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
+auto ParseDefault = [this, OpeningBrace, InRequiresExpression, IfKind,
  , , , ] {
-  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
+  parseStructuralElement(OpeningBrace, InRequiresExpression, IfKind,

rymiel wrote:

If `InRequiresExpression` can be determined from just `OpeningBrace`, does it 
need to be passed down here?

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

2023-09-16 Thread Emilia Kond via cfe-commits

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

2023-09-16 Thread Emilia Kond via cfe-commits

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

2023-09-16 Thread Emilia Kond via cfe-commits

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

2023-09-16 Thread Emilia Kond via cfe-commits

https://github.com/rymiel updated 
https://github.com/llvm/llvm-project/pull/65908

>From 0cfeaee5ec5c431bc15fb037f2a20c944c508c2a Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Sun, 10 Sep 2023 23:01:39 +0300
Subject: [PATCH 1/3] [clang-format] Fix requires misannotation with comma

clang-format uses a heuristic to determine if a requires() is either a
requires clause or requires expression, based on what is in the
parentheses. Part of this heuristic assumed that a requires clause can
never contain a comma, however this is not the case if said comma is in
the template argument of a type.

This patch allows commas to appear in a requires clause if an angle
bracket `<` has been opened.

Fixes https://github.com/llvm/llvm-project/issues/65904
---
 clang/lib/Format/UnwrappedLineParser.cpp  | 10 +++---
 clang/unittests/Format/TokenAnnotatorTest.cpp |  8 
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 0ff0656a92d7222..7af9a0cba221458 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3369,9 +3369,13 @@ bool clang::format::UnwrappedLineParser::parseRequires() 
{
 case tok::kw_volatile:
 case tok::kw_const:
 case tok::comma:
-  FormatTok = Tokens->setPosition(StoredPosition);
-  parseRequiresExpression(RequiresToken);
-  return false;
+  if (OpenAngles == 0) {
+FormatTok = Tokens->setPosition(StoredPosition);
+parseRequiresExpression(RequiresToken);
+return false;
+  } else {
+break;
+  }
 case tok::r_paren:
 case tok::pipepipe:
   FormatTok = Tokens->setPosition(StoredPosition);
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index 434852983712940..f3cdb8a8b2cc1b4 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1016,6 +1016,14 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
   ASSERT_EQ(Tokens.size(), 22u) << Tokens;
   EXPECT_TOKEN(Tokens[4], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[10], tok::ampamp, TT_PointerOrReference);
+
+  Tokens = annotate("void f() & requires(true) {}");
+  EXPECT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
+
+  Tokens = annotate("void f() & requires(C) {}");
+  EXPECT_EQ(Tokens.size(), 17u) << Tokens;
+  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsRequiresExpressions) {

>From 7dc5321cf79d3b59546a45040c9434dff3076844 Mon Sep 17 00:00:00 2001
From: Emilia Kond 
Date: Sun, 10 Sep 2023 23:27:16 +0300
Subject: [PATCH 2/3] Adjust tests

---
 clang/lib/Format/UnwrappedLineParser.cpp  |  3 +--
 clang/unittests/Format/TokenAnnotatorTest.cpp | 10 ++
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 7af9a0cba221458..c88e081936094bd 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -3373,9 +3373,8 @@ bool clang::format::UnwrappedLineParser::parseRequires() {
 FormatTok = Tokens->setPosition(StoredPosition);
 parseRequiresExpression(RequiresToken);
 return false;
-  } else {
-break;
   }
+  break;
 case tok::r_paren:
 case tok::pipepipe:
   FormatTok = Tokens->setPosition(StoredPosition);
diff --git a/clang/unittests/Format/TokenAnnotatorTest.cpp 
b/clang/unittests/Format/TokenAnnotatorTest.cpp
index f3cdb8a8b2cc1b4..b1e14925281546c 100644
--- a/clang/unittests/Format/TokenAnnotatorTest.cpp
+++ b/clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1019,10 +1019,12 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 
   Tokens = annotate("void f() & requires(true) {}");
   EXPECT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
 
   Tokens = annotate("void f() & requires(C) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
 }
 
@@ -1143,6 +1145,14 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresExpressions) {
   EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
   EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
+
+  Tokens = annotate("bool foo = requires(C c) {\n"
+"  { c.foo(); }\n"
+"}");
+  ASSERT_EQ(Tokens.size(), 24u) << Tokens;
+  EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
+  EXPECT_TOKEN(Tokens[4], tok::l_paren, 

[clang] [Clang] Allow mixed scalar type constraints for inline asm (PR #65465)

2023-09-16 Thread Craig Topper via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 %s -emit-llvm -o /dev/null
+
+unsigned test(float f)

topperc wrote:

This test is using -emit-llvm, but the patch is in SelectionDAG. SelectionDAG 
doesn't run with -emit-llvm

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


[clang] [Clang] Allow mixed scalar type constraints for inline asm (PR #65465)

2023-09-16 Thread Craig Topper via cfe-commits


@@ -0,0 +1,8 @@
+// RUN: %clang_cc1 %s -emit-llvm -o /dev/null
+
+unsigned test(float f)

topperc wrote:

What IR does this generate?

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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


@@ -1019,10 +1019,12 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 
   Tokens = annotate("void f() & requires(true) {}");
   EXPECT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
 
   Tokens = annotate("void f() & requires(C) {}");
   EXPECT_EQ(Tokens.size(), 17u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);

owenca wrote:

Ditto.

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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


@@ -1019,10 +1019,12 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresClausesAndConcepts) {
 
   Tokens = annotate("void f() & requires(true) {}");
   EXPECT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
   EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);

owenca wrote:

```suggestion
  EXPECT_TOKEN(Tokens[4], tok::amp, TT_PointerOrReference);
  EXPECT_TOKEN(Tokens[5], tok::kw_requires, TT_RequiresClause);
```

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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


@@ -1135,6 +1145,14 @@ TEST_F(TokenAnnotatorTest, 
UnderstandsRequiresExpressions) {
   EXPECT_TOKEN(Tokens[3], tok::kw_requires, TT_RequiresExpression);
   EXPECT_TOKEN(Tokens[4], tok::l_paren, TT_RequiresExpressionLParen);
   EXPECT_TOKEN(Tokens[14], tok::l_brace, TT_RequiresExpressionLBrace);
+
+  Tokens = annotate("bool foo = requires(C c) {\n"
+"  { c.foo(); }\n"
+"}");

owenca wrote:

```suggestion
"};");
```

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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

https://github.com/owenca commented:

Nits.

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


[clang] [clang-format] Fix requires misannotation with comma (PR #65908)

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

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


[clang] Fix math-errno issue (PR #66381)

2023-09-16 Thread Zahira Ammarguellat via cfe-commits

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


[clang] Fix math-errno issue (PR #66381)

2023-09-16 Thread Zahira Ammarguellat via cfe-commits

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


[clang] Fix math-errno issue (PR #66381)

2023-09-16 Thread Zahira Ammarguellat via cfe-commits

https://github.com/zahiraam updated 
https://github.com/llvm/llvm-project/pull/66381

>From 997e3b69ac5c20a9130b957c86c08b16d23af07c Mon Sep 17 00:00:00 2001
From: Zahira Ammarguellat 
Date: Thu, 14 Sep 2023 06:27:35 -0700
Subject: [PATCH 1/6] Fix math-errno issue

---
 clang/lib/CodeGen/CGBuiltin.cpp| 41 +-
 clang/test/CodeGen/math-builtins.c |  2 ++
 clang/test/CodeGen/math-libcalls.c |  2 ++
 3 files changed, 39 insertions(+), 6 deletions(-)

diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 8b19bf85d47a19f..c69ccdb0eb522bf 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -2313,14 +2313,18 @@ RValue CodeGenFunction::EmitBuiltinExpr(const 
GlobalDecl GD, unsigned BuiltinID,
   FD->hasAttr() ? 0 : BuiltinID;
 
   bool ErrnoOverriden = false;
+  bool ErrnoOverrideValue = false;
   // True if math-errno is overriden via the
   // '#pragma float_control(precise, on)'. This pragma disables fast-math,
   // which implies math-errno.
   if (E->hasStoredFPFeatures()) {
 FPOptionsOverride OP = E->getFPFeatures();
-if (OP.hasMathErrnoOverride())
-  ErrnoOverriden = OP.getMathErrnoOverride();
+if (OP.hasMathErrnoOverride()) {
+  ErrnoOverriden = true;
+  ErrnoOverrideValue = OP.getMathErrnoOverride();
+}
   }
+
   // True if 'atttibute__((optnone)) is used. This attibute overrides
   // fast-math which implies math-errno.
   bool OptNone = CurFuncDecl && CurFuncDecl->hasAttr();
@@ -2329,8 +2333,8 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   // using the '#pragma float_control(precise, off)', and
   // attribute opt-none hasn't been seen.
   bool ErrnoOverridenToFalseWithOpt =
-  !ErrnoOverriden && !OptNone &&
-  CGM.getCodeGenOpts().OptimizationLevel != 0;
+   ErrnoOverriden && !ErrnoOverrideValue && !OptNone &&
+   CGM.getCodeGenOpts().OptimizationLevel != 0;
 
   // There are LLVM math intrinsics/instructions corresponding to math library
   // functions except the LLVM op will never set errno while the math library
@@ -2339,6 +2343,28 @@ RValue CodeGenFunction::EmitBuiltinExpr(const GlobalDecl 
GD, unsigned BuiltinID,
   // LLVM counterparts if the call is marked 'const' (known to never set 
errno).
   // In case FP exceptions are enabled, the experimental versions of the
   // intrinsics model those.
+  bool ConstAlways =
+  getContext().BuiltinInfo.isConst(BuiltinID);
+
+  // There's a special case with the fma builtins where they are always const
+  // if the target environment is GNU or the target is OS is Windows and we're
+  // targeting the MSVCRT.dll environment.
+  switch (BuiltinID) {
+  case Builtin::BI__builtin_fma:
+  case Builtin::BI__builtin_fmaf:
+  case Builtin::BI__builtin_fmal:
+  case Builtin::BIfma:
+  case Builtin::BIfmaf:
+  case Builtin::BIfmal: {
+auto  = CGM.getTriple();
+if (Trip.isGNUEnvironment() || Trip.isOSMSVCRT())
+  ConstAlways = true;
+break;
+}
+  default:
+break;
+  }  
+
   bool ConstWithoutErrnoAndExceptions =
   getContext().BuiltinInfo.isConstWithoutErrnoAndExceptions(BuiltinID);
   bool ConstWithoutExceptions =
@@ -2362,14 +2388,17 @@ RValue CodeGenFunction::EmitBuiltinExpr(const 
GlobalDecl GD, unsigned BuiltinID,
   bool ConstWithoutErrnoOrExceptions =
   ConstWithoutErrnoAndExceptions || ConstWithoutExceptions;
   bool GenerateIntrinsics =
-  FD->hasAttr() && !ErrnoOverriden && !OptNone;
+   (ConstAlways && !OptNone) ||
+   (!getLangOpts().MathErrno && !(ErrnoOverriden && ErrnoOverrideValue) &&
+   !OptNone);
   if (!GenerateIntrinsics) {
 GenerateIntrinsics =
 ConstWithoutErrnoOrExceptions && !ConstWithoutErrnoAndExceptions;
 if (!GenerateIntrinsics)
   GenerateIntrinsics =
   ConstWithoutErrnoOrExceptions &&
-  (!getLangOpts().MathErrno && !ErrnoOverriden && !OptNone);
+ (!getLangOpts().MathErrno &&
+   !(ErrnoOverriden && ErrnoOverrideValue) && !OptNone);
 if (!GenerateIntrinsics)
   GenerateIntrinsics =
   ConstWithoutErrnoOrExceptions && ErrnoOverridenToFalseWithOpt;
diff --git a/clang/test/CodeGen/math-builtins.c 
b/clang/test/CodeGen/math-builtins.c
index 962e311698f5755..554c604219957ca 100644
--- a/clang/test/CodeGen/math-builtins.c
+++ b/clang/test/CodeGen/math-builtins.c
@@ -1,5 +1,7 @@
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm
  %s | FileCheck %s -check-prefix=NO__ERRNO
 // RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
+//  RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-disable-llvm-passes -O2  %s | FileCheck %s -check-prefix=NO__ERRNO
+// RUN: %clang_cc1 -triple x86_64-unknown-unknown -w -S -o - -emit-llvm 
-disable-llvm-passes -O2 -fmath-errno %s | FileCheck %s -check-prefix=HAS_ERRNO
 // 

[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

2023-09-16 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert added inline comments.



Comment at: clang/test/Sema/warn-thread-safety-analysis.c:26
 
+
 // Define the mutex struct.

Oh, I wouldn't mind if you were to drop this spurious added newline. But you 
can do this when committing, no need for a new patch set.


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

https://reviews.llvm.org/D152504

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


[PATCH] D152504: [clang][ThreadSafety] Analyze cleanup functions

2023-09-16 Thread Aaron Puchert via Phabricator via cfe-commits
aaronpuchert accepted this revision.
aaronpuchert added a comment.

Thanks, looks good! I'd like to hear from @aaron.ballman if this warrants a 
release note, but that can be added separately.


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

https://reviews.llvm.org/D152504

___
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 modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 8f5e9e6024b0db8f251625669adbc5d607da83cb Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH 1/3] [clang-tidy] add modernize-use-std-numbers check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../modernize/UseStdNumbersCheck.cpp  | 377 ++
 .../clang-tidy/modernize/UseStdNumbersCheck.h |  37 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   3 +-
 .../checks/modernize/use-std-numbers.rst  |  25 ++
 .../checkers/modernize/use-std-numbers.cpp| 205 ++
 8 files changed, 656 insertions(+), 1 deletion(-)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-numbers.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-numbers.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..d82353d74fbd0d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  UseStdNumbersCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 73751cf2705068d..73584e20166f66a 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MacroToEnumCheck.h"
 #include "MakeSharedCheck.h"
 #include "MakeUniqueCheck.h"
+#include "UseStdNumbersCheck.h"
 #include "PassByValueCheck.h"
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
@@ -65,6 +66,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-macro-to-enum");
 CheckFactories.registerCheck("modernize-make-shared");
 CheckFactories.registerCheck("modernize-make-unique");
+CheckFactories.registerCheck(
+"modernize-use-std-numbers");
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck("modernize-use-std-print");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
new file mode 100644
index 000..c23dc6671013bc3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
@@ -0,0 +1,377 @@
+//===--- UseStdNumbersCheck.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 "UseStdNumbersCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 

[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 8f5e9e6024b0db8f251625669adbc5d607da83cb Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add modernize-use-std-numbers check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../modernize/UseStdNumbersCheck.cpp  | 377 ++
 .../clang-tidy/modernize/UseStdNumbersCheck.h |  37 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   3 +-
 .../checks/modernize/use-std-numbers.rst  |  25 ++
 .../checkers/modernize/use-std-numbers.cpp| 205 ++
 8 files changed, 656 insertions(+), 1 deletion(-)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-numbers.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-numbers.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..d82353d74fbd0d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  UseStdNumbersCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 73751cf2705068d..73584e20166f66a 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MacroToEnumCheck.h"
 #include "MakeSharedCheck.h"
 #include "MakeUniqueCheck.h"
+#include "UseStdNumbersCheck.h"
 #include "PassByValueCheck.h"
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
@@ -65,6 +66,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-macro-to-enum");
 CheckFactories.registerCheck("modernize-make-shared");
 CheckFactories.registerCheck("modernize-make-unique");
+CheckFactories.registerCheck(
+"modernize-use-std-numbers");
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck("modernize-use-std-print");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
new file mode 100644
index 000..c23dc6671013bc3
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
@@ -0,0 +1,377 @@
+//===--- UseStdNumbersCheck.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 "UseStdNumbersCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 

[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 26fb41a2903110b6fc8bd986284d41b1fe6814d5 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add modernize-use-std-numbers check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../modernize/UseStdNumbersCheck.cpp  | 377 ++
 .../clang-tidy/modernize/UseStdNumbersCheck.h |  37 ++
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   3 +-
 .../checks/modernize/use-std-numbers.rst  |  25 ++
 .../checkers/modernize/use-std-numbers.cpp| 205 ++
 8 files changed, 656 insertions(+), 1 deletion(-)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/use-std-numbers.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/use-std-numbers.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..d82353d74fbd0d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  UseStdNumbersCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 73751cf2705068d..73584e20166f66a 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MacroToEnumCheck.h"
 #include "MakeSharedCheck.h"
 #include "MakeUniqueCheck.h"
+#include "UseStdNumbersCheck.h"
 #include "PassByValueCheck.h"
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
@@ -65,6 +66,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-macro-to-enum");
 CheckFactories.registerCheck("modernize-make-shared");
 CheckFactories.registerCheck("modernize-make-unique");
+CheckFactories.registerCheck(
+"modernize-use-std-numbers");
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck("modernize-use-std-print");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
new file mode 100644
index 000..272b17919ba86f9
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/UseStdNumbersCheck.cpp
@@ -0,0 +1,377 @@
+//===--- UseStdNumbersCheck.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 "UseStdNumbersCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 

[clang-tools-extra] [clang-tidy] add modernize-use-std-numbers (PR #66583)

2023-09-16 Thread via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 0f14b63b7336532f45abd40749a2a7cd11cfe7e6 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add modernize-use-std-numbers check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 clang-tools-extra/clang-tidy/modernize/CMakeLists.txt   | 1 +
 .../clang-tidy/modernize/ModernizeTidyModule.cpp| 3 +++
 clang-tools-extra/docs/ReleaseNotes.rst | 6 ++
 clang-tools-extra/docs/clang-tidy/checks/list.rst   | 3 ++-
 4 files changed, 12 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..d82353d74fbd0d4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  UseStdNumbersCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index 73751cf2705068d..73584e20166f66a 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -18,6 +18,7 @@
 #include "MacroToEnumCheck.h"
 #include "MakeSharedCheck.h"
 #include "MakeUniqueCheck.h"
+#include "UseStdNumbersCheck.h"
 #include "PassByValueCheck.h"
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
@@ -65,6 +66,8 @@ class ModernizeModule : public ClangTidyModule {
 CheckFactories.registerCheck("modernize-macro-to-enum");
 CheckFactories.registerCheck("modernize-make-shared");
 CheckFactories.registerCheck("modernize-make-unique");
+CheckFactories.registerCheck(
+"modernize-use-std-numbers");
 CheckFactories.registerCheck("modernize-pass-by-value");
 CheckFactories.registerCheck("modernize-use-std-print");
 CheckFactories.registerCheck(
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d6f51998a01e57..02efc22a7fe164e 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -163,6 +163,12 @@ New checks
   Flags coroutines that suspend while a lock guard is in scope at the
   suspension point.
 
+- New :doc:`modernize-use-std-numbers
+  ` check.
+
+  Finds constants and function calls to math functions that can be replaced
+  with c++20's mathematical constants ('numbers' header).
+
 - New :doc:`modernize-use-constraints
   ` check.
 
diff --git a/clang-tools-extra/docs/clang-tidy/checks/list.rst 
b/clang-tools-extra/docs/clang-tidy/checks/list.rst
index 1baabceea06ef48..ae1d541e40387a1 100644
--- a/clang-tools-extra/docs/clang-tidy/checks/list.rst
+++ b/clang-tools-extra/docs/clang-tidy/checks/list.rst
@@ -82,7 +82,7 @@ Clang-Tidy Checks
:doc:`bugprone-bad-signal-to-kill-thread 
`,
:doc:`bugprone-bool-pointer-implicit-conversion 
`, "Yes"
:doc:`bugprone-branch-clone `,
-   :doc:`bugprone-compare-pointer-to-member-virtual-function 
`, "Yes"
+   :doc:`bugprone-compare-pointer-to-member-virtual-function 
`,
:doc:`bugprone-copy-constructor-init `, 
"Yes"
:doc:`bugprone-dangling-handle `,
:doc:`bugprone-dynamic-static-initializers 
`,
@@ -290,6 +290,7 @@ Clang-Tidy Checks
:doc:`modernize-use-noexcept `, "Yes"
:doc:`modernize-use-nullptr `, "Yes"
:doc:`modernize-use-override `, "Yes"
+   :doc:`modernize-use-std-numbers `, "Yes"
:doc:`modernize-use-std-print `, "Yes"
:doc:`modernize-use-trailing-return-type 
`, "Yes"
:doc:`modernize-use-transparent-functors 
`, "Yes"

___
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 modernize-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

5chmidti wrote:

> I'ts not only about category but also name, check suggests std::numbers, then 
> better name it modernize-use-std-numbers, reason for that is simple. Before 
> C++20 we may want to have a check for example -prefer-math-constants that 
> would change 3.14 hardcoded in code into M_PI. And in same way we could have 
> check -use-std-numeric-limits that would change -2147483648 into 
> std::numeric_limitsstd::sint32_t::min(). Simply we may have many of such 
> checks.

Sorry, I read too fast it seems. But no objections to the name change on my 
end. It is more precise.
I'll force push one more time before any review comments come in. 

I don't plan to implement pre c++20 macros or limits here.
However, I do plan to write a check for numeric limits, as it is quite similar 
to this one.


https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-math-constant check (PR #66583)

2023-09-16 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

Simply better to reduce scope of check name to avoid overlap, unless check 
would support pre-c++20, then it could be fine.

https://github.com/llvm/llvm-project/pull/66583
___
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 modernize-math-constant check (PR #66583)

2023-09-16 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

> Sure thing. I don't have a strong feeling about the category.

I'ts not only about category but also name, check suggests std::numbers, then 
better name it modernize-use-std-numbers, reason for that is simple. Before 
C++20 we may want to have a check for example -prefer-math-constants 
that would change 3.14 hardcoded in code into M_PI. And in same way we could 
have check -use-std-numeric-limits that would change -2147483648 
into std::numeric_limits::min(). Simply we may have many of such 
checks.

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


[PATCH] D150075: Fix PR#62594 : static lambda call operator is not convertible to function pointer on win32

2023-09-16 Thread Faisal Vali via Phabricator via cfe-commits
faisalv closed this revision.
faisalv added a comment.

Sorry about the delay - this patch has landed - 
https://github.com/llvm/llvm-project/commit/5bdd5d064d5171b2d5ff6268528cfffd2f86b8ea
Thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D150075

___
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 modernize-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

https://github.com/5chmidti edited 
https://github.com/llvm/llvm-project/pull/66583
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 248c433be176806766f8c2ae9f19ca61f392220e Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add modernize-math-constant check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/MathConstantCheck.cpp   | 377 ++
 .../clang-tidy/modernize/MathConstantCheck.h  |  37 ++
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/math-constant.rst|  25 ++
 .../checkers/modernize/math-constant.cpp  | 205 ++
 8 files changed, 655 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/MathConstantCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/math-constant.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/math-constant.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..cf48d19767c9bc4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MathConstantCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
new file mode 100644
index 000..92a58a97b98b46a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
@@ -0,0 +1,377 @@
+//===--- MathConstantCheck.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 "MathConstantCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502884197169399;
+constexpr double Euler = 2.718281828459045235360287471352662497757247093;
+constexpr double Phi = 1.618033988749894848204586834365638117720309179;
+constexpr double Egamma = 0.577215664901532860606512090082402431042159335;
+
+constexpr auto DiffThreshold = 0.001;
+
+AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double, Threshold) 
{
+  return std::abs(Node.getValue().convertToDouble() - Value) < Threshold;
+}
+
+// We don't want to match uses of macros, such as
+//
+// auto PiHalved = MY_PI / 2;
+//
+// because a project might use defines for math constants.
+// Instead, the macro definition is matched and the value is exchanged there.
+// Hinting at replacing macro definitions with language constructs is done in
+// another check.
+AST_MATCHER(clang::Expr, isMathMacro) { return Node.getBeginLoc().isMacroID(); 
}
+
+AST_MATCHER_P(clang::QualType, hasUnqualifiedDesugaredType,
+  Matcher, InnerMatcher) {
+  return InnerMatcher.matches(Node->getCanonicalTypeUnqualified(), Finder,
+  Builder);

[clang-tools-extra] [clang-tidy] add misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 32d56e1bfb79ec0be5344ec11bb465777c2fd236 Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add misc-math-constant check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/MathConstantCheck.cpp   | 377 ++
 .../clang-tidy/modernize/MathConstantCheck.h  |  37 ++
 .../modernize/ModernizeTidyModule.cpp |   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../checks/modernize/math-constant.rst|  25 ++
 .../checkers/modernize/math-constant.cpp  | 205 ++
 8 files changed, 655 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/modernize/MathConstantCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/math-constant.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/modernize/math-constant.cpp

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index 717c400c4790330..cf48d19767c9bc4 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -16,6 +16,7 @@ add_clang_library(clangTidyModernizeModule
   MakeSharedCheck.cpp
   MakeSmartPtrCheck.cpp
   MakeUniqueCheck.cpp
+  MathConstantCheck.cpp
   ModernizeTidyModule.cpp
   PassByValueCheck.cpp
   RawStringLiteralCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp 
b/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
new file mode 100644
index 000..92a58a97b98b46a
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/MathConstantCheck.cpp
@@ -0,0 +1,377 @@
+//===--- MathConstantCheck.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 "MathConstantCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502884197169399;
+constexpr double Euler = 2.718281828459045235360287471352662497757247093;
+constexpr double Phi = 1.618033988749894848204586834365638117720309179;
+constexpr double Egamma = 0.577215664901532860606512090082402431042159335;
+
+constexpr auto DiffThreshold = 0.001;
+
+AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double, Threshold) 
{
+  return std::abs(Node.getValue().convertToDouble() - Value) < Threshold;
+}
+
+// We don't want to match uses of macros, such as
+//
+// auto PiHalved = MY_PI / 2;
+//
+// because a project might use defines for math constants.
+// Instead, the macro definition is matched and the value is exchanged there.
+// Hinting at replacing macro definitions with language constructs is done in
+// another check.
+AST_MATCHER(clang::Expr, isMathMacro) { return Node.getBeginLoc().isMacroID(); 
}
+
+AST_MATCHER_P(clang::QualType, hasUnqualifiedDesugaredType,
+  Matcher, InnerMatcher) {
+  return InnerMatcher.matches(Node->getCanonicalTypeUnqualified(), Finder,
+  Builder);
+}
+

[clang] 5bdd5d0 - Fix PR#62594 : static lambda call operator is not convertible to function pointer on win32

2023-09-16 Thread faisal vali via cfe-commits

Author: faisal vali
Date: 2023-09-16T13:29:59-05:00
New Revision: 5bdd5d064d5171b2d5ff6268528cfffd2f86b8ea

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

LOG: Fix PR#62594 : static lambda call operator is not convertible to function 
pointer on win32

See issue https://github.com/llvm/llvm-project/issues/62594

This code does not work on win32:

  auto lstatic = []()  static  { return 0;  };
  int (*f2)(void) = lstatic;

Since a calling convention such as CC_X86ThisCall can rightly interfere with 
the implicit pointer to function conversion if erroneously marked on a static 
function, the fix entails checking the 'static' specifier on the lambda 
declarator prior to assigning it a calling convention of an non-static member 
(which pre-c++23 made sense).

Added: 
clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp

Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaType.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index d558705f16ca3be..e9bfefd40bbbf82 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -283,6 +283,10 @@ Bug Fixes to C++ Support
 - Clang now properly handles out of line template specializations when there is
   a non-template inner-class between the function and the class template.
   (`#65810 `_)
+  
+- Clang now properly converts static lambda call operator to function 
+  pointer on win32.
+  (`#62594 `_)  
 
 Bug Fixes to AST Handling
 ^

diff  --git a/clang/lib/Sema/SemaType.cpp b/clang/lib/Sema/SemaType.cpp
index ffd29446b4f2edd..d13a5564e9ad64c 100644
--- a/clang/lib/Sema/SemaType.cpp
+++ b/clang/lib/Sema/SemaType.cpp
@@ -4095,8 +4095,9 @@ static CallingConv getCCForDeclaratorChunk(
   D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
   // This can only be a call operator for a lambda, which is an instance
-  // method.
-  IsCXXInstanceMethod = true;
+  // method, unless explicitly specified as 'static'.
+  IsCXXInstanceMethod =
+  D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
 } else {
   // We're the innermost decl chunk, so must be a function declarator.
   assert(D.isFunctionDeclarator());

diff  --git a/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp 
b/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp
new file mode 100644
index 000..fab76ffc423a3b2
--- /dev/null
+++ b/clang/test/SemaCXX/cxx23-static-callop-lambda-expression.cpp
@@ -0,0 +1,33 @@
+// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify %s
+
+
+namespace ns1 {
+  auto lstatic = []() static { return 3; }; 
+  int (*f2)(void) = lstatic;   
+
+}
+
+namespace ns1_1 {
+  
+  auto lstatic = []() static consteval  //expected-error{{cannot take address 
of consteval call}} \
+  expected-note {{declared here}} 
+  { return 3; };   
+  
+  // FIXME: the above error should indicate that it was triggered below.
+  int (*f2)(void) = lstatic;   
+
+}
+
+
+namespace ns2 {
+  auto lstatic = []() static { return 3; }; 
+  constexpr int (*f2)(void) = lstatic;  
+  static_assert(lstatic() == f2());
+}
+
+namespace ns3 {
+  void main() {
+static int x = 10;
+auto L = []() static { return x; };
+  }
+}



___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

5chmidti wrote:

> In general scope of the check is fine, but specially as it's limited to C++20 
> and way how its written would be good to rename it into 
> modernize-use-std-numbers.

Sure thing. I don't have a strong feeling about the category.

https://github.com/llvm/llvm-project/pull/66583
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

5chmidti wrote:

- How do I correctly parse the values in a macro? While the test locally works, 
it doesn't in CI. I also don't differentiate between what kind of numeric 
constant the token is, which might be another problem. Any pointers on how to 
do this correctly are greatly appreciated.
- Macros currently don't distinguish between `float`, `double` and `long 
double` like the AST-based check does. The values matched in the PPCallback 
should be able to provide the `..._v<>` versions of replacements as well. The 
question about how to detect the difference is probably related to the point 
above.

https://github.com/llvm/llvm-project/pull/66583
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread Piotr Zegar via cfe-commits

PiotrZSL wrote:

In general scope of the check is fine, but specially as it's limited to C++20 
and way how its written would be good to rename it into 
modernize-use-std-numbers.

https://github.com/llvm/llvm-project/pull/66583
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

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

>From 6e14980c7b7fe22e8b614d641ba72117982b798f Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add misc-math-constant check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/misc/CMakeLists.txt|   1 +
 .../clang-tidy/misc/MathConstantCheck.cpp | 377 ++
 .../clang-tidy/misc/MathConstantCheck.h   |  37 ++
 .../clang-tidy/misc/MiscTidyModule.cpp|   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../clang-tidy/checks/misc/math-constant.rst  |  25 ++
 .../checkers/misc/math-constant.cpp   | 205 ++
 8 files changed, 655 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/misc/MathConstantCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/misc/math-constant.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/misc/math-constant.cpp

diff --git a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
index 2e88e68a5447825..9259de378340f45 100644
--- a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangTidyMiscModule
   ConfusableIdentifierCheck.cpp
   HeaderIncludeCycleCheck.cpp
   IncludeCleanerCheck.cpp
+  MathConstantCheck.cpp
   MiscTidyModule.cpp
   MisleadingBidirectional.cpp
   MisleadingIdentifier.cpp
diff --git a/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
new file mode 100644
index 000..0fce2eeb2d07cd1
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
@@ -0,0 +1,377 @@
+//===--- MathConstantCheck.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 "MathConstantCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502884197169399;
+constexpr double Euler = 2.718281828459045235360287471352662497757247093;
+constexpr double Phi = 1.618033988749894848204586834365638117720309179;
+constexpr double Egamma = 0.577215664901532860606512090082402431042159335;
+
+constexpr auto DiffThreshold = 0.001;
+
+AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double, Threshold) 
{
+  return std::abs(Node.getValue().convertToDouble() - Value) < Threshold;
+}
+
+// We don't want to match uses of macros, such as
+//
+// auto PiHalved = MY_PI / 2;
+//
+// because a project might use defines for math constants.
+// Instead, the macro definition is matched and the value is exchanged there.
+// Hinting at replacing macro definitions with language constructs is done in
+// another check.
+AST_MATCHER(clang::Expr, isMathMacro) { return Node.getBeginLoc().isMacroID(); 
}
+
+AST_MATCHER_P(clang::QualType, hasUnqualifiedDesugaredType,
+  Matcher, InnerMatcher) {
+  return InnerMatcher.matches(Node->getCanonicalTypeUnqualified(), Finder,
+  Builder);
+}
+
+auto matchMathCall(const StringRef 

[clang] [Clang][test] Replace legacy -target with --target=. (PR #66572)

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

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


https://github.com/llvm/llvm-project/pull/66572
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

5chmidti wrote:

For macros I have only implemented matching literals, not function calls or 
formulas. I also don't suggest using modern language constructs for macros, 
there are other checks that do this.

https://github.com/llvm/llvm-project/pull/66583
___
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 misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy


Changes

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.

---

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


8 Files Affected:

- (modified) clang-tools-extra/clang-tidy/misc/CMakeLists.txt (+1) 
- (added) clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp (+377) 
- (added) clang-tools-extra/clang-tidy/misc/MathConstantCheck.h (+37) 
- (modified) clang-tools-extra/clang-tidy/misc/MiscTidyModule.cpp (+3) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/list.rst (+1) 
- (added) clang-tools-extra/docs/clang-tidy/checks/misc/math-constant.rst (+25) 
- (added) clang-tools-extra/test/clang-tidy/checkers/misc/math-constant.cpp 
(+203) 


``diff
diff --git a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
index 2e88e68a5447825..9259de378340f45 100644
--- a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangTidyMiscModule
   ConfusableIdentifierCheck.cpp
   HeaderIncludeCycleCheck.cpp
   IncludeCleanerCheck.cpp
+  MathConstantCheck.cpp
   MiscTidyModule.cpp
   MisleadingBidirectional.cpp
   MisleadingIdentifier.cpp
diff --git a/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
new file mode 100644
index 000..5fb4c999cb4361d
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
@@ -0,0 +1,377 @@
+//===--- MathConstantCheck.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 "MathConstantCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502884197169399;
+constexpr double Euler = 2.718281828459045235360287471352662497757247093;
+constexpr double Phi = 1.618033988749894848204586834365638117720309179;
+constexpr double Egamma = 0.577215664901532860606512090082402431042159335;
+
+constexpr auto DiffThreshold = 0.001;
+
+AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double, Threshold) 
{
+  return std::abs(Node.getValue().convertToDouble() - Value) < Threshold;
+}
+
+// We don't want to match uses of macros, such as
+//
+// auto PiHalved = MY_PI / 2;
+//
+// because a project might use defines for math constants.
+// Instead, the macro definition is matched and the value is exchanged there.
+// Hinting at replacing macro definitions with language constructs is done in
+// another check.
+AST_MATCHER(clang::Expr, isMathMacro) { return Node.getBeginLoc().isMacroID(); 
}
+
+AST_MATCHER_P(clang::QualType, hasUnqualifiedDesugaredType,
+  Matcher, InnerMatcher) {
+  return InnerMatcher.matches(Node->getCanonicalTypeUnqualified(), Finder,
+  Builder);
+}
+
+auto matchMathCall(const StringRef FunctionName,
+   const Matcher ArgumentMatcher) {
+  return callExpr(callee(functionDecl(hasName(FunctionName))),
+  hasArgument(0, ignoringImplicit(ArgumentMatcher)));
+}
+
+auto matchSqrt(const Matcher ArgumentMatcher) {
+  return matchMathCall("sqrt", ArgumentMatcher);
+}
+
+// 'MatchDeclRefExprOrMacro' is used to 

[clang-tools-extra] [clang-tidy] add misc-math-constant check (PR #66583)

2023-09-16 Thread via cfe-commits

https://github.com/5chmidti created 
https://github.com/llvm/llvm-project/pull/66583

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.


>From 8fb9b118d35d7c992c67cffd6ea2b2e82f217ddb Mon Sep 17 00:00:00 2001
From: Julian Schmidt <44101708+5chmi...@users.noreply.github.com>
Date: Sat, 16 Sep 2023 16:24:13 +0200
Subject: [PATCH] [clang-tidy] add misc-math-constant check

This check finds constants and function calls to math functions that can be 
replaced
with c++20's mathematical constants ('numbers' header) and offers fixit-hints.
Does not match the use of variables or macros with that value and instead, 
offers a replacement
at the definition of said variables and macros.
---
 .../clang-tidy/misc/CMakeLists.txt|   1 +
 .../clang-tidy/misc/MathConstantCheck.cpp | 377 ++
 .../clang-tidy/misc/MathConstantCheck.h   |  37 ++
 .../clang-tidy/misc/MiscTidyModule.cpp|   3 +
 clang-tools-extra/docs/ReleaseNotes.rst   |   6 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../clang-tidy/checks/misc/math-constant.rst  |  25 ++
 .../checkers/misc/math-constant.cpp   | 203 ++
 8 files changed, 653 insertions(+)
 create mode 100644 clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
 create mode 100644 clang-tools-extra/clang-tidy/misc/MathConstantCheck.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/misc/math-constant.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/misc/math-constant.cpp

diff --git a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
index 2e88e68a5447825..9259de378340f45 100644
--- a/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/misc/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangTidyMiscModule
   ConfusableIdentifierCheck.cpp
   HeaderIncludeCycleCheck.cpp
   IncludeCleanerCheck.cpp
+  MathConstantCheck.cpp
   MiscTidyModule.cpp
   MisleadingBidirectional.cpp
   MisleadingIdentifier.cpp
diff --git a/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp 
b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
new file mode 100644
index 000..5fb4c999cb4361d
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/misc/MathConstantCheck.cpp
@@ -0,0 +1,377 @@
+//===--- MathConstantCheck.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 "MathConstantCheck.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/Expr.h"
+#include "clang/AST/Stmt.h"
+#include "clang/AST/Type.h"
+#include "clang/ASTMatchers/ASTMatchers.h"
+#include "clang/ASTMatchers/ASTMatchersInternal.h"
+#include "clang/ASTMatchers/ASTMatchersMacros.h"
+#include "clang/Basic/Diagnostic.h"
+#include "clang/Basic/SourceLocation.h"
+#include "clang/Basic/TokenKinds.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
+#include "clang/Lex/Token.h"
+#include "clang/Tooling/Transformer/RewriteRule.h"
+#include "clang/Tooling/Transformer/Stencil.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include 
+#include 
+
+namespace {
+using namespace clang::ast_matchers;
+using clang::ast_matchers::internal::Matcher;
+using clang::transformer::addInclude;
+using clang::transformer::applyFirst;
+using clang::transformer::ASTEdit;
+using clang::transformer::cat;
+using clang::transformer::changeTo;
+using clang::transformer::edit;
+using clang::transformer::EditGenerator;
+using clang::transformer::flattenVector;
+using clang::transformer::RewriteRuleWith;
+using llvm::StringRef;
+
+constexpr double Pi = 3.141592653589793238462643383279502884197169399;
+constexpr double Euler = 2.718281828459045235360287471352662497757247093;
+constexpr double Phi = 1.618033988749894848204586834365638117720309179;
+constexpr double Egamma = 0.577215664901532860606512090082402431042159335;
+
+constexpr auto DiffThreshold = 0.001;
+
+AST_MATCHER_P2(clang::FloatingLiteral, near, double, Value, double, Threshold) 
{
+  return std::abs(Node.getValue().convertToDouble() - Value) < Threshold;
+}
+
+// We don't want to match uses of macros, such as
+//
+// auto PiHalved = MY_PI / 2;
+//
+// because a project might use defines for math constants.
+// Instead, the macro definition is matched and the value is exchanged there.
+// Hinting at replacing macro definitions with language constructs is done in
+// another check.
+AST_MATCHER(clang::Expr, 

[clang] [clang-format] Properly indent lines inside Verilog case structure (PR #65861)

2023-09-16 Thread via cfe-commits

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


[clang] 00e794b - [clang-format] Properly indent lines inside Verilog case structure (#65861)

2023-09-16 Thread via cfe-commits

Author: sstwcw
Date: 2023-09-16T14:30:19Z
New Revision: 00e794b4dd9699403f2df3ac9c8147fc139730b2

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

LOG: [clang-format] Properly indent lines inside Verilog case structure (#65861)

When a statement following a case label had to be broken into multiple
lines, the continuation parts were not indented correctly.

Old:

```Verilog
case (data)
  16'd0:
result = // break here
10'b01;
endcase
```

New:

```Verilog
case (data)
  16'd0:
result = // break here
10'b01;
endcase
```

Verilog case labels and the following statements are on the same
unwrapped line due to the difficulty of identifying them. So there was a
rule in `getNewLineColumn` to add a level of indentation to the part
following the case label. However, in case the line had to be broken
again, the code at the end of the function would see that the line was
already broken with the continuation part indented, so it would not
indent it more. Now `State.FirstIndent` is changed as well for the part
following the case label, so the logic for determining when to add a
continuation indentation works.

Added: 


Modified: 
clang/lib/Format/ContinuationIndenter.cpp
clang/unittests/Format/FormatTestVerilog.cpp

Removed: 




diff  --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index 8ce7e5b8a2a2055..deb3e554fdc124b 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1204,12 +1204,13 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState ) {
 CurrentState.Indent + Style.ContinuationIndentWidth);
   }
 
-  // After a goto label. Usually labels are on separate lines. However
-  // for Verilog the labels may be only recognized by the annotator and
-  // thus are on the same line as the current token.
-  if ((Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous)) ||
-  (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
-   State.Line->First->is(tok::kw_enum))) {
+  // Indentation of the statement following a Verilog case label is taken care
+  // of in moveStateToNextToken.
+  if (Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous))
+return State.FirstIndent;
+
+  if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
+  State.Line->First->is(tok::kw_enum)) {
 return (Style.IndentWidth * State.Line->First->IndentLevel) +
Style.IndentWidth;
   }
@@ -1599,6 +1600,15 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState ,
 
   State.Column += Current.ColumnWidth;
   State.NextToken = State.NextToken->Next;
+  // Verilog case labels are on the same unwrapped lines as the statements that
+  // follow. TokenAnnotator identifies them and sets MustBreakBefore.
+  // Indentation is taken care of here. A case label can only have 1 statement
+  // in Verilog, so we don't have to worry about lines that follow.
+  if (Style.isVerilog() && State.NextToken &&
+  State.NextToken->MustBreakBefore &&
+  Keywords.isVerilogEndOfLabel(Current)) {
+State.FirstIndent += Style.IndentWidth;
+  }
 
   unsigned Penalty =
   handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);

diff  --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index 9b090aa74f714d1..945e06143ccc3f1 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -312,6 +312,53 @@ TEST_F(FormatTestVerilog, Case) {
   verifyFormat("default:\n"
"  x = '{x: x, default: 9};\n",
Style);
+  // When the line following the case label needs to be broken, the 
continuation
+  // should be indented correctly.
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result = //\n"
+   "10'b01;\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0, //\n"
+   "  16'd1:\n"
+   "result = //\n"
+   "10'b01;\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result = (10'b01 + //\n"
+   "  10'b01 + //\n"
+   "  10'b01);\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result =  //\n"
+   "(10'b01 + //\n"
+   " 10'b01 + //\n"
+   " 10'b01);\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+ 

[clang] [clang-format] Properly indent lines inside Verilog case structure (PR #65861)

2023-09-16 Thread via cfe-commits

https://github.com/sstwcw updated 
https://github.com/llvm/llvm-project/pull/65861

>From c1982d451e6ca8e3cf1269677aabe984000f6801 Mon Sep 17 00:00:00 2001
From: sstwcw 
Date: Sat, 9 Sep 2023 20:35:33 +
Subject: [PATCH 1/3] [clang-format] Properly indent lines inside Verilog case
 structure

When a statement following a case label had to be broken into multiple
lines, the continuation parts were not indented correctly.

Old:

```Verilog
case (data)
  16'd0:
result = // break here
10'b01;
endcase
```

New:

```Verilog
case (data)
  16'd0:
result = // break here
10'b01;
endcase
```

Verilog case labels and the following statements are on the same
unwrapped line due to the difficulty of identifying them.  So there was
a rule in `getNewLineColumn` to add a level of indentation to the part
following the case label.  However, in case the line had to be broken
again, the code at the end of the function would see that the line was
already broken with the continuation part indented, so it would not
indent it more.  Now `State.FirstIndent` is changed as well for the part
following the case label, so the logic for determining when to add a
continuation indentation works.
---
 clang/lib/Format/ContinuationIndenter.cpp| 22 ++---
 clang/unittests/Format/FormatTestVerilog.cpp | 47 
 2 files changed, 63 insertions(+), 6 deletions(-)

diff --git a/clang/lib/Format/ContinuationIndenter.cpp 
b/clang/lib/Format/ContinuationIndenter.cpp
index ac62dab1b07cdca..ec21c181772fa81 100644
--- a/clang/lib/Format/ContinuationIndenter.cpp
+++ b/clang/lib/Format/ContinuationIndenter.cpp
@@ -1204,12 +1204,13 @@ unsigned ContinuationIndenter::getNewLineColumn(const 
LineState ) {
 CurrentState.Indent + Style.ContinuationIndentWidth);
   }
 
-  // After a goto label. Usually labels are on separate lines. However
-  // for Verilog the labels may be only recognized by the annotator and
-  // thus are on the same line as the current token.
-  if ((Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous)) ||
-  (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
-   State.Line->First->is(tok::kw_enum))) {
+  // Indentation of the statement following a Verilog case label is taken care
+  // of in moveStateToNextToken.
+  if (Style.isVerilog() && Keywords.isVerilogEndOfLabel(Previous))
+return State.FirstIndent;
+
+  if (Style.BreakBeforeBraces == FormatStyle::BS_Whitesmiths &&
+  State.Line->First->is(tok::kw_enum)) {
 return (Style.IndentWidth * State.Line->First->IndentLevel) +
Style.IndentWidth;
   }
@@ -1599,6 +1600,15 @@ unsigned 
ContinuationIndenter::moveStateToNextToken(LineState ,
 
   State.Column += Current.ColumnWidth;
   State.NextToken = State.NextToken->Next;
+  // Verilog case labels are are on the same unwrapped lines as the statements
+  // that follow.  TokenAnnotator identifies them and sets MustBreakBefore.
+  // Indentation is taken care of here.  A case label can only have 1 statement
+  // in Verilog, so we don't have to worry about lines that follow.
+  if (Style.isVerilog() && State.NextToken &&
+  State.NextToken->MustBreakBefore &&
+  Keywords.isVerilogEndOfLabel(Current)) {
+State.FirstIndent += Style.IndentWidth;
+  }
 
   unsigned Penalty =
   handleEndOfLine(Current, State, DryRun, AllowBreak, Newline);
diff --git a/clang/unittests/Format/FormatTestVerilog.cpp 
b/clang/unittests/Format/FormatTestVerilog.cpp
index 9b090aa74f714d1..7161312126ea6ed 100644
--- a/clang/unittests/Format/FormatTestVerilog.cpp
+++ b/clang/unittests/Format/FormatTestVerilog.cpp
@@ -312,6 +312,53 @@ TEST_F(FormatTestVerilog, Case) {
   verifyFormat("default:\n"
"  x = '{x: x, default: 9};\n",
Style);
+  // When the line following the case label needs to be indented, the
+  // continuation should be indented correctly.
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result = //\n"
+   "10'b01;\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0, //\n"
+   "  16'd1:\n"
+   "result = //\n"
+   "10'b01;\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result = (10'b01 + //\n"
+   "  10'b01 + //\n"
+   "  10'b01);\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result =  //\n"
+   "(10'b01 + //\n"
+   " 10'b01 + //\n"
+   " 10'b01);\n"
+   "endcase");
+  verifyFormat("case (data)\n"
+   "  16'd0:\n"
+   "result =  //\n"
+   "longfunction( //\n"
+   

[clang] [ValueTracking] Simplify uaddo pattern (PR #65910)

2023-09-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms


Changes

This patch simplifies the overflow check of unsigned addition.

`a + b u a` implies `a + b u b`
`a + b =u a` implies `a + b =u b`

Alive2: https://alive2.llvm.org/ce/z/H8oK8n
Fixes #65863.

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


2 Files Affected:

- (modified) llvm/lib/Analysis/ValueTracking.cpp (+23) 
- (modified) llvm/test/Transforms/InstSimplify/and-or-implied-cond.ll (+8-24) 


``diff
diff --git a/llvm/lib/Analysis/ValueTracking.cpp 
b/llvm/lib/Analysis/ValueTracking.cpp
index c4153b824c37e0a..5aaff4ee81be969 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -8291,6 +8291,29 @@ static std::optional isImpliedCondICmps(const 
ICmpInst *LHS,
   if (L0 == R0 && match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)))
 return isImpliedCondCommonOperandWithConstants(LPred, *LC, RPred, *RC);
 
+  // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 


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


[clang-tools-extra] [ValueTracking] Simplify uaddo pattern (PR #65910)

2023-09-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-llvm-transforms


Changes

This patch simplifies the overflow check of unsigned addition.

`a + b u a` implies `a + b u b`
`a + b =u a` implies `a + b =u b`

Alive2: https://alive2.llvm.org/ce/z/H8oK8n
Fixes #65863.

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


2 Files Affected:

- (modified) llvm/lib/Analysis/ValueTracking.cpp (+23) 
- (modified) llvm/test/Transforms/InstSimplify/and-or-implied-cond.ll (+8-24) 


``diff
diff --git a/llvm/lib/Analysis/ValueTracking.cpp 
b/llvm/lib/Analysis/ValueTracking.cpp
index c4153b824c37e0a..5aaff4ee81be969 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -8291,6 +8291,29 @@ static std::optional isImpliedCondICmps(const 
ICmpInst *LHS,
   if (L0 == R0 && match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)))
 return isImpliedCondCommonOperandWithConstants(LPred, *LC, RPred, *RC);
 
+  // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 


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


[clang] [ValueTracking] Simplify uaddo pattern (PR #65910)

2023-09-16 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65910

>From 9bb817aa40dd9bc1bbb18b4cf4bc079145c8ecaa Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Mon, 11 Sep 2023 03:58:02 +0800
Subject: [PATCH] [ValueTracking] Simplify uaddo pattern

---
 llvm/lib/Analysis/ValueTracking.cpp   |  23 
 .../InstSimplify/and-or-implied-cond.ll   | 104 ++
 2 files changed, 127 insertions(+)

diff --git a/llvm/lib/Analysis/ValueTracking.cpp 
b/llvm/lib/Analysis/ValueTracking.cpp
index c4153b824c37e0a..5aaff4ee81be969 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -8291,6 +8291,29 @@ static std::optional isImpliedCondICmps(const 
ICmpInst *LHS,
   if (L0 == R0 && match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)))
 return isImpliedCondCommonOperandWithConstants(LPred, *LC, RPred, *RC);
 
+  // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [ValueTracking] Simplify uaddo pattern (PR #65910)

2023-09-16 Thread Yingwei Zheng via cfe-commits

https://github.com/dtcxzyw updated 
https://github.com/llvm/llvm-project/pull/65910

>From 9bb817aa40dd9bc1bbb18b4cf4bc079145c8ecaa Mon Sep 17 00:00:00 2001
From: Yingwei Zheng 
Date: Mon, 11 Sep 2023 03:58:02 +0800
Subject: [PATCH] [ValueTracking] Simplify uaddo pattern

---
 llvm/lib/Analysis/ValueTracking.cpp   |  23 
 .../InstSimplify/and-or-implied-cond.ll   | 104 ++
 2 files changed, 127 insertions(+)

diff --git a/llvm/lib/Analysis/ValueTracking.cpp 
b/llvm/lib/Analysis/ValueTracking.cpp
index c4153b824c37e0a..5aaff4ee81be969 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -8291,6 +8291,29 @@ static std::optional isImpliedCondICmps(const 
ICmpInst *LHS,
   if (L0 == R0 && match(L1, m_APInt(LC)) && match(R1, m_APInt(RC)))
 return isImpliedCondCommonOperandWithConstants(LPred, *LC, RPred, *RC);
 
+  // L0 = R0 = L1 + R1, L0 >=u L1 implies R0 >=u R1, L0 https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

2023-09-16 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL updated 
https://github.com/llvm/llvm-project/pull/66553

>From d67dbfb1e926e90b2f4a067c86732bd41783791d Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Fri, 15 Sep 2023 21:39:17 +
Subject: [PATCH 1/2] [clang-tidy] Fix handling --driver-mode=

Driver mode passed as an extra argument (command line or config)
were not utilized for removing invalid arguments in
stripPositionalArgs function, and even if passed as config
driver mode were not used for dependency file striping
leading to invalid handling of -MD. Additionally driver mode
were needed even if user already added cl.exe after --.
---
 .../clang-tidy/tool/ClangTidyMain.cpp | 96 ++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../clang-tidy/infrastructure/driver-mode.cpp | 57 +++
 3 files changed, 157 insertions(+), 1 deletion(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/driver-mode.cpp

diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index 0d2593e74f052b9..d922abeb3ba9bca 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -19,6 +19,7 @@
 #include "../ClangTidyForceLinker.h"
 #include "../GlobList.h"
 #include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/PluginLoader.h"
@@ -26,7 +27,11 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
+#include 
+#include 
 #include 
+#include 
+#include 
 
 using namespace clang::tooling;
 using namespace llvm;
@@ -450,7 +455,7 @@ static StringRef closest(StringRef Value, const StringSet<> 
) {
   return Closest;
 }
 
-static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n";
+static constexpr StringRef VerifyConfigWarningEnd = " [-verify-config]\n";
 
 static bool verifyChecks(const StringSet<> , StringRef CheckGlob,
  StringRef Source) {
@@ -550,9 +555,91 @@ static llvm::IntrusiveRefCntPtr 
createBaseFS() {
   return BaseFS;
 }
 
+static llvm::Expected
+recreateOptionsParserIfNeeded(llvm::ArrayRef Args,
+  llvm::Expected 
OptionsParser,
+  const ClangTidyOptions ) {
+
+  auto DoubleDashIt = std::find(Args.begin(), Args.end(), StringRef("--"));
+
+  // Exit if we don't have any compiler arguments
+  if (DoubleDashIt == Args.end() || Args.empty() ||
+  Args.back() == StringRef("--"))
+return OptionsParser;
+
+  auto IsDriverMode = [](StringRef Argument) {
+return Argument.startswith("--driver-mode=");
+  };
+
+  // Exit if --driver-mode= is explicitly passed in compiler arguments
+  if (Args.end() !=
+  std::find_if(std::next(DoubleDashIt), Args.end(), IsDriverMode))
+return OptionsParser;
+
+  std::vector CommandArguments(std::next(DoubleDashIt),
+Args.end());
+
+  // Add clang-tool as program name if not added
+  if (CommandArguments.empty() ||
+  llvm::StringRef(CommandArguments.front()).startswith("-"))
+CommandArguments.insert(CommandArguments.begin(), "clang-tool");
+
+  // Apply --extra-arg and --extra-arg-before to compiler arguments
+  CommandArguments =
+  OptionsParser->getArgumentsAdjuster()(CommandArguments, "");
+
+  // Apply ExtraArgsBefore from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgsBefore)
+CommandArguments = tooling::getInsertArgumentAdjuster(
+*EffectiveOptions.ExtraArgsBefore,
+tooling::ArgumentInsertPosition::BEGIN)(CommandArguments, "");
+
+  // Apply ExtraArgs from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgs)
+CommandArguments = tooling::getInsertArgumentAdjuster(
+*EffectiveOptions.ExtraArgs,
+tooling::ArgumentInsertPosition::END)(CommandArguments, "");
+
+  // Check if now we have --driver-mode=
+  auto DriverModeIt = std::find_if(CommandArguments.begin(),
+   CommandArguments.end(), IsDriverMode);
+  if (DriverModeIt == CommandArguments.end()) {
+// Try to detect and add --driver-mode=
+std::string ExeName = CommandArguments.front();
+tooling::addTargetAndModeForProgramName(CommandArguments, ExeName);
+DriverModeIt = std::find_if(CommandArguments.begin(),
+CommandArguments.end(), IsDriverMode);
+  }
+
+  // Exit if there is no --driver-mode= at this stage
+  if (DriverModeIt == CommandArguments.end())
+return OptionsParser;
+
+  std::vector NewArgs(Args.begin(), Args.end());
+
+  // Find place to insert --driver-mode= into new args, best after program 
name.
+  auto InsertIt =
+  NewArgs.begin() + std::distance(Args.begin(), DoubleDashIt) + 1U;
+  if (!StringRef(*InsertIt).startswith("-"))
+

[clang-tools-extra] [clang-tidy] Improve bugprone-unused-return-value check (PR #66573)

2023-09-16 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tidy


Changes

Improve diagnostic message to be more straight forward, fix handling of 
casting to non-void and add new option AllowCastToVoid to control casting
to void behavior.

Closes #66570
---

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


9 Files Affected:

- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
(+25-11) 
- (modified) clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h 
(+4) 
- (modified) clang-tools-extra/clang-tidy/cert/CERTTidyModule.cpp (+1) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+6) 
- (modified) 
clang-tools-extra/docs/clang-tidy/checks/bugprone/unused-return-value.rst (+4) 
- (modified) clang-tools-extra/docs/clang-tidy/checks/cert/err33-c.rst (+3) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
 (+11-16) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value.cpp 
(+54-49) 
- (modified) clang-tools-extra/test/clang-tidy/checkers/cert/err33-c.c (+6-6) 


``diff
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index bdc601c2445f5e6..6bc9f2dd367dcbd 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -130,26 +130,35 @@ 
UnusedReturnValueCheck::UnusedReturnValueCheck(llvm::StringRef Name,
 "::std::error_condition;"
 "::std::errc;"
 "::std::expected;"
-"::boost::system::error_code"))) {}
+"::boost::system::error_code"))),
+  AllowCastToVoid(Options.get("AllowCastToVoid", false)) {}
 
 void UnusedReturnValueCheck::storeOptions(ClangTidyOptions::OptionMap ) {
   Options.store(Opts, "CheckedFunctions", CheckedFunctions);
   Options.store(Opts, "CheckedReturnTypes",
 utils::options::serializeStringList(CheckedReturnTypes));
+  Options.store(Opts, "AllowCastToVoid", AllowCastToVoid);
 }
 
 void UnusedReturnValueCheck::registerMatchers(MatchFinder *Finder) {
   auto FunVec = utils::options::parseStringList(CheckedFunctions);
 
-  auto MatchedCallExpr = expr(ignoringImplicit(ignoringParenImpCasts(
-  callExpr(callee(functionDecl(
-   // Don't match void overloads of checked functions.
-   unless(returns(voidType())),
-   anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
- returns(hasCanonicalType(hasDeclaration(
- namedDecl(matchers::matchesAnyListedName(
- CheckedReturnTypes)
-  .bind("match";
+  auto MatchedDirectCallExpr =
+  expr(callExpr(callee(functionDecl(
+// Don't match void overloads of checked functions.
+unless(returns(voidType())),
+anyOf(isInstantiatedFrom(hasAnyName(FunVec)),
+  returns(hasCanonicalType(hasDeclaration(
+  namedDecl(matchers::matchesAnyListedName(
+  CheckedReturnTypes)
+   .bind("match"));
+
+  auto CheckCastToVoid =
+  AllowCastToVoid ? castExpr(unless(hasCastKind(CK_ToVoid))) : castExpr();
+  auto MatchedCallExpr = expr(
+  anyOf(MatchedDirectCallExpr,
+explicitCastExpr(unless(cxxFunctionalCastExpr()), CheckCastToVoid,
+ hasSourceExpression(MatchedDirectCallExpr;
 
   auto UnusedInCompoundStmt =
   compoundStmt(forEach(MatchedCallExpr),
@@ -178,8 +187,13 @@ void UnusedReturnValueCheck::registerMatchers(MatchFinder 
*Finder) {
 void UnusedReturnValueCheck::check(const MatchFinder::MatchResult ) {
   if (const auto *Matched = Result.Nodes.getNodeAs("match")) {
 diag(Matched->getBeginLoc(),
- "the value returned by this function should be used")
+ "the value returned by this function should not be disregarded; "
+ "neglecting it may lead to errors")
 << Matched->getSourceRange();
+
+if (!AllowCastToVoid)
+  return;
+
 diag(Matched->getBeginLoc(),
  "cast the expression to void to silence this warning",
  DiagnosticIDs::Note);
diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
index 15881e12ca0c36a..b4356f8379fdc85 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.h
@@ -24,10 +24,14 @@ class UnusedReturnValueCheck : public 

[clang-tools-extra] [clang-tidy] Improve bugprone-unused-return-value check (PR #66573)

2023-09-16 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL created 
https://github.com/llvm/llvm-project/pull/66573

Improve diagnostic message to be more straight forward, fix handling of 
casting to non-void and add new option AllowCastToVoid to control casting
to void behavior.

Closes #66570

>From b1ab97c39754126d66ed40fc6d31ee54ac96b1a7 Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Sat, 16 Sep 2023 08:46:02 +
Subject: [PATCH 1/3] [clang-tidy] Improve bugprone-unused-return-value
 diagnostic

Improve diagnostic message to be more straight forward.
---
 .../bugprone/UnusedReturnValueCheck.cpp   |  3 +-
 clang-tools-extra/docs/ReleaseNotes.rst   |  3 +
 .../bugprone/unused-return-value-custom.cpp   | 32 +++
 .../checkers/bugprone/unused-return-value.cpp | 96 +--
 .../test/clang-tidy/checkers/cert/err33-c.c   | 12 +--
 5 files changed, 75 insertions(+), 71 deletions(-)

diff --git a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp 
b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
index bdc601c2445f5e6..791385fbb18b493 100644
--- a/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
+++ b/clang-tools-extra/clang-tidy/bugprone/UnusedReturnValueCheck.cpp
@@ -178,7 +178,8 @@ void UnusedReturnValueCheck::registerMatchers(MatchFinder 
*Finder) {
 void UnusedReturnValueCheck::check(const MatchFinder::MatchResult ) {
   if (const auto *Matched = Result.Nodes.getNodeAs("match")) {
 diag(Matched->getBeginLoc(),
- "the value returned by this function should be used")
+ "the value returned by this function should not be disregarded; "
+ "neglecting it may lead to errors")
 << Matched->getSourceRange();
 diag(Matched->getBeginLoc(),
  "cast the expression to void to silence this warning",
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d6f51998a01e57..4230d62dfaae407 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -202,6 +202,9 @@ Changes in existing checks
   ` check, so that it does not
   warn on macros starting with underscore and lowercase letter.
 
+- Improved :doc:`bugprone-unused-return-value
+  ` check diagnostic message.
+
 - Improved :doc:`cppcoreguidelines-avoid-non-const-global-variables
   ` check
   to ignore ``static`` variables declared within the scope of
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
index fb5f77031a3276f..a949fb37884b880 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/unused-return-value-custom.cpp
@@ -47,40 +47,40 @@ void fun(int);
 
 void warning() {
   fun();
-  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value returned by this function 
should be used
-  // CHECK-NOTES: [[@LINE-2]]:3: note: cast the expression to void to silence 
this warning
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: cast the expression to void to 
silence this warning
 
   (fun());
-  // CHECK-NOTES: [[@LINE-1]]:4: warning: the value {{.*}} should be used
-  // CHECK-NOTES: [[@LINE-2]]:4: note: cast {{.*}} this warning
+  // CHECK-MESSAGES: [[@LINE-1]]:4: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+  // CHECK-MESSAGES: [[@LINE-2]]:4: note: cast the expression to void to 
silence this warning
 
   ns::Outer::Inner ObjA1;
   ObjA1.memFun();
-  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value {{.*}} should be used
-  // CHECK-NOTES: [[@LINE-2]]:3: note: cast {{.*}} this warning
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: cast the expression to void to 
silence this warning
 
   ns::AliasName::Inner ObjA2;
   ObjA2.memFun();
-  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value {{.*}} should be used
-  // CHECK-NOTES: [[@LINE-2]]:3: note: cast {{.*}} this warning
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: cast the expression to void to 
silence this warning
 
   ns::Derived ObjA3;
   ObjA3.memFun();
-  // CHECK-NOTES: [[@LINE-1]]:3: warning: the value {{.*}} should be used
-  // CHECK-NOTES: [[@LINE-2]]:3: note: cast {{.*}} this warning
+  // CHECK-MESSAGES: [[@LINE-1]]:3: warning: the value returned by this 
function should not be disregarded; neglecting it may lead to errors
+  // CHECK-MESSAGES: [[@LINE-2]]:3: note: cast the expression to void to 
silence this warning
 
   

[clang] [RISCV] Support predefined marcro __riscv_misaligned_{fast,avoid}. (PR #65756)

2023-09-16 Thread Yeting Kuo via cfe-commits

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


[clang] [RISCV] Support predefined marcro __riscv_misaligned_{fast,avoid}. (PR #65756)

2023-09-16 Thread Yeting Kuo via cfe-commits


@@ -1220,3 +1220,15 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \

yetingk wrote:

I created a pr https://github.com/llvm/llvm-project/pull/66572 for this.

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


[clang] [Clang][test] Replace legacy -target with --target=. (PR #66572)

2023-09-16 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk created 
https://github.com/llvm/llvm-project/pull/66572

None

>From 368db97ba8cb62106980abe320a61f48a96da68b Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Sat, 16 Sep 2023 19:34:50 +0800
Subject: [PATCH] [Clang][test] Replace legacy -target with --target=.

---
 .../CodeGen/RISCV/riscv-sdata-module-flag.c   |  30 +-
 clang/test/Preprocessor/riscv-cmodel.c|  20 +-
 .../test/Preprocessor/riscv-target-features.c | 522 +-
 3 files changed, 286 insertions(+), 286 deletions(-)

diff --git a/clang/test/CodeGen/RISCV/riscv-sdata-module-flag.c 
b/clang/test/CodeGen/RISCV/riscv-sdata-module-flag.c
index 27d9af5dbd6fc74..e758b384bc6eb23 100644
--- a/clang/test/CodeGen/RISCV/riscv-sdata-module-flag.c
+++ b/clang/test/CodeGen/RISCV/riscv-sdata-module-flag.c
@@ -1,33 +1,33 @@
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-DEFAULT
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -G4 -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm -G4 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-G4
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=0 -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=0 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-S0
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=2 -G4 -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=2 -G4 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-S2G4
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-threshold=16 -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm 
-msmall-data-threshold=16 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-T16
-// RUN: %clang -target riscv32-unknown-elf %s -S -emit-llvm -fpic -o - \
+// RUN: %clang --target=riscv32-unknown-elf %s -S -emit-llvm -fpic -o - \
 // RUN:   | FileCheck %s -check-prefix=RV32-PIC
 
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-DEFAULT
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -G4 -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm -G4 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-G4
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=0 -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=0 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-S0
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=2 -G4 -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-limit=2 -G4 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-S2G4
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-threshold=16 -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm 
-msmall-data-threshold=16 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-T16
-// RUN: %clang -target riscv64-linux-android %s -S -emit-llvm -o - \
+// RUN: %clang --target=riscv64-linux-android %s -S -emit-llvm -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-ANDROID
-// RUN: %clang -target riscv64-linux-android %s -S -emit-llvm 
-msmall-data-limit=8 -o - \
+// RUN: %clang --target=riscv64-linux-android %s -S -emit-llvm 
-msmall-data-limit=8 -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-ANDROID
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -fpic -o - \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm -fpic -o - \
 // RUN:   | FileCheck %s -check-prefix=RV64-PIC
-// RUN: %clang -target riscv64-unknown-elf %s -S -emit-llvm -mcmodel=large -o 
- \
+// RUN: %clang --target=riscv64-unknown-elf %s -S -emit-llvm -mcmodel=large -o 
- \
 // RUN:   | FileCheck %s -check-prefix=RV64-LARGE
 
 void test(void) {}
diff --git a/clang/test/Preprocessor/riscv-cmodel.c 
b/clang/test/Preprocessor/riscv-cmodel.c
index c0b85eba16bda8b..45b9a93de6f78ac 100644
--- a/clang/test/Preprocessor/riscv-cmodel.c
+++ b/clang/test/Preprocessor/riscv-cmodel.c
@@ -1,29 +1,29 @@
-// RUN: %clang -target riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \
+// RUN: %clang --target=riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-MEDLOW %s
-// RUN: %clang -target riscv64-unknown-linux-gnu -march=rv64i -x c -E -dM %s \
+// RUN: %clang --target=riscv64-unknown-linux-gnu -march=rv64i -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-MEDLOW %s
 
-// RUN: %clang -target riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \
+// RUN: %clang --target=riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \
 // RUN: -mcmodel=small -o - | FileCheck 

[PATCH] D155610: [Clang][Sema] Fix display of characters on static assertion failure

2023-09-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/test/SemaCXX/static-assert-cxx26.cpp:304
+static_assert('\u{9}' == (char)1, ""); // expected-error {{failed}} \
+   // expected-note {{evaluates to ''\t' 
(0x09, 9) == '' (0x01, 1)'}}
+static_assert((char8_t)-128 == (char8_t)-123, ""); // expected-error 
{{failed}} \

tahonermann wrote:
> cor3ntin wrote:
> > tahonermann wrote:
> > > cor3ntin wrote:
> > > > tahonermann wrote:
> > > > > Is the expected note up to date? I don't see code that would generate 
> > > > > the `` output. Am I just missing it? Since U+0001 is a valid, 
> > > > > though non-printable, character, I would expect more `'\u0001'`.
> > > > See elsewhere in the discussion. this formating is pre existing and 
> > > > managed at the DiagnosticEngine level (pushEscapedString). the reason 
> > > > it's not `\u0001` is 1/ to avoid  reusing c++ syntactic elements for 
> > > > something that comes from diagnostics and is not represented as an 
> > > > escaped sequence in source 2/ `\u00011` is unreadable, and 
> > > > `\U1` is also not helpful :)
> > > > 
> > > Thanks for the explanation. I'm not sure that I agree with the rationale 
> > > for (1) though. We're already putting the value in single quotes and 
> > > representing some values with escapes in many of these cases when the 
> > > value isn't produced by an escape sequence (or even a character/string 
> > > literal); why exclude `\u`? I agree with the rationale for (2); we 
> > > could use `'\u{1}'` in that case.
> > FYI afaik the notation in clang predates the existence of \u{} by a few 
> > years, and follow Unicode notation 
> > (https://unicode.org/mail-arch/unicode-ml/y2005-m11/0060.html).
> > Oldest instance seems to be 
> > https://github.com/llvm/llvm-project/commit/77091b167fd959e1ee0c4dad4ec44de43b6c95db
> >  - i followed suite when reworking the generic escaping mechanism all 
> > string fed to diagnostics go through.
> > 
> > I don't care about changing the syntax, but i do hope we are consistent. 
> > Ultimately what we are trying to do is to designate a unicode codepoint and 
> > whether we do it through C++ syntax or not probably does not matter much as 
> > long as it's clear, delimited and consistent!
> I think the substitution of `` by the diagnostic engine itself is 
> perfectly fine and good; particularly when it has no context to suggest a 
> different presentation. In this particular case, where the character is being 
> presented using C++ syntax as a character literal, I would prefer that C++ 
> syntax be used consistently.
> 
> From an implementation standpoint, I'm suggesting that 
> `WriteCharValueForDiagnostic()` be modified such that, if 
> `escapeCStyle()` returns an empty string, that the 
> character be presented in `'\u{}'` form if the character is one that 
> would otherwise be substituted by the diagnostic engine (e.g., if 
> `isPrintable()` is false). Note that this would be restricted to `char` 
> values <= 0x7F; larger values could still be passed through as invalid code 
> units that the diagnostic engine would then render as, e.g., `''`.
We should take a decision before forcing the author to do further change as to 
avoid going in circle.
As a user `\u{}` vs `` makes no difference in terms of the amount 
of information i receive.

I'm really not fan of duplicating code, spreading the logic in multiple places 
and having multiple ways to render a an invalid `char`. But I'm also concerned 
about spending too much time on `char` literals in `static_assert`. It might 
not be a common enough use case to warrant that much scrutiny :)

So I would be happy to go with _any_ direction



Comment at: clang/test/SemaCXX/static-assert.cpp:287
+  static_assert((char16_t)L'ゆ' == L"C̵̭̯̠̎͌ͅť̺"[1], ""); // expected-error 
{{failed}} \
+  // expected-note {{evaluates 
to ''ゆ' (0x3086) == '̵' (0x335)'}}
+  static_assert(L"\/"[1] == u'\xFFFD', ""); // expected-error {{failed}} \

hubert.reinterpretcast wrote:
> tahonermann wrote:
> > cor3ntin wrote:
> > > hubert.reinterpretcast wrote:
> > > > hubert.reinterpretcast wrote:
> > > > > cor3ntin wrote:
> > > > > > hubert.reinterpretcast wrote:
> > > > > > > The C++23 escaped string formatting facility would not generate a 
> > > > > > > trailing combining character like this. I recommend following 
> > > > > > > suit.
> > > > > > > 
> > > > > > > Info on U+0335: 
> > > > > > > https://util.unicode.org/UnicodeJsps/character.jsp?a=0335
> > > > > > > 
> > > > > > This is way outside the scope of the patch. The diagnostic output 
> > > > > > facility has no understanding of combining characters or graphemes 
> > > > > > and do not attempt to match std::print. It probably would be an 
> > > > > > improvement but this patch is not trying to modify how all 
> > > > > > diagnostics are printed. (all of that logic 

[PATCH] D158595: [clang][Interp] Allow zero-init of primitives with an empty init list

2023-09-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin accepted this revision.
cor3ntin added a comment.
This revision is now accepted and ready to land.

LGTM


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D158595

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


[PATCH] D159351: [Sema] Change order of displayed overloads in diagnostics

2023-09-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added subscribers: hubert.reinterpretcast, rsmith, cor3ntin.
cor3ntin added a comment.

@hubert.reinterpretcast @rsmith Opinions on that?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159351

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


[PATCH] D137043: [clang] add implicit include for Linux/gnu compatibility

2023-09-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

We should take a decision on this before the move off Phab. Generally the 
changes look sensible to me so I'm not sure there are blockers left


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137043

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


[PATCH] D140996: [c++20] P1907R1: Support for generalized non-type template arguments of scalar type.

2023-09-16 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

It would be nice to figure out a plan for this PR in the next few weeks, before 
we get kicked out of Phab!


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

https://reviews.llvm.org/D140996

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


[clang] [Clang] Static member initializers are not immediate escalating context. (PR #66021)

2023-09-16 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/66021

>From a3390c4ac8bba43e73ea41f4af85b37df97b1098 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 11 Sep 2023 23:40:38 +0200
Subject: [PATCH 1/3] [Clang] Static member initializers are not immediate
 escalating context.

Per CWG2760, default members initializers should be consider
part the body of consstructors, which mean they are evaluated
in an immediate escalating context.

However, this does not apply to static members.

This patch produces some extraneous diagnostics, unfortunately
we do not have a good way to report an error back to the
initializer and this is a preexisting issue

Fixes #65985
---
 clang/docs/ReleaseNotes.rst   |  4 
 clang/lib/Parse/ParseDeclCXX.cpp  | 12 --
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 23 +++
 3 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..8c8ec0e11e3dd7d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,10 @@ Bug Fixes to C++ Support
   a non-template inner-class between the function and the class template.
   (`#65810 `_)
 
+- Fix a crash when calling a non-constant immediate function
+  in the initializer of a static data member.
+  (`#65985 _`).
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 730b6e55246d6b7..b4a72d599da6655 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3230,13 +3230,21 @@ ExprResult Parser::ParseCXXMemberInitializer(Decl *D, 
bool IsFunction,
   assert(Tok.isOneOf(tok::equal, tok::l_brace) &&
  "Data member initializer not starting with '=' or '{'");
 
+  bool IsFieldInitialization = isa_and_present(D);
+
   EnterExpressionEvaluationContext Context(
   Actions,
-  isa_and_present(D)
+  IsFieldInitialization
   ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
   : Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
   D);
-  Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext = true;
+
+  // CWG2760
+  // Default member initializers used to initialize a base or member subobject
+  // [...] are considered to be part of the function body
+  Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
+  IsFieldInitialization;
+
   if (TryConsumeToken(tok::equal, EqualLoc)) {
 if (Tok.is(tok::kw_delete)) {
   // In principle, an initializer of '= delete p;' is legal, but it will
diff --git a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
index c5eb7f139327505..f967ce6554d777c 100644
--- a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -330,3 +330,26 @@ struct S {
 S s(0); // expected-note {{in the default initializer of 'j'}}
 
 }
+
+namespace GH65985 {
+
+int consteval operator""_foo(unsigned long long V) {
+return 0;
+}
+int consteval operator""_bar(unsigned long long V); // expected-note 3{{here}}
+
+struct C {
+static const int a = 1_foo;
+static constexpr int b = 1_foo;
+static const int c = 1_bar; // expected-error {{call to consteval function 
'GH65985::operator""_bar' is not a constant expression}} \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}} \
+// expected-error {{in-class initializer for 
static data member is not a constant expression}}
+
+// FIXME: remove duplicate diagnostics
+static constexpr int d = 1_bar; // expected-error {{call to consteval 
function 'GH65985::operator""_bar' is not a constant expression}} \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}} \
+// expected-error {{constexpr variable 'd' 
must be initialized by a constant expression}}  \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}}
+};
+
+}

>From 12e04c8bd51d1f4e0d77969642f115b554b3a589 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 13 Sep 2023 10:10:28 +0200
Subject: [PATCH 2/3] Add more tests

---
 clang/test/SemaCXX/cxx2a-consteval.cpp| 35 +++
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 23 
 2 files changed, 35 insertions(+), 23 deletions(-)

diff --git a/clang/test/SemaCXX/cxx2a-consteval.cpp 
b/clang/test/SemaCXX/cxx2a-consteval.cpp
index 

[clang] [Clang] Static member initializers are not immediate escalating context. (PR #66021)

2023-09-16 Thread via cfe-commits

https://github.com/cor3ntin updated 
https://github.com/llvm/llvm-project/pull/66021

>From a3390c4ac8bba43e73ea41f4af85b37df97b1098 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Mon, 11 Sep 2023 23:40:38 +0200
Subject: [PATCH 1/3] [Clang] Static member initializers are not immediate
 escalating context.

Per CWG2760, default members initializers should be consider
part the body of consstructors, which mean they are evaluated
in an immediate escalating context.

However, this does not apply to static members.

This patch produces some extraneous diagnostics, unfortunately
we do not have a good way to report an error back to the
initializer and this is a preexisting issue

Fixes #65985
---
 clang/docs/ReleaseNotes.rst   |  4 
 clang/lib/Parse/ParseDeclCXX.cpp  | 12 --
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 23 +++
 3 files changed, 37 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..8c8ec0e11e3dd7d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -281,6 +281,10 @@ Bug Fixes to C++ Support
   a non-template inner-class between the function and the class template.
   (`#65810 `_)
 
+- Fix a crash when calling a non-constant immediate function
+  in the initializer of a static data member.
+  (`#65985 _`).
+
 Bug Fixes to AST Handling
 ^
 - Fixed an import failure of recursive friend class template.
diff --git a/clang/lib/Parse/ParseDeclCXX.cpp b/clang/lib/Parse/ParseDeclCXX.cpp
index 730b6e55246d6b7..b4a72d599da6655 100644
--- a/clang/lib/Parse/ParseDeclCXX.cpp
+++ b/clang/lib/Parse/ParseDeclCXX.cpp
@@ -3230,13 +3230,21 @@ ExprResult Parser::ParseCXXMemberInitializer(Decl *D, 
bool IsFunction,
   assert(Tok.isOneOf(tok::equal, tok::l_brace) &&
  "Data member initializer not starting with '=' or '{'");
 
+  bool IsFieldInitialization = isa_and_present(D);
+
   EnterExpressionEvaluationContext Context(
   Actions,
-  isa_and_present(D)
+  IsFieldInitialization
   ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
   : Sema::ExpressionEvaluationContext::PotentiallyEvaluated,
   D);
-  Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext = true;
+
+  // CWG2760
+  // Default member initializers used to initialize a base or member subobject
+  // [...] are considered to be part of the function body
+  Actions.ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
+  IsFieldInitialization;
+
   if (TryConsumeToken(tok::equal, EqualLoc)) {
 if (Tok.is(tok::kw_delete)) {
   // In principle, an initializer of '= delete p;' is legal, but it will
diff --git a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp 
b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
index c5eb7f139327505..f967ce6554d777c 100644
--- a/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ b/clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -330,3 +330,26 @@ struct S {
 S s(0); // expected-note {{in the default initializer of 'j'}}
 
 }
+
+namespace GH65985 {
+
+int consteval operator""_foo(unsigned long long V) {
+return 0;
+}
+int consteval operator""_bar(unsigned long long V); // expected-note 3{{here}}
+
+struct C {
+static const int a = 1_foo;
+static constexpr int b = 1_foo;
+static const int c = 1_bar; // expected-error {{call to consteval function 
'GH65985::operator""_bar' is not a constant expression}} \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}} \
+// expected-error {{in-class initializer for 
static data member is not a constant expression}}
+
+// FIXME: remove duplicate diagnostics
+static constexpr int d = 1_bar; // expected-error {{call to consteval 
function 'GH65985::operator""_bar' is not a constant expression}} \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}} \
+// expected-error {{constexpr variable 'd' 
must be initialized by a constant expression}}  \
+// expected-note {{undefined function 
'operator""_bar' cannot be used in a constant expression}}
+};
+
+}

>From 12e04c8bd51d1f4e0d77969642f115b554b3a589 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 13 Sep 2023 10:10:28 +0200
Subject: [PATCH 2/3] Add more tests

---
 clang/test/SemaCXX/cxx2a-consteval.cpp| 35 +++
 .../SemaCXX/cxx2b-consteval-propagate.cpp | 23 
 2 files changed, 35 insertions(+), 23 deletions(-)

diff --git a/clang/test/SemaCXX/cxx2a-consteval.cpp 
b/clang/test/SemaCXX/cxx2a-consteval.cpp
index 

[PATCH] D155688: [PATCH] [llvm] [InstCombine] Reassociate loop invariant GEP index calculations.

2023-09-16 Thread Dmitriy Smirnov via Phabricator via cfe-commits
d-smirnov updated this revision to Diff 556894.
d-smirnov added a comment.

unit test fixed


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155688

Files:
  clang/test/CodeGen/SystemZ/systemz-inline-asm-03.c
  clang/test/CodeGenCXX/microsoft-abi-dynamic-cast.cpp
  llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
  llvm/test/Transforms/InstCombine/align-addr.ll
  llvm/test/Transforms/InstCombine/gep-combine-loop-invariant.ll
  llvm/test/Transforms/InstCombine/lshr-phi.ll
  llvm/test/Transforms/InstCombine/mem-par-metadata-memcpy.ll
  llvm/test/Transforms/InstCombine/memrchr-4.ll
  llvm/test/Transforms/InstCombine/shift.ll
  llvm/test/Transforms/LoopUnroll/runtime-unroll-remainder.ll
  llvm/test/Transforms/LoopVectorize/AArch64/sve-interleaved-accesses.ll
  llvm/test/Transforms/LoopVectorize/AArch64/sve-vector-reverse.ll
  llvm/test/Transforms/LoopVectorize/AArch64/sve-widen-phi.ll
  llvm/test/Transforms/LoopVectorize/AArch64/vector-reverse-mask4.ll
  llvm/test/Transforms/LoopVectorize/if-conversion-nest.ll
  llvm/test/Transforms/LoopVectorize/induction.ll
  llvm/test/Transforms/LoopVectorize/interleaved-accesses.ll
  llvm/test/Transforms/LoopVectorize/invariant-store-vectorization.ll
  llvm/test/Transforms/LoopVectorize/runtime-check.ll
  llvm/test/Transforms/LowerMatrixIntrinsics/multiply-fused-loops.ll

Index: llvm/test/Transforms/LowerMatrixIntrinsics/multiply-fused-loops.ll
===
--- llvm/test/Transforms/LowerMatrixIntrinsics/multiply-fused-loops.ll
+++ llvm/test/Transforms/LowerMatrixIntrinsics/multiply-fused-loops.ll
@@ -27,14 +27,14 @@
 ; CHECK-NEXT:br label [[INNER_BODY:%.*]]
 ; CHECK:   inner.body:
 ; CHECK-NEXT:[[TMP0:%.*]] = shl i64 [[INNER_IV]], 2
-; CHECK-NEXT:[[TMP1:%.*]] = add i64 [[TMP0]], [[ROWS_IV]]
-; CHECK-NEXT:[[TMP2:%.*]] = getelementptr double, ptr [[A:%.*]], i64 [[TMP1]]
+; CHECK-NEXT:[[TMP1:%.*]] = getelementptr double, ptr [[A:%.*]], i64 [[TMP0]]
+; CHECK-NEXT:[[TMP2:%.*]] = getelementptr double, ptr [[TMP1]], i64 [[ROWS_IV]]
 ; CHECK-NEXT:[[COL_LOAD:%.*]] = load <2 x double>, ptr [[TMP2]], align 8
 ; CHECK-NEXT:[[VEC_GEP:%.*]] = getelementptr double, ptr [[TMP2]], i64 4
 ; CHECK-NEXT:[[COL_LOAD1:%.*]] = load <2 x double>, ptr [[VEC_GEP]], align 8
 ; CHECK-NEXT:[[TMP3:%.*]] = shl i64 [[COLS_IV]], 2
-; CHECK-NEXT:[[TMP4:%.*]] = add i64 [[TMP3]], [[INNER_IV]]
-; CHECK-NEXT:[[TMP5:%.*]] = getelementptr double, ptr [[B:%.*]], i64 [[TMP4]]
+; CHECK-NEXT:[[TMP4:%.*]] = getelementptr double, ptr [[B:%.*]], i64 [[TMP3]]
+; CHECK-NEXT:[[TMP5:%.*]] = getelementptr double, ptr [[TMP4]], i64 [[INNER_IV]]
 ; CHECK-NEXT:[[COL_LOAD2:%.*]] = load <2 x double>, ptr [[TMP5]], align 8
 ; CHECK-NEXT:[[VEC_GEP3:%.*]] = getelementptr double, ptr [[TMP5]], i64 4
 ; CHECK-NEXT:[[COL_LOAD4:%.*]] = load <2 x double>, ptr [[VEC_GEP3]], align 8
@@ -55,8 +55,8 @@
 ; CHECK-NEXT:[[ROWS_STEP]] = add i64 [[ROWS_IV]], 2
 ; CHECK-NEXT:[[ROWS_COND_NOT:%.*]] = icmp eq i64 [[ROWS_STEP]], 4
 ; CHECK-NEXT:[[TMP10:%.*]] = shl i64 [[COLS_IV]], 2
-; CHECK-NEXT:[[TMP11:%.*]] = add i64 [[TMP10]], [[ROWS_IV]]
-; CHECK-NEXT:[[TMP12:%.*]] = getelementptr double, ptr [[C:%.*]], i64 [[TMP11]]
+; CHECK-NEXT:[[TMP11:%.*]] = getelementptr double, ptr [[C:%.*]], i64 [[TMP10]]
+; CHECK-NEXT:[[TMP12:%.*]] = getelementptr double, ptr [[TMP11]], i64 [[ROWS_IV]]
 ; CHECK-NEXT:store <2 x double> [[TMP7]], ptr [[TMP12]], align 8
 ; CHECK-NEXT:[[VEC_GEP16:%.*]] = getelementptr double, ptr [[TMP12]], i64 4
 ; CHECK-NEXT:store <2 x double> [[TMP9]], ptr [[VEC_GEP16]], align 8
@@ -103,14 +103,14 @@
 ; CHECK-NEXT:br label [[INNER_BODY:%.*]]
 ; CHECK:   inner.body:
 ; CHECK-NEXT:[[TMP0:%.*]] = shl i64 [[INNER_IV]], 1
-; CHECK-NEXT:[[TMP1:%.*]] = add i64 [[TMP0]], [[ROWS_IV]]
-; CHECK-NEXT:[[TMP2:%.*]] = getelementptr i64, ptr [[A:%.*]], i64 [[TMP1]]
+; CHECK-NEXT:[[TMP1:%.*]] = getelementptr i64, ptr [[A:%.*]], i64 [[TMP0]]
+; CHECK-NEXT:[[TMP2:%.*]] = getelementptr i64, ptr [[TMP1]], i64 [[ROWS_IV]]
 ; CHECK-NEXT:[[COL_LOAD:%.*]] = load <2 x i64>, ptr [[TMP2]], align 8
 ; CHECK-NEXT:[[VEC_GEP:%.*]] = getelementptr i64, ptr [[TMP2]], i64 2
 ; CHECK-NEXT:[[COL_LOAD1:%.*]] = load <2 x i64>, ptr [[VEC_GEP]], align 8
 ; CHECK-NEXT:[[TMP3:%.*]] = shl i64 [[COLS_IV]], 2
-; CHECK-NEXT:[[TMP4:%.*]] = add i64 [[TMP3]], [[INNER_IV]]
-; CHECK-NEXT:[[TMP5:%.*]] = getelementptr i64, ptr [[B:%.*]], i64 [[TMP4]]
+; CHECK-NEXT:[[TMP4:%.*]] = getelementptr i64, ptr [[B:%.*]], i64 [[TMP3]]
+; CHECK-NEXT:[[TMP5:%.*]] = getelementptr i64, ptr [[TMP4]], i64 [[INNER_IV]]
 ; CHECK-NEXT:[[COL_LOAD2:%.*]] = load <2 x i64>, ptr [[TMP5]], align 8
 ; CHECK-NEXT:[[VEC_GEP3:%.*]] = getelementptr i64, ptr [[TMP5]], i64 4
 ; CHECK-NEXT:

[clang] [Documentation] Replace recommonmark by myst-parser (PR #65664)

2023-09-16 Thread via cfe-commits

cor3ntin wrote:

@andreil99 did you update all the sphinx bots or just specific ones?

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


[PATCH] D149867: [Clang][M68k] Add Clang support for the new M68k_RTD CC

2023-09-16 Thread John Paul Adrian Glaubitz via Phabricator via cfe-commits
glaubitz added a comment.

Any news on this? I guess it would be nice to get the remaining m68k patches 
merged before the Phrabricator shutdown.


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

https://reviews.llvm.org/D149867

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


[clang] [analyzer] TaintPropagation checker strlen() should not propagate (PR #66086)

2023-09-16 Thread Daniel Krupp via cfe-commits

https://github.com/dkrupp updated 
https://github.com/llvm/llvm-project/pull/66086

>From f8997b16c74543eb57b272c4dd4abca1a10d9ac7 Mon Sep 17 00:00:00 2001
From: Daniel Krupp 
Date: Fri, 8 Sep 2023 16:57:49 +0200
Subject: [PATCH] [analyzer] TaintPropagation checker strlen() should not
 propagate

strlen(..) call should not propagate taintedness,
because it brings in many false positive findings.
It is a common pattern to copy user provided input
to another buffer. In these cases we always
get warnings about tainted data used as the malloc parameter:

buf = malloc(strlen(tainted_txt) + 1); // false warning

This pattern can lead to a denial of service attack only, when
the attacker can directly specify the size of the allocated area
as an arbitrary large number (e.g. the value is converted
from a user provided string).

Later, we could reintroduce strlen() as a taint propagating function
with the consideration not to emit warnings when the tainted value
cannot be "arbitrarily large" (such as the size of an already allocated
memory block).
---
 clang/docs/analyzer/checkers.rst|  4 ++--
 .../StaticAnalyzer/Checkers/GenericTaintChecker.cpp |  3 ---
 clang/test/Analysis/taint-diagnostic-visitor.c  | 13 +++--
 clang/test/Analysis/taint-generic.c | 10 +-
 4 files changed, 14 insertions(+), 16 deletions(-)

diff --git a/clang/docs/analyzer/checkers.rst b/clang/docs/analyzer/checkers.rst
index 54ea49e7426cc86..dbd6d7787823530 100644
--- a/clang/docs/analyzer/checkers.rst
+++ b/clang/docs/analyzer/checkers.rst
@@ -2599,8 +2599,8 @@ Default propagations rules:
  ``memcpy``, ``memmem``, ``memmove``, ``mbtowc``, ``pread``, ``qsort``,
  ``qsort_r``, ``rawmemchr``, ``read``, ``recv``, ``recvfrom``, ``rindex``,
  ``strcasestr``, ``strchr``, ``strchrnul``, ``strcasecmp``, ``strcmp``,
- ``strcspn``, ``strlen``, ``strncasecmp``, ``strncmp``, ``strndup``,
- ``strndupa``, ``strnlen``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
+ ``strcspn``, ``strncasecmp``, ``strncmp``, ``strndup``,
+ ``strndupa``, ``strpbrk``, ``strrchr``, ``strsep``, ``strspn``,
  ``strstr``, ``strtol``, ``strtoll``, ``strtoul``, ``strtoull``, ``tolower``,
  ``toupper``, ``ttyname``, ``ttyname_r``, ``wctomb``, ``wcwidth``
 
diff --git a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
index 5da0f34b3d0464f..95a759c251ca490 100644
--- a/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/GenericTaintChecker.cpp
@@ -695,9 +695,6 @@ void GenericTaintChecker::initTaintRules(CheckerContext ) 
const {
   {{{"strpbrk"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{{"strndup"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{{"strndupa"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
-  {{{"strlen"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
-  {{{"wcslen"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
-  {{{"strnlen"}}, TR::Prop({{0}}, {{ReturnValueIndex}})},
   {{{"strtol"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
   {{{"strtoll"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
   {{{"strtoul"}}, TR::Prop({{0}}, {{1, ReturnValueIndex}})},
diff --git a/clang/test/Analysis/taint-diagnostic-visitor.c 
b/clang/test/Analysis/taint-diagnostic-visitor.c
index f1b9ceebdd9a6b8..8a7510177f3e444 100644
--- a/clang/test/Analysis/taint-diagnostic-visitor.c
+++ b/clang/test/Analysis/taint-diagnostic-visitor.c
@@ -10,6 +10,7 @@ int scanf(const char *restrict format, ...);
 int system(const char *command);
 char* getenv( const char* env_var );
 size_t strlen( const char* str );
+int atoi( const char* str );
 void *malloc(size_t size );
 void free( void *ptr );
 char *fgets(char *str, int n, FILE *stream);
@@ -54,11 +55,11 @@ void taintDiagnosticVLA(void) {
 // propagating through variables and expressions
 char *taintDiagnosticPropagation(){
   char *pathbuf;
-  char *pathlist=getenv("PATH"); // expected-note {{Taint originated here}}
+  char *size=getenv("SIZE"); // expected-note {{Taint originated here}}
  // expected-note@-1 {{Taint propagated to the 
return value}}
-  if (pathlist){ // expected-note {{Assuming 'pathlist' is non-null}}
+  if (size){ // expected-note {{Assuming 'size' is non-null}}
   // expected-note@-1 {{Taking true branch}}
-pathbuf=(char*) malloc(strlen(pathlist)+1); // expected-warning{{Untrusted 
data is used to specify the buffer size}}
+pathbuf=(char*) malloc(atoi(size)); // expected-warning{{Untrusted data is 
used to specify the buffer size}}
 // expected-note@-1{{Untrusted 
data is used to specify the buffer size}}
 // expected-note@-2 {{Taint 
propagated to the return value}}
 return pathbuf;
@@ -71,12 +72,12 @@ char *taintDiagnosticPropagation(){
 char *taintDiagnosticPropagation2(){
   

[PATCH] D159522: [Clang][C] Fixed a bug where we reject an _Atomic qualified integer in a switch statment

2023-09-16 Thread Guillot Tony via Phabricator via cfe-commits
to268 updated this revision to Diff 556892.
to268 marked an inline comment as done.
to268 added a comment.

I have fixed the ReleaseNote formatting error.
Please land this patch on my behalf "Guillot Tony "


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D159522

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Sema/atomic-expr.c


Index: clang/test/Sema/atomic-expr.c
===
--- clang/test/Sema/atomic-expr.c
+++ clang/test/Sema/atomic-expr.c
@@ -216,3 +216,9 @@
   struct T { int a; };
   (void)(_Atomic struct T)s; // expected-error {{used type 'struct T' where 
arithmetic or pointer type is required}}
 }
+
+// Test if we can handle an _Atomic qualified integer in a switch statement.
+void func_19(void) {
+  _Atomic int a = 0;
+  switch (a) { }
+}
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -6302,10 +6302,12 @@
 From = result.get();
   }
 
+  // Try converting the expression to an Lvalue first, to get rid of 
qualifiers.
+  ExprResult Converted = DefaultLvalueConversion(From);
+  QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
   // If the expression already has a matching type, we're golden.
-  QualType T = From->getType();
   if (Converter.match(T))
-return DefaultLvalueConversion(From);
+return Converted;
 
   // FIXME: Check for missing '()' if T is a function type?
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -223,6 +223,8 @@
   an invalid conversion during method function overload resolution.
 - Fix parser crash when dealing with ill-formed objective C++ header code. 
Fixes
   (`#64836 `_)
+- Clang now allows an ``_Atomic`` qualified integer in a switch statement. 
Fixes
+  (`#65557 `_)
 
 Bug Fixes to Compiler Builtins
 ^^


Index: clang/test/Sema/atomic-expr.c
===
--- clang/test/Sema/atomic-expr.c
+++ clang/test/Sema/atomic-expr.c
@@ -216,3 +216,9 @@
   struct T { int a; };
   (void)(_Atomic struct T)s; // expected-error {{used type 'struct T' where arithmetic or pointer type is required}}
 }
+
+// Test if we can handle an _Atomic qualified integer in a switch statement.
+void func_19(void) {
+  _Atomic int a = 0;
+  switch (a) { }
+}
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -6302,10 +6302,12 @@
 From = result.get();
   }
 
+  // Try converting the expression to an Lvalue first, to get rid of qualifiers.
+  ExprResult Converted = DefaultLvalueConversion(From);
+  QualType T = Converted.isUsable() ? Converted.get()->getType() : QualType();
   // If the expression already has a matching type, we're golden.
-  QualType T = From->getType();
   if (Converter.match(T))
-return DefaultLvalueConversion(From);
+return Converted;
 
   // FIXME: Check for missing '()' if T is a function type?
 
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -223,6 +223,8 @@
   an invalid conversion during method function overload resolution.
 - Fix parser crash when dealing with ill-formed objective C++ header code. Fixes
   (`#64836 `_)
+- Clang now allows an ``_Atomic`` qualified integer in a switch statement. Fixes
+  (`#65557 `_)
 
 Bug Fixes to Compiler Builtins
 ^^
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[clang] [RISCV] Support predefined marcro __riscv_misaligned_{fast,avoid}. (PR #65756)

2023-09-16 Thread Yeting Kuo via cfe-commits

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


[clang] [RISCV] Support predefined marcro __riscv_misaligned_{fast,avoid}. (PR #65756)

2023-09-16 Thread Yeting Kuo via cfe-commits

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


[clang] [RISCV] Support predefined marcro __riscv_misaligned_{fast,avoid}. (PR #65756)

2023-09-16 Thread Yeting Kuo via cfe-commits


@@ -1220,3 +1220,15 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32-unknown-linux-gnu -march=rv32i -x c -E -dM %s \

yetingk wrote:

> Should we update this test file to use --target= for all test cases in 
> another patch?
I think I can have a pr for this.

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


[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

2023-09-16 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

2023-09-16 Thread Piotr Zegar via cfe-commits

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


[clang-tools-extra] [clang-tidy] Fix handling --driver-mode= (PR #66553)

2023-09-16 Thread Piotr Zegar via cfe-commits

https://github.com/PiotrZSL updated 
https://github.com/llvm/llvm-project/pull/66553

>From d67dbfb1e926e90b2f4a067c86732bd41783791d Mon Sep 17 00:00:00 2001
From: Piotr Zegar 
Date: Fri, 15 Sep 2023 21:39:17 +
Subject: [PATCH] [clang-tidy] Fix handling --driver-mode=

Driver mode passed as an extra argument (command line or config)
were not utilized for removing invalid arguments in
stripPositionalArgs function, and even if passed as config
driver mode were not used for dependency file striping
leading to invalid handling of -MD. Additionally driver mode
were needed even if user already added cl.exe after --.
---
 .../clang-tidy/tool/ClangTidyMain.cpp | 96 ++-
 clang-tools-extra/docs/ReleaseNotes.rst   |  5 +
 .../clang-tidy/infrastructure/driver-mode.cpp | 57 +++
 3 files changed, 157 insertions(+), 1 deletion(-)
 create mode 100644 
clang-tools-extra/test/clang-tidy/infrastructure/driver-mode.cpp

diff --git a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp 
b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
index 0d2593e74f052b9..d922abeb3ba9bca 100644
--- a/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
+++ b/clang-tools-extra/clang-tidy/tool/ClangTidyMain.cpp
@@ -19,6 +19,7 @@
 #include "../ClangTidyForceLinker.h"
 #include "../GlobList.h"
 #include "clang/Tooling/CommonOptionsParser.h"
+#include "clang/Tooling/Tooling.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/PluginLoader.h"
@@ -26,7 +27,11 @@
 #include "llvm/Support/Signals.h"
 #include "llvm/Support/TargetSelect.h"
 #include "llvm/Support/WithColor.h"
+#include 
+#include 
 #include 
+#include 
+#include 
 
 using namespace clang::tooling;
 using namespace llvm;
@@ -450,7 +455,7 @@ static StringRef closest(StringRef Value, const StringSet<> 
) {
   return Closest;
 }
 
-static constexpr StringLiteral VerifyConfigWarningEnd = " [-verify-config]\n";
+static constexpr StringRef VerifyConfigWarningEnd = " [-verify-config]\n";
 
 static bool verifyChecks(const StringSet<> , StringRef CheckGlob,
  StringRef Source) {
@@ -550,9 +555,91 @@ static llvm::IntrusiveRefCntPtr 
createBaseFS() {
   return BaseFS;
 }
 
+static llvm::Expected
+recreateOptionsParserIfNeeded(llvm::ArrayRef Args,
+  llvm::Expected 
OptionsParser,
+  const ClangTidyOptions ) {
+
+  auto DoubleDashIt = std::find(Args.begin(), Args.end(), StringRef("--"));
+
+  // Exit if we don't have any compiler arguments
+  if (DoubleDashIt == Args.end() || Args.empty() ||
+  Args.back() == StringRef("--"))
+return OptionsParser;
+
+  auto IsDriverMode = [](StringRef Argument) {
+return Argument.startswith("--driver-mode=");
+  };
+
+  // Exit if --driver-mode= is explicitly passed in compiler arguments
+  if (Args.end() !=
+  std::find_if(std::next(DoubleDashIt), Args.end(), IsDriverMode))
+return OptionsParser;
+
+  std::vector CommandArguments(std::next(DoubleDashIt),
+Args.end());
+
+  // Add clang-tool as program name if not added
+  if (CommandArguments.empty() ||
+  llvm::StringRef(CommandArguments.front()).startswith("-"))
+CommandArguments.insert(CommandArguments.begin(), "clang-tool");
+
+  // Apply --extra-arg and --extra-arg-before to compiler arguments
+  CommandArguments =
+  OptionsParser->getArgumentsAdjuster()(CommandArguments, "");
+
+  // Apply ExtraArgsBefore from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgsBefore)
+CommandArguments = tooling::getInsertArgumentAdjuster(
+*EffectiveOptions.ExtraArgsBefore,
+tooling::ArgumentInsertPosition::BEGIN)(CommandArguments, "");
+
+  // Apply ExtraArgs from clang-tidy config to compiler arguments
+  if (EffectiveOptions.ExtraArgs)
+CommandArguments = tooling::getInsertArgumentAdjuster(
+*EffectiveOptions.ExtraArgs,
+tooling::ArgumentInsertPosition::END)(CommandArguments, "");
+
+  // Check if now we have --driver-mode=
+  auto DriverModeIt = std::find_if(CommandArguments.begin(),
+   CommandArguments.end(), IsDriverMode);
+  if (DriverModeIt == CommandArguments.end()) {
+// Try to detect and add --driver-mode=
+std::string ExeName = CommandArguments.front();
+tooling::addTargetAndModeForProgramName(CommandArguments, ExeName);
+DriverModeIt = std::find_if(CommandArguments.begin(),
+CommandArguments.end(), IsDriverMode);
+  }
+
+  // Exit if there is no --driver-mode= at this stage
+  if (DriverModeIt == CommandArguments.end())
+return OptionsParser;
+
+  std::vector NewArgs(Args.begin(), Args.end());
+
+  // Find place to insert --driver-mode= into new args, best after program 
name.
+  auto InsertIt =
+  NewArgs.begin() + std::distance(Args.begin(), DoubleDashIt) + 1U;
+  if (!StringRef(*InsertIt).startswith("-"))
+

[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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

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


[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/66569

>From bf3160066ae83d43837f18825d00c963d0c29ca8 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 15 Sep 2023 21:59:47 -0700
Subject: [PATCH] [clang-format][NFC] Clean up signatures of some parser
 functions

Removed TT_CompoundRequirementLBrace and parameters CanContainBracedList and
NextLBracesType.
---
 clang/lib/Format/FormatToken.h   |  1 -
 clang/lib/Format/TokenAnnotator.cpp  |  2 +-
 clang/lib/Format/UnwrappedLineParser.cpp | 58 ++--
 clang/lib/Format/UnwrappedLineParser.h   | 13 ++
 4 files changed, 29 insertions(+), 45 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 1ea7ce6a564d8fa..0605ac9da7219f2 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -41,7 +41,6 @@ namespace format {
   TYPE(CaseLabelColon) 
\
   TYPE(CastRParen) 
\
   TYPE(ClassLBrace)
\
-  TYPE(CompoundRequirementLBrace)  
\
   /* ternary ?: expression */  
\
   TYPE(ConditionalExpr)
\
   /* the condition in an if statement */   
\
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 142168e074bbc27..138f7e8562dcc39 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1698,7 +1698,7 @@ class AnnotatingParser {
 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, 
TT_RequiresClause,
 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
-TT_CompoundRequirementLBrace, TT_BracedListLBrace)) {
+TT_BracedListLBrace)) {
   CurrentToken->setType(TT_Unknown);
 }
 CurrentToken->Role.reset();
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 0ff0656a92d7222..ef96dea4e7e59e4 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -335,22 +335,16 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 }
 
 /// \brief Parses a level, that is ???.
-/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
-/// \param CanContainBracedList If the content can contain (at any level) a
-/// braced list.
-/// \param NextLBracesType The type for left brace found in this level.
+/// \param OpeningBrace Opening brace (\p nullptr if absent) of that level.
 /// \param IfKind The \p if statement kind in the level.
 /// \param IfLeftBrace The left brace of the \p if block in the level.
 /// \returns true if a simple block of if/else/for/while, or false otherwise.
 /// (A simple block has a single statement.)
 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
- bool CanContainBracedList,
- TokenType NextLBracesType,
  IfStmtKind *IfKind,
  FormatToken **IfLeftBrace) {
-  auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
-  ? TT_BracedListLBrace
-  : TT_Unknown;
+  const bool InRequiresExpression =
+  OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
   const bool IsPrecededByCommentOrPPDirective =
   !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
   FormatToken *IfLBrace = nullptr;
@@ -370,9 +364,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
+auto ParseDefault = [this, OpeningBrace, InRequiresExpression, IfKind,
  , , , ] {
-  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
+  parseStructuralElement(OpeningBrace, InRequiresExpression, IfKind,
  , HasDoWhile ? nullptr : ,
  HasLabel ? nullptr : );
   ++StatementCount;
@@ -385,8 +379,8 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   addUnwrappedLine();
   break;
 case tok::l_brace:
-  if (NextLBracesType != TT_Unknown) {
-FormatTok->setFinalizedType(NextLBracesType);
+  if (InRequiresExpression) {
+FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
   } else if (FormatTok->Previous &&
  FormatTok->Previous->ClosesRequiresClause) {

[clang] [clang-format][NFC] Clean up signatures of some parser functions (PR #66569)

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

https://github.com/owenca updated 
https://github.com/llvm/llvm-project/pull/66569

>From 83b81df954391c38c123a116ab5c39acd29a3a87 Mon Sep 17 00:00:00 2001
From: Owen Pan 
Date: Fri, 15 Sep 2023 21:59:47 -0700
Subject: [PATCH] [clang-format][NFC] Clean up signatures of some parser
 functions

Removed TT_CompoundRequirementLBrace and parameters CanContainBracedList and
NextLBracesType.
---
 clang/lib/Format/FormatToken.h   |  1 -
 clang/lib/Format/TokenAnnotator.cpp  |  2 +-
 clang/lib/Format/UnwrappedLineParser.cpp | 55 ++--
 clang/lib/Format/UnwrappedLineParser.h   | 13 ++
 4 files changed, 28 insertions(+), 43 deletions(-)

diff --git a/clang/lib/Format/FormatToken.h b/clang/lib/Format/FormatToken.h
index 1ea7ce6a564d8fa..0605ac9da7219f2 100644
--- a/clang/lib/Format/FormatToken.h
+++ b/clang/lib/Format/FormatToken.h
@@ -41,7 +41,6 @@ namespace format {
   TYPE(CaseLabelColon) 
\
   TYPE(CastRParen) 
\
   TYPE(ClassLBrace)
\
-  TYPE(CompoundRequirementLBrace)  
\
   /* ternary ?: expression */  
\
   TYPE(ConditionalExpr)
\
   /* the condition in an if statement */   
\
diff --git a/clang/lib/Format/TokenAnnotator.cpp 
b/clang/lib/Format/TokenAnnotator.cpp
index 142168e074bbc27..138f7e8562dcc39 100644
--- a/clang/lib/Format/TokenAnnotator.cpp
+++ b/clang/lib/Format/TokenAnnotator.cpp
@@ -1698,7 +1698,7 @@ class AnnotatingParser {
 TT_RecordLBrace, TT_StructLBrace, TT_UnionLBrace, 
TT_RequiresClause,
 TT_RequiresClauseInARequiresExpression, TT_RequiresExpression,
 TT_RequiresExpressionLParen, TT_RequiresExpressionLBrace,
-TT_CompoundRequirementLBrace, TT_BracedListLBrace)) {
+TT_BracedListLBrace)) {
   CurrentToken->setType(TT_Unknown);
 }
 CurrentToken->Role.reset();
diff --git a/clang/lib/Format/UnwrappedLineParser.cpp 
b/clang/lib/Format/UnwrappedLineParser.cpp
index 0ff0656a92d7222..7f9d51f73762c01 100644
--- a/clang/lib/Format/UnwrappedLineParser.cpp
+++ b/clang/lib/Format/UnwrappedLineParser.cpp
@@ -336,21 +336,16 @@ bool 
UnwrappedLineParser::precededByCommentOrPPDirective() const {
 
 /// \brief Parses a level, that is ???.
 /// \param OpeningBrace Opening brace (\p nullptr if absent) of that level
-/// \param CanContainBracedList If the content can contain (at any level) a
 /// braced list.
-/// \param NextLBracesType The type for left brace found in this level.
 /// \param IfKind The \p if statement kind in the level.
 /// \param IfLeftBrace The left brace of the \p if block in the level.
 /// \returns true if a simple block of if/else/for/while, or false otherwise.
 /// (A simple block has a single statement.)
 bool UnwrappedLineParser::parseLevel(const FormatToken *OpeningBrace,
- bool CanContainBracedList,
- TokenType NextLBracesType,
  IfStmtKind *IfKind,
  FormatToken **IfLeftBrace) {
-  auto NextLevelLBracesType = NextLBracesType == TT_CompoundRequirementLBrace
-  ? TT_BracedListLBrace
-  : TT_Unknown;
+  const bool InRequiresExpression =
+  OpeningBrace && OpeningBrace->is(TT_RequiresExpressionLBrace);
   const bool IsPrecededByCommentOrPPDirective =
   !Style.RemoveBracesLLVM || precededByCommentOrPPDirective();
   FormatToken *IfLBrace = nullptr;
@@ -370,9 +365,9 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
 else if (FormatTok->getType() == TT_MacroBlockEnd)
   kind = tok::r_brace;
 
-auto ParseDefault = [this, OpeningBrace, NextLevelLBracesType, IfKind,
+auto ParseDefault = [this, OpeningBrace, InRequiresExpression, IfKind,
  , , , ] {
-  parseStructuralElement(!OpeningBrace, NextLevelLBracesType, IfKind,
+  parseStructuralElement(OpeningBrace, InRequiresExpression, IfKind,
  , HasDoWhile ? nullptr : ,
  HasLabel ? nullptr : );
   ++StatementCount;
@@ -385,8 +380,8 @@ bool UnwrappedLineParser::parseLevel(const FormatToken 
*OpeningBrace,
   addUnwrappedLine();
   break;
 case tok::l_brace:
-  if (NextLBracesType != TT_Unknown) {
-FormatTok->setFinalizedType(NextLBracesType);
+  if (InRequiresExpression) {
+FormatTok->setFinalizedType(TT_RequiresExpressionLBrace);
   } else if (FormatTok->Previous &&
  FormatTok->Previous->ClosesRequiresClause) {
 // We need the 'default' case here to correctly parse a function
@@ 

[clang] [Driver] Change default PCH extension name from .gch to .pch (PR #66165)

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

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


[clang] 4da1c18 - [Driver] Change default PCH extension name from .gch to .pch (#66165)

2023-09-16 Thread via cfe-commits

Author: Fangrui Song
Date: 2023-09-16T00:27:45-07:00
New Revision: 4da1c180b996ca0a7f8d64782d1a875eb162ce9c

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

LOG: [Driver] Change default PCH extension name from .gch to .pch (#66165)

For `c-header` and `c++-header` inputs, Clang driver selects the
`-emit-pch` frontend action and defaults the output suffix name to
`.gch` (except clang-cl, which uses `.pch`) to follow GCC.
```
clang -c a.h   # a.h.gch
clang -xc++-header -c a.h  # a.h.gch
```

In every other place we prefer `.pch` to `.gch`. E.g. `-include a.h`
probes `a.h.pch` before `a.h.gch`, and we have `-include-pch` instead of
`-include-gch`. (Clang and GCC use different extension names for C++
modules as well.)

This change isn't disruptive because:

* Most newer build systems specify explicit output filenames and are
unaffected
* Implicit output name users almost assuredly use something like
  `-include a.h`, which probes both `a.h.pch` and `a.h.gch`[^1]

[^1]: In the future, we shall stop probing `a.h.gch` for `-include a.h`
as the
compatibility intended behavior actually gets in the way

(https://discourse.llvm.org/t/how-to-have-clang-ignore-gch-directories/51835).
This patch is a prerequisite.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/include/clang/Driver/Types.def
clang/test/Driver/pch-codegen.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 3cdad2f7b9f0e5a..d558705f16ca3be 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -41,6 +41,9 @@ code bases.
 C/C++ Language Potentially Breaking Changes
 ---
 
+- The default extension name for PCH generation (``-c -xc-header`` and ``-c
+  -xc++-header``) is now ``.pch`` instead of ``.gch``.
+
 C++ Specific Potentially Breaking Changes
 -
 

diff  --git a/clang/include/clang/Driver/Types.def 
b/clang/include/clang/Driver/Types.def
index 519d51f8ad1e5f0..b889883125c4c16 100644
--- a/clang/include/clang/Driver/Types.def
+++ b/clang/include/clang/Driver/Types.def
@@ -98,7 +98,7 @@ TYPE("plist",Plist,INVALID,   
  "plist",  phases
 TYPE("rewritten-objc",   RewrittenObjC,INVALID, "cpp",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("rewritten-legacy-objc",RewrittenLegacyObjC,INVALID,   "cpp",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("remap",Remap,INVALID, "remap",  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
-TYPE("precompiled-header",   PCH,  INVALID, "gch",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
+TYPE("precompiled-header",   PCH,  INVALID, "pch",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("object",   Object,   INVALID, "o",  
phases::Link)
 TYPE("treelang", Treelang, INVALID, nullptr,  
phases::Compile, phases::Backend, phases::Assemble, phases::Link)
 TYPE("image",Image,INVALID, "out",
phases::Compile, phases::Backend, phases::Assemble, phases::Link)

diff  --git a/clang/test/Driver/pch-codegen.cpp 
b/clang/test/Driver/pch-codegen.cpp
index f16f6b51bf409ff..ac4ffb978ca59b1 100644
--- a/clang/test/Driver/pch-codegen.cpp
+++ b/clang/test/Driver/pch-codegen.cpp
@@ -2,10 +2,12 @@
 // RUN: mkdir -p %t
 
 // Create PCH without codegen.
-// RUN: %clang -x c++-header %S/../Modules/Inputs/codegen-flags/foo.h -o 
%t/foo-cg.pch -### 2>&1 | FileCheck %s -check-prefix=CHECK-PCH-CREATE
+// RUN: %clang -x c++-header %S/../Modules/Inputs/codegen-flags/foo.h -### 
2>&1 | FileCheck %s -check-prefix=CHECK-PCH-CREATE
 // CHECK-PCH-CREATE: -emit-pch
 // CHECK-PCH-CREATE-NOT: -fmodules-codegen
 // CHECK-PCH-CREATE-NOT: -fmodules-debuginfo
+/// Also test that the default extension name is .pch instead of .gch
+// CHECK-PCH-CREATE: "-o" "{{[^"]+.pch}}"
 
 // Create PCH with -fpch-codegen.
 // RUN: %clang -x c++-header -fpch-codegen 
%S/../Modules/Inputs/codegen-flags/foo.h -o %t/foo-cg.pch -### 2>&1 | FileCheck 
%s -check-prefix=CHECK-PCH-CODEGEN-CREATE



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


[clang] Introduce paged vector (PR #66430)

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


@@ -0,0 +1,133 @@
+//===- llvm/ADT/PagedVector.h - 'Lazyly allocated' vectors *- 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
+//
+//===--===//
+//
+// This file defines the PagedVector class.
+//
+//===--===//
+#ifndef LLVM_ADT_PAGEDVECTOR_H
+#define LLVM_ADT_PAGEDVECTOR_H
+
+#include 
+#include 
+
+namespace llvm {
+// A vector that allocates memory in pages.
+// Order is kept, but memory is allocated only when one element of the page is
+// accessed. This introduces a level of indirection, but it is useful when you
+// have a sparsely initialised vector where the full size is allocated upfront
+// with the default constructor and elements are initialised later, on first
+// access.
+//
+// Notice that this does not have iterators, because if you
+// have iterators it probably means you are going to touch
+// all the memory in any case, so better use a std::vector in
+// the first place.
+template  class PagedVector {
+  // The actual number of element in the vector which can be accessed.
+  std::size_t Size = 0;
+  // The position of the initial element of the page in the Data vector.
+  // Pages are allocated contiguously in the Data vector.
+  mutable std::vector Lookup;
+  // Actual page data. All the page elements are added to this vector on the
+  // first access of any of the elements of the page. Elements default
+  // constructed and elements of the page are stored contiguously. The oder of
+  // the elements however depends on the order of access of the pages.
+  mutable std::vector Data;

zygoloid wrote:

Using a single vector here seems unnecessarily inefficient, due to vector 
working to provide contiguous storage, which you don't need here.

It would be better to instead store pointers in your `PageToData` vector, and 
store a block of unallocated pages, allocating a new block (with exponential 
growth, like `vector`), when you run out. Alternatively, you could make this 
container take a `BumpPtrAllocator` for its pages, and pass in the Clang AST's 
allocator; that way you could share the same memory pool as the AST and 
minimize overallocation.

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


[clang] Introduce paged vector (PR #66430)

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


@@ -0,0 +1,131 @@
+//===- llvm/ADT/PagedVector.h - 'Lazyly allocated' vectors *- 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
+//
+//===--===//
+//
+// This file defines the PagedVector class.
+//
+//===--===//
+#ifndef LLVM_ADT_PAGEDVECTOR_H
+#define LLVM_ADT_PAGEDVECTOR_H
+
+#include 
+#include 
+
+namespace llvm {
+// A vector that allocates memory in pages.
+// Order is kept, but memory is allocated only when one element of the page is
+// accessed. This introduces a level of indirection, but it is useful when you
+// have a sparsely initialised vector where the full size is allocated upfront
+// with the default constructor and elements are initialised later, on first
+// access.
+//
+// Notice that this does not have iterators, because if you
+// have iterators it probably means you are going to touch
+// all the memory in any case, so better use a std::vector in
+// the first place.
+template 

zygoloid wrote:

Please consider adding some kind of check that PAGE_SIZE is not too small. It 
needs to be at least 1, for a start.

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


[clang] Introduce paged vector (PR #66430)

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


@@ -1625,6 +1625,35 @@ SmallVector has grown a few other minor advantages over 
std::vector, causing
and is no longer "private to the implementation". A name like
``SmallVectorHeader`` might be more appropriate.
 
+.. _dss_pagedvector:
+
+llvm/ADT/PagedVector.h
+^^
+
+``PagedVector`` is a random access container that allocates 
(PageSize) elements
+of type Type when the first element of a page is accessed via the 
``operator[]`` or the ``at()``
+method.  This is useful for the case in which the number of elements is known 
in advance and 
+their actual initialization is expensive and sparse so that it's only done 
lazily when the element is 
+accessed. When the number of used pages is small significant memory savings 
can be achieved.
+
+The main advantage is that a PagedVector allows to delay the actual allocation 
of the page until it's needed,
+at the extra cost of one integer per page and one extra indirection when 
accessing elements with their positional
+index. 
+
+In order to maximise the memory footprint of this container, it's important to 
balance the PageSize so that 
+it's not too small (otherwise the overhead of the integer per page might 
become too high) and not too big 
+(otherwise the memory is wasted if the page is not fully used).
+
+The PagedVector can only be expanded at the end, and it's not possible to 
shrink it, to keep the implementation
+simple and not give the false hope that the resize operation is cheap.
+
+Moreover, while retaining the oder of the elements based on their insertion 
index, like a vector, iterating over

zygoloid wrote:

Typo "oder"

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


[clang] Introduce paged vector (PR #66430)

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


@@ -1625,6 +1625,35 @@ SmallVector has grown a few other minor advantages over 
std::vector, causing
and is no longer "private to the implementation". A name like
``SmallVectorHeader`` might be more appropriate.
 
+.. _dss_pagedvector:
+
+llvm/ADT/PagedVector.h
+^^
+
+``PagedVector`` is a random access container that allocates 
(PageSize) elements
+of type Type when the first element of a page is accessed via the 
``operator[]`` or the ``at()``
+method.  This is useful for the case in which the number of elements is known 
in advance and 
+their actual initialization is expensive and sparse so that it's only done 
lazily when the element is 
+accessed. When the number of used pages is small significant memory savings 
can be achieved.
+
+The main advantage is that a PagedVector allows to delay the actual allocation 
of the page until it's needed,
+at the extra cost of one integer per page and one extra indirection when 
accessing elements with their positional
+index. 
+
+In order to maximise the memory footprint of this container, it's important to 
balance the PageSize so that 
+it's not too small (otherwise the overhead of the integer per page might 
become too high) and not too big 
+(otherwise the memory is wasted if the page is not fully used).
+
+The PagedVector can only be expanded at the end, and it's not possible to 
shrink it, to keep the implementation
+simple and not give the false hope that the resize operation is cheap.
+
+Moreover, while retaining the oder of the elements based on their insertion 
index, like a vector, iterating over
+the elements via begin() and end() is not provided in the API, due to the fact 
accessing the elements in order would
+allocate all the iterated pages, defeating memory savings and the purpose of 
the PagedVector.
+
+Finally a ``materialised()`` method is provided to access the elements 
associated to the accessed pages, which could
+speedup operations that need to iterate over initialized elements in a 
non-ordered manner.

zygoloid wrote:

```suggestion
speed up operations that need to iterate over initialized elements in a 
non-ordered manner.
```

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


  1   2   >