[PATCH] D155202: [clang][dataflow] Simplify implementation of `transferStdForwardCall()` in optional check.

2023-07-14 Thread Martin Böhme via Phabricator via cfe-commits
mboehme marked an inline comment as done.
mboehme added inline comments.



Comment at: 
clang/lib/Analysis/FlowSensitive/Models/UncheckedOptionalAccessModel.cpp:683
 
-  StorageLocation *LocRet = State.Env.getStorageLocation(*E, SkipPast::None);
-  if (LocRet != nullptr)
-return;
-
-  StorageLocation *LocArg =
-  State.Env.getStorageLocation(*E->getArg(0), SkipPast::Reference);
-
-  if (LocArg == nullptr)
-return;
-
-  Value *ValArg = State.Env.getValue(*LocArg);
-  if (ValArg == nullptr)
-ValArg = &createOptionalValue(State.Env.makeAtomicBoolValue(), State.Env);
-
-  // Create a new storage location
-  LocRet = &State.Env.createStorageLocation(*E);
-  State.Env.setStorageLocation(*E, *LocRet);
-
-  State.Env.setValue(*LocRet, *ValArg);
+  if (auto *Loc = State.Env.getStorageLocationStrict(*E->getArg(0)))
+State.Env.setStorageLocationStrict(*E, *Loc);

gribozavr2 wrote:
> Should we add an assert that it is not a value?
`getStorageLocationStrict` already contains such an assertion.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155202

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


[clang-tools-extra] 5649b24 - [clangd] Fix an assertion failure in NamedDecl::getName during the prepareRename

2023-07-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-07-14T09:17:46+02:00
New Revision: 5649b24c48ab3b48c1cb89155626a7f128c3f598

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

LOG: [clangd] Fix an assertion failure in NamedDecl::getName during the 
prepareRename

getName method required to be called on a simple-identifier NamedDecl,
otherwise it will trigger an assertion.

Reviewed By: kadircet

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

Added: 


Modified: 
clang-tools-extra/clangd/refactor/Rename.cpp
clang-tools-extra/clangd/unittests/RenameTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/refactor/Rename.cpp 
b/clang-tools-extra/clangd/refactor/Rename.cpp
index 97ea5e1836579c..11f9e4627af760 100644
--- a/clang-tools-extra/clangd/refactor/Rename.cpp
+++ b/clang-tools-extra/clangd/refactor/Rename.cpp
@@ -332,7 +332,8 @@ const NamedDecl 
*lookupSiblingWithinEnclosingScope(ASTContext &Ctx,
   return nullptr;
 for (const auto &Child : DS->getDeclGroup())
   if (const auto *ND = dyn_cast(Child))
-if (ND != &RenamedDecl && ND->getName() == Name)
+if (ND != &RenamedDecl && ND->getDeclName().isIdentifier() &&
+ND->getName() == Name)
   return ND;
 return nullptr;
   };

diff  --git a/clang-tools-extra/clangd/unittests/RenameTests.cpp 
b/clang-tools-extra/clangd/unittests/RenameTests.cpp
index 2414ff6b64c3f2..9cbf59684fbc10 100644
--- a/clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ b/clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1129,6 +1129,15 @@ TEST(RenameTest, Renameable) {
 using ns::^foo;
   )cpp",
"there are multiple symbols at the given location", !HeaderFile},
+
+  {R"cpp(
+void test() {
+  // no crash
+  using namespace std;
+  int [[V^ar]];
+}
+  )cpp",
+nullptr, !HeaderFile},
   };
 
   for (const auto& Case : Cases) {



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


[PATCH] D153617: [clangd] Fix an assertion failure in NamedDecl::getName during the prepareRename

2023-07-14 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 rG5649b24c48ab: [clangd] Fix an assertion failure in 
NamedDecl::getName during the prepareRename (authored by hokein).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153617

Files:
  clang-tools-extra/clangd/refactor/Rename.cpp
  clang-tools-extra/clangd/unittests/RenameTests.cpp


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1129,6 +1129,15 @@
 using ns::^foo;
   )cpp",
"there are multiple symbols at the given location", !HeaderFile},
+
+  {R"cpp(
+void test() {
+  // no crash
+  using namespace std;
+  int [[V^ar]];
+}
+  )cpp",
+nullptr, !HeaderFile},
   };
 
   for (const auto& Case : Cases) {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -332,7 +332,8 @@
   return nullptr;
 for (const auto &Child : DS->getDeclGroup())
   if (const auto *ND = dyn_cast(Child))
-if (ND != &RenamedDecl && ND->getName() == Name)
+if (ND != &RenamedDecl && ND->getDeclName().isIdentifier() &&
+ND->getName() == Name)
   return ND;
 return nullptr;
   };


Index: clang-tools-extra/clangd/unittests/RenameTests.cpp
===
--- clang-tools-extra/clangd/unittests/RenameTests.cpp
+++ clang-tools-extra/clangd/unittests/RenameTests.cpp
@@ -1129,6 +1129,15 @@
 using ns::^foo;
   )cpp",
"there are multiple symbols at the given location", !HeaderFile},
+
+  {R"cpp(
+void test() {
+  // no crash
+  using namespace std;
+  int [[V^ar]];
+}
+  )cpp",
+nullptr, !HeaderFile},
   };
 
   for (const auto& Case : Cases) {
Index: clang-tools-extra/clangd/refactor/Rename.cpp
===
--- clang-tools-extra/clangd/refactor/Rename.cpp
+++ clang-tools-extra/clangd/refactor/Rename.cpp
@@ -332,7 +332,8 @@
   return nullptr;
 for (const auto &Child : DS->getDeclGroup())
   if (const auto *ND = dyn_cast(Child))
-if (ND != &RenamedDecl && ND->getName() == Name)
+if (ND != &RenamedDecl && ND->getDeclName().isIdentifier() &&
+ND->getName() == Name)
   return ND;
 return nullptr;
   };
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta updated this revision to Diff 540301.
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

Files:
  clang/lib/Driver/Driver.cpp
  lld/COFF/Driver.cpp
  lld/COFF/Driver.h
  lld/test/COFF/print-search-paths.s


Index: lld/test/COFF/print-search-paths.s
===
--- lld/test/COFF/print-search-paths.s
+++ lld/test/COFF/print-search-paths.s
@@ -4,11 +4,17 @@
 # RUN: llvm-mc -triple i686-windows-msvc %s -filetype=obj -o %t_32.obj
 # RUN: lld-link -safeseh:no /dll /noentry /winsysroot:%t.dir/sysroot 
/vctoolsversion:1.1.1.1 /winsdkversion:10.0.1 %t_32.obj -print-search-paths | 
FileCheck -DSYSROOT=%t.dir -check-prefix=X86 %s
 # CHECK: Library search paths:
+# CHECK:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# CHECK:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# CHECK:   [[CPATH]]lib
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}um{{[/\\]}}x64
 # X86: Library search paths:
+# X86:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# X86:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# X86:   [[CPATH]]lib
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x86
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x86
Index: lld/COFF/Driver.h
===
--- lld/COFF/Driver.h
+++ lld/COFF/Driver.h
@@ -84,6 +84,8 @@
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string& argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 
Index: lld/COFF/Driver.cpp
===
--- lld/COFF/Driver.cpp
+++ lld/COFF/Driver.cpp
@@ -638,6 +638,31 @@
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string& argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by 
MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", 
std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), 
saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1544,6 +1569,7 @@
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
 addLibSearchPaths();
+  addClangLibSearchPaths(argsArr[0]);
 
   // Handle /ignore
   for (auto *arg : args.filtered(OPT_ignore)) {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -184,6 +184,8 @@
 // path of the embedding binary, which for LLVM binaries will be in bin/.
 // ../lib gets us to lib/ in both cases.
 P = llvm::sys::path::parent_path(Dir);
+// This search path is also created in the COFF driver of lld, so any
+// changes here also needs to happen in lld/COFF/Driver.cpp
 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
 CLANG_VERSION_MAJOR_STRING);
   }


Index: lld/test/COFF/print-sea

[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta updated this revision to Diff 540302.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

Files:
  clang/lib/Driver/Driver.cpp
  lld/COFF/Driver.cpp
  lld/COFF/Driver.h
  lld/test/COFF/print-search-paths.s


Index: lld/test/COFF/print-search-paths.s
===
--- lld/test/COFF/print-search-paths.s
+++ lld/test/COFF/print-search-paths.s
@@ -4,11 +4,17 @@
 # RUN: llvm-mc -triple i686-windows-msvc %s -filetype=obj -o %t_32.obj
 # RUN: lld-link -safeseh:no /dll /noentry /winsysroot:%t.dir/sysroot 
/vctoolsversion:1.1.1.1 /winsdkversion:10.0.1 %t_32.obj -print-search-paths | 
FileCheck -DSYSROOT=%t.dir -check-prefix=X86 %s
 # CHECK: Library search paths:
+# CHECK:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# CHECK:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# CHECK:   [[CPATH]]lib
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}um{{[/\\]}}x64
 # X86: Library search paths:
+# X86:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# X86:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# X86:   [[CPATH]]lib
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x86
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x86
Index: lld/COFF/Driver.h
===
--- lld/COFF/Driver.h
+++ lld/COFF/Driver.h
@@ -84,6 +84,8 @@
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string& argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 
Index: lld/COFF/Driver.cpp
===
--- lld/COFF/Driver.cpp
+++ lld/COFF/Driver.cpp
@@ -638,6 +638,31 @@
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by 
MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", 
std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), 
saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1544,6 +1569,7 @@
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
 addLibSearchPaths();
+  addClangLibSearchPaths(argsArr[0]);
 
   // Handle /ignore
   for (auto *arg : args.filtered(OPT_ignore)) {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -184,6 +184,8 @@
 // path of the embedding binary, which for LLVM binaries will be in bin/.
 // ../lib gets us to lib/ in both cases.
 P = llvm::sys::path::parent_path(Dir);
+// This search path is also created in the COFF driver of lld, so any
+// changes here also needs to happen in lld/COFF/Driver.cpp
 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
 CLANG_VERSION_MAJOR_STRING);
   }


Index: lld/test/COFF/print-search-paths.s
===

[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta updated this revision to Diff 540304.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

Files:
  clang/lib/Driver/Driver.cpp
  lld/COFF/Driver.cpp
  lld/COFF/Driver.h
  lld/test/COFF/print-search-paths.s


Index: lld/test/COFF/print-search-paths.s
===
--- lld/test/COFF/print-search-paths.s
+++ lld/test/COFF/print-search-paths.s
@@ -4,11 +4,17 @@
 # RUN: llvm-mc -triple i686-windows-msvc %s -filetype=obj -o %t_32.obj
 # RUN: lld-link -safeseh:no /dll /noentry /winsysroot:%t.dir/sysroot 
/vctoolsversion:1.1.1.1 /winsdkversion:10.0.1 %t_32.obj -print-search-paths | 
FileCheck -DSYSROOT=%t.dir -check-prefix=X86 %s
 # CHECK: Library search paths:
+# CHECK:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# CHECK:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# CHECK:   [[CPATH]]lib
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}um{{[/\\]}}x64
 # X86: Library search paths:
