[PATCH] D137036: [X86] Enable EVEX GFNI instructions without avx512bw.

2022-10-31 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei accepted this revision.
pengfei added a comment.
This revision is now accepted and ready to land.

LGTM, thanks for the patch!




Comment at: llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll:29
+;
+; X86NOBW-LABEL: test_vgf2p8affineinvqb_128:
+; X86NOBW:   # %bb.0:

Since we are able to lower the mask version intrinsics, we have 3 choices for 
the FE support:
1. Still disallow Clang intrinsics for AVX512F. This matches with GCC too;
2. Allow the mask intrinsics as well. This matches with Intrinsic Guide and SDM 
somehow;
3. And mixed for AVX512F and AVX512BW as in this revision;
I slightly prefer to 1). I think the intention of the EVEX design is to use the 
masked instructions directly, so it should always imply AVX512BW in reality. 
But I'm fine with any way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137036

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


[PATCH] D137056: [clangd] Fix a small inconsistency in system-include-extractor.test

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge created this revision.
nridge added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
nridge requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Also add an explanatory comment


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137056

Files:
  clang-tools-extra/clangd/test/system-include-extractor.test


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,12 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc. 
arguments,
+# all of which are present in the command in compile_commands.json below, are 
passed
+# on by clang to the driver being queried (unlike most other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,12 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc. arguments,
+# all of which are present in the command in compile_commands.json below, are passed
+# on by clang to the driver being queried (unlike most other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> %t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> %t.dir/bin/my_driver.sh
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137056: [clangd] Fix a small inconsistency in system-include-extractor.test

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 471908.
nridge added a comment.

format comment better


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137056

Files:
  clang-tools-extra/clangd/test/system-include-extractor.test


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,13 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc.
+# arguments, all of which are present in the command in compile_commands.json
+# below, are passed on by clang to the driver being queried (unlike most
+# other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,13 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc.
+# arguments, all of which are present in the command in compile_commands.json
+# below, are passed on by clang to the driver being queried (unlike most
+# other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> %t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> %t.dir/bin/my_driver.sh
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137056: [clangd] Fix a small inconsistency in system-include-extractor.test

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 471909.
nridge added a comment.

fix typo


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137056

Files:
  clang-tools-extra/clangd/test/system-include-extractor.test


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,13 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc.
+# arguments, all of which are present in the command in compile_commands.json
+# below, are passed on by clangd to the driver being queried (unlike most
+# other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> 
%t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> 
%t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> 
%t.dir/bin/my_driver.sh


Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -11,9 +11,13 @@
 # RUN: echo '#!/bin/sh' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ "$0" = "%t.dir/bin/my_driver.sh" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'args="$*"' >> %t.dir/bin/my_driver.sh
+# The purpose of the three lines below is to test that the -nostdinc etc.
+# arguments, all of which are present in the command in compile_commands.json
+# below, are passed on by clangd to the driver being queried (unlike most
+# other arguments).
 # RUN: echo '[ -z "${args##*"-nostdinc"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo '[ -z "${args##*"-isysroot=/isysroot"*}" ] || exit' >> %t.dir/bin/my_driver.sh
-# RUN: echo 'echo " $* " | grep " --sysroot /my/sysroot/path " || exit' >> %t.dir/bin/my_driver.sh
+# RUN: echo '[ -z "${args##*"--sysroot /my/sysroot/path"*}" ] || exit' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'echo line to ignore >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "Target: arm-linux-gnueabihf\r\n" >&2' >> %t.dir/bin/my_driver.sh
 # RUN: echo 'printf "#include <...> search starts here:\r\n" >&2' >> %t.dir/bin/my_driver.sh
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136545: [Clang] use non-instantiated function declaration for constraints partial ordering

2022-10-31 Thread NAKAMURA Takumi via Phabricator via cfe-commits
chapuni added inline comments.



Comment at: clang/lib/Sema/SemaConcept.cpp:1310
+const auto *FD2 = dyn_cast(D2);
+assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
+   "use non-instantiated function declaration for constraints partial "

IsExpectedEntity, FD2, (and possibly FD1) are used only in assert.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136545

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


[PATCH] D137058: [Driver] [Modules] Support -fsave-std-c++-module-file (1/2)

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: dblaikie, ben.boeckel, iains, tschuett.
ChuanqiXu added a project: clang-modules.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Patches to support the `one-phase` compilation model for modules. This is the 
successor of D134267 .

@dblaikie suggests to do the following 3 steps to make the `one-phase` 
compilation model.
(1) Support `.cppm -> .pcm + .o` in one phase. (This patch)
(2) Support specify the path of `.pcm` file in the one phase compilation.
(3) Support the module cache.

Then @ben.boeckel clarifies that the module cache is not necessary. So I won't 
pursue it too. This patch adds an option `-fsave-std-c++-module-file` to save 
the module file if we compile the module unit to object files directly. Why a 
new option? Because I think it may pollutes the space if we make the behavior 
default. And I feel good to add an option for this behavior.

The behavior:
(1) If `-o` is specified , the module file is in the same path within the same 
directory as the output the `-o`  specified and with a new suffix `.pcm`.
(2) If `-o` is not specified, the module file is in the same path within the 
same directory as the input file and with the new suffix `.pcm`.

For example,

  Hello.cppm Use.cpp

A trivial one and the contents are ignored. When we run:

  clang++ -std=c++20 -fsave-std-c++-module-file Hello.cppm -c

The directory would look like:

  Hello.cppm  Hello.o  Hello.pcm Use.cpp

And if we run:

  clang++ -std=c++20 -fsave-std-c++-module-file Hello.cppm -c -o output/Hello.o

Then the `output` directory may look like:

  Hello.o  Hello.pcm

Can we compile the `Hello World` example in one command line? Yes! we can do 
the following one:

  clang++ -std=c++20 Hello.cppm  Use.cpp -fsave-std-c++-module-file 
-fprebuilt-module-path=.



---

I'll add the ReleaseNotes and documentation after the series got accepted.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137058

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/save-std-c++-module-file.cpp


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- /dev/null
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -0,0 +1,17 @@
+// RUN: rm -rf %t
+// RUN: mkdir %t
+// RUN: split-file %s %t
+//
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -c
+// RUN: ls %t | FileCheck %t/Hello.cppm --check-prefix=CHECK-DEFAULT
+//
+// RUN: mkdir %t/tmp
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -c -o 
%t/tmp/H.o
+// RUN: ls %t/tmp | FileCheck %t/Hello.cppm --check-prefix=CHECK-O
+
+
+//--- Hello.cppm
+export module Hello;
+
+// CHECK-DEFAULT: Hello.pcm
+// CHECK-O: H.pcm
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5532,6 +5532,28 @@
 return "-";
   }
 
+  // If `-fsave-std-c++-module-file` is specfied, then:
+  // - If `-o` is specified, the module file is writing to the same path
+  //   with the output file in module file's suffix. 
+  // - If `-o` is not specified, the module file is writing to the same path
+  //   with the input file in module file's suffix.
+  //
+  // FIXME: Do we need to handle the case that the calculated output is
+  // conflicting with the specified output file or the input file?
+  if (!AtTopLevel && isa(JA) &&
+  JA.getType() == types::TY_ModuleFile &&
+  C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file)) {
+SmallString<128> TempPath;
+if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
+  TempPath = FinalOutput->getValue();
+else
+  TempPath = BaseInput;
+
+const char *Extension = types::getTypeTempSuffix(JA.getType());
+llvm::sys::path::replace_extension(TempPath, Extension);
+return C.addResultFile(C.getArgs().MakeArgString(TempPath.c_str()), &JA);
+  }
+
   if (IsDXCMode() && !C.getArgs().hasArg(options::OPT_o))
 return "-";
 
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2276,6 +2276,9 @@
   PosFlag,
   NegFlag, BothFlags<[NoXarchOption, CC1Option]>>;
 
+def fsave_std_cxx_module_file : Flag<["-"], "fsave-std-c++-module-file">, 
Flags<[NoXarchOption, CC1Option]>,
+  HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
+
 def fmodules_prune_interval : Joined<["-"], "fmodules-prune-interval=">, 
Group,
   Flags<[CC1Option]>, MetaVarName<"">,
   HelpText<"Specify the interval (in seconds) between attempts to prune the 
module cache">,


Index: clang/test/Driver/save-std-c++-mod

[clang] 21bac59 - Fix unused-variable warning in release build, NFC

2022-10-31 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-31T08:53:30+01:00
New Revision: 21bac595041d46d9882fb930a4467055b99ffa0a

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

LOG: Fix unused-variable warning in release build, NFC

Added: 


Modified: 
clang/lib/Sema/SemaConcept.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index 54d8a746fa247..63c58d64c472b 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -1307,6 +1307,8 @@ bool Sema::IsAtLeastAsConstrained(NamedDecl *D1,
  Kind == FunctionDecl::TK_FunctionTemplate;
 };
 const auto *FD2 = dyn_cast(D2);
+(void)IsExpectedEntity;
+(void)FD2;
 assert(IsExpectedEntity(FD1) && FD2 && IsExpectedEntity(FD2) &&
"use non-instantiated function declaration for constraints partial "
"ordering");



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


[PATCH] D137059: [Driver] [Modules] Introduce -fsave-std-c++-module-file= to specify the path of the module file

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu created this revision.
ChuanqiXu added reviewers: dblaikie, ben.boeckel, iains, tschuett.
ChuanqiXu added a project: clang-modules.
Herald added a project: All.
ChuanqiXu requested review of this revision.
Herald added subscribers: cfe-commits, MaskRay.
Herald added a project: clang.

Successor of D137058 . The intention is 
described as the second step in D137058 . 
This is helpful if the build systems want to generate these output files in 
other places which is not the same with `-o` specified or the input file lived.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137059

Files:
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/save-std-c++-module-file.cpp


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- clang/test/Driver/save-std-c++-module-file.cpp
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -8,6 +8,11 @@
 // RUN: mkdir %t/tmp
 // RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -c -o 
%t/tmp/H.o
 // RUN: ls %t/tmp | FileCheck %t/Hello.cppm --check-prefix=CHECK-O
+//
+// RUN: rm -fr %t/tmp/*
+// RUN: %clang -std=c++20 %t/Hello.cppm 
-fsave-std-c++-module-file=%t/tmp/Hello.pcm \
+// RUN:  -c -o %t/tmp/H.o
+// RUN: ls %t/tmp | FileCheck %t/Hello.cppm --check-prefix=CHECK-EQ
 
 
 //--- Hello.cppm
@@ -15,3 +20,4 @@
 
 // CHECK-DEFAULT: Hello.pcm
 // CHECK-O: H.pcm
+// CHECK-EQ: Hello.pcm
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5533,18 +5533,24 @@
   }
 
   // If `-fsave-std-c++-module-file` is specfied, then:
-  // - If `-o` is specified, the module file is writing to the same path
+  // - If `-fsave-std-c++-module-file` has a value, the module file is
+  //   writing to the value.
+  // - Else if `-o` is specified, the module file is writing to the same path
   //   with the output file in module file's suffix. 
-  // - If `-o` is not specified, the module file is writing to the same path
+  // - Else, the module file is writing to the same path
   //   with the input file in module file's suffix.
   //
   // FIXME: Do we need to handle the case that the calculated output is
   // conflicting with the specified output file or the input file?
   if (!AtTopLevel && isa(JA) &&
   JA.getType() == types::TY_ModuleFile &&
-  C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file)) {
+  (C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file) ||
+   C.getArgs().hasArg(options::OPT_fsave_std_cxx_module_file_EQ))) {
 SmallString<128> TempPath;
-if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
+
+if (Arg *ModuleFilePath = 
C.getArgs().getLastArg(options::OPT_fsave_std_cxx_module_file_EQ))
+  TempPath = ModuleFilePath->getValue();
+else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
   TempPath = FinalOutput->getValue();
 else
   TempPath = BaseInput;
Index: clang/include/clang/Driver/Options.td
===
--- clang/include/clang/Driver/Options.td
+++ clang/include/clang/Driver/Options.td
@@ -2276,6 +2276,8 @@
   PosFlag,
   NegFlag, BothFlags<[NoXarchOption, CC1Option]>>;
 
+def fsave_std_cxx_module_file_EQ : Joined<["-"], 
"fsave-std-c++-module-file=">, Flags<[NoXarchOption, CC1Option]>,
+  HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
 def fsave_std_cxx_module_file : Flag<["-"], "fsave-std-c++-module-file">, 
Flags<[NoXarchOption, CC1Option]>,
   HelpText<"Save intermediate module file results when compiling a standard 
C++ module unit.">;
 


Index: clang/test/Driver/save-std-c++-module-file.cpp
===
--- clang/test/Driver/save-std-c++-module-file.cpp
+++ clang/test/Driver/save-std-c++-module-file.cpp
@@ -8,6 +8,11 @@
 // RUN: mkdir %t/tmp
 // RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file -c -o %t/tmp/H.o
 // RUN: ls %t/tmp | FileCheck %t/Hello.cppm --check-prefix=CHECK-O
+//
+// RUN: rm -fr %t/tmp/*
+// RUN: %clang -std=c++20 %t/Hello.cppm -fsave-std-c++-module-file=%t/tmp/Hello.pcm \
+// RUN:  -c -o %t/tmp/H.o
+// RUN: ls %t/tmp | FileCheck %t/Hello.cppm --check-prefix=CHECK-EQ
 
 
 //--- Hello.cppm
@@ -15,3 +20,4 @@
 
 // CHECK-DEFAULT: Hello.pcm
 // CHECK-O: H.pcm
+// CHECK-EQ: Hello.pcm
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -5533,18 +5533,24 @@
   }
 
   // If `-fsave-std-c++-module-file` is specfied, then:
-  // - If `-o` is specified, the module file is writing to the same path
+  // - If `-fsave-std-c++-module-file` has a value, the mo

[PATCH] D137036: [X86] Enable EVEX GFNI instructions without avx512bw.

2022-10-31 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added inline comments.



Comment at: llvm/test/CodeGen/X86/avx512-gfni-intrinsics.ll:29
+;
+; X86NOBW-LABEL: test_vgf2p8affineinvqb_128:
+; X86NOBW:   # %bb.0:

pengfei wrote:
> Since we are able to lower the mask version intrinsics, we have 3 choices for 
> the FE support:
> 1. Still disallow Clang intrinsics for AVX512F. This matches with GCC too;
> 2. Allow the mask intrinsics as well. This matches with Intrinsic Guide and 
> SDM somehow;
> 3. And mixed for AVX512F and AVX512BW as in this revision;
> I slightly prefer to 1). I think the intention of the EVEX design is to use 
> the masked instructions directly, so it should always imply AVX512BW in 
> reality. But I'm fine with any way.
I think gcc allows the 128-bit mask with avx512vl only. The 256 and 512 require 
avx512bw due to needing kmovd and kmovq to have a large enough mask register.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137036

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


[PATCH] D134267: [C++] [Modules] Support one phase compilation model for named modules

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

In D134267#3892629 , @ben.boeckel 
wrote:

> In D134267#3876071 , @dblaikie 
> wrote:
>
>> I'm getting a bit exhausted with all the words involved here & not sure how 
>> to simplify/clarify this.
>>
>> If @ben.boeckel has particular use cases, it might be easier for him to be 
>> here discussing them so we can discuss the tradeoffs directly rather than 
>> through intermediaries.
>
> Sorry, I've been lax on actually keeping up-to-date on all of these Clang 
> threads.
>
> The current state is that CMake's test suite for C++ modules does not work 
> with clang because it doesn't provide the control CMake needs to do its 
> explicit builds. @ChuanqiXu's MyP1689 branch is close except that the `.pcm` 
> output path can't seem to be controlled closely enough for reliable builds. 
> Namely, I would like:
>
> - the ability to disable the module cache (completely); CMake doesn't need 
> nor want it
> - the ability to say put the generated `.pcm` that this TU will generate goes 
> *here*
>
> The latter is currently a juggle of flags and restrictions that I haven't 
> been able to figure out. Without something like `-fmodule-output-path=`, 
> convincing Clang to output its `.pcm` file to where CMake wants it to be is 
> some combination of `-fmodules-cache-path=` and `-fmodule-name=` while hoping 
> that the internal path computation inside of Clang makes what CMake wants. 
> It's just far easier to have something like `-o` that gives the answer 
> straight away.
>
> For the former, I use `-x c++module` as well so that I don't have to care 
> about any extension-sniffing behaviors. I also need to give a bogus 
> `-fmodule-cache-path=` for module consumers because as soon as `import` is 
> seen, it wants to run off to look at the cache instead of noticing that 
> there's a `-fmodule-file=` for everything it needs already and the cache is 
> 100% unused.

BTW, the bogus `-fmodule-cache-path=` for module consumers can be addressed by 
the existing `-fprebuilt-module-path`. And I sent the new revisions in D137058 
 and D137059 
.


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

https://reviews.llvm.org/D134267

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


[clang] e12b627 - [docs] Add the description about mixing use of clang modules and c++

2022-10-31 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-10-31T16:02:43+08:00
New Revision: e12b627a35ee41e2bee069bf871c8b779f4d4e35

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

LOG: [docs] Add the description about mixing use of clang modules and c++
modules

>From the discussion in
https://discourse.llvm.org/t/how-should-we-support-dependency-scanner-for-c-20-modules/66027,
we get a consensus that we want to support clang modules and c++ modules
at the same time. This patch documents this intention.

Reviewed By: bruno

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

Added: 


Modified: 
clang/docs/StandardCPlusPlusModules.rst

Removed: 