+# X86:   
[[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# X86:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# X86:   [[CPATH]]lib
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x86
 # X86:   
[[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows 
Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x86
Index: lld/COFF/Driver.h
===
--- lld/COFF/Driver.h
+++ lld/COFF/Driver.h
@@ -84,6 +84,8 @@
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string &argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 
Index: lld/COFF/Driver.cpp
===
--- lld/COFF/Driver.cpp
+++ lld/COFF/Driver.cpp
@@ -638,6 +638,31 @@
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by 
MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", 
std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), 
saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1544,6 +1569,7 @@
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
 addLibSearchPaths();
+  addClangLibSearchPaths(argsArr[0]);
 
   // Handle /ignore
   for (auto *arg : args.filtered(OPT_ignore)) {
Index: clang/lib/Driver/Driver.cpp
===
--- clang/lib/Driver/Driver.cpp
+++ clang/lib/Driver/Driver.cpp
@@ -184,6 +184,8 @@
 // path of the embedding binary, which for LLVM binaries will be in bin/.
 // ../lib gets us to lib/ in both cases.
 P = llvm::sys::path::parent_path(Dir);
+// This search path is also created in the COFF driver of lld, so any
+// changes here also needs to happen in lld/COFF/Driver.cpp
 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
 CLANG_VERSION_MAJOR_STRING);
   }


Index: lld/test/COFF/print-search-paths.s
===

[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta marked 6 inline comments as done.
thieta added a comment.

- Split the relative patch to this diff https://reviews.llvm.org/D155268
- Added some comments in both Clang and LLD
- Fixed some code style.
- Removed stray changes.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

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


[PATCH] D155217: [clang-tidy][include-cleaner] Don't warn for the same symbol twice

2023-07-14 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo added a comment.

Hi Alex,

Thank you for the patch.
We are aware that issuing one diagnostic per symbol reference might be 
overwhelming. However, we have decided to choose it over other options after 
considering the use cases that we'd like to cover.
This check is intended to be used in review tooling, where the user usually 
only sees their own change/diff. Issuing only one diagnostic for the first 
symbol reference would render this check mostly useless in code review, since 
the first symbol reference is not in the scope of the user's change most of the 
time.

Moreover, it's desirable to have similar behavior in include-cleaner checks 
across multiple clang tools. The current behaviour corresponds to the behaviour 
of built-in include-cleaner in clangd for similar reasons, i.e., users are most 
prone to act on a finding if it shows up in the piece of code they're currently 
editing.

The currently ongoing cleanup efforts should help the make the findings less 
overwhelming as well.


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

https://reviews.llvm.org/D155217

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


[clang-tools-extra] 7a328cf - [include-cleaner] Bail out in the standalone tool for invalid ignore-headers

2023-07-14 Thread Haojian Wu via cfe-commits

Author: Haojian Wu
Date: 2023-07-14T10:05:22+02:00
New Revision: 7a328cf539b38484218a0eb902611c69cfba7981

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

LOG: [include-cleaner] Bail out in the standalone tool for invalid 
ignore-headers
flag

Added: 


Modified: 
clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp

Removed: 




diff  --git a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp 
b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
index c6cd7995d2e829..ae4d1e97414415 100644
--- a/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
+++ b/clang-tools-extra/include-cleaner/tool/IncludeCleaner.cpp
@@ -271,6 +271,8 @@ int main(int argc, const char **argv) {
 }
   }
   auto HeaderFilter = headerFilter();
+  if (!HeaderFilter)
+return 1; // error already reported.
   ActionFactory Factory(HeaderFilter);
   return clang::tooling::ClangTool(OptionsParser->getCompilations(),
OptionsParser->getSourcePathList())



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


[clang] 8fe0449 - [RISCV] Fix required features checking with empty string

2023-07-14 Thread Jim Lin via cfe-commits

Author: Jim Lin
Date: 2023-07-14T16:09:11+08:00
New Revision: 8fe0449ac99087c74f785ddbdd4fbba65b396b3b

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

LOG: [RISCV] Fix required features checking with empty string

In our downstream, we define some intrinsics that don't require any
extra extension enabled. Such as

TARGET_BUILTIN(__builtin_riscv_xxx, "LiLi", "nc", "")

But `split` function's `KeepEmpty` argument is True. Got the error message

error: builtin requires at least one of the following extensions support to be 
enabled : ''

when we use our customized intrinsic.

Reviewed By: craig.topper, wangpc

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

Added: 


Modified: 
clang/lib/Sema/SemaChecking.cpp

Removed: 




diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 392062ea64a1fc..f9a50f6ef3be6f 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -4481,7 +4481,7 @@ bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo 
&TI,
   bool FeatureMissing = false;
   SmallVector ReqFeatures;
   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
-  Features.split(ReqFeatures, ',');
+  Features.split(ReqFeatures, ',', -1, false);
 
   // Check if each required feature is included
   for (StringRef F : ReqFeatures) {



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


[PATCH] D154596: [RISCV] Fix required features checking with empty string

2023-07-14 Thread Jim Lin 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 rG8fe0449ac990: [RISCV] Fix required features checking with 
empty string (authored by Jim).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154596

Files:
  clang/lib/Sema/SemaChecking.cpp


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -4481,7 +4481,7 @@
   bool FeatureMissing = false;
   SmallVector ReqFeatures;
   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
-  Features.split(ReqFeatures, ',');
+  Features.split(ReqFeatures, ',', -1, false);
 
   // Check if each required feature is included
   for (StringRef F : ReqFeatures) {


Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -4481,7 +4481,7 @@
   bool FeatureMissing = false;
   SmallVector ReqFeatures;
   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
-  Features.split(ReqFeatures, ',');
+  Features.split(ReqFeatures, ',', -1, false);
 
   // Check if each required feature is included
   for (StringRef F : ReqFeatures) {
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D155270: [clang][Interp] Basic support for bit fields

2023-07-14 Thread Timm Bäder via Phabricator via cfe-commits
tbaeder created this revision.
tbaeder added reviewers: aaron.ballman, erichkeane, shafik, cor3ntin.
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/D155270

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

Index: clang/test/AST/Interp/bitfields.cpp
===
--- /dev/null
+++ clang/test/AST/Interp/bitfields.cpp
@@ -0,0 +1,34 @@
+// RUN: %clang_cc1 -fexperimental-new-constant-interpreter -Wno-bitfield-constant-conversion -verify %s
+// RUN: %clang_cc1 -verify=ref -Wno-bitfield-constant-conversion %s
+
+
+namespace Basic {
+  struct A {
+unsigned int a : 2;
+constexpr A() : a(0) {}
+constexpr A(int a) : a(a) {}
+  };
+
+  constexpr A a{1};
+  static_assert(a.a == 1, "");
+
+  constexpr A a2{10};
+  static_assert(a2.a == 2, "");
+
+
+  constexpr int storeA() {
+A a;
+a.a = 10;
+
+return a.a;
+  }
+  static_assert(storeA() == 2, "");
+
+  constexpr int storeA2() {
+A a;
+return a.a = 10;
+  }
+  static_assert(storeA2() == 2, "");
+
+  // TODO: +=, -=, etc. operators.
+}
Index: clang/lib/AST/Interp/Record.h
===
--- clang/lib/AST/Interp/Record.h
+++ clang/lib/AST/Interp/Record.h
@@ -29,6 +29,7 @@
 const FieldDecl *Decl;
 unsigned Offset;
 Descriptor *Desc;
+bool isBitField() const { return Decl->isBitField(); }
   };
 
   /// Describes a base class.
Index: clang/lib/AST/Interp/Interp.h
===
--- clang/lib/AST/Interp/Interp.h
+++ clang/lib/AST/Interp/Interp.h
@@ -965,6 +965,7 @@
 
 template ::T>
 bool InitThisBitField(InterpState &S, CodePtr OpPC, const Record::Field *F) {
+  assert(F->isBitField());
   if (S.checkingPotentialConstantExpression())
 return false;
   const Pointer &This = S.Current->getThis();
@@ -1006,8 +1007,9 @@
 
 template ::T>
 bool InitBitField(InterpState &S, CodePtr OpPC, const Record::Field *F) {
+  assert(F->isBitField());
   const T &Value = S.Stk.pop();
-  const Pointer &Field = S.Stk.pop().atField(F->Offset);
+  const Pointer &Field = S.Stk.peek().atField(F->Offset);
   Field.deref() = Value.truncate(F->Decl->getBitWidthValue(S.getCtx()));
   Field.activate();
   Field.initialize();
@@ -1205,11 +1207,10 @@
 return false;
   if (!Ptr.isRoot())
 Ptr.initialize();
-  if (auto *FD = Ptr.getField()) {
+  if (const auto *FD = Ptr.getField())
 Ptr.deref() = Value.truncate(FD->getBitWidthValue(S.getCtx()));
-  } else {
+  else
 Ptr.deref() = Value;
-  }
   return true;
 }
 
@@ -1221,11 +1222,10 @@
 return false;
   if (!Ptr.isRoot())
 Ptr.initialize();
-  if (auto *FD = Ptr.getField()) {
+  if (const auto *FD = Ptr.getField())
 Ptr.deref() = Value.truncate(FD->getBitWidthValue(S.getCtx()));
-  } else {
+  else
 Ptr.deref() = Value;
-  }
   return true;
 }
 
Index: clang/lib/AST/Interp/ByteCodeStmtGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeStmtGen.cpp
+++ clang/lib/AST/Interp/ByteCodeStmtGen.cpp
@@ -113,8 +113,13 @@
   if (!this->visit(InitExpr))
 return false;
 
-  if (!this->emitInitThisField(*T, F->Offset, InitExpr))
-return false;
+  if (F->isBitField()) {
+if (!this->emitInitThisBitField(*T, F, InitExpr))
+  return false;
+  } else {
+if (!this->emitInitThisField(*T, F->Offset, InitExpr))
+  return false;
+  }
 } else {
   // Non-primitive case. Get a pointer to the field-to-initialize
   // on the stack and call visitInitialzer() for it.
Index: clang/lib/AST/Interp/ByteCodeExprGen.cpp
===
--- clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -282,8 +282,10 @@
 return Discard(this->emitDiv(*T, BO));
   case BO_Assign:
 if (DiscardResult)
-  return this->emitStorePop(*T, BO);
-return this->emitStore(*T, BO);
+  return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
+ : this->emitStorePop(*T, BO);
+return LHS->refersToBitField() ? this->emitStoreBitField(*T, BO)
+   : this->emitStore(*T, BO);
   case BO_And:
 return Discard(this->emitBitAnd(*T, BO));
   case BO_Or:
@@ -1474,8 +1476,13 @@
 if (!this->visit(Init))
   return false;
 
-if (!this->emitInitField(*T, FieldToInit->Offset, Initializer))
-  return false;
+if (FieldToInit->isBitField()) {
+  if (!this->emitInitBitFiel

[clang] 61e0822 - [llvm][clang] Remove uses of isOpaquePointerTy() (NFC)

2023-07-14 Thread Nikita Popov via cfe-commits

Author: Nikita Popov
Date: 2023-07-14T10:27:58+02:00
New Revision: 61e0822efab14dd922f9c3ee479a0a51952526d9

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

LOG: [llvm][clang] Remove uses of isOpaquePointerTy() (NFC)

This now always returns true (for pointer types).

Added: 


Modified: 
clang/lib/CodeGen/CGCall.h
llvm/lib/Analysis/InstructionSimplify.cpp
llvm/lib/AsmParser/LLParser.cpp
llvm/lib/Bitcode/Reader/BitcodeReader.cpp
llvm/lib/FuzzMutate/Operations.cpp
llvm/lib/FuzzMutate/RandomIRBuilder.cpp
llvm/lib/IR/Core.cpp
llvm/lib/Transforms/Coroutines/Coroutines.cpp
llvm/lib/Transforms/Scalar/GVN.cpp
llvm/lib/Transforms/Scalar/SROA.cpp
llvm/tools/llvm-stress/llvm-stress.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGCall.h b/clang/lib/CodeGen/CGCall.h
index 824f0a9a882990..eaaf10c4eec687 100644
--- a/clang/lib/CodeGen/CGCall.h
+++ b/clang/lib/CodeGen/CGCall.h
@@ -109,9 +109,6 @@ class CGCallee {
 AbstractInfo = abstractInfo;
 assert(functionPtr && "configuring callee without function pointer");
 assert(functionPtr->getType()->isPointerTy());
-assert(functionPtr->getType()->isOpaquePointerTy() ||
-   functionPtr->getType()->getNonOpaquePointerElementType()
-   ->isFunctionTy());
   }
 
   static CGCallee forBuiltin(unsigned builtinID,

diff  --git a/llvm/lib/Analysis/InstructionSimplify.cpp 
b/llvm/lib/Analysis/InstructionSimplify.cpp
index 038268d0705f85..6cc919afa0285f 100644
--- a/llvm/lib/Analysis/InstructionSimplify.cpp
+++ b/llvm/lib/Analysis/InstructionSimplify.cpp
@@ -4888,10 +4888,8 @@ static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
 }
   }
 
-  // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
-  // it may be equivalent to a bitcast.
-  if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
-  Ptr->getType() == GEPTy &&
+  // All-zero GEP is a no-op, unless it performs a vector splat.
+  if (Ptr->getType() == GEPTy &&
   all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
 return Ptr;
 

diff  --git a/llvm/lib/AsmParser/LLParser.cpp b/llvm/lib/AsmParser/LLParser.cpp
index dcb3476a2d840a..ed9e1d6ebfa210 100644
--- a/llvm/lib/AsmParser/LLParser.cpp
+++ b/llvm/lib/AsmParser/LLParser.cpp
@@ -2675,7 +2675,7 @@ bool LLParser::parseType(Type *&Result, const Twine &Msg, 
bool AllowVoid) {
 // Handle "ptr" opaque pointer type.
 //
 // Type ::= ptr ('addrspace' '(' uint32 ')')?
-if (Result->isOpaquePointerTy()) {
+if (Result->isPointerTy()) {
   unsigned AddrSpace;
   if (parseOptionalAddrSpace(AddrSpace))
 return true;

diff  --git a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp 
b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
index c31f2afadc516f..4095545240ca11 100644
--- a/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
+++ b/llvm/lib/Bitcode/Reader/BitcodeReader.cpp
@@ -1381,17 +1381,6 @@ unsigned BitcodeReader::getVirtualTypeID(Type *Ty,
 return It->second;
   }
 
-#ifndef NDEBUG
-  if (!Ty->isOpaquePointerTy()) {
-assert(Ty->getNumContainedTypes() == ChildTypeIDs.size() &&
-   "Wrong number of contained types");
-for (auto Pair : zip(Ty->subtypes(), ChildTypeIDs)) {
-  assert(std::get<0>(Pair) == getTypeByID(std::get<1>(Pair)) &&
- "Incorrect contained type ID");
-}
-  }
-#endif
-
   unsigned TypeID = TypeList.size();
   TypeList.push_back(Ty);
   if (!ChildTypeIDs.empty())

diff  --git a/llvm/lib/FuzzMutate/Operations.cpp 
b/llvm/lib/FuzzMutate/Operations.cpp
index 48455c781629f2..408f35879acd3b 100644
--- a/llvm/lib/FuzzMutate/Operations.cpp
+++ b/llvm/lib/FuzzMutate/Operations.cpp
@@ -196,9 +196,7 @@ OpDescriptor llvm::fuzzerop::gepDescriptor(unsigned Weight) 
{
   auto buildGEP = [](ArrayRef Srcs, Instruction *Inst) {
 // TODO: It would be better to generate a random type here, rather than
 // generating a random value and picking its type.
-Type *Ty = Srcs[0]->getType()->isOpaquePointerTy()
-   ? Srcs[1]->getType()
-   : Srcs[0]->getType()->getNonOpaquePointerElementType();
+Type *Ty = Srcs[1]->getType();
 auto Indices = ArrayRef(Srcs).drop_front(2);
 return GetElementPtrInst::Create(Ty, Srcs[0], Indices, "G", Inst);
   };

diff  --git a/llvm/lib/FuzzMutate/RandomIRBuilder.cpp 
b/llvm/lib/FuzzMutate/RandomIRBuilder.cpp
index bbacfedf456d37..548ba7956fd5a1 100644
--- a/llvm/lib/FuzzMutate/RandomIRBuilder.cpp
+++ b/llvm/lib/FuzzMutate/RandomIRBuilder.cpp
@@ -211,10 +211,8 @@ Value *RandomIRBuilder::newSource(BasicBlock &BB, 
ArrayRef Insts,
   IP = ++I->getIterator();
   assert(IP != BB.end() && "guaranteed by the findPointer");
 }
-// For opaque pointers, pick the type independently.
-T

[PATCH] D155273: [clang-format] Add TypeNames option to disambiguate types/objects

2023-07-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan created this revision.
Herald added projects: All, clang, clang-format.
Herald added a subscriber: cfe-commits.
Herald added reviewers: rymiel, HazardyKnusperkeks, MyDeveloperDay.
owenpan requested review of this revision.

If a non-keyword identifier is found in `TypeNames`, then a `*`, `&`, or `&&` 
that follows it is annotated as `TT_PointerOrReference`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155273

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/include/clang/Format/Format.h
  clang/lib/Format/Format.cpp
  clang/lib/Format/FormatToken.h
  clang/lib/Format/FormatTokenLexer.cpp
  clang/lib/Format/FormatTokenLexer.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -272,6 +272,19 @@
   Tokens = annotate("template * = nullptr> void f();");
   ASSERT_EQ(Tokens.size(), 19u) << Tokens;
   EXPECT_TOKEN(Tokens[5], tok::ampamp, TT_BinaryOperator);
+
+  FormatStyle Style = getLLVMStyle();
+  Style.TypeNames.push_back("MYI");
+  Tokens = annotate("if (MYI *p{nullptr})", Style);
+  ASSERT_EQ(Tokens.size(), 10u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_TypeName);
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);
+
+  Style.TypeNames.push_back("Class");
+  Tokens = annotate("if (Class *obj {getObj()})", Style);
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;
+  EXPECT_TOKEN(Tokens[2], tok::identifier, TT_TypeName);
+  EXPECT_TOKEN(Tokens[3], tok::star, TT_PointerOrReference);
 }
 
 TEST_F(TokenAnnotatorTest, UnderstandsUsesOfPlusAndMinus) {
Index: clang/lib/Format/TokenAnnotator.cpp
===
--- clang/lib/Format/TokenAnnotator.cpp
+++ clang/lib/Format/TokenAnnotator.cpp
@@ -422,6 +422,7 @@
   FormatToken *PrevPrev = Prev->getPreviousNonComment();
   FormatToken *Next = CurrentToken->Next;
   if (PrevPrev && PrevPrev->is(tok::identifier) &&
+  PrevPrev->isNot(TT_TypeName) &&
   Prev->isOneOf(tok::star, tok::amp, tok::ampamp) &&
   CurrentToken->is(tok::identifier) && Next->isNot(tok::equal)) {
 Prev->setType(TT_BinaryOperator);
@@ -2508,6 +2509,8 @@
 const FormatToken *PrevToken = Tok.getPreviousNonComment();
 if (!PrevToken)
   return TT_UnaryOperator;
+if (PrevToken->is(TT_TypeName))
+  return TT_PointerOrReference;
 
 const FormatToken *NextToken = Tok.getNextNonComment();
 
Index: clang/lib/Format/FormatTokenLexer.h
===
--- clang/lib/Format/FormatTokenLexer.h
+++ clang/lib/Format/FormatTokenLexer.h
@@ -22,6 +22,7 @@
 #include "clang/Basic/SourceManager.h"
 #include "clang/Format/Format.h"
 #include "llvm/ADT/MapVector.h"
+#include "llvm/ADT/SmallPtrSet.h"
 #include "llvm/ADT/StringSet.h"
 #include "llvm/Support/Regex.h"
 
@@ -126,6 +127,8 @@
 
   llvm::SmallMapVector Macros;
 
+  llvm::SmallPtrSet TypeNames;
+
   bool FormattingDisabled;
 
   llvm::Regex MacroBlockBeginRegex;
Index: clang/lib/Format/FormatTokenLexer.cpp
===
--- clang/lib/Format/FormatTokenLexer.cpp
+++ clang/lib/Format/FormatTokenLexer.cpp
@@ -71,6 +71,9 @@
 auto Identifier = &IdentTable.get(StatementAttributeLikeMacro);
 Macros.insert({Identifier, TT_StatementAttributeLikeMacro});
   }
+
+  for (const auto &TypeName : Style.TypeNames)
+TypeNames.insert(&IdentTable.get(TypeName));
 }
 
 ArrayRef FormatTokenLexer::lex() {
@@ -1222,7 +1225,8 @@
   }
 
   if (Style.isCpp()) {
-auto it = Macros.find(FormatTok->Tok.getIdentifierInfo());
+auto *Identifier = FormatTok->Tok.getIdentifierInfo();
+auto it = Macros.find(Identifier);
 if (!(Tokens.size() > 0 && Tokens.back()->Tok.getIdentifierInfo() &&
   Tokens.back()->Tok.getIdentifierInfo()->getPPKeywordID() ==
   tok::pp_define) &&
@@ -1240,6 +1244,8 @@
 FormatTok->setType(TT_MacroBlockBegin);
   else if (MacroBlockEndRegex.match(Text))
 FormatTok->setType(TT_MacroBlockEnd);
+  else if (TypeNames.contains(Identifier))
+FormatTok->setFinalizedType(TT_TypeName);
 }
   }
 
Index: clang/lib/Format/FormatToken.h
===
--- clang/lib/Format/FormatToken.h
+++ clang/lib/Format/FormatToken.h
@@ -141,6 +141,7 @@
   TYPE(TrailingReturnArrow)\
   TYPE(TrailingUnaryOperator)  \
   TYPE(TypeDeclarationParen)   \
+  TYPE(TypeName)   \
   TYPE

[PATCH] D155215: [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 540321.
VitaNuo added a comment.

Re-use the logic from include cleaner in clangd.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155215

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp


Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2299,7 +2299,7 @@
 
 TEST(FindReferences, UsedSymbolsFromInclude) {
   const char *Tests[] = {
-  R"cpp([[#include ^"bar.h"]]
+  R"cpp(   [[#include   ^"bar.h"]]
 #include 
 int fstBar = [[bar1]]();
 int sndBar = [[bar2]]();
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1362,10 +1362,9 @@
 return std::nullopt;
 
   // Add the #include line to the references list.
-  auto IncludeLen = std::string{"#include"}.length() + Inc.Written.length() + 
1;
   ReferencesResult::Reference Result;
-  Result.Loc.range = clangd::Range{Position{Inc.HashLine, 0},
-   Position{Inc.HashLine, (int)IncludeLen}};
+  Result.Loc.range =
+  getIncludeRange(SM.getBufferData(SM.getMainFileID()), Inc.HashOffset);
   Result.Loc.uri = URIMainFile;
   Results.References.push_back(std::move(Result));
 
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -21,6 +21,7 @@
 #include "Diagnostics.h"
 #include "Headers.h"
 #include "ParsedAST.h"
+#include "Protocol.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Syntax/Tokens.h"
@@ -82,6 +83,10 @@
 std::optional
 firstMatchedProvider(const include_cleaner::Includes &Includes,
  llvm::ArrayRef Providers);
+
+// Returns the range starting at '#' and ending at EOL. Escaped newlines are 
not
+// handled.
+clangd::Range getIncludeRange(llvm::StringRef Code, unsigned HashOffset);
 } // namespace clangd
 } // namespace clang
 
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -58,11 +58,7 @@
 static bool AnalyzeStdlib = false;
 void setIncludeCleanerAnalyzesStdlib(bool B) { AnalyzeStdlib = B; }
 
-namespace {
-
-// Returns the range starting at '#' and ending at EOL. Escaped newlines are 
not
-// handled.
-clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) {
+clangd::Range getIncludeRange(llvm::StringRef Code, unsigned HashOffset) {
   clangd::Range Result;
   Result.end = Result.start = offsetToPosition(Code, HashOffset);
 
@@ -74,6 +70,8 @@
   return Result;
 }
 
+namespace {
+
 bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter IgnoreHeaders) {
   // Convert the path to Unix slashes and try to match against the filter.
   llvm::SmallString<64> NormalizedPath(HeaderPath);
@@ -224,7 +222,7 @@
 D.InsideMainFile = true;
 D.Severity = DiagnosticsEngine::Warning;
 D.Tags.push_back(Unnecessary);
-D.Range = getDiagnosticRange(Code, Inc->HashOffset);
+D.Range = getIncludeRange(Code, Inc->HashOffset);
 // FIXME(kirillbobyrev): Removing inclusion might break the code if the
 // used headers are only reachable transitively through this one. Suggest
 // including them directly instead.


Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2299,7 +2299,7 @@
 
 TEST(FindReferences, UsedSymbolsFromInclude) {
   const char *Tests[] = {
-  R"cpp([[#include ^"bar.h"]]
+  R"cpp(   [[#include   ^"bar.h"]]
 #include 
 int fstBar = [[bar1]]();
 int sndBar = [[bar2]]();
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1362,10 +1362,9 @@
 return std::nullopt;
 
   // Add the #include line to the references list.
-  auto IncludeLen = std::string{"#include"}.length() + Inc.Written.length() + 1;
   ReferencesResult::Reference Result;
-  Result.Loc.range = clangd::Range{Position{Inc.HashLine, 0},
-   Position{Inc.HashLine, (int)IncludeLen}};
+  Result.Loc.range =
+  getIncludeRange(SM.

[PATCH] D155273: [clang-format] Add TypeNames option to disambiguate types/objects

2023-07-14 Thread Owen Pan via Phabricator via cfe-commits
owenpan added inline comments.



Comment at: clang/unittests/Format/TokenAnnotatorTest.cpp:284
+  Style.TypeNames.push_back("Class");
+  Tokens = annotate("if (Class *obj {getObj()})", Style);
+  ASSERT_EQ(Tokens.size(), 12u) << Tokens;

This test case comes from D137327.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155273

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


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-14 Thread Christian Walther via Phabricator via cfe-commits
cwalther added a comment.

Thank you!

So I guess next time I submit a patch here (nothing planned at the moment), I 
should put the proposed commit message into the summary field and the backstory 
and start of discussion / open questions into a first comment. But maybe the 
point is moot as I understand you are about to move to GitHub pull requests, 
which I am more familiar with.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154357

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


[PATCH] D155273: [clang-format] Add TypeNames option to disambiguate types/objects

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta added a comment.

Thanks for doing this!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155273

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


[PATCH] D155173: [clangd] Refine the workflow for diagnostic Fixits.

2023-07-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet added inline comments.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:671
+  // FIMXE: this is tricky
+  llvm::StringRef(LSPDiag.Message)
+  .starts_with_insensitive(Diag.Message))

this is tricky indeed and conceptually really hard to achieve inside 
ClangdServer layer.

what about keeping the cache in ClangdLSPServer, but changing the format? 
Similar to `TweakRef`, we now have a `DiagRef`, which is ClangdServer-native. 
So we can keep a cache from `(FilePath, clangd::Diagnostic)` to 
`clangd::DiagRef`, and pass those `DiagRef`s to `ClangdServer` and make sure 
we're doing the search for sure on the right domain here?

this also gives us the flexibility to change the definition of a `DiagRef` in 
the future.



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:683
+  // Return immediately if this is a quick-fix-only codeAction request.
+  if (Params.RequestedActionKinds.size() == 1)
+return CB(std::move(Results));

we can have quick fix kind tweaks too (e.g. populate switch)



Comment at: clang-tools-extra/clangd/ClangdServer.cpp:714-715
   // Tracks number of times a tweak has been offered.
   static constexpr trace::Metric TweakAvailable(
   "tweak_available", trace::Metric::Counter, "tweak_id");
   auto Action = [Sel, CB = std::move(CB), Filter = std::move(Filter),

can you also move this counter to global scope and use it in `::codeAction` too?



Comment at: clang-tools-extra/clangd/ClangdServer.h:387
+  void codeAction(const CodeActionInputs &Inputs,
+  Callback> CB);
+

maybe a more structured output can be useful here:
```
struct CodeActionResult {
  std::string Version; // Version of content results belong to.
  struct QuickFix {
  DiagRef D; // Diagnostic being addressed by the fix.
  Fix F;
  };
  std::vector QuickFixes;
  std::vector TweakRefs;
};
```


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155173

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


[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo accepted this revision.
mstorsjo added a comment.

LGTM, thanks!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

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


[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Martin Storsjö via Phabricator via cfe-commits
mstorsjo added a comment.

Maybe add a release note for this too? It's rather significant.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

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


[PATCH] D155215: [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Kadir Cetinkaya via Phabricator via cfe-commits
kadircet accepted this revision.
kadircet added inline comments.
This revision is now accepted and ready to land.



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:87
+
+// Returns the range starting at '#' and ending at EOL. Escaped newlines are 
not
+// handled.

nit: convention is to use `///` for public documentation (as some tools don't 
export rest for public docs)



Comment at: clang-tools-extra/clangd/IncludeCleaner.h:89
+// handled.
+clangd::Range getIncludeRange(llvm::StringRef Code, unsigned HashOffset);
 } // namespace clangd

FWIW, this function has nothing specific about includes. what about renaming it 
to `rangeTillEOL(llvm::StringRef Code, unsigned Offset); // Returns the Range 
starting at Offset and spanning the whole line.` and moving it to 
`SourceCode.h`?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155215

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


[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via Phabricator via cfe-commits
thieta updated this revision to Diff 540344.

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

Files:
  clang/lib/Driver/Driver.cpp
  lld/COFF/Driver.cpp
  lld/COFF/Driver.h
  lld/docs/ReleaseNotes.rst
  lld/test/COFF/print-search-paths.s

Index: lld/test/COFF/print-search-paths.s
===
--- lld/test/COFF/print-search-paths.s
+++ lld/test/COFF/print-search-paths.s
@@ -4,11 +4,17 @@
 # RUN: llvm-mc -triple i686-windows-msvc %s -filetype=obj -o %t_32.obj
 # RUN: lld-link -safeseh:no /dll /noentry /winsysroot:%t.dir/sysroot /vctoolsversion:1.1.1.1 /winsdkversion:10.0.1 %t_32.obj -print-search-paths | FileCheck -DSYSROOT=%t.dir -check-prefix=X86 %s
 # CHECK: Library search paths:
+# CHECK:   [[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# CHECK:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# CHECK:   [[CPATH]]lib
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}um{{[/\\]}}x64
 # X86: Library search paths:
+# X86:   [[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# X86:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# X86:   [[CPATH]]lib
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x86
Index: lld/docs/ReleaseNotes.rst
===
--- lld/docs/ReleaseNotes.rst
+++ lld/docs/ReleaseNotes.rst
@@ -42,6 +42,12 @@
   current directory.
   I.e. ``lld-link /libpath:c:\relative\root relative\path\my.lib`` where before
   we would have to do ``lld-link /libpath:c:\relative\root\relative\path my.lib``
+* lld-link learned -print-search-paths that will print all the paths where it will
+  search for libraries.
+* By default lld-link will now search for libraries in the toolchain directories.
+  Specifically it will search:
+  ``/lib``, ``/lib/clang//lib`` and
+  ``/lib/clang//lib/windows``.
 
 MinGW Improvements
 --
Index: lld/COFF/Driver.h
===
--- lld/COFF/Driver.h
+++ lld/COFF/Driver.h
@@ -84,6 +84,8 @@
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string &argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 
Index: lld/COFF/Driver.cpp
===
--- lld/COFF/Driver.cpp
+++ lld/COFF/Driver.cpp
@@ -637,6 +637,31 @@
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1543,6 +1568,7 @@
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
 addLibSearchPaths();
+  addClangLibSearchPaths(argsArr[0]);
 
   // Handle /ignore
   for (auto *arg : args.filtered(OPT_ignore)) {
Index: clang/lib/Dri

[PATCH] D144634: [Clang][OpenMP] Support for Code Generation of loop bind clause

2023-07-14 Thread Sunil K via Phabricator via cfe-commits
koops updated this revision to Diff 540373.
koops added a comment.

Addressing Alexey's comments.
The name matching in loop_bind_messages.cpp & generic_loop_codegen.cpp tests 
changed to take care of the failures.


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

https://reviews.llvm.org/D144634

Files:
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/generic_loop_ast_print.cpp
  clang/test/OpenMP/generic_loop_codegen.cpp
  clang/test/OpenMP/loop_bind_codegen.cpp
  clang/test/OpenMP/loop_bind_enclosed.cpp
  clang/test/OpenMP/loop_bind_messages.cpp
  clang/test/OpenMP/nested_loop_codegen.cpp

Index: clang/test/OpenMP/nested_loop_codegen.cpp
===
--- clang/test/OpenMP/nested_loop_codegen.cpp
+++ clang/test/OpenMP/nested_loop_codegen.cpp
@@ -58,6 +58,12 @@
 // CHECK1-NEXT:[[DOTGLOBAL_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[DOTBOUND_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[I_ADDR:%.*]] = alloca ptr, align 8
+// CHECK1-NEXT:[[TMP:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_IV:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_LB:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_UB:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_STRIDE:%.*]] = alloca i32, align 4
+// CHECK1-NEXT:[[DOTOMP_IS_LAST:%.*]] = alloca i32, align 4
 // CHECK1-NEXT:[[K:%.*]] = alloca i32, align 4
 // CHECK1-NEXT:store ptr [[DOTGLOBAL_TID_]], ptr [[DOTGLOBAL_TID__ADDR]], align 8
 // CHECK1-NEXT:store ptr [[DOTBOUND_TID_]], ptr [[DOTBOUND_TID__ADDR]], align 8
@@ -66,35 +72,27 @@
 // CHECK1-NEXT:store i32 0, ptr [[TMP0]], align 4
 // CHECK1-NEXT:br label [[FOR_COND:%.*]]
 // CHECK1:   for.cond:
-// CHECK1-NEXT:[[TMP1:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK1-NEXT:[[CMP:%.*]] = icmp slt i32 [[TMP1]], 10
-// CHECK1-NEXT:br i1 [[CMP]], label [[FOR_BODY:%.*]], label [[FOR_END7:%.*]]
 // CHECK1:   for.body:
-// CHECK1-NEXT:store i32 0, ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_COND1:%.*]]
-// CHECK1:   for.cond1:
-// CHECK1-NEXT:[[TMP2:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[CMP2:%.*]] = icmp slt i32 [[TMP2]], 5
-// CHECK1-NEXT:br i1 [[CMP2]], label [[FOR_BODY3:%.*]], label [[FOR_END:%.*]]
-// CHECK1:   for.body3:
-// CHECK1-NEXT:[[TMP3:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[INC:%.*]] = add nsw i32 [[TMP3]], 1
-// CHECK1-NEXT:store i32 [[INC]], ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_INC:%.*]]
-// CHECK1:   for.inc:
-// CHECK1-NEXT:[[TMP4:%.*]] = load i32, ptr [[K]], align 4
-// CHECK1-NEXT:[[INC4:%.*]] = add nsw i32 [[TMP4]], 1
-// CHECK1-NEXT:store i32 [[INC4]], ptr [[K]], align 4
-// CHECK1-NEXT:br label [[FOR_COND1]], !llvm.loop [[LOOP3:![0-9]+]]
-// CHECK1:   for.end:
-// CHECK1-NEXT:br label [[FOR_INC5:%.*]]
-// CHECK1:   for.inc5:
-// CHECK1-NEXT:[[TMP5:%.*]] = load i32, ptr [[TMP0]], align 4
-// CHECK1-NEXT:[[INC6:%.*]] = add nsw i32 [[TMP5]], 1
-// CHECK1-NEXT:store i32 [[INC6]], ptr [[TMP0]], align 4
-// CHECK1-NEXT:br label [[FOR_COND]], !llvm.loop [[LOOP5:![0-9]+]]
-// CHECK1:   for.end7:
-// CHECK1-NEXT:ret void
+// CHECK1-NEXT [[TMP2:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 8
+// CHECK1-NEXT [[TMP3:%.*]] = load i32, ptr [[TMP2]], align 4
+// CHECK1-NEXT call void @__kmpc_for_static_init_4(ptr @1, i32 [[TMP3]], i32 34, ptr [[DOTOMP_IS_LAST]], ptr [[DOTOMP_LB]], ptr [[DOTOMP_UB]], ptr [[DOTOMP_STRIDE]], i32 1, i32 1)
+//CHECK1 cond.end:
+//CHECK1 omp.inner.for.cond:
+//CHECK1 omp.inner.for.body:
+//CHECK1 omp.body.continue:
+//CHECK1 omp.inner.for.inc:
+//CHECK1 omp.inner.for.end:
+//CHECK1 omp.loop.exit:
+// CHECK1-NEXT [[TMP13:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 8
+// CHECK1-NEXT [[TMP14:%.*]] = load i32, ptr [[TMP12]], align 4
+// CHECK1-NEXT call void @__kmpc_for_static_fini(ptr @1, i32 [[TMP14]])
+// CHECK1-NEXT [[TMP15:%.*]] = load ptr, ptr [[DOTGLOBAL_TID__ADDR]], align 8
+// CHECK1-NEXT [[TMP16:%.*]] = load i32, ptr [[TMP15]], align 4
+// CHECK1-NEXT call void @__kmpc_barrier(ptr @2, i32 [[TMP16]])
+//CHECK1 for.inc:
+//CHECK1 for.end:
+// CHECK1-NEXT ret void
+//
 //
 //
 // CHECK1-LABEL: define {{[^@]+}}@_Z11inline_declv
@@ -114,45 +112,36 @@
 // CHECK1-NEXT:[[DOTBOUND_TID__ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[I_ADDR:%.*]] = alloca ptr, align 8
 // CHECK1-NEXT:[[RES_ADDR:%.*]] = alloca ptr, align 8
-// CHECK1-NEXT:[[K:%.*]] = alloca i32, align 4
-// CHECK1-NEXT:store ptr [[DOTGLOBAL_TID_]], ptr [[DOTGLOBAL_TID__ADDR]], align 8
-// CHECK1-NEXT:store ptr [[DOTBOUND_TID_]], ptr [[DOTBOUND_TID__ADDR]], align 8
-// CHECK1-NEXT:store ptr [[I

[PATCH] D144634: [Clang][OpenMP] Support for Code Generation of loop bind clause

2023-07-14 Thread Alexey Bataev via Phabricator via cfe-commits
ABataev added inline comments.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:9837
+def err_omp_bind_required_on_loop : Error<
+  "expected 'bind' clause for loop construct without an enclosing OpenMP "
+  "construct">;

Also, `'loop'`



Comment at: clang/include/clang/Sema/Sema.h:11136
+  /// rigorous semantic checking in the new mapped directives.
+  bool mapLoopConstruct(llvm::SmallVector &ClausesWithoutBind,
+ArrayRef Clauses,

`llvm::SmallVectorImpl &ClausesWithoutBind`


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

https://reviews.llvm.org/D144634

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


[clang] af744f0 - [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta via cfe-commits

Author: Tobias Hieta
Date: 2023-07-14T14:37:24+02:00
New Revision: af744f0b84e2b6410be65277068b9033124c73b2

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

LOG: [LLD][COFF] Add LLVM toolchain library paths by default.

We want lld-link to automatically find compiler-rt's and
libc++ when it's in the same directory as the rest of the
toolchain. This is because on Windows linking isn't done
via the clang driver - but instead invoked directly.

This prepends: /lib /lib/clang/XX/lib and
/lib/clang/XX/lib/windows automatically to the library
search paths.

Related to #63827

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

Added: 


Modified: 
clang/lib/Driver/Driver.cpp
lld/COFF/Driver.cpp
lld/COFF/Driver.h
lld/docs/ReleaseNotes.rst
lld/test/COFF/print-search-paths.s

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index f7d28ab46b680c..be8632b0954983 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -184,6 +184,8 @@ std::string Driver::GetResourcesPath(StringRef BinaryPath,
 // path of the embedding binary, which for LLVM binaries will be in bin/.
 // ../lib gets us to lib/ in both cases.
 P = llvm::sys::path::parent_path(Dir);
+// This search path is also created in the COFF driver of lld, so any
+// changes here also needs to happen in lld/COFF/Driver.cpp
 llvm::sys::path::append(P, CLANG_INSTALL_LIBDIR_BASENAME, "clang",
 CLANG_VERSION_MAJOR_STRING);
   }

diff  --git a/lld/COFF/Driver.cpp b/lld/COFF/Driver.cpp
index 5f11d11ea72538..d7476e91e03e38 100644
--- a/lld/COFF/Driver.cpp
+++ b/lld/COFF/Driver.cpp
@@ -637,6 +637,31 @@ void LinkerDriver::detectWinSysRoot(const 
opt::InputArgList &Args) {
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by 
MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", 
std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), 
saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1543,6 +1568,7 @@ void LinkerDriver::linkerMain(ArrayRef 
argsArr) {
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldignoreenv) && !args.hasArg(OPT_winsysroot))
 addLibSearchPaths();
+  addClangLibSearchPaths(argsArr[0]);
 
   // Handle /ignore
   for (auto *arg : args.filtered(OPT_ignore)) {

diff  --git a/lld/COFF/Driver.h b/lld/COFF/Driver.h
index 6fb3abf260d6cf..17d2e6a483dc33 100644
--- a/lld/COFF/Driver.h
+++ b/lld/COFF/Driver.h
@@ -84,6 +84,8 @@ class LinkerDriver {
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string &argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 

diff  --git a/lld/docs/ReleaseNotes.rst b/lld/docs/ReleaseNotes.rst
index 4bd5a628d2b902..9435f23a7af616 100644
--- a/lld/docs/ReleaseNotes.rst
+++ b/lld/docs/ReleaseNotes.rst
@@ -42,6 +42,12 @@ COFF Improvements
   current directory.
   I.e. ``lld-link /libpath:c:\relative\root relative\path\my.lib`` where before
   we would have to do ``lld-link /libpath:c:\relative\root\relative\path 
my.lib``
+* lld-link learned -print-search-paths that will print all the paths where it 
will
+  search for libraries.
+* By default lld-link will now search for libraries in the toolchain 
directories.
+  Specifically it will search:
+  ``/lib``, ``/lib/clang//lib`` and
+  ``/lib/clang//lib/windows``.
 
 MinGW Improvements
 --

diff  --git a/lld/test/COFF/print-search-paths.s 
b/lld/test/COFF/print-search-paths.s
index a484ac5b0fb164..5c292aafc68a11 100644
--- a/lld/test/COFF/print-sea

[PATCH] D151188: [LLD][COFF] Add LLVM toolchain library paths by default.

2023-07-14 Thread Tobias Hieta 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 rGaf744f0b84e2: [LLD][COFF] Add LLVM toolchain library paths 
by default. (authored by thieta).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D151188

Files:
  clang/lib/Driver/Driver.cpp
  lld/COFF/Driver.cpp
  lld/COFF/Driver.h
  lld/docs/ReleaseNotes.rst
  lld/test/COFF/print-search-paths.s

Index: lld/test/COFF/print-search-paths.s
===
--- lld/test/COFF/print-search-paths.s
+++ lld/test/COFF/print-search-paths.s
@@ -4,11 +4,17 @@
 # RUN: llvm-mc -triple i686-windows-msvc %s -filetype=obj -o %t_32.obj
 # RUN: lld-link -safeseh:no /dll /noentry /winsysroot:%t.dir/sysroot /vctoolsversion:1.1.1.1 /winsdkversion:10.0.1 %t_32.obj -print-search-paths | FileCheck -DSYSROOT=%t.dir -check-prefix=X86 %s
 # CHECK: Library search paths:
+# CHECK:   [[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# CHECK:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# CHECK:   [[CPATH]]lib
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x64
 # CHECK:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}um{{[/\\]}}x64
 # X86: Library search paths:
+# X86:   [[CPATH:.*]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib{{[/\\]}}windows
+# X86:   [[CPATH]]lib{{[/\\]}}clang{{[/\\]}}{{[0-9]+}}{{[/\\]}}lib
+# X86:   [[CPATH]]lib
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}VC{{[/\\]}}Tools{{[/\\]}}MSVC{{[/\\]}}1.1.1.1{{[/\\]}}atlmfc{{[/\\]}}lib{{[/\\]}}x86
 # X86:   [[SYSROOT]]{{[/\\]}}sysroot{{[/\\]}}Windows Kits{{[/\\]}}10{{[/\\]}}Lib{{[/\\]}}10.0.1{{[/\\]}}ucrt{{[/\\]}}x86
Index: lld/docs/ReleaseNotes.rst
===
--- lld/docs/ReleaseNotes.rst
+++ lld/docs/ReleaseNotes.rst
@@ -42,6 +42,12 @@
   current directory.
   I.e. ``lld-link /libpath:c:\relative\root relative\path\my.lib`` where before
   we would have to do ``lld-link /libpath:c:\relative\root\relative\path my.lib``
+* lld-link learned -print-search-paths that will print all the paths where it will
+  search for libraries.
+* By default lld-link will now search for libraries in the toolchain directories.
+  Specifically it will search:
+  ``/lib``, ``/lib/clang//lib`` and
+  ``/lib/clang//lib/windows``.
 
 MinGW Improvements
 --
Index: lld/COFF/Driver.h
===
--- lld/COFF/Driver.h
+++ lld/COFF/Driver.h
@@ -84,6 +84,8 @@
   // config->machine has been set.
   void addWinSysRootLibSearchPaths();
 
+  void addClangLibSearchPaths(const std::string &argv0);
+
   // Used by the resolver to parse .drectve section contents.
   void parseDirectives(InputFile *file);
 
Index: lld/COFF/Driver.cpp
===
--- lld/COFF/Driver.cpp
+++ lld/COFF/Driver.cpp
@@ -637,6 +637,31 @@
   }
 }
 
+void LinkerDriver::addClangLibSearchPaths(const std::string &argv0) {
+  std::string lldBinary = sys::fs::getMainExecutable(argv0.c_str(), nullptr);
+  SmallString<128> binDir(lldBinary);
+  sys::path::remove_filename(binDir); // remove lld-link.exe
+  StringRef rootDir = sys::path::parent_path(binDir); // remove 'bin'
+
+  SmallString<128> libDir(rootDir);
+  sys::path::append(libDir, "lib");
+  // We need to prepend the paths here in order to make sure that we always
+  // try to link the clang versions of the builtins over the ones supplied by MSVC.
+  searchPaths.insert(searchPaths.begin(), saver().save(libDir.str()));
+
+  // Add the resource dir library path
+  SmallString<128> runtimeLibDir(rootDir);
+  sys::path::append(runtimeLibDir, "lib", "clang", std::to_string(LLVM_VERSION_MAJOR), "lib");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDir.str()));
+
+  // Resource dir + osname, which is hardcoded to windows since we are in the
+  // COFF driver.
+  SmallString<128> runtimeLibDirWithOS(runtimeLibDir);
+  sys::path::append(runtimeLibDirWithOS, "windows");
+  searchPaths.insert(searchPaths.begin(), saver().save(runtimeLibDirWithOS.str()));
+
+}
+
 void LinkerDriver::addWinSysRootLibSearchPaths() {
   if (!diaPath.empty()) {
 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
@@ -1543,6 +1568,7 @@
   detectWinSysRoot(args);
   if (!args.hasArg(OPT_lldign

[PATCH] D86310: [X86] Align i128 to 16 bytes in x86-64 datalayout

2023-07-14 Thread John Reagan via Phabricator via cfe-commits
JohnReagan added a comment.

As a legacy OS provider on a platform that needs/requires ABI compatibility, I 
don't like the direction this is going.  Like @rnk, I would having MORE control 
over struct layout is better than less.  I'm adapting non-traditional languages 
to LLVM which allow very explicit control over layout of fields in structs.  I 
have system-provided headers and data structures that have been the same since 
1977.  Fortunately, none contain i128 (or f128) sized items but I'm watching 
closely about any undermining of data layout control.  This area of layout 
control (both with fields in structures and variables in sections) has been our 
biggest challenge with getting OpenVMS running on x86 using LLVM.  I really 
don't want to be locked into a older version of the backend out of concerns 
about ABI reshuffling.  We guarantee that previously compiled images continue 
to execute forever and that you can mix/match objects across versions.  You can 
compile one file today and link it against an object library (provided by a 3rd 
party vendor) that was compiled 5 years ago with older compilers and it will 
work as intended.


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

https://reviews.llvm.org/D86310

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


[PATCH] D155215: [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo updated this revision to Diff 540385.
VitaNuo added a comment.

Address comments.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155215

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2299,7 +2299,7 @@
 
 TEST(FindReferences, UsedSymbolsFromInclude) {
   const char *Tests[] = {
-  R"cpp([[#include ^"bar.h"]]
+  R"cpp(   [[#include   ^"bar.h"]]
 #include 
 int fstBar = [[bar1]]();
 int sndBar = [[bar2]]();
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1362,10 +1362,9 @@
 return std::nullopt;
 
   // Add the #include line to the references list.
-  auto IncludeLen = std::string{"#include"}.length() + Inc.Written.length() + 1;
   ReferencesResult::Reference Result;
-  Result.Loc.range = clangd::Range{Position{Inc.HashLine, 0},
-   Position{Inc.HashLine, (int)IncludeLen}};
+  Result.Loc.range =
+  rangeTillEOL(SM.getBufferData(SM.getMainFileID()), Inc.HashOffset);
   Result.Loc.uri = URIMainFile;
   Results.References.push_back(std::move(Result));
 
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -337,6 +337,10 @@
 /// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
 SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
   const SourceManager &SM);
+
+/// Returns the range starting at offset and spanning the whole line. Escaped
+/// newlines are not handled.
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset);
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -1242,5 +1242,17 @@
   }
   return Loc;
 }
+
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset) {
+  clangd::Range Result;
+  Result.end = Result.start = offsetToPosition(Code, HashOffset);
+
+  // Span the warning until the EOL or EOF.
+  Result.end.character +=
+  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
+return C == '\n' || C == '\r';
+  }));
+  return Result;
+}
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -21,6 +21,7 @@
 #include "Diagnostics.h"
 #include "Headers.h"
 #include "ParsedAST.h"
+#include "Protocol.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Syntax/Tokens.h"
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -60,20 +60,6 @@
 
 namespace {
 
-// Returns the range starting at '#' and ending at EOL. Escaped newlines are not
-// handled.
-clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) {
-  clangd::Range Result;
-  Result.end = Result.start = offsetToPosition(Code, HashOffset);
-
-  // Span the warning until the EOL or EOF.
-  Result.end.character +=
-  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
-return C == '\n' || C == '\r';
-  }));
-  return Result;
-}
-
 bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter IgnoreHeaders) {
   // Convert the path to Unix slashes and try to match against the filter.
   llvm::SmallString<64> NormalizedPath(HeaderPath);
@@ -224,7 +210,7 @@
 D.InsideMainFile = true;
 D.Severity = DiagnosticsEngine::Warning;
 D.Tags.push_back(Unnecessary);
-D.Range = getDiagnosticRange(Code, Inc->HashOffset);
+D.Range = rangeTillEOL(Code, Inc->HashOffset);
 // FIXME(kirillbobyrev): Removing inclusion might break the code if the
 // used headers are only reachable transitively through this one. Suggest
 // including them directly instead.
___
cfe-commits mailing list
cfe-commits@lists.

[PATCH] D155215: [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Viktoriia Bakalova via Phabricator via cfe-commits
VitaNuo marked 2 inline comments as done.
VitaNuo added a comment.

Thanks for the comments!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155215

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


[clang-tools-extra] 96e5079 - [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Viktoriia Bakalova via cfe-commits

Author: Viktoriia Bakalova
Date: 2023-07-14T12:51:14Z
New Revision: 96e50797d6ea39d561fc90511152fd30b77c1e62

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

LOG: [clangd] Fix the range for include reference to itself.

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

Added: 


Modified: 
clang-tools-extra/clangd/IncludeCleaner.cpp
clang-tools-extra/clangd/IncludeCleaner.h
clang-tools-extra/clangd/SourceCode.cpp
clang-tools-extra/clangd/SourceCode.h
clang-tools-extra/clangd/XRefs.cpp
clang-tools-extra/clangd/unittests/XRefsTests.cpp

Removed: 




diff  --git a/clang-tools-extra/clangd/IncludeCleaner.cpp 
b/clang-tools-extra/clangd/IncludeCleaner.cpp
index 2a8499dade84c0..9a910e5850a9f1 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.cpp
+++ b/clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -60,20 +60,6 @@ void setIncludeCleanerAnalyzesStdlib(bool B) { AnalyzeStdlib 
= B; }
 
 namespace {
 
-// Returns the range starting at '#' and ending at EOL. Escaped newlines are 
not
-// handled.
-clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) {
-  clangd::Range Result;
-  Result.end = Result.start = offsetToPosition(Code, HashOffset);
-
-  // Span the warning until the EOL or EOF.
-  Result.end.character +=
-  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
-return C == '\n' || C == '\r';
-  }));
-  return Result;
-}
-
 bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter IgnoreHeaders) {
   // Convert the path to Unix slashes and try to match against the filter.
   llvm::SmallString<64> NormalizedPath(HeaderPath);
@@ -224,7 +210,7 @@ std::vector generateUnusedIncludeDiagnostics(
 D.InsideMainFile = true;
 D.Severity = DiagnosticsEngine::Warning;
 D.Tags.push_back(Unnecessary);
-D.Range = getDiagnosticRange(Code, Inc->HashOffset);
+D.Range = rangeTillEOL(Code, Inc->HashOffset);
 // FIXME(kirillbobyrev): Removing inclusion might break the code if the
 // used headers are only reachable transitively through this one. Suggest
 // including them directly instead.

diff  --git a/clang-tools-extra/clangd/IncludeCleaner.h 
b/clang-tools-extra/clangd/IncludeCleaner.h
index edd89777faf3d0..b1acbdd5484345 100644
--- a/clang-tools-extra/clangd/IncludeCleaner.h
+++ b/clang-tools-extra/clangd/IncludeCleaner.h
@@ -21,6 +21,7 @@
 #include "Diagnostics.h"
 #include "Headers.h"
 #include "ParsedAST.h"
+#include "Protocol.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Syntax/Tokens.h"

diff  --git a/clang-tools-extra/clangd/SourceCode.cpp 
b/clang-tools-extra/clangd/SourceCode.cpp
index 474570cb6459f7..eb0a578b0f4a12 100644
--- a/clang-tools-extra/clangd/SourceCode.cpp
+++ b/clang-tools-extra/clangd/SourceCode.cpp
@@ -1242,5 +1242,17 @@ SourceLocation 
translatePreamblePatchLocation(SourceLocation Loc,
   }
   return Loc;
 }
+
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset) {
+  clangd::Range Result;
+  Result.end = Result.start = offsetToPosition(Code, HashOffset);
+
+  // Span the warning until the EOL or EOF.
+  Result.end.character +=
+  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
+return C == '\n' || C == '\r';
+  }));
+  return Result;
+}
 } // namespace clangd
 } // namespace clang

diff  --git a/clang-tools-extra/clangd/SourceCode.h 
b/clang-tools-extra/clangd/SourceCode.h
index 3ba6f8b80ef373..a1bb44c1761202 100644
--- a/clang-tools-extra/clangd/SourceCode.h
+++ b/clang-tools-extra/clangd/SourceCode.h
@@ -337,6 +337,10 @@ inline bool isReservedName(llvm::StringRef Name) {
 /// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
 SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
   const SourceManager &SM);
+
+/// Returns the range starting at offset and spanning the whole line. Escaped
+/// newlines are not handled.
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset);
 } // namespace clangd
 } // namespace clang
 #endif

diff  --git a/clang-tools-extra/clangd/XRefs.cpp 
b/clang-tools-extra/clangd/XRefs.cpp
index b608296deefad5..29ce1f3e0d0e3b 100644
--- a/clang-tools-extra/clangd/XRefs.cpp
+++ b/clang-tools-extra/clangd/XRefs.cpp
@@ -1362,10 +1362,9 @@ maybeFindIncludeReferences(ParsedAST &AST, Position Pos,
 return std::nullopt;
 
   // Add the #include line to the references list.
-  auto IncludeLen = std::string{"#include"}.length() + Inc.Written.length() + 
1;
   ReferencesResult::Reference Result;
-  Result.Loc.range = clangd::Range{Position{Inc.HashLine, 0},
-   Position{Inc.HashLine, (int)IncludeLen}};
+  Result

[PATCH] D155215: [clangd] Fix the range for include reference to itself.

2023-07-14 Thread Viktoriia Bakalova 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 rG96e50797d6ea: [clangd] Fix the range for include reference 
to itself. (authored by VitaNuo).

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155215

Files:
  clang-tools-extra/clangd/IncludeCleaner.cpp
  clang-tools-extra/clangd/IncludeCleaner.h
  clang-tools-extra/clangd/SourceCode.cpp
  clang-tools-extra/clangd/SourceCode.h
  clang-tools-extra/clangd/XRefs.cpp
  clang-tools-extra/clangd/unittests/XRefsTests.cpp

Index: clang-tools-extra/clangd/unittests/XRefsTests.cpp
===
--- clang-tools-extra/clangd/unittests/XRefsTests.cpp
+++ clang-tools-extra/clangd/unittests/XRefsTests.cpp
@@ -2299,7 +2299,7 @@
 
 TEST(FindReferences, UsedSymbolsFromInclude) {
   const char *Tests[] = {
-  R"cpp([[#include ^"bar.h"]]
+  R"cpp(   [[#include   ^"bar.h"]]
 #include 
 int fstBar = [[bar1]]();
 int sndBar = [[bar2]]();
Index: clang-tools-extra/clangd/XRefs.cpp
===
--- clang-tools-extra/clangd/XRefs.cpp
+++ clang-tools-extra/clangd/XRefs.cpp
@@ -1362,10 +1362,9 @@
 return std::nullopt;
 
   // Add the #include line to the references list.
-  auto IncludeLen = std::string{"#include"}.length() + Inc.Written.length() + 1;
   ReferencesResult::Reference Result;
-  Result.Loc.range = clangd::Range{Position{Inc.HashLine, 0},
-   Position{Inc.HashLine, (int)IncludeLen}};
+  Result.Loc.range =
+  rangeTillEOL(SM.getBufferData(SM.getMainFileID()), Inc.HashOffset);
   Result.Loc.uri = URIMainFile;
   Results.References.push_back(std::move(Result));
 
Index: clang-tools-extra/clangd/SourceCode.h
===
--- clang-tools-extra/clangd/SourceCode.h
+++ clang-tools-extra/clangd/SourceCode.h
@@ -337,6 +337,10 @@
 /// using presumed locations. Returns \p Loc if it isn't inside preamble patch.
 SourceLocation translatePreamblePatchLocation(SourceLocation Loc,
   const SourceManager &SM);
+
+/// Returns the range starting at offset and spanning the whole line. Escaped
+/// newlines are not handled.
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset);
 } // namespace clangd
 } // namespace clang
 #endif
Index: clang-tools-extra/clangd/SourceCode.cpp
===
--- clang-tools-extra/clangd/SourceCode.cpp
+++ clang-tools-extra/clangd/SourceCode.cpp
@@ -1242,5 +1242,17 @@
   }
   return Loc;
 }
+
+clangd::Range rangeTillEOL(llvm::StringRef Code, unsigned HashOffset) {
+  clangd::Range Result;
+  Result.end = Result.start = offsetToPosition(Code, HashOffset);
+
+  // Span the warning until the EOL or EOF.
+  Result.end.character +=
+  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
+return C == '\n' || C == '\r';
+  }));
+  return Result;
+}
 } // namespace clangd
 } // namespace clang
Index: clang-tools-extra/clangd/IncludeCleaner.h
===
--- clang-tools-extra/clangd/IncludeCleaner.h
+++ clang-tools-extra/clangd/IncludeCleaner.h
@@ -21,6 +21,7 @@
 #include "Diagnostics.h"
 #include "Headers.h"
 #include "ParsedAST.h"
+#include "Protocol.h"
 #include "clang-include-cleaner/Types.h"
 #include "clang/Basic/SourceManager.h"
 #include "clang/Tooling/Syntax/Tokens.h"
Index: clang-tools-extra/clangd/IncludeCleaner.cpp
===
--- clang-tools-extra/clangd/IncludeCleaner.cpp
+++ clang-tools-extra/clangd/IncludeCleaner.cpp
@@ -60,20 +60,6 @@
 
 namespace {
 
-// Returns the range starting at '#' and ending at EOL. Escaped newlines are not
-// handled.
-clangd::Range getDiagnosticRange(llvm::StringRef Code, unsigned HashOffset) {
-  clangd::Range Result;
-  Result.end = Result.start = offsetToPosition(Code, HashOffset);
-
-  // Span the warning until the EOL or EOF.
-  Result.end.character +=
-  lspLength(Code.drop_front(HashOffset).take_until([](char C) {
-return C == '\n' || C == '\r';
-  }));
-  return Result;
-}
-
 bool isIgnored(llvm::StringRef HeaderPath, HeaderFilter IgnoreHeaders) {
   // Convert the path to Unix slashes and try to match against the filter.
   llvm::SmallString<64> NormalizedPath(HeaderPath);
@@ -224,7 +210,7 @@
 D.InsideMainFile = true;
 D.Severity = DiagnosticsEngine::Warning;
 D.Tags.push_back(Unnecessary);
-D.Range = getDiagnosticRange(Code, Inc->HashOffset);
+D.Range = rangeTillEOL(Code, Inc->HashOffset);
 // FIXME(kirillbobyrev): Removing inclusion might break the code if the
 // used headers are only reachable transitively throug

[PATCH] D155175: [Clang] Fix consteval propagation for aggregates and defaulted constructors

2023-07-14 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

In D155175#4498788 , @efriedma wrote:

> Do we need CodeGen testcases here for full coverage?  The testcases from the 
> issue passed with -fsyntax-only.
>
> 
>
> With this patch, the following cases produce errors that don't really make 
> sense to me:
>
>   consteval int f(int x) {
>   return x;
>   }
>   struct SS {
>   int y;
>   int x = f(this->y);
>   constexpr SS(int yy) : y(yy) {}
>   };
>   SS s = {1};
>
>
>
>   :6:13: error: call to consteval function 'f' is not a constant 
> expression
>   6 | int x = f(this->y);
> | ^
>   :7:15: note: in the default initializer of 'x'
>   7 | constexpr SS(int yy) : y(yy) {}
> |   ^
>   :6:5: note: declared here
>   6 | int x = f(this->y);
> | ^
>   :6:15: note: use of 'this' pointer is only allowed within the 
> evaluation of a call to a 'constexpr' member function
>   6 | int x = f(this->y);
> |   ^
>   1 error generated.

This seems reasonable,  it's equivalent to  `constexpr SS(int yy) : y(yy), 
x(f(y)) {}` = which is not a valid call of a consteval function. And the 
constructor is neither defaulted, nor templated, so escalation does not happen. 
I agree that "use of 'this' pointer is only allowed within the evaluation of a 
call to a 'constexpr' member function" isn't amazing but it's preexisting
https://godbolt.org/z/sa78bzsed

>   consteval int f(int x) {
>   return x;
>   }
>   struct SS {
>   int y;
>   int x = f(this->y);
>   consteval SS(int yy) : y(yy) {}
>   };
>   SS s = {1};
>
>   :6:13: error: cannot take address of consteval function 'f' outside 
> of an immediate invocation
>   6 | int x = f(this->y);
> | ^
>   :1:15: note: declared here
>   1 | consteval int f(int x) {
> |   ^
>   1 error generated.

Yup, this is not great - I think it's unrelated the degradation of error 
message was introduced between 15 and 16, I probably want to investigate in a 
separate patch, not sure yet.

> Somehow the following is accepted, though:
>
>   consteval int f(int x) {
>   return x;
>   }
>   struct SS {
>   int y;
>   int x = f(this->y);
>   template constexpr SS(T yy) : y(yy) {}
>   };
>   SS s = {1};

Yes, this is bad.  Thanks for finding it.
It compiles because 1 is a constant and somehow it ends up evaluating f(1) 
instead of f(y) - replacing 1 by a reference to a local variable produce the 
expected behavior. Investigating.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155175

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


[PATCH] D152093: [clang][Analysis] Handle && and || against variable and its negation as tautology

2023-07-14 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added a comment.

> Do you have any numbers on how often this fires in practice, and what the 
> true positive rate is? (Build some large-ish open source  project with this, 
> and see what it finds.)

I built rui314/mold and saw no new warnings emitted from this change. I 
searched several repositories to find only one instance in CBLAS code that this 
change could be relevant.
https://github.com/Reference-LAPACK/lapack/blob/c57e36a43bb1c25c7ec15a3c84f4800942a5ca43/CBLAS/src/cblas_xerbla.c#L69-L70
I'm not sure what exactly they are doing there, but the comment (`Force link of 
our F77 error handler`) suggests it is intentional, so it could be counted as 
false positive. But, I don't see any reason for not doing `if (0)` instead.

> Did you verify that this has negligible compile time impact for building a 
> large-ish project?

About the compile time impact, I don't expect this patch to have a noticeable 
change. The changes in this patch does not contain heavy computations like AST 
traversals. At least the build times of rui314/mold by clang ToT and patched 
clang did not have noticeable difference.




Comment at: clang/lib/Analysis/CFG.cpp:1096
+if (Negate->getOpcode() == UO_LNot &&
+Expr::isSameComparisonOperand(Negate->getSubExpr(), E2)) {
+  bool AlwaysTrue = B->getOpcode() == BO_LOr;

thakis wrote:
> Do you want to IgnoreParens() on the ! subexpr too?
I wanted to, but it looks like most codes containing parentheses in negation 
subexpression are macros, so now I don't think we need it.
https://sourcegraph.com/search?q=context:global+/%21%5C%28%5Ba-zA-Z_%5D%2B%5C%29/+lang:C+lang:C%2B%2B&patternType=standard&case=yes&sm=1&groupBy=repo


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

https://reviews.llvm.org/D152093

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


[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-07-14 Thread Qiongsi Wu via Phabricator via cfe-commits
qiongsiwu1 created this revision.
qiongsiwu1 added reviewers: w2yehia, davidxl, vsk, ellis.
Herald added subscribers: wlei, Enna1, wenlei.
Herald added a project: All.
qiongsiwu1 requested review of this revision.
Herald added subscribers: Sanitizers, cfe-commits, MaskRay.
Herald added projects: clang, Sanitizers.

Currently, the PGO runtime only creates unique per process profile files when 
both of the following conditions are true

1. __llvm_profile_initialize is triggered through global variable 
initialization (e.g. when exec starts an instrumented binary).
2. When there are no existing file patterns set. See 
https://github.com/llvm/llvm-project/blob/bb6d60bf9dfea82814d9e50c5bb457c47d010611/compiler-rt/lib/profile/InstrProfilingFile.c#L795

This patch changes the behaviour so that a new profile file name is generate as 
soon as a fork system call generates a new process from an instrumented binary. 
The patch uses the `pthread_atfork` hook to register the initialization code, 
and modifies the file name pattern parsing logic so that when `%p` is present 
in the pattern, a unique file name can be generated even though the pattern 
already exists.

Additionally, the unique profile files are created before the profiling starts. 
If a process is not terminated gracefully by calling `exit`, an empty profile 
file for that process will exist, indicating that the profiling may be 
incomplete due to the process's abnormal termination.

Note that the unique profile per process is only generated when `%p` is present 
in the profile file name pattern. Additionally, this patch does not support 
Windows because the implementation relies on `pthread`.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155290

Files:
  clang/lib/Driver/ToolChains/AIX.cpp
  compiler-rt/lib/profile/InstrProfilingFile.c
  compiler-rt/test/profile/Posix/instrprof-fork-int.c
  compiler-rt/test/profile/Posix/instrprof-fork.c

Index: compiler-rt/test/profile/Posix/instrprof-fork.c
===
--- /dev/null
+++ compiler-rt/test/profile/Posix/instrprof-fork.c
@@ -0,0 +1,25 @@
+/// Testing fork with out exec. The runtime should generate two profile files.
+// UNSUPPORTED: target={{.*windows.*}}
+// RUN: rm -rf %t.d
+// RUN: mkdir -p %t.d && cd %t.d
+// RUN: %clang_pgogen %s -o %t.exe
+// RUN: LLVM_PROFILE_FILE="%%p.profraw" %t.exe > %t.out
+// RUN: PROFILE1=`head -n 1 %t.out`
+// RUN: ls $PROFILE1
+// RUN: PROFILE2=`tail -n 1 %t.out`
+// RUN: ls $PROFILE2
+
+#include 
+#include 
+#include 
+
+int main(int argc, char **argv) {
+  pid_t pid;
+  pid = fork();
+  if (!pid) {
+printf("%ld.profraw\n", (long)getpid());
+  } else {
+printf("%ld.profraw\n", (long)getpid());
+  }
+  return 0;
+}
Index: compiler-rt/test/profile/Posix/instrprof-fork-int.c
===
--- /dev/null
+++ compiler-rt/test/profile/Posix/instrprof-fork-int.c
@@ -0,0 +1,27 @@
+/// Testing fork with out exec. The child is interrupted.
+/// Make sure we have an empty profile file.
+// UNSUPPORTED: target={{.*windows.*}}
+// RUN: rm -rf %t.d
+// RUN: mkdir -p %t.d && cd %t.d
+// RUN: %clang_pgogen %s -o %t.exe
+// RUN: LLVM_PROFILE_FILE="%%p.profraw" %t.exe > %t.out
+// RUN: PROFILE=`cat %t.out`
+// RUN: ls $PROFILE
+// RUN: wc $PROFILE | FileCheck %s
+
+// CHECK: 0   0   0
+#include 
+#include 
+#include 
+#include 
+
+int main(int argc, char **argv) {
+  pid_t pid;
+  pid = fork();
+  if (!pid) {
+printf("%ld.profraw\n", (long)getpid());
+fflush(stdout);
+raise(SIGSEGV);
+  }
+  return 0;
+}
Index: compiler-rt/lib/profile/InstrProfilingFile.c
===
--- compiler-rt/lib/profile/InstrProfilingFile.c
+++ compiler-rt/lib/profile/InstrProfilingFile.c
@@ -29,6 +29,8 @@
 #if defined(__linux__)
 #include 
 #endif
+/* For pthread_atfork(). Not supported on Windows. */
+#include 
 #endif
 
 #include "InstrProfiling.h"
@@ -90,7 +92,6 @@
 
 static lprofFilename lprofCurFilename = {0,   0, 0, {0}, NULL,
  {0}, 0, 0, 0,   PNS_unknown};
-
 static int ProfileMergeRequested = 0;
 static int getProfileFileSizeForMerging(FILE *ProfileFile,
 uint64_t *ProfileFileSize);
@@ -246,6 +247,11 @@
   return lprofCurFilename.MergePoolSize || isProfileMergeRequested();
 }
 
+// Flag to indicate if a new profile name should be used when a new
+// process is forked. The flag cannot be true on Windows,
+// because the implementation relies on pthread.
+static int ResetNameAtFork = 0;
+
 /* Return 1 if there is an error, otherwise return  0.  */
 static uint32_t fileWriter(ProfDataWriter *This, ProfDataIOVec *IOVecs,
uint32_t NumIOVecs) {
@@ -520,21 +526,27 @@
   if (!Filename)
 return;
 
-  /* Only create the profile directory and truncate an existing profile once.
-   * In continuous mo

[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-14 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt updated this revision to Diff 540395.
RIscRIpt added a comment.

Addressed review comments.

In D153914#4497696 , @aaron.ballman 
wrote:

> Sema seems like the wrong place to perform such concatenations, but given 
> that adjacent string literals are concatenated during phase 6...

I agree, but I couldn't come up with anything better (having limited knowledge 
about Clang).
Other possible //ugly// solution: make actual concatenation in 
`StringLiteralParser`, but this would require either of:

1. Pass `Decl*` into `StringLiteralParser` - this requires dependency (and 
linkage) of Lex with AST.
2. Pre-calculate function names for all possible types of tokens 
(`__FUNCTION__`, `__FUNCDNAME__`, etc.) in `ActOnStringLiteral` and pass into 
`StringLiteralParser`
3. Find other way of obtaining __current__ function name in Lex.

One may wish to expand these macros during phase (4), but these macros are 
predefined identifiers in non-MSVC compilers, and MSVC don't expand them as 
macros (`-E` compiler flag); and we don't have knowledge about AST (not to 
mention the function name) during phase (4).

In D153914#4497696 , @aaron.ballman 
wrote:

> I'm not certain it's actually observable.

I didn't understand this part.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/ms_predefined_expr.cpp

Index: clang/test/Sema/ms_predefined_expr.cpp
===
--- clang/test/Sema/ms_predefined_expr.cpp
+++ clang/test/Sema/ms_predefined_expr.cpp
@@ -1,9 +1,62 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
 
+using size_t = __SIZE_TYPE__;
+
 void f() {
  const char a[] = __FUNCTION__; // expected-warning{{initializing an array from a '__FUNCTION__' predefined identifier is a Microsoft extension}}
  const char b[] = __FUNCDNAME__; // expected-warning{{initializing an array from a '__FUNCDNAME__' predefined identifier is a Microsoft extension}}
  const char c[] = __FUNCSIG__; // expected-warning{{initializing an array from a '__FUNCSIG__' predefined identifier is a Microsoft extension}}
  const char d[] = __func__; // expected-warning{{initializing an array from a '__func__' predefined identifier is a Microsoft extension}}
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}
+}
+
+// Test concatenation
+
+void eat_const_char_p(const char*);
+void eat_const_wchar_p(const wchar_t*);
+
+void test_concat() {
+  eat_const_char_p("s" __FUNCTION__); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCDNAME__); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCSIG__); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_char_p(__FUNCTION__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p(__FUNCDNAME__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p(__FUNCSIG__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_char_p("s" __FUNCTION__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCDNAME__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCSIG__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+}
+
+void test_wide_concat() {
+  eat_const_wchar_p(L"s" L__FUNCTION__); // expected-warning{{concatenation of predefined identifier 'L__FUNCTION__' is a Microsoft extension}}
+  eat_const_wchar_p(L"s" L__FUNCSIG__); // expected-warning{{concatenation of predefined identifier 'L__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_wchar_p(L__FUNCTION__ L"s"); // expected-warning{{conc

[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-14 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt added inline comments.



Comment at: clang/include/clang/Parse/Parser.h:578-582
+  bool isTokenConcatenable() const {
+return isTokenStringLiteral() ||
+   getLangOpts().MicrosoftExt &&
+   tok::isMSPredefinedMacro(Tok.getKind());
+  }

cor3ntin wrote:
> Unless you find a better name,  I think it's preferable to keep 
> `isTokenConcatenable` and `isTokenPredefinedMsMacro` as separate functions.
> Also, this seems like a weird place to check for  `getLangOpts().MicrosoftExt`
Regarding `getLangOpts().MicrosoftExt`. If you are talking about it's presence 
in a function which name is meant to be used as a predicate, I agree. If you 
are talking about `class Parser`, then there're other places with references to 
`getLangOpts()`.

Without such function `ParseStringLiteralExpression` implementation would be 
too verbose.
Let's decide what we can do after I address other comments.

Meanwhile, I renamed it to `isTokenLikeStringLiteral()`.



Comment at: clang/lib/Parse/ParseExpr.cpp:1300
   case tok::kw___PRETTY_FUNCTION__:  // primary-expression: __P..Y_F..N__ [GNU]
-Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
-ConsumeToken();
+Res = ParsePredefinedExpression(true);
 break;

cor3ntin wrote:
> Can we instead, look at `NextToken()` and if next token is a StringLiteral or 
> a MS predefined extension we fallthrough?
> That would avoid having duplicated logic in `ParsePredefinedExpression` and 
> `ActOnStringLiteral` which would be a nice simplification
I thought of that, but I was afraid that playing with fallthrough wasn't 
appreciated.
Thanks, fixed.



Comment at: clang/lib/Parse/ParseExpr.cpp:3294-3298
 StringToks.push_back(Tok);
-ConsumeStringToken();
-  } while (isTokenStringLiteral());
+if (isTokenStringLiteral())
+  ConsumeStringToken();
+else
+  ConsumeToken();

cor3ntin wrote:
> I think I'd prefer `ConsumeAnyToken` with an assert that checks it's a 
> stringLiteral or a predefined ms exppression
Done. But do we really need an assertion here? We have one in the function 
preamble and strict condition in `while`.



Comment at: clang/lib/Sema/SemaExpr.cpp:1955-1991
+  // MSVC treats some of predefined identifiers (e.g. __FUNCTION__) as
+  // expandable predefined macros defined as string literals,
+  // which may be concatenated. Expand them here (in Sema),
+  // because StringLiteralParser (in Lex) doesn't have access to AST.
+  std::vector ExpandedToks;
+  if (getLangOpts().MicrosoftExt) {
+ExpandedToks = StringToks.vec();

cor3ntin wrote:
> Can we put that logic in a separate function?
Done. Tho, I couldn't make it `const` (for the same reason I couldn't make 
`getCurScopeDecl() const`). And I wasn't sure about the interface:
```
std::vector ExpandMSPredefinedMacros(ArrayRef Toks);
```
vs
```
void ExpandMSPredefinedMacros(MutableArrayRef Toks);
```



Comment at: clang/lib/Sema/SemaExpr.cpp:1964
+for (Token &Tok : ExpandedToks) {
+  if (!tok::isMSPredefinedMacro(Tok.getKind())) {
+continue;

cor3ntin wrote:
> can you assert it's a string literal otherwise?
Done.



Comment at: clang/lib/Sema/SemaExpr.cpp:1972-1987
+  SmallString<64> Str;
+  llvm::raw_svector_ostream OS(Str);
+  Token Exp;
+  Exp.startToken();
+  if (Tok.getKind() == tok::kw_L__FUNCTION__ ||
+  Tok.getKind() == tok::kw_L__FUNCSIG__) {
+OS << 'L';

cor3ntin wrote:
> I think it might be easier to create a string_literal token directly here. 
> I'm also not sure we need to use `Lexer::Stringify`
> I think it might be easier to create a string_literal token directly here.

What do you mean? Is there a function which creates Token object from 
StringRef? Or is there a way to associate string literal value with a Token 
without PP? I would like to simplify it, but I haven't found other ways of 
achieving the same result.

> I'm also not sure we need to use Lexer::Stringify

Well, as far as I can see `StringLiteralParser` expands escape sequences. So, I 
am just being too careful here.
If not using `Lexer::Stringify` do we want to assert that function name does 
not contain neither `"` not `\` (which should not happen™)?



Comment at: clang/test/Sema/ms_predefined_expr.cpp:9
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an 
array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft 
extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array 
from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array 
from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}

cor3ntin wrote:
> do we have any tests that 

[PATCH] D155213: [HIP] Add `-fno-hip-uniform-block`

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 540397.
yaxunl marked an inline comment as done.
yaxunl added a comment.

revised by comments


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

https://reviews.llvm.org/D155213

Files:
  clang/include/clang/Basic/LangOptions.def
  clang/include/clang/Driver/Options.td
  clang/lib/CodeGen/CGCall.cpp
  clang/lib/CodeGen/Targets/AMDGPU.cpp
  clang/lib/Driver/ToolChains/Clang.cpp
  clang/test/CodeGenHIP/default-attributes.hip
  clang/test/Driver/hip-options.hip

Index: clang/test/Driver/hip-options.hip
===
--- clang/test/Driver/hip-options.hip
+++ clang/test/Driver/hip-options.hip
@@ -169,3 +169,25 @@
 // RUN: %clang -### -nogpuinc -nogpulib -fhip-fp32-correctly-rounded-divide-sqrt \
 // RUN:   --cuda-gpu-arch=gfx906  %s 2>&1 | FileCheck -check-prefixes=CRDS %s
 // CRDS-NOT: "-f{{(no-)?}}hip-fp32-correctly-rounded-divide-sqrt"
+
+// Check -fno-hip-uniform-block is passed to clang -cc1 but
+// (default) -fhip-uniform-block is not.
+
+// RUN: %clang -### --target=x86_64-unknown-linux-gnu -nogpuinc -nogpulib -fno-hip-uniform-block \
+// RUN:   --cuda-gpu-arch=gfx906 %s 2>&1 | FileCheck -check-prefix=NOUNIBLK %s
+
+// NOUNIBLK: "-cc1"{{.*}} "-triple" "amdgcn-amd-amdhsa" {{.*}} "-fno-hip-uniform-block"
+// NOUNIBLK: "-cc1"{{.*}} "-triple" "x86_64-unknown-linux-gnu" {{.*}} "-fno-hip-uniform-block"
+
+// RUN: %clang -### -nogpuinc -nogpulib -fhip-uniform-block \
+// RUN:   --cuda-gpu-arch=gfx906 %s 2>&1 | FileCheck -check-prefix=UNIBLK %s
+
+// RUN: %clang -### -nogpuinc -nogpulib \
+// RUN:   --cuda-gpu-arch=gfx906 %s 2>&1 | FileCheck -check-prefix=UNIBLK %s
+
+// UNIBLK-NOT: "-f{{(no-)?}}hip-uniform-block"
+
+// Check no warnings for -f[no-]uniform-block.
+
+// RUN: %clang -fdriver-only -Werror --target=x86_64-unknown-linux-gnu -nogpuinc -nogpulib -fno-hip-uniform-block \
+// RUN:   -fhip-uniform-block --cuda-gpu-arch=gfx906 %s 2>&1 | count 0
Index: clang/test/CodeGenHIP/default-attributes.hip
===
--- clang/test/CodeGenHIP/default-attributes.hip
+++ clang/test/CodeGenHIP/default-attributes.hip
@@ -5,6 +5,9 @@
 // RUN: %clang_cc1 -O3 -triple amdgcn-amd-amdhsa -x hip -fno-ident -fcuda-is-device \
 // RUN:-emit-llvm -o - %s | FileCheck -check-prefix=OPT %s
 
+// RUN: %clang_cc1 -triple amdgcn-amd-amdhsa -x hip -fno-ident -fcuda-is-device -fno-hip-uniform-block \
+// RUN:-emit-llvm -o - %s | FileCheck -check-prefix=NOUNIBLK %s
+
 #define __device__ __attribute__((device))
 #define __global__ __attribute__((global))
 
@@ -20,6 +23,12 @@
 // OPT-NEXT:  entry:
 // OPT-NEXT:ret void
 //
+// NOUNIBLK: Function Attrs: convergent mustprogress noinline nounwind optnone
+// NOUNIBLK-LABEL: define {{[^@]+}}@_Z4funcv
+// NOUNIBLK-SAME: () #[[ATTR0:[0-9]+]] {
+// NOUNIBLK-NEXT:  entry:
+// NOUNIBLK-NEXT:ret void
+//
 __device__ void func() {
 
 }
@@ -36,21 +45,34 @@
 // OPT-NEXT:  entry:
 // OPT-NEXT:ret void
 //
+// NOUNIBLK: Function Attrs: convergent mustprogress noinline norecurse nounwind optnone
+// NOUNIBLK-LABEL: define {{[^@]+}}@_Z6kernelv
+// NOUNIBLK-SAME: () #[[ATTR1:[0-9]+]] {
+// NOUNIBLK-NEXT:  entry:
+// NOUNIBLK-NEXT:ret void
+//
 __global__ void kernel() {
 
 }
 //.
-// OPTNONE: attributes #0 = { convergent mustprogress noinline nounwind optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
-// OPTNONE: attributes #1 = { convergent mustprogress noinline norecurse nounwind optnone "amdgpu-flat-work-group-size"="1,1024" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "uniform-work-group-size"="true" }
+// OPTNONE: attributes #[[ATTR0]] = { convergent mustprogress noinline nounwind optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
+// OPTNONE: attributes #[[ATTR1]] = { convergent mustprogress noinline norecurse nounwind optnone "amdgpu-flat-work-group-size"="1,1024" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "uniform-work-group-size"="true" }
+//.
+// OPT: attributes #[[ATTR0]] = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
+// OPT: attributes #[[ATTR1]] = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "amdgpu-flat-work-group-size"="1,1024" "no-trapping-math"="true" "stack-protector-buffer-size"="8" "uniform-work-group-size"="true" }
+//.
+// NOUNIBLK: attributes #[[ATTR0]] = { convergent mustprogress noinline nounwind optnone "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
+// NOUNIBLK: attributes #[[ATTR1]] = { convergent mustprogress noinline norecurse nounwind optnone "amdgpu-flat-work-group-size"="1,1024" "no-trapping-math"="true" "stack-protector-buffer-size"="8" }
 //.
-// OPT: attributes #0 = { mustprogress nofree norecurse nosync nounwind willreturn memory(none) "no-trapping-math"="true" "stack-protector-buffer-si

[PATCH] D152632: [Clang] Add warnings for CWG2521

2023-07-14 Thread PoYao Chang via Phabricator via cfe-commits
rZhBoYao added a comment.

Hmm… I don’t see why check-format keeps failing. I `git clang-format` thrice 
before uploading. 
https://buildkite.com/llvm-project/premerge-checks/builds/164452


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

https://reviews.llvm.org/D152632

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


[clang] 176981a - [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

2023-07-14 Thread Takuya Shimizu via cfe-commits

Author: Takuya Shimizu
Date: 2023-07-14T22:59:41+09:00
New Revision: 176981ac58d3e4beb02b9d110524e72be509375d

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

LOG: [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

Now that clang supports printing of multiple lines of code snippet in 
diagnostics, source ranges in diagnostics that are located in different lines 
from the diagnosed source location get to be printed if the gap happened to be 
less than the maximum number of lines clang is allowed to print in.
Many of the bad-conversion notes in overload resolution failures have their 
source location in the function declaration and source range in the argument of 
function call. This can cause an unnecessarily many lines of snippet printing.
This patch fixes it by changing the source range from function callsite to the 
problematic parameter in function declaration.

e.g.

```
void func(int aa, int bb);

void test() { func(1, "two"); }
```
BEFORE this patch:

```
source:4:15: error: no matching function for call to 'func'
4 | void test() { func(1, "two"); }
  |   ^~~~
source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
1 | void func(int aa, int bb);
  |  ^
2 |
3 |
4 | void test() { func(1, "two"); }
  |   ~
1 error generated.
```
AFTER this patch:

```
source:4:15: error: no matching function for call to 'func'
4 | void test() { func(1, "two"); }
  |   ^~~~
source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
1 | void func(int aa, int bb);
  |  ^~~
```

Reviewed By: cjdb
Differential Revision: https://reviews.llvm.org/D153359

Added: 
clang/test/Misc/diag-overload-cand-ranges.cpp
clang/test/Misc/diag-overload-cand-ranges.mm

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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 08d49bf72fbaaf..53a83b9c94176d 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -384,6 +384,37 @@ Improvements to Clang's diagnostics
   (`#57081: `_)
 - Clang no longer emits inappropriate notes about the loss of ``__unaligned`` 
qualifier
   on overload resolution, when the actual reason for the failure is loss of 
other qualifiers.
+- Clang's notes about unconvertible types in overload resolution failure now 
covers
+  the source range of parameter declaration of the candidate function 
declaration.
+
+  *Example Code*:
+
+  .. code-block:: c++
+
+ void func(int aa, int bb);
+ void test() { func(1, "two"); }
+
+  *BEFORE*:
+
+  .. code-block:: text
+
+source:2:15: error: no matching function for call to 'func'
+void test() { func(1, "two");  }
+  ^~~~
+source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
+void func(int aa, int bb);
+ ^
+
+  *AFTER*:
+
+  .. code-block:: text
+
+source:2:15: error: no matching function for call to 'func'
+void test() { func(1, "two");  }
+  ^~~~
+source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
+void func(int aa, int bb);
+ ^~~
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaOverload.cpp b/clang/lib/Sema/SemaOverload.cpp
index d45257ec7a4c7b..45a9e5dc98c032 100644
--- a/clang/lib/Sema/SemaOverload.cpp
+++ b/clang/lib/Sema/SemaOverload.cpp
@@ -10753,6 +10753,8 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *Cand,
   Expr *FromExpr = Conv.Bad.FromExpr;
   QualType FromTy = Conv.Bad.getFromType();
   QualType ToTy = Conv.Bad.getToType();
+  SourceRange ToParamRange =
+  !isObjectArgument ? Fn->getParamDecl(I)->getSourceRange() : 
SourceRange();
 
   if (FromTy == S.Context.OverloadTy) {
 assert(FromExpr && "overload set argument came from implicit argument?");
@@ -10763,8 +10765,7 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *Cand,
 
 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
 << (unsigned)FnKindPair.first << (unsigned)FnKindPair.second << FnDesc
-<< (FromExpr ? FromExpr->getSourceRange() : SourceRange()) << ToTy
-<< Name << I + 1;
+<< ToParamRange << ToTy << Name << I + 1;
 MaybeEmitInheritedConstructorNote(S, Cand->FoundDecl);
 return;
   }
@@ -10793,14 +10794,12 @@ static void DiagnoseBadConversion(Sema &S, 
OverloadCandidate *

[PATCH] D153359: [clang][Diagnostics] Fix distant source ranges in bad-conversion notes

2023-07-14 Thread Takuya Shimizu 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 rG176981ac58d3: [clang][Diagnostics] Fix distant source ranges 
in bad-conversion notes (authored by hazohelet).

Changed prior to commit:
  https://reviews.llvm.org/D153359?vs=536743&id=540401#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153359

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaOverload.cpp
  clang/test/Misc/diag-overload-cand-ranges.cpp
  clang/test/Misc/diag-overload-cand-ranges.mm

Index: clang/test/Misc/diag-overload-cand-ranges.mm
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.mm
@@ -0,0 +1,26 @@
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-arc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,ARC
+// RUN: not %clang_cc1 -fobjc-runtime-has-weak -fobjc-gc -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace -check-prefixes=CHECK,GC
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:15-[[@LINE+1]]:28}: note: {{.*}}: 1st argument
+void powerful(__strong id &);
+void lifetime_gcattr_mismatch() {
+  static __weak id weak_id;
+  powerful(weak_id);
+}
+
+// CHECK:  error: no matching function
+// ARC::{[[@LINE+2]]:11-[[@LINE+2]]:21}: note: {{.*}}: cannot implicitly convert
+// GC: :{[[@LINE+1]]:11-[[@LINE+1]]:21}: note: {{.*}}: no known conversion
+void func(char *uiui);
+
+__attribute__((objc_root_class))
+@interface Interface
+- (void)something;
+@end
+
+@implementation Interface
+- (void)something{
+func(self);
+}
+@end
Index: clang/test/Misc/diag-overload-cand-ranges.cpp
===
--- /dev/null
+++ clang/test/Misc/diag-overload-cand-ranges.cpp
@@ -0,0 +1,72 @@
+// RUN: not %clang_cc1 -fsyntax-only -fdiagnostics-print-source-range-info %s 2>&1 | FileCheck %s --strict-whitespace
+// CHECK:  error: no matching function
+template  struct mcdata {
+  typedef int result_type;
+};
+template  typename mcdata::result_type wrap_mean(mcdata const &);
+// CHECK:  :{[[@LINE+1]]:19-[[@LINE+1]]:53}: note: {{.*}}: no overload of 'wrap_mean'
+void add_property(double (*)(mcdata const &));
+void f() { add_property(&wrap_mean); }
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:10-[[@LINE+1]]:51}: note: {{.*}}: cannot pass pointer to generic address space
+void baz(__attribute__((opencl_private)) int *Data) {}
+void fizz() {
+  int *Nop;
+  baz(Nop);
+  // CHECK:error: no matching function
+  // CHECK::[[@LINE+1]]:53: note: {{.*}}: 'this' object is in address space '__private'
+  __attribute__((opencl_private)) static auto err = [&]() {};
+  err();
+}
+
+// CHECK:  error: no matching function
+struct Bar {
+// CHECK:  :{[[@LINE+1]]:26-[[@LINE+1]]:32}: note: {{.*}} would lose const qualifier
+static void foo(int num, int *X) {}
+// CHECK:  :{[[@LINE+1]]:17-[[@LINE+1]]:25}: note: {{.*}} no known conversion
+static void foo(int *err, int *x) {}
+};
+void bar(const int *Y) {
+  Bar::foo(5, Y);
+}
+
+struct InComp;
+
+struct A {};
+struct B : public A{};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+5]]:36-[[@LINE+5]]:50}: note: {{.*}}: cannot convert initializer
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+3]]:36-[[@LINE+3]]:50}: note: {{.*}}: cannot convert argument
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:11-[[@LINE+1]]:18}: note: {{.*}}: no known conversion
+void hoge(char aa, const char *bb, const A& third);
+
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:14-[[@LINE+1]]:16}: note: {{.*}}: cannot convert from base class
+void derived(B*);
+
+void func(const A &arg) {
+  hoge(1, "pass", {{{arg}}});
+  InComp *a;
+  hoge(1, "pass", a);
+  hoge("first", 5, 6);
+  A *b;
+  derived(b);
+}
+
+struct Q {
+  // CHECK:error: invalid operands
+  // CHECK::[[@LINE+1]]:6: note: {{.*}}: 'this' argument has type 'const Q'
+  Q &operator+(void*);
+};
+
+void fuga(const Q q) { q + 3; }
+
+template  class Type1 {};
+// CHECK:  error: no matching function
+// CHECK:  :{[[@LINE+1]]:43-[[@LINE+1]]:54}: note: {{.*}}: expects an lvalue
+template  void Function1(int zz, Type1 &x, int ww) {}
+
+void Function() { Function1(33, Type1<-42>(), 66); }
Index: clang/lib/Sema/SemaOverload.cpp
===
--- clang/lib/Sema/SemaOverload.cpp
+++ clang/lib/Sema/SemaOverload.cpp
@@ -10753,6 +10753,8 @@
   Expr *FromExpr = Conv.Bad.FromExpr;
   QualType FromTy = Conv.Bad.getFromType();
   QualType ToTy = Conv.Bad.getToType();