diff  --git a/clang/docs/StandardCPlusPlusModules.rst 
b/clang/docs/StandardCPlusPlusModules.rst
index 86ba6f44dbb02..021edbc3dfdff 100644
--- a/clang/docs/StandardCPlusPlusModules.rst
+++ b/clang/docs/StandardCPlusPlusModules.rst
@@ -874,3 +874,10 @@ purposes of optimization (but definitions of these 
functions are still not inclu
 this means the build speedup at higher optimization levels may be lower than 
expected given ``O0`` experience, 
 but does provide by more optimization opportunities.
 
+Interoperability with Clang Modules
+---
+
+We **wish** to support clang modules and standard c++ modules at the same time,
+but the mixed using form is not well used/tested yet.
+
+Please file new github issues as you find interoperability problems.



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


[PATCH] D136221: [docs] Add the description about mixing use of clang modules and c++ modules

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
Closed by commit rGe12b627a35ee: [docs] Add the description about mixing use of 
clang modules and c++ (authored by ChuanqiXu).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136221

Files:
  clang/docs/StandardCPlusPlusModules.rst


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -874,3 +874,10 @@
 this means the build speedup at higher optimization levels may be lower than 
expected given ``O0`` experience, 
 but does provide by more optimization opportunities.
 
+Interoperability with Clang Modules
+---
+
+We **wish** to support clang modules and standard c++ modules at the same time,
+but the mixed using form is not well used/tested yet.
+
+Please file new github issues as you find interoperability problems.


Index: clang/docs/StandardCPlusPlusModules.rst
===
--- clang/docs/StandardCPlusPlusModules.rst
+++ clang/docs/StandardCPlusPlusModules.rst
@@ -874,3 +874,10 @@
 this means the build speedup at higher optimization levels may be lower than expected given ``O0`` experience, 
 but does provide by more optimization opportunities.
 
+Interoperability with Clang Modules
+---
+
+We **wish** to support clang modules and standard c++ modules at the same time,
+but the mixed using form is not well used/tested yet.
+
+Please file new github issues as you find interoperability problems.
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136554: Implement CWG2631

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added a comment.

The serialization part looks good to me.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

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


[PATCH] D135930: [X86] Add AVX-NE-CONVERT instructions.

2022-10-31 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe marked an inline comment as done.
FreddyYe added inline comments.



Comment at: clang/lib/Headers/avx512vlbf16intrin.h:164
+#define _mm_cvtneps_pbh(A) \
+  ((__m128bh)__builtin_ia32_vcvtneps2bf16128((__v4sf)(A)))
 

pengfei wrote:
> pengfei wrote:
> > RKSimon wrote:
> > > Is there no way for __attribute__ to allow different attribute 
> > > permutations?
> > > 
> > > Also, can we keep the __builtin_ia32_cvtneps2bf16_128 naming convention?
> > > Is there no way for attribute to allow different attribute permutations?
> > 
> > We have discussed this problem with GCC folks. There are two problems here:
> > 1. Unlike builtins, function attributes are more generic. It may introduce 
> > a lot of checks between callers and callees. I had a research to limit it 
> > to `__always_inline__` functions only. However, Clang handles inlining in 
> > middle-end, we don't have such information in the front-end. Besides, we 
> > don't know how to merge different permutations if they are inlining to the 
> > same function.
> > 2. We don't know how to put the permutations into IR's function attributes. 
> > We need to preserve all permutations for inlining reference, but the 
> > backend needs a determine feature list rather than selective.
> It's better to use `__builtin_ia32_cvtneps2bf16_128`.
I think __builtin_ia32_vcvtneps2bf16128 is also a "right" name.

See __builtin_ia32_vfmaddsubph256, __builtin_ia32_minph256...

And I admit naming conventions of clang builtins as well as LLVM IR builtins 
are confusing right now.


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

https://reviews.llvm.org/D135930

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


[clang] fd3d7a9 - Handle errors in expansion of response files

2022-10-31 Thread Serge Pavlov via cfe-commits

Author: Serge Pavlov
Date: 2022-10-31T15:36:41+07:00
New Revision: fd3d7a9f8cbb5ad81fb96d92d5f7b1d51a4d4127

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

LOG: Handle errors in expansion of response files

Previously an error raised during an expansion of response files (including
configuration files) was ignored and only the fact of its presence was
reported to the user with generic error messages. This made it difficult to
analyze problems. For example, if a configuration file tried to read an
inexistent file, the error message said that 'configuration file cannot
be found', which is wrong and misleading.

This change enhances handling errors in the expansion so that users
could get more informative error messages.

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

Added: 


Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/lib/Driver/Driver.cpp
clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
clang/test/Driver/config-file-errs.c
clang/tools/driver/driver.cpp
clang/unittests/Driver/ToolChainTest.cpp
flang/tools/flang-driver/driver.cpp
llvm/include/llvm/Support/CommandLine.h
llvm/lib/Support/CommandLine.cpp
llvm/unittests/Support/CommandLineTest.cpp

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index b09e124206213..e477d93ba067f 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -214,14 +214,14 @@ def err_drv_malformed_sanitizer_coverage_ignorelist : 
Error<
   "malformed sanitizer coverage ignorelist: '%0'">;
 def err_drv_duplicate_config : Error<
   "no more than one option '--config' is allowed">;
-def err_drv_config_file_not_exist : Error<
-  "configuration file '%0' does not exist">;
+def err_drv_cannot_open_config_file : Error<
+  "configuration file '%0' cannot be opened: %1">;
 def err_drv_config_file_not_found : Error<
   "configuration file '%0' cannot be found">;
 def note_drv_config_file_searched_in : Note<
   "was searched for in the directory: %0">;
 def err_drv_cannot_read_config_file : Error<
-  "cannot read configuration file '%0'">;
+  "cannot read configuration file '%0': %1">;
 def err_drv_nested_config_file: Error<
   "option '--config' is not allowed inside configuration file">;
 def err_drv_arg_requires_bitcode_input: Error<

diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 26729f1d03ea8..80e6ec76d16f7 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -940,10 +940,24 @@ static void appendOneArg(InputArgList &Args, const Arg 
*Opt,
 
 bool Driver::readConfigFile(StringRef FileName,
 llvm::cl::ExpansionContext &ExpCtx) {
+  // Try opening the given file.
+  auto Status = getVFS().status(FileName);
+  if (!Status) {
+Diag(diag::err_drv_cannot_open_config_file)
+<< FileName << Status.getError().message();
+return true;
+  }
+  if (Status->getType() != llvm::sys::fs::file_type::regular_file) {
+Diag(diag::err_drv_cannot_open_config_file)
+<< FileName << "not a regular file";
+return true;
+  }
+
   // Try reading the given file.
   SmallVector NewCfgArgs;
-  if (!ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
-Diag(diag::err_drv_cannot_read_config_file) << FileName;
+  if (llvm::Error Err = ExpCtx.readConfigFile(FileName, NewCfgArgs)) {
+Diag(diag::err_drv_cannot_read_config_file)
+<< FileName << toString(std::move(Err));
 return true;
   }
 
@@ -1025,12 +1039,9 @@ bool Driver::loadConfigFiles() {
   if (llvm::sys::path::has_parent_path(CfgFileName)) {
 CfgFilePath.assign(CfgFileName);
 if (llvm::sys::path::is_relative(CfgFilePath)) {
-  if (getVFS().makeAbsolute(CfgFilePath))
-return true;
-  auto Status = getVFS().status(CfgFilePath);
-  if (!Status ||
-  Status->getType() != llvm::sys::fs::file_type::regular_file) {
-Diag(diag::err_drv_config_file_not_exist) << CfgFilePath;
+  if (getVFS().makeAbsolute(CfgFilePath)) {
+Diag(diag::err_drv_cannot_open_config_file)
+<< CfgFilePath << "cannot get absolute path";
 return true;
   }
 }

diff  --git a/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp 
b/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
index c4b3abc1a0a45..88d20ba3957d2 100644
--- a/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
+++ b/clang/lib/Tooling/ExpandResponseFilesCompilationDatabase.cpp
@@ -61,9 +61,11 @@ class ExpandResponseFilesDatabase : public 
CompilationDatabase {
 continue;
  

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

2022-10-31 Thread Tao Liang via Phabricator via cfe-commits
Origami404 added a comment.

After digging more deeply into tests, I found that if we decide to make clang 
include `stdc-predef.h` or other things, the behavior of many 
libtooling-related tools (e.g. clang-tidy, clangd, and python binding) will be 
affected.

For example, `clang-tidy/checkers/cppcoreguidelines/macro-usage.cpp` tests 
improper macro usage. If we #include `stdc-predef.h` implicitly, it will give 
warnings to macros that are inside this header. Another example is 
`clang-tidy/checkers/portability/restrict-system-includes-disallow.cpp`, it 
will give errors for including `stdc-predef.h`.

In my opinion, we may need to spend more time discussing how to make 
`__STD_C_*` macros available. The way that D34158 
 take will affect too many tools using 
libtooling, which may not be a problem back in 2017.

By the way, I have made a patch to pass tests about clang-tidy and python 
binding by adding more `-ffreestanding` flags. But I think it's better to 
re-think the impact it will make instead of just making the test pass. But I 
still can not figure out why the `git clang-format` failed on the CI.


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] D133757: [clangd] Turn QueryDriverDatabase into a CompileCommandsAdjuster

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge updated this revision to Diff 471925.
nridge added a comment.

reformulate test as lit test
address other review comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133757

Files:
  clang-tools-extra/clangd/ClangdLSPServer.cpp
  clang-tools-extra/clangd/CompileCommands.cpp
  clang-tools-extra/clangd/CompileCommands.h
  clang-tools-extra/clangd/GlobalCompilationDatabase.h
  clang-tools-extra/clangd/QueryDriverDatabase.cpp
  clang-tools-extra/clangd/test/system-include-extractor.test
  clang-tools-extra/clangd/tool/Check.cpp

Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -100,9 +100,9 @@
 Config::current().CompileFlags.CDBSearch.FixedCDBPath;
 std::unique_ptr BaseCDB =
 std::make_unique(CDBOpts);
-BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs),
- std::move(BaseCDB));
 auto Mangler = CommandMangler::detect();
+Mangler.SystemIncludeExtractor =
+getSystemIncludeExtractor(llvm::makeArrayRef(Opts.QueryDriverGlobs));
 if (Opts.ResourceDir)
   Mangler.ResourceDir = *Opts.ResourceDir;
 auto CDB = std::make_unique(
Index: clang-tools-extra/clangd/test/system-include-extractor.test
===
--- clang-tools-extra/clangd/test/system-include-extractor.test
+++ clang-tools-extra/clangd/test/system-include-extractor.test
@@ -42,7 +42,7 @@
 # RUN: sed -E -e 's|"file://([A-Z]):/|"file:///\1:/|g' %t.test.1 > %t.test
 
 # Bless the mock driver we've just created so that clangd can execute it.
-# RUN: clangd -lit-test -query-driver="**.test,**.sh" < %t.test | FileCheck -strict-whitespace %t.test
+# RUN: clangd -lit-test -query-driver="**.test,**.sh" < %t.test | FileCheck -strict-whitespace %t.test --check-prefix=CHECK1
 {"jsonrpc":"2.0","id":0,"method":"initialize","params":{}}
 ---
 {
@@ -57,10 +57,38 @@
 }
   }
 }
-# CHECK:   "method": "textDocument/publishDiagnostics",
-# CHECK-NEXT:   "params": {
-# CHECK-NEXT: "diagnostics": [],
+# CHECK1:   "method": "textDocument/publishDiagnostics",
+# CHECK1-NEXT:   "params": {
+# CHECK1-NEXT: "diagnostics": [],
+# CHECK1-NEXT: "uri": "file://INPUT_DIR/the-file.cpp",
 ---
 {"jsonrpc":"2.0","id":1,"method":"shutdown"}
 ---
 {"jsonrpc":"2.0","method":"exit"}
+
+# Generate a different compile_commands.json which does not point to the mock driver
+# RUN: echo '[{"directory": "%/t.dir", "command": "gcc the-file.cpp -nostdinc --sysroot /my/sysroot/path -isysroot=/isysroot", "file": "the-file.cpp"}]' > %t.dir/compile_commands.json
+
+# Generate a clangd config file which points to the mock driver instead
+# RUN: echo 'CompileFlags:' > %t.dir/.clangd
+# RUN: echo '  Compiler: my_driver.sh' >> %t.dir/.clangd
+
+# Run clangd a second time, to make sure it picks up the driver name from the config file
+# Reuse the same input as above, but make different CHECKs because this time we'll
+# get publishDiagnostics for the config files too.
+# Note, we need to pass -enable-config because -lit-test otherwise disables it
+# RUN: clangd -lit-test -enable-config -query-driver="**.test,**.sh" < %t.test | FileCheck -strict-whitespace %t.test --check-prefix=CHECK2
+
+# Skip past the lack of diagnostics in the workspace and user config files...
+# CHECK2:   "method": "textDocument/publishDiagnostics",
+# CHECK2-NEXT:   "params": {
+# CHECK2-NEXT: "diagnostics": [],
+# CHECK2:   "method": "textDocument/publishDiagnostics",
+# CHECK2-NEXT:   "params": {
+# CHECK2-NEXT: "diagnostics": [],
+
+# ... to get to the interesting check: no diagnostics in the C++ file
+# CHECK2:   "method": "textDocument/publishDiagnostics",
+# CHECK2-NEXT:   "params": {
+# CHECK2-NEXT: "diagnostics": [],
+# CHECK2-NEXT: "uri": "file://INPUT_DIR/the-file.cpp",
Index: clang-tools-extra/clangd/QueryDriverDatabase.cpp
===
--- clang-tools-extra/clangd/QueryDriverDatabase.cpp
+++ clang-tools-extra/clangd/QueryDriverDatabase.cpp
@@ -315,24 +315,20 @@
 /// Extracts system includes from a trusted driver by parsing the output of
 /// include search path and appends them to the commands coming from underlying
 /// compilation database.
-class QueryDriverDatabase : public DelegatingCDB {
+class SystemIncludeExtractor {
 public:
-  QueryDriverDatabase(llvm::ArrayRef QueryDriverGlobs,
-  std::unique_ptr Base)
-  : DelegatingCDB(std::move(Base)),
-QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)) {}
+  SystemIncludeExtractor(llvm::ArrayRef QueryDriverGlobs)
+  : QueryDriverRegex(convertGlobsToRegex(QueryDriverGlobs)) {}
 
-  llvm::Optional
-  getCompileCommand(PathRef File) const overrid

[PATCH] D133757: [clangd] Perform system include extraction inside CommandMangler

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added a comment.

I believe this addresses the remaining review comments. I will follow up with a 
patch to rename QueryDriverDatabase.{h,cpp} to SystemIncludeExtractor,{h,cpp}.




Comment at: clang-tools-extra/clangd/QueryDriverDatabase.cpp:318
 /// compilation database.
-class QueryDriverDatabase : public DelegatingCDB {
+class SystemIncludeExtractor : public CompileCommandsAdjuster {
 public:

sammccall wrote:
> nridge wrote:
> > sammccall wrote:
> > > this is renaming the class, but not the file, the flag, etc.
> > > The actual name aside, such a rename should probably be more complete and 
> > > a separate commit. If we keep the `--query-driver` flag we'll have at 
> > > least two names, so we have to weigh that against the betterness of the 
> > > name too.
> > > 
> > > (I agree that the current name is somewhat confusing. The new name is 
> > > somewhat inaccurate: we're extracting from a compiler rather than the 
> > > (operating?) system, and we extract more than includes. I prefer the new 
> > > one on balance but maybe `ToolchainFlagsExtractor` or something would be 
> > > even better...)
> > Mostly I wanted to drop the `Database` from `QueryDriverDatabase` because 
> > it was no longer a `GlobalCompilationDatabase`, and just `QueryDriver` 
> > didn't sound right (a verb, not a noun).
> > 
> > I do see the value in sticking to the terminology already used in the flag. 
> > If you're happy with the `CompileCommandsAdjuster` abstraction (and its 
> > name), we could make it `QueryDriverAdjuster`?
> > Mostly I wanted to drop the Database from QueryDriverDatabase
> 
> Yup, makes sense. We should drop it from the filename too, right? On 
> reflection renaming the class in this patch and the file in a subsequent one 
> also seems reasonable.
> 
> > If you're happy with the CompileCommandsAdjuster abstraction (and its 
> > name), we could make it QueryDriverAdjuster?
> 
> As mentioned on the other patch I'm not really happy with the Adjuster name, 
> too much trauma from tooling::ArgumentsAdjuster :-)
> Having thought about it more, I like `SystemIncludeExtractor` a lot, even if 
> it doesn't totally cover everything.
> 
> So I'd prefer either:
>  - best name: rename everything to `SystemIncludeExtractor` except the flag. 
> (i.e. this patch, with a followup commit renaming the file)
>  - most consistent: rename everything to `QueryDriver` - it's a verb, but 
> it's also a functor
> 
> up to you
> So I'd prefer either:
>  - best name: rename everything to `SystemIncludeExtractor` except the flag. 
> (i.e. this patch, with a followup commit renaming the file)
>  - most consistent: rename everything to `QueryDriver` - it's a verb, but 
> it's also a functor
> 
> up to you

I went with the first one.

A couple of minor deviations from what you suggested in [this 
comment](https://reviews.llvm.org/D133756#inline-1300154) are:

 1. I declared a typedef for the `unique_function` at namespace scope rather 
than inside `CommandMangler`, so that I can use it in the declaration of 
`getSystemIncludeExtractor()`
 2. I named the typedef `SystemIncludeExtractorFn` to avoid a conflict with the 
name of the actual implementing class

Let me know if you prefer some other choices here.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133757

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


[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Allowing us to test this feature (context: a recent crash in
semantic highlighting.)


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137063

Files:
  clang-tools-extra/clangd/tool/Check.cpp


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,11 @@
 }
   }
 
+  void buildSemanticHighlighting() {
+log("Building semantic highlighting");
+getSemanticHighlightings(*AST);
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +308,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting();
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,11 @@
 }
   }
 
+  void buildSemanticHighlighting() {
+log("Building semantic highlighting");
+getSemanticHighlightings(*AST);
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +308,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting();
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133756: [clangd] Pass the entire tooling::CompileCommand to CommandMangler

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/GlobalCompilationDatabase.h:165
+// process a file (possibly different from the one in the command).
+class CompileCommandsAdjuster {
+public:

sammccall wrote:
> nridge wrote:
> > sammccall wrote:
> > > nridge wrote:
> > > > nridge wrote:
> > > > > sammccall wrote:
> > > > > > I have a couple of concerns with this interface:
> > > > > >  - we seem to be stretching to cover {mangler, querydriver} with 
> > > > > > one interface, but there's no particular reason to - we never use 
> > > > > > it polymorphically.
> > > > > >  - the contract is very vague. If it's just "mutate flags" then 
> > > > > > some sort of generic `function` seems 
> > > > > > sufficient
> > > > > >  - `File` feels out-of-place - it's purely an input for the 
> > > > > > mangler. If query-driver needs an extra input, will we add that too?
> > > > > >  - either `CompileCommand` or filename+argv seems reasonable, 
> > > > > > providing CompileCommand+argv is confusing. 
> > > > > >  - the name is hard to distinguish from tooling::ArgumentsAdjuster 
> > > > > > (which is a bad interface)
> > > > > > 
> > > > > > The immediate problem being solved is the type of 
> > > > > > CommandMangler::SystemIncludeExtractor, right?
> > > > > > Can that just be `unique_function&, 
> > > > > > StringRef)>` or so? Possibly behind `using SystemIncludeExtractor = 
> > > > > > ...`.
> > > > > It's more that `QueryDriverDatabase` 
> > > > > [uses](https://searchfox.org/llvm/rev/f213128b292da85f68eeebbb68cba1541e1c39e2/clang-tools-extra/clangd/QueryDriverDatabase.cpp#354)
> > > > >  the `Directory` field of `tooling::CompileCommand` in addition to 
> > > > > the arguments.
> > > > > 
> > > > > We could add the directory as another argument to the function, but 
> > > > > at that point why not group the arguments into 
> > > > > `tooling::CompileCommand` which is more semantically meaningful?
> > > > > 
> > > > > As for polymorphism vs. `unique_function`, I don't feel strongly 
> > > > > about that, happy to change that up. (I do find `function` more 
> > > > > annoying to debug because `step into` at a call site in the debugger 
> > > > > steps into some hard-to-read library code, but that's probably better 
> > > > > solved at the debugger tooling level.)
> > > > Forgot to mention one other subtlety here: because 
> > > > `QueryDriverDatabase` needs to operate on a `tooling::CompileCommand`, 
> > > > the interface between `CommandMangler` and `OverlayCDB` needs to be 
> > > > widened to accommodate passing a `tooling::CompileCommand`, i.e. it 
> > > > can't be `ArgumentsAdjuster` any more.
> > > > 
> > > > This is why I reused `CompileCommandsAdjuster` as the type used to pass 
> > > > `CommandMangler` to `OverlayCDB`, and the type used to pass 
> > > > `SystemIncludeExtractor` to `CommandMangler`. It's not used 
> > > > //polymorphically//, we just need an interface that can accept a 
> > > > `CompileCommand` in both places; they could be two different types if 
> > > > we prefer.
> > > > It's more that QueryDriverDatabase uses the Directory field of 
> > > > tooling::CompileCommand in addition to the arguments.
> > > 
> > > Yes, that makes sense - my concern is providing **two** filenames the 
> > > query driver database, which needs none. The first one is semantically 
> > > clear and the function could potentially use it. The second one is 
> > > completely meaningless though.
> > > 
> > > > the interface between CommandMangler and OverlayCDB needs to be widened 
> > > > to accommodate passing a tooling::CompileCommand
> > > 
> > > Right. IIUC the reason we're using these abstract types (as opposed to 
> > > directly using CommandMangler and some concrete SystemIncludeExtractor) 
> > > is dependency injection: we don't want OverlayCDB to depend on 
> > > CommandMangler, or CommandMangler to depend on SystemIncludeExtractor.
> > > 
> > > For DI, I think we should specify these types independently where they're 
> > > consumed, i.e.
> > > ```
> > > class OverlayCDB {
> > >   using CommandMangler = unique_function > > NewFilename)>;
> > >   OverlayCDB(..., CommandMangler M = nullptr);
> > > }
> > > ```
> > > This avoids spurious dependencies in the *other* direction (e.g. 
> > > CommandMangler should not have to depend on OverlayCDB).
> > > We don't give readers the impression that mangler & extractor are 
> > > interchangeable somehow.
> > > And things needed by one (e.g if CommandMangler needs 6 more filename 
> > > params!) needn't affect the other.
> > > 
> > > (I violated all these ideas in reusing tooling::ArgumentsAdjuster here, 
> > > it was a mistake)
> > > 
> > > Ack on the debugger/stacktrace problems with type-erased functions 
> > > though, I wish I had a good answer.
> > > my concern is providing two filenames the query driver database, which 
> > > needs none
> > 
> > QueryDriverDatabase does in fact use "TargetFile", 
> > [here](https://se

[PATCH] D137064: [clangd] Fix a semantic-highlighting crash.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein created this revision.
hokein added a reviewer: kadircet.
Herald added a subscriber: arphaman.
Herald added a project: All.
hokein requested review of this revision.
Herald added subscribers: MaskRay, ilya-biryukov.
Herald added a project: clang-tools-extra.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137064

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -887,6 +887,17 @@
 $TemplateParameter[[T]] $Variable_def[[x]] = {};
 template <>
 int $Variable_def[[x]] = (int)sizeof($Class[[Base]]);
+  )cpp",
+  // no crash
+  R"cpp(
+struct $Class_def[[Foo]] {
+  void $Method_decl[[foo]]();
+};
+
+void $Function_def[[s]]($Class[[Foo]] $Parameter_def[[f]]) {
+  auto $LocalVariable_def[[k]] = &$Class[[Foo]]::$Method[[foo]];
+  ($Parameter[[f]].*$LocalVariable[[k]])(); // no crash on 
VisitCXXMemberCallExpr
+}
   )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -661,7 +661,7 @@
   }
 
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+if (isa_and_nonnull(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {
 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
   H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -887,6 +887,17 @@
 $TemplateParameter[[T]] $Variable_def[[x]] = {};
 template <>
 int $Variable_def[[x]] = (int)sizeof($Class[[Base]]);
+  )cpp",
+  // no crash
+  R"cpp(
+struct $Class_def[[Foo]] {
+  void $Method_decl[[foo]]();
+};
+
+void $Function_def[[s]]($Class[[Foo]] $Parameter_def[[f]]) {
+  auto $LocalVariable_def[[k]] = &$Class[[Foo]]::$Method[[foo]];
+  ($Parameter[[f]].*$LocalVariable[[k]])(); // no crash on VisitCXXMemberCallExpr
+}
   )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -661,7 +661,7 @@
   }
 
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+if (isa_and_nonnull(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {
 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
   H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D133757: [clangd] Perform system include extraction inside CommandMangler

2022-10-31 Thread Nathan Ridge via Phabricator via cfe-commits
nridge added inline comments.



Comment at: clang-tools-extra/clangd/test/system-include-extractor.test:82
+
+# Skip past the lack of diagnostics in the workspace and user config files...
+# CHECK2:   "method": "textDocument/publishDiagnostics",

Ugh, this doesn't quite work in that whether we get diagnostics for the 
**user** config file depends on whether it exists. It happens to on my system 
but presumably it may not on a buildbot?

Should I create a user config file in the lit test so it reliably exists (and 
delete it at the end)? Or is there some FileCheck magic I can employ that would 
ignore an optional second publishDiagnostics which is not the interesting one?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D133757

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


[PATCH] D135930: [X86] Add AVX-NE-CONVERT instructions.

2022-10-31 Thread Phoebe Wang via Phabricator via cfe-commits
pengfei added inline comments.



Comment at: clang/lib/Headers/avx512vlbf16intrin.h:164
+#define _mm_cvtneps_pbh(A) \
+  ((__m128bh)__builtin_ia32_vcvtneps2bf16128((__v4sf)(A)))
 

FreddyYe wrote:
> pengfei wrote:
> > pengfei wrote:
> > > RKSimon wrote:
> > > > Is there no way for __attribute__ to allow different attribute 
> > > > permutations?
> > > > 
> > > > Also, can we keep the __builtin_ia32_cvtneps2bf16_128 naming convention?
> > > > Is there no way for attribute to allow different attribute permutations?
> > > 
> > > We have discussed this problem with GCC folks. There are two problems 
> > > here:
> > > 1. Unlike builtins, function attributes are more generic. It may 
> > > introduce a lot of checks between callers and callees. I had a research 
> > > to limit it to `__always_inline__` functions only. However, Clang handles 
> > > inlining in middle-end, we don't have such information in the front-end. 
> > > Besides, we don't know how to merge different permutations if they are 
> > > inlining to the same function.
> > > 2. We don't know how to put the permutations into IR's function 
> > > attributes. We need to preserve all permutations for inlining reference, 
> > > but the backend needs a determine feature list rather than selective.
> > It's better to use `__builtin_ia32_cvtneps2bf16_128`.
> I think __builtin_ia32_vcvtneps2bf16128 is also a "right" name.
> 
> See __builtin_ia32_vfmaddsubph256, __builtin_ia32_minph256...
> 
> And I admit naming conventions of clang builtins as well as LLVM IR builtins 
> are confusing right now.
The problem here is `16128` is a bit confusing, a `_` breaks it into 2 number.
But I'm not insist on it :)


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

https://reviews.llvm.org/D135930

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


[PATCH] D136844: [libclang] Expose completion result kind in `CXCompletionResult`

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang/include/clang/Sema/CodeCompleteConsumer.h:755
-  /// Describes the kind of result generated.
-  enum ResultKind {
-/// Refers to a declaration.

egorzhdan wrote:
> kadircet wrote:
> > i don't follow the reason for replacing this struct with 
> > `CXCompletionResultKind` and renaming occurrences in half of the codebase. 
> > can we keep this around, introduce the new enum type into `Index.h` and 
> > have `clang/tools/libclang/CIndexCodeCompletion.cpp` do the conversion from 
> > Sema type to Index type instead?
> > 
> > Unless I am missing some other requirement for doing so. i feel like the 
> > conceptual dependency from Sema to Index is one we should get rid of, 
> > rather than make tighter.
> This was mostly done to be consistent with the way `CXCursorKind` and 
> `CXAvailabilityKind` are declared in `Index.h` and used as fields of 
> `CodeCompletionResult`. I think updating the enum name in a few source files 
> shouldn't be a major problem, but I can avoid it if you feel strongly against 
> this approach.
I completely agree with the consistency argument, but IMO the conceptual 
dependency from clang-sema to clang-cindex is just wrong.

cindex is mostly implemented by `libclang`, which is part of clang-tools. all 
of this works today because clang-sema is only using declarations visible in 
headers and doesn't properly depend on `libclang` in the build files.

Hence I believe rather than preserving consistency here, we should be moving 
towards breaking that dependency over time. Therefore I was opposing the idea 
of introducing another type usage that'll make this dependency more strong.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136844

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


[PATCH] D136071: [include-cleaner] WIP: Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 471936.
hokein marked 6 inline comments as done.
hokein added a comment.

address comments


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -8,6 +8,7 @@
 
 #include "clang-include-cleaner/Record.h"
 #include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
@@ -88,5 +89,60 @@
   EXPECT_THAT(Recorded.Roots, testing::ElementsAre(Named("x")));
 }
 
+class PragmaIncludeTest : public ::testing::Test {
+protected:
+  // We don't build an AST, we just run a preprocessor action!
+  TestInputs Inputs;
+  PragmaIncludes PI;
+
+  PragmaIncludeTest() {
+Inputs.MakeAction = [this] {
+  struct Hook : public PreprocessOnlyAction {
+  public:
+Hook(PragmaIncludes *Out) : Out(Out) {}
+bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+  Out->record(CI);
+  return true;
+}
+PragmaIncludes *Out;
+  };
+  return std::make_unique(&PI);
+};
+  }
+
+  TestAST build() { return TestAST(Inputs); }
+};
+
+TEST_F(PragmaIncludeTest, IWYUKeep) {
+  Inputs.Code = R"cpp(// Line 1
+#include "keep1.h" // IWYU pragma: keep
+#include "keep2.h" /* IWYU pragma: keep */
+  )cpp";
+  Inputs.ExtraFiles["keep1.h"] = Inputs.ExtraFiles["keep2.h"] = "";
+
+  TestAST Processed = build();
+  EXPECT_FALSE(PI.shouldKeep(1));
+  EXPECT_TRUE(PI.shouldKeep(2));
+  EXPECT_TRUE(PI.shouldKeep(3));
+}
+
+TEST_F(PragmaIncludeTest, IWYUPrivate) {
+  Inputs.Code = R"cpp(
+#include "public.h"
+  )cpp";
+  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "public.h"
+class Private {};
+  )cpp";
+  TestAST Processed = build();
+  auto PrivateFE = Processed.fileManager().getFile("private.h");
+  assert(PrivateFE);
+  EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public.h\"");
+  auto PublicFE = Processed.fileManager().getFile("public.h");
+  assert(PublicFE);
+  EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+}
+
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -11,9 +11,115 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 
 namespace clang::include_cleaner {
 
+// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
+// to share the code?
+static llvm::Optional parseIWYUPragma(const char *Text) {
+  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  Text += 2; // Skip the comment start, // or /*.
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
+class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler {
+public:
+  RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
+  : SM(CI.getSourceManager()), Out(Out) {}
+
+  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
+   SrcMgr::CharacteristicKind FileType,
+   FileID PrevFID) override {
+InMainFile = SM.isWrittenInMainFile(Loc);
+  }
+
+  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
+  llvm::StringRef FileName, bool IsAngled,
+  CharSourceRange /*FilenameRange*/,
+  Optional File,
+  llvm::StringRef /*SearchPath*/,
+  llvm::StringRef /*RelativePath*/,
+  const clang::Module * /*Imported*/,
+  SrcMgr::CharacteristicKind FileKind) override {
+if (!InMainFile)
+  return;
+int HashLine =
+SM.getLineNumber(SM.getMainFileID(), SM.getFileOffset(HashLoc));
+if (LastPragmaKeepInMainFileLine == HashLine)
+  Out->ShouldKeep.insert(

[PATCH] D136071: [include-cleaner] WIP: Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein added inline comments.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h:41
+// spelling header rather than the header directly defines the symbol.
+class PragmaIncludes {
+public:

kadircet wrote:
> i think this interface is OK, if we're planning to implement another adapter 
> on top of this class and use this only as a repository. Then have the adapter 
> provide a more convenient interface/data structures for types of queries 
> we'll have during `Location => Header` mapping inside include cleaner.
> 
> As those will most likely look like 
> `getHeaders(SourceLocation)/getHeaders(string)` -> `vector Signals>>`, without really caring about the details an implementation detail 
> being mapped to some other file, or getting exports of a certain header (as 
> discussed this is the piece that would require a little bit more detailed 
> design).
yeah, the plan is that this class is a low-level piece, only providing the data 
extracted from pragmas, and we will build another layer on top of this class 
(this is my next step).




Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h:54
+
+  class RecordPragma;
+

kadircet wrote:
> why do we need to expose this?
no needed, move it to private.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h:67
+  llvm::DenseMap
+  IWYUPrivate;
+

sammccall wrote:
> nit: naming a member after the keys rather than the values is confusing, 
> consider `IWYUPublic` or just `PublicMapping`?
rename to `IWYUPublic`.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

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


[PATCH] D135937: [WIP][X86] Support -march=raptorlake, meteorlake

2022-10-31 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe updated this revision to Diff 471938.
FreddyYe marked an inline comment as done.
FreddyYe added a comment.

Rebase.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D135937

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Basic/Targets/X86.cpp
  clang/test/CodeGen/attr-target-mv.c
  clang/test/CodeGen/target-builtin-noerror.c
  clang/test/Driver/x86-march.c
  clang/test/Misc/target-invalid-cpu-note.c
  clang/test/Preprocessor/predefined-arch-macros.c
  compiler-rt/lib/builtins/cpu_model.c
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/Support/X86TargetParser.def
  llvm/include/llvm/Support/X86TargetParser.h
  llvm/lib/Support/Host.cpp
  llvm/lib/Support/X86TargetParser.cpp
  llvm/lib/Target/X86/X86.td
  llvm/test/CodeGen/X86/cpus-intel.ll

Index: llvm/test/CodeGen/X86/cpus-intel.ll
===
--- llvm/test/CodeGen/X86/cpus-intel.ll
+++ llvm/test/CodeGen/X86/cpus-intel.ll
@@ -17,6 +17,8 @@
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=yonah 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=prescott 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=lakemont 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=raptorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=i686-unknown-unknown -mcpu=meteorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=nocona 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=core2 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
@@ -52,6 +54,8 @@
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=tremont 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=knl 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 ; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=knm 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=raptorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
+; RUN: llc < %s -o /dev/null -mtriple=x86_64-unknown-unknown -mcpu=meteorlake 2>&1 | FileCheck %s --check-prefix=CHECK-NO-ERROR --allow-empty
 
 define void @foo() {
   ret void
Index: llvm/lib/Target/X86/X86.td
===
--- llvm/lib/Target/X86/X86.td
+++ llvm/lib/Target/X86/X86.td
@@ -1499,6 +1499,10 @@
 ProcessorFeatures.SPRFeatures, ProcessorFeatures.SPRTuning>;
 def : ProcModel<"alderlake", AlderlakePModel,
 ProcessorFeatures.ADLFeatures, ProcessorFeatures.ADLTuning>;
+def : ProcModel<"raptorlake", AlderlakePModel,
+ProcessorFeatures.ADLFeatures, ProcessorFeatures.ADLTuning>;
+def : ProcModel<"meteorlake", AlderlakePModel,
+ProcessorFeatures.ADLFeatures, ProcessorFeatures.ADLTuning>;
 
 // AMD CPUs.
 
Index: llvm/lib/Support/X86TargetParser.cpp
===
--- llvm/lib/Support/X86TargetParser.cpp
+++ llvm/lib/Support/X86TargetParser.cpp
@@ -370,6 +370,10 @@
   { {"sapphirerapids"}, CK_SapphireRapids, FEATURE_AVX512BF16, FeaturesSapphireRapids },
   // Alderlake microarchitecture based processors.
   { {"alderlake"}, CK_Alderlake, FEATURE_AVX2, FeaturesAlderlake },
+  // Raptorlake microarchitecture based processors.
+  { {"raptorlake"}, CK_Raptorlake, FEATURE_AVX2, FeaturesAlderlake },
+  // Meteorlake microarchitecture based processors.
+  { {"meteorlake"}, CK_Meteorlake, FEATURE_AVX2, FeaturesAlderlake },
   // Knights Landing processor.
   { {"knl"}, CK_KNL, FEATURE_AVX512F, FeaturesKNL },
   // Knights Mill processor.
Index: llvm/lib/Support/Host.cpp
===
--- llvm/lib/Support/Host.cpp
+++ llvm/lib/Support/Host.cpp
@@ -820,6 +820,21 @@
   *Subtype = X86::INTEL_COREI7_ALDERLAKE;
   break;
 
+// Raptorlake:
+case 0xb7:
+  CPU = "raptorlake";
+  *Type = X86::INTEL_COREI7;
+  *Subtype = X86::INTEL_COREI7_RAPTORLAKE;
+  break;
+
+// Meteorlake:
+case 0xb5:
+case 0xaa:
+case 0xac:
+  CPU = "meteorlake";
+  *Type = X86::INTEL_COREI7;
+  *Subtype = X86::INTEL_COREI7_METEORLAKE;
+
 // Icelake Xeon:
 case 0x6a:
 case 0x6c:
Index: llvm/include/llvm/Support/X86TargetParser.h
===
--- llvm

[PATCH] D137056: [clangd] Fix a small inconsistency in system-include-extractor.test

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!




Comment at: clang-tools-extra/clangd/test/system-include-extractor.test:14-17
+# The purpose of the three lines below is to test that the -nostdinc etc.
+# arguments, all of which are present in the command in compile_commands.json
+# below, are passed on by clangd to the driver being queried (unlike most
+# other arguments).

nit:


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137056

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


[PATCH] D136951: [clangd] Populate ranges and symbol origin for paramname completions

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein accepted this revision.
hokein added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/CodeComplete.cpp:2019
+  // Point back to cursor location.
+  Offset += 2;
+  CompletionRange.start = offsetToPosition(ParseInput.Contents, Offset);

nit: I think  a comment `// skip /*` is clearer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136951

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


[PATCH] D137064: [clangd] Fix a semantic-highlighting crash.

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!




Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:664
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+if (isa_and_nonnull(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {

can you add a comment here saying `getMethodDecl can return nullptr with member 
pointers`.

(it's also quite surprising that this is the only place we're calling 
getMethodDecl in clangd, afaict).



Comment at: clang-tools-extra/clangd/SemanticHighlighting.cpp:664
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+if (isa_and_nonnull(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {

kadircet wrote:
> can you add a comment here saying `getMethodDecl can return nullptr with 
> member pointers`.
> 
> (it's also quite surprising that this is the only place we're calling 
> getMethodDecl in clangd, afaict).
nit: `isa_and_present` is the new alternative


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137064

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


[PATCH] D136846: [Driver] Add -fsample-profile-use-profi

2022-10-31 Thread Hans Wennborg via Phabricator via cfe-commits
hans added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1254
+HelpText<"Use profi to infer block and edge counts.">,
+DocBrief<[{Profi - a flow-based profile inference algorithm is an extended
+   and significantly re-engineered classic MCMF (min-cost max-flow)

I have to say, just reading this text I don't understand what it does.

I think a good description would start with "Infer block and edge counts " and 
then some kind of summary of how it does that.

I assume profile info is still needed for this (that's the input, right?) That 
should probably also be explained, and maybe we should warn when using 
-fsample-profile-use-profi without -fprofile-sample-use?


My main concern is that there's no documentation for this. How is a user 
supposed to learn about this feature and how it works? Why can't someone add 
something to 
https://clang.llvm.org/docs/UsersManual.html#profile-guided-optimization ? Once 
that is figured out, describing what the option does will probably be easy.



Comment at: clang/test/CodeGen/pgo-sample-use-profi.c:1
+//Test if profi flat is enabled in frontend as user-facing feature.
+//

This file should be under clang/test/Driver/ not CodeGen/ (since it's testing 
Driver functionality)

nit: There should typically be a space after the //



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136846

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


[PATCH] D136071: [include-cleaner] Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Sam McCall via Phabricator via cfe-commits
sammccall added inline comments.



Comment at: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h:41
+// spelling header rather than the header directly defines the symbol.
+class PragmaIncludes {
+public:

hokein wrote:
> kadircet wrote:
> > i think this interface is OK, if we're planning to implement another 
> > adapter on top of this class and use this only as a repository. Then have 
> > the adapter provide a more convenient interface/data structures for types 
> > of queries we'll have during `Location => Header` mapping inside include 
> > cleaner.
> > 
> > As those will most likely look like 
> > `getHeaders(SourceLocation)/getHeaders(string)` -> `vector > Signals>>`, without really caring about the details an implementation 
> > detail being mapped to some other file, or getting exports of a certain 
> > header (as discussed this is the piece that would require a little bit more 
> > detailed design).
> yeah, the plan is that this class is a low-level piece, only providing the 
> data extracted from pragmas, and we will build another layer on top of this 
> class (this is my next step).
> 
My suggestion would be to see what it looks like coding directly against this 
first - it might be fine, or it might make it obvious that making this class a 
little higher level is a better choice.
Trying to place an abstraction around this kind of "bits and pieces" 
information is easy to get wrong ime


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

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


[PATCH] D137067: [DebugInfo][Metadata] Make AllEnumTypes holding TrackingMDNodeRef

2022-10-31 Thread Kristina Bessonova via Phabricator via cfe-commits
krisb created this revision.
krisb added reviewers: ellis, aprantl, dblaikie.
Herald added a subscriber: hiraditya.
Herald added a project: All.
krisb requested review of this revision.
Herald added projects: clang, LLVM.
Herald added subscribers: llvm-commits, cfe-commits.

Having AllEnumtypes to be a vector of TrackingMDNodeRef makes it possible
to reflect changes in metadata in the vector if they took place before DIBuilder
being finalized.

Otherwise, we end up with heap-use-after-free because AllEnumTypes contains
metadata that no longer valid.

Consider a case where we have a class containing a definition of a enum,
so this enum has the class as a scope. For some reason (doesn't matter for
the current issue), we create a temporary debug metadata for this class, and
then resolve it while finalizing CGDebugInfo.

Once resolved the temporary, we may need to replace its uses with a new pointer.
If a temporary's user is unique (this is the enum mentioned above), we
may need re-uniqueing it, which may return a new pointer in a case of collision.
If so, the pointer we stored in AllEnumTypes vector become dangling.
Making AllEnumTypes hodling TrackingMDNodeRef should solve this problem
(see debug-info-enum-metadata-collision.cpp test for details).


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137067

Files:
  clang/test/CodeGenCXX/debug-info-enum-metadata-collision.cpp
  llvm/include/llvm/IR/DIBuilder.h
  llvm/lib/IR/DIBuilder.cpp


Index: llvm/lib/IR/DIBuilder.cpp
===
--- llvm/lib/IR/DIBuilder.cpp
+++ llvm/lib/IR/DIBuilder.cpp
@@ -84,7 +84,9 @@
   }
 
   if (!AllEnumTypes.empty())
-CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
+CUNode->replaceEnumTypes(MDTuple::get(
+VMContext, SmallVector(AllEnumTypes.begin(),
+   AllEnumTypes.end(;
 
   SmallVector RetainValues;
   // Declarations and definitions of the same type may be retained. Some
@@ -556,7 +558,7 @@
   getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 
0,
   IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, 
nullptr,
   nullptr, UniqueIdentifier);
-  AllEnumTypes.push_back(CTy);
+  AllEnumTypes.emplace_back(CTy);
   trackIfUnresolved(CTy);
   return CTy;
 }
Index: llvm/include/llvm/IR/DIBuilder.h
===
--- llvm/include/llvm/IR/DIBuilder.h
+++ llvm/include/llvm/IR/DIBuilder.h
@@ -48,7 +48,7 @@
 Function *LabelFn;   ///< llvm.dbg.label
 Function *AddrFn;///< llvm.dbg.addr
 
-SmallVector AllEnumTypes;
+SmallVector AllEnumTypes;
 /// Track the RetainTypes, since they can be updated later on.
 SmallVector AllRetainTypes;
 SmallVector AllSubprograms;
Index: clang/test/CodeGenCXX/debug-info-enum-metadata-collision.cpp
===
--- /dev/null
+++ clang/test/CodeGenCXX/debug-info-enum-metadata-collision.cpp
@@ -0,0 +1,30 @@
+// RUN: %clang_cc1 -triple %itanium_abi_triple -emit-llvm 
-debug-info-kind=constructor %s -o - | FileCheck %s
+
+// Test that clang doesn't crash while resolving temporary debug metadata of
+// a record with collisions in the record's enum users.
+
+// CHECK:  !DICompositeType(tag: DW_TAG_enumeration_type,
+// CHECK-SAME:  scope: [[SCOPE:![0-9]+]]
+// CHECK-SAME:  elements: [[ELEMENTS:![0-9]+]]
+// CHECK:  [[SCOPE]] = !DICompositeType(tag: DW_TAG_structure_type
+// CHECK-SAME:  name: "Struct1"
+// CHECK:  [[ELEMENTS]] = !{[[ELEMENT:![0-9]+]]}
+// CHECK:  [[ELEMENT]] = !DIEnumerator(name: "enumValue1"
+
+template  struct Struct1 {
+  enum { enumValue1 };
+  Struct1();
+};
+template  struct Struct2 {
+  void function1() { (void)Struct1::enumValue1; }
+};
+void function2() {
+  struct Struct3 {};
+  Struct2 variable1;
+  variable1.function1();
+}
+void function3() {
+  struct Struct3 {};
+  Struct2 variable1;
+  variable1.function1();
+}


Index: llvm/lib/IR/DIBuilder.cpp
===
--- llvm/lib/IR/DIBuilder.cpp
+++ llvm/lib/IR/DIBuilder.cpp
@@ -84,7 +84,9 @@
   }
 
   if (!AllEnumTypes.empty())
-CUNode->replaceEnumTypes(MDTuple::get(VMContext, AllEnumTypes));
+CUNode->replaceEnumTypes(MDTuple::get(
+VMContext, SmallVector(AllEnumTypes.begin(),
+   AllEnumTypes.end(;
 
   SmallVector RetainValues;
   // Declarations and definitions of the same type may be retained. Some
@@ -556,7 +558,7 @@
   getNonCompileUnitScope(Scope), UnderlyingType, SizeInBits, AlignInBits, 0,
   IsScoped ? DINode::FlagEnumClass : DINode::FlagZero, Elements, 0, nullptr,
   nullptr, UniqueIdentifier);
-  AllEnumTypes.push_back(CTy);
+  AllEnumTypes.emplace_back(CTy);
   trackIfUnresolved(CTy);

[clang-tools-extra] 1258747 - [clangd] Fix a semantic-highlighting crash.

2022-10-31 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-31T11:19:01+01:00
New Revision: 1258747a59db5200112fca7c6140d184f3b8748e

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

LOG: [clangd] Fix a semantic-highlighting crash.

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

Added: 


Modified: 
clang-tools-extra/clangd/SemanticHighlighting.cpp
clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/SemanticHighlighting.cpp 
b/clang-tools-extra/clangd/SemanticHighlighting.cpp
index 08cca2203667b..af3a3e6f8e941 100644
--- a/clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ b/clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -661,7 +661,9 @@ class CollectExtraHighlightings
   }
 
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+// getMethodDecl can return nullptr with member pointers, e.g.
+// `(foo.*pointer_to_member_fun)(arg);`
+if (isa_and_present(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {
 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
   H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),

diff  --git a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp 
b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
index 3666f1e5f21bc..9abc49bb06014 100644
--- a/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ b/clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -887,6 +887,17 @@ sizeof...($TemplateParameter[[Elements]]);
 $TemplateParameter[[T]] $Variable_def[[x]] = {};
 template <>
 int $Variable_def[[x]] = (int)sizeof($Class[[Base]]);
+  )cpp",
+  // no crash
+  R"cpp(
+struct $Class_def[[Foo]] {
+  void $Method_decl[[foo]]();
+};
+
+void $Function_def[[s]]($Class[[Foo]] $Parameter_def[[f]]) {
+  auto $LocalVariable_def[[k]] = &$Class[[Foo]]::$Method[[foo]];
+  ($Parameter[[f]].*$LocalVariable[[k]])(); // no crash on 
VisitCXXMemberCallExpr
+}
   )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.



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


[PATCH] D137064: [clangd] Fix a semantic-highlighting crash.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hokein marked 2 inline comments as done.
Closed by commit rG1258747a59db: [clangd] Fix a semantic-highlighting crash. 
(authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D137064?vs=471930&id=471947#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137064

Files:
  clang-tools-extra/clangd/SemanticHighlighting.cpp
  clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -887,6 +887,17 @@
 $TemplateParameter[[T]] $Variable_def[[x]] = {};
 template <>
 int $Variable_def[[x]] = (int)sizeof($Class[[Base]]);
+  )cpp",
+  // no crash
+  R"cpp(
+struct $Class_def[[Foo]] {
+  void $Method_decl[[foo]]();
+};
+
+void $Function_def[[s]]($Class[[Foo]] $Parameter_def[[f]]) {
+  auto $LocalVariable_def[[k]] = &$Class[[Foo]]::$Method[[foo]];
+  ($Parameter[[f]].*$LocalVariable[[k]])(); // no crash on 
VisitCXXMemberCallExpr
+}
   )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -661,7 +661,9 @@
   }
 
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+// getMethodDecl can return nullptr with member pointers, e.g.
+// `(foo.*pointer_to_member_fun)(arg);`
+if (isa_and_present(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {
 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
   H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),


Index: clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
===
--- clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
+++ clang-tools-extra/clangd/unittests/SemanticHighlightingTests.cpp
@@ -887,6 +887,17 @@
 $TemplateParameter[[T]] $Variable_def[[x]] = {};
 template <>
 int $Variable_def[[x]] = (int)sizeof($Class[[Base]]);
+  )cpp",
+  // no crash
+  R"cpp(
+struct $Class_def[[Foo]] {
+  void $Method_decl[[foo]]();
+};
+
+void $Function_def[[s]]($Class[[Foo]] $Parameter_def[[f]]) {
+  auto $LocalVariable_def[[k]] = &$Class[[Foo]]::$Method[[foo]];
+  ($Parameter[[f]].*$LocalVariable[[k]])(); // no crash on VisitCXXMemberCallExpr
+}
   )cpp"};
   for (const auto &TestCase : TestCases)
 // Mask off scope modifiers to keep the tests manageable.
Index: clang-tools-extra/clangd/SemanticHighlighting.cpp
===
--- clang-tools-extra/clangd/SemanticHighlighting.cpp
+++ clang-tools-extra/clangd/SemanticHighlighting.cpp
@@ -661,7 +661,9 @@
   }
 
   bool VisitCXXMemberCallExpr(CXXMemberCallExpr *CE) {
-if (isa(CE->getMethodDecl())) {
+// getMethodDecl can return nullptr with member pointers, e.g.
+// `(foo.*pointer_to_member_fun)(arg);`
+if (isa_and_present(CE->getMethodDecl())) {
   if (auto *ME = dyn_cast(CE->getCallee())) {
 if (auto *TI = ME->getMemberNameInfo().getNamedTypeInfo()) {
   H.addExtraModifier(TI->getTypeLoc().getBeginLoc(),
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/tool/Check.cpp:212
+log("Building semantic highlighting");
+getSemanticHighlightings(*AST);
+  }

can you also vlog the highlights, while limitting the output to ranges that 
intersect with the `LineRange` passed to `check`, when present.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137063

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


[clang-tools-extra] da5ded4 - [clangd] Populate ranges and symbol origin for paramname completions

2022-10-31 Thread Kadir Cetinkaya via cfe-commits

Author: Kadir Cetinkaya
Date: 2022-10-31T11:34:06+01:00
New Revision: da5ded4fc9d8c8edfd4a79fa0e75c2ac9165fa7b

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

LOG: [clangd] Populate ranges and symbol origin for paramname completions

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

Added: 


Modified: 
clang-tools-extra/clangd/CodeComplete.cpp
clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/CodeComplete.cpp 
b/clang-tools-extra/clangd/CodeComplete.cpp
index 5616f5e49dd2..5612fc599fb5 100644
--- a/clang-tools-extra/clangd/CodeComplete.cpp
+++ b/clang-tools-extra/clangd/CodeComplete.cpp
@@ -2014,14 +2014,23 @@ CodeCompleteResult codeCompleteComment(PathRef 
FileName, unsigned Offset,
 return CodeCompleteResult();
 
   CodeCompleteResult Result;
+  Range CompletionRange;
+  // Skip /*
+  Offset += 2;
+  CompletionRange.start = offsetToPosition(ParseInput.Contents, Offset);
+  CompletionRange.end =
+  offsetToPosition(ParseInput.Contents, Offset + Prefix.size());
+  Result.CompletionRange = CompletionRange;
   Result.Context = CodeCompletionContext::CCC_NaturalLanguage;
   for (llvm::StringRef Name : ParamNames) {
 if (!Name.startswith(Prefix))
   continue;
 CodeCompletion Item;
-Item.Name = Name.str() + "=";
+Item.Name = Name.str() + "=*/";
 Item.FilterText = Item.Name;
 Item.Kind = CompletionItemKind::Text;
+Item.CompletionTokenRange = CompletionRange;
+Item.Origin = SymbolOrigin::AST;
 Result.Completions.push_back(Item);
   }
 

diff  --git a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp 
b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
index 0166bea7d7e7..db700556e1d2 100644
--- a/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ b/clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -21,6 +21,7 @@
 #include "TestTU.h"
 #include "index/Index.h"
 #include "index/MemIndex.h"
+#include "index/SymbolOrigin.h"
 #include "support/Threading.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -29,6 +30,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "llvm/Testing/Support/Error.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
@@ -83,6 +85,9 @@ MATCHER(insertInclude, "") {
 MATCHER_P(snippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
 MATCHER_P(origin, OriginSet, "") { return arg.Origin == OriginSet; }
 MATCHER_P(signature, S, "") { return arg.Signature == S; }
+MATCHER_P(replacesRange, Range, "") {
+  return arg.CompletionTokenRange == Range;
+}
 
 // Shorthand for Contains(named(Name)).
 Matcher &> has(std::string Name) {
@@ -3713,7 +3718,6 @@ TEST(CompletionTest, PreambleCodeComplete) {
 }
 
 TEST(CompletionTest, CommentParamName) {
-  clangd::CodeCompleteOptions Opts;
   const std::string Code = R"cpp(
 void fun(int foo, int bar);
 void overloaded(int param_int);
@@ -3722,23 +3726,46 @@ TEST(CompletionTest, CommentParamName) {
 int main() {
   )cpp";
 
-  EXPECT_THAT(completions(Code + "fun(/*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(1, /*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("bar=")));
-  EXPECT_THAT(completions(Code + "/*^", {}, Opts).Completions, IsEmpty());
+  EXPECT_THAT(completions(Code + "fun(/*^").Completions,
+  UnorderedElementsAre(labeled("foo=*/")));
+  EXPECT_THAT(completions(Code + "fun(1, /*^").Completions,
+  UnorderedElementsAre(labeled("bar=*/")));
+  EXPECT_THAT(completions(Code + "/*^").Completions, IsEmpty());
   // Test de-duplication.
   EXPECT_THAT(
-  completions(Code + "overloaded(/*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("param_int="), labeled("param_char=")));
+  completions(Code + "overloaded(/*^").Completions,
+  UnorderedElementsAre(labeled("param_int=*/"), labeled("param_char=*/")));
   // Comment already has some text in it.
-  EXPECT_THAT(completions(Code + "fun(/*  ^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(/* f^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(/* x^", {}, Opts).Completions, 
IsEmpty());
-  EXPECT_THAT(completions(Code + "fun(/* f ^", {}, Opts).Completions,
-  IsEmpty());
+  EXPECT_THAT(completions(Code + "fun(/*  ^").Completions,
+  UnorderedElementsAre(labeled("foo=*/")));
+  EXPECT_THAT(completions(Code + "fun(/* f^").Completions,
+  Unord

[PATCH] D136951: [clangd] Populate ranges and symbol origin for paramname completions

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
kadircet marked an inline comment as done.
Closed by commit rGda5ded4fc9d8: [clangd] Populate ranges and symbol origin for 
paramname completions (authored by kadircet).

Changed prior to commit:
  https://reviews.llvm.org/D136951?vs=471544&id=471950#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136951

Files:
  clang-tools-extra/clangd/CodeComplete.cpp
  clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp

Index: clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
===
--- clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
+++ clang-tools-extra/clangd/unittests/CodeCompleteTests.cpp
@@ -21,6 +21,7 @@
 #include "TestTU.h"
 #include "index/Index.h"
 #include "index/MemIndex.h"
+#include "index/SymbolOrigin.h"
 #include "support/Threading.h"
 #include "clang/Sema/CodeCompleteConsumer.h"
 #include "clang/Tooling/CompilationDatabase.h"
@@ -29,6 +30,7 @@
 #include "llvm/Support/Path.h"
 #include "llvm/Testing/Support/Annotations.h"
 #include "llvm/Testing/Support/Error.h"
+#include "llvm/Testing/Support/SupportHelpers.h"
 #include "gmock/gmock.h"
 #include "gtest/gtest.h"
 #include 
@@ -83,6 +85,9 @@
 MATCHER_P(snippetSuffix, Text, "") { return arg.SnippetSuffix == Text; }
 MATCHER_P(origin, OriginSet, "") { return arg.Origin == OriginSet; }
 MATCHER_P(signature, S, "") { return arg.Signature == S; }
+MATCHER_P(replacesRange, Range, "") {
+  return arg.CompletionTokenRange == Range;
+}
 
 // Shorthand for Contains(named(Name)).
 Matcher &> has(std::string Name) {
@@ -3713,7 +3718,6 @@
 }
 
 TEST(CompletionTest, CommentParamName) {
-  clangd::CodeCompleteOptions Opts;
   const std::string Code = R"cpp(
 void fun(int foo, int bar);
 void overloaded(int param_int);
@@ -3722,23 +3726,46 @@
 int main() {
   )cpp";
 
-  EXPECT_THAT(completions(Code + "fun(/*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(1, /*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("bar=")));
-  EXPECT_THAT(completions(Code + "/*^", {}, Opts).Completions, IsEmpty());
+  EXPECT_THAT(completions(Code + "fun(/*^").Completions,
+  UnorderedElementsAre(labeled("foo=*/")));
+  EXPECT_THAT(completions(Code + "fun(1, /*^").Completions,
+  UnorderedElementsAre(labeled("bar=*/")));
+  EXPECT_THAT(completions(Code + "/*^").Completions, IsEmpty());
   // Test de-duplication.
   EXPECT_THAT(
-  completions(Code + "overloaded(/*^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("param_int="), labeled("param_char=")));
+  completions(Code + "overloaded(/*^").Completions,
+  UnorderedElementsAre(labeled("param_int=*/"), labeled("param_char=*/")));
   // Comment already has some text in it.
-  EXPECT_THAT(completions(Code + "fun(/*  ^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(/* f^", {}, Opts).Completions,
-  UnorderedElementsAre(labeled("foo=")));
-  EXPECT_THAT(completions(Code + "fun(/* x^", {}, Opts).Completions, IsEmpty());
-  EXPECT_THAT(completions(Code + "fun(/* f ^", {}, Opts).Completions,
-  IsEmpty());
+  EXPECT_THAT(completions(Code + "fun(/*  ^").Completions,
+  UnorderedElementsAre(labeled("foo=*/")));
+  EXPECT_THAT(completions(Code + "fun(/* f^").Completions,
+  UnorderedElementsAre(labeled("foo=*/")));
+  EXPECT_THAT(completions(Code + "fun(/* x^").Completions, IsEmpty());
+  EXPECT_THAT(completions(Code + "fun(/* f ^").Completions, IsEmpty());
+
+  // Test ranges
+  {
+std::string CompletionRangeTest(Code + "fun(/*[[^]]");
+auto Results = completions(CompletionRangeTest);
+EXPECT_THAT(Results.CompletionRange,
+llvm::ValueIs(Annotations(CompletionRangeTest).range()));
+EXPECT_THAT(
+Results.Completions,
+testing::Each(
+AllOf(replacesRange(Annotations(CompletionRangeTest).range()),
+  origin(SymbolOrigin::AST), kind(CompletionItemKind::Text;
+  }
+  {
+std::string CompletionRangeTest(Code + "fun(/*[[fo^]]");
+auto Results = completions(CompletionRangeTest);
+EXPECT_THAT(Results.CompletionRange,
+llvm::ValueIs(Annotations(CompletionRangeTest).range()));
+EXPECT_THAT(
+Results.Completions,
+testing::Each(
+AllOf(replacesRange(Annotations(CompletionRangeTest).range()),
+  origin(SymbolOrigin::AST), kind(CompletionItemKind::Text;
+  }
 }
 
 TEST(CompletionTest, Concepts) {
Index: clang-tools-extra/clangd/CodeComplete.cpp
===
--- clang-tools-extra/clangd/CodeComplete.cpp
+++ clang-tools-extra/clangd/CodeComplete.

[PATCH] D137054: [X86][Driver] Remove stale FIXME. NFC

2022-10-31 Thread Simon Pilgrim via Phabricator via cfe-commits
RKSimon accepted this revision.
RKSimon 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/D137054/new/

https://reviews.llvm.org/D137054

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


[PATCH] D123352: [analyzer] Add FixItHint to `nullability.NullReturnedFromNonnull` and `nullability.NullableReturnedFromNonnull`

2022-10-31 Thread Moshe via Phabricator via cfe-commits
MosheBerman abandoned this revision.
MosheBerman added a comment.

In the interest of not leaving detritus on the internet, I'm going to abandon 
this diff. I believe there's an alternate approach worth pursuing, with clang 
tidy. Thanks for your reviews and constructive feedback!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D123352

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


[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 471951.
hokein marked an inline comment as done.
hokein added a comment.

add line-range support


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137063

Files:
  clang-tools-extra/clangd/tool/Check.cpp


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,17 @@
 }
   }
 
+  void buildSemanticHighlighting(llvm::Optional LineRange) {
+log("Building semantic highlighting");
+auto Highlights = getSemanticHighlightings(*AST);
+if (LineRange) {
+  for (const auto HL : Highlights) {
+if (LineRange->contains(HL.R))
+  vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
+  }
+}
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +314,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting(LineRange);
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,17 @@
 }
   }
 
+  void buildSemanticHighlighting(llvm::Optional LineRange) {
+log("Building semantic highlighting");
+auto Highlights = getSemanticHighlightings(*AST);
+if (LineRange) {
+  for (const auto HL : Highlights) {
+if (LineRange->contains(HL.R))
+  vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
+  }
+}
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +314,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting(LineRange);
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

ChuanqiXu wrote:
> std modules should be irreverent with system headers; The intuition of the 
> wording should be that the users can't declare modules like `std` or 
> `std.compat` to avoid possible conflicting. The approach I imaged may be add 
> a new compilation flags (call it `-fstd-modules`) now. And if the compiler 
> found a `std` module declaration without `-fstd-modules`, emit an error.  
> 
> For now, I think we can skip the check for `-fstd-modules` and add it back 
> when we starts to support std modules actually.
The idea is that standard modules are built from system directories... it seems 
a better heuristic than adding a flag for the purpose of 1 diagnostics ( maybe 
some other system library could in theory export std with no warning, but I'm 
not super worried about that being a concern in practice)


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

https://reviews.llvm.org/D136953

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


[PATCH] D136071: [include-cleaner] Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks, LG from my side as well, just some small tweaks for tests.




Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:124
+  TestAST Processed = build();
+  EXPECT_FALSE(PI.shouldKeep(1));
+  EXPECT_TRUE(PI.shouldKeep(2));

it'd be better to test with an include-directive that doesn't have a keep 
pragma attached



Comment at: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp:135
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "public.h"
+class Private {};

it'd be better to map this to a header that isn't part of the TU, to make sure 
we don't rely on a file entry being around for a particular spelling.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

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


[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added a comment.
This revision is now accepted and ready to land.

thanks!




Comment at: clang-tools-extra/clangd/tool/Check.cpp:213
+auto Highlights = getSemanticHighlightings(*AST);
+if (LineRange) {
+  for (const auto HL : Highlights) {

we should print all the highlights when LineRange is missing. so maybe turn 
this into:
```
auto Highlights = ...
for(const auto HL : ..) {
  if(!LineRange || LineRange->contains(HL.R))
 vlog(...);
}
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137063

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


[clang] da4b929 - [clang][Interp] Reorder field destruction to avoid use after dtor

2022-10-31 Thread Benjamin Kramer via cfe-commits

Author: Benjamin Kramer
Date: 2022-10-31T12:20:10+01:00
New Revision: da4b929da79f4ce886f5612e3c84d29c1d2632f7

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

LOG: [clang][Interp] Reorder field destruction to avoid use after dtor

Found by msan -fsanitize-memory-use-after-dtor.

==8259==WARNING: MemorySanitizer: use-of-uninitialized-value
#0 0x55dbec54d2b8 in dtorRecord(clang::interp::Block*, char*, 
clang::interp::Descriptor*) clang/lib/AST/Interp/Descriptor.cpp:150:22
#1 0x55dbec54bfcf in dtorArrayDesc(clang::interp::Block*, char*, 
clang::interp::Descriptor*) clang/lib/AST/Interp/Descriptor.cpp:97:7
#2 0x55dbec508578 in invokeDtor clang/lib/AST/Interp/InterpBlock.h:79:7
#3 0x55dbec508578 in clang::interp::Program::~Program() 
clang/lib/AST/Interp/Program.h:55:19
#4 0x55dbec50657a in operator() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:55:5
#5 0x55dbec50657a in std::__msan::unique_ptr>::~unique_ptr() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:261:7
#6 0x55dbec5035a1 in clang::interp::Context::~Context() 
clang/lib/AST/Interp/Context.cpp:27:22
#7 0x55dbebec1daa in operator() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:55:5
#8 0x55dbebec1daa in std::__msan::unique_ptr>::~unique_ptr() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:261:7
#9 0x55dbebe285f9 in clang::ASTContext::~ASTContext() 
clang/lib/AST/ASTContext.cpp:1038:40
#10 0x55dbe941ff13 in llvm::RefCountedBase::Release() 
const llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:101:7
#11 0x55dbe94353ef in release 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:159:38
#12 0x55dbe94353ef in release 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:224:7
#13 0x55dbe94353ef in ~IntrusiveRefCntPtr 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:191:27
#14 0x55dbe94353ef in 
clang::CompilerInstance::setASTContext(clang::ASTContext*) 
clang/lib/Frontend/CompilerInstance.cpp:178:3
#15 0x55dbe95ad0ad in clang::FrontendAction::EndSourceFile() 
clang/lib/Frontend/FrontendAction.cpp:1100:8
#16 0x55dbe9445fcf in 
clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) 
clang/lib/Frontend/CompilerInstance.cpp:1047:11
#17 0x55dbe6b3afef in 
clang::ExecuteCompilerInvocation(clang::CompilerInstance*) 
clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:266:25
#18 0x55dbe6b13288 in cc1_main(llvm::ArrayRef, char const*, 
void*) clang/tools/driver/cc1_main.cpp:250:15
#19 0x55dbe6b0095f in ExecuteCC1Tool(llvm::SmallVectorImpl&) 
clang/tools/driver/driver.cpp:319:12
#20 0x55dbe6aff41c in clang_main(int, char**) 
clang/tools/driver/driver.cpp:395:12
#21 0x7f9be07fa632 in __libc_start_main
#22 0x55dbe6a702e9 in _start

  Member fields were destroyed
#0 0x55dbe6a7da5d in __sanitizer_dtor_callback_fields 
compiler-rt/lib/msan/msan_interceptors.cpp:949:5
#1 0x55dbec5094ac in ~SmallVectorImpl 
llvm/include/llvm/ADT/SmallVector.h:479:7
#2 0x55dbec5094ac in ~SmallVectorImpl 
llvm/include/llvm/ADT/SmallVector.h:612:3
#3 0x55dbec5094ac in llvm::SmallVector::~SmallVector() llvm/include/llvm/ADT/SmallVector.h:1207:3
#4 0x55dbec508e79 in clang::interp::Record::~Record() 
clang/lib/AST/Interp/Record.h:24:7
#5 0x55dbec508612 in clang::interp::Program::~Program() 
clang/lib/AST/Interp/Program.h:49:26
#6 0x55dbec50657a in operator() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:55:5
#7 0x55dbec50657a in std::__msan::unique_ptr>::~unique_ptr() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:261:7
#8 0x55dbec5035a1 in clang::interp::Context::~Context() 
clang/lib/AST/Interp/Context.cpp:27:22
#9 0x55dbebec1daa in operator() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:55:5
#10 0x55dbebec1daa in std::__msan::unique_ptr>::~unique_ptr() 
third_party/crosstool/v18/stable/toolchain/bin/../include/c++/v1/__memory/unique_ptr.h:261:7
#11 0x55dbebe285f9 in clang::ASTContext::~ASTContext() 
clang/lib/AST/ASTContext.cpp:1038:40
#12 0x55dbe941ff13 in llvm::RefCountedBase::Release() 
const llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:101:7
#13 0x55dbe94353ef in release 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:159:38
#14 0x55dbe94353ef in release 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:224:7
#15 0x55dbe94353ef in ~IntrusiveRefCntPtr 
llvm/include/llvm/ADT/IntrusiveRefCntPtr.h:191:27
#16 0x55dbe94353ef in 
clang::CompilerInstance::setASTContext(clang::ASTContext*) 
clang/lib/Frontend/CompilerInstance.cpp:178:3
#17 0x55dbe95ad0ad in clang::FrontendAction::EndSourceFile() 
clang/lib/Frontend/FrontendAction.cpp:1100:8
 

[PATCH] D137070: [clang][Interp] Support destructors

2022-10-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Try to use the existing cleanup machinery to implement calling destructors.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137070

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/test/AST/Interp/cxx20.cpp

Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -166,3 +166,93 @@
// ref-error {{must be initialized by a constant expression}}
 
 };
+
+namespace Destructors {
+
+  class Inc final {
+  public:
+int &I;
+constexpr Inc(int &I) : I(I) {}
+constexpr ~Inc() {
+  I++;
+}
+  };
+
+  class Dec final {
+  public:
+int &I;
+constexpr Dec(int &I) : I(I) {}
+constexpr ~Dec() {
+  I--;
+}
+  };
+
+
+
+  constexpr int m() {
+int i = 0;
+{
+  Inc f1(i);
+  Inc f2(i);
+  Inc f3(i);
+}
+return i;
+  }
+  static_assert(m() == 3, "");
+
+
+  constexpr int C() {
+int i = 0;
+
+while (i < 10) {
+  Inc inc(i);
+  continue;
+  Dec dec(i);
+}
+return i;
+  }
+  static_assert(C() == 10, "");
+
+
+  constexpr int D() {
+int i = 0;
+
+{
+  Inc i1(i);
+  {
+Inc i2(i);
+return i;
+  }
+}
+
+return i;
+  }
+  static_assert(D() == 0, "");
+
+  constexpr int E() {
+int i = 0;
+
+for(;;) {
+  Inc i1(i);
+  break;
+}
+return i;
+  }
+  static_assert(E() == 1, "");
+
+
+  /// FIXME: This should be rejected, since we call the destructor
+  ///   twice. However, GCC doesn't care either.
+  constexpr int ManualDtor() {
+int i = 0;
+{
+  Inc I(i); // ref-note {{destroying object 'I' whose lifetime has already ended}}
+  I.~Inc();
+}
+return i;
+  }
+  static_assert(ManualDtor() == 1, ""); // expected-error {{static assertion failed}} \
+// expected-note {{evaluates to '2 == 1'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'ManualDtor()'}}
+};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -375,6 +375,7 @@
   if (!BreakLabel)
 return false;
 
+  this->emitCleanup();
   return this->jump(*BreakLabel);
 }
 
@@ -383,6 +384,7 @@
   if (!ContinueLabel)
 return false;
 
+  this->emitCleanup();
   return this->jump(*ContinueLabel);
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -340,7 +340,7 @@
 public:
   LocalScope(ByteCodeExprGen *Ctx) : VariableScope(Ctx) {}
 
-  ~LocalScope() override { this->emitDestruction(); }
+  virtual ~LocalScope() override { this->emitDestruction(); }
 
   void addLocal(const Scope::Local &Local) override {
 if (!Idx) {
@@ -354,6 +354,29 @@
   void emitDestruction() override {
 if (!Idx)
   return;
+
+// Emit destructor calls for local variables of record
+// type with a destructor.
+for (Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
+  const Record *TypeRecord = Local.Desc->ElemRecord;
+  if (!TypeRecord)
+continue;
+
+  const auto *RDecl = dyn_cast(TypeRecord->getDecl());
+  if (!RDecl)
+continue;
+
+  if (const auto *DtorDecl = RDecl->getDestructor()) {
+const Function *Dtor = this->Ctx->getFunction(DtorDecl);
+if (Dtor && Dtor->isConstexpr()) {
+  assert(Dtor->hasThisPointer());
+  assert(Dtor->getNumParams() == 1);
+  // Emit destructor call.
+  this->Ctx->emitGetPtrLocal(Local.Offset, DtorDecl);
+  this->Ctx->emitCall(Dtor, DtorDecl);
+}
+  }
+}
 this->Ctx->emitDestroy(*Idx, SourceInfo{});
   }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -27,10 +27,12 @@
 namespace interp {
 
 /// Scope used to handle temporaries in toplevel variable declarations.
-template  class DeclScope final : public LocalScope {
+template  class DeclScope final : public VariableScope {
 public:
   DeclScope(ByteCodeExprGen *Ctx, const VarDecl *VD)
-  : LocalScope(Ctx), Scope(Ctx->P, VD) {}
+  : VariableScope(Ctx), Scope(Ctx->P, VD) {}
+
+  virtual ~DeclScop

[PATCH] D136080: [flang] Add -ffp-contract option processing

2022-10-31 Thread Tom Eccles via Phabricator via cfe-commits
tblah updated this revision to Diff 471958.
tblah added a comment.

I've updated the patch with @awarzynski's nit and an up-to-date context.

@kiranchandramohan please could you commit for me


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

https://reviews.llvm.org/D136080

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/LangOptions.def
  flang/include/flang/Frontend/LangOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/LangOptions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/flang_f_opts.f90
  flang/test/Driver/flang_fp_opts.f90
  flang/test/Driver/frontend-forwarding.f90

Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -8,6 +8,7 @@
 ! RUN: -fdefault-real-8 \
 ! RUN: -flarge-sizes \
 ! RUN: -fconvert=little-endian \
+! RUN: -ffp-contract=fast \
 ! RUN: -mllvm -print-before-all\
 ! RUN: -P \
 ! RUN:   | FileCheck %s
@@ -18,5 +19,6 @@
 ! CHECK: "-fdefault-integer-8"
 ! CHECK: "-fdefault-real-8"
 ! CHECK: "-flarge-sizes"
+! CHECK: "-ffp-contract=fast"
 ! CHECK: "-fconvert=little-endian"
 ! CHECK:  "-mllvm" "-print-before-all"
Index: flang/test/Driver/flang_fp_opts.f90
===
--- /dev/null
+++ flang/test/Driver/flang_fp_opts.f90
@@ -0,0 +1,4 @@
+! Test for handling of floating point options within the frontend driver
+
+! RUN: %flang_fc1 -ffp-contract=fast %s 2>&1 | FileCheck %s
+! CHECK: ffp-contract= is not currently implemented
Index: flang/test/Driver/flang_f_opts.f90
===
--- flang/test/Driver/flang_f_opts.f90
+++ flang/test/Driver/flang_f_opts.f90
@@ -1,8 +1,10 @@
 ! Test for warnings generated when parsing driver options. You can use this file for relatively small tests and to avoid creating
 ! new test files.
 
-! RUN: %flang -### -S -O4 %s 2>&1 | FileCheck %s
+! RUN: %flang -### -S -O4 -ffp-contract=on %s 2>&1 | FileCheck %s
 
+! CHECK: warning: the argument 'on' is not supported for option 'ffp-contract='. Mapping to 'ffp-contract=off'
 ! CHECK: warning: -O4 is equivalent to -O3
 ! CHECK-LABEL: "-fc1"
+! CHECK: -ffp-contract=off
 ! CHECK: -O3
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -31,6 +31,7 @@
 ! HELP-NEXT: -ffixed-form   Process source files in fixed form
 ! HELP-NEXT: -ffixed-line-length=
 ! HELP-NEXT: Use  as character line width in fixed mode
+! HELP-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! HELP-NEXT: -ffree-formProcess source files in free form
 ! HELP-NEXT: -fimplicit-noneNo implicit typing allowed unless overridden by IMPLICIT statements
 ! HELP-NEXT: -finput-charset= Specify the default character set for source files
@@ -105,6 +106,7 @@
 ! HELP-FC1-NEXT: -ffixed-form   Process source files in fixed form
 ! HELP-FC1-NEXT: -ffixed-line-length=
 ! HELP-FC1-NEXT: Use  as character line width in fixed mode
+! HELP-FC1-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! HELP-FC1-NEXT: -ffree-formProcess source files in free form
 ! HELP-FC1-NEXT: -fget-definition   
 ! HELP-FC1-NEXT:Get the symbol definition from   
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -31,6 +31,7 @@
 ! CHECK-NEXT: -ffixed-form   Process source files in fixed form
 ! CHECK-NEXT: -ffixed-line-length=
 ! CHECK-NEXT: Use  as character line width in fixed mode
+! CHECK-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! CHECK-NEXT: -ffree-formProcess source files in free form
 ! CHECK-NEXT: -fimplicit-noneNo implicit typing allowed unless overridden by IMPLICIT statements
 ! CHECK-NEXT: -finput-charset= Specify the default character set for source files
Index: flang/lib/Frontend/LangOptions.cpp
===
--- /dev/null
+++ flang/lib/Frontend/LangOptions.cpp
@@ -0,0 +1,24 @@
+//===-- LangOptions.cpp ---===//
+//
+// 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
+//
+//===--

[clang] a784de7 - [flang] Add -ffp-contract option processing

2022-10-31 Thread Kiran Chandramohan via cfe-commits

Author: Tom Eccles
Date: 2022-10-31T11:32:31Z
New Revision: a784de783af5096e593c5e214c2c78215fe303f5

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

LOG: [flang] Add -ffp-contract option processing

Only add the option processing and store the result. No attributes are
added to FIR yet.

Only the "off" and "fast" options are supported. "fast-honor-pragmas" is not 
applicable because we do not implement `#pragma clang fp contract()` in Fortran 
[1]. "on" is not supported because it is unclear how to fuse only within 
individual statements. gfortran also does not implement "on": treating it as an 
"off".

Currently the default value is "off" to preserve existing behavior. gfortran 
uses "fast" by default and that may be the right thing for flang-new after 
further discussion in the future, but that can be changed separately. 
gfortran's documentation is available [[ 
https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html | here ]].

[1] 
https://clang.llvm.org/docs/LanguageExtensions.html#extensions-to-specify-floating-point-flags

Reviewed By: vzakhari, awarzynski

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

Added: 
flang/include/flang/Frontend/LangOptions.def
flang/include/flang/Frontend/LangOptions.h
flang/lib/Frontend/LangOptions.cpp
flang/test/Driver/flang_fp_opts.f90

Modified: 
clang/include/clang/Basic/DiagnosticDriverKinds.td
clang/include/clang/Driver/Options.td
clang/lib/Driver/ToolChains/Flang.cpp
flang/include/flang/Frontend/CompilerInvocation.h
flang/lib/Frontend/CMakeLists.txt
flang/lib/Frontend/CompilerInvocation.cpp
flang/test/Driver/driver-help-hidden.f90
flang/test/Driver/driver-help.f90
flang/test/Driver/flang_f_opts.f90
flang/test/Driver/frontend-forwarding.f90

Removed: 




diff  --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index e477d93ba067f..44c277b3c3d8b 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -110,6 +110,9 @@ def 
warn_drv_unsupported_option_for_offload_arch_req_feature : Warning<
 def warn_drv_unsupported_option_for_target : Warning<
   "ignoring '%0' option as it is not currently supported for target '%1'">,
   InGroup;
+def warn_drv_unsupported_option_for_flang : Warning<
+  "the argument '%0' is not supported for option '%1'. Mapping to '%1%2'">,
+  InGroup;
 
 def err_drv_invalid_thread_model_for_target : Error<
   "invalid thread model '%0' in '%1' for this target">;

diff  --git a/clang/include/clang/Driver/Options.td 
b/clang/include/clang/Driver/Options.td
index 6d2c999873733..aa199e4608741 100644
--- a/clang/include/clang/Driver/Options.td
+++ b/clang/include/clang/Driver/Options.td
@@ -1919,12 +1919,14 @@ def fno_rounding_math : Flag<["-"], 
"fno-rounding-math">, Group, Flags<
 def ftrapping_math : Flag<["-"], "ftrapping-math">, Group;
 def fno_trapping_math : Flag<["-"], "fno-trapping-math">, Group;
 def ffp_contract : Joined<["-"], "ffp-contract=">, Group,
-  Flags<[CC1Option]>, HelpText<"Form fused FP ops (e.g. FMAs):"
+  Flags<[CC1Option, FC1Option, FlangOption]>,
+  DocBrief<"Form fused FP ops (e.g. FMAs):"
   " fast (fuses across statements disregarding pragmas)"
   " | on (only fuses in the same statement unless dictated by pragmas)"
   " | off (never fuses)"
   " | fast-honor-pragmas (fuses across statements unless diectated by 
pragmas)."
   " Default is 'fast' for CUDA, 'fast-honor-pragmas' for HIP, and 'on' 
otherwise.">,
+  HelpText<"Form fused FP ops (e.g. FMAs)">,
   Values<"fast,on,off,fast-honor-pragmas">;
 
 defm strict_float_cast_overflow : BoolFOption<"strict-float-cast-overflow",

diff  --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index 964f0e2617047..6c6895da61299 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -80,6 +80,31 @@ void Flang::AddPicOptions(const ArgList &Args, ArgStringList 
&CmdArgs) const {
   }
 }
 
+static void addFloatingPointOptions(const Driver &D, const ArgList &Args,
+ArgStringList &CmdArgs) {
+  StringRef FPContract;
+
+  if (const Arg *A = Args.getLastArg(options::OPT_ffp_contract)) {
+const StringRef Val = A->getValue();
+if (Val == "fast" || Val == "off") {
+  FPContract = Val;
+} else if (Val == "on") {
+  // Warn instead of error because users might have makefiles written for
+  // gfortran (which accepts -ffp-contract=on)
+  D.Diag(diag::warn_drv_unsupported_option_for_flang)
+  << Val << A->getOption().getName() << "off";
+  FPContract = "off";
+} else
+  // Clang's "fast-honor-pragmas" option is not suppo

[PATCH] D136080: [flang] Add -ffp-contract option processing

2022-10-31 Thread Kiran Chandramohan via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rGa784de783af5: [flang] Add -ffp-contract option processing 
(authored by tblah, committed by kiranchandramohan).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136080

Files:
  clang/include/clang/Basic/DiagnosticDriverKinds.td
  clang/include/clang/Driver/Options.td
  clang/lib/Driver/ToolChains/Flang.cpp
  flang/include/flang/Frontend/CompilerInvocation.h
  flang/include/flang/Frontend/LangOptions.def
  flang/include/flang/Frontend/LangOptions.h
  flang/lib/Frontend/CMakeLists.txt
  flang/lib/Frontend/CompilerInvocation.cpp
  flang/lib/Frontend/LangOptions.cpp
  flang/test/Driver/driver-help-hidden.f90
  flang/test/Driver/driver-help.f90
  flang/test/Driver/flang_f_opts.f90
  flang/test/Driver/flang_fp_opts.f90
  flang/test/Driver/frontend-forwarding.f90

Index: flang/test/Driver/frontend-forwarding.f90
===
--- flang/test/Driver/frontend-forwarding.f90
+++ flang/test/Driver/frontend-forwarding.f90
@@ -8,6 +8,7 @@
 ! RUN: -fdefault-real-8 \
 ! RUN: -flarge-sizes \
 ! RUN: -fconvert=little-endian \
+! RUN: -ffp-contract=fast \
 ! RUN: -mllvm -print-before-all\
 ! RUN: -P \
 ! RUN:   | FileCheck %s
@@ -18,5 +19,6 @@
 ! CHECK: "-fdefault-integer-8"
 ! CHECK: "-fdefault-real-8"
 ! CHECK: "-flarge-sizes"
+! CHECK: "-ffp-contract=fast"
 ! CHECK: "-fconvert=little-endian"
 ! CHECK:  "-mllvm" "-print-before-all"
Index: flang/test/Driver/flang_fp_opts.f90
===
--- /dev/null
+++ flang/test/Driver/flang_fp_opts.f90
@@ -0,0 +1,4 @@
+! Test for handling of floating point options within the frontend driver
+
+! RUN: %flang_fc1 -ffp-contract=fast %s 2>&1 | FileCheck %s
+! CHECK: ffp-contract= is not currently implemented
Index: flang/test/Driver/flang_f_opts.f90
===
--- flang/test/Driver/flang_f_opts.f90
+++ flang/test/Driver/flang_f_opts.f90
@@ -1,8 +1,10 @@
 ! Test for warnings generated when parsing driver options. You can use this file for relatively small tests and to avoid creating
 ! new test files.
 
-! RUN: %flang -### -S -O4 %s 2>&1 | FileCheck %s
+! RUN: %flang -### -S -O4 -ffp-contract=on %s 2>&1 | FileCheck %s
 
+! CHECK: warning: the argument 'on' is not supported for option 'ffp-contract='. Mapping to 'ffp-contract=off'
 ! CHECK: warning: -O4 is equivalent to -O3
 ! CHECK-LABEL: "-fc1"
+! CHECK: -ffp-contract=off
 ! CHECK: -O3
Index: flang/test/Driver/driver-help.f90
===
--- flang/test/Driver/driver-help.f90
+++ flang/test/Driver/driver-help.f90
@@ -31,6 +31,7 @@
 ! HELP-NEXT: -ffixed-form   Process source files in fixed form
 ! HELP-NEXT: -ffixed-line-length=
 ! HELP-NEXT: Use  as character line width in fixed mode
+! HELP-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! HELP-NEXT: -ffree-formProcess source files in free form
 ! HELP-NEXT: -fimplicit-noneNo implicit typing allowed unless overridden by IMPLICIT statements
 ! HELP-NEXT: -finput-charset= Specify the default character set for source files
@@ -105,6 +106,7 @@
 ! HELP-FC1-NEXT: -ffixed-form   Process source files in fixed form
 ! HELP-FC1-NEXT: -ffixed-line-length=
 ! HELP-FC1-NEXT: Use  as character line width in fixed mode
+! HELP-FC1-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! HELP-FC1-NEXT: -ffree-formProcess source files in free form
 ! HELP-FC1-NEXT: -fget-definition   
 ! HELP-FC1-NEXT:Get the symbol definition from   
Index: flang/test/Driver/driver-help-hidden.f90
===
--- flang/test/Driver/driver-help-hidden.f90
+++ flang/test/Driver/driver-help-hidden.f90
@@ -31,6 +31,7 @@
 ! CHECK-NEXT: -ffixed-form   Process source files in fixed form
 ! CHECK-NEXT: -ffixed-line-length=
 ! CHECK-NEXT: Use  as character line width in fixed mode
+! CHECK-NEXT: -ffp-contract= Form fused FP ops (e.g. FMAs)
 ! CHECK-NEXT: -ffree-formProcess source files in free form
 ! CHECK-NEXT: -fimplicit-noneNo implicit typing allowed unless overridden by IMPLICIT statements
 ! CHECK-NEXT: -finput-charset= Specify the default character set for source files
Index: flang/lib/Frontend/LangOptions.cpp
===
--- /dev/null
+++ flang/lib/Frontend/LangOptions.cpp
@@ -0,0 +1,24 @@
+//===-- LangOptions.cpp ---===//
+//
+// 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: 

[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2022-10-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, tahonermann, shafik.
Herald added a project: All.
tbaeder requested review of this revision.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137071

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -469,5 +469,129 @@
 return (a -= a);
   }
   static_assert(subAll(213) == 0, "");
+
+  constexpr bool BoolOr(bool b1, bool b2) {
+bool a;
+a = b1;
+a |= b2;
+return a;
+  }
+  static_assert(BoolOr(true, true), "");
+  static_assert(BoolOr(true, false), "");
+  static_assert(BoolOr(false, true), "");
+  static_assert(!BoolOr(false, false), "");
+
+  constexpr int IntOr(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r |= b;
+return r;
+  }
+  static_assert(IntOr(10, 1) == 11, "");
+  static_assert(IntOr(1337, -1) == -1, "");
+  static_assert(IntOr(0, 12) == 12, "");
+
+  constexpr bool BoolAnd(bool b1, bool b2) {
+bool a;
+a = b1;
+a &= b2;
+return a;
+  }
+  static_assert(BoolAnd(true, true), "");
+  static_assert(!BoolAnd(true, false), "");
+  static_assert(!BoolAnd(false, true), "");
+  static_assert(!BoolAnd(false, false), "");
+
+  constexpr int IntAnd(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r &= b;
+return r;
+  }
+  static_assert(IntAnd(10, 1) == 0, "");
+  static_assert(IntAnd(1337, -1) == 1337, "");
+  static_assert(IntAnd(0, 12) == 0, "");
+
+  constexpr bool BoolXor(bool b1, bool b2) {
+bool a;
+a = b1;
+a ^= b2;
+return a;
+  }
+  static_assert(!BoolXor(true, true), "");
+  static_assert(BoolXor(true, false), "");
+  static_assert(BoolXor(false, true), "");
+  static_assert(!BoolXor(false, false), "");
+
+  constexpr int IntXor(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r ^= b;
+return r;
+  }
+  static_assert(IntXor(10, 1) == 11, "");
+  static_assert(IntXor(10, 10) == 0, "");
+  static_assert(IntXor(12, true) == 13, "");
+
+  constexpr bool BoolRem(bool b1, bool b2) {
+bool a;
+a = b1;
+a %= b2;
+return a;
+  }
+  static_assert(!BoolRem(true, true), "");
+  static_assert(!BoolRem(false, true), "");
+
+  constexpr int IntRem(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r %= b;
+return r;
+  }
+  static_assert(IntRem(2, 2) == 0, "");
+  static_assert(IntRem(2, 1) == 0, "");
+  static_assert(IntRem(9, 7) == 2, "");
+
+  constexpr bool BoolDiv(bool b1, bool b2) {
+bool a;
+a = b1;
+a /= b2;
+return a;
+  }
+  static_assert(BoolDiv(true, true), "");
+  static_assert(!BoolDiv(false, true), "");
+
+  constexpr int IntDiv(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r /= b;
+return r;
+  }
+  static_assert(IntDiv(2, 2) == 1, "");
+  static_assert(IntDiv(12, 20) == 0, "");
+  static_assert(IntDiv(2, 1) == 2, "");
+  static_assert(IntDiv(9, 7) == 1, "");
+
+  constexpr bool BoolMul(bool b1, bool b2) {
+bool a;
+a = b1;
+a *= b2;
+return a;
+  }
+  static_assert(BoolMul(true, true), "");
+  static_assert(!BoolMul(true, false), "");
+  static_assert(!BoolMul(false, true), "");
+  static_assert(!BoolMul(false, false), "");
+
+  constexpr int IntMul(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r *= b;
+return r;
+  }
+  static_assert(IntMul(2, 2) == 4, "");
+  static_assert(IntMul(12, 20) == 240, "");
+  static_assert(IntMul(2, 1) == 2, "");
+  static_assert(IntMul(9, 7) == 63, "");
 };
 #endif
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -527,8 +527,8 @@
 const CompoundAssignOperator *E) {
   const Expr *LHS = E->getLHS();
   const Expr *RHS = E->getRHS();
-  Optional LT = classify(E->getLHS()->getType());
-  Optional RT = classify(E->getRHS()->getType());
+  Optional LT = classify(E->getComputationLHSType());
+  Optional RT = classify(E->getComputationResultType());
 
   if (!LT || !RT)
 return false;
@@ -554,10 +554,18 @@
 if (!this->emitSub(*LT, E))
   return false;
 break;
-
   case BO_MulAssign:
+if (!this->emitMul(*RT, E))
+  return false;
+break;
   case BO_DivAssign:
+if (!this->emitDiv(*RT, E))
+  return false;
+break;
   case BO_RemAssign:
+if (!this->emitRem(*RT, E))
+  return false;
+break;
   case BO_ShlAssign:
 if (!this->emitShl(*LT, *RT, E))
   return false;
@@ -567,8 +575,17 @@
   return false;
 break;
   case BO_AndAssign:
+if (!this->emitBitAnd(*RT, E))
+  return false;
+break;
   case BO_XorAssign:
+if (!this->emitBitXor(*RT, E))
+  

[PATCH] D137071: [clang][Interp] Implement missing compound assign operators

2022-10-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 471965.

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

https://reviews.llvm.org/D137071

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/test/AST/Interp/literals.cpp

Index: clang/test/AST/Interp/literals.cpp
===
--- clang/test/AST/Interp/literals.cpp
+++ clang/test/AST/Interp/literals.cpp
@@ -469,5 +469,129 @@
 return (a -= a);
   }
   static_assert(subAll(213) == 0, "");
+
+  constexpr bool BoolOr(bool b1, bool b2) {
+bool a;
+a = b1;
+a |= b2;
+return a;
+  }
+  static_assert(BoolOr(true, true), "");
+  static_assert(BoolOr(true, false), "");
+  static_assert(BoolOr(false, true), "");
+  static_assert(!BoolOr(false, false), "");
+
+  constexpr int IntOr(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r |= b;
+return r;
+  }
+  static_assert(IntOr(10, 1) == 11, "");
+  static_assert(IntOr(1337, -1) == -1, "");
+  static_assert(IntOr(0, 12) == 12, "");
+
+  constexpr bool BoolAnd(bool b1, bool b2) {
+bool a;
+a = b1;
+a &= b2;
+return a;
+  }
+  static_assert(BoolAnd(true, true), "");
+  static_assert(!BoolAnd(true, false), "");
+  static_assert(!BoolAnd(false, true), "");
+  static_assert(!BoolAnd(false, false), "");
+
+  constexpr int IntAnd(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r &= b;
+return r;
+  }
+  static_assert(IntAnd(10, 1) == 0, "");
+  static_assert(IntAnd(1337, -1) == 1337, "");
+  static_assert(IntAnd(0, 12) == 0, "");
+
+  constexpr bool BoolXor(bool b1, bool b2) {
+bool a;
+a = b1;
+a ^= b2;
+return a;
+  }
+  static_assert(!BoolXor(true, true), "");
+  static_assert(BoolXor(true, false), "");
+  static_assert(BoolXor(false, true), "");
+  static_assert(!BoolXor(false, false), "");
+
+  constexpr int IntXor(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r ^= b;
+return r;
+  }
+  static_assert(IntXor(10, 1) == 11, "");
+  static_assert(IntXor(10, 10) == 0, "");
+  static_assert(IntXor(12, true) == 13, "");
+
+  constexpr bool BoolRem(bool b1, bool b2) {
+bool a;
+a = b1;
+a %= b2;
+return a;
+  }
+  static_assert(!BoolRem(true, true), "");
+  static_assert(!BoolRem(false, true), "");
+
+  constexpr int IntRem(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r %= b;
+return r;
+  }
+  static_assert(IntRem(2, 2) == 0, "");
+  static_assert(IntRem(2, 1) == 0, "");
+  static_assert(IntRem(9, 7) == 2, "");
+
+  constexpr bool BoolDiv(bool b1, bool b2) {
+bool a;
+a = b1;
+a /= b2;
+return a;
+  }
+  static_assert(BoolDiv(true, true), "");
+  static_assert(!BoolDiv(false, true), "");
+
+  constexpr int IntDiv(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r /= b;
+return r;
+  }
+  static_assert(IntDiv(2, 2) == 1, "");
+  static_assert(IntDiv(12, 20) == 0, "");
+  static_assert(IntDiv(2, 1) == 2, "");
+  static_assert(IntDiv(9, 7) == 1, "");
+
+  constexpr bool BoolMul(bool b1, bool b2) {
+bool a;
+a = b1;
+a *= b2;
+return a;
+  }
+  static_assert(BoolMul(true, true), "");
+  static_assert(!BoolMul(true, false), "");
+  static_assert(!BoolMul(false, true), "");
+  static_assert(!BoolMul(false, false), "");
+
+  constexpr int IntMul(unsigned a, unsigned b) {
+unsigned r;
+r = a;
+r *= b;
+return r;
+  }
+  static_assert(IntMul(2, 2) == 4, "");
+  static_assert(IntMul(12, 20) == 240, "");
+  static_assert(IntMul(2, 1) == 2, "");
+  static_assert(IntMul(9, 7) == 63, "");
 };
 #endif
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -527,8 +527,8 @@
 const CompoundAssignOperator *E) {
   const Expr *LHS = E->getLHS();
   const Expr *RHS = E->getRHS();
-  Optional LT = classify(E->getLHS()->getType());
-  Optional RT = classify(E->getRHS()->getType());
+  Optional LT = classify(E->getComputationLHSType());
+  Optional RT = classify(E->getComputationResultType());
 
   if (!LT || !RT)
 return false;
@@ -554,10 +554,18 @@
 if (!this->emitSub(*LT, E))
   return false;
 break;
-
   case BO_MulAssign:
+if (!this->emitMul(*LT, E))
+  return false;
+break;
   case BO_DivAssign:
+if (!this->emitDiv(*LT, E))
+  return false;
+break;
   case BO_RemAssign:
+if (!this->emitRem(*LT, E))
+  return false;
+break;
   case BO_ShlAssign:
 if (!this->emitShl(*LT, *RT, E))
   return false;
@@ -567,8 +575,17 @@
   return false;
 break;
   case BO_AndAssign:
+if (!this->emitBitAnd(*LT, E))
+  return false;
+break;
   case BO_XorAssign:
+if (!this->emitBitXor(*LT, E))
+  return false;
+break;
   case BO_OrAssign:
+if (!this->emitBitOr(*LT, E))
+  return false;
+break;
   default:
 llvm_unreachable("Unimplemented compound 

[PATCH] D137073: [clang] Fix inline builtin functions of an __asm__ renamed function with symbol prefixes

2022-10-31 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo created this revision.
mstorsjo added reviewers: aaron.ballman, rnk.
Herald added a project: All.
mstorsjo requested review of this revision.
Herald added a project: clang.

If a function is renamed with `__asm__`, the name provided is the
exact symbol name, without any extra implicit symbol prefixes.
If the target does use symbol prefixes, the IR level symbol gets
an `\01` prefix to indicate that it's a literal symbol name to be
taken as is.

When a builtin function is specialized by providing an inline
version of it, that inline function is named `.inline`.

When the base function has been renamed due to `__asm__`, the inline
function ends up named `.inline`. Up to this point,
things did work as expected before.

However, for targets with symbol prefixes, one codepath that produced
the combined name `.inline` used the mangled `asmname` with
`\01` prefix, while others didn't. This patch fixes this.

This fixes the combination of asm renamed builtin function, with
inline override of the function, on any target with symbol
prefixes (such as i386 windows and any Darwin target).

Alternatively, instead of reimplementing this piece of logic
here, should it try to call MangleContext::mangleName somehow?


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137073

Files:
  clang/lib/CodeGen/CGExpr.cpp
  clang/test/CodeGen/inline-builtin-asm-name.c


Index: clang/test/CodeGen/inline-builtin-asm-name.c
===
--- /dev/null
+++ clang/test/CodeGen/inline-builtin-asm-name.c
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -o - %s 
-disable-llvm-optzns | FileCheck %s
+
+// CHECK: call i32 @"\01_asm_func_name.inline"
+
+// CHECK: declare dso_local i32 @"\01_asm_func_name"(ptr noundef, i32 noundef, 
ptr noundef, ptr noundef)
+
+// CHECK: define internal i32 @"\01_asm_func_name.inline"
+
+// CHECK: call i32 @__mingw_vsnprintf
+
+// CHECK: declare dso_local i32 @__mingw_vsnprintf
+
+typedef unsigned int size_t;
+
+int __mingw_vsnprintf(char *_DstBuf, size_t _MaxCount, const char *_Format, 
__builtin_va_list _ArgList);
+
+// For the real use case, "_asm_func_name" is actually "___mingw_vsnprintf", 
but it's renamed in the testcase for disambiguation.
+int vsnprintf(char *__stream, size_t __n, const char *__format, 
__builtin_va_list __local_argv) __asm__("_asm_func_name");
+
+extern __inline__ __attribute__((__always_inline__, __gnu_inline__))
+int vsnprintf(char *__stream, size_t __n, const char *__format, 
__builtin_va_list __local_argv)
+{
+  return __mingw_vsnprintf(__stream, __n, __format, __local_argv);
+}
+
+void call(const char* fmt, ...) {
+  char buf[200];
+  __builtin_va_list ap;
+  __builtin_va_start(ap, fmt);
+  vsnprintf(buf, sizeof(buf), fmt, ap);
+  __builtin_va_end(ap);
+}
Index: clang/lib/CodeGen/CGExpr.cpp
===
--- clang/lib/CodeGen/CGExpr.cpp
+++ clang/lib/CodeGen/CGExpr.cpp
@@ -5014,8 +5014,18 @@
 std::string NoBuiltinFD = ("no-builtin-" + FD->getName()).str();
 std::string NoBuiltins = "no-builtins";
 
-auto *A = FD->getAttr();
-StringRef Ident = A ? A->getLabel() : FD->getName();
+StringRef Ident = FD->getName();
+
+std::string AsmName;
+if (auto *A = FD->getAttr()) {
+  StringRef UserLabelPrefix =
+  CGF.getContext().getTargetInfo().getUserLabelPrefix();
+  if (!UserLabelPrefix.empty())
+AsmName += '\01'; // LLVM IR Marker for __asm("foo")
+  AsmName += A->getLabel();
+  Ident = AsmName;
+}
+
 std::string FDInlineName = (Ident + ".inline").str();
 
 bool IsPredefinedLibFunction =


Index: clang/test/CodeGen/inline-builtin-asm-name.c
===
--- /dev/null
+++ clang/test/CodeGen/inline-builtin-asm-name.c
@@ -0,0 +1,32 @@
+// RUN: %clang_cc1 -triple i686-windows-gnu -emit-llvm -o - %s -disable-llvm-optzns | FileCheck %s
+
+// CHECK: call i32 @"\01_asm_func_name.inline"
+
+// CHECK: declare dso_local i32 @"\01_asm_func_name"(ptr noundef, i32 noundef, ptr noundef, ptr noundef)
+
+// CHECK: define internal i32 @"\01_asm_func_name.inline"
+
+// CHECK: call i32 @__mingw_vsnprintf
+
+// CHECK: declare dso_local i32 @__mingw_vsnprintf
+
+typedef unsigned int size_t;
+
+int __mingw_vsnprintf(char *_DstBuf, size_t _MaxCount, const char *_Format, __builtin_va_list _ArgList);
+
+// For the real use case, "_asm_func_name" is actually "___mingw_vsnprintf", but it's renamed in the testcase for disambiguation.
+int vsnprintf(char *__stream, size_t __n, const char *__format, __builtin_va_list __local_argv) __asm__("_asm_func_name");
+
+extern __inline__ __attribute__((__always_inline__, __gnu_inline__))
+int vsnprintf(char *__stream, size_t __n, const char *__format, __builtin_va_list __local_argv)
+{
+  return __mingw_vsnprintf(__stream, __n, __format, __local_argv);
+}
+
+void call(const char* fmt, ...) {
+  char buf[2

[PATCH] D137070: [clang][Interp] Support destructors

2022-10-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder updated this revision to Diff 471971.

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

https://reviews.llvm.org/D137070

Files:
  clang/lib/AST/Interp/ByteCodeExprGen.cpp
  clang/lib/AST/Interp/ByteCodeExprGen.h
  clang/lib/AST/Interp/ByteCodeStmtGen.cpp
  clang/test/AST/Interp/cxx20.cpp

Index: clang/test/AST/Interp/cxx20.cpp
===
--- clang/test/AST/Interp/cxx20.cpp
+++ clang/test/AST/Interp/cxx20.cpp
@@ -166,3 +166,114 @@
// ref-error {{must be initialized by a constant expression}}
 
 };
+
+namespace Destructors {
+
+  class Inc final {
+  public:
+int &I;
+constexpr Inc(int &I) : I(I) {}
+constexpr ~Inc() {
+  I++;
+}
+  };
+
+  class Dec final {
+  public:
+int &I;
+constexpr Dec(int &I) : I(I) {}
+constexpr ~Dec() {
+  I--;
+}
+  };
+
+
+
+  constexpr int m() {
+int i = 0;
+{
+  Inc f1(i);
+  Inc f2(i);
+  Inc f3(i);
+}
+return i;
+  }
+  static_assert(m() == 3, "");
+
+
+  constexpr int C() {
+int i = 0;
+
+while (i < 10) {
+  Inc inc(i);
+  continue;
+  Dec dec(i);
+}
+return i;
+  }
+  static_assert(C() == 10, "");
+
+
+  constexpr int D() {
+int i = 0;
+
+{
+  Inc i1(i);
+  {
+Inc i2(i);
+return i;
+  }
+}
+
+return i;
+  }
+  static_assert(D() == 0, "");
+
+  constexpr int E() {
+int i = 0;
+
+for(;;) {
+  Inc i1(i);
+  break;
+}
+return i;
+  }
+  static_assert(E() == 1, "");
+
+
+  /// FIXME: This should be rejected, since we call the destructor
+  ///   twice. However, GCC doesn't care either.
+  constexpr int ManualDtor() {
+int i = 0;
+{
+  Inc I(i); // ref-note {{destroying object 'I' whose lifetime has already ended}}
+  I.~Inc();
+}
+return i;
+  }
+  static_assert(ManualDtor() == 1, ""); // expected-error {{static assertion failed}} \
+// expected-note {{evaluates to '2 == 1'}} \
+// ref-error {{not an integral constant expression}} \
+// ref-note {{in call to 'ManualDtor()'}}
+
+  constexpr void doInc(int &i) {
+Inc I(i);
+return;
+  }
+  constexpr int testInc() {
+int i = 0;
+doInc(i);
+return i;
+  }
+  static_assert(testInc() == 1, "");
+  constexpr void doInc2(int &i) {
+Inc I(i);
+// No return statement.
+  }
+   constexpr int testInc2() {
+int i = 0;
+doInc2(i);
+return i;
+  }
+  static_assert(testInc2() == 1, "");
+};
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -375,6 +375,7 @@
   if (!BreakLabel)
 return false;
 
+  this->emitCleanup();
   return this->jump(*BreakLabel);
 }
 
@@ -383,6 +384,7 @@
   if (!ContinueLabel)
 return false;
 
+  this->emitCleanup();
   return this->jump(*ContinueLabel);
 }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.h
===
--- clang/lib/AST/Interp/ByteCodeExprGen.h
+++ clang/lib/AST/Interp/ByteCodeExprGen.h
@@ -340,7 +340,7 @@
 public:
   LocalScope(ByteCodeExprGen *Ctx) : VariableScope(Ctx) {}
 
-  ~LocalScope() override { this->emitDestruction(); }
+  virtual ~LocalScope() override { this->emitDestruction(); }
 
   void addLocal(const Scope::Local &Local) override {
 if (!Idx) {
@@ -354,6 +354,29 @@
   void emitDestruction() override {
 if (!Idx)
   return;
+
+// Emit destructor calls for local variables of record
+// type with a destructor.
+for (Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
+  const Record *TypeRecord = Local.Desc->ElemRecord;
+  if (!TypeRecord)
+continue;
+
+  const auto *RDecl = dyn_cast(TypeRecord->getDecl());
+  if (!RDecl)
+continue;
+
+  if (const auto *DtorDecl = RDecl->getDestructor()) {
+const Function *Dtor = this->Ctx->getFunction(DtorDecl);
+if (Dtor && Dtor->isConstexpr()) {
+  assert(Dtor->hasThisPointer());
+  assert(Dtor->getNumParams() == 1);
+  // Emit destructor call.
+  this->Ctx->emitGetPtrLocal(Local.Offset, DtorDecl);
+  this->Ctx->emitCall(Dtor, DtorDecl);
+}
+  }
+}
 this->Ctx->emitDestroy(*Idx, SourceInfo{});
   }
 
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -27,10 +27,12 @@
 namespace interp {
 
 /// Scope used to handle temporaries in toplevel variable declarations.
-template  class DeclScope final : public LocalScope {
+template  class DeclScope final : public VariableScope {
 public:
   DeclScope(ByteCodeExprGen *

[PATCH] D137075: [clang-format] Fix document of AlignTrailingComments

2022-10-31 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki created this revision.
Herald added a project: All.
yusuke-kadowaki edited the summary of this revision.
yusuke-kadowaki added reviewers: MyDeveloperDay, HazardyKnusperkeks.
yusuke-kadowaki published this revision for review.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

The documentation of the patch https://reviews.llvm.org/D132131 looks 
disorganized on the website 
https://clang.llvm.org/docs/ClangFormatStyleOptions.html.
This patch tries to fix that.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137075

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -402,11 +402,11 @@
 
   /// Alignment options
   struct TrailingCommentsAlignmentStyle {
-/// Specifies the way to align trailing comments
+/// Specifies the way to align trailing comments.
 TrailingCommentsAlignmentKinds Kind;
-/// How many empty lines to apply alignment
-/// With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
-/// \code
+/// How many empty lines to apply alignment.
+/// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+/// it formats like below. \code
 ///   int a;  // all these
 ///
 ///   int ab; // comments are
@@ -414,8 +414,8 @@
 ///
 ///   int abcdef; // aligned
 /// \endcode
-/// And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
-/// \code
+/// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+/// to 1, it formats like below. \code
 ///   int a;  // these are
 ///
 ///   int ab; // aligned
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -865,7 +865,7 @@
   Alignment options
 
   * ``TrailingCommentsAlignmentKinds Kind``
-Specifies the way to align trailing comments
+Specifies the way to align trailing comments.
 
 Possible values:
 
@@ -903,8 +903,8 @@
 int abcd; // comment
 
 
-  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment
-With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment.
+When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2, it 
formats like below.
 
 .. code-block:: c++
 
@@ -914,8 +914,7 @@
 
 
   int abcdef; // aligned
-
-And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set to 
1, it formats like below.
 
 .. code-block:: c++
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -402,11 +402,11 @@
 
   /// Alignment options
   struct TrailingCommentsAlignmentStyle {
-/// Specifies the way to align trailing comments
+/// Specifies the way to align trailing comments.
 TrailingCommentsAlignmentKinds Kind;
-/// How many empty lines to apply alignment
-/// With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
-/// \code
+/// How many empty lines to apply alignment.
+/// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+/// it formats like below. \code
 ///   int a;  // all these
 ///
 ///   int ab; // comments are
@@ -414,8 +414,8 @@
 ///
 ///   int abcdef; // aligned
 /// \endcode
-/// And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
-/// \code
+/// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+/// to 1, it formats like below. \code
 ///   int a;  // these are
 ///
 ///   int ab; // aligned
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -865,7 +865,7 @@
   Alignment options
 
   * ``TrailingCommentsAlignmentKinds Kind``
-Specifies the way to align trailing comments
+Specifies the way to align trailing comments.
 
 Possible values:
 
@@ -903,8 +903,8 @@
 int abcd; // comment
 
 
-  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment
-With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment.
+When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2, it formats like below.
 
 .. code-block:: c++
 
@@ -914,8 +914,7 @@
 
 
   int abcdef; // aligned
-
-And w

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:452
 
+  if (auto *ND = dyn_cast_or_null(Context.getVaListTagDecl())) {
+if (auto *DC = ND->getLexicalDeclContext(); DC->isStdNamespace()) {

The API changed names recently.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

Is it valid to use a local variable as a `Scope` object? I would assume that 
scope goes away at the end of this compound statement? I didn't spot other 
cases where we did this -- usually we call `Parser::EnterScope()` which 
allocates a new `Scope` that `Sema` then uses.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

This looks like a benign typo -- we still match the line because FileCheck will 
match partial lines, but I'm pretty sure nothing in your patch would have 
necessitated this change. Then again, you make this change in a lot of tests, 
so maybe I'm wrong -- in which case, what changed?



Comment at: clang/test/AST/ast-dump-traits.cpp:55
 // CHECK-NEXT: | `-ExpressionTraitExpr {{.*}}  'bool' 
__is_lvalue_expr
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:30:6{{( 
imported)?}} test_unary_expr_or_type_trait 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

Typo?



Comment at: clang/test/AST/fixed_point.c:405
 
-//CHECK-NEXT: `-VarDecl {{.*}} literallast '_Accum' cinit
+//CHECK-NEXT:  -VarDecl {{.*}} literallast '_Accum' cinit
 //CHECK-NEXT:   `-FixedPointLiteral {{.*}} '_Accum' 1.0

Typo?



Comment at: clang/test/PCH/stmt-openmp_structured_block-bit.cpp:16
 // CHECK: TranslationUnitDecl 0x{{.*}} <> 
-// CHECK: `-FunctionDecl 0x{{.*}} 
<{{.*}}stmt-openmp_structured_block-bit.cpp:8:1, line:11:1> line:8:6 
{{(test|imported test)}} 'void ()'
+// CHECK:  -FunctionDecl 0x{{.*}} 
<{{.*}}stmt-openmp_structured_block-bit.cpp:8:1, line:11:1> line:8:6 
{{(test|imported test)}} 'void ()'
 // CHECK-NEXT:   `-CompoundStmt 0x{{.*}} 

Typo?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D137075: [clang-format] Fix document of AlignTrailingComments

2022-10-31 Thread Yusuke Kadowaki via Phabricator via cfe-commits
yusuke-kadowaki updated this revision to Diff 471977.
yusuke-kadowaki added a comment.

Add a blankline after the endcode to deal with the Buildbot error.
https://lab.llvm.org/buildbot/#/builders/92/builds/34906


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137075

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/include/clang/Format/Format.h


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -402,10 +402,11 @@
 
   /// Alignment options
   struct TrailingCommentsAlignmentStyle {
-/// Specifies the way to align trailing comments
+/// Specifies the way to align trailing comments.
 TrailingCommentsAlignmentKinds Kind;
-/// How many empty lines to apply alignment
-/// With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+/// How many empty lines to apply alignment.
+/// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+/// it formats like below.
 /// \code
 ///   int a;  // all these
 ///
@@ -414,7 +415,9 @@
 ///
 ///   int abcdef; // aligned
 /// \endcode
-/// And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+///
+/// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+/// to 1, it formats like below.
 /// \code
 ///   int a;  // these are
 ///
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -865,7 +865,7 @@
   Alignment options
 
   * ``TrailingCommentsAlignmentKinds Kind``
-Specifies the way to align trailing comments
+Specifies the way to align trailing comments.
 
 Possible values:
 
@@ -903,8 +903,9 @@
 int abcd; // comment
 
 
-  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment
-With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment.
+When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+it formats like below.
 
 .. code-block:: c++
 
@@ -915,7 +916,8 @@
 
   int abcdef; // aligned
 
-And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+to 1, it formats like below.
 
 .. code-block:: c++
 


Index: clang/include/clang/Format/Format.h
===
--- clang/include/clang/Format/Format.h
+++ clang/include/clang/Format/Format.h
@@ -402,10 +402,11 @@
 
   /// Alignment options
   struct TrailingCommentsAlignmentStyle {
-/// Specifies the way to align trailing comments
+/// Specifies the way to align trailing comments.
 TrailingCommentsAlignmentKinds Kind;
-/// How many empty lines to apply alignment
-/// With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+/// How many empty lines to apply alignment.
+/// When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+/// it formats like below.
 /// \code
 ///   int a;  // all these
 ///
@@ -414,7 +415,9 @@
 ///
 ///   int abcdef; // aligned
 /// \endcode
-/// And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+///
+/// When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+/// to 1, it formats like below.
 /// \code
 ///   int a;  // these are
 ///
Index: clang/docs/ClangFormatStyleOptions.rst
===
--- clang/docs/ClangFormatStyleOptions.rst
+++ clang/docs/ClangFormatStyleOptions.rst
@@ -865,7 +865,7 @@
   Alignment options
 
   * ``TrailingCommentsAlignmentKinds Kind``
-Specifies the way to align trailing comments
+Specifies the way to align trailing comments.
 
 Possible values:
 
@@ -903,8 +903,9 @@
 int abcd; // comment
 
 
-  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment
-With ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 2,
+  * ``unsigned OverEmptyLines`` How many empty lines to apply alignment.
+When both ``MaxEmptyLinesToKeep`` and ``OverEmptyLines`` are set to 2,
+it formats like below.
 
 .. code-block:: c++
 
@@ -915,7 +916,8 @@
 
   int abcdef; // aligned
 
-And with ``MaxEmptyLinesToKeep`` is 2 and ``OverEmptyLines`` is 1,
+When ``MaxEmptyLinesToKeep`` is set to 2 and ``OverEmptyLines`` is set
+to 1, it formats like below.
 
 .. code-block:: c++
 
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commi

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

aaron.ballman wrote:
> This looks like a benign typo -- we still match the line because FileCheck 
> will match partial lines, but I'm pretty sure nothing in your patch would 
> have necessitated this change. Then again, you make this change in a lot of 
> tests, so maybe I'm wrong -- in which case, what changed?
What is happening here (and in all the other such instances) is that on the 
`import` case, this declaration stops being the last one on the TU. So the 
beginning of the line would match on `|-` instead of ``-`, but the non-import 
case this remains the last one.

So I simply relaxed the match.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

aaron.ballman wrote:
> Is it valid to use a local variable as a `Scope` object? I would assume that 
> scope goes away at the end of this compound statement? I didn't spot other 
> cases where we did this -- usually we call `Parser::EnterScope()` which 
> allocates a new `Scope` that `Sema` then uses.
I don't see anything problematic about allocating it on the stack like this, 
implementation-wise.

I thought it would be a bit counter-intuitive to use parser functions here, 
since these declarations are entirely synthetic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D137077: [Diagnostic] Clarify -Winfinite-recursion message

2022-10-31 Thread Dani Ferreira Franco Moura via Phabricator via cfe-commits
merrymeerkat created this revision.
Herald added a project: All.
merrymeerkat requested review of this revision.
Herald added a project: clang.

Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D137077

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/test/SemaCXX/warn-infinite-recursion.cpp

Index: clang/test/SemaCXX/warn-infinite-recursion.cpp
===
--- clang/test/SemaCXX/warn-infinite-recursion.cpp
+++ clang/test/SemaCXX/warn-infinite-recursion.cpp
@@ -1,10 +1,10 @@
 // RUN: %clang_cc1 %s -fsyntax-only -verify -Winfinite-recursion
 
-void a() {  // expected-warning{{call itself}}
+void a() {  // expected-warning{{to understand recursion}}
   a();
 }
 
-void b(int x) {  // expected-warning{{call itself}}
+void b(int x) {  // expected-warning{{to understand recursion}}
   if (x)
 b(x);
   else
@@ -16,7 +16,7 @@
 c(5);
 }
 
-void d(int x) {  // expected-warning{{call itself}}
+void d(int x) {  // expected-warning{{to understand recursion}}
   if (x)
 ++x;
   return d(x);
@@ -29,7 +29,7 @@
 void e() { f(); }
 void f() { e(); }
 
-void g() {  // expected-warning{{call itself}}
+void g() {  // expected-warning{{to understand recursion}}
   while (true)
 g();
 
@@ -42,14 +42,14 @@
   }
 }
 
-void i(int x) {  // expected-warning{{call itself}}
+void i(int x) {  // expected-warning{{to understand recursion}}
   while (x < 5) {
 --x;
   }
   i(0);
 }
 
-int j() {  // expected-warning{{call itself}}
+int j() {  // expected-warning{{to understand recursion}}
   return 5 + j();
 }
 
@@ -80,11 +80,11 @@
   void b();
 };
 
-void S::a() {  // expected-warning{{call itself}}
+void S::a() {  // expected-warning{{to understand recursion}}
   return a();
 }
 
-void S::b() {  // expected-warning{{call itself}}
+void S::b() {  // expected-warning{{to understand recursion}}
   int i = 0;
   do {
 ++i;
@@ -95,8 +95,8 @@
 template
 struct T {
   member m;
-  void a() { return a(); }  // expected-warning{{call itself}}
-  static void b() { return b(); }  // expected-warning{{call itself}}
+  void a() { return a(); }  // expected-warning{{to understand recursion}}
+  static void b() { return b(); }  // expected-warning{{to understand recursion}}
 };
 
 void test_T() {
@@ -107,13 +107,13 @@
 
 class U {
   U* u;
-  void Fun() {  // expected-warning{{call itself}}
+  void Fun() {  // expected-warning{{to understand recursion}}
 u->Fun();
   }
 };
 
 // No warnings on templated functions
-// sum<0>() is instantiated, does recursively call itself, but never runs.
+// sum<0>() is instantiated, does recursively to understand recursion, but never runs.
 template 
 int sum() {
   return value + sum();
@@ -157,7 +157,7 @@
   return 0;
 return Wrapper::run();
   }
-  static int run2() {  // expected-warning{{call itself}}
+  static int run2() {  // expected-warning{{to understand recursion}}
 return run2();
   }
 };
@@ -194,7 +194,7 @@
 };
 
 Q q;
-Q &evaluated_recursive_function(int x) { // expected-warning{{call itself}}
+Q &evaluated_recursive_function(int x) { // expected-warning{{to understand recursion}}
   (void)typeid(evaluated_recursive_function(x)); // expected-warning {{expression with side effects will be evaluated despite being used as an operand to 'typeid'}}
   return q;
 }
Index: clang/include/clang/Basic/DiagnosticSemaKinds.td
===
--- clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -60,7 +60,7 @@
   "remove call to max function and unsigned zero argument">;
 
 def warn_infinite_recursive_function : Warning<
-  "all paths through this function will call itself">,
+  "in order to understand recursion, you must first understand recursion">,
   InGroup, DefaultIgnore;
 
 def warn_comma_operator : Warning<"possible misuse of comma operator here">,
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136554: Implement CWG2631

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added a comment.

Thank you for working on this!

> Immediate calls in default arguments and defaults members are not evaluated.

Er, I think this meant to say "are not evaluated immediately, unlike what the 
misnamed term of art would suggest." ;-)

> As a result of this patch, unused default member initializers are not 
> considered odr-used, ...

So this is a potentially breaking change because instantiations that used to 
happen might no longer happen. Do you have test coverage showing that break in 
behavior?




Comment at: clang/docs/ReleaseNotes.rst:507-508
   ``-std=gnu++14`` to their build settings to restore the previous behaviour.
+- Implemented DR2631. Invalid ``consteval`` calls in default arguments and 
default
+  member initializers are diagnosed when and if the default is used.
 

Should this be listed as a potentially breaking change as this now 1) 
potentially changes the value people were getting for 
`source_location::current()` as a default argument, and 2) potentially causes 
instantiation differences due to the change in ODR use?



Comment at: clang/include/clang/AST/ExprCXX.h:1307-1315
+  const Expr *getRewrittenExpr() const {
+return hasRewrittenInit() ? *getTrailingObjects() : nullptr;
+  }
+  Expr *getRewrittenExpr() {
+return hasRewrittenInit() ? *getTrailingObjects() : nullptr;
+  }
+

Comments on these methods would be appreciated, otherwise we don't know what 
kind of adjustments you're talking about.



Comment at: clang/include/clang/AST/ExprCXX.h:1396-1404
+  const Expr *getExpr() const;
+  Expr *getExpr();
+
+  const Expr *getRewrittenExpr() const {
+return hasRewrittenInit() ? *getTrailingObjects() : nullptr;
   }
+

Comments here would also be appreciated.



Comment at: clang/include/clang/Sema/Sema.h:1336
+// When evaluating immediate functions in the initializer of a default
+// parameter or default member initializer, this is is the declaration 
whose
+// default initializer is being evaluated and the location of the call





Comment at: clang/include/clang/Sema/Sema.h:9618
+
+  ExpressionEvaluationContextRecord::InitializationContext
+  InnermostDeclarationWithDelayedImmediateInvocations() const {

Rather than go with `isValid()` on this class type, why not have this function 
return an `Optional` instead (so `InitializationContext` can always be assumed 
to be valid)?



Comment at: clang/include/clang/Sema/Sema.h:9633
+
+  ExpressionEvaluationContextRecord::InitializationContext
+  OutermostDeclarationWithDelayedImmediateInvocations() const {

Same here as above.



Comment at: clang/lib/AST/ExprCXX.cpp:981-982
+const Expr *CXXDefaultArgExpr::getAdjustedRewrittenExpr() const {
+  if (!hasRewrittenInit())
+return nullptr;
+  const Expr *Init = getRewrittenExpr();

Should this be an assert instead?



Comment at: clang/lib/AST/ExprCXX.cpp:985
+
+  if (auto *E = dyn_cast_or_null(Init))
+if (!isa(E))





Comment at: clang/lib/AST/ExprCXX.cpp:992-993
+Expr *CXXDefaultArgExpr::getAdjustedRewrittenExpr() {
+  if (!hasRewrittenInit())
+return nullptr;
+  Expr *Init = getRewrittenExpr();

Same here as above?



Comment at: clang/lib/AST/ExprCXX.cpp:995
+  Expr *Init = getRewrittenExpr();
+  if (auto *E = dyn_cast_or_null(Init))
+if (!isa(E))





Comment at: clang/lib/AST/ExprCXX.cpp:1013-1015
+  if (CXXDefaultInitExprBits.HasRewrittenInit) {
+*getTrailingObjects() = RewrittenInitExpr;
+  }





Comment at: clang/lib/Parse/ParseDeclCXX.cpp:3188
+  Actions,
+  isa_and_nonnull(D)
+  ? Sema::ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed





Comment at: clang/lib/Sema/SemaExpr.cpp:5895
   // blocks in default argument expression can never capture anything.
-  if (auto Init = dyn_cast(Param->getInit())) {
+  if (auto InitWithCleanup = dyn_cast(Init)) {
 // Set the "needs cleanups" bit regardless of whether there are





Comment at: clang/lib/Sema/SemaExpr.cpp:5909
+  SkipImmediateInvocations;
+  MarkDeclarationsReferencedInExpr(Init, true);
   return false;





Comment at: clang/lib/Sema/SemaExpr.cpp:5916-5919
+if (const FunctionDecl *FD =
+dyn_cast_or_null(E->getCalleeDecl())) {
+  HasImmediateCalls |= FD->isConsteval();
+}





Comment at: clang/lib/Sema/SemaExpr.cpp:5971-5973
+  if (!Init && !Param->hasUnparsedDefaultArg()) {
+
+// Mark that we are replacing a default argument first.





Comment at: clang/lib/Sema/SemaExpr.cpp:597

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

mizvekov wrote:
> aaron.ballman wrote:
> > This looks like a benign typo -- we still match the line because FileCheck 
> > will match partial lines, but I'm pretty sure nothing in your patch would 
> > have necessitated this change. Then again, you make this change in a lot of 
> > tests, so maybe I'm wrong -- in which case, what changed?
> What is happening here (and in all the other such instances) is that on the 
> `import` case, this declaration stops being the last one on the TU. So the 
> beginning of the line would match on `|-` instead of ``-`, but the non-import 
> case this remains the last one.
> 
> So I simply relaxed the match.
Hmmm, I think it'd help to show what new lines are now showing up so we can 
validate that they make sense in context. WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:347
   Fixes `Issue 57562 `_.
+- Clang now diagnoses use of invalid or reserved module names. Both are
+  diagnosed as an error, but the diagnostic is suppressed for use of reserved

So question: ARE we diagnosing all 'use' of invalid/reserved module names?  So 
the idea is you cannot import:
`std.concepts`?  Or are we diagnosing `export` only?


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

https://reviews.llvm.org/D136953

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


[clang] 22914a8 - [NFC] Use isa<...> to replace isa<>||isa<> in clang/Serialization

2022-10-31 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2022-10-31T21:17:03+08:00
New Revision: 22914a82299dc45d4e5a3ec6c50808c97e6e6a10

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

LOG: [NFC] Use isa<...> to replace isa<>||isa<>  in clang/Serialization

Now isa supports the variant args, which could simplify the codes
further. This patch simplify the uses in clang/Serialization

Added: 


Modified: 
clang/lib/Serialization/ASTCommon.cpp
clang/lib/Serialization/ASTReader.cpp
clang/lib/Serialization/ASTReaderDecl.cpp
clang/lib/Serialization/ASTWriter.cpp
clang/lib/Serialization/ASTWriterDecl.cpp

Removed: 




diff  --git a/clang/lib/Serialization/ASTCommon.cpp 
b/clang/lib/Serialization/ASTCommon.cpp
index 152037dfc9269..62ae1e74ece8b 100644
--- a/clang/lib/Serialization/ASTCommon.cpp
+++ b/clang/lib/Serialization/ASTCommon.cpp
@@ -474,7 +474,7 @@ bool serialization::needsAnonymousDeclarationNumber(const 
NamedDecl *D) {
 if (auto *VD = dyn_cast(D))
   return VD->isStaticLocal();
 // FIXME: What about CapturedDecls (and declarations nested within them)?
-return isa(D) || isa(D);
+return isa(D);
   }
 
   // Otherwise, we only care about anonymous class members / block-scope decls.
@@ -484,5 +484,5 @@ bool serialization::needsAnonymousDeclarationNumber(const 
NamedDecl *D) {
 return false;
   if (!isa(D->getLexicalDeclContext()))
 return false;
-  return isa(D) || isa(D);
+  return isa(D);
 }

diff  --git a/clang/lib/Serialization/ASTReader.cpp 
b/clang/lib/Serialization/ASTReader.cpp
index d1132032c71fc..27ae748222553 100644
--- a/clang/lib/Serialization/ASTReader.cpp
+++ b/clang/lib/Serialization/ASTReader.cpp
@@ -7229,8 +7229,7 @@ void ASTReader::CompleteRedeclChain(const Decl *D) {
   //
   // FIXME: Merging a function definition should merge
   // all mergeable entities within it.
-  if (isa(DC) || isa(DC) ||
-  isa(DC) || isa(DC)) {
+  if (isa(DC)) {
 if (DeclarationName Name = cast(D)->getDeclName()) {
   if (!getContext().getLangOpts().CPlusPlus &&
   isa(DC)) {

diff  --git a/clang/lib/Serialization/ASTReaderDecl.cpp 
b/clang/lib/Serialization/ASTReaderDecl.cpp
index cabf06dcee7da..1fa8fa0f72e47 100644
--- a/clang/lib/Serialization/ASTReaderDecl.cpp
+++ b/clang/lib/Serialization/ASTReaderDecl.cpp
@@ -567,7 +567,7 @@ void ASTDeclReader::Visit(Decl *D) {
 
 void ASTDeclReader::VisitDecl(Decl *D) {
   if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
-  isa(D) || isa(D)) {
+  isa(D)) {
 // We don't want to deserialize the DeclContext of a template
 // parameter or of a parameter of a function template immediately.   These
 // entities might be used in the formulation of its DeclContext (for
@@ -3021,16 +3021,11 @@ static bool isConsumerInterestedIn(ASTContext &Ctx, 
Decl *D, bool HasBody) {
   return false;
   }
 
-  if (isa(D) ||
-  isa(D) ||
-  isa(D) ||
-  isa(D) ||
-  isa(D) ||
-  isa(D))
+  if (isa(D))
 return true;
-  if (isa(D) || isa(D) ||
-  isa(D) || isa(D) ||
-  isa(D))
+  if (isa(D))
 return !D->getDeclContext()->isFunctionOrMethod();
   if (const auto *Var = dyn_cast(D))
 return Var->isFileVarDecl() &&
@@ -4049,7 +4044,7 @@ void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord 
&Record) {
   }
   // Add the lazy specializations to the template.
   assert((PendingLazySpecializationIDs.empty() || isa(D) ||
-  isa(D) || isa(D)) &&
+  isa(D)) &&
  "Must not have pending specializations");
   if (auto *CTD = dyn_cast(D))
 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);

diff  --git a/clang/lib/Serialization/ASTWriter.cpp 
b/clang/lib/Serialization/ASTWriter.cpp
index b70eb9526e19b..c2a586426a935 100644
--- a/clang/lib/Serialization/ASTWriter.cpp
+++ b/clang/lib/Serialization/ASTWriter.cpp
@@ -5471,7 +5471,7 @@ void ASTWriter::associateDeclWithFile(const Decl *D, 
DeclID ID) {
   // a function/objc method, should not have TU as lexical context.
   // TemplateTemplateParmDecls that are part of an alias template, should not
   // have TU as lexical context.
-  if (isa(D) || isa(D))
+  if (isa(D))
 return;
 
   SourceManager &SM = Context->getSourceManager();

diff  --git a/clang/lib/Serialization/ASTWriterDecl.cpp 
b/clang/lib/Serialization/ASTWriterDecl.cpp
index 93785eeb9e880..e6c09cf5d7f4f 100644
--- a/clang/lib/Serialization/ASTWriterDecl.cpp
+++ b/clang/lib/Serialization/ASTWriterDecl.cpp
@@ -2417,7 +2417,7 @@ static bool isRequiredDecl(const Decl *D, ASTContext 
&Context,
 
   // File scoped assembly or obj-c or OMP declare target implementation must be
   // seen.
-  if (isa(D) || isa(D))
+  if (isa(D))
 return true;
 
   if (WritingModule && isPartOfPerModuleInitializer(D)) {


   

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

mizvekov wrote:
> aaron.ballman wrote:
> > Is it valid to use a local variable as a `Scope` object? I would assume 
> > that scope goes away at the end of this compound statement? I didn't spot 
> > other cases where we did this -- usually we call `Parser::EnterScope()` 
> > which allocates a new `Scope` that `Sema` then uses.
> I don't see anything problematic about allocating it on the stack like this, 
> implementation-wise.
> 
> I thought it would be a bit counter-intuitive to use parser functions here, 
> since these declarations are entirely synthetic.
I dont know much about "Scope", as it is particularly used in Parsing, but I DO 
see the comment says: "A scope is a transient data structure that is used while 
parsing the program.  It assists with resolving identifiers to the appropriate 
declaration."

Which means to me it doesn't need to out-live its parsing time.  I THINK it 
gets replaced with a CXXScope at one point, but I dont know when/where that 
happens.



Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

aaron.ballman wrote:
> mizvekov wrote:
> > aaron.ballman wrote:
> > > This looks like a benign typo -- we still match the line because 
> > > FileCheck will match partial lines, but I'm pretty sure nothing in your 
> > > patch would have necessitated this change. Then again, you make this 
> > > change in a lot of tests, so maybe I'm wrong -- in which case, what 
> > > changed?
> > What is happening here (and in all the other such instances) is that on the 
> > `import` case, this declaration stops being the last one on the TU. So the 
> > beginning of the line would match on `|-` instead of ``-`, but the 
> > non-import case this remains the last one.
> > 
> > So I simply relaxed the match.
> Hmmm, I think it'd help to show what new lines are now showing up so we can 
> validate that they make sense in context. WDYT?
It's the new lines from the synthesized `va_list_tag`. I think they would be 
noise on this these tests, they are testing something completely unrelated.

But they do show up on the ast-json tests where we are basically dumping the 
whole TU.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

mizvekov wrote:
> aaron.ballman wrote:
> > mizvekov wrote:
> > > aaron.ballman wrote:
> > > > This looks like a benign typo -- we still match the line because 
> > > > FileCheck will match partial lines, but I'm pretty sure nothing in your 
> > > > patch would have necessitated this change. Then again, you make this 
> > > > change in a lot of tests, so maybe I'm wrong -- in which case, what 
> > > > changed?
> > > What is happening here (and in all the other such instances) is that on 
> > > the `import` case, this declaration stops being the last one on the TU. 
> > > So the beginning of the line would match on `|-` instead of ``-`, but the 
> > > non-import case this remains the last one.
> > > 
> > > So I simply relaxed the match.
> > Hmmm, I think it'd help to show what new lines are now showing up so we can 
> > validate that they make sense in context. WDYT?
> It's the new lines from the synthesized `va_list_tag`. I think they would be 
> noise on this these tests, they are testing something completely unrelated.
> 
> But they do show up on the ast-json tests where we are basically dumping the 
> whole TU.
Oh, so we're adding those to the *end* of the translation unit, not at the 
beginning? 


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

cor3ntin wrote:
> ChuanqiXu wrote:
> > std modules should be irreverent with system headers; The intuition of the 
> > wording should be that the users can't declare modules like `std` or 
> > `std.compat` to avoid possible conflicting. The approach I imaged may be 
> > add a new compilation flags (call it `-fstd-modules`) now. And if the 
> > compiler found a `std` module declaration without `-fstd-modules`, emit an 
> > error.  
> > 
> > For now, I think we can skip the check for `-fstd-modules` and add it back 
> > when we starts to support std modules actually.
> The idea is that standard modules are built from system directories... it 
> seems a better heuristic than adding a flag for the purpose of 1 diagnostics 
> ( maybe some other system library could in theory export std with no warning, 
> but I'm not super worried about that being a concern in practice)
> The idea is that standard modules are built from system directories...

This is not true. For example, if someday libc++ supports std modules, then we 
need to build the std modules in our working directory, which is not system 
directories. And **ideally**, we would distribute and install module file in 
the system directories. But it is irreverent with the path of the source file.


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

https://reviews.llvm.org/D136953

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


[PATCH] D136554: Implement CWG2631

2022-10-31 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:507-508
   ``-std=gnu++14`` to their build settings to restore the previous behaviour.
+- Implemented DR2631. Invalid ``consteval`` calls in default arguments and 
default
+  member initializers are diagnosed when and if the default is used.
 

aaron.ballman wrote:
> Should this be listed as a potentially breaking change as this now 1) 
> potentially changes the value people were getting for 
> `source_location::current()` as a default argument, and 2) potentially causes 
> instantiation differences due to the change in ODR use?
No because the current value of `source_location::current()` is invalid per 
library wording ( i should reference the issue though) and 2/ i don't think 
there are any difference in odr use except the point of diagnostic. Or at least 
i don't think you could observe it?



Comment at: clang/test/CXX/class/class.local/p1-0x.cpp:14
   int& x2 = x; // expected-error{{reference to local variable 'x' declared 
in enclosing lambda expression}}
-};
+}c; // expected-note {{required here}}
   };

aaron.ballman wrote:
> Double-checking: you did intend to name that local variable, right?
Yes, that's actually the change I'm talking about,
That specific warning only triggers when the initializer is ODR used, which now 
only happens when a constructor is defined, which, in the case of aggregate, 
only happens on use of said aggregate.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

erichkeane wrote:
> mizvekov wrote:
> > aaron.ballman wrote:
> > > Is it valid to use a local variable as a `Scope` object? I would assume 
> > > that scope goes away at the end of this compound statement? I didn't spot 
> > > other cases where we did this -- usually we call `Parser::EnterScope()` 
> > > which allocates a new `Scope` that `Sema` then uses.
> > I don't see anything problematic about allocating it on the stack like 
> > this, implementation-wise.
> > 
> > I thought it would be a bit counter-intuitive to use parser functions here, 
> > since these declarations are entirely synthetic.
> I dont know much about "Scope", as it is particularly used in Parsing, but I 
> DO see the comment says: "A scope is a transient data structure that is used 
> while parsing the program.  It assists with resolving identifiers to the 
> appropriate declaration."
> 
> Which means to me it doesn't need to out-live its parsing time.  I THINK it 
> gets replaced with a CXXScope at one point, but I dont know when/where that 
> happens.
> 
The situation I'm worried about (and maybe it's not a valid concern) is that 
`Parser::EnterScope` uses a cache of scopes that this bypasses and I'm not 
certain whether that's a good thing or not. I *think* it might be reasonable 
(`Scope` is just a holder for a `DeclContext` and that's the object which has 
all the declarations added to and removed from, and that context outlives the 
`Scope` object), but it's worth double-checking.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136554: Implement CWG2631

2022-10-31 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/test/CXX/class/class.local/p1-0x.cpp:14
   int& x2 = x; // expected-error{{reference to local variable 'x' declared 
in enclosing lambda expression}}
-};
+}c; // expected-note {{required here}}
   };

cor3ntin wrote:
> aaron.ballman wrote:
> > Double-checking: you did intend to name that local variable, right?
> Yes, that's actually the change I'm talking about,
> That specific warning only triggers when the initializer is ODR used, which 
> now only happens when a constructor is defined, which, in the case of 
> aggregate, only happens on use of said aggregate.
Note that i considered delaying that warning only in the presence of immediate 
invocations but I think this would be inconsistent and surprising - and also 
probably wrong to mark things odr used if they are not actually ever used.
And alternative would be to not tie that check with the odr-used marking, but 
that does seem like a pretty consequent change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

ChuanqiXu wrote:
> cor3ntin wrote:
> > ChuanqiXu wrote:
> > > std modules should be irreverent with system headers; The intuition of 
> > > the wording should be that the users can't declare modules like `std` or 
> > > `std.compat` to avoid possible conflicting. The approach I imaged may be 
> > > add a new compilation flags (call it `-fstd-modules`) now. And if the 
> > > compiler found a `std` module declaration without `-fstd-modules`, emit 
> > > an error.  
> > > 
> > > For now, I think we can skip the check for `-fstd-modules` and add it 
> > > back when we starts to support std modules actually.
> > The idea is that standard modules are built from system directories... it 
> > seems a better heuristic than adding a flag for the purpose of 1 
> > diagnostics ( maybe some other system library could in theory export std 
> > with no warning, but I'm not super worried about that being a concern in 
> > practice)
> > The idea is that standard modules are built from system directories...
> 
> This is not true. For example, if someday libc++ supports std modules, then 
> we need to build the std modules in our working directory, which is not 
> system directories. And **ideally**, we would distribute and install module 
> file in the system directories. But it is irreverent with the path of the 
> source file.
> then we need to build the std modules in our working directory, which is not 
> system directories.

`-isystem`, pragmas, and linemarkers are all ways around that -- I don't think 
we need a feature flag for this, unless I'm misunderstanding something.


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

https://reviews.llvm.org/D136953

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


[PATCH] D136554: Implement CWG2631

2022-10-31 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added inline comments.



Comment at: clang/docs/ReleaseNotes.rst:507-508
   ``-std=gnu++14`` to their build settings to restore the previous behaviour.
+- Implemented DR2631. Invalid ``consteval`` calls in default arguments and 
default
+  member initializers are diagnosed when and if the default is used.
 

cor3ntin wrote:
> aaron.ballman wrote:
> > Should this be listed as a potentially breaking change as this now 1) 
> > potentially changes the value people were getting for 
> > `source_location::current()` as a default argument, and 2) potentially 
> > causes instantiation differences due to the change in ODR use?
> No because the current value of `source_location::current()` is invalid per 
> library wording ( i should reference the issue though) and 2/ i don't think 
> there are any difference in odr use except the point of diagnostic. Or at 
> least i don't think you could observe it?
The wording for source location
http://eel.is/c++draft/support.srcloc#cons-2 

Without that issue resolution this calls for magic.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136554

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

aaron.ballman wrote:
> mizvekov wrote:
> > aaron.ballman wrote:
> > > mizvekov wrote:
> > > > aaron.ballman wrote:
> > > > > This looks like a benign typo -- we still match the line because 
> > > > > FileCheck will match partial lines, but I'm pretty sure nothing in 
> > > > > your patch would have necessitated this change. Then again, you make 
> > > > > this change in a lot of tests, so maybe I'm wrong -- in which case, 
> > > > > what changed?
> > > > What is happening here (and in all the other such instances) is that on 
> > > > the `import` case, this declaration stops being the last one on the TU. 
> > > > So the beginning of the line would match on `|-` instead of ``-`, but 
> > > > the non-import case this remains the last one.
> > > > 
> > > > So I simply relaxed the match.
> > > Hmmm, I think it'd help to show what new lines are now showing up so we 
> > > can validate that they make sense in context. WDYT?
> > It's the new lines from the synthesized `va_list_tag`. I think they would 
> > be noise on this these tests, they are testing something completely 
> > unrelated.
> > 
> > But they do show up on the ast-json tests where we are basically dumping 
> > the whole TU.
> Oh, so we're adding those to the *end* of the translation unit, not at the 
> beginning? 
We are adding them at the beginning, but it seems we import the other stuff 
before adding them, so on the import tests they show up on the end.

The thing here is that we end up importing them, but then adding new ones from 
the current Sema anyway. But this is fine as most other import things, they get 
separate declarations but merged in any case so they have the same canonical 
decl.

The way we avoid doing that for the other synthesized builtins around it, is 
that we just skip creating them if we find their `Identifier` has been created 
somehow, which is a fairly strange way to test this.

This seemed even less appropriate for `va_list_tag`, since some ABIs put it 
into `std` namespace.

And it seems to me that avoiding creating them again for the current Sema is a 
fairly minimal optimization, and it could make we miss diagnosing imports where 
those things are inconsistent between contexts.

WDYT?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

aaron.ballman wrote:
> erichkeane wrote:
> > mizvekov wrote:
> > > aaron.ballman wrote:
> > > > Is it valid to use a local variable as a `Scope` object? I would assume 
> > > > that scope goes away at the end of this compound statement? I didn't 
> > > > spot other cases where we did this -- usually we call 
> > > > `Parser::EnterScope()` which allocates a new `Scope` that `Sema` then 
> > > > uses.
> > > I don't see anything problematic about allocating it on the stack like 
> > > this, implementation-wise.
> > > 
> > > I thought it would be a bit counter-intuitive to use parser functions 
> > > here, since these declarations are entirely synthetic.
> > I dont know much about "Scope", as it is particularly used in Parsing, but 
> > I DO see the comment says: "A scope is a transient data structure that is 
> > used while parsing the program.  It assists with resolving identifiers to 
> > the appropriate declaration."
> > 
> > Which means to me it doesn't need to out-live its parsing time.  I THINK it 
> > gets replaced with a CXXScope at one point, but I dont know when/where that 
> > happens.
> > 
> The situation I'm worried about (and maybe it's not a valid concern) is that 
> `Parser::EnterScope` uses a cache of scopes that this bypasses and I'm not 
> certain whether that's a good thing or not. I *think* it might be reasonable 
> (`Scope` is just a holder for a `DeclContext` and that's the object which has 
> all the declarations added to and removed from, and that context outlives the 
> `Scope` object), but it's worth double-checking.
Yeah I checked that. The scope object is fairly innocuous, the `EnterScope` 
function uses a cache to stack them, which seems useful in performance 
intensive workloads, and in case the object needs to outlive the function that 
creates it.

But here I see no problem just making it clear that this Scope is only used 
here, by simply allocating it on the stack.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D136826: [clang][Interp] Make sure we free() allocated InitMaps

2022-10-31 Thread Anton Daubert via Phabricator via cfe-commits
antondaubert added inline comments.



Comment at: clang/lib/AST/Interp/Program.h:54-56
+for (Global *G : Globals) {
+  G->block()->invokeDtor();
+}

Seems like this change generates a

```
use-of-uninitialized-value lib/AST/Interp/Descriptor.cpp:150:22 in 
dtorRecord(clang::interp::Block*, char*, clang::interp::Descriptor*)
```

when executing the test test/AST/Interp/arrays.cpp with a memory sanitizer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136826

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked 3 inline comments as done.
aaron.ballman added a comment.

In D136953#3893039 , @tschuett wrote:

> Are malformed imports an issue or are they already covered? There is limit 
> test coverage for import. Am I missing something?
>
>   import import;
>   import module;

It's unclear to me whether the constraints also apply to module imports or not. 
The wording for the constraints is in the section about module units and the 
section about module imports doesn't say anything further. Certainly we want to 
allow `import std;` instead of telling the user about the use of a reserved 
identifier, but it's less clear to me about `import module;` -- if the user 
writes that, they'll either get an error about not being able to find a module 
by that name, or they'd import the module (but how did they produce that module 
in the first place?).




Comment at: clang/docs/ReleaseNotes.rst:347
   Fixes `Issue 57562 `_.
+- Clang now diagnoses use of invalid or reserved module names. Both are
+  diagnosed as an error, but the diagnostic is suppressed for use of reserved

erichkeane wrote:
> So question: ARE we diagnosing all 'use' of invalid/reserved module names?  
> So the idea is you cannot import:
> `std.concepts`?  Or are we diagnosing `export` only?
Export only for the moment. I'll update the release note accordingly.



Comment at: clang/lib/Sema/SemaModule.cpp:148
+/// Tests whether the given identifier is reserved as a module name and
+/// diagnoses if it is. Returs true if a diagnostic is emitted and false
+/// otherwise.

tschuett wrote:
> Returns
Good catch!


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

https://reviews.llvm.org/D136953

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


[PATCH] D136826: [clang][Interp] Make sure we free() allocated InitMaps

2022-10-31 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder added inline comments.



Comment at: clang/lib/AST/Interp/Program.h:54-56
+for (Global *G : Globals) {
+  G->block()->invokeDtor();
+}

antondaubert wrote:
> Seems like this change generates a
> 
> ```
> use-of-uninitialized-value lib/AST/Interp/Descriptor.cpp:150:22 in 
> dtorRecord(clang::interp::Block*, char*, clang::interp::Descriptor*)
> ```
> 
> when executing the test test/AST/Interp/arrays.cpp with a memory sanitizer.
Should be fixed by 
https://github.com/llvm/llvm-project/commit/da4b929da79f4ce886f5612e3c84d29c1d2632f7


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136826

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


[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein marked an inline comment as done.
hokein added inline comments.



Comment at: clang-tools-extra/clangd/tool/Check.cpp:213
+auto Highlights = getSemanticHighlightings(*AST);
+if (LineRange) {
+  for (const auto HL : Highlights) {

kadircet wrote:
> we should print all the highlights when LineRange is missing. so maybe turn 
> this into:
> ```
> auto Highlights = ...
> for(const auto HL : ..) {
>   if(!LineRange || LineRange->contains(HL.R))
>  vlog(...);
> }
> ```
I was going to say this likely introduces too much noise to the output log, 
then I realized that we already did it for inlay hints, probably it is fine for 
verbose log...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137063

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


[clang-tools-extra] e3ec9dd - [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-31T14:46:36+01:00
New Revision: e3ec9dd0ba42a6022b37d8a61e20fe338b8dc51f

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

LOG: [clangd] Run semantic highligting in clangd check.

Allowing us to test this feature (context: a recent crash in
semantic highlighting.)

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

Added: 


Modified: 
clang-tools-extra/clangd/tool/Check.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/tool/Check.cpp 
b/clang-tools-extra/clangd/tool/Check.cpp
index 1fc44fd29ce98..46752e2135639 100644
--- a/clang-tools-extra/clangd/tool/Check.cpp
+++ b/clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,14 @@ class Checker {
 }
   }
 
+  void buildSemanticHighlighting(llvm::Optional LineRange) {
+log("Building semantic highlighting");
+auto Highlights = getSemanticHighlightings(*AST);
+for (const auto HL : Highlights)
+  if (!LineRange || LineRange->contains(HL.R))
+vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +311,7 @@ bool check(llvm::StringRef File, llvm::Optional 
LineRange,
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting(LineRange);
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);



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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman updated this revision to Diff 471988.
aaron.ballman marked 2 inline comments as done.
aaron.ballman added a comment.

Updated based on review feedback:

- Fixed a typo
- Clarified the release note
- Added a test case for `std.foo` being reserved


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

https://reviews.llvm.org/D136953

Files:
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/lib/Sema/SemaModule.cpp
  clang/test/CodeGenCXX/cxx20-module-std-subst-1.cppm
  clang/test/Modules/pair-unambiguous-ctor.cppm
  clang/test/Modules/reserved-names-1.cpp
  clang/test/Modules/reserved-names-2.cpp
  clang/test/Modules/reserved-names-3.cpp
  clang/test/Modules/reserved-names-system-header-1.cpp
  clang/test/Modules/reserved-names-system-header-2.cpp

Index: clang/test/Modules/reserved-names-system-header-2.cpp
===
--- /dev/null
+++ clang/test/Modules/reserved-names-system-header-2.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// Show that we suppress the reserved identifier diagnostic in a system header.
+# 100 "file.cpp" 1 3  // Enter a system header
+export module __test;
+# 100 "file.cpp" 2 3  // Leave the system header
Index: clang/test/Modules/reserved-names-system-header-1.cpp
===
--- /dev/null
+++ clang/test/Modules/reserved-names-system-header-1.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// Show that we suppress the reserved identifier diagnostic in a system header.
+# 100 "file.cpp" 1 3  // Enter a system header
+export module std;
+# 100 "file.cpp" 2 3  // Leave the system header
Index: clang/test/Modules/reserved-names-3.cpp
===
--- /dev/null
+++ clang/test/Modules/reserved-names-3.cpp
@@ -0,0 +1,7 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// Demonstrate that we don't consider use of 'std' (potentially followed by
+// zero or more digits) to be a reserved identifier if it is not the only part
+// of the path.
+export module std12Three;
Index: clang/test/Modules/reserved-names-2.cpp
===
--- /dev/null
+++ clang/test/Modules/reserved-names-2.cpp
@@ -0,0 +1,6 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+// expected-no-diagnostics
+
+// Demonstrate that we don't consider use of 'std' a reserved identifier if it
+// is not the first part of the path.
+export module should_succeed.std0;
Index: clang/test/Modules/reserved-names-1.cpp
===
--- /dev/null
+++ clang/test/Modules/reserved-names-1.cpp
@@ -0,0 +1,45 @@
+// RUN: %clang_cc1 -std=c++20 -fsyntax-only -verify %s
+
+// expected-note@1 15{{add 'module;' to the start of the file to introduce a global module fragment}}
+
+module std;// expected-error {{'std' is a reserved name for a module}}
+module _Test;  // expected-error {{'_Test' is a reserved name for a module}} \
+  expected-error {{module declaration must occur at the start of the translation unit}}
+module module; // expected-error {{'module' is an invalid name for a module}} \
+  expected-error {{module declaration must occur at the start of the translation unit}}
+module std0;   // expected-error {{'std0' is a reserved name for a module}} \
+  expected-error {{module declaration must occur at the start of the translation unit}}
+
+export module module; // expected-error {{'module' is an invalid name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module import; // expected-error {{'import' is an invalid name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module _Test;  // expected-error {{'_Test' is a reserved name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module __test; // expected-error {{'__test' is a reserved name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module te__st; // expected-error {{'te__st' is a reserved name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module std;// expected-error {{'std' is a reserved name for a module}} \
+ expected-error {{module declaration must occur at the start of the translation unit}}
+export module std.foo;// expected-error {{'std' is a reserved name for a module

[PATCH] D137063: [clangd] Run semantic highligting in clangd check.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was automatically updated to reflect the committed changes.
hokein marked an inline comment as done.
Closed by commit rGe3ec9dd0ba42: [clangd] Run semantic highligting in clangd 
check. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D137063?vs=471951&id=471989#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137063

Files:
  clang-tools-extra/clangd/tool/Check.cpp


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,14 @@
 }
   }
 
+  void buildSemanticHighlighting(llvm::Optional LineRange) {
+log("Building semantic highlighting");
+auto Highlights = getSemanticHighlightings(*AST);
+for (const auto HL : Highlights)
+  if (!LineRange || LineRange->contains(HL.R))
+vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +311,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting(LineRange);
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);


Index: clang-tools-extra/clangd/tool/Check.cpp
===
--- clang-tools-extra/clangd/tool/Check.cpp
+++ clang-tools-extra/clangd/tool/Check.cpp
@@ -34,6 +34,7 @@
 #include "ParsedAST.h"
 #include "Preamble.h"
 #include "Protocol.h"
+#include "SemanticHighlighting.h"
 #include "SourceCode.h"
 #include "XRefs.h"
 #include "index/CanonicalIncludes.h"
@@ -206,6 +207,14 @@
 }
   }
 
+  void buildSemanticHighlighting(llvm::Optional LineRange) {
+log("Building semantic highlighting");
+auto Highlights = getSemanticHighlightings(*AST);
+for (const auto HL : Highlights)
+  if (!LineRange || LineRange->contains(HL.R))
+vlog(" {0} {1} {2}", HL.R, HL.Kind, HL.Modifiers);
+  }
+
   // Run AST-based features at each token in the file.
   void testLocationFeatures(llvm::Optional LineRange,
 const bool EnableCodeCompletion) {
@@ -302,6 +311,7 @@
   !C.buildAST())
 return false;
   C.buildInlayHints(LineRange);
+  C.buildSemanticHighlighting(LineRange);
   C.testLocationFeatures(LineRange, EnableCodeCompletion);
 
   log("All checks completed, {0} errors", C.ErrCount);
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D136533: [clang] Fix missing diagnostic of declaration use when accessing TypeDecls through typename access

2022-10-31 Thread Louis Dionne via Phabricator via cfe-commits
ldionne added a comment.

In D136533#3894958 , @thakis wrote:

> In D136533#3893032 , @ldionne wrote:
>
>> In D136533#3892949 , @ldionne 
>> wrote:
>>
>>> 2. Shipping this change does mean that anyone building anything with a new 
>>> Clang and a not-yet-updated libc++ with a deployment target before 10.15 
>>> (or whatever first version we shipped filesystem in) will fail. IMO that's 
>>> kind of annoying, but may be OK if we fix libc++ first.
>>
>> I guess the interesting question here would be: @thakis, is there a reason 
>> why you are using the SDK-provided libc++ but the tip-of-trunk Clang for 
>> building Chrome? (I feel like we've talked about this before but I don't 
>> remember).
>
> Because that's what you recommended :) We used to use the just-built libc++ 
> but that had other issues.

Ugh, OK. Yeah, your previous setup was even much weirder in fact, it used the 
trunk libc++ headers but linked against the system dylib IIRC. I stand by my 
previous recommendation, but your setup is still unusual: you're using the SDK 
libc++ with a ToT clang, which is technically not a supported combination. The 
best would be to use the Apple-provided Clang on macOS as well, but I 
understand you might have reasons to want to use the ToT clang instead.

I investigated the issue and the problem reproduces for me with:

  cat 

[PATCH] D136957: [AArch64] Add support for the Cortex-A715 CPU

2022-10-31 Thread Simi Pallipurath via Phabricator via cfe-commits
simpal01 updated this revision to Diff 471991.
simpal01 added a comment.

Comments Addressed.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136957

Files:
  clang/docs/ReleaseNotes.rst
  clang/test/Driver/aarch64-mcpu.c
  clang/test/Misc/target-invalid-cpu-note.c
  llvm/docs/ReleaseNotes.rst
  llvm/include/llvm/Support/AArch64TargetParser.def
  llvm/lib/Support/Host.cpp
  llvm/lib/Target/AArch64/AArch64.td
  llvm/lib/Target/AArch64/AArch64Subtarget.cpp
  llvm/lib/Target/AArch64/AArch64Subtarget.h
  llvm/unittests/Support/TargetParserTest.cpp

Index: llvm/unittests/Support/TargetParserTest.cpp
===
--- llvm/unittests/Support/TargetParserTest.cpp
+++ llvm/unittests/Support/TargetParserTest.cpp
@@ -1016,6 +1016,19 @@
  AArch64::AEK_FLAGM | AArch64::AEK_SB |
  AArch64::AEK_I8MM | AArch64::AEK_BF16,
  "9-A"),
+ARMCPUTestParams("cortex-a715", "armv9-a", "neon-fp-armv8",
+ AArch64::AEK_CRC | AArch64::AEK_FP | AArch64::AEK_BF16 |
+ AArch64::AEK_SIMD | AArch64::AEK_RAS |
+ AArch64::AEK_LSE | AArch64::AEK_RDM |
+ AArch64::AEK_RCPC | AArch64::AEK_DOTPROD |
+ AArch64::AEK_MTE | AArch64::AEK_PAUTH |
+ AArch64::AEK_SVE | AArch64::AEK_SVE2 |
+ AArch64::AEK_SVE2BITPERM | AArch64::AEK_SSBS |
+ AArch64::AEK_SB | AArch64::AEK_I8MM |
+ AArch64::AEK_PERFMON | AArch64::AEK_PREDRES |
+ AArch64::AEK_PROFILE | AArch64::AEK_FP16FML |
+ AArch64::AEK_FP16 | AArch64::AEK_FLAGM,
+ "9-A"),
 ARMCPUTestParams(
 "neoverse-v1", "armv8.4-a", "crypto-neon-fp-armv8",
 AArch64::AEK_RAS | AArch64::AEK_SVE | AArch64::AEK_SSBS |
@@ -1296,7 +1309,7 @@
  "8.2-A")));
 
 // Note: number of CPUs includes aliases.
-static constexpr unsigned NumAArch64CPUArchs = 59;
+static constexpr unsigned NumAArch64CPUArchs = 60;
 
 TEST(TargetParserTest, testAArch64CPUArchList) {
   SmallVector List;
Index: llvm/lib/Target/AArch64/AArch64Subtarget.h
===
--- llvm/lib/Target/AArch64/AArch64Subtarget.h
+++ llvm/lib/Target/AArch64/AArch64Subtarget.h
@@ -64,6 +64,7 @@
 CortexA78,
 CortexA78C,
 CortexA710,
+CortexA715,
 CortexR82,
 CortexX1,
 CortexX1C,
Index: llvm/lib/Target/AArch64/AArch64Subtarget.cpp
===
--- llvm/lib/Target/AArch64/AArch64Subtarget.cpp
+++ llvm/lib/Target/AArch64/AArch64Subtarget.cpp
@@ -142,6 +142,7 @@
 MaxBytesForLoopAlignment = 8;
 break;
   case CortexA710:
+  case CortexA715:
   case CortexX2:
 PrefFunctionLogAlignment = 4;
 VScaleForTuning = 1;
Index: llvm/lib/Target/AArch64/AArch64.td
===
--- llvm/lib/Target/AArch64/AArch64.td
+++ llvm/lib/Target/AArch64/AArch64.td
@@ -764,6 +764,14 @@
FeatureLSLFast,
FeaturePostRAScheduler]>;
 
+def TuneA715 : SubtargetFeature<"a715", "ARMProcFamily", "CortexA715",
+ "Cortex-A715 ARM processors", [
+ FeatureFuseAES,
+ FeaturePostRAScheduler,
+ FeatureCmpBccFusion,
+ FeatureLSLFast,
+ FeatureFuseAdrpAdd]>;
+
 def TuneR82 : SubtargetFeature<"cortex-r82", "ARMProcFamily",
"CortexR82",
"Cortex-R82 ARM processors", [
@@ -1093,6 +1101,10 @@
   list A710 = [HasV9_0aOps, FeatureNEON, FeaturePerfMon,
  FeatureETE, FeatureMTE, FeatureFP16FML,
  FeatureSVE2BitPerm, FeatureBF16, FeatureMatMulInt8];
+  list A715 = [HasV9_0aOps, FeatureNEON, FeatureMTE,
+ FeatureFP16FML, FeatureSVE, FeatureTRBE,
+ FeatureSVE2BitPerm, FeatureBF16, FeatureETE,
+ FeaturePerfMon, FeatureMatMulInt8, FeatureSPE];
   list R82  = [HasV8_0rOps, FeaturePerfMon, FeatureFullFP16,
  FeatureFP16FML, FeatureSSBS, FeaturePredRes,
  FeatureSB];
@@ -1231,6 +1243,8 @@
  [TuneA78C]>;
 def : ProcessorModel<"cortex-a710", NeoverseN2Model, ProcessorFeatures.A710,
  [TuneA710]>;
+def : ProcessorModel<"cortex-a715", NeoverseN2Model, Processor

[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

aaron.ballman wrote:
> ChuanqiXu wrote:
> > cor3ntin wrote:
> > > ChuanqiXu wrote:
> > > > std modules should be irreverent with system headers; The intuition of 
> > > > the wording should be that the users can't declare modules like `std` 
> > > > or `std.compat` to avoid possible conflicting. The approach I imaged 
> > > > may be add a new compilation flags (call it `-fstd-modules`) now. And 
> > > > if the compiler found a `std` module declaration without 
> > > > `-fstd-modules`, emit an error.  
> > > > 
> > > > For now, I think we can skip the check for `-fstd-modules` and add it 
> > > > back when we starts to support std modules actually.
> > > The idea is that standard modules are built from system directories... it 
> > > seems a better heuristic than adding a flag for the purpose of 1 
> > > diagnostics ( maybe some other system library could in theory export std 
> > > with no warning, but I'm not super worried about that being a concern in 
> > > practice)
> > > The idea is that standard modules are built from system directories...
> > 
> > This is not true. For example, if someday libc++ supports std modules, then 
> > we need to build the std modules in our working directory, which is not 
> > system directories. And **ideally**, we would distribute and install module 
> > file in the system directories. But it is irreverent with the path of the 
> > source file.
> > then we need to build the std modules in our working directory, which is 
> > not system directories.
> 
> `-isystem`, pragmas, and linemarkers are all ways around that -- I don't 
> think we need a feature flag for this, unless I'm misunderstanding something.
Although it may be a little bit nit picker, the module unit which declares the 
std modules won't be header. It is a module unit. So it requires we implement 
std modules by wrapping linemarkers around the std modules declaration, which 
looks a little bit overkill.

And another point is that maybe we need to introduce another feature flags to 
implement std modules. Although I tried to implement std modules within the 
current features, I can't prove we can implement std modules in that way in the 
end of the day.

Let me add some more words. The standards require us to implement std modules 
without deprecating the system headers. This strategy leads the direction to 
"implement the components in the original headers and control their visibility 
in the std module unit".
It may look like:

```
//--- std.cppm
module;
#include 
...
export module std;
```

Then how can control the visibility?  In my original experiments, I use the 
style:

```
//--- std.cppm
module;
#include 
...
export module std;
export namespace std {
using std::sort;
}
```

but this doesn't always work. For example, we can't `using` a in-class friend 
definition. And there are more reasons, the unreachable declarations in the 
global module fragment (the section from `module;` to `export module 
[module_name]`) can be discarded to reduce the size of the module file. And the 
reachable rules are complex. But the simple story is that it is highly possible 
the a lot of necessary declarations in global module fragment in the above 
snippet would be discarded so that the user can't use std modules correctly. I 
mean, we **may** need a special feature flag for it. And the method with 
`system headers` looks not good and semantics are not so consistency.




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

https://reviews.llvm.org/D136953

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


[PATCH] D135930: [X86] Add AVX-NE-CONVERT instructions.

2022-10-31 Thread Freddy, Ye via Phabricator via cfe-commits
FreddyYe marked an inline comment as done.
FreddyYe added inline comments.



Comment at: clang/lib/Headers/avx512vlbf16intrin.h:164
+#define _mm_cvtneps_pbh(A) \
+  ((__m128bh)__builtin_ia32_vcvtneps2bf16128((__v4sf)(A)))
 

pengfei wrote:
> FreddyYe wrote:
> > pengfei wrote:
> > > pengfei wrote:
> > > > RKSimon wrote:
> > > > > Is there no way for __attribute__ to allow different attribute 
> > > > > permutations?
> > > > > 
> > > > > Also, can we keep the __builtin_ia32_cvtneps2bf16_128 naming 
> > > > > convention?
> > > > > Is there no way for attribute to allow different attribute 
> > > > > permutations?
> > > > 
> > > > We have discussed this problem with GCC folks. There are two problems 
> > > > here:
> > > > 1. Unlike builtins, function attributes are more generic. It may 
> > > > introduce a lot of checks between callers and callees. I had a research 
> > > > to limit it to `__always_inline__` functions only. However, Clang 
> > > > handles inlining in middle-end, we don't have such information in the 
> > > > front-end. Besides, we don't know how to merge different permutations 
> > > > if they are inlining to the same function.
> > > > 2. We don't know how to put the permutations into IR's function 
> > > > attributes. We need to preserve all permutations for inlining 
> > > > reference, but the backend needs a determine feature list rather than 
> > > > selective.
> > > It's better to use `__builtin_ia32_cvtneps2bf16_128`.
> > I think __builtin_ia32_vcvtneps2bf16128 is also a "right" name.
> > 
> > See __builtin_ia32_vfmaddsubph256, __builtin_ia32_minph256...
> > 
> > And I admit naming conventions of clang builtins as well as LLVM IR 
> > builtins are confusing right now.
> The problem here is `16128` is a bit confusing, a `_` breaks it into 2 number.
> But I'm not insist on it :)
I did a try but found __builtin_ia32_cvtneps2bf16_256 existed for avx512bf16, 
and it's used for mask intrinsic lowering currently. What about not change this 
time? We can do a refine patch later for avx512bf16 builtins since they also 
have some redundant FE/codegen logics for 256/512 mask intrinsics.


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

https://reviews.llvm.org/D135930

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/Modules/reserved-names-1.cpp:25
+ expected-error {{module declaration must occur at the 
start of the translation unit}}
+export module std.foo;// expected-error {{'std' is a reserved name for a 
module}} \
+ expected-error {{module declaration must occur at the 
start of the translation unit}}

It looks like the diagnostic message should be '`std.foo` is a ...'


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

https://reviews.llvm.org/D136953

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


[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked an inline comment as done.
aaron.ballman added inline comments.



Comment at: clang/test/Modules/reserved-names-1.cpp:25
+ expected-error {{module declaration must occur at the 
start of the translation unit}}
+export module std.foo;// expected-error {{'std' is a reserved name for a 
module}} \
+ expected-error {{module declaration must occur at the 
start of the translation unit}}

ChuanqiXu wrote:
> It looks like the diagnostic message should be '`std.foo` is a ...'
We tell the user which part of the path name is reserved instead of giving them 
the whole path name. That helps for cases like: `export module 
aaron.wrote.this.awesome.module;` If there's confusion from this, we could 
probably change the diagnostic to be `'this' is a reserved identifier within 
module name 'aaron.wrote.this.awesome.module'`, but because you can only 
declare one module at a time, that seemed like overkill.


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

https://reviews.llvm.org/D136953

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


[PATCH] D136701: [LinkerWrapper] Perform device linking steps in parallel

2022-10-31 Thread Joseph Huber via Phabricator via cfe-commits
jhuber6 updated this revision to Diff 471994.
jhuber6 added a comment.

Ping and fix test.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136701

Files:
  clang/test/Driver/linker-wrapper.c
  clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
  clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td

Index: clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
===
--- clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
+++ clang/tools/clang-linker-wrapper/LinkerWrapperOpts.td
@@ -59,6 +59,10 @@
   Flags<[WrapperOnlyOption]>, MetaVarName<"">,
   HelpText<"Set the granularity of time-trace updates">;
 
+def wrapper_jobs : Joined<["--"], "wrapper-jobs=">,
+  Flags<[WrapperOnlyOption]>, MetaVarName<"">,
+  HelpText<"Sets the number of parallel jobs to use for device linking">;
+
 // Flags passed to the device linker.
 def arch_EQ : Joined<["--"], "arch=">,
   Flags<[DeviceOnlyOption, HelpHidden]>, MetaVarName<"">,
Index: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
===
--- clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
+++ clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp
@@ -42,6 +42,7 @@
 #include "llvm/Support/Host.h"
 #include "llvm/Support/InitLLVM.h"
 #include "llvm/Support/MemoryBuffer.h"
+#include "llvm/Support/Parallel.h"
 #include "llvm/Support/Path.h"
 #include "llvm/Support/Program.h"
 #include "llvm/Support/Signals.h"
@@ -1119,19 +1120,34 @@
 /// be registered by the runtime.
 Expected>
 linkAndWrapDeviceFiles(SmallVectorImpl &LinkerInputFiles,
-   const InputArgList &Args) {
+   const InputArgList &Args, char **Argv, int Argc) {
   llvm::TimeTraceScope TimeScope("Handle all device input");
 
-  DenseMap> InputsForTarget;
+  DenseMap> InputMap;
   for (auto &File : LinkerInputFiles)
-InputsForTarget[File].emplace_back(std::move(File));
+InputMap[File].emplace_back(std::move(File));
   LinkerInputFiles.clear();
 
-  DenseMap> Images;
-  for (auto &[ID, Input] : InputsForTarget) {
+  SmallVector> InputsForTarget;
+  for (auto &[ID, Input] : InputMap)
+InputsForTarget.emplace_back(std::move(Input));
+  InputMap.clear();
+
+  std::mutex ImageMtx;
+  DenseMap> Images;
+  auto Err = parallelForEachError(InputsForTarget, [&](auto &Input) -> Error {
 llvm::TimeTraceScope TimeScope("Link device input");
 
-auto LinkerArgs = getLinkerArgs(Input, Args);
+// Each thread needs its own copy of the base arguments to maintain
+// per-device argument storage of synthetic strings.
+const OptTable &Tbl = getOptTable();
+BumpPtrAllocator Alloc;
+StringSaver Saver(Alloc);
+auto BaseArgs =
+Tbl.parseArgs(Argc, Argv, OPT_INVALID, Saver, [](StringRef Err) {
+  reportError(createStringError(inconvertibleErrorCode(), Err));
+});
+auto LinkerArgs = getLinkerArgs(Input, BaseArgs);
 
 DenseSet ActiveOffloadKinds;
 for (const auto &File : Input)
@@ -1142,7 +1158,7 @@
 if (Error Err = linkBitcodeFiles(Input, InputFiles, LinkerArgs))
   return std::move(Err);
 
-// Write any remaining device inputs to an output file for the linker job.
+// Write any remaining device inputs to an output file for the linker.
 for (const OffloadFile &File : Input) {
   auto FileNameOrErr = writeOffloadFile(File);
   if (!FileNameOrErr)
@@ -1150,7 +1166,7 @@
   InputFiles.emplace_back(*FileNameOrErr);
 }
 
-// Link the remaining device files, if necessary, using the device linker.
+// Link the remaining device files using the device linker.
 llvm::Triple Triple(LinkerArgs.getLastArgValue(OPT_triple_EQ));
 bool RequiresLinking =
 !Args.hasArg(OPT_embed_bitcode) &&
@@ -1171,17 +1187,30 @@
   TheImage.TheImageKind = IMG_Object;
   TheImage.TheOffloadKind = Kind;
   TheImage.StringData = {
-  {"triple", LinkerArgs.getLastArgValue(OPT_triple_EQ)},
-  {"arch", LinkerArgs.getLastArgValue(OPT_arch_EQ)}};
+  {"triple",
+   Args.MakeArgString(LinkerArgs.getLastArgValue(OPT_triple_EQ))},
+  {"arch",
+   Args.MakeArgString(LinkerArgs.getLastArgValue(OPT_arch_EQ))}};
   TheImage.Image = std::move(*FileOrErr);
+
+  std::lock_guard Guard(ImageMtx);
   Images[Kind].emplace_back(std::move(TheImage));
 }
-  }
+return Error::success();
+  });
+  if (Err)
+return std::move(Err);
 
   // Create a binary image of each offloading image and embed it into a new
   // object file.
   SmallVector WrappedOutput;
-  for (const auto &[Kind, Input] : Images) {
+  for (auto &[Kind, Input] : Images) {
+// We sort the entries before bundling so they appear in a deterministic
+// order in the final binary.
+llvm::sort(Input, [](OffloadingImage &A, OffloadingImage &B) {
+ 

[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Chuanqi Xu via Phabricator via cfe-commits
ChuanqiXu added inline comments.



Comment at: clang/test/Modules/reserved-names-1.cpp:25
+ expected-error {{module declaration must occur at the 
start of the translation unit}}
+export module std.foo;// expected-error {{'std' is a reserved name for a 
module}} \
+ expected-error {{module declaration must occur at the 
start of the translation unit}}

aaron.ballman wrote:
> ChuanqiXu wrote:
> > It looks like the diagnostic message should be '`std.foo` is a ...'
> We tell the user which part of the path name is reserved instead of giving 
> them the whole path name. That helps for cases like: `export module 
> aaron.wrote.this.awesome.module;` If there's confusion from this, we could 
> probably change the diagnostic to be `'this' is a reserved identifier within 
> module name 'aaron.wrote.this.awesome.module'`, but because you can only 
> declare one module at a time, that seemed like overkill.
Got it. Makes sense.


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

https://reviews.llvm.org/D136953

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


[PATCH] D136786: Fix `unsafe-fp-math` attribute emission.

2022-10-31 Thread Zahira Ammarguellat via Phabricator via cfe-commits
zahiraam added a comment.

In D136786#3893485 , @andrew.w.kaylor 
wrote:

> In D136786#3892177 , @zahiraam 
> wrote:
>
 I'm not following entirely, but -funsafe-math-optimizations is just a 
 subset of -ffast-math, so checking only the properties that contribute to 
 -funsafe-math-optimizations should be enough. 
  I think it is way simpler to reason in these terms than enumerating all 
 the possible scenarios.
>>
>> Exactly my point Since -funsafe-math-optimizations is a subset of 
>> -ffast-math, shouldn't it be the "minimal" option to trigger the 
>> unsafe-fp-math attribute for functions? 
>> I agree with the second part of the condition; it should be
>> updated with (LangOpts.getDefaultFPContractMode() ==  
>> LangOptions::FPModeKind::FPM_Fast ||   LangOpts.getDefaultFPContractMode() 
>> == LangOptions::FPModeKind::FPM_FastHonorPragmas) 
>> but I am still hesitant about the change you are proposing for the first 
>> part of the condition.
>> @andrew.w.kaylor Can you please weigh in on this?
>
> I talked to Zahira about this offline, and the current state is even messier 
> than I realized. I think we need to start by making sure we agree on the 
> behavior we want and then figure out how to get there. There are some messy 
> complications in the different ways things are handled in the driver, the 
> front end, and the backend. There are more overlapping settings than I would 
> like, but I guess it's best to look for the best way we can incrementally 
> improve that situation.
>
> As a first principle, I'd like to clarify a "big picture" item that I was 
> trying to get at in my earlier comment. I'd like to be able to reason about 
> this from the starting point of individual semantic modes. There is a set of 
> modes defined in the clang user's manual 
> (https://clang.llvm.org/docs/UsersManual.html#controlling-floating-point-behavior).
>  I think this is reasonably complete:
>
>   exception_behavior
>   fenv_access
>   rounding_mode
>   fp-contract
>   denormal_fp_math
>   denormal_fp_math_32
>   support_math_errno
>   no_honor_nans
>   no_honor_infinities
>   no_signed_zeros
>   allow_reciprocal
>   allow_approximate_fns
>   allow_reassociation
>
> These are the modes from clang's perspective. They get communicated to the 
> back end in different ways. The backend handling of this isn't nearly as 
> consistent as I'd like, but that's a different problem. I think these basic 
> modes can be thought of as language-independent and should be used as the 
> basic building blocks for reasoning about floating point behavior across all 
> LLVM-based compilers.
>
> On top of these modes, we have two concepts "fast-math" and 
> "unsafe-math-optimizations" which are essentially composites of one or more 
> of the above semantic modes. I say "essentially" because up to this point 
> there has been some fuzzy handling of that. I'd like to say they are 
> absolutely composites of the above modes, and I think we can make it so, 
> starting here.
>
> If we agree that fast-math and unsafe-math-optimizations/unsafe-fp-math are 
> composites of some of the other modes, then we can apply a symmetry property 
> that I think will be helpful in the problem we're trying to solve here and 
> will lead to better reasoning about these settings in the future.
>
> I am proposing that passing "-ffast-math" should have *exactly* the same 
> effects as passing all of the individual command line options that are 
> implied by -ffast-math. Likewise, passing "-funsafe-math-optimizations" 
> should have *exactly* the same effects as passing all of the individual 
> options that are implied by -funsafe-math-optimizations. And, of course, any 
> combination of options that turn various states on and off can be strung 
> together and we can just evaluate the final state those options leave us in 
> to see if we are in the "fast-math" state or the "unsafe-fp-math" state.

Strongly agree.

> I'm going to ignore fast-math right now, because I think the current handling 
> is mostly OK, and this review is about unsafe-fp-math. The unsafe-fp-math 
> case is a little simpler in concept, but I think we've got more problems with 
> it.
>
> Another fundamental principle I'd like to declare here is that 
> LangOpts.UnsafeFPMath, TargetOptions.UnsafeFPMath, and the "unsafe-fp-math" 
> function attribute should all mean exactly the same thing. The function 
> attribute has a different scope, so it might not always have the same value 
> as the other two, but it should at least mean the same thing.
>
> My understanding is this:
>
>   unsafe-fp-math = exception_behavior(ignore) +
>fenv_access(off) +
>no_signed_zeros(on) +
>allow_reciprocal(on) +
>allow_approximate_fns(on) +
>allow_reassociation(on) +
>fp_contract(fast)
>
> The fi

[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Erich Keane via Phabricator via cfe-commits
erichkeane added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

ChuanqiXu wrote:
> aaron.ballman wrote:
> > ChuanqiXu wrote:
> > > cor3ntin wrote:
> > > > ChuanqiXu wrote:
> > > > > std modules should be irreverent with system headers; The intuition 
> > > > > of the wording should be that the users can't declare modules like 
> > > > > `std` or `std.compat` to avoid possible conflicting. The approach I 
> > > > > imaged may be add a new compilation flags (call it `-fstd-modules`) 
> > > > > now. And if the compiler found a `std` module declaration without 
> > > > > `-fstd-modules`, emit an error.  
> > > > > 
> > > > > For now, I think we can skip the check for `-fstd-modules` and add it 
> > > > > back when we starts to support std modules actually.
> > > > The idea is that standard modules are built from system directories... 
> > > > it seems a better heuristic than adding a flag for the purpose of 1 
> > > > diagnostics ( maybe some other system library could in theory export 
> > > > std with no warning, but I'm not super worried about that being a 
> > > > concern in practice)
> > > > The idea is that standard modules are built from system directories...
> > > 
> > > This is not true. For example, if someday libc++ supports std modules, 
> > > then we need to build the std modules in our working directory, which is 
> > > not system directories. And **ideally**, we would distribute and install 
> > > module file in the system directories. But it is irreverent with the path 
> > > of the source file.
> > > then we need to build the std modules in our working directory, which is 
> > > not system directories.
> > 
> > `-isystem`, pragmas, and linemarkers are all ways around that -- I don't 
> > think we need a feature flag for this, unless I'm misunderstanding 
> > something.
> Although it may be a little bit nit picker, the module unit which declares 
> the std modules won't be header. It is a module unit. So it requires we 
> implement std modules by wrapping linemarkers around the std modules 
> declaration, which looks a little bit overkill.
> 
> And another point is that maybe we need to introduce another feature flags to 
> implement std modules. Although I tried to implement std modules within the 
> current features, I can't prove we can implement std modules in that way in 
> the end of the day.
> 
> Let me add some more words. The standards require us to implement std modules 
> without deprecating the system headers. This strategy leads the direction to 
> "implement the components in the original headers and control their 
> visibility in the std module unit".
> It may look like:
> 
> ```
> //--- std.cppm
> module;
> #include 
> ...
> export module std;
> ```
> 
> Then how can control the visibility?  In my original experiments, I use the 
> style:
> 
> ```
> //--- std.cppm
> module;
> #include 
> ...
> export module std;
> export namespace std {
> using std::sort;
> }
> ```
> 
> but this doesn't always work. For example, we can't `using` a in-class friend 
> definition. And there are more reasons, the unreachable declarations in the 
> global module fragment (the section from `module;` to `export module 
> [module_name]`) can be discarded to reduce the size of the module file. And 
> the reachable rules are complex. But the simple story is that it is highly 
> possible the a lot of necessary declarations in global module fragment in the 
> above snippet would be discarded so that the user can't use std modules 
> correctly. I mean, we **may** need a special feature flag for it. And the 
> method with `system headers` looks not good and semantics are not so 
> consistency.
> 
> 
IMO, any such additional flag (say `-isystem-module`) should ALSO use the 
`isInSystemHeader` infrastructure.  I suspect nearly every place we use 
`isInSystemHeader` we also mean to exclude a system-module as well.

I think that any such flag can/should be added later as you figure out how it 
should be specified/work.  That said, when you do so, it should either also 
feed `isInSystemHeader`, or basically every use of `isInSystemHeader` should 
ALSO changed to use the new flag as well


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

https://reviews.llvm.org/D136953

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/Sema.cpp:460-462
+Scope S(TUScope, Scope::DeclScope, getDiagnostics());
+PushDeclContext(&S, DC);
+PushOnScopeChains(ND, &S);

mizvekov wrote:
> aaron.ballman wrote:
> > erichkeane wrote:
> > > mizvekov wrote:
> > > > aaron.ballman wrote:
> > > > > Is it valid to use a local variable as a `Scope` object? I would 
> > > > > assume that scope goes away at the end of this compound statement? I 
> > > > > didn't spot other cases where we did this -- usually we call 
> > > > > `Parser::EnterScope()` which allocates a new `Scope` that `Sema` then 
> > > > > uses.
> > > > I don't see anything problematic about allocating it on the stack like 
> > > > this, implementation-wise.
> > > > 
> > > > I thought it would be a bit counter-intuitive to use parser functions 
> > > > here, since these declarations are entirely synthetic.
> > > I dont know much about "Scope", as it is particularly used in Parsing, 
> > > but I DO see the comment says: "A scope is a transient data structure 
> > > that is used while parsing the program.  It assists with resolving 
> > > identifiers to the appropriate declaration."
> > > 
> > > Which means to me it doesn't need to out-live its parsing time.  I THINK 
> > > it gets replaced with a CXXScope at one point, but I dont know when/where 
> > > that happens.
> > > 
> > The situation I'm worried about (and maybe it's not a valid concern) is 
> > that `Parser::EnterScope` uses a cache of scopes that this bypasses and I'm 
> > not certain whether that's a good thing or not. I *think* it might be 
> > reasonable (`Scope` is just a holder for a `DeclContext` and that's the 
> > object which has all the declarations added to and removed from, and that 
> > context outlives the `Scope` object), but it's worth double-checking.
> Yeah I checked that. The scope object is fairly innocuous, the `EnterScope` 
> function uses a cache to stack them, which seems useful in performance 
> intensive workloads, and in case the object needs to outlive the function 
> that creates it.
> 
> But here I see no problem just making it clear that this Scope is only used 
> here, by simply allocating it on the stack.
Great, thank you for double-checking, I appreciate it!



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

mizvekov wrote:
> aaron.ballman wrote:
> > mizvekov wrote:
> > > aaron.ballman wrote:
> > > > mizvekov wrote:
> > > > > aaron.ballman wrote:
> > > > > > This looks like a benign typo -- we still match the line because 
> > > > > > FileCheck will match partial lines, but I'm pretty sure nothing in 
> > > > > > your patch would have necessitated this change. Then again, you 
> > > > > > make this change in a lot of tests, so maybe I'm wrong -- in which 
> > > > > > case, what changed?
> > > > > What is happening here (and in all the other such instances) is that 
> > > > > on the `import` case, this declaration stops being the last one on 
> > > > > the TU. So the beginning of the line would match on `|-` instead of 
> > > > > ``-`, but the non-import case this remains the last one.
> > > > > 
> > > > > So I simply relaxed the match.
> > > > Hmmm, I think it'd help to show what new lines are now showing up so we 
> > > > can validate that they make sense in context. WDYT?
> > > It's the new lines from the synthesized `va_list_tag`. I think they would 
> > > be noise on this these tests, they are testing something completely 
> > > unrelated.
> > > 
> > > But they do show up on the ast-json tests where we are basically dumping 
> > > the whole TU.
> > Oh, so we're adding those to the *end* of the translation unit, not at the 
> > beginning? 
> We are adding them at the beginning, but it seems we import the other stuff 
> before adding them, so on the import tests they show up on the end.
> 
> The thing here is that we end up importing them, but then adding new ones 
> from the current Sema anyway. But this is fine as most other import things, 
> they get separate declarations but merged in any case so they have the same 
> canonical decl.
> 
> The way we avoid doing that for the other synthesized builtins around it, is 
> that we just skip creating them if we find their `Identifier` has been 
> created somehow, which is a fairly strange way to test this.
> 
> This seemed even less appropriate for `va_list_tag`, since some ABIs put it 
> into `std` namespace.
> 
> And it seems to me that avoiding creating them again for the current Sema is 
> a fairly minimal optimization, and it could make we miss diagnosing imports 
> where those things are inconsistent between contex

[PATCH] D136953: [C++20] Diagnose invalid and reserved module names

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman marked an inline comment as done.
aaron.ballman added inline comments.



Comment at: clang/lib/Sema/SemaModule.cpp:282
+  StringRef FirstComponentName = Path[0].first->getName();
+  if (!getSourceManager().isInSystemHeader(Path[0].second) &&
+  (FirstComponentName == "std" ||

erichkeane wrote:
> ChuanqiXu wrote:
> > aaron.ballman wrote:
> > > ChuanqiXu wrote:
> > > > cor3ntin wrote:
> > > > > ChuanqiXu wrote:
> > > > > > std modules should be irreverent with system headers; The intuition 
> > > > > > of the wording should be that the users can't declare modules like 
> > > > > > `std` or `std.compat` to avoid possible conflicting. The approach I 
> > > > > > imaged may be add a new compilation flags (call it `-fstd-modules`) 
> > > > > > now. And if the compiler found a `std` module declaration without 
> > > > > > `-fstd-modules`, emit an error.  
> > > > > > 
> > > > > > For now, I think we can skip the check for `-fstd-modules` and add 
> > > > > > it back when we starts to support std modules actually.
> > > > > The idea is that standard modules are built from system 
> > > > > directories... it seems a better heuristic than adding a flag for the 
> > > > > purpose of 1 diagnostics ( maybe some other system library could in 
> > > > > theory export std with no warning, but I'm not super worried about 
> > > > > that being a concern in practice)
> > > > > The idea is that standard modules are built from system directories...
> > > > 
> > > > This is not true. For example, if someday libc++ supports std modules, 
> > > > then we need to build the std modules in our working directory, which 
> > > > is not system directories. And **ideally**, we would distribute and 
> > > > install module file in the system directories. But it is irreverent 
> > > > with the path of the source file.
> > > > then we need to build the std modules in our working directory, which 
> > > > is not system directories.
> > > 
> > > `-isystem`, pragmas, and linemarkers are all ways around that -- I don't 
> > > think we need a feature flag for this, unless I'm misunderstanding 
> > > something.
> > Although it may be a little bit nit picker, the module unit which declares 
> > the std modules won't be header. It is a module unit. So it requires we 
> > implement std modules by wrapping linemarkers around the std modules 
> > declaration, which looks a little bit overkill.
> > 
> > And another point is that maybe we need to introduce another feature flags 
> > to implement std modules. Although I tried to implement std modules within 
> > the current features, I can't prove we can implement std modules in that 
> > way in the end of the day.
> > 
> > Let me add some more words. The standards require us to implement std 
> > modules without deprecating the system headers. This strategy leads the 
> > direction to "implement the components in the original headers and control 
> > their visibility in the std module unit".
> > It may look like:
> > 
> > ```
> > //--- std.cppm
> > module;
> > #include 
> > ...
> > export module std;
> > ```
> > 
> > Then how can control the visibility?  In my original experiments, I use the 
> > style:
> > 
> > ```
> > //--- std.cppm
> > module;
> > #include 
> > ...
> > export module std;
> > export namespace std {
> > using std::sort;
> > }
> > ```
> > 
> > but this doesn't always work. For example, we can't `using` a in-class 
> > friend definition. And there are more reasons, the unreachable declarations 
> > in the global module fragment (the section from `module;` to `export module 
> > [module_name]`) can be discarded to reduce the size of the module file. And 
> > the reachable rules are complex. But the simple story is that it is highly 
> > possible the a lot of necessary declarations in global module fragment in 
> > the above snippet would be discarded so that the user can't use std modules 
> > correctly. I mean, we **may** need a special feature flag for it. And the 
> > method with `system headers` looks not good and semantics are not so 
> > consistency.
> > 
> > 
> IMO, any such additional flag (say `-isystem-module`) should ALSO use the 
> `isInSystemHeader` infrastructure.  I suspect nearly every place we use 
> `isInSystemHeader` we also mean to exclude a system-module as well.
> 
> I think that any such flag can/should be added later as you figure out how it 
> should be specified/work.  That said, when you do so, it should either also 
> feed `isInSystemHeader`, or basically every use of `isInSystemHeader` should 
> ALSO changed to use the new flag as well
> I think that any such flag can/should be added later as you figure out how it 
> should be specified/work. That said, when you do so, it should either also 
> feed isInSystemHeader, or basically every use of isInSystemHeader should ALSO 
> changed to use the new flag as well

+1, that's my thinking as well.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D136953/ne

[PATCH] D136701: [LinkerWrapper] Perform device linking steps in parallel

2022-10-31 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl added inline comments.



Comment at: clang/tools/clang-linker-wrapper/ClangLinkerWrapper.cpp:1211-1212
+llvm::sort(Input, [](OffloadingImage &A, OffloadingImage &B) {
+  return A.StringData["triple"].compare(B.StringData["triple"]) == 1 ||
+ A.StringData["arch"].compare(B.StringData["arch"]) == 1;
+});

should we also sort for offload kind? In the future, we may have both openmp 
and hip binaries embeded.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136701

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


[PATCH] D136071: [include-cleaner] Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
hokein updated this revision to Diff 471995.
hokein marked 2 inline comments as done.
hokein added a comment.

address comments around tests.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -8,6 +8,7 @@
 
 #include "clang-include-cleaner/Record.h"
 #include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
@@ -88,5 +89,62 @@
   EXPECT_THAT(Recorded.Roots, testing::ElementsAre(Named("x")));
 }
 
+class PragmaIncludeTest : public ::testing::Test {
+protected:
+  // We don't build an AST, we just run a preprocessor action!
+  TestInputs Inputs;
+  PragmaIncludes PI;
+
+  PragmaIncludeTest() {
+Inputs.MakeAction = [this] {
+  struct Hook : public PreprocessOnlyAction {
+  public:
+Hook(PragmaIncludes *Out) : Out(Out) {}
+bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+  Out->record(CI);
+  return true;
+}
+PragmaIncludes *Out;
+  };
+  return std::make_unique(&PI);
+};
+  }
+
+  TestAST build() { return TestAST(Inputs); }
+};
+
+TEST_F(PragmaIncludeTest, IWYUKeep) {
+  Inputs.Code = R"cpp(// Line 1
+#include "keep1.h" // IWYU pragma: keep
+#include "keep2.h" /* IWYU pragma: keep */
+#include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["keep1.h"] = Inputs.ExtraFiles["keep2.h"] =
+  Inputs.ExtraFiles["normal.h"] = "";
+
+  TestAST Processed = build();
+  EXPECT_FALSE(PI.shouldKeep(1));
+  EXPECT_TRUE(PI.shouldKeep(2));
+  EXPECT_TRUE(PI.shouldKeep(3));
+}
+
+TEST_F(PragmaIncludeTest, IWYUPrivate) {
+  Inputs.Code = R"cpp(
+#include "public.h"
+  )cpp";
+  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "public2.h"
+class Private {};
+  )cpp";
+  TestAST Processed = build();
+  auto PrivateFE = Processed.fileManager().getFile("private.h");
+  assert(PrivateFE);
+  EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
+  auto PublicFE = Processed.fileManager().getFile("public.h");
+  assert(PublicFE);
+  EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+}
+
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -11,9 +11,115 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 
 namespace clang::include_cleaner {
 
+// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
+// to share the code?
+static llvm::Optional parseIWYUPragma(const char *Text) {
+  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  Text += 2; // Skip the comment start, // or /*.
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
+class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler {
+public:
+  RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
+  : SM(CI.getSourceManager()), Out(Out) {}
+
+  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
+   SrcMgr::CharacteristicKind FileType,
+   FileID PrevFID) override {
+InMainFile = SM.isWrittenInMainFile(Loc);
+  }
+
+  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
+  llvm::StringRef FileName, bool IsAngled,
+  CharSourceRange /*FilenameRange*/,
+  Optional File,
+  llvm::StringRef /*SearchPath*/,
+  llvm::StringRef /*RelativePath*/,
+  const clang::Module * /*Imported*/,
+  SrcMgr::CharacteristicKind FileKind) override {
+if (!InMainFile)
+  return;
+int HashLine =
+SM.getLineNumber(SM.getMainFileID(), SM.getFileOffset(HashLoc));
+

[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

aaron.ballman wrote:
> mizvekov wrote:
> > aaron.ballman wrote:
> > > mizvekov wrote:
> > > > aaron.ballman wrote:
> > > > > mizvekov wrote:
> > > > > > aaron.ballman wrote:
> > > > > > > This looks like a benign typo -- we still match the line because 
> > > > > > > FileCheck will match partial lines, but I'm pretty sure nothing 
> > > > > > > in your patch would have necessitated this change. Then again, 
> > > > > > > you make this change in a lot of tests, so maybe I'm wrong -- in 
> > > > > > > which case, what changed?
> > > > > > What is happening here (and in all the other such instances) is 
> > > > > > that on the `import` case, this declaration stops being the last 
> > > > > > one on the TU. So the beginning of the line would match on `|-` 
> > > > > > instead of ``-`, but the non-import case this remains the last one.
> > > > > > 
> > > > > > So I simply relaxed the match.
> > > > > Hmmm, I think it'd help to show what new lines are now showing up so 
> > > > > we can validate that they make sense in context. WDYT?
> > > > It's the new lines from the synthesized `va_list_tag`. I think they 
> > > > would be noise on this these tests, they are testing something 
> > > > completely unrelated.
> > > > 
> > > > But they do show up on the ast-json tests where we are basically 
> > > > dumping the whole TU.
> > > Oh, so we're adding those to the *end* of the translation unit, not at 
> > > the beginning? 
> > We are adding them at the beginning, but it seems we import the other stuff 
> > before adding them, so on the import tests they show up on the end.
> > 
> > The thing here is that we end up importing them, but then adding new ones 
> > from the current Sema anyway. But this is fine as most other import things, 
> > they get separate declarations but merged in any case so they have the same 
> > canonical decl.
> > 
> > The way we avoid doing that for the other synthesized builtins around it, 
> > is that we just skip creating them if we find their `Identifier` has been 
> > created somehow, which is a fairly strange way to test this.
> > 
> > This seemed even less appropriate for `va_list_tag`, since some ABIs put it 
> > into `std` namespace.
> > 
> > And it seems to me that avoiding creating them again for the current Sema 
> > is a fairly minimal optimization, and it could make we miss diagnosing 
> > imports where those things are inconsistent between contexts.
> > 
> > WDYT?
> > We are adding them at the beginning, but it seems we import the other stuff 
> > before adding them, so on the import tests they show up on the end.
> 
> That really surprises me -- I thought we would export the AST in order and 
> import it in order. I'm a bit worried that out-of-order AST nodes may break 
> invariants.
> 
> > This seemed even less appropriate for va_list_tag, since some ABIs put it 
> > into std namespace.
> 
> Yeah, identifying things by name in the frontend is rarely a trivial 
> exercise, we try to avoid it whenever possible.
> 
> > And it seems to me that avoiding creating them again for the current Sema 
> > is a fairly minimal optimization, and it could make we miss diagnosing 
> > imports where those things are inconsistent between contexts.
> 
> Yeah, it doesn't strike me as a significant optimization to be worth worrying 
> about. My concern is more that we expect import order to match export order 
> and we're not matching up.
We are importing in the right order.

The problem is that we import the pch before we create the builtins here.

Ie look at what the test is doing, it first creates a TU, then imports it into 
an empty TU `/dev/null`.
In that last case, we end up adding the declaration for this Sema's 
`va_list_tag` after the imported stuff, but the one from the original context 
is still imported in the right order.

It doesn't seem problematic to me, but would you rather we changed the import 
order around wrt the creation of the builtins?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[PATCH] D137077: [Diagnostic] Clarify -Winfinite-recursion message

2022-10-31 Thread Aaron Ballman via Phabricator via cfe-commits
aaron.ballman requested changes to this revision.
aaron.ballman added a comment.
This revision now requires changes to proceed.

Thank you for the patch! However, I think this isn't an improvement to the 
diagnostic -- it's a cute phrase, but it doesn't help the programmer to 
understand what about their code needs to change.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D137077

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


[PATCH] D136886: [clang] ASTImporter: Fix importing of va_list types and declarations

2022-10-31 Thread Matheus Izvekov via Phabricator via cfe-commits
mizvekov added inline comments.



Comment at: clang/test/AST/ast-dump-overloaded-operators.cpp:27
 // CHECK-NEXT: | `-ParmVarDecl {{.*}}  col:19{{( imported)?}} 'E'
-// CHECK-NEXT: `-FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
+// CHECK-NEXT:  -FunctionDecl {{.*}}  line:14:6{{( 
imported)?}} test 'void ()'
 // CHECK-NEXT:   `-CompoundStmt {{.*}} 

mizvekov wrote:
> aaron.ballman wrote:
> > mizvekov wrote:
> > > aaron.ballman wrote:
> > > > mizvekov wrote:
> > > > > aaron.ballman wrote:
> > > > > > mizvekov wrote:
> > > > > > > aaron.ballman wrote:
> > > > > > > > This looks like a benign typo -- we still match the line 
> > > > > > > > because FileCheck will match partial lines, but I'm pretty sure 
> > > > > > > > nothing in your patch would have necessitated this change. Then 
> > > > > > > > again, you make this change in a lot of tests, so maybe I'm 
> > > > > > > > wrong -- in which case, what changed?
> > > > > > > What is happening here (and in all the other such instances) is 
> > > > > > > that on the `import` case, this declaration stops being the last 
> > > > > > > one on the TU. So the beginning of the line would match on `|-` 
> > > > > > > instead of ``-`, but the non-import case this remains the last 
> > > > > > > one.
> > > > > > > 
> > > > > > > So I simply relaxed the match.
> > > > > > Hmmm, I think it'd help to show what new lines are now showing up 
> > > > > > so we can validate that they make sense in context. WDYT?
> > > > > It's the new lines from the synthesized `va_list_tag`. I think they 
> > > > > would be noise on this these tests, they are testing something 
> > > > > completely unrelated.
> > > > > 
> > > > > But they do show up on the ast-json tests where we are basically 
> > > > > dumping the whole TU.
> > > > Oh, so we're adding those to the *end* of the translation unit, not at 
> > > > the beginning? 
> > > We are adding them at the beginning, but it seems we import the other 
> > > stuff before adding them, so on the import tests they show up on the end.
> > > 
> > > The thing here is that we end up importing them, but then adding new ones 
> > > from the current Sema anyway. But this is fine as most other import 
> > > things, they get separate declarations but merged in any case so they 
> > > have the same canonical decl.
> > > 
> > > The way we avoid doing that for the other synthesized builtins around it, 
> > > is that we just skip creating them if we find their `Identifier` has been 
> > > created somehow, which is a fairly strange way to test this.
> > > 
> > > This seemed even less appropriate for `va_list_tag`, since some ABIs put 
> > > it into `std` namespace.
> > > 
> > > And it seems to me that avoiding creating them again for the current Sema 
> > > is a fairly minimal optimization, and it could make we miss diagnosing 
> > > imports where those things are inconsistent between contexts.
> > > 
> > > WDYT?
> > > We are adding them at the beginning, but it seems we import the other 
> > > stuff before adding them, so on the import tests they show up on the end.
> > 
> > That really surprises me -- I thought we would export the AST in order and 
> > import it in order. I'm a bit worried that out-of-order AST nodes may break 
> > invariants.
> > 
> > > This seemed even less appropriate for va_list_tag, since some ABIs put it 
> > > into std namespace.
> > 
> > Yeah, identifying things by name in the frontend is rarely a trivial 
> > exercise, we try to avoid it whenever possible.
> > 
> > > And it seems to me that avoiding creating them again for the current Sema 
> > > is a fairly minimal optimization, and it could make we miss diagnosing 
> > > imports where those things are inconsistent between contexts.
> > 
> > Yeah, it doesn't strike me as a significant optimization to be worth 
> > worrying about. My concern is more that we expect import order to match 
> > export order and we're not matching up.
> We are importing in the right order.
> 
> The problem is that we import the pch before we create the builtins here.
> 
> Ie look at what the test is doing, it first creates a TU, then imports it 
> into an empty TU `/dev/null`.
> In that last case, we end up adding the declaration for this Sema's 
> `va_list_tag` after the imported stuff, but the one from the original context 
> is still imported in the right order.
> 
> It doesn't seem problematic to me, but would you rather we changed the import 
> order around wrt the creation of the builtins?
I think changing that order is weirder in fact, it would cause part of the 
current TU to come before the imported one, and then part afterwards.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136886

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


[clang-tools-extra] 9ab0827 - [include-cleaner] Add a data-structure to capture IWYU pragmas.

2022-10-31 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2022-10-31T15:21:24+01:00
New Revision: 9ab0827f70a524aa9f94995662d37675cd042f30

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

LOG: [include-cleaner] Add a data-structure to capture IWYU pragmas.

PragmaIncludes captures the pragma-based header-mapping information, it is used
in the "Location => Header" step to determine the final spelling header for a
symbol (rather than the header directive).

The structure is by design to be used inside the include-cleaner library
and clangd.

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

Added: 


Modified: 
clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
clang-tools-extra/include-cleaner/lib/Record.cpp
clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Removed: 




diff  --git 
a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h 
b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
index c5449b68b1f79..258d36141e5b0 100644
--- a/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
+++ b/clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
@@ -17,15 +17,64 @@
 #ifndef CLANG_INCLUDE_CLEANER_RECORD_H
 #define CLANG_INCLUDE_CLEANER_RECORD_H
 
+#include "llvm/ADT/DenseMap.h"
+#include "llvm/ADT/DenseSet.h"
+#include "llvm/Support/FileSystem/UniqueID.h"
 #include 
 #include 
 
 namespace clang {
 class ASTConsumer;
 class ASTContext;
+class CompilerInstance;
 class Decl;
+class FileEntry;
+
 namespace include_cleaner {
 
+/// Captures #include mapping information. It analyses IWYU Pragma comments and
+/// other use-instead-like mechanisms (#pragma include_instead) on included
+/// files.
+///
+/// This is a low-level piece being used in the "Location => Header" analysis
+/// step to determine the final public header rather than the header directly
+/// defines the symbol.
+class PragmaIncludes {
+public:
+  /// Installs an analysing PPCallback and CommentHandler and populates results
+  /// to the structure.
+  void record(const CompilerInstance &CI);
+
+  /// Returns true if the given #include of the main-file should never be
+  /// removed.
+  bool shouldKeep(unsigned HashLineNumber) const {
+return ShouldKeep.find(HashLineNumber) != ShouldKeep.end();
+  }
+
+  /// Returns the public mapping include for the given physical header file.
+  /// Returns "" if there is none.
+  llvm::StringRef getPublic(const FileEntry *File) const;
+
+private:
+  class RecordPragma;
+  /// 1-based Line numbers for the #include directives of the main file that
+  /// should always keep (e.g. has the `IWYU pragma: keep` or `IWYU pragma:
+  /// export` right after).
+  llvm::DenseSet ShouldKeep;
+
+  /// The public header mapping by the IWYU private pragma.
+  //
+  // !!NOTE: instead of using a FileEntry* to identify the physical file, we
+  // deliberately use the UniqueID to ensure the result is stable across
+  // FileManagers (for clangd's preamble and main-file builds).
+  llvm::DenseMap
+  IWYUPublic;
+
+  // FIXME: add other IWYU supports (export etc)
+  // FIXME: add support for clang use_instead pragma
+  // FIXME: add selfcontained file.
+};
+
 // Contains recorded parser events relevant to include-cleaner.
 struct RecordedAST {
   // The consumer (when installed into clang) tracks declarations in this.

diff  --git a/clang-tools-extra/include-cleaner/lib/Record.cpp 
b/clang-tools-extra/include-cleaner/lib/Record.cpp
index 88f9268eeb93c..ba691f46460a3 100644
--- a/clang-tools-extra/include-cleaner/lib/Record.cpp
+++ b/clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -11,9 +11,115 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 
 namespace clang::include_cleaner {
 
+// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to 
libTooling
+// to share the code?
+static llvm::Optional parseIWYUPragma(const char *Text) {
+  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  Text += 2; // Skip the comment start, // or /*.
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
+class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler 
{
+public:
+  RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
+  : SM(CI.getSourceManager()), Out(Out) {}
+
+  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
+   

[PATCH] D136071: [include-cleaner] Add PragmaIncludes which handles include-mapping pragmas.

2022-10-31 Thread Haojian Wu via Phabricator via cfe-commits
This revision was landed with ongoing or failed builds.
This revision was automatically updated to reflect the committed changes.
Closed by commit rG9ab0827f70a5: [include-cleaner] Add a data-structure to 
capture IWYU pragmas. (authored by hokein).

Changed prior to commit:
  https://reviews.llvm.org/D136071?vs=471995&id=471997#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D136071

Files:
  clang-tools-extra/include-cleaner/include/clang-include-cleaner/Record.h
  clang-tools-extra/include-cleaner/lib/Record.cpp
  clang-tools-extra/include-cleaner/unittests/RecordTest.cpp

Index: clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
===
--- clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
+++ clang-tools-extra/include-cleaner/unittests/RecordTest.cpp
@@ -8,6 +8,7 @@
 
 #include "clang-include-cleaner/Record.h"
 #include "clang/Frontend/FrontendAction.h"
+#include "clang/Frontend/FrontendActions.h"
 #include "clang/Testing/TestAST.h"
 #include "llvm/Support/raw_ostream.h"
 #include "gmock/gmock.h"
@@ -88,5 +89,63 @@
   EXPECT_THAT(Recorded.Roots, testing::ElementsAre(Named("x")));
 }
 
+class PragmaIncludeTest : public ::testing::Test {
+protected:
+  // We don't build an AST, we just run a preprocessor action!
+  TestInputs Inputs;
+  PragmaIncludes PI;
+
+  PragmaIncludeTest() {
+Inputs.MakeAction = [this] {
+  struct Hook : public PreprocessOnlyAction {
+  public:
+Hook(PragmaIncludes *Out) : Out(Out) {}
+bool BeginSourceFileAction(clang::CompilerInstance &CI) override {
+  Out->record(CI);
+  return true;
+}
+PragmaIncludes *Out;
+  };
+  return std::make_unique(&PI);
+};
+  }
+
+  TestAST build() { return TestAST(Inputs); }
+};
+
+TEST_F(PragmaIncludeTest, IWYUKeep) {
+  Inputs.Code = R"cpp(// Line 1
+#include "keep1.h" // IWYU pragma: keep
+#include "keep2.h" /* IWYU pragma: keep */
+#include "normal.h"
+  )cpp";
+  Inputs.ExtraFiles["keep1.h"] = Inputs.ExtraFiles["keep2.h"] =
+  Inputs.ExtraFiles["normal.h"] = "";
+
+  TestAST Processed = build();
+  EXPECT_FALSE(PI.shouldKeep(1));
+  EXPECT_TRUE(PI.shouldKeep(2));
+  EXPECT_TRUE(PI.shouldKeep(3));
+  EXPECT_FALSE(PI.shouldKeep(4));
+}
+
+TEST_F(PragmaIncludeTest, IWYUPrivate) {
+  Inputs.Code = R"cpp(
+#include "public.h"
+  )cpp";
+  Inputs.ExtraFiles["public.h"] = "#include \"private.h\"";
+  Inputs.ExtraFiles["private.h"] = R"cpp(
+// IWYU pragma: private, include "public2.h"
+class Private {};
+  )cpp";
+  TestAST Processed = build();
+  auto PrivateFE = Processed.fileManager().getFile("private.h");
+  assert(PrivateFE);
+  EXPECT_EQ(PI.getPublic(PrivateFE.get()), "\"public2.h\"");
+  auto PublicFE = Processed.fileManager().getFile("public.h");
+  assert(PublicFE);
+  EXPECT_EQ(PI.getPublic(PublicFE.get()), ""); // no mapping.
+}
+
 } // namespace
 } // namespace clang::include_cleaner
Index: clang-tools-extra/include-cleaner/lib/Record.cpp
===
--- clang-tools-extra/include-cleaner/lib/Record.cpp
+++ clang-tools-extra/include-cleaner/lib/Record.cpp
@@ -11,9 +11,115 @@
 #include "clang/AST/ASTContext.h"
 #include "clang/AST/DeclGroup.h"
 #include "clang/Basic/SourceManager.h"
+#include "clang/Frontend/CompilerInstance.h"
+#include "clang/Lex/PPCallbacks.h"
+#include "clang/Lex/Preprocessor.h"
 
 namespace clang::include_cleaner {
 
+// FIXME: this is a mirror of clang::clangd::parseIWYUPragma, move to libTooling
+// to share the code?
+static llvm::Optional parseIWYUPragma(const char *Text) {
+  assert(strncmp(Text, "//", 2) || strncmp(Text, "/*", 2));
+  constexpr llvm::StringLiteral IWYUPragma = " IWYU pragma: ";
+  Text += 2; // Skip the comment start, // or /*.
+  if (strncmp(Text, IWYUPragma.data(), IWYUPragma.size()))
+return llvm::None;
+  Text += IWYUPragma.size();
+  const char *End = Text;
+  while (*End != 0 && *End != '\n')
+++End;
+  return StringRef(Text, End - Text);
+}
+
+class PragmaIncludes::RecordPragma : public PPCallbacks, public CommentHandler {
+public:
+  RecordPragma(const CompilerInstance &CI, PragmaIncludes *Out)
+  : SM(CI.getSourceManager()), Out(Out) {}
+
+  void FileChanged(SourceLocation Loc, FileChangeReason Reason,
+   SrcMgr::CharacteristicKind FileType,
+   FileID PrevFID) override {
+InMainFile = SM.isWrittenInMainFile(Loc);
+  }
+
+  void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
+  llvm::StringRef FileName, bool IsAngled,
+  CharSourceRange /*FilenameRange*/,
+  Optional File,
+  llvm::StringRef /*SearchPath*/,
+  llvm::StringRef /*RelativePath*/,
+  const clang::Mod

  1   2   3   >