+  SourceRange ToParamRange =
+  !isO

[PATCH] D154869: [Flang] [FlangRT] Implement FlangRT library as solution to Flang's runtime LLVM integration

2023-07-14 Thread Paul Scoropan via Phabricator via cfe-commits
pscoro updated this revision to Diff 540413.
pscoro added a comment.

Decided to remove all the commented code related to the previous approach 
(wrapper library). The code that exists currently is for the object library 
approach and is functional.

Currently, on phabricator there is a failing x64 Windows build. The failure 
happens during building, the compiler seems to run out of heap space? I don't 
see how this error could be related to my patch but if I am wrong and it is, 
please let me know.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154869

Files:
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  flang-rt/CMakeLists.txt
  flang/CMakeLists.txt
  flang/cmake/modules/AddFlang.cmake
  flang/lib/Decimal/CMakeLists.txt
  flang/runtime/CMakeLists.txt
  flang/test/CMakeLists.txt
  flang/test/Driver/linker-flags.f90
  flang/test/lit.cfg.py
  flang/tools/flang-driver/CMakeLists.txt
  lld/COFF/MinGW.cpp
  llvm/CMakeLists.txt
  llvm/projects/CMakeLists.txt
  runtimes/CMakeLists.txt

Index: runtimes/CMakeLists.txt
===
--- runtimes/CMakeLists.txt
+++ runtimes/CMakeLists.txt
@@ -19,7 +19,7 @@
 
 # We order libraries to mirror roughly how they are layered, except that compiler-rt can depend
 # on libc++, so we put it after.
-set(LLVM_DEFAULT_RUNTIMES "libc;libunwind;libcxxabi;pstl;libcxx;compiler-rt;openmp")
+set(LLVM_DEFAULT_RUNTIMES "libc;libunwind;libcxxabi;pstl;libcxx;compiler-rt;openmp;flang-rt")
 set(LLVM_SUPPORTED_RUNTIMES "${LLVM_DEFAULT_RUNTIMES};llvm-libgcc")
 set(LLVM_ENABLE_RUNTIMES "" CACHE STRING
   "Semicolon-separated list of runtimes to build, or \"all\" (${LLVM_DEFAULT_RUNTIMES}). Supported runtimes are ${LLVM_SUPPORTED_RUNTIMES}.")
Index: llvm/projects/CMakeLists.txt
===
--- llvm/projects/CMakeLists.txt
+++ llvm/projects/CMakeLists.txt
@@ -6,6 +6,7 @@
   if(IS_DIRECTORY ${entry} AND EXISTS ${entry}/CMakeLists.txt)
 if((NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/compiler-rt) AND
(NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/dragonegg) AND
+   (NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/flang-rt) AND
(NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/libcxx) AND
(NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/libcxxabi) AND
(NOT ${entry} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}/libunwind) AND
@@ -42,6 +43,8 @@
 add_llvm_external_project(dragonegg)
 add_llvm_external_project(openmp)
 
+add_llvm_external_project(flang-rt)
+
 if(LLVM_INCLUDE_TESTS)
   add_llvm_external_project(cross-project-tests)
 endif()
Index: llvm/CMakeLists.txt
===
--- llvm/CMakeLists.txt
+++ llvm/CMakeLists.txt
@@ -149,7 +149,10 @@
 # As we migrate runtimes to using the bootstrapping build, the set of default runtimes
 # should grow as we remove those runtimes from LLVM_ENABLE_PROJECTS above.
 set(LLVM_DEFAULT_RUNTIMES "libcxx;libcxxabi;libunwind")
-set(LLVM_SUPPORTED_RUNTIMES "libc;libunwind;libcxxabi;pstl;libcxx;compiler-rt;openmp;llvm-libgcc")
+if ("flang" IN_LIST LLVM_ENABLE_PROJECTS)
+  set(LLVM_DEFAULT_RUNTIMES "libcxx;libcxxabi;libunwind;flang-rt")
+endif()
+set(LLVM_SUPPORTED_RUNTIMES "libc;libunwind;libcxxabi;pstl;libcxx;compiler-rt;openmp;llvm-libgcc;flang-rt")
 set(LLVM_ENABLE_RUNTIMES "" CACHE STRING
   "Semicolon-separated list of runtimes to build, or \"all\" (${LLVM_DEFAULT_RUNTIMES}). Supported runtimes are ${LLVM_SUPPORTED_RUNTIMES}.")
 if(LLVM_ENABLE_RUNTIMES STREQUAL "all")
@@ -171,6 +174,11 @@
   endif()
 endif()
 
+if ("flang" IN_LIST LLVM_ENABLE_PROJECTS AND NOT "flang-rt" IN_LIST LLVM_ENABLE_RUNTIMES)
+  message(STATUS "Enabling flang-rt to be built with the flang project")
+  list(APPEND LLVM_ENABLE_RUNTIMES "flang-rt")
+endif()
+
 # LLVM_ENABLE_PROJECTS_USED is `ON` if the user has ever used the
 # `LLVM_ENABLE_PROJECTS` CMake cache variable.  This exists for
 # several reasons:
Index: lld/COFF/MinGW.cpp
===
--- lld/COFF/MinGW.cpp
+++ lld/COFF/MinGW.cpp
@@ -50,8 +50,7 @@
   "libc++",
   "libc++abi",
   "libFortran_main",
-  "libFortranRuntime",
-  "libFortranDecimal",
+  "libflang-rt",
   "libunwind",
   "libmsvcrt",
   "libucrtbase",
Index: flang/tools/flang-driver/CMakeLists.txt
===
--- flang/tools/flang-driver/CMakeLists.txt
+++ flang/tools/flang-driver/CMakeLists.txt
@@ -19,8 +19,7 @@
   # These libraries are used in the linker invocation generated by the driver
   # (i.e. when constructing the linker job). Without them the driver would be
   # unable to generate executables.
-  FortranRuntime
-  FortranDecimal
+  flang-rt
   Fortran_main
 )
 
Index: flang/test/lit.cfg.py
==

[PATCH] D155294: [Driver][RISCV] Find baremetal multilibs using YAML for GNU toolchain

2023-07-14 Thread Joseph Faulls via Phabricator via cfe-commits
Joe created this revision.
Joe added reviewers: michaelplatings, kito-cheng.
Joe added a project: clang.
Herald added subscribers: jobnoorman, luke, shiva0217, VincentWu, vkmr, 
frasercrmck, luismarques, apazos, sameer.abuasal, s.egerton, Jim, benna, 
psnobl, abidh, jocewei, PkmX, the_o, brucehoult, MartinMosbeck, rogfer01, 
edward-jones, zzheng, jrtc27, niosHD, sabuasal, simoncook, johnrusso, rbar, 
asb, kristof.beyls, arichardson, emaste.
Herald added a project: All.
Joe requested review of this revision.
Herald added subscribers: cfe-commits, wangpc, eopXD, MaskRay.

This patch allows usage of multilib.yaml 
 when using a riscv gnu 
toolchain

This could certainly land as three separate patches, but I wanted to put this 
up as one to gather feedback to make sure the direction makes sense.

These are the main discussion points I want to bring to attention:

1. For the RISCVMultilibFlags, the mabi flag is used in combination with all 
the march extension features (e.g +m). Notably, this doesn't align with the 
current arm/aarch64 multilib flags, which all flags corresponding to the 
command line flag. E.G `-march=`. Does this violate a particular design 
decision, or can any target decide on whatever multilib flags they want?

2. The location of multilib.yaml for a gnu toolchain is in the lib directory of 
the sysroot. E.G `riscv64-unknown-elf/lib/multilib.yaml`. This differs from the 
baremetal location of "lib/clang-runtimes".

3. Does it make more sense to implement finding multilibs using yaml for riscv 
in the baremetal toolchain first? I was planning on doing it after.

Theoretically, I think this matching of multilibs could be done without the 
need for multilib.yaml, but it is indeed much easier considering the logic is 
already there.


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155294

Files:
  clang/include/clang/Driver/ToolChain.h
  clang/lib/Driver/ToolChain.cpp
  clang/lib/Driver/ToolChains/BareMetal.cpp
  clang/lib/Driver/ToolChains/Gnu.cpp
  clang/lib/Driver/ToolChains/Gnu.h
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32i/ilp32/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32i/ilp32/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32iac/ilp32/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32iac/ilp32/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32im/ilp32/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32im/ilp32/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imac/ilp32/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imafc/ilp32f/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv32imafc/ilp32f/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imac/lp64/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imafdc/lp64d/crtbegin.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/lib/gcc/riscv64-unknown-elf/8.2.0/rv64imafdc/lp64d/crtend.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/bin/ld
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/multilib.yaml
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv32i/ilp32/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv32iac/ilp32/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv32im/ilp32/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv32imac/ilp32/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv32imafc/ilp32f/crt0.o
  
clang/test/Driver/Inputs/multilib_riscv_elf_sdk_yaml/riscv64-unknown-elf/lib/rv64imac/lp64/crt0.o
  clang/test/Driver/riscv-toolchain-multilib-yaml.c

Index: clang/test/Driver/riscv-toolchain-multilib-yaml.c
===
--- /dev/null
+++ clang/test/Driver/riscv-toolch

[PATCH] D125765: [RISCV] Add type aliases float16_t, float32_t and float64_t

2023-07-14 Thread Alex Bradbury via Phabricator via cfe-commits
asb added a reviewer: eopXD.
asb added a comment.

Adding eop as a reviewer.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D125765

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


[PATCH] D155217: [clang-tidy][include-cleaner] Don't warn for the same symbol twice

2023-07-14 Thread Piotr Zegar via Phabricator via cfe-commits
PiotrZSL added a comment.

Check emits warnings per symbol/usage, but fixes header includes, won't it make 
duplicate includes ?

Problem that I see is that multiple warnings for same symbol will generate lot 
of noise.
And when dealing with diff why developer should be forced to fix legacy issues 
just because he/she used same symbol, after all issue is actually peer symbol, 
whatever how many times is used.
Stil...

I cannot make "decision" here.
Both patch author, and check author got a point.

There is only one option, could this be made configurable ?


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

https://reviews.llvm.org/D155217

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-14 Thread Richard Dzenis via Phabricator via cfe-commits
RIscRIpt updated this revision to Diff 540427.
RIscRIpt added a comment.

Rebased onto main


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153914

Files:
  clang/include/clang/Basic/DiagnosticGroups.td
  clang/include/clang/Basic/DiagnosticSemaKinds.td
  clang/include/clang/Basic/TokenKinds.h
  clang/include/clang/Parse/Parser.h
  clang/include/clang/Sema/Sema.h
  clang/lib/Parse/ParseExpr.cpp
  clang/lib/Sema/Sema.cpp
  clang/lib/Sema/SemaExpr.cpp
  clang/test/Sema/ms_predefined_expr.cpp

Index: clang/test/Sema/ms_predefined_expr.cpp
===
--- clang/test/Sema/ms_predefined_expr.cpp
+++ clang/test/Sema/ms_predefined_expr.cpp
@@ -1,9 +1,62 @@
 // RUN: %clang_cc1 %s -fsyntax-only -Wmicrosoft -verify -fms-extensions
 
+using size_t = __SIZE_TYPE__;
+
 void f() {
  const char a[] = __FUNCTION__; // expected-warning{{initializing an array from a '__FUNCTION__' predefined identifier is a Microsoft extension}}
  const char b[] = __FUNCDNAME__; // expected-warning{{initializing an array from a '__FUNCDNAME__' predefined identifier is a Microsoft extension}}
  const char c[] = __FUNCSIG__; // expected-warning{{initializing an array from a '__FUNCSIG__' predefined identifier is a Microsoft extension}}
  const char d[] = __func__; // expected-warning{{initializing an array from a '__func__' predefined identifier is a Microsoft extension}}
  const char e[] = __PRETTY_FUNCTION__; // expected-warning{{initializing an array from a '__PRETTY_FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t f[] = L__FUNCTION__; // expected-warning{{initializing an array from a 'L__FUNCTION__' predefined identifier is a Microsoft extension}}
+ const wchar_t g[] = L__FUNCSIG__; // expected-warning{{initializing an array from a 'L__FUNCSIG__' predefined identifier is a Microsoft extension}}
+}
+
+// Test concatenation
+
+void eat_const_char_p(const char*);
+void eat_const_wchar_p(const wchar_t*);
+
+void test_concat() {
+  eat_const_char_p("s" __FUNCTION__); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCDNAME__); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCSIG__); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_char_p(__FUNCTION__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p(__FUNCDNAME__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p(__FUNCSIG__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_char_p("s" __FUNCTION__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCDNAME__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCDNAME__' is a Microsoft extension}}
+  eat_const_char_p("s" __FUNCSIG__ "s"); // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+}
+
+void test_wide_concat() {
+  eat_const_wchar_p(L"s" L__FUNCTION__); // expected-warning{{concatenation of predefined identifier 'L__FUNCTION__' is a Microsoft extension}}
+  eat_const_wchar_p(L"s" L__FUNCSIG__); // expected-warning{{concatenation of predefined identifier 'L__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_wchar_p(L__FUNCTION__ L"s"); // expected-warning{{concatenation of predefined identifier 'L__FUNCTION__' is a Microsoft extension}}
+  eat_const_wchar_p(L__FUNCSIG__ L"s"); // expected-warning{{concatenation of predefined identifier 'L__FUNCSIG__' is a Microsoft extension}}
+
+  eat_const_wchar_p(L"s" L__FUNCTION__ L"s"); // expected-warning{{concatenation of predefined identifier 'L__FUNCTION__' is a Microsoft extension}}
+  eat_const_wchar_p(L"s" L__FUNCSIG__ L"s"); // expected-warning{{concatenation of predefined identifier 'L__FUNCSIG__' is a Microsoft extension}}
+}
+
+const char* test_return() {
+  return __FUNCTION__ "s" __FUNCSIG__; // expected-warning{{concatenation of predefined identifier '__FUNCTION__' is a Microsoft extension}} \
+   // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+}
+
+void test_struct_init_fn() {
+  struct test_struct_init {
+const char* str;
+  } struct_init = { "struct: " __FUNCSIG__ }; // expected-warning{{concatenation of predefined identifier '__FUNCSIG__' is a Microsoft extension}}
+}
+
+constexpr size_t operator""_len(const char*, size_t len) {
+return len;
+}
+
+void test_udliteral() {
+static_assert(__FUNCTION__ ""_len == 14)

[PATCH] D154123: [HIP] Start document HIP support by clang

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 540430.
yaxunl added a comment.

revised by comments


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

https://reviews.llvm.org/D154123

Files:
  clang/docs/HIPSupport.rst

Index: clang/docs/HIPSupport.rst
===
--- /dev/null
+++ clang/docs/HIPSupport.rst
@@ -0,0 +1,134 @@
+.. raw:: html
+
+  
+.none { background-color: #FF }
+.part { background-color: #99 }
+.good { background-color: #CCFF99 }
+  
+
+.. role:: none
+.. role:: part
+.. role:: good
+
+.. contents::
+   :local:
+
+===
+HIP Support
+===
+
+`HIP (Heterogeneous-Compute Interface for Portability) `_
+is a C++ Runtime API and Kernel Language that allows developers to create portable applications for
+GPUs from single source code.
+
+Clang supports HIP on `ROCm platform `_.
+
+Example Usage
+=
+
+To compile a HIP program, you can use the following command:
+
+.. code-block:: shell
+
+   clang -c --offload-arch=gfx906 -xhip test.cpp -o test.o
+
+To link a HIP program, you can use this command:
+
+.. code-block:: shell
+
+   clang --hip-link --offload-arch=gfx906 test.o -o test
+
+In the above commands, ``gfx906`` is the GPU architecture that the code is being compiled for.
+The supported GPU architectures can be found in the `AMDGPU Processor Table `_.
+Alternatively, you can run the ``amdgpu-arch`` tool that comes with Clang to list the GPU architecture on your sytem:
+
+.. code-block:: shell
+
+   amdgpu-arch
+
+You can also use ``--offload-arch=native`` to let ``amdgpu-arch`` automatically detect the GPU architectures on your system:
+
+.. code-block:: shell
+
+   clang -c --offload-arch=native -xhip test.cpp -o test.o
+
+Path Setting for Dependencies
+=
+
+Compiling a HIP program depends on the HIP runtime and device library. The paths to the HIP runtime and device libraries can be specified either using compiler options or environment variables. The paths can also be set through the ROCm path if they follow the ROCm installation directory structure.
+
+Order of Precedence for HIP Path
+
+
+1. ``--hip-path`` compiler option
+2. ``HIP_PATH`` environment variable *(use with caution)*
+3. ``--rocm-path`` compiler option
+4. ``ROCM_PATH`` environment variable *(use with caution)*
+5. Default automatic detection (relative to Clang or at the default ROCm installation location)
+
+Order of Precedence for Device Library Path
+---
+
+1. ``--hip-device-lib-path`` compiler option
+2. ``HIP_DEVICE_LIB_PATH`` environment variable *(use with caution)*
+3. ``--rocm-path`` compiler option
+4. ``ROCM_PATH`` environment variable *(use with caution)*
+5. Default automatic detection (relative to Clang or at the default ROCm installation location)
+
+
+.. list-table::
+   :header-rows: 1
+
+   * - Compiler Option
+ - Environment Variable
+ - Description
+ - Default Value
+   * - ``--rocm-path=``
+ - ``ROCM_PATH``
+ - Specifies the ROCm installation path.
+ - Automatic detection
+   * - ``--hip-path=``
+ - ``HIP_PATH``
+ - Specifies the HIP runtime installation path.
+ - Determined by ROCm directory structure
+   * - ``--hip-device-lib-path=``
+ - ``HIP_DEVICE_LIB_PATH``
+ - Specifies the HIP device library installation path.
+ - Determined by ROCm directory structure
+
+.. note::
+
+   We recommend using the compiler options as the primary method for specifying these paths. While the environment variables ``ROCM_PATH``, ``HIP_PATH``, and ``HIP_DEVICE_LIB_PATH`` are supported, their use can lead to implicit dependencies that might cause issues in the long run. Use them with caution.
+
+
+Predefined Macros
+=
+
+.. list-table::
+   :header-rows: 1
+
+   * - Macro
+ - Description
+   * - ``__CLANG_RDC__``
+ - Defined when Clang is compiling code in Relocatable Device Code (RDC) mode. RDC, enabled with the ``-fgpu-rdc`` compiler option, is necessary for linking device codes across translation units.
+   * - ``__HIP__``
+ - Defined when compiling with HIP language support, indicating that the code targets the HIP environment.
+   * - ``__HIPCC__``
+ - Alias to ``__HIP__``.
+   * - ``__HIP_DEVICE_COMPILE__``
+ - Defined during device code compilation in Clang's separate compilation process for the host and each offloading GPU architecture.
+   * - ``__HIP_MEMORY_SCOPE_SINGLETHREAD``
+ - Represents single-thread memory scope in HIP (value is 1).
+   * - ``__HIP_MEMORY_SCOPE_WAVEFRONT``
+ - Represents wavefront memory scope in HIP (value is 2).
+   * - ``__HIP_MEMORY_SCOPE_WORKGROUP``
+ - Represents workgroup memory scope in HIP (value is 3).
+   * - ``__HIP_MEMORY_SCOPE_AGENT``
+ 

[PATCH] D154123: [HIP] Start document HIP support by clang

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 2 inline comments as done.
yaxunl added inline comments.



Comment at: clang/docs/HIPSupport.rst:49
+
+You can also use ``--offload-arch=native`` to let ``amdgpu-arch`` 
automatically detect the GPU architecture on your system:
+

arsenm wrote:
> s/architecture/architectures
done



Comment at: clang/docs/HIPSupport.rst:99
+
+Note: The compiler options override environment variables. Specifying HIP 
runtime and device library paths individually will override the ROCm path.
+

arsenm wrote:
> We should really not have the environment variables I wouldn't go out of the 
> way to advertise them, just mark as deprecated
added warnings to discourage use of env vars


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

https://reviews.llvm.org/D154123

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


[PATCH] D154423: [clang][analyzer] Add all success/failure messages to StdLibraryFunctionsChecker.

2023-07-14 Thread Balázs Kéri via Phabricator via cfe-commits
balazske added a comment.

About the "`fileno` with standard stream" problem: I do not see an always good 
solution for this case because these standard streams are global variables. If 
we want to be exact, we can not know much about these at analysis start unless 
it is the `main` function. The standard stream variables can be overwritten by 
the program or opened or closed, even if not, any unknown function can change 
the state of these. Because the possibility to change these, the file number 
can change.
At least it is possible to add a checker option for "the program does not 
manipulate standard streams". If this is true the standard streams are 
different values from all other opened streams and the file number is known. 
This can be the default value, most programs probably work this way.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154423

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


[PATCH] D86310: [X86] Align i128 to 16 bytes in x86-64 datalayout

2023-07-14 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added a comment.

@JohnReagan That is a valid concern, and I hope it reassures you that if things 
were working before, I would never be on board with this change. For example, 
it would generally be better if long double were 8-byte-aligned, but the x86 
32-bit ABI specifies that it is 4-byte-aligned, and that is set in stone. I 
would be against any change in LLVM's ABI that changed their alignment, even if 
it would speed up code. I still occasionally run 20-year-old binaries, myself, 
that are dynamically linked to shared object files built with current 
compilers. Compatibility matters, I would not be on board with a change that 
breaks things like that. But that is not what is happening here. For i128, what 
clang implemented matched GCC, what LLVM implemented deviated from GCC/clang, 
but LLVM assumed that its implementation actually did match GCC/clang and code 
crashed as a result. This change would make it so that LLVM starts to also 
match GCC/clang, to change things from something that doesn't work to something 
that does work, and because things crash in current LLVM, I do not believe 
there can be much code out there that relies on the current behaviour. As you 
say, you aren't using i128/f128 yourself either. I hope that when I can update 
the patch, you can check that this does not cause problems for you.

@craig.topper Just to make sure, are you okay with me 'commandeering' this 
change and updating it?


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

https://reviews.llvm.org/D86310

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


[PATCH] D155064: [clang][SemaCXX] Diagnose tautological uses of consteval if and is_constant_evaluated

2023-07-14 Thread Mark de Wever via Phabricator via cfe-commits
Mordante added inline comments.



Comment at: 
libcxx/test/std/utilities/meta/meta.const.eval/is_constant_evaluated.verify.cpp:27
   static_assert(!std::is_constant_evaluated(), "");
-  // expected-warning@-1 0-1 {{'std::is_constant_evaluated' will always 
evaluate to 'true' in a manifestly constant-evaluated expression}}
+  // expected-warning@-1 0-1 {{'std::is_constant_evaluated' will always 
evaluate to true in this context}}
 #endif

hazohelet wrote:
> philnik wrote:
> > Mordante wrote:
> > > Since libc++ support the latest ToT Clang and the last two official 
> > > releases this wont work. The `expected-warning` needs to be a 
> > > `expected-warning-re` that works for both the new and old diagnostic
> > You can also just shorten it to `'std::is_constant_evaluated' will always 
> > evaluate to`. Seems good enough to me.
> Thanks!
I really would like a regex. To me the current message misses an important 
piece of information; the `true` part. I care less about the rest of the 
message, but stripping the `true` means a warning like 
`std::is_constant_evaluated' will always evaluate to FALSE` would be valid too.


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

https://reviews.llvm.org/D155064

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


[PATCH] D144829: [WIP][BPF] Add a few new insns under cpu=v4

2023-07-14 Thread Alexei Starovoitov via Phabricator via cfe-commits
ast added inline comments.



Comment at: llvm/lib/Target/BPF/BPFInstrInfo.td:56
 def BPFNoALU32 : Predicate<"!Subtarget->getHasAlu32()">;
+def BPFHasCPUv4_ldsx : Predicate<"Subtarget->getCPUv4_ldsx()">;
+def BPFHasCPUv4_movsx : Predicate<"Subtarget->getCPUv4_movsx()">;

Here and elsewhere... let's drop CPUv4 mid prefix. imo the extra verbosity 
doesn't improve readability.
Same with the flag: disable-cpuv4-movsx. I can be disable-movsx.

s/BPFHasCPUv4_ldsx/BPFHasLdsx/
s/getCPUv4_bswap/getHasBswap/ or even shorter hasBswap ?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D144829

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


[PATCH] D86310: [X86] Align i128 to 16 bytes in x86-64 datalayout

2023-07-14 Thread Reid Kleckner via Phabricator via cfe-commits
rnk added a comment.

In D86310#4501170 , @hvdijk wrote:

> For example, it would generally be better if long double were 8-byte-aligned, 
> but the x86 32-bit ABI specifies that it is 4-byte-aligned, and that is set 
> in stone. I would be against any change in LLVM's ABI that changed their 
> alignment, even if it would speed up code.

That may be your view, but other users rely on the `-malign-double` flag 
(D19734 ) to get the new behavior, despite the 
ABI concerns. Specifically, it mattered for users passing structs from CPU to 
GPU, because the GPU doesn't tolerate misaligned doubles well. With that in 
mind, I wouldn't describe this ABI rule as being "set in stone", but I 
understand your perspective.

Returning to the patch at hand, it sounds like we have consensus that the next 
step is to teach auto-upgrade to traverse the module looking for uses of a 
particular type in structs and IR. That logic could be reused in the future to 
solve similar problems when we need to adjust the layout of exotic types.


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

https://reviews.llvm.org/D86310

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


[PATCH] D86310: [X86] Align i128 to 16 bytes in x86-64 datalayout

2023-07-14 Thread Harald van Dijk via Phabricator via cfe-commits
hvdijk added a comment.

In D86310#4501240 , @rnk wrote:

> In D86310#4501170 , @hvdijk wrote:
>
>> For example, it would generally be better if long double were 
>> 8-byte-aligned, but the x86 32-bit ABI specifies that it is 4-byte-aligned, 
>> and that is set in stone. I would be against any change in LLVM's ABI that 
>> changed their alignment, even if it would speed up code.
>
> That may be your view, but other users rely on the `-malign-double` flag 
> (D19734 ) to get the new behavior, despite 
> the ABI concerns. Specifically, it mattered for users passing structs from 
> CPU to GPU, because the GPU doesn't tolerate misaligned doubles well. With 
> that in mind, I wouldn't describe this ABI rule as being "set in stone", but 
> I understand your perspective.

As long as it is an option, it is fine, that will not cause compatibility 
issues.

> Returning to the patch at hand, it sounds like we have consensus that the 
> next step is to teach auto-upgrade to traverse the module looking for uses of 
> a particular type in structs and IR. That logic could be reused in the future 
> to solve similar problems when we need to adjust the layout of exotic types.

That is not my understanding of the consensus that we have, that is something 
that you asked for, then asked who asked for it, and are now again asking for. 
I do not see anyone else having asked for this, and I repeat that I think it is 
an unreasonable amount of work.


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

https://reviews.llvm.org/D86310

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


[PATCH] D112921: [clang] Enable sized deallocation by default in C++14 onwards

2023-07-14 Thread Mark de Wever via Phabricator via cfe-commits
Mordante added inline comments.



Comment at: 
libcxx/test/std/language.support/support.dynamic/new.delete/new.delete.array/sized_delete_array14.pass.cpp:16
+// Sized deallocation was added in macOS 10.12 and aligned OSes.
+// XFAIL: use_system_cxx_lib && target={{.+}}-apple-macosx10.{{9|10|11}}
 

Maybe as a pragmatic solution
```
// TODO(mordante) fix this test after updating clang in Docker
// UNSUPPORTED: clang-17
```
The same for the other failing test. Then I'll fix this once the libc++ CI can 
be updated with this fix included.




Comment at: libcxx/utils/ci/buildkite-pipeline.yml:148
   #
-  - wait
+  # - wait
 

Please undo the changes to this file.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D112921

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


[PATCH] D146777: [clang] Preliminary fat-lto-object support

2023-07-14 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added a comment.



In D146777#4499608 , @MaskRay wrote:

> Thanks for the update. Can you add a comment for the `-funified-lto` 
> combination? It's unclear what it does...

ugh, I had put comments above each compiler invocation, but forgot that `#` 
makes lines ignored in the commit message. Thanks for pointing that out, as I 
hadn't noticed after updating.

> `clang -flto=thin -ffat-lto-objects -funified-lto -fuse-ld=lld foo.c`
>
> I've left some comments about missing test coverage.

ah, sorry, for some reason I read your last comment as `test locally to confirm 
it works` instead of the obvious `write a proper test`. I will correct that 
shortly.




Comment at: clang/test/CodeGen/embed-fat-lto-objects.c:3
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full 
-ffat-lto-objects -emit-llvm < %s  | FileCheck %s --check-prefixes=FULL,SPLIT
+
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=thin 
-fsplit-lto-unit -ffat-lto-objects -emit-llvm < %s  | FileCheck %s 
--check-prefixes=THIN,SPLIT

MaskRay wrote:
> We need a `-emit-obj` test with `// REQUIRES: x86-registered-target`.
> Use llvm-readelf to check that .llvm.lto section is present.
> 
> We also need a `-S` test, otherwise the behavior of driver `clang -S 
> -ffat-lto-objects` is untested.
> 
> 
Sure, I can do both of those, but as a general question, isn't the generation 
of assembly the responsibility of the backend? I believe we have some tests 
that use `llc` on the the modules that have gone through the FatLTO pipeline. 
Is that insufficient?

Also, as a best practice, do you know if there are specific types of changes to 
`clang` that imply that we'd need to test `-S`? Sorry for all the questions, 
but I'm trying to get a bit better in how I structure my patches and approach 
testing.



Comment at: clang/test/Driver/fat-lto-objects.c:10
+// CHECK-CC-NOLTO-NOT: -ffat-lto-objects
+// CHECK-CC-NOLTO-NOT: warning: argument unused during compilation: 
'-ffat-lto-objects'
+

MaskRay wrote:
> This NOT pattern has no effect as warnings are usually emitted before -cc1.
> 
> You can use `--implicit-check-not=warning:`
I'm happy to try that suggestion, but isn't this testing the generated `cc1` 
command from the driver(e.g.,  because we're using `%clang` and not 
`%clang_cc1`)? I //think// that should still produce the warning, shouldn't it? 

It's been a while since I made the patch, but I recall writing this test, 
having it fail, and then applying the change to stop it from being an `unused 
argument`... 

Also, thanks for all the great feedback on testing. Despite writing many(well, 
more than a few at least) `lit` tests, I'm still surprised by lots of 
behaviors, and your suggestions have been very helpful.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146777

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


[clang] 3c0a136 - [clang][Sema] Suggest static_cast in C++ code

2023-07-14 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2023-07-14T16:22:06Z
New Revision: 3c0a136ce4b724221a7f75b656b9f7af3de6b64c

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

LOG: [clang][Sema] Suggest static_cast in C++ code

This patch changes the -Wformat diagnostic to suggest static_cast over
a C-style cast for {,Objective}C++ when recommending the argument be
casted rather than changing the format string.

Before:
```
clang/test/FixIt/format.mm:11:16: warning: format specifies type 'unichar' (aka 
'unsigned short') but the argument has type 'wchar_t' [-Wformat]
   11 |   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
  |   ~~   ^~
  |(unsigned short)
```
After:
```
clang/test/FixIt/format.mm:11:16: warning: format specifies type 'unichar' (aka 
'unsigned short') but the argument has type 'wchar_t' [-Wformat]
   11 |   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
  |   ~~   ^~
  |static_cast( )
```

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

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaChecking.cpp
clang/test/FixIt/format.mm

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 53a83b9c94176d..0423c054bd0b58 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -415,6 +415,8 @@ Improvements to Clang's diagnostics
 source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
 void func(int aa, int bb);
  ^~~
+- ``-Wformat`` cast fix-its will now suggest ``static_cast`` instead of 
C-style casts
+  for C++ code.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index f9a50f6ef3be6f..66a1a8f3f90ee3 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11184,9 +11184,9 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier &FS,
   // if necessary).
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
-  CastFix << "(";
+  CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
   IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
-  CastFix << ")";
+  CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
   if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
@@ -11197,7 +11197,7 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier &FS,
 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
 Hints.push_back(FixItHint::CreateReplacement(CastRange, 
CastFix.str()));
 
-  } else if (!requiresParensToAddCast(E)) {
+  } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
 // If the expression has high enough precedence,
 // just write the C-style cast.
 Hints.push_back(

diff  --git a/clang/test/FixIt/format.mm b/clang/test/FixIt/format.mm
index eed7c981f2c455..f630db41b37844 100644
--- a/clang/test/FixIt/format.mm
+++ b/clang/test/FixIt/format.mm
@@ -9,22 +9,22 @@ void test_percent_C() {
 
   const wchar_t wchar_data = L'a';
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unsigned short)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast(
 
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"static_cast(
 
   typedef unsigned short unichar;
 
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unichar)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast(
 
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
+  // CHECK: 
fix

[clang] 563a23c - [clang][Sema] Add fixit for scoped enum format error

2023-07-14 Thread Alex Brachet via cfe-commits

Author: Alex Brachet
Date: 2023-07-14T16:23:22Z
New Revision: 563a23c824db22da3ea378e8179fcc7072e897ec

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

LOG: [clang][Sema] Add fixit for scoped enum format error

This helps transition code bases to handle the new warning added in 3632e2f5179

Before:
```
clang/test/FixIt/format.cpp:10:16: warning: format specifies type 'int' but the 
argument has type 'N::E' [-Wformat]
   10 |   printf("%d", N::E::One); // expected-warning{{format specifies type 
'int' but the argument has type 'N::E'}}
  |   ~~   ^
  |   %d
```
After:
```
clang/test/FixIt/format.cpp:10:16: warning: format specifies type 'int' but the 
argument has type 'N::E' [-Wformat]
   10 |   printf("%d", N::E::One); // expected-warning{{format specifies type 
'int' but the argument has type 'N::E'}}
  |   ~~   ^
  |static_cast( )
```

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

Added: 
clang/test/FixIt/format.cpp

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

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 0423c054bd0b58..d55757183d58e9 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -417,6 +417,9 @@ Improvements to Clang's diagnostics
  ^~~
 - ``-Wformat`` cast fix-its will now suggest ``static_cast`` instead of 
C-style casts
   for C++ code.
+- ``-Wformat`` will no longer suggest a no-op fix-it for fixing scoped enum 
format
+  warnings. Instead, it will suggest casting the enum object to the type 
specified
+  in the format string.
 
 Bug Fixes in This Version
 -

diff  --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index 66a1a8f3f90ee3..b09d0383b4bd9a 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -11077,12 +11077,15 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier &FS,
   assert(Match != ArgType::MatchPromotion);
   // Look through unscoped enums to their underlying type.
   bool IsEnum = false;
+  bool IsScopedEnum = false;
   if (auto EnumTy = ExprTy->getAs()) {
 if (EnumTy->isUnscopedEnumerationType()) {
   ExprTy = EnumTy->getDecl()->getIntegerType();
   // This controls whether we're talking about the underlying type or not,
   // which we only want to do when it's an unscoped enum.
   IsEnum = true;
+} else {
+  IsScopedEnum = true;
 }
   }
 
@@ -11148,7 +11151,7 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier &FS,
 
 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, 
SpecifierLen);
 
-if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
+if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
   unsigned Diag;
   switch (Match) {
   case ArgType::Match:
@@ -11185,11 +11188,17 @@ CheckPrintfHandler::checkFormatExpr(const 
analyze_printf::PrintfSpecifier &FS,
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
   CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
-  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
+  if (IsScopedEnum) {
+CastFix << AT.getRepresentativeType(S.Context).getAsString(
+S.Context.getPrintingPolicy());
+  } else {
+IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
+  }
   CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
+  if ((!AT.matchesType(S.Context, IntendedTy) && !IsScopedEnum) ||
+  ShouldNotPrintDirectly)
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {

diff  --git a/clang/test/FixIt/format.cpp b/clang/test/FixIt/format.cpp
new file mode 100644
index 00..9cc4c2600eb667
--- /dev/null
+++ b/clang/test/FixIt/format.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -Wformat %s 
2>&1 | FileCheck %s
+
+extern "C" int printf(const char *, ...);
+
+namespace N {
+  enum class E { One };
+}
+
+void a() {
+  printf("%d", N::E::One); // expected-warning{{format specifies type 'int' 
but the argument has type 'N::E'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast("
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:25-[[@LINE-2]]:25}:")"
+
+  printf("%hd", N::E::One);
+  // CHECK: "static_cast("
+
+  printf("%hu", N::E::One);
+  // CHECK: "static_cast("
+}



___
cfe-commits maili

[PATCH] D153622: [clang][Sema] Suggest static_cast in C++ code

2023-07-14 Thread Alex Brachet 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 rG3c0a136ce4b7: [clang][Sema] Suggest static_cast in C++ code 
(authored by abrachet).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D153622?vs=535074&id=540454#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153622

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/FixIt/format.mm


Index: clang/test/FixIt/format.mm
===
--- clang/test/FixIt/format.mm
+++ clang/test/FixIt/format.mm
@@ -9,22 +9,22 @@
 
   const wchar_t wchar_data = L'a';
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unsigned short)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast(
 
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"static_cast(
 
   typedef unsigned short unichar;
 
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unichar)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast(
 
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 
'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
+  // CHECK: 
fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"static_cast(
 
   NSLog(@"%C", 0.0); // expected-warning{{format specifies type 'unichar' (aka 
'unsigned short') but the argument has type 'double'}}
   // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%f"
-  // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unichar)"
+  // CHECK-NOT: 
fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"static_cast(
 }
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -11184,9 +11184,9 @@
   // if necessary).
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
-  CastFix << "(";
+  CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
   IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
-  CastFix << ")";
+  CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
   if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
@@ -11197,7 +11197,7 @@
 SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
 Hints.push_back(FixItHint::CreateReplacement(CastRange, 
CastFix.str()));
 
-  } else if (!requiresParensToAddCast(E)) {
+  } else if (!requiresParensToAddCast(E) && !S.LangOpts.CPlusPlus) {
 // If the expression has high enough precedence,
 // just write the C-style cast.
 Hints.push_back(
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -415,6 +415,8 @@
 source:1:6: note: candidate function not viable: no known conversion from 
'const char[4]' to 'int' for 2nd argument
 void func(int aa, int bb);
  ^~~
+- ``-Wformat`` cast fix-its will now suggest ``static_cast`` instead of 
C-style casts
+  for C++ code.
 
 Bug Fixes in This Version
 -


Index: clang/test/FixIt/format.mm
===
--- clang/test/FixIt/format.mm
+++ clang/test/FixIt/format.mm
@@ -9,22 +9,22 @@
 
   const wchar_t wchar_data = L'a';
   NSLog(@"%C", wchar_data);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'wchar_t'}}
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"(unsigned short)"
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast(
 
   NSLog(@"%C", 0x260300);  // expected-warning{{format specifies type 'unichar' (aka 'unsigned short') but the argument has type 'int'}}
   // CHECK-NOT: fix-it:"{{.*}}":{[[@LINE-1]]:11-[[@LINE-1]]:13}:"%d"
-  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:16-[[@LINE-2]]:16}:"(unsigned short

[PATCH] D153623: [clang][Sema] Add fixit for scoped enum format error

2023-07-14 Thread Alex Brachet 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 rG563a23c824db: [clang][Sema] Add fixit for scoped enum format 
error (authored by abrachet).
Herald added a project: clang.
Herald added a subscriber: cfe-commits.

Changed prior to commit:
  https://reviews.llvm.org/D153623?vs=538669&id=540455#toc

Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D153623

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaChecking.cpp
  clang/test/FixIt/format.cpp


Index: clang/test/FixIt/format.cpp
===
--- /dev/null
+++ clang/test/FixIt/format.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -Wformat %s 
2>&1 | FileCheck %s
+
+extern "C" int printf(const char *, ...);
+
+namespace N {
+  enum class E { One };
+}
+
+void a() {
+  printf("%d", N::E::One); // expected-warning{{format specifies type 'int' 
but the argument has type 'N::E'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast("
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:25-[[@LINE-2]]:25}:")"
+
+  printf("%hd", N::E::One);
+  // CHECK: "static_cast("
+
+  printf("%hu", N::E::One);
+  // CHECK: "static_cast("
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -11077,12 +11077,15 @@
   assert(Match != ArgType::MatchPromotion);
   // Look through unscoped enums to their underlying type.
   bool IsEnum = false;
+  bool IsScopedEnum = false;
   if (auto EnumTy = ExprTy->getAs()) {
 if (EnumTy->isUnscopedEnumerationType()) {
   ExprTy = EnumTy->getDecl()->getIntegerType();
   // This controls whether we're talking about the underlying type or not,
   // which we only want to do when it's an unscoped enum.
   IsEnum = true;
+} else {
+  IsScopedEnum = true;
 }
   }
 
@@ -11148,7 +11151,7 @@
 
 CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, 
SpecifierLen);
 
-if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
+if (IntendedTy == ExprTy && !ShouldNotPrintDirectly && !IsScopedEnum) {
   unsigned Diag;
   switch (Match) {
   case ArgType::Match:
@@ -11185,11 +11188,17 @@
   SmallString<16> CastBuf;
   llvm::raw_svector_ostream CastFix(CastBuf);
   CastFix << (S.LangOpts.CPlusPlus ? "static_cast<" : "(");
-  IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
+  if (IsScopedEnum) {
+CastFix << AT.getRepresentativeType(S.Context).getAsString(
+S.Context.getPrintingPolicy());
+  } else {
+IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
+  }
   CastFix << (S.LangOpts.CPlusPlus ? ">" : ")");
 
   SmallVector Hints;
-  if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
+  if ((!AT.matchesType(S.Context, IntendedTy) && !IsScopedEnum) ||
+  ShouldNotPrintDirectly)
 Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
 
   if (const CStyleCastExpr *CCast = dyn_cast(E)) {
Index: clang/docs/ReleaseNotes.rst
===
--- clang/docs/ReleaseNotes.rst
+++ clang/docs/ReleaseNotes.rst
@@ -417,6 +417,9 @@
  ^~~
 - ``-Wformat`` cast fix-its will now suggest ``static_cast`` instead of 
C-style casts
   for C++ code.
+- ``-Wformat`` will no longer suggest a no-op fix-it for fixing scoped enum 
format
+  warnings. Instead, it will suggest casting the enum object to the type 
specified
+  in the format string.
 
 Bug Fixes in This Version
 -


Index: clang/test/FixIt/format.cpp
===
--- /dev/null
+++ clang/test/FixIt/format.cpp
@@ -0,0 +1,19 @@
+// RUN: %clang_cc1 -fsyntax-only -fdiagnostics-parseable-fixits -Wformat %s 2>&1 | FileCheck %s
+
+extern "C" int printf(const char *, ...);
+
+namespace N {
+  enum class E { One };
+}
+
+void a() {
+  printf("%d", N::E::One); // expected-warning{{format specifies type 'int' but the argument has type 'N::E'}}
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:16-[[@LINE-1]]:16}:"static_cast("
+  // CHECK: fix-it:"{{.*}}":{[[@LINE-2]]:25-[[@LINE-2]]:25}:")"
+
+  printf("%hd", N::E::One);
+  // CHECK: "static_cast("
+
+  printf("%hu", N::E::One);
+  // CHECK: "static_cast("
+}
Index: clang/lib/Sema/SemaChecking.cpp
===
--- clang/lib/Sema/SemaChecking.cpp
+++ clang/lib/Sema/SemaChecking.cpp
@@ -11077,12 +11077,15 @@
   assert(Match != ArgType::MatchPromotion);
   // Look through unscoped enums to their underlying type.
   bool IsEnum = false;
+  bool IsScopedEnum = false;
   if (auto En

[PATCH] D146777: [clang] Preliminary fat-lto-object support

2023-07-14 Thread Paul Kirth via Phabricator via cfe-commits
paulkirth added inline comments.



Comment at: clang/lib/Driver/Driver.cpp:4733
+  types::ID Output;
+  if (Args.hasArg(options::OPT_S))
+Output = types::TY_LTO_IR;

MaskRay wrote:
> This part is not tested. 
oh, feel free to disregard my Q about `-S`. I missed this comment, and why 
you've asked for that is now obvious.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146777

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


[PATCH] D146777: [clang] Preliminary fat-lto-object support

2023-07-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added inline comments.



Comment at: clang/test/CodeGen/embed-fat-lto-objects.c:3
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=full 
-ffat-lto-objects -emit-llvm < %s  | FileCheck %s --check-prefixes=FULL,SPLIT
+
+// RUN: %clang -cc1 -triple x86_64-unknown-linux-gnu -flto=thin 
-fsplit-lto-unit -ffat-lto-objects -emit-llvm < %s  | FileCheck %s 
--check-prefixes=THIN,SPLIT

paulkirth wrote:
> MaskRay wrote:
> > We need a `-emit-obj` test with `// REQUIRES: x86-registered-target`.
> > Use llvm-readelf to check that .llvm.lto section is present.
> > 
> > We also need a `-S` test, otherwise the behavior of driver `clang -S 
> > -ffat-lto-objects` is untested.
> > 
> > 
> Sure, I can do both of those, but as a general question, isn't the generation 
> of assembly the responsibility of the backend? I believe we have some tests 
> that use `llc` on the the modules that have gone through the FatLTO pipeline. 
> Is that insufficient?
> 
> Also, as a best practice, do you know if there are specific types of changes 
> to `clang` that imply that we'd need to test `-S`? Sorry for all the 
> questions, but I'm trying to get a bit better in how I structure my patches 
> and approach testing.
Ah, sorry for my inaccurate suggestion. You are right.

To test `clang/lib/Driver/Driver.cpp`, we need to test the cc1 options of these 
driver options:

* `-S -ffat-lto-objects -flto`
* `-S -emit-llvm -ffat-lto-objects -flto`
* `-c -ffat-lto-objects -flto` (already tested)

test/CodeGen doesn't need more tests.



Comment at: clang/test/Driver/fat-lto-objects.c:10
+// CHECK-CC-NOLTO-NOT: -ffat-lto-objects
+// CHECK-CC-NOLTO-NOT: warning: argument unused during compilation: 
'-ffat-lto-objects'
+

paulkirth wrote:
> MaskRay wrote:
> > This NOT pattern has no effect as warnings are usually emitted before -cc1.
> > 
> > You can use `--implicit-check-not=warning:`
> I'm happy to try that suggestion, but isn't this testing the generated `cc1` 
> command from the driver(e.g.,  because we're using `%clang` and not 
> `%clang_cc1`)? I //think// that should still produce the warning, shouldn't 
> it? 
> 
> It's been a while since I made the patch, but I recall writing this test, 
> having it fail, and then applying the change to stop it from being an `unused 
> argument`... 
> 
> Also, thanks for all the great feedback on testing. Despite writing 
> many(well, more than a few at least) `lit` tests, I'm still surprised by lots 
> of behaviors, and your suggestions have been very helpful.
Yes, test/Driver just tests how Clang Driver generates warnings/errors and cc1 
options. If there is a warning, it will be before the cc1 line, so `// 
CHECK-CC-NOLTO-NOT: warning: argument unused during compilation: 
'-ffat-lto-objects'` after cc1 will have no effect.

```
% myclang -flto -ffat-lto-objects -pie -c a.cc '-###'
clang version 17.0.0
Target: x86_64-unknown-linux-gnu
Thread model: posix
InstalledDir: /tmp/Debug/bin
clang: warning: argument unused during compilation: '-pie' 
[-Wunused-command-line-argument]
 (in-process)
 "/tmp/Debug/bin/clang-17" "-cc1" ...
```

Actually, we usually don't want to check that a certain warning doesn't occur. 
Rather, we want to test no warning occurs, as it's easy to adjust a warning 
message and get stale tests.

In this case, I think I find a better test strategy: -fdriver-only -v -Werror. 
`-fdriver-only` ensures that an error changes the exit code and lit does check 
the exit code, fulfilling our testing requirement.
```
% myclang -fdriver-only -v -Werror -flto -ffat-lto-objects -pie -fdriver-only 
-c a.cc
clang: error: argument unused during compilation: '-pie' 
[-Werror,-Wunused-command-line-argument]
% echo $?
1
```

> Also, thanks for all the great feedback on testing. Despite writing 
> many(well, more than a few at least) lit tests, I'm still surprised by lots 
> of behaviors, and your suggestions have been very helpful.

NP! Glad to help. I have spent too much time fiddling with driver options...


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146777

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


[PATCH] D86310: [X86] Align i128 to 16 bytes in x86-64 datalayout

2023-07-14 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

> @craig.topper Just to make sure, are you okay with me 'commandeering' this 
> change and updating it?

Yes. Thanks for taking it on.


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

https://reviews.llvm.org/D86310

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


[PATCH] D154647: [RISCV] Re-define sha256, Zksed, and Zksh intrinsics to use i32 types.

2023-07-14 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154647

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


[PATCH] D154616: [RISCV] Use unsigned instead of signed types for Zk* and Zb* builtins.

2023-07-14 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

Ping


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154616

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


[PATCH] D145262: [clang-format] Treat AttributeMacros more like attribute macros

2023-07-14 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb updated this revision to Diff 540477.
jaredgrubb added a comment.

Rebased and added a line to Release Notes, no other changes. Have requested 
this to be merged if all builds are green (since this patch has been approved).


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

https://reviews.llvm.org/D145262

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Format/ContinuationIndenter.cpp
  clang/lib/Format/ContinuationIndenter.h
  clang/lib/Format/TokenAnnotator.cpp
  clang/unittests/Format/FormatTestObjC.cpp
  clang/unittests/Format/TokenAnnotatorTest.cpp

Index: clang/unittests/Format/TokenAnnotatorTest.cpp
===
--- clang/unittests/Format/TokenAnnotatorTest.cpp
+++ clang/unittests/Format/TokenAnnotatorTest.cpp
@@ -1642,6 +1642,116 @@
   EXPECT_TOKEN(Tokens[13], tok::arrow, TT_Unknown);
 }
 
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacros) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("__attribute__(X) void Foo(void);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("A(X) void Foo(void);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_Unknown);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("A(X) void Foo(void);", Style);
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCDecl) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("__attribute__(X) @interface Foo");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("A(X) @interface Foo");
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  // Note: Don't check token-type as a random token in this position is hard to
+  // reason about.
+  EXPECT_TOKEN_KIND(Tokens[0], tok::identifier);
+  EXPECT_TOKEN_KIND(Tokens[1], tok::l_paren);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("A(X) @interface Foo", Style);
+  ASSERT_EQ(Tokens.size(), 8u) << Tokens;
+  EXPECT_TOKEN(Tokens[0], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[1], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[3], tok::r_paren, TT_AttributeParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCMethodDecl) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("- (id)init __attribute__(X);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_AttributeParen);
+
+  // Generic macro has no special handling in this location.
+  Tokens = annotate("- (id)init A(X);");
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  // Note: Don't check token-type as a random token in this position is hard to
+  // reason about.
+  EXPECT_TOKEN_KIND(Tokens[5], tok::identifier);
+  EXPECT_TOKEN_KIND(Tokens[6], tok::l_paren);
+
+  // Add a custom AttributeMacro. Test that it has the same behavior.
+  FormatStyle Style = getLLVMStyle();
+  Style.AttributeMacros.push_back("A");
+
+  // An "AttributeMacro" gets annotated like '__attribute__'.
+  Tokens = annotate("- (id)init A(X);", Style);
+  ASSERT_EQ(Tokens.size(), 11u) << Tokens;
+  EXPECT_TOKEN(Tokens[5], tok::identifier, TT_AttributeMacro);
+  EXPECT_TOKEN(Tokens[6], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[8], tok::r_paren, TT_AttributeParen);
+}
+
+TEST_F(TokenAnnotatorTest, UnderstandsAttributeMacrosOnObjCProperty) {
+  // '__attribute__' has special handling.
+  auto Tokens = annotate("@property(weak) id delegate __attribute__(X);");
+  ASSERT_EQ(Tokens.size(), 13u) << Tokens;
+  EXPECT_TOKEN(Tokens[7], tok::kw___attribute, TT_Unknown);
+  EXPECT_TOKEN(Tokens[8], tok::l_paren, TT_AttributeParen);
+  EXPECT_TOKEN(Tokens[10], tok::r_paren, TT_AttributeParen);
+
+  // Gener

[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-07-14 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 540479.
hazohelet marked 6 inline comments as done.
hazohelet added a comment.

Address comments from Aaron and Corentin

- Call `ConditionVar->setReferenced(false)` without any checks
- Added some more tests


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

https://reviews.llvm.org/D152495

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/Sema/SemaDecl.cpp
  clang/lib/Sema/SemaExprCXX.cpp
  clang/lib/Sema/SemaTemplateInstantiateDecl.cpp
  clang/test/SemaCXX/warn-unused-variables.cpp

Index: clang/test/SemaCXX/warn-unused-variables.cpp
===
--- clang/test/SemaCXX/warn-unused-variables.cpp
+++ clang/test/SemaCXX/warn-unused-variables.cpp
@@ -1,5 +1,5 @@
 // RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label -Wno-c++1y-extensions -verify %s
-// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label -Wno-c++1y-extensions -verify -std=c++11 %s
+// RUN: %clang_cc1 -fsyntax-only -Wunused-variable -Wunused-label -Wno-c++14-extensions -Wno-c++17-extensions -verify -std=c++11 %s
 template void f() {
   T t;
   t = 17;
@@ -294,3 +294,115 @@
 }
 
 } // namespace gh54489
+
+namespace inside_condition {
+  void ifs() {
+if (int hoge = 0) // expected-warning {{unused variable 'hoge'}}
+  return;
+if (const int const_hoge = 0) // expected-warning {{unused variable 'const_hoge'}}
+  return;
+else if (int fuga = 0)
+  (void)fuga;
+else if (int used = 1; int catched = used) // expected-warning {{unused variable 'catched'}}
+  return;
+else if (int refed = 1; int used = refed)
+  (void)used;
+else if (int unused1 = 2; int unused2 = 3) // expected-warning {{unused variable 'unused1'}} \
+   // expected-warning {{unused variable 'unused2'}}
+  return;
+else if (int unused = 4; int used = 5) // expected-warning {{unused variable 'unused'}}
+  (void)used;
+else if (int used = 6; int unused = 7) // expected-warning {{unused variable 'unused'}}
+  (void)used;
+else if (int used1 = 8; int used2 = 9)
+  (void)(used1 + used2);
+else if (auto [a, b] = (int[2]){ 1, 2 }; 1) // expected-warning {{unused variable '[a, b]'}}
+  return;
+else if (auto [a, b] = (int[2]){ 1, 2 }; a)
+  return;
+  }
+
+  void fors() {
+for (int i = 0;int unused = 0;); // expected-warning {{unused variable 'i'}} \
+ // expected-warning {{unused variable 'unused'}}
+for (int i = 0;int used = 0;) // expected-warning {{unused variable 'i'}}
+  (void)used;
+  while(int var = 1) // expected-warning {{unused variable 'var'}}
+return;
+  }
+
+  void whiles() {
+while(int unused = 1) // expected-warning {{unused variable 'unused'}}
+  return;
+while(int used = 1)
+  (void)used;
+  }
+
+
+  void switches() {
+switch(int unused = 1) { // expected-warning {{unused variable 'unused'}}
+  case 1: return;
+}
+switch(constexpr int used = 3; int unused = 4) { // expected-warning {{unused variable 'unused'}}
+  case used: return;
+}
+switch(int used = 3; int unused = 4) { // expected-warning {{unused variable 'unused'}}
+  case 3: (void)used;
+}
+switch(constexpr int used1 = 0; constexpr int used2 = 6) {
+  case (used1+used2): return;
+}
+switch(auto [a, b] = (int[2]){ 1, 2 }; 1) { // expected-warning {{unused variable '[a, b]'}}
+  case 1: return;
+}
+switch(auto [a, b] = (int[2]){ 1, 2 }; b) {
+  case 1: return;
+}
+switch(auto [a, b] = (int[2]){ 1, 2 }; 1) {
+  case 1: (void)a;
+}
+  }
+  template 
+  struct Vector {
+void doIt() {
+  for (auto& e : elements){} // expected-warning {{unused variable 'e'}}
+}
+T elements[10];
+  };
+  void ranged_for() {
+Vectorvector;
+vector.doIt(); // expected-note {{here}}
+  }
+
+
+  struct RAII {
+int &x;
+RAII(int &ref) : x(ref) {}
+~RAII() { x = 0;}
+operator int() const { return 1; }
+  };
+  void aggregate() {
+int x = 10;
+int y = 10;
+if (RAII var = x) {}
+for(RAII var = x; RAII var2 = y;) {}
+while (RAII var = x) {}
+switch (RAII var = x) {}
+  }
+
+  struct TrivialDtor{
+int &x;
+TrivialDtor(int &ref) : x(ref) { ref = 32; }
+operator int() const { return 1; }
+  };
+  void trivial_dtor() {
+int x = 10;
+int y = 10;
+if (TrivialDtor var = x) {} // expected-warning {{unused variable 'var'}}
+for(TrivialDtor var = x; TrivialDtor var2 = y;) {} // expected-warning {{unused variable 'var'}} \
+ // expected-warning {{unused variable 'var2'}}
+while (TrivialDtor var = x) {} // expected-warning {{unused variable 'var'}}
+switch (TrivialDtor var = x) {} // expected-warning {{unused variable 'var'}}
+  }
+
+} // namespace inside_condition
Index: clang/lib/Sema/SemaTemplateI

[PATCH] D155175: [Clang] Fix consteval propagation for aggregates and defaulted constructors

2023-07-14 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

I found further issues with aggregates,
I think not supporting aggregates for now would be fine, the high bit is to fix 
the regressions 
I did add some more info there 
https://github.com/cplusplus/CWG/issues/354#issuecomment-1636129255


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155175

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


[PATCH] D154123: [HIP] Start document HIP support by clang

2023-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/docs/HIPSupport.rst:33
+
+   clang -c --offload-arch=gfx906 -xhip test.cpp -o test.o
+

Aren't you supposed to use clang++? Also, could show that .hip is recognized?


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

https://reviews.llvm.org/D154123

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


[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-07-14 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:4016-4019
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  if (!T->isAggregateType())
+ConditionVar->setReferenced(/*R=*/false);

cor3ntin wrote:
> hazohelet wrote:
> > cor3ntin wrote:
> > > aaron.ballman wrote:
> > > > `isAggregateType()` includes arrays and I think we still want to 
> > > > diagnose an unused array.
> > > Should it not be `Condition->hasSideEffects()` ? 
> > > Hopefully we want to be consistent with existing behavior 
> > > https://godbolt.org/z/6abbPhn4G
> > The condition here only applies to condition variables.
> > C++ does not allow array type in condition variable, correct? I think it's 
> > OK to use `isAggregateType` as well then.
> After a chat with Aaron, I have a few questions: Do we call `Scope::AddDecl` 
> - or `PushOnScopeChains` somewhere?
> My intuition is that if the condition is added to a scope, and we call `
> ConditionVar->setReferenced(false);`, the all the diagnostic mechanism in 
> `DiagnoseUnusedDecl` should be triggered. and it seen to be because we do get 
> a diagnostic.
> So neither `if (!T->isAggregateType())` or any check should be needed there
> 
> Can you just remove that if statement (just set `setReferenced(false)`) and 
> see if it works? Otherwise, i think we need to understand why it doesn't but 
> trying to reimplement the logic of `ShouldDiagnoseUnusedDecl`seems fraught 
> with unbounded complexity.
It didn't break any tests locally, but when the record type does not have a 
user-provided dtor, it is diagnosed as unused, which seems not nice. (example 
written in the test `trivial_dtor`)


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

https://reviews.llvm.org/D152495

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


[PATCH] D154881: [HIP] Ignore host linker flags for device-only

2023-07-14 Thread Siu Chi Chan via Phabricator via cfe-commits
scchan updated this revision to Diff 540481.
scchan added a comment.

added extra checks for not host, rebased


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154881

Files:
  clang/lib/Driver/Driver.cpp
  clang/test/Driver/hip-phases.hip

Index: clang/test/Driver/hip-phases.hip
===
--- clang/test/Driver/hip-phases.hip
+++ clang/test/Driver/hip-phases.hip
@@ -219,6 +219,14 @@
 // RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
 // RUN: --cuda-gpu-arch=gfx803 %s --cuda-device-only 2>&1 \
 // RUN: | FileCheck -check-prefixes=DBIN %s
+//
+// Test single gpu architecture with complete compilation in device-only
+// compilation mode with an unused host linker flag.
+//
+// RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
+// RUN: --cuda-gpu-arch=gfx803 %s --cuda-device-only -Wl,--disable-new-dtags 2>&1 \
+// RUN: | FileCheck -check-prefixes=DBIN %s
+
 // DBIN-DAG: [[P0:[0-9]+]]: input, "{{.*}}hip-phases.hip", [[T:hip]], (device-[[T]], [[ARCH:gfx803]])
 // DBIN-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, [[T]]-cpp-output, (device-[[T]], [[ARCH]])
 // DBIN-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-[[T]], [[ARCH]])
@@ -229,6 +237,7 @@
 // DBIN-DAG: [[P7:[0-9]+]]: linker, {[[P6]]}, hip-fatbin, (device-hip, )
 // DBIN-DAG: [[P8:[0-9]+]]: offload, "device-[[T]] (amdgcn-amd-amdhsa:)" {[[P7]]}, hip-fatbin
 // DBIN-NOT: host
+
 //
 // Test single gpu architecture up to the assemble phase in device-only
 // compilation mode.
@@ -251,6 +260,11 @@
 // RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
 // RUN: --cuda-gpu-arch=gfx803 %s --cuda-device-only -fhip-emit-relocatable 2>&1 \
 // RUN: | FileCheck -check-prefixes=RELOC %s
+//
+// RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
+// RUN: --cuda-gpu-arch=gfx803 %s --cuda-device-only -fhip-emit-relocatable -Wl,--disable-new-dtags \
+// RUN: 2>&1 | FileCheck -check-prefixes=RELOC %s
+//
 // RELOC-DAG: [[P0:[0-9]+]]: input, "{{.*}}hip-phases.hip", [[T:hip]], (device-[[T]], [[ARCH:gfx803]])
 // RELOC-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, [[T]]-cpp-output, (device-[[T]], [[ARCH]])
 // RELOC-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-[[T]], [[ARCH]])
@@ -258,6 +272,7 @@
 // RELOC-DAG: [[P4:[0-9]+]]: assembler, {[[P3]]}, object, (device-[[T]], [[ARCH]])
 // RELOC-NOT: linker
 // RELOC-DAG: [[P5:[0-9]+]]: offload, "device-[[T]] (amdgcn-amd-amdhsa:[[ARCH]])" {[[P4]]}, object
+// RELOC-NOT: host
 
 //
 // Test two gpu architectures with compile to relocatable in device-only
@@ -266,6 +281,11 @@
 // RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
 // RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %s --cuda-device-only -fhip-emit-relocatable 2>&1 \
 // RUN: | FileCheck -check-prefixes=RELOC2 %s
+//
+// RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
+// RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %s --cuda-device-only -fhip-emit-relocatable \
+// RUN: -Wl,--disable-new-dtags 2>&1 | FileCheck -check-prefixes=RELOC2 %s
+//
 // RELOC2-DAG: [[P0:[0-9]+]]: input, "{{.*}}hip-phases.hip", [[T:hip]], (device-[[T]], [[ARCH:gfx803]])
 // RELOC2-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, [[T]]-cpp-output, (device-[[T]], [[ARCH]])
 // RELOC2-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-[[T]], [[ARCH]])
@@ -280,6 +300,7 @@
 // RELOC2-DAG: [[P10:[0-9]+]]: assembler, {[[P9]]}, object, (device-[[T]], [[ARCH2]])
 // RELOC2-NOT: linker
 // RELOC2-DAG: [[P11:[0-9]+]]: offload, "device-[[T]] (amdgcn-amd-amdhsa:[[ARCH2]])" {[[P10]]}, object
+// RELOC2-NOT: host
 
 //
 // Test two gpu architectures with complete compilation in device-only
@@ -288,6 +309,14 @@
 // RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
 // RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %s --cuda-device-only \
 // RUN: 2>&1 | FileCheck -check-prefixes=DBIN2 %s
+//
+// Test two gpu architectures with complete compilation in device-only
+// compilation mode with an unused host linker flag.
+//
+// RUN: %clang -x hip --target=x86_64-unknown-linux-gnu -ccc-print-phases \
+// RUN: --cuda-gpu-arch=gfx803 --cuda-gpu-arch=gfx900 %s --cuda-device-only \
+// RUN: -Wl,--disable-new-dtags 2>&1 | FileCheck -check-prefixes=DBIN2 %s
+
 // DBIN2-DAG: [[P0:[0-9]+]]: input, "{{.*}}hip-phases.hip", [[T:hip]], (device-[[T]], [[ARCH:gfx803]])
 // DBIN2-DAG: [[P1:[0-9]+]]: preprocessor, {[[P0]]}, [[T]]-cpp-output, (device-[[T]], [[ARCH]])
 // DBIN2-DAG: [[P2:[0-9]+]]: compiler, {[[P1]]}, ir, (device-[[T]], [[ARCH]])
@@ -305,6 +334,7 @@
 // DBIN2-DAG: [[P14:[0-9]+]]: linker, {[[P6]], [[P13]]}, hip-fatbin, (device-hip, )
 // DBIN2-DAG: [[P15:[0-9]+]]: offload, "device-[[T]] (amdgcn-amd-amdhsa:)" {[[P14]]}, hip-fatbin
 // DBIN2-NOT: host
+
 //
 // Test two gpu architectures up to the assembl

[PATCH] D155213: [HIP] Add `-fno-hip-uniform-block`

2023-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1092
   ShouldParseIf;
+defm hip_uniform_block : BoolFOption<"hip-uniform-block",
+  LangOpts<"HIPUniformBlock">, DefaultTrue,

Can we avoid adding yet another language flag for something that's reusable for 
everything? Is there an --offload- ?


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

https://reviews.llvm.org/D155213

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


[PATCH] D154123: [HIP] Start document HIP support by clang

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked 3 inline comments as done.
yaxunl added inline comments.



Comment at: clang/docs/HIPSupport.rst:33
+
+   clang -c --offload-arch=gfx906 -xhip test.cpp -o test.o
+

arsenm wrote:
> Aren't you supposed to use clang++? Also, could show that .hip is recognized?
good point. will fix


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

https://reviews.llvm.org/D154123

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


[PATCH] D154123: [HIP] Start document HIP support by clang

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl updated this revision to Diff 540485.
yaxunl marked an inline comment as done.
yaxunl edited the summary of this revision.
yaxunl added a comment.

revised by comments


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

https://reviews.llvm.org/D154123

Files:
  clang/docs/HIPSupport.rst

Index: clang/docs/HIPSupport.rst
===
--- /dev/null
+++ clang/docs/HIPSupport.rst
@@ -0,0 +1,143 @@
+.. raw:: html
+
+  
+.none { background-color: #FF }
+.part { background-color: #99 }
+.good { background-color: #CCFF99 }
+  
+
+.. role:: none
+.. role:: part
+.. role:: good
+
+.. contents::
+   :local:
+
+===
+HIP Support
+===
+
+`HIP (Heterogeneous-Compute Interface for Portability) `_
+is a C++ Runtime API and Kernel Language that allows developers to create portable applications for
+GPUs from single source code.
+
+Clang supports HIP on `ROCm platform `_.
+
+Example Usage
+=
+
+To compile a HIP program, you can use the following command:
+
+.. code-block:: shell
+
+   clang++ -c --offload-arch=gfx906 -xhip test.cpp -o test.o
+
+This command will compile a .cpp file with the -xhip option to indicate that
+the source is a HIP program. However, if the file has a .hip extension, you
+don't need the -xhip option. Clang will automatically recognize it as a HIP
+program. Here's an example:
+
+.. code-block:: shell
+
+   clang++ -c --offload-arch=gfx906 test.hip -o test.o
+
+To link a HIP program, you can use this command:
+
+.. code-block:: shell
+
+   clang++ --hip-link --offload-arch=gfx906 test.o -o test
+
+In the above commands, ``gfx906`` is the GPU architecture that the code is being compiled for.
+The supported GPU architectures can be found in the `AMDGPU Processor Table `_.
+Alternatively, you can run the ``amdgpu-arch`` tool that comes with Clang to list the GPU architecture on your sytem:
+
+.. code-block:: shell
+
+   amdgpu-arch
+
+You can also use ``--offload-arch=native`` to let ``amdgpu-arch`` automatically detect the GPU architectures on your system:
+
+.. code-block:: shell
+
+   clang -c --offload-arch=native -xhip test.cpp -o test.o
+
+Path Setting for Dependencies
+=
+
+Compiling a HIP program depends on the HIP runtime and device library. The paths to the HIP runtime and device libraries can be specified either using compiler options or environment variables. The paths can also be set through the ROCm path if they follow the ROCm installation directory structure.
+
+Order of Precedence for HIP Path
+
+
+1. ``--hip-path`` compiler option
+2. ``HIP_PATH`` environment variable *(use with caution)*
+3. ``--rocm-path`` compiler option
+4. ``ROCM_PATH`` environment variable *(use with caution)*
+5. Default automatic detection (relative to Clang or at the default ROCm installation location)
+
+Order of Precedence for Device Library Path
+---
+
+1. ``--hip-device-lib-path`` compiler option
+2. ``HIP_DEVICE_LIB_PATH`` environment variable *(use with caution)*
+3. ``--rocm-path`` compiler option
+4. ``ROCM_PATH`` environment variable *(use with caution)*
+5. Default automatic detection (relative to Clang or at the default ROCm installation location)
+
+
+.. list-table::
+   :header-rows: 1
+
+   * - Compiler Option
+ - Environment Variable
+ - Description
+ - Default Value
+   * - ``--rocm-path=``
+ - ``ROCM_PATH``
+ - Specifies the ROCm installation path.
+ - Automatic detection
+   * - ``--hip-path=``
+ - ``HIP_PATH``
+ - Specifies the HIP runtime installation path.
+ - Determined by ROCm directory structure
+   * - ``--hip-device-lib-path=``
+ - ``HIP_DEVICE_LIB_PATH``
+ - Specifies the HIP device library installation path.
+ - Determined by ROCm directory structure
+
+.. note::
+
+   We recommend using the compiler options as the primary method for specifying these paths. While the environment variables ``ROCM_PATH``, ``HIP_PATH``, and ``HIP_DEVICE_LIB_PATH`` are supported, their use can lead to implicit dependencies that might cause issues in the long run. Use them with caution.
+
+
+Predefined Macros
+=
+
+.. list-table::
+   :header-rows: 1
+
+   * - Macro
+ - Description
+   * - ``__CLANG_RDC__``
+ - Defined when Clang is compiling code in Relocatable Device Code (RDC) mode. RDC, enabled with the ``-fgpu-rdc`` compiler option, is necessary for linking device codes across translation units.
+   * - ``__HIP__``
+ - Defined when compiling with HIP language support, indicating that the code targets the HIP environment.
+   * - ``__HIPCC__``
+ - Alias to ``__HIP__``.
+   * - ``__HIP_DEVICE_COMPILE__``
+ - Defined during device code compilation in Clang's separat

[PATCH] D146434: [clang-format] Fix support for ObjC blocks with pointer return types

2023-07-14 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb marked 2 inline comments as done.
jaredgrubb added inline comments.
Herald added a subscriber: wangpc.
Herald added a reviewer: rymiel.



Comment at: clang/lib/Format/UnwrappedLineParser.cpp:1779-1782
 nextToken();
+// Return types: pointers are ok too.
+while (FormatTok->is(tok::star))
+  nextToken();

owenpan wrote:
> 
I think this obscures the logic a bit. The first one is to consume one token 
(the return type) and the next is to consume a different kind of token 
(trailing stars). Putting them in a while loop makes it harder to reason about 
why it's looping in that way.



Comment at: clang/unittests/Format/FormatTestObjC.cpp:1007-1010
+  Style = getWebKitStyle();
+  verifyFormat("int* p = ^int*() { //\n"
+   "return nullptr;\n"
+   "}();");

owenpan wrote:
> 
Fixed!


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D146434

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


[PATCH] D146434: [clang-format] Fix support for ObjC blocks with pointer return types

2023-07-14 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb updated this revision to Diff 540488.
jaredgrubb marked an inline comment as done.
jaredgrubb added a comment.

Address review comment and rebase to re-run tests. Intend to merge if 
everything is green! (If there are further comments, I will commit to address 
them!)


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

https://reviews.llvm.org/D146434

Files:
  clang/lib/Format/UnwrappedLineParser.cpp
  clang/unittests/Format/FormatTest.cpp
  clang/unittests/Format/FormatTestObjC.cpp


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1019,6 +1019,20 @@
   verifyFormat("int (^foo[kNumEntries])(char, float);");
   verifyFormat("int (^foo[kNumEntries + 10])(char, float);");
   verifyFormat("int (^foo[(kNumEntries + 10)])(char, float);");
+
+  verifyFormat("int *p = ^int *() { //\n"
+   "  return nullptr;\n"
+   "}();");
+
+  verifyFormat("int * (^p)(void) = ^int *(void) { //\n"
+   "  return nullptr;\n"
+   "};");
+
+  // WebKit forces function braces onto a newline, but blocks should not.
+  verifyFormat("int* p = ^int*() { //\n"
+   "return nullptr;\n"
+   "}();",
+   getWebKitStyle());
 }
 
 TEST_F(FormatTestObjC, ObjCSnippets) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22619,7 +22619,8 @@
"}\n"
"  }\n"
"});");
-  verifyFormat("Block b = ^int *(A *a, B *b) {}");
+  verifyFormat("Block b = ^int *(A *a, B *b) {\n"
+   "};");
   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
"};");
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1798,12 +1798,18 @@
   break;
 case tok::caret:
   nextToken();
+  // Block return type.
   if (FormatTok->Tok.isAnyIdentifier() ||
   FormatTok->isSimpleTypeSpecifier()) {
 nextToken();
+// Return types: pointers are ok too.
+while (FormatTok->is(tok::star))
+  nextToken();
   }
+  // Block argument list.
   if (FormatTok->is(tok::l_paren))
 parseParens();
+  // Block body.
   if (FormatTok->is(tok::l_brace))
 parseChildBlock();
   break;


Index: clang/unittests/Format/FormatTestObjC.cpp
===
--- clang/unittests/Format/FormatTestObjC.cpp
+++ clang/unittests/Format/FormatTestObjC.cpp
@@ -1019,6 +1019,20 @@
   verifyFormat("int (^foo[kNumEntries])(char, float);");
   verifyFormat("int (^foo[kNumEntries + 10])(char, float);");
   verifyFormat("int (^foo[(kNumEntries + 10)])(char, float);");
+
+  verifyFormat("int *p = ^int *() { //\n"
+   "  return nullptr;\n"
+   "}();");
+
+  verifyFormat("int * (^p)(void) = ^int *(void) { //\n"
+   "  return nullptr;\n"
+   "};");
+
+  // WebKit forces function braces onto a newline, but blocks should not.
+  verifyFormat("int* p = ^int*() { //\n"
+   "return nullptr;\n"
+   "}();",
+   getWebKitStyle());
 }
 
 TEST_F(FormatTestObjC, ObjCSnippets) {
Index: clang/unittests/Format/FormatTest.cpp
===
--- clang/unittests/Format/FormatTest.cpp
+++ clang/unittests/Format/FormatTest.cpp
@@ -22619,7 +22619,8 @@
"}\n"
"  }\n"
"});");
-  verifyFormat("Block b = ^int *(A *a, B *b) {}");
+  verifyFormat("Block b = ^int *(A *a, B *b) {\n"
+   "};");
   verifyFormat("BOOL (^aaa)(void) = ^BOOL {\n"
"};");
 
Index: clang/lib/Format/UnwrappedLineParser.cpp
===
--- clang/lib/Format/UnwrappedLineParser.cpp
+++ clang/lib/Format/UnwrappedLineParser.cpp
@@ -1798,12 +1798,18 @@
   break;
 case tok::caret:
   nextToken();
+  // Block return type.
   if (FormatTok->Tok.isAnyIdentifier() ||
   FormatTok->isSimpleTypeSpecifier()) {
 nextToken();
+// Return types: pointers are ok too.
+while (FormatTok->is(tok::star))
+  nextToken();
   }
+  // Block argument list.
   if (FormatTok->is(tok::l_paren))
 parseParens();
+  // Block body.
   if (FormatTok->is(tok::l_brace))
 parseChildBlock();
   break;
___
cfe-commits mailing list
cfe-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits


[PATCH] D154366: [clang][ExprConstant] Print template arguments when describing stack frame

2023-07-14 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet updated this revision to Diff 540486.
hazohelet added a comment.

Uses `FunctionDecl::getNameForDiagnostic`


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

https://reviews.llvm.org/D154366

Files:
  clang/docs/ReleaseNotes.rst
  clang/lib/AST/ExprConstant.cpp
  clang/test/AST/Interp/literals.cpp
  clang/test/SemaCXX/builtin-align-cxx.cpp
  clang/test/SemaCXX/constant-expression-cxx11.cpp
  clang/test/SemaCXX/constant-expression-cxx14.cpp
  clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
  clang/test/SemaCXX/cxx2b-consteval-propagate.cpp

Index: clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
===
--- clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
+++ clang/test/SemaCXX/cxx2b-consteval-propagate.cpp
@@ -45,7 +45,7 @@
 }
 
 int i = hh(); // expected-error {{call to immediate function 'examples::hh' is not a constant expression}} \
-   // expected-note {{in call to 'hh()'}}
+   // expected-note {{in call to 'hh()'}}
 
 struct A {
   int x;
Index: clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
===
--- clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
+++ clang/test/SemaCXX/constexpr-builtin-bit-cast.cpp
@@ -117,11 +117,11 @@
 
   constexpr pad pir{4, 4};
   // expected-error@+2 {{constexpr variable 'piw' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr int piw = bit_cast(pir).x;
 
   // expected-error@+2 {{constexpr variable 'bad' must be initialized by a constant expression}}
-  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
+  // expected-note@+1 {{in call to 'bit_cast(pir)'}}
   constexpr no_pad bad = bit_cast(pir);
 
   constexpr pad fine = bit_cast(no_pad{1, 2, 3, 4, 5});
Index: clang/test/SemaCXX/constant-expression-cxx14.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx14.cpp
+++ clang/test/SemaCXX/constant-expression-cxx14.cpp
@@ -1038,7 +1038,7 @@
 void foo() __attribute__((enable_if(sum(Cs) == 'a' + 'b', "")));
 void run() { foo(); }
 
-static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum(Cs)'}}
+static_assert(sum(Cs) == 'a' + 'b', ""); // expected-error{{not an integral constant expression}} expected-note{{in call to 'sum<2>(Cs)'}}
 constexpr int S = sum(Cs); // expected-error{{must be initialized by a constant expression}} expected-note{{in call}}
 }
 
Index: clang/test/SemaCXX/constant-expression-cxx11.cpp
===
--- clang/test/SemaCXX/constant-expression-cxx11.cpp
+++ clang/test/SemaCXX/constant-expression-cxx11.cpp
@@ -1781,7 +1781,7 @@
   static_assert(get(arr, 1) == 1, "");
   static_assert(get(arr, 4) == 4, "");
   static_assert(get(arr, 0) == 4, ""); // expected-error{{not an integral constant expression}} \
-  // expected-note{{in call to 'get(arr, 0)'}}
+  // expected-note{{in call to 'get(arr, 0)'}}
 }
 
 namespace std { struct type_info; }
Index: clang/test/SemaCXX/builtin-align-cxx.cpp
===
--- clang/test/SemaCXX/builtin-align-cxx.cpp
+++ clang/test/SemaCXX/builtin-align-cxx.cpp
@@ -137,26 +137,26 @@
 constexpr long const_value(long l) { return l; }
 // Check some invalid values during constant-evaluation
 static_assert(wrap_align_down(1, const_value(-1)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, -1)'}}
 static_assert(wrap_align_up(1, const_value(-2)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, -2)'}}
 static_assert(wrap_is_aligned(1, const_value(-3)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
+// expected-note@-1{{in call to 'wrap_is_aligned(1, -3)'}}
 static_assert(wrap_align_down(1, const_value(17)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
+// expected-note@-1{{in call to 'wrap_align_down(1, 17)'}}
 static_assert(wrap_align_up(1, const_value(18)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
+// expected-note@-1{{in call to 'wrap_align_up(1, 18)'}}
 static_assert(wrap_is_aligned(1, const_value(19)), ""); // expected-error{{not an integral constant expression}}
-// expected-note@-1{{in call to 'wrap_is_aligned(1, 19)'}}
+// expected-note@-1{{in call to 'wrap_is_aligned(1, 19)'}}
 
 // Check invalid values for smaller

[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-07-14 Thread Corentin Jabot via Phabricator via cfe-commits
cor3ntin added a comment.

This looks reasonable to me now.
I'll wait next week before approving it so other get a chance to look at it :)




Comment at: clang/lib/Sema/SemaExprCXX.cpp:4016-4019
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  if (!T->isAggregateType())
+ConditionVar->setReferenced(/*R=*/false);

hazohelet wrote:
> cor3ntin wrote:
> > hazohelet wrote:
> > > cor3ntin wrote:
> > > > aaron.ballman wrote:
> > > > > `isAggregateType()` includes arrays and I think we still want to 
> > > > > diagnose an unused array.
> > > > Should it not be `Condition->hasSideEffects()` ? 
> > > > Hopefully we want to be consistent with existing behavior 
> > > > https://godbolt.org/z/6abbPhn4G
> > > The condition here only applies to condition variables.
> > > C++ does not allow array type in condition variable, correct? I think 
> > > it's OK to use `isAggregateType` as well then.
> > After a chat with Aaron, I have a few questions: Do we call 
> > `Scope::AddDecl` - or `PushOnScopeChains` somewhere?
> > My intuition is that if the condition is added to a scope, and we call `
> > ConditionVar->setReferenced(false);`, the all the diagnostic mechanism in 
> > `DiagnoseUnusedDecl` should be triggered. and it seen to be because we do 
> > get a diagnostic.
> > So neither `if (!T->isAggregateType())` or any check should be needed there
> > 
> > Can you just remove that if statement (just set `setReferenced(false)`) and 
> > see if it works? Otherwise, i think we need to understand why it doesn't 
> > but trying to reimplement the logic of `ShouldDiagnoseUnusedDecl`seems 
> > fraught with unbounded complexity.
> It didn't break any tests locally, but when the record type does not have a 
> user-provided dtor, it is diagnosed as unused, which seems not nice. (example 
> written in the test `trivial_dtor`)
It's still a declaration that does nothing, so diagnosing let you remove it
https://compiler-explorer.com/z/a1GGs9cxa this is consistent with local 
variables. I like the simplicity of the change.


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

https://reviews.llvm.org/D152495

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


[PATCH] D154881: [HIP] Ignore host linker flags for device-only

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154881

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


[PATCH] D155213: [HIP] Add `-fno-hip-uniform-block`

2023-07-14 Thread Siu Chi Chan via Phabricator via cfe-commits
scchan added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1092
   ShouldParseIf;
+defm hip_uniform_block : BoolFOption<"hip-uniform-block",
+  LangOpts<"HIPUniformBlock">, DefaultTrue,

arsenm wrote:
> Can we avoid adding yet another language flag for something that's reusable 
> for everything? Is there an --offload- ?
Don't we need a different default value for some languages like OpenCL?


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

https://reviews.llvm.org/D155213

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


[PATCH] D152495: [Clang][SemaCXX] Add unused warning for variables declared in condition expressions

2023-07-14 Thread Takuya Shimizu via Phabricator via cfe-commits
hazohelet added inline comments.



Comment at: clang/lib/Sema/SemaExprCXX.cpp:4016-4019
+  // Ensure that `-Wunused-variable` will be emitted for condition variables
+  // that are not referenced later. e.g.: if (int var = init());
+  if (!T->isAggregateType())
+ConditionVar->setReferenced(/*R=*/false);

cor3ntin wrote:
> hazohelet wrote:
> > cor3ntin wrote:
> > > hazohelet wrote:
> > > > cor3ntin wrote:
> > > > > aaron.ballman wrote:
> > > > > > `isAggregateType()` includes arrays and I think we still want to 
> > > > > > diagnose an unused array.
> > > > > Should it not be `Condition->hasSideEffects()` ? 
> > > > > Hopefully we want to be consistent with existing behavior 
> > > > > https://godbolt.org/z/6abbPhn4G
> > > > The condition here only applies to condition variables.
> > > > C++ does not allow array type in condition variable, correct? I think 
> > > > it's OK to use `isAggregateType` as well then.
> > > After a chat with Aaron, I have a few questions: Do we call 
> > > `Scope::AddDecl` - or `PushOnScopeChains` somewhere?
> > > My intuition is that if the condition is added to a scope, and we call `  
> > >   ConditionVar->setReferenced(false);`, the all the diagnostic mechanism 
> > > in `DiagnoseUnusedDecl` should be triggered. and it seen to be because we 
> > > do get a diagnostic.
> > > So neither `if (!T->isAggregateType())` or any check should be needed 
> > > there
> > > 
> > > Can you just remove that if statement (just set `setReferenced(false)`) 
> > > and see if it works? Otherwise, i think we need to understand why it 
> > > doesn't but trying to reimplement the logic of 
> > > `ShouldDiagnoseUnusedDecl`seems fraught with unbounded complexity.
> > It didn't break any tests locally, but when the record type does not have a 
> > user-provided dtor, it is diagnosed as unused, which seems not nice. 
> > (example written in the test `trivial_dtor`)
> It's still a declaration that does nothing, so diagnosing let you remove it
> https://compiler-explorer.com/z/a1GGs9cxa this is consistent with local 
> variables. I like the simplicity of the change.
Ah, I see. Thanks!


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

https://reviews.llvm.org/D152495

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


[PATCH] D155213: [HIP] Add `-fno-hip-uniform-block`

2023-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1092
   ShouldParseIf;
+defm hip_uniform_block : BoolFOption<"hip-uniform-block",
+  LangOpts<"HIPUniformBlock">, DefaultTrue,

scchan wrote:
> arsenm wrote:
> > Can we avoid adding yet another language flag for something that's reusable 
> > for everything? Is there an --offload- ?
> Don't we need a different default value for some languages like OpenCL?
Yes, but opencl already has a spec'd flag for this. If we're making up a new 
one, it could be something generic that aliases the opencl one in that case. 
Plus the +/- value of a new flag should work (the CL one only goes in one 
direction)


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

https://reviews.llvm.org/D155213

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


[PATCH] D150083: [clang-format] ObjCPropertyAttributeOrder to sort ObjC property attributes

2023-07-14 Thread Jared Grubb via Phabricator via cfe-commits
jaredgrubb updated this revision to Diff 540492.
jaredgrubb added a comment.

Rebased (no other updates) to re-run build and hopefully get some eyes on this.


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

https://reviews.llvm.org/D150083

Files:
  clang/docs/ClangFormatStyleOptions.rst
  clang/docs/ReleaseNotes.rst
  clang/docs/tools/clang-formatted-files.txt
  clang/include/clang/Format/Format.h
  clang/lib/Format/CMakeLists.txt
  clang/lib/Format/Format.cpp
  clang/lib/Format/ObjCPropertyAttributeOrderFixer.cpp
  clang/lib/Format/ObjCPropertyAttributeOrderFixer.h
  clang/lib/Format/QualifierAlignmentFixer.cpp
  clang/lib/Format/QualifierAlignmentFixer.h
  clang/unittests/Format/CMakeLists.txt
  clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp
  llvm/utils/gn/secondary/clang/lib/Format/BUILD.gn
  llvm/utils/gn/secondary/clang/unittests/Format/BUILD.gn
  utils/bazel/llvm-project-overlay/clang/BUILD.bazel

Index: utils/bazel/llvm-project-overlay/clang/BUILD.bazel
===
--- utils/bazel/llvm-project-overlay/clang/BUILD.bazel
+++ utils/bazel/llvm-project-overlay/clang/BUILD.bazel
@@ -1357,6 +1357,7 @@
 "lib/Format/FormatTokenLexer.h",
 "lib/Format/FormatTokenSource.h",
 "lib/Format/Macros.h",
+"lib/Format/ObjCPropertyAttributeOrderFixer.h",
 "lib/Format/QualifierAlignmentFixer.h",
 "lib/Format/UnwrappedLineParser.h",
 ] + glob([
Index: llvm/utils/gn/secondary/clang/unittests/Format/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/unittests/Format/BUILD.gn
+++ llvm/utils/gn/secondary/clang/unittests/Format/BUILD.gn
@@ -36,6 +36,7 @@
 "MacroCallReconstructorTest.cpp",
 "MacroExpanderTest.cpp",
 "NamespaceEndCommentsFixerTest.cpp",
+"ObjCPropertyAttributeOrderFixerTest.cpp",
 "QualifierFixerTest.cpp",
 "SortImportsTestJS.cpp",
 "SortImportsTestJava.cpp",
Index: llvm/utils/gn/secondary/clang/lib/Format/BUILD.gn
===
--- llvm/utils/gn/secondary/clang/lib/Format/BUILD.gn
+++ llvm/utils/gn/secondary/clang/lib/Format/BUILD.gn
@@ -20,6 +20,7 @@
 "MacroCallReconstructor.cpp",
 "MacroExpander.cpp",
 "NamespaceEndCommentsFixer.cpp",
+"ObjCPropertyAttributeOrderFixer.cpp",
 "QualifierAlignmentFixer.cpp",
 "SortJavaScriptImports.cpp",
 "TokenAnalyzer.cpp",
Index: clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp
===
--- /dev/null
+++ clang/unittests/Format/ObjCPropertyAttributeOrderFixerTest.cpp
@@ -0,0 +1,393 @@
+//===- unittest/Format/ObjCPropertyAttributeOrderFixerTest.cpp - unit tests
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#include "../lib/Format/ObjCPropertyAttributeOrderFixer.h"
+#include "FormatTestBase.h"
+#include "TestLexer.h"
+
+#define DEBUG_TYPE "format-objc-property-attribute-order-fixer-test"
+
+namespace clang {
+namespace format {
+namespace test {
+namespace {
+
+#define CHECK_PARSE(TEXT, FIELD, VALUE)\
+  EXPECT_NE(VALUE, Style.FIELD) << "Initial value already the same!";  \
+  EXPECT_EQ(0, parseConfiguration(TEXT, &Style).value());  \
+  EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
+
+#define FAIL_PARSE(TEXT, FIELD, VALUE) \
+  EXPECT_NE(0, parseConfiguration(TEXT, &Style).value());  \
+  EXPECT_EQ(VALUE, Style.FIELD) << "Unexpected value after parsing!"
+
+class ObjCPropertyAttributeOrderFixerTest : public FormatTestBase {
+protected:
+  TokenList annotate(llvm::StringRef Code,
+ const FormatStyle &Style = getLLVMStyle()) {
+return TestLexer(Allocator, Buffers, Style).annotate(Code);
+  }
+
+  llvm::SpecificBumpPtrAllocator Allocator;
+  std::vector> Buffers;
+};
+
+TEST_F(ObjCPropertyAttributeOrderFixerTest, ParsesStyleOption) {
+  FormatStyle Style = {};
+  Style.Language = FormatStyle::LK_ObjC;
+
+  CHECK_PARSE("ObjCPropertyAttributeOrder: [class]", ObjCPropertyAttributeOrder,
+  std::vector({"class"}));
+
+  CHECK_PARSE("ObjCPropertyAttributeOrder: ["
+  "class, direct, atomic, nonatomic, "
+  "assign, retain, strong, copy, weak, unsafe_unretained, "
+  "readonly, readwrite, getter, setter, "
+  "nullable, nonnull, null_resettable, null_unspecified"
+  "]",
+  ObjCPropertyAttributeOrder,
+  std::vector({
+  "class",
+  "direct",
+  "a

[PATCH] D155213: [HIP] Add `-fno-hip-uniform-block`

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl marked an inline comment as done.
yaxunl added inline comments.



Comment at: clang/include/clang/Driver/Options.td:1092
   ShouldParseIf;
+defm hip_uniform_block : BoolFOption<"hip-uniform-block",
+  LangOpts<"HIPUniformBlock">, DefaultTrue,

arsenm wrote:
> Can we avoid adding yet another language flag for something that's reusable 
> for everything? Is there an --offload- ?
Currently, the naming convention for shared CUDA/HIP language options is 
`-fgpu-*` or `--gpu-* . The shared CUDA/HIP/OpenMP driver options are named 
`--offload-*`.

This option is named `-fhip-uniform-block` because AFAIK CUDA does not support 
non-uniform block size.

If we want to make it a generic option, it should be named as 
`-fgpu-uniform-block` by the current naming convention. Unless we want to 
change the naming convention for generic offloading language options.

@tra What do you think? Thanks.


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

https://reviews.llvm.org/D155213

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


[PATCH] D154495: clang: Attach !fpmath metadata to __builtin_sqrt based on language flags

2023-07-14 Thread Matt Arsenault via Phabricator via cfe-commits
arsenm added a comment.

ping


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

https://reviews.llvm.org/D154495

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


[PATCH] D154495: clang: Attach !fpmath metadata to __builtin_sqrt based on language flags

2023-07-14 Thread Yaxun Liu via Phabricator via cfe-commits
yaxunl accepted this revision.
yaxunl added a comment.
This revision is now accepted and ready to land.

LGTM. Thanks.


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

https://reviews.llvm.org/D154495

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


[clang] df71216 - [RISCV] Make __builtin_riscv_clz/ctz return an unsigned int instead of signed int.

2023-07-14 Thread Craig Topper via cfe-commits

Author: Craig Topper
Date: 2023-07-14T11:13:47-07:00
New Revision: df71216d0301780de9dfc467745dd10843de4400

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

LOG: [RISCV] Make __builtin_riscv_clz/ctz return an unsigned int instead of 
signed int.

This is different than the target independent __builtin_clz/ctz, but
logically makes more sense.

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsRISCV.def
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-xtheadbb.c
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-xtheadbb.c
clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-zbb.c

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsRISCV.def 
b/clang/include/clang/Basic/BuiltinsRISCV.def
index 4b4c7858d0fa7d..8eac0afae3ec95 100644
--- a/clang/include/clang/Basic/BuiltinsRISCV.def
+++ b/clang/include/clang/Basic/BuiltinsRISCV.def
@@ -18,10 +18,10 @@
 // Zbb extension
 TARGET_BUILTIN(__builtin_riscv_orc_b_32, "UZiUZi", "nc", "zbb")
 TARGET_BUILTIN(__builtin_riscv_orc_b_64, "UWiUWi", "nc", "zbb,64bit")
-TARGET_BUILTIN(__builtin_riscv_clz_32, "iUZi", "nc", "zbb|xtheadbb")
-TARGET_BUILTIN(__builtin_riscv_clz_64, "iUWi", "nc", "zbb|xtheadbb,64bit")
-TARGET_BUILTIN(__builtin_riscv_ctz_32, "iUZi", "nc", "zbb")
-TARGET_BUILTIN(__builtin_riscv_ctz_64, "iUWi", "nc", "zbb,64bit")
+TARGET_BUILTIN(__builtin_riscv_clz_32, "UiUZi", "nc", "zbb|xtheadbb")
+TARGET_BUILTIN(__builtin_riscv_clz_64, "UiUWi", "nc", "zbb|xtheadbb,64bit")
+TARGET_BUILTIN(__builtin_riscv_ctz_32, "UiUZi", "nc", "zbb")
+TARGET_BUILTIN(__builtin_riscv_ctz_64, "UiUWi", "nc", "zbb,64bit")
 
 // Zbc or Zbkc extension
 TARGET_BUILTIN(__builtin_riscv_clmul, "LiLiLi", "nc", "zbc|zbkc")

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-xtheadbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-xtheadbb.c
index 915dd806d21791..a16b1436fef9c7 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-xtheadbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-xtheadbb.c
@@ -10,7 +10,7 @@
 // RV32XTHEADBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], 
i1 false)
 // RV32XTHEADBB-NEXT:ret i32 [[TMP1]]
 //
-int clz_32(int a) {
+unsigned int clz_32(unsigned int a) {
   return __builtin_riscv_clz_32(a);
 }
 
@@ -23,6 +23,6 @@ int clz_32(int a) {
 // RV32XTHEADBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[NOT]], 
i1 false)
 // RV32XTHEADBB-NEXT:ret i32 [[TMP1]]
 //
-int clo_32(int a) {
+unsigned int clo_32(unsigned int a) {
   return __builtin_riscv_clz_32(~a);
 }

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
index b4610be2714e77..6e7ecf0300fba5 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv32-zbb.c
@@ -22,7 +22,7 @@ unsigned int orc_b_32(unsigned int a) {
 // RV32ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], i1 
false)
 // RV32ZBB-NEXT:ret i32 [[TMP1]]
 //
-int clz_32(unsigned int a) {
+unsigned int clz_32(unsigned int a) {
   return __builtin_riscv_clz_32(a);
 }
 
@@ -34,6 +34,6 @@ int clz_32(unsigned int a) {
 // RV32ZBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.cttz.i32(i32 [[TMP0]], i1 
false)
 // RV32ZBB-NEXT:ret i32 [[TMP1]]
 //
-int ctz_32(unsigned int a) {
+unsigned int ctz_32(unsigned int a) {
   return __builtin_riscv_ctz_32(a);
 }

diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-xtheadbb.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-xtheadbb.c
index 44220627b36cf2..da74ca92137c11 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-xtheadbb.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/riscv64-xtheadbb.c
@@ -10,7 +10,7 @@
 // RV64XTHEADBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[TMP0]], 
i1 false)
 // RV64XTHEADBB-NEXT:ret i32 [[TMP1]]
 //
-int clz_32(int a) {
+unsigned int clz_32(unsigned int a) {
   return __builtin_riscv_clz_32(a);
 }
 
@@ -23,7 +23,7 @@ int clz_32(int a) {
 // RV64XTHEADBB-NEXT:[[TMP1:%.*]] = call i32 @llvm.ctlz.i32(i32 [[NOT]], 
i1 false)
 // RV64XTHEADBB-NEXT:ret i32 [[TMP1]]
 //
-int clo_32(int a) {
+unsigned int clo_32(unsigned int a) {
   return __builtin_riscv_clz_32(~a);
 }
 
@@ -36,7 +36,7 @@ int clo_32(int a) {
 // RV64XTHEADBB-NEXT:[[CAST:%.*]] = trunc i64 [[TMP1]] to i32
 // RV64XTHEADBB-NEXT:ret i32 [[CAST]]
 //
-int clz_64(long a) {
+unsigned int clz_64(unsigned long a) {
   return __builtin_riscv_clz_64(a);
 }
 
@@ -50,6 +50,6 @@ int clz_64(long a) {
 // RV64XTHEADBB-NEXT:[[CAST:%.*]] = trunc i64 [[TMP1]] to i32
 // RV64XTHEADBB-NEXT:ret i32 [[CAST]]
 //
-int clo_64(long a) {
+unsigned int clo_64(unsigned long a) {
  

[PATCH] D155321: [clang][Analysis] ExprMutationAnalyzer: break infinite recursion on recursive function call

2023-07-14 Thread Ding Fei via Phabricator via cfe-commits
danix800 created this revision.
danix800 added a reviewer: shuaiwang.
danix800 added projects: clang, clang-tools-extra.
Herald added subscribers: PiotrZSL, carlosgalvezp, manas, ASDenysPetrov, 
dkrupp, donat.nagy, Szelethus, a.sidorin, baloghadamsoftware.
Herald added a reviewer: NoQ.
Herald added a project: All.
danix800 requested review of this revision.
Herald added a subscriber: cfe-commits.

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


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155321

Files:
  
clang-tools-extra/test/clang-tidy/checkers/readability/use-anyofallof-nocrash.cpp
  clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
  clang/lib/Analysis/ExprMutationAnalyzer.cpp
  clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp

Index: clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
===
--- clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
+++ clang/unittests/Analysis/ExprMutationAnalyzerTest.cpp
@@ -1309,6 +1309,30 @@
   EXPECT_FALSE(isMutated(Results, AST.get()));
 }
 
+TEST(ExprMutationAnalyzerTest, RangeForNonArrayByConstRefNoCrash) {
+  const auto AST = buildASTFromCode(R"(
+struct V {
+  V* begin() const;
+  V* end() const;
+};
+void f(V &elem) {
+  auto rec = [](const auto& e, auto&& self) -> bool {
+for (auto& child : e) {
+  if (!self(child, self)) {
+return false;
+  }
+}
+return true;
+  };
+
+  rec(elem, rec);
+}
+  )");
+  const auto Results =
+  match(withEnclosingCompound(declRefTo("elem")), AST->getASTContext());
+  EXPECT_FALSE(isMutated(Results, AST.get()));
+}
+
 // section: unevaluated expressions
 
 TEST(ExprMutationAnalyzerTest, UnevaluatedExpressions) {
Index: clang/lib/Analysis/ExprMutationAnalyzer.cpp
===
--- clang/lib/Analysis/ExprMutationAnalyzer.cpp
+++ clang/lib/Analysis/ExprMutationAnalyzer.cpp
@@ -568,6 +568,11 @@
 if (!Func->getBody() || !Func->getPrimaryTemplate())
   return Exp;
 
+if (DeclAnalyzed->contains(Func)) {
+  return nullptr;
+}
+DeclAnalyzed->insert(Func);
+
 const auto *Parm = Nodes.getNodeAs("parm");
 const ArrayRef AllParams =
 Func->getPrimaryTemplate()->getTemplatedDecl()->parameters();
@@ -586,7 +591,8 @@
 std::unique_ptr &Analyzer =
 FuncParmAnalyzer[Func];
 if (!Analyzer)
-  Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context));
+  Analyzer.reset(new FunctionParmMutationAnalyzer(*Func, Context,
+  DeclAnalyzed));
 if (Analyzer->findMutation(Parm))
   return Exp;
 continue;
@@ -599,8 +605,8 @@
 }
 
 FunctionParmMutationAnalyzer::FunctionParmMutationAnalyzer(
-const FunctionDecl &Func, ASTContext &Context)
-: BodyAnalyzer(*Func.getBody(), Context) {
+const FunctionDecl &Func, ASTContext &Context, DeclSet *DeclAnalyzed)
+: BodyAnalyzer(*Func.getBody(), Context, DeclAnalyzed) {
   if (const auto *Ctor = dyn_cast(&Func)) {
 // CXXCtorInitializer might also mutate Param but they're not part of
 // function body, check them eagerly here since they're typically trivial.
Index: clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
===
--- clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
+++ clang/include/clang/Analysis/Analyses/ExprMutationAnalyzer.h
@@ -18,12 +18,20 @@
 
 class FunctionParmMutationAnalyzer;
 
+using DeclSet = llvm::DenseSet;
+
 /// Analyzes whether any mutative operations are applied to an expression within
 /// a given statement.
 class ExprMutationAnalyzer {
 public:
-  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context)
-  : Stm(Stm), Context(Context) {}
+  ExprMutationAnalyzer(const Stmt &Stm, ASTContext &Context,
+   DeclSet *DeclAnalyzed = nullptr)
+  : Stm(Stm), Context(Context), DeclAnalyzed(DeclAnalyzed) {
+if (nullptr == DeclAnalyzed) {
+  OwningDeclAnalyzed = std::make_unique();
+  this->DeclAnalyzed = OwningDeclAnalyzed.get();
+}
+  }
 
   bool isMutated(const Expr *Exp) { return findMutation(Exp) != nullptr; }
   bool isMutated(const Decl *Dec) { return findMutation(Dec) != nullptr; }
@@ -74,13 +82,16 @@
   FuncParmAnalyzer;
   ResultMap Results;
   ResultMap PointeeResults;
+  DeclSet *DeclAnalyzed;
+  std::unique_ptr OwningDeclAnalyzed;
 };
 
 // A convenient wrapper around ExprMutationAnalyzer for analyzing function
 // params.
 class FunctionParmMutationAnalyzer {
 public:
-  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context);
+  FunctionParmMutationAnalyzer(const FunctionDecl &Func, ASTContext &Context,
+   DeclSet *DeclAnalyzed = nullptr);
 
   bool isMutated(const Par

[PATCH] D155290: [PGO] Use Unique Profile Files when New Processes are Forked

2023-07-14 Thread David Li via Phabricator via cfe-commits
davidxl added inline comments.



Comment at: compiler-rt/lib/profile/InstrProfilingFile.c:795
-  /* When PNS >= OldPNS, the last one wins. */
-  if (!FilenamePat || parseFilenamePattern(FilenamePat, CopyFilenamePat))
 resetFilenameToDefault();

what is this change for?



Comment at: compiler-rt/test/profile/Posix/instrprof-fork.c:10
+// RUN: PROFILE2=`tail -n 1 %t.out`
+// RUN: ls $PROFILE2
+

add some dump and check to make sure profiles are not truncated?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155290

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


[PATCH] D153914: [clang-cl] Enable concatenation of predefined identifiers

2023-07-14 Thread Tom Honermann via Phabricator via cfe-commits
tahonermann requested changes to this revision.
tahonermann added inline comments.
This revision now requires changes to proceed.



Comment at: clang/include/clang/Basic/DiagnosticSemaKinds.td:118-120
+def ext_concat_predef_ms : ExtWarn<
+  "concatenation of predefined identifier '%0' is a Microsoft extension">,
+  InGroup;

I think it makes since to be more explicit that the concatenation is with 
regard to string literals.



Comment at: clang/include/clang/Basic/TokenKinds.h:87-93
+/// Return true if this token is a predefined macro
+/// unexpandable by MSVC preprocessor.
+inline bool isUnexpandableMsMacro(TokenKind K) {
+  return K == tok::kw___FUNCTION__ || K == tok::kw___FUNCSIG__ ||
+ K == tok::kw_L__FUNCTION__ || K == tok::kw_L__FUNCSIG__ ||
+ K == tok::kw___FUNCDNAME__;
+}





Comment at: clang/include/clang/Parse/Parser.h:578-582
+  bool isTokenConcatenable() const {
+return isTokenStringLiteral() ||
+   getLangOpts().MicrosoftExt &&
+   tok::isMSPredefinedMacro(Tok.getKind());
+  }

RIscRIpt wrote:
> cor3ntin wrote:
> > Unless you find a better name,  I think it's preferable to keep 
> > `isTokenConcatenable` and `isTokenPredefinedMsMacro` as separate functions.
> > Also, this seems like a weird place to check for  
> > `getLangOpts().MicrosoftExt`
> Regarding `getLangOpts().MicrosoftExt`. If you are talking about it's 
> presence in a function which name is meant to be used as a predicate, I 
> agree. If you are talking about `class Parser`, then there're other places 
> with references to `getLangOpts()`.
> 
> Without such function `ParseStringLiteralExpression` implementation would be 
> too verbose.
> Let's decide what we can do after I address other comments.
> 
> Meanwhile, I renamed it to `isTokenLikeStringLiteral()`.
I suggest passing `getLangOpts()` to `isFunctionLocalPredefinedMacro` 
(`isUnexpandableMsMacro`) and letting it determine whether the token is or is 
not one of these special not-really-a-string-literal macro things. This will 
facilitate additional such macros controlled by different options while also 
colocating the option check with the related tokens.



Comment at: clang/include/clang/Sema/Sema.h:5681
 
+  std::vector ExpandUnexpandableMsMacros(ArrayRef Toks);
   ExprResult BuildPredefinedExpr(SourceLocation Loc,





Comment at: clang/lib/Parse/ParseExpr.cpp:1300-1307
+if (!getLangOpts().MicrosoftExt || !tok::isUnexpandableMsMacro(SavedKind) 
||
+!tok::isUnexpandableMsMacro(NextToken().getKind()) &&
+!tok::isStringLiteral(NextToken().getKind())) {
+  Res = Actions.ActOnPredefinedExpr(Tok.getLocation(), SavedKind);
+  ConsumeToken();
+  break;
+}

Since the conditional code is only relevant for some of the tokens here, I 
would prefer to see the other token kinds (`kw___func__`, 
`kw___PRETTY_FUNCTION__`) handled separately to avoid the conditional 
fallthrough. That means duplicating the calls to 
`Actions.ActOnPredefinedExpr()` and `ConsumeToken()` between the blocks, but 
that bothers me less than having to understand the complicated condition.



Comment at: clang/lib/Parse/ParseExpr.cpp:3277-3280
+  // String concatenation.
+  // Note that keywords like __func__ and __FUNCTION__
+  // are not considered to be strings for concatenation purposes,
+  // unless Microsoft extensions are enabled.

I think `__func__` is not considered a string literal in Microsoft mode, so I 
think this comment needs some adjusting.



Comment at: clang/lib/Parse/ParseExpr.cpp:3288-3291
+  assert(
+  (StringToks.size() != 1 ||
+   !tok::isUnexpandableMsMacro(StringToks[0].getKind())) &&
+  "single predefined identifiers shall be handled by ActOnPredefinedExpr");

What is the reason for requiring non-concatenated predefined function local 
macros to be handled by `ActOnPredefinedExpr()`?



Comment at: clang/lib/Sema/Sema.cpp:1494
 
+Decl *Sema::getCurScopeDecl() {
+  if (const BlockScopeInfo *BSI = getCurBlock())

`getCurScopeDecl` isn't a great name since this doesn't handle class or 
namespace scopes. How about `getCurLocalScopeDecl`? That name isn't quite right 
either since this can return a `TranslationUnitDecl`, but I think it matches 
the intent fairly well.

None of the callers need the actual `TranslationUnitDecl` that is returned. I 
think this function can return `nullptr` is the current scope isn't function 
local and callers can issue the relevant diagnostic in that case (thus avoiding 
the need to check that a translation unit decl was returned).



Comment at: clang/lib/Sema/SemaExpr.cpp:1971-1974
+  // MSVC treats some of predefined identifiers (e.g. __FUNCTION__) as
+  // expandable macros defined as string lite

[PATCH] D155326: [Clang][lld][RISCV] Passing 'mattr' to lld/llvmgold

2023-07-14 Thread Yingwei Zheng via Phabricator via cfe-commits
dtcxzyw created this revision.
dtcxzyw added reviewers: MaskRay, jrtc27, kito-cheng, craig.topper.
dtcxzyw added projects: lld, clang.
Herald added subscribers: jobnoorman, VincentWu, vkmr, luismarques, 
sameer.abuasal, s.egerton, Jim, benna, psnobl, PkmX, rogfer01, shiva0217, 
simoncook, arichardson, emaste.
Herald added a project: All.
dtcxzyw requested review of this revision.
Herald added subscribers: llvm-commits, cfe-commits, wangpc, eopXD.
Herald added a project: LLVM.

When building applications with LTO/ThinLTO, lld and llvmgold emit wrong 
`.riscv.attributes` sections due to the lack of sub-target features 
(`codegen::getMAttrs()` returns empty).
This patch adds a new plugin option `mattr` for lld and llvmgold, to get right 
module-level sub-target features for temporary ELF objects generated from llvm 
bitcode.

I think it is a better solution than merging func-level sub-target features 
like D142191 .


Repository:
  rG LLVM Github Monorepo

https://reviews.llvm.org/D155326

Files:
  clang/lib/Driver/ToolChains/Arch/CSKY.cpp
  clang/lib/Driver/ToolChains/Arch/CSKY.h
  clang/lib/Driver/ToolChains/CommonArgs.cpp
  lld/ELF/Driver.cpp
  lld/ELF/Options.td
  llvm/tools/gold/gold-plugin.cpp

Index: llvm/tools/gold/gold-plugin.cpp
===
--- llvm/tools/gold/gold-plugin.cpp
+++ llvm/tools/gold/gold-plugin.cpp
@@ -33,6 +33,7 @@
 #include "llvm/Support/Threading.h"
 #include "llvm/Support/raw_ostream.h"
 #include "llvm/TargetParser/Host.h"
+#include "llvm/TargetParser/SubtargetFeature.h"
 #include 
 #include 
 #include 
@@ -152,6 +153,7 @@
   static std::string extra_library_path;
   static std::string triple;
   static std::string mcpu;
+  static std::string mattr;
   // When the thinlto plugin option is specified, only read the function
   // the information from intermediate files and write a combined
   // global index for the ThinLTO backends.
@@ -228,6 +230,8 @@
 
 if (opt.consume_front("mcpu=")) {
   mcpu = std::string(opt);
+} else if (opt.consume_front("mattr=")) {
+  mattr = std::string(opt);
 } else if (opt.consume_front("extra-library-path=")) {
   extra_library_path = std::string(opt);
 } else if (opt.consume_front("mtriple=")) {
@@ -875,7 +879,8 @@
   if (!codegen::getExplicitDataSections())
 Conf.Options.DataSections = SplitSections;
 
-  Conf.MAttrs = codegen::getMAttrs();
+  SubtargetFeatures Features(options::mattr);
+  Conf.MAttrs = Features.getFeatures();
   Conf.RelocModel = RelocationModel;
   Conf.CodeModel = codegen::getExplicitCodeModel();
   std::optional CGOptLevelOrNone =
Index: lld/ELF/Options.td
===
--- lld/ELF/Options.td
+++ lld/ELF/Options.td
@@ -656,6 +656,7 @@
 def: J<"plugin-opt=jobs=">, Alias, HelpText<"Alias for --thinlto-jobs=">;
 def: J<"plugin-opt=lto-partitions=">, Alias, HelpText<"Alias for --lto-partitions">;
 def plugin_opt_mcpu_eq: J<"plugin-opt=mcpu=">;
+def plugin_opt_mattr_eq: J<"plugin-opt=mattr=">;
 def: F<"plugin-opt=cs-profile-generate">,
   Alias, HelpText<"Alias for --lto-cs-profile-generate">;
 def: J<"plugin-opt=cs-profile-path=">,
Index: lld/ELF/Driver.cpp
===
--- lld/ELF/Driver.cpp
+++ lld/ELF/Driver.cpp
@@ -1467,6 +1467,10 @@
 parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
  arg->getSpelling());
 
+  if (auto *arg = args.getLastArg(OPT_plugin_opt_mattr_eq))
+parseClangOption(saver().save("-mattr=" + StringRef(arg->getValue())),
+ arg->getSpelling());
+
   for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq_minus))
 parseClangOption(std::string("-") + arg->getValue(), arg->getSpelling());
 
Index: clang/lib/Driver/ToolChains/CommonArgs.cpp
===
--- clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -62,6 +62,7 @@
 #include "llvm/Support/VirtualFileSystem.h"
 #include "llvm/Support/YAMLParser.h"
 #include "llvm/TargetParser/Host.h"
+#include "llvm/TargetParser/SubtargetFeature.h"
 #include "llvm/TargetParser/TargetParser.h"
 #include 
 
@@ -485,10 +486,10 @@
 options::OPT_m_wasm_Features_Group);
 }
 
-void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
-  const ArgList &Args, ArgStringList &CmdArgs,
-  bool ForAS, bool IsAux) {
-  std::vector Features;
+static void collectTargetFeatures(const Driver &D, const llvm::Triple &Triple,
+  const ArgList &Args,
+  std::vector &Features,
+  bool ForAS) {
   switch (Triple.getArch()) {
   default:
 break;
@@ -556,13 +557,20 @@
 ve::getVETargetFeatures(D, Args, Features);
 

[PATCH] D155326: [Clang][lld][RISCV] Passing 'mattr' to lld/llvmgold

2023-07-14 Thread Jessica Clarke via Phabricator via cfe-commits
jrtc27 added a comment.

Why do you believe this is better than encoding it in the module's IR like the 
ABI?


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155326

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


[PATCH] D154130: [lit] Avoid os.path.realpath on Windows due to MAX_PATH limitations

2023-07-14 Thread Tristan Labelle via Phabricator via cfe-commits
MrTrillian added a comment.

In D154130#4487292 , @jdenny wrote:

> 3. Extend lit's own test suite to cover it.

I submitted an update with your suggestions #1 and #2 but this #3 is much more 
difficult because of the nature of `%{t:real}`. I'm not sure I can have a 
source/target path that includes symlinks in a way that allows me to test this, 
and even more so with substitute drives since we can't know which drive letters 
are unallocated.


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

https://reviews.llvm.org/D154130

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


[clang] 7a59e2c - [clang][NFC] Remove trailing whitespace from riscv_vector.td

2023-07-14 Thread Nikolas Klauser via cfe-commits

Author: Nikolas Klauser
Date: 2023-07-14T12:38:29-07:00
New Revision: 7a59e2c59187fc76e39b0e4d5bfd13a0a5144c44

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

LOG: [clang][NFC] Remove trailing whitespace from riscv_vector.td

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/riscv_vector.td 
b/clang/include/clang/Basic/riscv_vector.td
index 3aa69b124a97a2..49011d61af1a2a 100644
--- a/clang/include/clang/Basic/riscv_vector.td
+++ b/clang/include/clang/Basic/riscv_vector.td
@@ -2368,7 +2368,7 @@ let ManualCodegen = [{
 let OverloadedName = "vfcvt_x" in
   defm :
 RVVConvBuiltinSet<"vfcvt_x_f_v", "xfd", [["Iv", "Ivvu"]]>;
-let OverloadedName = "vfcvt_xu" in
+let OverloadedName = "vfcvt_xu" in
   defm :
 RVVConvBuiltinSet<"vfcvt_xu_f_v", "xfd", [["Uv", "Uvvu"]]>;
 let OverloadedName = "vfcvt_f" in {
@@ -2411,7 +2411,7 @@ let ManualCodegen = [{
   let OverloadedName = "vfcvt_x" in
 defm :
   RVVConvBuiltinSet<"vfcvt_x_f_v", "xfd", [["Iv", "Ivv"]]>;
-  let OverloadedName = "vfcvt_xu" in
+  let OverloadedName = "vfcvt_xu" in
 defm :
   RVVConvBuiltinSet<"vfcvt_xu_f_v", "xfd", [["Uv", "Uvv"]]>;
   let OverloadedName = "vfcvt_f" in {



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


[PATCH] D154357: [Driver] Recognize powerpc-unknown-eabi as a bare-metal toolchain

2023-07-14 Thread Fangrui Song via Phabricator via cfe-commits
MaskRay added a comment.

In D154357#4500241 , @cwalther wrote:

> Thank you!
>
> So I guess next time I submit a patch here (nothing planned at the moment), I 
> should put the proposed commit message into the summary field and the 
> backstory and start of discussion / open questions into a first comment. But 
> maybe the point is moot as I understand you are about to move to GitHub pull 
> requests, which I am more familiar with.

Yeah, you can place the commit message in the summary field and add 
supplementary information as a separate comment.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D154357

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


[PATCH] D155326: [Clang][lld][RISCV] Passing 'mattr' to lld/llvmgold

2023-07-14 Thread Yingwei Zheng via Phabricator via cfe-commits
dtcxzyw added a comment.

In D155326#4501997 , @jrtc27 wrote:

> Why do you believe this is better than encoding it in the module's IR like 
> the ABI?



- There is no module-level metadata for target CPU and sub-target features. So 
I just think that this patch is better than merging from **func-level** 
attributes like D142191 .
- Clang passes `-plugin-opt=mcpu` to lld. Then lld builds `lto::Config` using 
`codegen::getCPUStr` and `codegen::getMAttrs` (both get the result from command 
args). It is taken for granted that clang passes `-plugin-opt=mattr` down to 
lld.

If we introduce top-level fields like `target cpu` and `target features`, we 
should modify a lot of things (clang/llvm/lld). It can take a long time to 
migrate (like opaque pointers).


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155326

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


[PATCH] D155326: [Clang][lld][RISCV] Passing 'mattr' to lld/llvmgold

2023-07-14 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

-mattr is a different syntax than -march that users are used to. Why would we 
want to expose that?  There was previously a proposal for doing this 
automatically https://reviews.llvm.org/D132843


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155326

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


[PATCH] D155326: [Clang][lld][RISCV] Passing 'mattr' to lld/llvmgold

2023-07-14 Thread Craig Topper via Phabricator via cfe-commits
craig.topper added a comment.

In D155326#4502097 , @dtcxzyw wrote:

> In D155326#4501997 , @jrtc27 wrote:
>
>> Why do you believe this is better than encoding it in the module's IR like 
>> the ABI?
>
>
>
> - There is no module-level metadata for target CPU and sub-target features. 
> So I just think that this patch is better than merging from **func-level** 
> attributes like D142191 .
> - Clang passes `-plugin-opt=mcpu` to lld. Then lld builds `lto::Config` using 
> `codegen::getCPUStr` and `codegen::getMAttrs` (both get the result from 
> command args). It is taken for granted that clang passes `-plugin-opt=mattr` 
> down to lld.
>
> If we introduce top-level fields like `target cpu` and `target features`, we 
> should modify a lot of things (clang/llvm/lld). It can take a long time to 
> migrate (like opaque pointers).

You're right it might take time, but we've been saying that's what needs to be 
done for a year. It might have been done by now if the work had gotten started.


Repository:
  rG LLVM Github Monorepo

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

https://reviews.llvm.org/D155326

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


[PATCH] D154130: [lit] Avoid os.path.realpath on Windows due to MAX_PATH limitations

2023-07-14 Thread Joel E. Denny via Phabricator via cfe-commits
jdenny added a comment.

In D154130#4502036 , @MrTrillian 
wrote:

> In D154130#4487292 , @jdenny wrote:
>
>> 3. Extend lit's own test suite to cover it.
>
> I submitted an update with your suggestions #1 and #2 but this #3 is much 
> more difficult because of the nature of `%{t:real}`.

Thanks for doing that. I'll try to review more carefully soon, hopefully early 
next week.

> I'm not sure I can have a source/target path that includes symlinks in a way 
> that allows me to test this, and even more so with substitute drives since we 
> can't know which drive letters are unallocated.

Not being a windows person, it's hard for me to answer about substitute drives, 
but I understand your concern.

One possible approach is to verify the relationships among the various flavors 
of a substitution (e.g., `%t`, `%{t:real}`, etc.), and hope (or ensure) that 
some CI configs that run check-lit will use substitute drives for the source 
and/or build directory.  The tests should pass regardless.

A less desirable approach is just to do minimal sanity checks, such as checking 
that the base file name is the same across all flavors of a substitution.

Of course, the least desirable approach is to depend on other subprojects' test 
suites to catch lit bugs.  It's easier for lit developers to identify lit bugs 
when check-lit itself shows them, preferably locally but possibly in CI.

Thanks for taking a look at this.


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

https://reviews.llvm.org/D154130

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


[PATCH] D150338: [-Wunsafe-buffer-usage] Improving insertion of the [[clang::unsafe_buffer_usage]] attribute

2023-07-14 Thread Ziqing Luo via Phabricator via cfe-commits
ziqingluo-90 updated this revision to Diff 540548.
ziqingluo-90 added a comment.

rebase


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

https://reviews.llvm.org/D150338

Files:
  clang/include/clang/Analysis/Analyses/UnsafeBufferUsage.h
  clang/lib/Analysis/UnsafeBufferUsage.cpp
  clang/lib/Sema/AnalysisBasedWarnings.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-attributes-spelling.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span-overload.cpp
  
clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span-qualified-names.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
  clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp

Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-unsupported.cpp
@@ -5,13 +5,13 @@
   // CHECK: fix-it:{{.*}}:{[[@LINE-1]]:16-[[@LINE-1]]:29}:"std::span const x"
   int tmp = x[5]; // expected-note{{used in buffer access here}}
 }
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoid const_ptr(int * const x) {return const_ptr(std::span(x, <# size #>));}\n"
+// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void const_ptr(int * const x) {return const_ptr(std::span(x, <# size #>));}\n"
 
 void const_ptr_to_const(const int * const x) {// expected-warning{{'x' is an unsafe pointer used for buffer access}} expected-note{{change type of 'x' to 'std::span' to preserve bounds information}}
   // CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:25-[[@LINE-1]]:44}:"std::span const x"
   int tmp = x[5]; // expected-note{{used in buffer access here}}
 }
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoid const_ptr_to_const(const int * const x) {return const_ptr_to_const(std::span(x, <# size #>));}\n"
+// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void const_ptr_to_const(const int * const x) {return const_ptr_to_const(std::span(x, <# size #>));}\n"
 
 typedef struct {int x;} NAMED_UNNAMED_STRUCT; // an unnamed struct type named by a typedef
 typedef struct {int x;} * PTR_TO_ANON;// pointer to an unnamed struct
@@ -24,7 +24,7 @@
 // CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:7-[[@LINE-1]]:10}:"(p = p.subspan(1)).data()"
   }
 }
-// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoid namedPointeeType(NAMED_UNNAMED_STRUCT * p) {return namedPointeeType(std::span(p, <# size #>));}\n"
+// CHECK: fix-it:"{{.*}}":{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void namedPointeeType(NAMED_UNNAMED_STRUCT * p) {return namedPointeeType(std::span(p, <# size #>));}\n"
 
 // We CANNOT fix a pointer to an unnamed type
 // CHECK-NOT: fix-it:
Index: clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
===
--- clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
+++ clang/test/SemaCXX/warn-unsafe-buffer-usage-fixits-parm-span.cpp
@@ -6,13 +6,13 @@
 #define INCLUDE_ME
 
 void simple(int *p);
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:1-[[@LINE-1]]:1}:"{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\n"
+// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:1-[[@LINE-1]]:1}:"{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} "
 // CHECK-DAG: fix-it:{{.*}}:{[[@LINE-2]]:20-[[@LINE-2]]:20}:";\nvoid simple(std::span p)"
 
 #else
 
 void simple(int *);
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:1-[[@LINE-1]]:1}:"{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\n"
+// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:1-[[@LINE-1]]:1}:"{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} "
 // CHECK-DAG: fix-it:{{.*}}:{[[@LINE-2]]:19-[[@LINE-2]]:19}:";\nvoid simple(std::span)"
 
 void simple(int *p) {
@@ -20,7 +20,7 @@
   int tmp;
   tmp = p[5];
 }
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoid simple(int *p) {return simple(std::span(p, <# size #>));}\n"
+// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}} void simple(int *p) {return simple(std::span(p, <# size #>));}\n"
 
 
 void twoParms(int *p, int * q) {
@@ -29,14 +29,14 @@
   int tmp;
   tmp = p[5] + q[5];
 }
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-1]]:2-[[@LINE-1]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoid twoParms(int *p, int * q) {return twoParms(std::span(p, <# size #>), q);}\n"
-// CHECK-DAG: fix-it:{{.*}}:{[[@LINE-2]]:2-[[@LINE-2]]:2}:"\n{{\[}}{{\[}}clang::unsafe_buffer_usage{{\]}}{{\]}}\nvoi

  1   2   >