[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-11-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-x86_64-linux-bootstrap-asan` running on `sanitizer-buildbot2` while 
building `clang` at step 2 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/52/builds/3444


Here is the relevant piece of the build log for the reference

```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 900 seconds was requested on the command line. Forcing 
timeout to be 900 seconds.
-- Testing: 86843 of 86844 tests, 88 workers --
Testing:  0.. 10.. 20.. 30.. 40.. 50.. 60.. 70.. 80.. 90..
FAIL: lld :: ELF/warnings.s (86175 of 86843)
 TEST 'lld :: ELF/warnings.s' FAILED 
Exit Code: 1

Command Output (stderr):
--
RUN: at line 2: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64-pc-linux 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/warnings.s
 -o 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp1.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64-pc-linux 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/warnings.s
 -o 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp1.o
RUN: at line 3: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64-pc-linux 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/Inputs/warn-common.s
 -o 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp2.o
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/llvm-mc 
-filetype=obj -triple=x86_64-pc-linux 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/Inputs/warn-common.s
 -o 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp2.o
RUN: at line 5: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld 
--warn-common 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp1.o
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp2.o
 -o /dev/null 2>&1 |
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 -check-prefix=ERR 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/warnings.s
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 -check-prefix=ERR 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/lld/test/ELF/warnings.s
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld 
--warn-common 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Output/warnings.s.tmp1.o
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/tools/lld/test/ELF/Out

[clang] [lld] [llvm] [Windows] Add support for emitting PGO/LTO magic strings in the Windows PE debug directory (PR #114260)

2024-11-03 Thread Saleem Abdulrasool via cfe-commits


@@ -1165,6 +1188,23 @@ void Writer::createMiscChunks() {
   llvm::TimeTraceScope timeScope("Misc chunks");
   Configuration *config = &ctx.config;
 
+  auto searchForPgoMagicSection = [this](char sectionName[]) {
+for (auto *obj : ctx.objFileInstances) {
+  for (auto &chunk : obj->getChunks()) {
+if (chunk->kind() == Chunk::SectionKind &&
+chunk->getSectionName() == sectionName) {
+  return true;
+}
+  }
+}
+return false;
+  };

compnerd wrote:

Hmm, my thinking was that if we have content that is guaranteed to be folded 
into the debug data directory, the directory will be emitted. As such, the 
linker will link the directory in the header and emit that. This would avoid 
the need to iterate all the sections, it would simply force the emission of the 
debug directory without `/debug` being passed.

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


[clang] [CUDA/HIP] fix propagate -cuid to a host-only compilation. (PR #111650)

2024-11-03 Thread Pankaj Dwivedi via cfe-commits

PankajDwivedi-25 wrote:

Both are separate builds here. 'By Inconsistency' you mean both cases can not 
be present in same build?

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


[clang] 80a4948 - [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (#113966)

2024-11-03 Thread via cfe-commits

Author: Zhaoshi Zheng
Date: 2024-11-03T18:25:20-08:00
New Revision: 80a49487e1b64d32d00f0c80cff746cfd4988b36

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

LOG: [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on 
*windows-msvc targets (#113966)

Follow-up on https://github.com/llvm/llvm-project/pull/109607, we have a
use case on Windows-on-ARM64 where `cmake -G "Unix Makefiles"` generates
`-fuse-ld=lld-link`, which is accidentally disallowed by PR#109607.

Added: 
clang/test/Driver/windows-lto.c

Modified: 
clang/lib/Driver/Driver.cpp
clang/test/Driver/clang_f_opts.c

Removed: 




diff  --git a/clang/lib/Driver/Driver.cpp b/clang/lib/Driver/Driver.cpp
index 083035dee43028..df802450ad5938 100644
--- a/clang/lib/Driver/Driver.cpp
+++ b/clang/lib/Driver/Driver.cpp
@@ -4035,7 +4035,7 @@ void Driver::handleArguments(Compilation &C, 
DerivedArgList &Args,
 if (C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment() &&
 LTOMode != LTOK_None &&
 !Args.getLastArgValue(options::OPT_fuse_ld_EQ)
- .equals_insensitive("lld"))
+ .starts_with_insensitive("lld"))
   Diag(clang::diag::err_drv_lto_without_lld);
 
 // If -dumpdir is not specified, give a default prefix derived from the 
link

diff  --git a/clang/test/Driver/clang_f_opts.c 
b/clang/test/Driver/clang_f_opts.c
index fd15552715cb35..2cfbe256bc7456 100644
--- a/clang/test/Driver/clang_f_opts.c
+++ b/clang/test/Driver/clang_f_opts.c
@@ -606,6 +606,7 @@
 // RUN: %clang -### -S -fjmc -g --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC %s
 // RUN: %clang -### -S -fjmc -g -fno-jmc --target=x86_64-unknown-linux %s 2>&1 
| FileCheck -check-prefix=CHECK_NOJMC %s
 // RUN: %clang -### -fjmc -g -flto -fuse-ld=lld 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
+// RUN: %clang -### -fjmc -g -flto -fuse-ld=lld-link 
--target=x86_64-pc-windows-msvc %s 2>&1 | FileCheck 
-check-prefix=CHECK_NOJMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto --target=x86_64-unknown-linux %s 2>&1 | 
FileCheck -check-prefix=CHECK_JMC_LTO %s
 // RUN: %clang -### -fjmc -g -flto -fno-jmc --target=x86_64-unknown-linux %s 
2>&1 | FileCheck -check-prefix=CHECK_NOJMC_LTO %s
 // CHECK_JMC_WARN: -fjmc requires debug info. Use -g or debug options that 
enable debugger's stepping function; option ignored

diff  --git a/clang/test/Driver/windows-lto.c b/clang/test/Driver/windows-lto.c
new file mode 100644
index 00..f85b0438ee4b1b
--- /dev/null
+++ b/clang/test/Driver/windows-lto.c
@@ -0,0 +1,9 @@
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld -### %s 
2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin -fuse-ld=lld 
-### %s 2>&1 | FileCheck %s
+
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto -fuse-ld=lld-link 
-### %s 2>&1 | FileCheck %s
+// RUN: %clang --target=aarch64-pc-windows-msvc -O3 -flto=thin 
-fuse-ld=lld-link -### %s 2>&1 | FileCheck %s
+
+// CHECK: "{{.*}}lld-link{{(.exe)?}}" "-out:a.exe" "-defaultlib:libcmt" 
"-defaultlib:oldnames"
+
+int main() { return 0; }



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


[clang] [clang][Driver] Allow -fuse-lld=lld-link when lto is enabled on *windows-msvc targets (PR #113966)

2024-11-03 Thread Zhaoshi Zheng via cfe-commits

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


[clang] 4006b28 - [LoongArch][Clang] Make the parameters and return value of {x,}vshuf.b builtins `signed char` vectors (#114512)

2024-11-03 Thread via cfe-commits

Author: Xi Ruoyao
Date: 2024-11-04T08:57:55+08:00
New Revision: 4006b28d102b09f4c736ef0f2664873305fedcd3

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

LOG: [LoongArch][Clang] Make the parameters and return value of {x,}vshuf.b 
builtins `signed char` vectors (#114512)

The lsxintrin.h and and lasxintrin.h headers uses `signed char` vectors
instead of `unsigned char` vectors.  GCC also uses `signed char` for
them, so align their definition with the headers and GCC.

Depends on #114511.  Part of #110834 fix.

Added: 


Modified: 
clang/include/clang/Basic/BuiltinsLoongArchLASX.def
clang/include/clang/Basic/BuiltinsLoongArchLSX.def

Removed: 




diff  --git a/clang/include/clang/Basic/BuiltinsLoongArchLASX.def 
b/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
index 477f704860873c..e6c41dd0974948 100644
--- a/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
+++ b/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
@@ -935,7 +935,7 @@ TARGET_BUILTIN(__builtin_lasx_xvilvh_h, "V16sV16sV16s", 
"nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvilvh_w, "V8iV8iV8i", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvilvh_d, "V4LLiV4LLiV4LLi", "nc", "lasx")
 
-TARGET_BUILTIN(__builtin_lasx_xvshuf_b, "V32UcV32UcV32UcV32Uc", "nc", "lasx")
+TARGET_BUILTIN(__builtin_lasx_xvshuf_b, "V32ScV32ScV32ScV32Sc", "nc", "lasx")
 
 TARGET_BUILTIN(__builtin_lasx_xvshuf_h, "V16sV16sV16sV16s", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvshuf_w, "V8iV8iV8iV8i", "nc", "lasx")

diff  --git a/clang/include/clang/Basic/BuiltinsLoongArchLSX.def 
b/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
index e847985f390367..ded6519f3ef16c 100644
--- a/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
+++ b/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
@@ -910,7 +910,7 @@ TARGET_BUILTIN(__builtin_lsx_vilvh_h, "V8sV8sV8s", "nc", 
"lsx")
 TARGET_BUILTIN(__builtin_lsx_vilvh_w, "V4iV4iV4i", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vilvh_d, "V2LLiV2LLiV2LLi", "nc", "lsx")
 
-TARGET_BUILTIN(__builtin_lsx_vshuf_b, "V16UcV16UcV16UcV16Uc", "nc", "lsx")
+TARGET_BUILTIN(__builtin_lsx_vshuf_b, "V16ScV16ScV16ScV16Sc", "nc", "lsx")
 
 TARGET_BUILTIN(__builtin_lsx_vshuf_h, "V8sV8sV8sV8s", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vshuf_w, "V4iV4iV4iV4i", "nc", "lsx")



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


[clang] [LoongArch][Clang] Make the parameters and return value of {x,}vshuf.b builtins `signed char` vectors (PR #114512)

2024-11-03 Thread Lu Weining via cfe-commits

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


[clang] [LoongArch][Clang] Make the parameters and return value of {x,}vshuf.b builtins `signed char` vectors (PR #114512)

2024-11-03 Thread Lu Weining via cfe-commits

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


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


[clang] [Clang] update reasoned delete diagnostic kind to use Extension, making it pedantic only (PR #114713)

2024-11-03 Thread Yanzuo Liu via cfe-commits

zwuis wrote:

I think we should make these changes to all backported features.

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -316,36 +287,169 @@ llvm::Error buildModuleFile(llvm::StringRef ModuleName,
   if (Clang->getDiagnostics().hasErrorOccurred())
 return llvm::createStringError("Compilation failed");
 
-  BuiltModuleFiles.addModuleFile(ModuleName, Inputs.CompileCommand.Output);
-  return llvm::Error::success();
+  return ModuleFile{ModuleName, Inputs.CompileCommand.Output};
+}
+
+bool ReusablePrerequisiteModules::canReuse(
+const CompilerInvocation &CI,
+llvm::IntrusiveRefCntPtr VFS) const {
+  if (RequiredModules.empty())
+return true;
+
+  SmallVector BMIPaths;
+  for (auto &MF : RequiredModules)
+BMIPaths.push_back(MF->ModuleFilePath);
+  return IsModuleFilesUpToDate(BMIPaths, *this, VFS);
 }
 } // namespace
 
+class ModulesBuilder::ModuleFileCache {
+public:
+  ModuleFileCache(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  llvm::Error
+  getOrBuildModuleFile(StringRef ModuleName, const ThreadsafeFS &TFS,
+   ProjectModules &MDB,
+   ReusablePrerequisiteModules &RequiredModules);
+  const GlobalCompilationDatabase &getCDB() const { return CDB; }
+
+private:
+  std::shared_ptr
+  getValidModuleFile(StringRef ModuleName, ProjectModules &MDB,
+ const ThreadsafeFS &TFS,
+ PrerequisiteModules &BuiltModuleFiles);
+
+  /// This should only be called by getValidModuleFile. This is unlocked 
version
+  /// of getValidModuleFile. The function is extracted to avoid dead locks when
+  /// recursing.
+  std::shared_ptr
+  isValidModuleFileUnlocked(StringRef ModuleName, ProjectModules &MDB,
+const ThreadsafeFS &TFS,
+PrerequisiteModules &BuiltModuleFiles);
+
+  const GlobalCompilationDatabase &CDB;
+
+  llvm::StringMap> ModuleFiles;
+  // Mutex to guard accesses to ModuleFiles.
+  std::mutex ModuleFilesMutex;
+};
+
+std::shared_ptr
+ModulesBuilder::ModuleFileCache::isValidModuleFileUnlocked(
+StringRef ModuleName, ProjectModules &MDB, const ThreadsafeFS &TFS,
+PrerequisiteModules &BuiltModuleFiles) {
+  auto Iter = ModuleFiles.find(ModuleName);
+  if (Iter != ModuleFiles.end()) {
+if (!IsModuleFileUpToDate(Iter->second->ModuleFilePath, BuiltModuleFiles,
+  TFS.view(std::nullopt))) {
+  log("Found not-up-date module file {0} for module {1} in cache",
+  Iter->second->ModuleFilePath, ModuleName);
+  ModuleFiles.erase(Iter);
+  return nullptr;
+}
+
+if (llvm::any_of(
+MDB.getRequiredModules(MDB.getSourceForModuleName(ModuleName)),
+[&MDB, &TFS, &BuiltModuleFiles, this](auto &&RequiredModuleName) {
+  return !isValidModuleFileUnlocked(RequiredModuleName, MDB, TFS,
+BuiltModuleFiles);
+})) {
+  ModuleFiles.erase(Iter);
+  return nullptr;
+}
+
+return Iter->second;
+  }
+
+  log("Don't find {0} in cache", ModuleName);
+
+  return nullptr;
+}
+
+std::shared_ptr 
ModulesBuilder::ModuleFileCache::getValidModuleFile(
+StringRef ModuleName, ProjectModules &MDB, const ThreadsafeFS &TFS,
+PrerequisiteModules &BuiltModuleFiles) {
+  std::lock_guard _(ModuleFilesMutex);
+
+  return isValidModuleFileUnlocked(ModuleName, MDB, TFS, BuiltModuleFiles);
+}
+
+llvm::Error ModulesBuilder::ModuleFileCache::getOrBuildModuleFile(

ChuanqiXu9 wrote:

I can understand your point as you wish the cache to be a cache only. And I 
feel good to leave the free function `buildModuleFile` as simple as possible so 
that it doesn't have to care about the cache.

To address both opinions, I tried to add `ModulesBuilderImpl` class to take the 
place of the previous ModuleFilesCache and the current ModuleFileCache is a 
cache only. I feel this is the neater solution.

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


[clang] [Clang] Consider outer instantiation scopes for constraint normalization (PR #114749)

2024-11-03 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 created 
https://github.com/llvm/llvm-project/pull/114749

We need to compare constraint expressions when instantiating a friend 
declaration that is lexically defined within a class template. Since the 
evaluation is deferred, the expression might refer to untransformed function 
parameters such that the substitution needs the mapping of instantiation.

These mappings are maintained by the function declaration instantiation, so we 
need to establish a "transparent" LocalInstantiationScope before substituting 
into the constraint.

No release note as this fixes a regression in 19.

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

>From a218508f38ebfc2e0ff19d08317fd3a13c3e8d36 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 4 Nov 2024 15:30:01 +0800
Subject: [PATCH] [Clang] Consider outer instantiation scopes for constraint
 normalization

We need to compare constraint expressions when instantiating a friend
declaration that is lexically defined within a class template. Since the
evaluation is deferred, the expression might refer to untransformed function
parameters such that the substitution needs the mapping of instantiation.

These mappings are maintained by the function declaration instantiation,
so we need to establish a "transparent" LocalInstantiationScope before
substituting into the constraint.
---
 clang/lib/Sema/SemaConcept.cpp   |  2 +-
 .../SemaTemplate/concepts-out-of-line-def.cpp| 16 
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/clang/lib/Sema/SemaConcept.cpp b/clang/lib/Sema/SemaConcept.cpp
index e36ee062213716..bc988001ea7e46 100644
--- a/clang/lib/Sema/SemaConcept.cpp
+++ b/clang/lib/Sema/SemaConcept.cpp
@@ -975,7 +975,7 @@ static const Expr 
*SubstituteConstraintExpressionWithoutSatisfaction(
   std::optional ScopeForParameters;
   if (const NamedDecl *ND = DeclInfo.getDecl();
   ND && ND->isFunctionOrFunctionTemplate()) {
-ScopeForParameters.emplace(S);
+ScopeForParameters.emplace(S, /*CombineWithOuterScope=*/true);
 const FunctionDecl *FD = ND->getAsFunction();
 for (auto *PVD : FD->parameters()) {
   if (!PVD->isParameterPack()) {
diff --git a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp 
b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
index fe8f74928fc370..dd518d283c83c8 100644
--- a/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
+++ b/clang/test/SemaTemplate/concepts-out-of-line-def.cpp
@@ -702,3 +702,19 @@ class TTP;
 C v;
 
 } // namespace GH93099
+
+namespace GH114685 {
+
+template  struct ptr {
+  template 
+  friend ptr make_item(auto &&args)
+requires(sizeof(args) > 1);
+};
+
+template 
+ptr make_item(auto &&args)
+  requires(sizeof(args) > 1) {}
+
+ptr p;
+
+} // namespace GH114685

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -482,6 +482,42 @@ void func() {
   EXPECT_EQ(Result.signatures[0].parameters[0].labelString, "int a");
 }
 
+TEST_F(PrerequisiteModulesTests, ReusablePrerequisiteModulesTest) {

ChuanqiXu9 wrote:

Done by appending a new test.

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits

ChuanqiXu9 wrote:

> thanks I think this LG in terms of module-builder interfaces, but I think we 
> can make some more changes to implementation to ensure it's easier to 
> maintain going forward.
> 
> speaking of maintenance, @HighCommander4 is definitely doing more of that 
> than me recently. so i'd like to make sure he's also ok with this new 
> complexity. i also would like to highlight @ChuanqiXu9 is definitely a 
> responsible member of community, hence i believe he'll also be around if we 
> have bug reports about this bits.

Thanks : )

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


[clang] [Clang] Implement labelled type filtering for overflow/truncation sanitizers w/ SSCLs (PR #107332)

2024-11-03 Thread Vitaly Buka via cfe-commits

vitalybuka wrote:

Thanks!

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


[clang] [Clang] Implement labelled type filtering for overflow/truncation sanitizers w/ SSCLs (PR #107332)

2024-11-03 Thread Vitaly Buka via cfe-commits

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


[clang] 3dd1d88 - [Clang] Implement labelled type filtering for overflow/truncation sanitizers w/ SSCLs (#107332)

2024-11-03 Thread via cfe-commits

Author: Justin Stitt
Date: 2024-11-03T23:57:47-08:00
New Revision: 3dd1d888fb18b40859504e207e57abdc6c43d838

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

LOG: [Clang] Implement labelled type filtering for overflow/truncation 
sanitizers w/ SSCLs (#107332)

[Related
RFC](https://discourse.llvm.org/t/rfc-support-globpattern-add-operator-to-invert-matches/80683/5?u=justinstitt)

### Summary

Implement type-based filtering via [Sanitizer Special Case
Lists](https://clang.llvm.org/docs/SanitizerSpecialCaseList.html) for
the arithmetic overflow and truncation sanitizers.

Currently, using the `type:` prefix with these sanitizers does nothing.
I've hooked up the SSCL parsing with Clang codegen so that we don't emit
the overflow/truncation checks if the arithmetic contains an ignored
type.

### Usefulness

You can craft ignorelists that ignore specific types that are expected
to overflow or wrap-around. For example, to ignore `my_type` from
`unsigned-integer-overflow` instrumentation:
```bash
$ cat ignorelist.txt
[unsigned-integer-overflow]
type:my_type=no_sanitize

$ cat foo.c
typedef unsigned long my_type;
void foo() {
  my_type a = ULONG_MAX;
  ++a;
}

$ clang foo.c -fsanitize=unsigned-integer-overflow 
-fsanitize-ignorelist=ignorelist.txt ; ./a.out
// --> no sanitizer error
```

If a type is functionally intended to overflow, like
[refcount_t](https://kernsec.org/wiki/index.php/Kernel_Protections/refcount_t)
and its associated APIs in the Linux kernel, then this type filtering
would prove useful for reducing sanitizer noise. Currently, the Linux
kernel dealt with this by
[littering](https://elixir.bootlin.com/linux/v6.10.8/source/include/linux/refcount.h#L139
) `__attribute__((no_sanitize("signed-integer-overflow")))` annotations
on all the `refcount_t` APIs. I think this serves as an example of how a
codebase could be made cleaner. We could make custom types that are
filtered out in an ignorelist, allowing for types to be more expressive
-- without the need for annotations. This accomplishes a similar goal to
https://github.com/llvm/llvm-project/pull/86618.


Yet another use case for this type filtering is whitelisting. We could
ignore _all_ types, save a few.

```bash
$ cat ignorelist.txt
[implicit-signed-integer-truncation]
type:*=no_sanitize # ignore literally all types
type:short=sanitize # except `short`

$ cat bar.c
// compile with -fsanitize=implicit-signed-integer-truncation
void bar(int toobig) {
  char a = toobig;  // not instrumented
  short b = toobig; // instrumented
}
```

### Other ways to accomplish the goal of sanitizer
allowlisting/whitelisting
* ignore list SSCL type support (this PR that you're reading)
* [my sanitize-allowlist
branch](https://github.com/llvm/llvm-project/compare/main...JustinStitt:llvm-project:sanitize-allowlist)
- this just implements a sibling flag `-fsanitize-allowlist=`, removing
some of the double negative logic present with `skip`/`ignore` when
trying to whitelist something.
* [Glob
Negation](https://discourse.llvm.org/t/rfc-support-globpattern-add-operator-to-invert-matches/80683)
- Implement a negation operator to the GlobPattern class so the
ignorelist query can use them to simulate allowlisting


Please let me know which of the three options we like best. They are not
necessarily mutually exclusive.

Here's [another related
PR](https://github.com/llvm/llvm-project/pull/86618) which implements a
`wraps` attribute. This can accomplish a similar goal to this PR but
requires in-source changes to codebases and also covers a wider variety
of integer definedness problems.

### CCs
@kees @vitalybuka @bwendling

-

Signed-off-by: Justin Stitt 

Added: 
clang/test/CodeGen/ubsan-type-ignorelist-category-2.test
clang/test/CodeGen/ubsan-type-ignorelist-category.test

Modified: 
clang/docs/ReleaseNotes.rst
clang/docs/SanitizerSpecialCaseList.rst
clang/include/clang/AST/ASTContext.h
clang/lib/AST/ASTContext.cpp
clang/lib/CodeGen/CGExprScalar.cpp

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1372e49dfac03c..a8e2e5c1e045ce 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -871,6 +871,14 @@ Sanitizers
   This new flag should allow those projects to enable integer sanitizers with
   less noise.
 
+- Arithmetic overflow sanitizers ``-fsanitize=signed-integer-overflow`` and
+  ``-fsanitize=unsigned-integer-overflow`` as well as the implicit integer
+  truncation sanitizers ``-fsanitize=implicit-signed-integer-truncation`` and
+  ``-fsanitize=implicit-unsigned-integer-truncation`` now properly support the
+  "type" prefix within `Sanitizer Special Case Lists (SSCL)
+  `_. See that link
+  for

[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2024-11-03 Thread Chris Copeland via cfe-commits

chrisnc wrote:

I've updated this PR to remove the aforementioned `clang` warning for this 
case, and I've updated all `clang` and `llvm` tests that were implicitly using 
the soft-float ABI despite requesting hard-float. In some cases, explicitly 
testing hard-float seemed to be intended because there was a corresponding line 
for the soft-float version, so I added a feature or CPU selection that 
accomplishes this. In other cases, the hard-float-ness of the test did not seem 
relevant, so I just switched those to soft-float. I attempted to write a test 
case for the new LLVM error, but I'm struggling with having a `lit` test that 
tolerates `llc` exiting with a nonzero exit code, even if I can get the `CHECK` 
directives to match. Any pointers on this would be appreciated.

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


[clang] [llvm] [ARM] Emit an error when the hard-float ABI is enabled but can't be used. (PR #111334)

2024-11-03 Thread Chris Copeland via cfe-commits

https://github.com/chrisnc updated 
https://github.com/llvm/llvm-project/pull/111334

>From 5e916c3c4d2579318fa990eca178f4cfd4ab35b0 Mon Sep 17 00:00:00 2001
From: Chris Copeland 
Date: Sun, 6 Oct 2024 20:27:48 -0700
Subject: [PATCH] [ARM] Emit an error when the hard-float ABI is enabled but
 can't be used.

Currently, compiling for an eabihf target with a CPU lacking
floating-point registers will silently use the soft-float ABI instead,
even though the Arm attributes section still has Tag_ABI_VFP_args: VFP
registers, which leads to silent ABI mismatches at link time.

Update all ARM tests that were using an affected combination to enable
the necessary FPU features or use a soft-float ABI.

[clang] Remove the warning from clang that detected this case only if
-mfloat-abi=hard or -mhard-float were specified explicitly.

Fixes #110383.
---
 .../clang/Basic/DiagnosticDriverKinds.td  |  3 ---
 clang/lib/Driver/ToolChains/Arch/ARM.cpp  | 18 --
 clang/test/Driver/arm-float-abi-lto.c |  4 ++--
 clang/test/Driver/arm-no-float-regs.c | 22 -
 llvm/lib/Target/ARM/ARMTargetMachine.cpp  |  6 -
 .../2013-04-05-Small-ByVal-Structs-PR15293.ll |  2 +-
 .../ARM/2013-05-13-AAPCS-byval-padding.ll |  2 +-
 .../ARM/2013-05-13-AAPCS-byval-padding2.ll|  2 +-
 .../2014-02-21-byval-reg-split-alignment.ll   |  2 +-
 llvm/test/CodeGen/ARM/arm-eabi.ll | 24 +--
 llvm/test/CodeGen/ARM/block-order.mir |  4 ++--
 llvm/test/CodeGen/ARM/constantpool-promote.ll | 24 +--
 llvm/test/CodeGen/ARM/fp16-promote.ll |  7 +++---
 llvm/test/CodeGen/ARM/macho-extern-hidden.ll  |  2 +-
 llvm/test/CodeGen/ARM/memfunc.ll  |  6 ++---
 .../ARM/no-expand-memcpy-no-builtins.ll   |  2 +-
 llvm/test/CodeGen/ARM/readtp.ll   | 16 ++---
 llvm/test/CodeGen/ARM/subtarget-align.ll  |  6 ++---
 llvm/test/CodeGen/Thumb2/emit-unwinding.ll|  2 +-
 .../ARM/dbgcallsite-noreg-is-imm-check.mir|  4 ++--
 20 files changed, 59 insertions(+), 99 deletions(-)
 delete mode 100644 clang/test/Driver/arm-no-float-regs.c

diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index cdfdaa01fb121d..e5103cb7a5bebc 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -459,9 +459,6 @@ def warn_drv_assuming_mfloat_abi_is : Warning<
 def warn_drv_unsupported_float_abi_by_lib : Warning<
   "float ABI '%0' is not supported by current library">,
   InGroup;
-def warn_drv_no_floating_point_registers: Warning<
-  "'%0': selected processor lacks floating point registers">,
-  InGroup;
 def warn_ignoring_ftabstop_value : Warning<
   "ignoring invalid -ftabstop value '%0', using default value %1">;
 def warn_drv_overriding_option : Warning<
diff --git a/clang/lib/Driver/ToolChains/Arch/ARM.cpp 
b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
index 0489911ecd9dee..f597d67eb1c89c 100644
--- a/clang/lib/Driver/ToolChains/Arch/ARM.cpp
+++ b/clang/lib/Driver/ToolChains/Arch/ARM.cpp
@@ -158,22 +158,6 @@ static void checkARMCPUName(const Driver &D, const Arg *A, 
const ArgList &Args,
 << A->getSpelling() << A->getValue();
 }
 
-// If -mfloat-abi=hard or -mhard-float are specified explicitly then check that
-// floating point registers are available on the target CPU.
-static void checkARMFloatABI(const Driver &D, const ArgList &Args,
- bool HasFPRegs) {
-  if (HasFPRegs)
-return;
-  const Arg *A =
-  Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
-  options::OPT_mfloat_abi_EQ);
-  if (A && (A->getOption().matches(options::OPT_mhard_float) ||
-(A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
- A->getValue() == StringRef("hard"
-D.Diag(clang::diag::warn_drv_no_floating_point_registers)
-<< A->getAsString(Args);
-}
-
 bool arm::useAAPCSForMachO(const llvm::Triple &T) {
   // The backend is hardwired to assume AAPCS for M-class processors, ensure
   // the frontend matches that.
@@ -985,8 +969,6 @@ llvm::ARM::FPUKind arm::getARMTargetFeatures(const Driver 
&D,
   if (Args.getLastArg(options::OPT_mno_bti_at_return_twice))
 Features.push_back("+no-bti-at-return-twice");
 
-  checkARMFloatABI(D, Args, HasFPRegs);
-
   return FPUKind;
 }
 
diff --git a/clang/test/Driver/arm-float-abi-lto.c 
b/clang/test/Driver/arm-float-abi-lto.c
index 83c2435d97a4d2..0a5a6cebf97e45 100644
--- a/clang/test/Driver/arm-float-abi-lto.c
+++ b/clang/test/Driver/arm-float-abi-lto.c
@@ -4,7 +4,7 @@
 
 // RUN: %clang --target=arm-none-eabi -mcpu=cortex-m33 -mfloat-abi=hard -O1 %s 
-flto=full -c -o %t.call_full.bc -DCALL_LIB
 // RUN: %clang --target=arm-none-eabi -mcpu=cortex-m33 -mfloat-abi=hard -O1 %s 
-flto=full -c -o %t.define_full.bc -DDEFINE_LIB
-// RUN: llvm-lto2 run -o %t.lto_full -save-temps %t.ca

[clang] dc45ff1 - [PassBuilder] Add `ThinOrFullLTOPhase` to early simplication EP call backs (#114547)

2024-11-03 Thread via cfe-commits

Author: Shilei Tian
Date: 2024-11-03T23:24:10-05:00
New Revision: dc45ff1d2a01ff68326c6444dba683cf66d80651

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

LOG: [PassBuilder] Add `ThinOrFullLTOPhase` to early simplication EP call backs 
(#114547)

The early simplication pipeline is used in non-LTO and (Thin/Full)LTO
pre-link
stage. There are some passes that we want them in non-LTO mode, but not
at LTO
pre-link stage. The control is missing currently. This PR adds the
support. To
demonstrate the use, we only enable the internalization pass in non-LTO
mode for
AMDGPU because having it run in pre-link stage causes some issues.

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
llvm/include/llvm/Passes/PassBuilder.h
llvm/lib/Passes/PassBuilderPipelines.cpp
llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
llvm/lib/Target/BPF/BPFTargetMachine.cpp
llvm/test/CodeGen/AMDGPU/print-pipeline-passes.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index ae33554a66b6b5..47a30f00612eb7 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -993,7 +993,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
   });
   PB.registerPipelineEarlySimplificationEPCallback(
-  [](ModulePassManager &MPM, OptimizationLevel Level) {
+  [](ModulePassManager &MPM, OptimizationLevel Level,
+ ThinOrFullLTOPhase) {
 if (Level != OptimizationLevel::O0)
   MPM.addPass(ObjCARCAPElimPass());
   });

diff  --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 0ebfdbb7865fdd..565fd2ab2147e5 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -480,7 +480,8 @@ class PassBuilder {
   /// This extension point allows adding optimization right after passes that 
do
   /// basic simplification of the input IR.
   void registerPipelineEarlySimplificationEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 PipelineEarlySimplificationEPCallbacks.push_back(C);
   }
 
@@ -639,7 +640,8 @@ class PassBuilder {
   void invokePipelineStartEPCallbacks(ModulePassManager &MPM,
   OptimizationLevel Level);
   void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM,
-OptimizationLevel Level);
+OptimizationLevel Level,
+ThinOrFullLTOPhase Phase);
 
   static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
 if (!Name.consume_front(PassName))
@@ -764,7 +766,9 @@ class PassBuilder {
   FullLinkTimeOptimizationLastEPCallbacks;
   SmallVector, 2>
   PipelineStartEPCallbacks;
-  SmallVector, 2>
+  SmallVector,
+  2>
   PipelineEarlySimplificationEPCallbacks;
 
   SmallVector, 2>

diff  --git a/llvm/lib/Passes/PassBuilderPipelines.cpp 
b/llvm/lib/Passes/PassBuilderPipelines.cpp
index 466fbcd7bb7703..9c90accd9c376b 100644
--- a/llvm/lib/Passes/PassBuilderPipelines.cpp
+++ b/llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -384,9 +384,9 @@ void 
PassBuilder::invokePipelineStartEPCallbacks(ModulePassManager &MPM,
 C(MPM, Level);
 }
 void PassBuilder::invokePipelineEarlySimplificationEPCallbacks(
-ModulePassManager &MPM, OptimizationLevel Level) {
+ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase) 
{
   for (auto &C : PipelineEarlySimplificationEPCallbacks)
-C(MPM, Level);
+C(MPM, Level, Phase);
 }
 
 // Helper to add AnnotationRemarksPass.
@@ -1140,7 +1140,7 @@ 
PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr,
lowertypetests::DropTestKind::Assume));
 
-  invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
+  invokePipelineEarlySimplificationEPCallbacks(MPM, Level, Phase);
 
   // Interprocedural constant propagation now that basic cleanup has occurred
   // and prior to optimizing globals.
@@ -2153,7 +2153,7 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel 
Level,
   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
 
-  invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
+  invokePipelineEarlySimplificationEPCallbacks(MPM, Level, Phase);
 
   // Build a minimal pipeline based on the semantics required by LLVM,
   // which is just that always inl

[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (PR #114577)

2024-11-03 Thread Shilei Tian via cfe-commits

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


[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to early simplication EP call backs (PR #114547)

2024-11-03 Thread Shilei Tian via cfe-commits

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


[clang] 390300d - [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (#114577)

2024-11-03 Thread via cfe-commits

Author: Shilei Tian
Date: 2024-11-03T23:25:29-05:00
New Revision: 390300d9f41df6ad71f0f4196ef4885d4bd5dc48

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

LOG: [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (#114577)

Added: 


Modified: 
clang/lib/CodeGen/BackendUtil.cpp
llvm/include/llvm/Passes/PassBuilder.h
llvm/lib/Passes/PassBuilderPipelines.cpp
llvm/lib/Target/AMDGPU/AMDGPUTargetMachine.cpp
llvm/test/CodeGen/AMDGPU/print-pipeline-passes.ll
llvm/tools/opt/NewPMDriver.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 47a30f00612eb7..70035a5e069a90 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -674,7 +674,7 @@ static void addKCFIPass(const Triple &TargetTriple, const 
LangOptions &LangOpts,
 
   // Ensure we lower KCFI operand bundles with -O0.
   PB.registerOptimizerLastEPCallback(
-  [&](ModulePassManager &MPM, OptimizationLevel Level) {
+  [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) 
{
 if (Level == OptimizationLevel::O0 &&
 LangOpts.Sanitize.has(SanitizerKind::KCFI))
   MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
@@ -693,8 +693,8 @@ static void addKCFIPass(const Triple &TargetTriple, const 
LangOptions &LangOpts,
 static void addSanitizers(const Triple &TargetTriple,
   const CodeGenOptions &CodeGenOpts,
   const LangOptions &LangOpts, PassBuilder &PB) {
-  auto SanitizersCallback = [&](ModulePassManager &MPM,
-OptimizationLevel Level) {
+  auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel 
Level,
+ThinOrFullLTOPhase) {
 if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(SanitizerCoveragePass(
@@ -778,9 +778,10 @@ static void addSanitizers(const Triple &TargetTriple,
   };
   if (ClSanitizeOnOptimizerEarlyEP) {
 PB.registerOptimizerEarlyEPCallback(
-[SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
+[SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
+ ThinOrFullLTOPhase Phase) {
   ModulePassManager NewMPM;
-  SanitizersCallback(NewMPM, Level);
+  SanitizersCallback(NewMPM, Level, Phase);
   if (!NewMPM.isEmpty()) {
 // Sanitizers can abandon.
 NewMPM.addPass(RequireAnalysisPass());
@@ -1058,11 +1059,12 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
 // the PGOOptions, and set this up there.
 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
-  PB.registerOptimizerLastEPCallback(
-  [](ModulePassManager &MPM, OptimizationLevel Level) {
-MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
-MPM.addPass(ModuleMemProfilerPass());
-  });
+  PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
+OptimizationLevel Level,
+ThinOrFullLTOPhase) {
+MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
+MPM.addPass(ModuleMemProfilerPass());
+  });
 }
 
 if (CodeGenOpts.FatLTO) {

diff  --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 565fd2ab2147e5..e7bc3a58f414f1 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -490,7 +490,8 @@ class PassBuilder {
   /// This extension point allows adding optimizations before the function
   /// optimization pipeline.
   void registerOptimizerEarlyEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 OptimizerEarlyEPCallbacks.push_back(C);
   }
 
@@ -499,7 +500,8 @@ class PassBuilder {
   /// This extension point allows adding optimizations at the very end of the
   /// function optimization pipeline.
   void registerOptimizerLastEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 OptimizerLastEPCallbacks.push_back(C);
   }
 
@@ -630,9 +632,11 @@ class PassBuilder {
   void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM,
 OptimizationLevel Level);
   void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM,
-   OptimizationLevel Level);
+   OptimizationLevel Level,
+   ThinOrFullLTOPha

[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (PR #114577)

2024-11-03 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/114577

>From 76d44f744fc9b859e4ffe151c8c71d0e16d8eb39 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Fri, 1 Nov 2024 12:39:52 -0400
Subject: [PATCH] [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline

---
 clang/lib/CodeGen/BackendUtil.cpp | 22 +
 llvm/include/llvm/Passes/PassBuilder.h| 20 +++-
 llvm/lib/Passes/PassBuilderPipelines.cpp  | 24 +++
 .../lib/Target/AMDGPU/AMDGPUTargetMachine.cpp | 23 +++---
 .../CodeGen/AMDGPU/print-pipeline-passes.ll   |  1 +
 llvm/tools/opt/NewPMDriver.cpp|  4 ++--
 6 files changed, 57 insertions(+), 37 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 47a30f00612eb7..70035a5e069a90 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -674,7 +674,7 @@ static void addKCFIPass(const Triple &TargetTriple, const 
LangOptions &LangOpts,
 
   // Ensure we lower KCFI operand bundles with -O0.
   PB.registerOptimizerLastEPCallback(
-  [&](ModulePassManager &MPM, OptimizationLevel Level) {
+  [&](ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase) 
{
 if (Level == OptimizationLevel::O0 &&
 LangOpts.Sanitize.has(SanitizerKind::KCFI))
   MPM.addPass(createModuleToFunctionPassAdaptor(KCFIPass()));
@@ -693,8 +693,8 @@ static void addKCFIPass(const Triple &TargetTriple, const 
LangOptions &LangOpts,
 static void addSanitizers(const Triple &TargetTriple,
   const CodeGenOptions &CodeGenOpts,
   const LangOptions &LangOpts, PassBuilder &PB) {
-  auto SanitizersCallback = [&](ModulePassManager &MPM,
-OptimizationLevel Level) {
+  auto SanitizersCallback = [&](ModulePassManager &MPM, OptimizationLevel 
Level,
+ThinOrFullLTOPhase) {
 if (CodeGenOpts.hasSanitizeCoverage()) {
   auto SancovOpts = getSancovOptsFromCGOpts(CodeGenOpts);
   MPM.addPass(SanitizerCoveragePass(
@@ -778,9 +778,10 @@ static void addSanitizers(const Triple &TargetTriple,
   };
   if (ClSanitizeOnOptimizerEarlyEP) {
 PB.registerOptimizerEarlyEPCallback(
-[SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level) {
+[SanitizersCallback](ModulePassManager &MPM, OptimizationLevel Level,
+ ThinOrFullLTOPhase Phase) {
   ModulePassManager NewMPM;
-  SanitizersCallback(NewMPM, Level);
+  SanitizersCallback(NewMPM, Level, Phase);
   if (!NewMPM.isEmpty()) {
 // Sanitizers can abandon.
 NewMPM.addPass(RequireAnalysisPass());
@@ -1058,11 +1059,12 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 // TODO: Consider passing the MemoryProfileOutput to the pass builder via
 // the PGOOptions, and set this up there.
 if (!CodeGenOpts.MemoryProfileOutput.empty()) {
-  PB.registerOptimizerLastEPCallback(
-  [](ModulePassManager &MPM, OptimizationLevel Level) {
-MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
-MPM.addPass(ModuleMemProfilerPass());
-  });
+  PB.registerOptimizerLastEPCallback([](ModulePassManager &MPM,
+OptimizationLevel Level,
+ThinOrFullLTOPhase) {
+MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass()));
+MPM.addPass(ModuleMemProfilerPass());
+  });
 }
 
 if (CodeGenOpts.FatLTO) {
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 565fd2ab2147e5..e7bc3a58f414f1 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -490,7 +490,8 @@ class PassBuilder {
   /// This extension point allows adding optimizations before the function
   /// optimization pipeline.
   void registerOptimizerEarlyEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 OptimizerEarlyEPCallbacks.push_back(C);
   }
 
@@ -499,7 +500,8 @@ class PassBuilder {
   /// This extension point allows adding optimizations at the very end of the
   /// function optimization pipeline.
   void registerOptimizerLastEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 OptimizerLastEPCallbacks.push_back(C);
   }
 
@@ -630,9 +632,11 @@ class PassBuilder {
   void invokeVectorizerStartEPCallbacks(FunctionPassManager &FPM,
 OptimizationLevel Level);
   void invokeOptimizerEarlyEPCallbacks(ModulePassManager &MPM,
-   OptimizationLevel Level);
+   OptimizationLevel Level,
+   ThinOrFullLTOPhase Phase);
   void invo

[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (PR #114577)

2024-11-03 Thread Shilei Tian via cfe-commits

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


[clang] [llvm] [BPF] Add load-acquire and store-release instructions under -mcpu=v4 (PR #108636)

2024-11-03 Thread via cfe-commits

yonghong-song wrote:

> Sure Yonghong, I can include that in this PR. Similarly, since we cannot have 
> both `relaxed_load` and 
> `relaxed_load`, I'll keep it `zext` (`BPF_MEM` | 
> `BPF_LDX`) for now. For example:
> 
> ```c
> int foo(char *ptr) {
> return __atomic_load_n(ptr, __ATOMIC_RELAXED);
> }
> ```
> 
> This'll be compiled into:
> 
> ```
>  :
>0: 71 11 00 00 00 00 00 00 w1 = *(u8 *)(r1 + 0x0)
>1: bc 10 08 00 00 00 00 00 w0 = (s8)w1
>2: 95 00 00 00 00 00 00 00 exit
> ```

Okay, LGTM. Thanks!

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


[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -691,7 +691,7 @@ ensure it is reachable, e.g. ``using N::g;``.
 Support for Reduced BMIs is still experimental, but it may become the default
 in the future. The expected roadmap for Reduced BMIs as of Clang 19.x is:

ChuanqiXu9 wrote:

I looked up the dictionary and it says "as of" means "from". So I feel the 
wording is good since it was added in 19.

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


[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to early simplication EP call backs (PR #114547)

2024-11-03 Thread Shilei Tian via cfe-commits

https://github.com/shiltian updated 
https://github.com/llvm/llvm-project/pull/114547

>From 3da52a072583f835b69694b9649ccc66986cd346 Mon Sep 17 00:00:00 2001
From: Shilei Tian 
Date: Fri, 1 Nov 2024 10:51:20 -0400
Subject: [PATCH] [PassBuilder] Add `LTOPreLink` to early simplication EP call
 backs

The early simplication pipeline is used in non-LTO and (Thin/Full)LTO pre-link
stage. There are some passes that we want them in non-LTO mode, but not at LTO
pre-link stage. The control is missing currently. This PR adds the support. To
demonstrate the use, we only enable the internalization pass in non-LTO mode for
AMDGPU because having it run in pre-link stage causes some issues.
---
 clang/lib/CodeGen/BackendUtil.cpp |  3 ++-
 llvm/include/llvm/Passes/PassBuilder.h| 10 +++---
 llvm/lib/Passes/PassBuilderPipelines.cpp  |  8 
 .../lib/Target/AMDGPU/AMDGPUTargetMachine.cpp | 19 +++
 llvm/lib/Target/BPF/BPFTargetMachine.cpp  |  2 +-
 .../CodeGen/AMDGPU/print-pipeline-passes.ll   |  8 
 llvm/tools/opt/NewPMDriver.cpp|  2 +-
 7 files changed, 38 insertions(+), 14 deletions(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index ae33554a66b6b5..47a30f00612eb7 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -993,7 +993,8 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
   createModuleToFunctionPassAdaptor(ObjCARCExpandPass()));
   });
   PB.registerPipelineEarlySimplificationEPCallback(
-  [](ModulePassManager &MPM, OptimizationLevel Level) {
+  [](ModulePassManager &MPM, OptimizationLevel Level,
+ ThinOrFullLTOPhase) {
 if (Level != OptimizationLevel::O0)
   MPM.addPass(ObjCARCAPElimPass());
   });
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 0ebfdbb7865fdd..565fd2ab2147e5 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -480,7 +480,8 @@ class PassBuilder {
   /// This extension point allows adding optimization right after passes that 
do
   /// basic simplification of the input IR.
   void registerPipelineEarlySimplificationEPCallback(
-  const std::function &C) {
+  const std::function &C) {
 PipelineEarlySimplificationEPCallbacks.push_back(C);
   }
 
@@ -639,7 +640,8 @@ class PassBuilder {
   void invokePipelineStartEPCallbacks(ModulePassManager &MPM,
   OptimizationLevel Level);
   void invokePipelineEarlySimplificationEPCallbacks(ModulePassManager &MPM,
-OptimizationLevel Level);
+OptimizationLevel Level,
+ThinOrFullLTOPhase Phase);
 
   static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
 if (!Name.consume_front(PassName))
@@ -764,7 +766,9 @@ class PassBuilder {
   FullLinkTimeOptimizationLastEPCallbacks;
   SmallVector, 2>
   PipelineStartEPCallbacks;
-  SmallVector, 2>
+  SmallVector,
+  2>
   PipelineEarlySimplificationEPCallbacks;
 
   SmallVector, 2>
diff --git a/llvm/lib/Passes/PassBuilderPipelines.cpp 
b/llvm/lib/Passes/PassBuilderPipelines.cpp
index 466fbcd7bb7703..9c90accd9c376b 100644
--- a/llvm/lib/Passes/PassBuilderPipelines.cpp
+++ b/llvm/lib/Passes/PassBuilderPipelines.cpp
@@ -384,9 +384,9 @@ void 
PassBuilder::invokePipelineStartEPCallbacks(ModulePassManager &MPM,
 C(MPM, Level);
 }
 void PassBuilder::invokePipelineEarlySimplificationEPCallbacks(
-ModulePassManager &MPM, OptimizationLevel Level) {
+ModulePassManager &MPM, OptimizationLevel Level, ThinOrFullLTOPhase Phase) 
{
   for (auto &C : PipelineEarlySimplificationEPCallbacks)
-C(MPM, Level);
+C(MPM, Level, Phase);
 }
 
 // Helper to add AnnotationRemarksPass.
@@ -1140,7 +1140,7 @@ 
PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr,
lowertypetests::DropTestKind::Assume));
 
-  invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
+  invokePipelineEarlySimplificationEPCallbacks(MPM, Level, Phase);
 
   // Interprocedural constant propagation now that basic cleanup has occurred
   // and prior to optimizing globals.
@@ -2153,7 +2153,7 @@ PassBuilder::buildO0DefaultPipeline(OptimizationLevel 
Level,
   if (PGOOpt && PGOOpt->DebugInfoForProfiling)
 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass()));
 
-  invokePipelineEarlySimplificationEPCallbacks(MPM, Level);
+  invokePipelineEarlySimplificationEPCallbacks(MPM, Level, Phase);
 
   // Build a minimal pipeline based on the semantics required by LLVM,
   // which is just that always inlining occurs. Further, disable generating
diff --

[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

https://github.com/goldsteinn updated 
https://github.com/llvm/llvm-project/pull/112792

>From 802764e879862541e205ba1a070824b71d2fef9a Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 17 Oct 2024 17:31:24 -0500
Subject: [PATCH 1/4] [emacs][clang-format] Add elisp API for clang-format on
 git diffs

New proposed function `clang-format-git-diffs`.

It is the same as calling `clang-format-region` on all diffs between
the content of a buffer-file and the content of the file at git
revision HEAD. This is essentially the same thing as:
`git-clang-format -f {filename}`
If the current buffer is saved.

The motivation is many project (LLVM included) both have code that is
non-compliant with there clang-format style and disallow unrelated
format diffs in PRs. This means users can't just run
`clang-format-buffer` on the buffer they are working on, and need to
manually go through all the regions by hand to get them
formatted. This is both an error prone and annoying workflow.
---
 clang/tools/clang-format/clang-format.el | 159 ---
 1 file changed, 144 insertions(+), 15 deletions(-)

diff --git a/clang/tools/clang-format/clang-format.el 
b/clang/tools/clang-format/clang-format.el
index fb943b7b722f8a..d3f874de41c550 100644
--- a/clang/tools/clang-format/clang-format.el
+++ b/clang/tools/clang-format/clang-format.el
@@ -146,18 +146,97 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--git-diffs-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Printout changes as only the line groups.
+   "--changed-group-format=--lines=%dF:%dL "
+   ;; Ignore unchanged content.
+   "--unchanged-group-format="
+   file-orig
+   file-new
+   )
+  )
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position)
+  (when (stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+  (unless (= status 0)
+(unless (= status 1)
+  (error "(diff returned unsuccessfully %s%s)" status stderr)))
+
+
+  (if (= status 0)
+  ;; Status == 0 -> no Diff.
+  nil
+(progn
+  ;; Split "--lines=:... --lines=:" output to
+  ;; a list for return.
+  (s-split
+   " "
+   (string-trim
+(buffer-substring-no-properties
+ (point-min) (point-max)
+
+(defun clang-format--git-diffs-get-git-head-file ()
+  "Returns a temporary file with the content of 'buffer-file-name' at
+git revision HEAD. If the current buffer is either not a file or not
+in a git repo, this results in an error"
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Need to be able to find version control (git) root
+  (unless (vc-root-dir)
+(error "File not known to git"))
+  ;; Need version control to in fact be git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")
+(error "Not using git"))
+
+  (let ((tmpfile-git-head (make-temp-file 
"clang-format-tmp-git-head-content")))
+;; Get filename relative to git root
+(let ((git-file-name (substring
+  (expand-file-name (buffer-file-name))
+  (string-width (expand-file-name (vc-root-dir)))
+  nil)))
+  (let ((status (call-process
+ "git"
+ nil
+ `(:file, tmpfile-git-head)
+ nil
+ "show" (concat "HEAD:" git-file-name)

[clang] [CIR] Call code gen; create empty cir.func op (PR #113483)

2024-11-03 Thread Eli Friedman via cfe-commits


@@ -24,9 +27,140 @@ CIRGenModule::CIRGenModule(mlir::MLIRContext &context,
clang::ASTContext &astctx,
const clang::CodeGenOptions &cgo,
DiagnosticsEngine &diags)
-: astCtx(astctx), langOpts(astctx.getLangOpts()),
-  theModule{mlir::ModuleOp::create(mlir::UnknownLoc())},
-  target(astCtx.getTargetInfo()) {}
+: builder(&context), astCtx(astctx), langOpts(astctx.getLangOpts()),
+  theModule{mlir::ModuleOp::create(mlir::UnknownLoc::get(&context))},
+  diags(diags), target(astCtx.getTargetInfo()) {}
+
+mlir::Location CIRGenModule::getLoc(SourceLocation cLoc) {
+  assert(cLoc.isValid() && "expected valid source location");
+  const SourceManager &sm = astCtx.getSourceManager();
+  PresumedLoc pLoc = sm.getPresumedLoc(cLoc);
+  StringRef filename = pLoc.getFilename();
+  return mlir::FileLineColLoc::get(builder.getStringAttr(filename),
+   pLoc.getLine(), pLoc.getColumn());
+}

efriedma-quic wrote:

If you ever want to generate diagnostics from CIR, you probably want to just 
use the clang SourceLocation directly, not try to translate it to an MLIR 
"Location".  It's extremely complicated to describe a location when macros are 
involved, and the abstraction clang uses really only makes sense for C 
preprocessor.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process

ideasman42 wrote:

Ah, I wasn't aware of that, even so, there is some advantage in using emacs 
diff functionality as it handles error cases, removing temp files etc.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,118 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; We are matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff ‘nil’ is returned. Otherwise the
+return is a ‘list’ of lines in the format ‘--lines=:’
+which can be passed directly to ‘clang-format’."
+  ;; Use temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"

ideasman42 wrote:

While I think it may be best to call `diff` functions directly, if this is call 
is kept, it's probably best to use `diff-command`, so the diff command used by 
`vc/diff.el` is used here, it may be necessary on WIN32.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/106683

>From 15aa6af1f5d22e4b837e8e2fd49469310ffbe7f1 Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Fri, 30 Aug 2024 15:11:07 +0800
Subject: [PATCH 1/3] [clangd] [Modules] Support Reusable Modules Builder

---
 clang-tools-extra/clangd/ModulesBuilder.cpp   | 375 ++
 clang-tools-extra/clangd/ModulesBuilder.h |   8 +-
 .../unittests/PrerequisiteModulesTest.cpp |  36 ++
 3 files changed, 344 insertions(+), 75 deletions(-)

diff --git a/clang-tools-extra/clangd/ModulesBuilder.cpp 
b/clang-tools-extra/clangd/ModulesBuilder.cpp
index 97f67ddf5495a2..c4fb3d4010d370 100644
--- a/clang-tools-extra/clangd/ModulesBuilder.cpp
+++ b/clang-tools-extra/clangd/ModulesBuilder.cpp
@@ -13,6 +13,7 @@
 #include "clang/Frontend/FrontendActions.h"
 #include "clang/Serialization/ASTReader.h"
 #include "clang/Serialization/InMemoryModuleCache.h"
+#include "llvm/ADT/ScopeExit.h"
 
 namespace clang {
 namespace clangd {
@@ -192,33 +193,27 @@ bool IsModuleFilesUpToDate(
   });
 }
 
-// StandalonePrerequisiteModules - stands for PrerequisiteModules for which all
+// ReusablePrerequisiteModules - stands for PrerequisiteModules for which all
 // the required modules are built successfully. All the module files
-// are owned by the StandalonePrerequisiteModules class.
-//
-// Any of the built module files won't be shared with other instances of the
-// class. So that we can avoid worrying thread safety.
-//
-// We don't need to worry about duplicated module names here since the standard
-// guarantees the module names should be unique to a program.
-class StandalonePrerequisiteModules : public PrerequisiteModules {
+// are owned by the modules builder.
+class ReusablePrerequisiteModules : public PrerequisiteModules {
 public:
-  StandalonePrerequisiteModules() = default;
+  ReusablePrerequisiteModules() = default;
 
-  StandalonePrerequisiteModules(const StandalonePrerequisiteModules &) = 
delete;
-  StandalonePrerequisiteModules
-  operator=(const StandalonePrerequisiteModules &) = delete;
-  StandalonePrerequisiteModules(StandalonePrerequisiteModules &&) = delete;
-  StandalonePrerequisiteModules
-  operator=(StandalonePrerequisiteModules &&) = delete;
+  ReusablePrerequisiteModules(const ReusablePrerequisiteModules &) = delete;
+  ReusablePrerequisiteModules
+  operator=(const ReusablePrerequisiteModules &) = delete;
+  ReusablePrerequisiteModules(ReusablePrerequisiteModules &&) = delete;
+  ReusablePrerequisiteModules
+  operator=(ReusablePrerequisiteModules &&) = delete;
 
-  ~StandalonePrerequisiteModules() override = default;
+  ~ReusablePrerequisiteModules() override = default;
 
   void adjustHeaderSearchOptions(HeaderSearchOptions &Options) const override {
 // Appending all built module files.
 for (auto &RequiredModule : RequiredModules)
   Options.PrebuiltModuleFiles.insert_or_assign(
-  RequiredModule.ModuleName, RequiredModule.ModuleFilePath);
+  RequiredModule->ModuleName, RequiredModule->ModuleFilePath);
   }
 
   bool canReuse(const CompilerInvocation &CI,
@@ -228,54 +223,30 @@ class StandalonePrerequisiteModules : public 
PrerequisiteModules {
 return BuiltModuleNames.contains(ModuleName);
   }
 
-  void addModuleFile(llvm::StringRef ModuleName,
- llvm::StringRef ModuleFilePath) {
-RequiredModules.emplace_back(ModuleName, ModuleFilePath);
-BuiltModuleNames.insert(ModuleName);
+  void addModuleFile(std::shared_ptr BMI) {
+BuiltModuleNames.insert(BMI->ModuleName);
+RequiredModules.emplace_back(std::move(BMI));
   }
 
 private:
-  llvm::SmallVector RequiredModules;
+  mutable llvm::SmallVector, 8> RequiredModules;
   // A helper class to speedup the query if a module is built.
   llvm::StringSet<> BuiltModuleNames;
 };
 
-// Build a module file for module with `ModuleName`. The information of built
-// module file are stored in \param BuiltModuleFiles.
-llvm::Error buildModuleFile(llvm::StringRef ModuleName,
-const GlobalCompilationDatabase &CDB,
-const ThreadsafeFS &TFS, ProjectModules &MDB,
-PathRef ModuleFilesPrefix,
-StandalonePrerequisiteModules &BuiltModuleFiles) {
-  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
-return llvm::Error::success();
-
-  PathRef ModuleUnitFileName = MDB.getSourceForModuleName(ModuleName);
-  // It is possible that we're meeting third party modules (modules whose
-  // source are not in the project. e.g, the std module may be a third-party
-  // module for most projects) or something wrong with the implementation of
-  // ProjectModules.
-  // FIXME: How should we treat third party modules here? If we want to ignore
-  // third party modules, we should return true instead of false here.
-  // Currently we simply bail out.
-  if (ModuleUnitFileName.empty())
-return llvm::createStringErro

[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -316,36 +287,169 @@ llvm::Error buildModuleFile(llvm::StringRef ModuleName,
   if (Clang->getDiagnostics().hasErrorOccurred())
 return llvm::createStringError("Compilation failed");
 
-  BuiltModuleFiles.addModuleFile(ModuleName, Inputs.CompileCommand.Output);
-  return llvm::Error::success();
+  return ModuleFile{ModuleName, Inputs.CompileCommand.Output};
+}
+
+bool ReusablePrerequisiteModules::canReuse(
+const CompilerInvocation &CI,
+llvm::IntrusiveRefCntPtr VFS) const {
+  if (RequiredModules.empty())
+return true;
+
+  SmallVector BMIPaths;
+  for (auto &MF : RequiredModules)
+BMIPaths.push_back(MF->ModuleFilePath);
+  return IsModuleFilesUpToDate(BMIPaths, *this, VFS);
 }
 } // namespace
 
+class ModulesBuilder::ModuleFileCache {
+public:
+  ModuleFileCache(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  llvm::Error
+  getOrBuildModuleFile(StringRef ModuleName, const ThreadsafeFS &TFS,
+   ProjectModules &MDB,
+   ReusablePrerequisiteModules &RequiredModules);
+  const GlobalCompilationDatabase &getCDB() const { return CDB; }
+
+private:
+  std::shared_ptr
+  getValidModuleFile(StringRef ModuleName, ProjectModules &MDB,
+ const ThreadsafeFS &TFS,
+ PrerequisiteModules &BuiltModuleFiles);
+
+  /// This should only be called by getValidModuleFile. This is unlocked 
version
+  /// of getValidModuleFile. The function is extracted to avoid dead locks when
+  /// recursing.
+  std::shared_ptr
+  isValidModuleFileUnlocked(StringRef ModuleName, ProjectModules &MDB,
+const ThreadsafeFS &TFS,
+PrerequisiteModules &BuiltModuleFiles);
+
+  const GlobalCompilationDatabase &CDB;
+
+  llvm::StringMap> ModuleFiles;
+  // Mutex to guard accesses to ModuleFiles.
+  std::mutex ModuleFilesMutex;
+};
+
+std::shared_ptr
+ModulesBuilder::ModuleFileCache::isValidModuleFileUnlocked(

ChuanqiXu9 wrote:

Done. I was uncomfortable slightly since we lost the chance to erase invalided 
entries in the cache now. But the things cache are never guaranteed to be valid.

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -228,54 +223,30 @@ class StandalonePrerequisiteModules : public 
PrerequisiteModules {
 return BuiltModuleNames.contains(ModuleName);
   }
 
-  void addModuleFile(llvm::StringRef ModuleName,
- llvm::StringRef ModuleFilePath) {
-RequiredModules.emplace_back(ModuleName, ModuleFilePath);
-BuiltModuleNames.insert(ModuleName);
+  void addModuleFile(std::shared_ptr BMI) {
+BuiltModuleNames.insert(BMI->ModuleName);
+RequiredModules.emplace_back(std::move(BMI));
   }
 
 private:
-  llvm::SmallVector RequiredModules;
+  mutable llvm::SmallVector, 8> RequiredModules;

ChuanqiXu9 wrote:

It is an oversight to mark it as mutable.

I add the data members of `ModuleFile ` to be private and we can only access 
them by the getters. I think this has the same effect.

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -228,54 +223,30 @@ class StandalonePrerequisiteModules : public 
PrerequisiteModules {
 return BuiltModuleNames.contains(ModuleName);
   }
 
-  void addModuleFile(llvm::StringRef ModuleName,
- llvm::StringRef ModuleFilePath) {
-RequiredModules.emplace_back(ModuleName, ModuleFilePath);
-BuiltModuleNames.insert(ModuleName);
+  void addModuleFile(std::shared_ptr BMI) {
+BuiltModuleNames.insert(BMI->ModuleName);
+RequiredModules.emplace_back(std::move(BMI));
   }
 
 private:
-  llvm::SmallVector RequiredModules;
+  mutable llvm::SmallVector, 8> RequiredModules;
   // A helper class to speedup the query if a module is built.
   llvm::StringSet<> BuiltModuleNames;
 };
 
-// Build a module file for module with `ModuleName`. The information of built
-// module file are stored in \param BuiltModuleFiles.
-llvm::Error buildModuleFile(llvm::StringRef ModuleName,
-const GlobalCompilationDatabase &CDB,
-const ThreadsafeFS &TFS, ProjectModules &MDB,
-PathRef ModuleFilesPrefix,
-StandalonePrerequisiteModules &BuiltModuleFiles) {
-  if (BuiltModuleFiles.isModuleUnitBuilt(ModuleName))
-return llvm::Error::success();
-
-  PathRef ModuleUnitFileName = MDB.getSourceForModuleName(ModuleName);
-  // It is possible that we're meeting third party modules (modules whose
-  // source are not in the project. e.g, the std module may be a third-party
-  // module for most projects) or something wrong with the implementation of
-  // ProjectModules.
-  // FIXME: How should we treat third party modules here? If we want to ignore
-  // third party modules, we should return true instead of false here.
-  // Currently we simply bail out.
-  if (ModuleUnitFileName.empty())
-return llvm::createStringError("Failed to get the primary source");
-
+/// Build a module file for module with `ModuleName`. The information of built
+/// module file are stored in \param BuiltModuleFiles.
+llvm::Expected
+buildModuleFile(llvm::StringRef ModuleName, PathRef ModuleUnitFileName,
+const GlobalCompilationDatabase &CDB, const ThreadsafeFS &TFS,
+PathRef ModuleFilesPrefix,
+const ReusablePrerequisiteModules &BuiltModuleFiles) {
   // Try cheap operation earlier to boil-out cheaply if there are problems.
   auto Cmd = CDB.getCompileCommand(ModuleUnitFileName);
   if (!Cmd)
 return llvm::createStringError(
 llvm::formatv("No compile command for {0}", ModuleUnitFileName));
 
-  for (auto &RequiredModuleName : MDB.getRequiredModules(ModuleUnitFileName)) {

ChuanqiXu9 wrote:

See the following comment.

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


[clang-tools-extra] [clangd] [Modules] Support Reusable Modules Builder (PR #106683)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -316,36 +287,169 @@ llvm::Error buildModuleFile(llvm::StringRef ModuleName,
   if (Clang->getDiagnostics().hasErrorOccurred())
 return llvm::createStringError("Compilation failed");
 
-  BuiltModuleFiles.addModuleFile(ModuleName, Inputs.CompileCommand.Output);
-  return llvm::Error::success();
+  return ModuleFile{ModuleName, Inputs.CompileCommand.Output};
+}
+
+bool ReusablePrerequisiteModules::canReuse(
+const CompilerInvocation &CI,
+llvm::IntrusiveRefCntPtr VFS) const {
+  if (RequiredModules.empty())
+return true;
+
+  SmallVector BMIPaths;
+  for (auto &MF : RequiredModules)
+BMIPaths.push_back(MF->ModuleFilePath);
+  return IsModuleFilesUpToDate(BMIPaths, *this, VFS);
 }
 } // namespace
 
+class ModulesBuilder::ModuleFileCache {
+public:
+  ModuleFileCache(const GlobalCompilationDatabase &CDB) : CDB(CDB) {}
+
+  llvm::Error
+  getOrBuildModuleFile(StringRef ModuleName, const ThreadsafeFS &TFS,
+   ProjectModules &MDB,
+   ReusablePrerequisiteModules &RequiredModules);
+  const GlobalCompilationDatabase &getCDB() const { return CDB; }
+
+private:
+  std::shared_ptr
+  getValidModuleFile(StringRef ModuleName, ProjectModules &MDB,
+ const ThreadsafeFS &TFS,
+ PrerequisiteModules &BuiltModuleFiles);
+
+  /// This should only be called by getValidModuleFile. This is unlocked 
version
+  /// of getValidModuleFile. The function is extracted to avoid dead locks when
+  /// recursing.
+  std::shared_ptr
+  isValidModuleFileUnlocked(StringRef ModuleName, ProjectModules &MDB,
+const ThreadsafeFS &TFS,
+PrerequisiteModules &BuiltModuleFiles);
+
+  const GlobalCompilationDatabase &CDB;
+
+  llvm::StringMap> ModuleFiles;

ChuanqiXu9 wrote:

I think `std::shared_ptr` is correct here. The cache should be an owner. 
Otherwise, if we close all tabs and we open a tab again, we may have to build 
the same module file that could be in the cache.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process

ideasman42 wrote:

Regarding temporary file use: did you check on the `diff-buffers` function? it 
should be possible to diff two temporary buffers without creating temporary 
files.

Looking into the implementation `diff-no-select` may be what your after as that 
looks to be intended for non interactive use.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Get minimal diff (copy diff config for git-clang-format)
+   "-U0"
+   file-orig
+   file-new))
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position
+  (diff-lines '()))
+  (cond
+   ((stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+   ;; Return of 0 indicates no diff
+   ((= status 0) nil)
+   ;; Return of 1 indicates found diffs and no error
+   ((= status 1)
+;; Iterate through all lines in diff buffer and collect all
+;; lines in current buffer that have a diff.
+(goto-char (point-min))
+(while (not (eobp))
+  (let ((diff-line (clang-format--vc-diff-match-diff-line
+(buffer-substring-no-properties
+ (line-beginning-position)
+ (line-end-position)
+(when diff-line
+  ;; Create list line regions with diffs to pass to
+  ;; clang-format
+  (add-to-list 'diff-lines (concat "--lines=" diff-line) t)))
+  (forward-line 1))
+diff-lines)
+   ;; Any return != 0 && != 1 indicates some level of error
+   (t
+(error "(diff returned unsuccessfully %s%s)" status stderr))
+
+(defun clang-format--vc-diff-get-vc-head-file (tmpfile-vc-head)
+  "Stores the contents of 'buffer-file-name' at vc revision HEAD into
+'tmpfile-vc-head'. If the current buffer is either not a file or not
+in a vc repo, this results in an error. Currently git is the only
+supported vc."
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Only version control currently supported is Git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")

ideasman42 wrote:

Suggestion: my preference would be to write this in a way that makes adding 
other VC more straightforward.
```
(let ((vc-backend ...snip...))
  (cond
(string-equal vc-backend "Git")
  ...git...logic...
(t
   (error "Version control %s isn't supported, currently supported backends 
... snip ..." vc-backend
```

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and

ideasman42 wrote:

Running `byte-compile-file` gives various warnings: 

```
clang-format.el:163:2: Warning: docstring has wrong usage of unescaped single 
quotes (use \=' or different quoting such as `...')
clang-format.el:201:19: Error: ‘add-to-list’ can’t use lexical var 
‘diff-lines’; use ‘push’ or ‘cl-pushnew’

In clang-format--vc-diff-get-vc-head-file:
clang-format.el:211:2: Warning: docstring has wrong usage of unescaped single 
quotes (use \=' or different quoting such as `...')

In clang-format--region-impl:
clang-format.el:252:2: Warning: docstring has wrong usage of unescaped single 
quotes (use \=' or different quoting such as `...')

In clang-format-vc-diff:
clang-format.el:325:2: Warning: docstring has wrong usage of unescaped single 
quotes (use \=' or different quoting such as `...')
```


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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

https://github.com/ideasman42 requested changes to this pull request.

This seems more ore less OK, although 

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Campbell Barton via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Get minimal diff (copy diff config for git-clang-format)
+   "-U0"
+   file-orig
+   file-new))
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position
+  (diff-lines '()))
+  (cond
+   ((stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+   ;; Return of 0 indicates no diff
+   ((= status 0) nil)
+   ;; Return of 1 indicates found diffs and no error
+   ((= status 1)
+;; Iterate through all lines in diff buffer and collect all
+;; lines in current buffer that have a diff.
+(goto-char (point-min))
+(while (not (eobp))
+  (let ((diff-line (clang-format--vc-diff-match-diff-line
+(buffer-substring-no-properties
+ (line-beginning-position)
+ (line-end-position)
+(when diff-line
+  ;; Create list line regions with diffs to pass to
+  ;; clang-format
+  (add-to-list 'diff-lines (concat "--lines=" diff-line) t)))
+  (forward-line 1))
+diff-lines)
+   ;; Any return != 0 && != 1 indicates some level of error
+   (t
+(error "(diff returned unsuccessfully %s%s)" status stderr))
+
+(defun clang-format--vc-diff-get-vc-head-file (tmpfile-vc-head)
+  "Stores the contents of 'buffer-file-name' at vc revision HEAD into
+'tmpfile-vc-head'. If the current buffer is either not a file or not
+in a vc repo, this results in an error. Currently git is the only
+supported vc."
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Only version control currently supported is Git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")
+(error "Not using git"))
+
+  (let ((base-dir (vc-root-dir)))
+;; Need to be able to find version control (git) root

ideasman42 wrote:

\*picky\* use full sentences for comments - end with a full-stop, applies to 
many other comments here.

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


[clang] [flang] [Flang][LoongArch] Emit target features for Loongarch64. (PR #114735)

2024-11-03 Thread Zhaoxin Yang via cfe-commits

https://github.com/ylzsx created 
https://github.com/llvm/llvm-project/pull/114735

None

>From dd4aca55c1e35ebd6dbb9d849ba9de8b930ae209 Mon Sep 17 00:00:00 2001
From: ylzsx <2375355...@qq.com>
Date: Sat, 2 Nov 2024 10:48:29 +0800
Subject: [PATCH] [Flang][LoongArch] Emit target features for Loongarch64.

---
 clang/lib/Driver/ToolChains/Flang.cpp | 3 +++
 flang/test/Driver/target-cpu-features.f90 | 6 ++
 2 files changed, 9 insertions(+)

diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index f9d2fdffe3b2fc..11070c23c75f4a 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -414,6 +414,9 @@ void Flang::addTargetOptions(const ArgList &Args,
   case llvm::Triple::ppc64le:
 AddPPCTargetArgs(Args, CmdArgs);
 break;
+  case llvm::Triple::loongarch64:
+getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
+break;
   }
 
   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
diff --git a/flang/test/Driver/target-cpu-features.f90 
b/flang/test/Driver/target-cpu-features.f90
index e3eb8491058c7f..5a3fd0d8380027 100644
--- a/flang/test/Driver/target-cpu-features.f90
+++ b/flang/test/Driver/target-cpu-features.f90
@@ -41,6 +41,9 @@
 ! RUN: %flang --target=r600-unknown-unknown -mcpu=cayman -nogpulib -c %s -### 
2>&1 \
 ! RUN: | FileCheck %s -check-prefix=CHECK-AMDGPU-R600
 
+! RUN: %flang --target=loongarch64-linux-gnu -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-LOONGARCH64
+
 ! CHECK-A57: "-fc1" "-triple" "aarch64-unknown-linux-gnu"
 ! CHECK-A57-SAME: "-target-cpu" "cortex-a57"
 ! CHECK-A57-SAME: "-target-feature" "+v8a" "-target-feature" "+aes" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2
@@ -86,3 +89,6 @@
 
 ! CHECK-AMDGPU-R600: "-fc1" "-triple" "r600-unknown-unknown"
 ! CHECK-AMDGPU-R600-SAME: "-target-cpu" "cayman"
+
+! CHECK-LOONGARCH64: "-fc1" "-triple" "loongarch64-unknown-linux-gnu"
+! CHECK-LOONGARCH64-SAME: "-target-cpu" "loongarch64" "-target-feature" "+lsx" 
"-target-feature" "+64bit" "-target-feature" "+f" "-target-feature" "+d" 
"-target-feature" "+ual"

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


[clang] [flang] [Flang][LoongArch] Emit target features for Loongarch64. (PR #114735)

2024-11-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Zhaoxin Yang (ylzsx)


Changes



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


2 Files Affected:

- (modified) clang/lib/Driver/ToolChains/Flang.cpp (+3) 
- (modified) flang/test/Driver/target-cpu-features.f90 (+6) 


``diff
diff --git a/clang/lib/Driver/ToolChains/Flang.cpp 
b/clang/lib/Driver/ToolChains/Flang.cpp
index f9d2fdffe3b2fc..11070c23c75f4a 100644
--- a/clang/lib/Driver/ToolChains/Flang.cpp
+++ b/clang/lib/Driver/ToolChains/Flang.cpp
@@ -414,6 +414,9 @@ void Flang::addTargetOptions(const ArgList &Args,
   case llvm::Triple::ppc64le:
 AddPPCTargetArgs(Args, CmdArgs);
 break;
+  case llvm::Triple::loongarch64:
+getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
+break;
   }
 
   if (Arg *A = Args.getLastArg(options::OPT_fveclib)) {
diff --git a/flang/test/Driver/target-cpu-features.f90 
b/flang/test/Driver/target-cpu-features.f90
index e3eb8491058c7f..5a3fd0d8380027 100644
--- a/flang/test/Driver/target-cpu-features.f90
+++ b/flang/test/Driver/target-cpu-features.f90
@@ -41,6 +41,9 @@
 ! RUN: %flang --target=r600-unknown-unknown -mcpu=cayman -nogpulib -c %s -### 
2>&1 \
 ! RUN: | FileCheck %s -check-prefix=CHECK-AMDGPU-R600
 
+! RUN: %flang --target=loongarch64-linux-gnu -c %s -### 2>&1 \
+! RUN: | FileCheck %s -check-prefix=CHECK-LOONGARCH64
+
 ! CHECK-A57: "-fc1" "-triple" "aarch64-unknown-linux-gnu"
 ! CHECK-A57-SAME: "-target-cpu" "cortex-a57"
 ! CHECK-A57-SAME: "-target-feature" "+v8a" "-target-feature" "+aes" 
"-target-feature" "+crc" "-target-feature" "+fp-armv8" "-target-feature" 
"+neon" "-target-feature" "+perfmon" "-target-feature" "+sha2
@@ -86,3 +89,6 @@
 
 ! CHECK-AMDGPU-R600: "-fc1" "-triple" "r600-unknown-unknown"
 ! CHECK-AMDGPU-R600-SAME: "-target-cpu" "cayman"
+
+! CHECK-LOONGARCH64: "-fc1" "-triple" "loongarch64-unknown-linux-gnu"
+! CHECK-LOONGARCH64-SAME: "-target-cpu" "loongarch64" "-target-feature" "+lsx" 
"-target-feature" "+64bit" "-target-feature" "+f" "-target-feature" "+d" 
"-target-feature" "+ual"

``




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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Get minimal diff (copy diff config for git-clang-format)
+   "-U0"
+   file-orig
+   file-new))
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position
+  (diff-lines '()))
+  (cond
+   ((stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+   ;; Return of 0 indicates no diff
+   ((= status 0) nil)
+   ;; Return of 1 indicates found diffs and no error
+   ((= status 1)
+;; Iterate through all lines in diff buffer and collect all
+;; lines in current buffer that have a diff.
+(goto-char (point-min))
+(while (not (eobp))
+  (let ((diff-line (clang-format--vc-diff-match-diff-line
+(buffer-substring-no-properties
+ (line-beginning-position)
+ (line-end-position)
+(when diff-line
+  ;; Create list line regions with diffs to pass to
+  ;; clang-format
+  (add-to-list 'diff-lines (concat "--lines=" diff-line) t)))
+  (forward-line 1))
+diff-lines)
+   ;; Any return != 0 && != 1 indicates some level of error
+   (t
+(error "(diff returned unsuccessfully %s%s)" status stderr))
+
+(defun clang-format--vc-diff-get-vc-head-file (tmpfile-vc-head)
+  "Stores the contents of 'buffer-file-name' at vc revision HEAD into
+'tmpfile-vc-head'. If the current buffer is either not a file or not
+in a vc repo, this results in an error. Currently git is the only
+supported vc."
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Only version control currently supported is Git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")

goldsteinn wrote:

Sure, the counter argument is it causes a bit of excessive nesting, but happy 
to change.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits


@@ -146,18 +146,115 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--vc-diff-match-diff-line (line)
+  ;; Matching something like:
+  ;; "@@ -80 +80 @@" or "@@ -80,2 +80,2 @@"
+  ;; Return as ":"
+  (when (string-match 
"^@@\s-[0-9,]+\s\\+\\([0-9]+\\)\\(,\\([0-9]+\\)\\)?\s@@$" line)
+;; If we have multi-line diff
+(if (match-string 3 line)
+(concat (match-string 1 line)
+":"
+(number-to-string
+ (+ (string-to-number (match-string 1 line))
+(string-to-number (match-string 3 line)
+  (concat (match-string 1 line) ":" (match-string 1 line)
+
+(defun clang-format--vc-diff-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process

goldsteinn wrote:

I don't think so, or at least `diff.el` uses temporary files:

```
(defun diff-file-local-copy (file-or-buf)
  "Like `file-local-copy' but also supports a buffer as the argument.
When FILE-OR-BUF is a buffer, return the filename of a local
temporary file with the buffer's contents."
  (if (bufferp file-or-buf)
  (with-current-buffer file-or-buf
(let ((tempfile (make-temp-file "buffer-content-")))
  (if diff-entire-buffers
  (write-region nil nil tempfile nil 'nomessage)
(write-region (point-min) (point-max) tempfile nil 'nomessage))
  tempfile))
(file-local-copy file-or-buf)))
...
  (let* ((old-alt (diff-file-local-copy old))
 (new-alt (diff-file-local-copy new))
 (command
  (mapconcat #'identity
 `(,diff-command
   ;; Use explicitly specified switches
   ,@switches
   ,@(mapcar #'shell-quote-argument
 (nconc
  (and (or old-alt new-alt)

```

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


[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to optimizer pipeline (PR #114577)

2024-11-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`openmp-offload-libc-amdgpu-runtime` running on `omp-vega20-1` while building 
`clang,llvm` at step 11 "Add check check-libc-amdgcn-amd-amdhsa".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/73/builds/7977


Here is the relevant piece of the build log for the reference

```
Step 11 (Add check check-libc-amdgcn-amd-amdhsa) failure: test (failure)
...
[   OK ] LlvmLibcAcosfTest.SpecialNumbers (6 us)
Ran 1 tests.  PASS: 1  FAIL: 0
[2410/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strcpy_test.__hermetic__.__build__
[2411/2687] Running hermetic test 
libc.test.src.math.smoke.atanf_test.__hermetic__
[==] Running 1 test from 1 test suite.
[ RUN  ] LlvmLibcAtanfTest.SpecialNumbers
[   OK ] LlvmLibcAtanfTest.SpecialNumbers (3 us)
Ran 1 tests.  PASS: 1  FAIL: 0
[2412/2687] Linking CXX executable 
libc/test/src/inttypes/libc.test.src.inttypes.imaxdiv_test.__hermetic__.__build__
[2413/2687] Running integration test 
libc.test.integration.src.stdio.sprintf_size_test
FAILED: 
libc/test/integration/src/stdio/CMakeFiles/libc.test.integration.src.stdio.sprintf_size_test
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-amdgcn-amd-amdhsa-bins/libc/test/integration/src/stdio/CMakeFiles/libc.test.integration.src.stdio.sprintf_size_test
 
cd 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-amdgcn-amd-amdhsa-bins/libc/test/integration/src/stdio
 && 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/bin/amdhsa-loader
 
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.build/runtimes/runtimes-amdgcn-amd-amdhsa-bins/libc/test/integration/src/stdio/libc.test.integration.src.stdio.sprintf_size_test.__build__
 %s\ %c\ %d First\ arg a 0
/home/ompworker/bbot/openmp-offload-libc-amdgpu-runtime/llvm.src/libc/test/integration/src/stdio/sprintf_size_test.cpp:57:
 Expected 'my_streq(buf, "First arg a 48")' to be true, but is false
[2414/2687] Running integration test 
libc.test.integration.src.stdio.gpu.printf_test
[2415/2687] Running hermetic test 
libc.test.src.math.smoke.atan2f_test.__hermetic__
[==] Running 1 test from 1 test suite.
[ RUN  ] LlvmLibcAtan2fTest.SpecialNumbers
[   OK ] LlvmLibcAtan2fTest.SpecialNumbers (8 us)
Ran 1 tests.  PASS: 1  FAIL: 0
[2416/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strrchr_test.__hermetic__.__build__
[2417/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strsep_test.__hermetic__.__build__
[2418/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.bcmp_test.__hermetic__.__build__
[2419/2687] Linking CXX executable 
libc/test/include/libc.test.include.signbitf_test.__hermetic__.__build__
[2420/2687] Linking CXX executable 
libc/test/include/libc.test.include.signbit_test.__hermetic__.__build__
[2421/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strncat_test.__hermetic__.__build__
[2422/2687] Linking CXX executable 
libc/test/include/libc.test.include.signbitl_test.__hermetic__.__build__
[2423/2687] Linking CXX executable 
libc/test/include/libc.test.include.fpclassify_test.__hermetic__.__build__
[2424/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.memcmp_test.__hermetic__.__build__
[2425/2687] Linking CXX executable 
libc/test/include/libc.test.include.iszerof_test.__hermetic__.__build__
[2426/2687] Linking CXX executable 
libc/test/include/libc.test.include.iszero_test.__hermetic__.__build__
[2427/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strlcat_test.__hermetic__.__build__
[2428/2687] Linking CXX executable 
libc/test/include/libc.test.include.fpclassifyl_test.__hermetic__.__build__
[2429/2687] Linking CXX executable 
libc/test/include/libc.test.include.fpclassifyf_test.__hermetic__.__build__
[2430/2687] Linking CXX executable 
libc/test/src/time/libc.test.src.time.clock_test.__hermetic__.__build__
[2431/2687] Linking CXX executable 
libc/test/include/libc.test.include.iszerol_test.__hermetic__.__build__
[2432/2687] Linking CXX executable 
libc/test/src/inttypes/libc.test.src.inttypes.strtoumax_test.__hermetic__.__build__
[2433/2687] Linking CXX executable 
libc/test/src/string/libc.test.src.string.strxfrm_test.__hermetic__.__build__
[2434/2687] Linking CXX executable 
libc/test/src/inttypes/libc.test.src.inttypes.strtoimax_test.__hermetic__.__build__
[2435/2687] Linking CXX executable 
libc/test/include/libc.test.include.isnan_test.__hermetic__.__build__
[2436/2687] Linking CXX executable 
libc/test/include/libc.test.include.isinfl_test.__hermetic__.__build__
[2437/2687] Linking CXX executable 
libc/test/include/libc.test.include.isfinitef_test.__hermetic__.__build__
[2438/2687] Linking CXX executable 
libc/test/include/libc.test.include.isnanl_test.__hermetic__.__build__
[2439/2687] Linkin

[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread via cfe-commits


@@ -691,7 +691,7 @@ ensure it is reachable, e.g. ``using N::g;``.
 Support for Reduced BMIs is still experimental, but it may become the default
 in the future. The expected roadmap for Reduced BMIs as of Clang 19.x is:
 
-1. ``-fexperimental-modules-reduced-bmi`` is opt-in for 1~2 releases. The 
period depends
+1. ``-fmodules-reduced-bmi`` is opt-in for 1~2 releases. The period depends
on user feedback and may be extended.
 2. Announce that Reduced BMIs are no longer experimental and introduce
``-fmodules-reduced-bmi`` as a new option, and recommend use of the new

h-vetinari wrote:

w.r.t. keeping the "as of 19.x": since removing `experimental-` prefix was part 
of the plan since v19, the first point should either be marked as done (or 
simply removed), but not simply renamed (which would be inconsistent both with 
the "as of 19.x", as well as the following item that already covers the same 
point). For example:
```suggestion
1. ``-fexperimental-modules-reduced-bmi`` was introduced in v19.x
2. For v20.x, ``-fmodules-reduced-bmi`` is introduced as an equivalent 
non-experimental
   option. It is expected to stay opt-in for 1~2 releases, though the period 
depends
   on user feedback and may be extended.
```

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


[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread via cfe-commits


@@ -691,7 +691,7 @@ ensure it is reachable, e.g. ``using N::g;``.
 Support for Reduced BMIs is still experimental, but it may become the default
 in the future. The expected roadmap for Reduced BMIs as of Clang 19.x is:

h-vetinari wrote:

It's confusing to update/clarify the plan during the 20.x cycle and then not 
update the "as of 19.x" (even though the overall shape of the plan didn't 
change). If you want to keep the "as of 19.x", then we should specify which 
steps have been done already (see below), though IMO _any_ updates here should 
also update the "as of".

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


[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread via cfe-commits

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


[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread via cfe-commits

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


[clang] [llvm] Intrinsics/clip (PR #114588)

2024-11-03 Thread via cfe-commits

https://github.com/joaosaffran updated 
https://github.com/llvm/llvm-project/pull/114588

>From 996405ae7454a13a01a8d249a8cf85cf4a29eee6 Mon Sep 17 00:00:00 2001
From: Joao Saffran 
Date: Tue, 29 Oct 2024 19:39:31 +
Subject: [PATCH 1/4] adding llvm intrinsic

---
 clang/include/clang/Basic/Builtins.td |  6 ++
 clang/lib/CodeGen/CGBuiltin.cpp   | 10 ++
 clang/lib/CodeGen/CGHLSLRuntime.h |  2 +-
 clang/lib/Headers/hlsl/hlsl_intrinsics.h  | 17 +
 clang/lib/Sema/SemaHLSL.cpp   |  8 
 clang/test/CodeGenHLSL/builtins/clip.hlsl | 14 ++
 llvm/include/llvm/IR/IntrinsicsDirectX.td |  1 +
 llvm/include/llvm/IR/IntrinsicsSPIRV.td   |  1 +
 8 files changed, 58 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGenHLSL/builtins/clip.hlsl

diff --git a/clang/include/clang/Basic/Builtins.td 
b/clang/include/clang/Basic/Builtins.td
index 9bd67e0cefebc3..1b8697b209bd70 100644
--- a/clang/include/clang/Basic/Builtins.td
+++ b/clang/include/clang/Basic/Builtins.td
@@ -4877,6 +4877,12 @@ def HLSLSplitDouble: LangBuiltin<"HLSL_LANG"> {
   let Prototype = "void(...)";
 }
 
+def HLSLClip: LangBuiltin<"HLSL_LANG"> {
+  let Spellings = ["__builtin_hlsl_elementwise_clip"];
+  let Attributes = [NoThrow, Const];
+  let Prototype = "void(bool)";
+}
+
 // Builtins for XRay.
 def XRayCustomEvent : Builtin {
   let Spellings = ["__xray_customevent"];
diff --git a/clang/lib/CodeGen/CGBuiltin.cpp b/clang/lib/CodeGen/CGBuiltin.cpp
index 038057d2164ced..b359ba8aff6d07 100644
--- a/clang/lib/CodeGen/CGBuiltin.cpp
+++ b/clang/lib/CodeGen/CGBuiltin.cpp
@@ -19041,6 +19041,16 @@ case Builtin::BI__builtin_hlsl_elementwise_isinf: {
"asuint operands types mismatch");
 return handleHlslSplitdouble(E, this);
   }
+  case Builtin::BI__builtin_hlsl_elementwise_clip:
+
+assert(E->getArg(0)->getType()->hasFloatingRepresentation() &&
+   "clip operands types mismatch");
+
+Value *Op0 = EmitScalarExpr(E->getArg(0));
+auto *CMP =
+Builder.CreateFCmpOLT(Op0, ConstantFP::get(Builder.getFloatTy(), 0.0));
+return Builder.CreateIntrinsic(
+VoidTy, CGM.getHLSLRuntime().getClipIntrinsic(), {CMP}, nullptr);
   }
   return nullptr;
 }
diff --git a/clang/lib/CodeGen/CGHLSLRuntime.h 
b/clang/lib/CodeGen/CGHLSLRuntime.h
index cd533cad84e9fb..06abc95bdb734f 100644
--- a/clang/lib/CodeGen/CGHLSLRuntime.h
+++ b/clang/lib/CodeGen/CGHLSLRuntime.h
@@ -91,7 +91,7 @@ class CGHLSLRuntime {
   GENERATE_HLSL_INTRINSIC_FUNCTION(UDot, udot)
   GENERATE_HLSL_INTRINSIC_FUNCTION(WaveIsFirstLane, wave_is_first_lane)
   GENERATE_HLSL_INTRINSIC_FUNCTION(WaveReadLaneAt, wave_readlane)
-
+  GENERATE_HLSL_INTRINSIC_FUNCTION(Clip, clip)
   GENERATE_HLSL_INTRINSIC_FUNCTION(CreateHandleFromBinding, handle_fromBinding)
 
   
//===--===//
diff --git a/clang/lib/Headers/hlsl/hlsl_intrinsics.h 
b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
index d9f3a17ea23d8e..424c2f7e7c23ee 100644
--- a/clang/lib/Headers/hlsl/hlsl_intrinsics.h
+++ b/clang/lib/Headers/hlsl/hlsl_intrinsics.h
@@ -655,6 +655,23 @@ double3 clamp(double3, double3, double3);
 _HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clamp)
 double4 clamp(double4, double4, double4);
 
+//===--===//
+// clip builtins
+//===--===//
+
+/// \fn void clip(T Val)
+/// \brief Discards the current pixel if the specified value is less than zero.
+/// \param Val The input value.
+
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clip)
+void clip(float);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clip)
+void clip(float2);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clip)
+void clip(float3);
+_HLSL_BUILTIN_ALIAS(__builtin_hlsl_elementwise_clip)
+void clip(float4);
+
 
//===--===//
 // cos builtins
 
//===--===//
diff --git a/clang/lib/Sema/SemaHLSL.cpp b/clang/lib/Sema/SemaHLSL.cpp
index a472538236e2d9..e360c54dc0760e 100644
--- a/clang/lib/Sema/SemaHLSL.cpp
+++ b/clang/lib/Sema/SemaHLSL.cpp
@@ -2110,6 +2110,14 @@ bool SemaHLSL::CheckBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
   return true;
 break;
   }
+  case Builtin::BI__builtin_hlsl_elementwise_clip: {
+if (SemaRef.checkArgCount(TheCall, 1))
+  return true;
+
+if (CheckScalarOrVector(&SemaRef, TheCall, SemaRef.Context.FloatTy, 0))
+  return true;
+break;
+  }
   case Builtin::BI__builtin_elementwise_acos:
   case Builtin::BI__builtin_elementwise_asin:
   case Builtin::BI__builtin_elementwise_atan:
diff --git a/clang/test/CodeGenHLSL/builtins/clip.hlsl 
b/clang/test/CodeGenHLSL/builtins/clip.hlsl
new file mode 100644
index 00..426ec8f128436a
--- /dev/null
+++ 

[clang] [LoongArch][Clang] Make the parameters and return value of {x,}vxor.v builti ns `unsigned char` vectors (PR #114513)

2024-11-03 Thread Xi Ruoyao via cfe-commits

https://github.com/xry111 updated 
https://github.com/llvm/llvm-project/pull/114513

>From 0d62818ddfa1d6b99afca4653a9f47478f301b32 Mon Sep 17 00:00:00 2001
From: Xi Ruoyao 
Date: Fri, 1 Nov 2024 00:22:09 +0800
Subject: [PATCH] [LoongArch][Clang] Make the parameters and return value of
 {x,}vxor.v builtins `unsigned char` vectors

The lsxintrin.h and and lasxintrin.h headers uses `unsigned char`
vectors instead of `signed char` vectors.  GCC also uses `unsigned char`
for them, so align their definition with the headers and GCC.

Fixes #110834.
---
 clang/include/clang/Basic/BuiltinsLoongArchLASX.def | 2 +-
 clang/include/clang/Basic/BuiltinsLoongArchLSX.def  | 2 +-
 clang/test/Headers/lasxintrin.c | 5 ++---
 clang/test/Headers/lsxintrin.c  | 5 ++---
 4 files changed, 6 insertions(+), 8 deletions(-)

diff --git a/clang/include/clang/Basic/BuiltinsLoongArchLASX.def 
b/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
index e6c41dd0974948..f644b820a61898 100644
--- a/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
+++ b/clang/include/clang/Basic/BuiltinsLoongArchLASX.def
@@ -368,7 +368,7 @@ TARGET_BUILTIN(__builtin_lasx_xvrepli_d, "V4LLiIi", "nc", 
"lasx")
 
 TARGET_BUILTIN(__builtin_lasx_xvand_v, "V32UcV32UcV32Uc", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvor_v, "V32UcV32UcV32Uc", "nc", "lasx")
-TARGET_BUILTIN(__builtin_lasx_xvxor_v, "V32ScV32ScV32Sc", "nc", "lasx")
+TARGET_BUILTIN(__builtin_lasx_xvxor_v, "V32UcV32UcV32Uc", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvnor_v, "V32UcV32UcV32Uc", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvandn_v, "V32UcV32UcV32Uc", "nc", "lasx")
 TARGET_BUILTIN(__builtin_lasx_xvorn_v, "V32ScV32ScV32Sc", "nc", "lasx")
diff --git a/clang/include/clang/Basic/BuiltinsLoongArchLSX.def 
b/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
index ded6519f3ef16c..b3056971986d19 100644
--- a/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
+++ b/clang/include/clang/Basic/BuiltinsLoongArchLSX.def
@@ -352,7 +352,7 @@ TARGET_BUILTIN(__builtin_lsx_vrepli_d, "V2LLiIi", "nc", 
"lsx")
 
 TARGET_BUILTIN(__builtin_lsx_vand_v, "V16UcV16UcV16Uc", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vor_v, "V16UcV16UcV16Uc", "nc", "lsx")
-TARGET_BUILTIN(__builtin_lsx_vxor_v, "V16ScV16ScV16Sc", "nc", "lsx")
+TARGET_BUILTIN(__builtin_lsx_vxor_v, "V16UcV16UcV16Uc", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vnor_v, "V16UcV16UcV16Uc", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vandn_v, "V16UcV16UcV16Uc", "nc", "lsx")
 TARGET_BUILTIN(__builtin_lsx_vorn_v, "V16ScV16ScV16Sc", "nc", "lsx")
diff --git a/clang/test/Headers/lasxintrin.c b/clang/test/Headers/lasxintrin.c
index 6126c6350455c1..08f71791bdf36f 100644
--- a/clang/test/Headers/lasxintrin.c
+++ b/clang/test/Headers/lasxintrin.c
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lasx
-// RUN: not %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature 
+lasx -flax-vector-conversions=none
-// RUN: not %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature 
+lasx -flax-vector-conversions=none -fno-signed-char
-// FIXME: "not" should be removed once we fix GH#110834.
+// RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lasx 
-flax-vector-conversions=none
+// RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lasx 
-flax-vector-conversions=none -fno-signed-char
 
 #include 
diff --git a/clang/test/Headers/lsxintrin.c b/clang/test/Headers/lsxintrin.c
index 930d3efe62e543..83c9879eea967d 100644
--- a/clang/test/Headers/lsxintrin.c
+++ b/clang/test/Headers/lsxintrin.c
@@ -1,6 +1,5 @@
 // RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lsx
-// RUN: not %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature 
+lsx -flax-vector-conversions=none
-// RUN: not %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature 
+lsx -flax-vector-conversions=none -fno-signed-char
-// FIXME: "not" should be removed once we fix GH#110834.
+// RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lsx 
-flax-vector-conversions=none
+// RUN: %clang_cc1 %s -fsyntax-only -triple loongarch64 -target-feature +lsx 
-flax-vector-conversions=none -fno-signed-char
 
 #include 

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


[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread Chuanqi Xu via cfe-commits

https://github.com/ChuanqiXu9 updated 
https://github.com/llvm/llvm-project/pull/114382

>From f33e3bcd7d31742a37059a9d75fa58aa4d9ff36d Mon Sep 17 00:00:00 2001
From: Chuanqi Xu 
Date: Thu, 31 Oct 2024 17:27:00 +0800
Subject: [PATCH 1/2] [C++20] [Modules] Convert
 '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi'

---
 clang/docs/StandardCPlusPlusModules.rst   | 18 ++---
 .../clang/Basic/DiagnosticDriverKinds.td  |  8 ++
 clang/include/clang/Driver/Options.td |  5 +++-
 clang/lib/Driver/ToolChains/Clang.cpp | 12 +++--
 .../test/Driver/module-fgen-reduced-bmi.cppm  | 26 +--
 5 files changed, 55 insertions(+), 14 deletions(-)

diff --git a/clang/docs/StandardCPlusPlusModules.rst 
b/clang/docs/StandardCPlusPlusModules.rst
index 8e22adad15106e..26b29337ce42cb 100644
--- a/clang/docs/StandardCPlusPlusModules.rst
+++ b/clang/docs/StandardCPlusPlusModules.rst
@@ -602,16 +602,16 @@ unnecessary dependencies for the BMI. To mitigate the 
problem, Clang has a
 compiler option to reduce the information contained in the BMI. These two
 formats are known as Full BMI and Reduced BMI, respectively.
 
-Users can use the ``-fexperimental-modules-reduced-bmi`` option to produce a
+Users can use the ``-fmodules-reduced-bmi`` option to produce a
 Reduced BMI.
 
 For the one-phase compilation model (CMake implements this model), with
-``-fexperimental-modules-reduced-bmi``, the generated BMI will be a Reduced
+``-fmodules-reduced-bmi``, the generated BMI will be a Reduced
 BMI automatically. (The output path of the BMI is specified by
 ``-fmodule-output=`` as usual with the one-phase compilation model).
 
 It is also possible to produce a Reduced BMI with the two-phase compilation
-model. When ``-fexperimental-modules-reduced-bmi``, ``--precompile``, and
+model. When ``-fmodules-reduced-bmi``, ``--precompile``, and
 ``-fmodule-output=`` are specified, the generated BMI specified by ``-o`` will
 be a full BMI and the BMI specified by ``-fmodule-output=`` will be a Reduced
 BMI. The dependency graph in this case would look like:
@@ -625,7 +625,7 @@ BMI. The dependency graph in this case would look like:
-> ...
-> consumer_n.cpp
 
-Clang does not emit diagnostics when ``-fexperimental-modules-reduced-bmi`` is
+Clang does not emit diagnostics when ``-fmodules-reduced-bmi`` is
 used with a non-module unit. This design permits users of the one-phase
 compilation model to try using reduced BMIs without needing to modify the build
 system. The two-phase compilation module requires build system support.
@@ -691,7 +691,7 @@ ensure it is reachable, e.g. ``using N::g;``.
 Support for Reduced BMIs is still experimental, but it may become the default
 in the future. The expected roadmap for Reduced BMIs as of Clang 19.x is:
 
-1. ``-fexperimental-modules-reduced-bmi`` is opt-in for 1~2 releases. The 
period depends
+1. ``-fmodules-reduced-bmi`` is opt-in for 1~2 releases. The period depends
on user feedback and may be extended.
 2. Announce that Reduced BMIs are no longer experimental and introduce
``-fmodules-reduced-bmi`` as a new option, and recommend use of the new
@@ -814,8 +814,8 @@ With reduced BMI, non-cascading changes can be more 
powerful. For example,
 
 .. code-block:: console
 
-  $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm  
-fexperimental-modules-reduced-bmi -o A.o
-  $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm  
-fexperimental-modules-reduced-bmi -o B.o -fmodule-file=A=A.pcm
+  $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm  -fmodules-reduced-bmi 
-o A.o
+  $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm  -fmodules-reduced-bmi 
-o B.o -fmodule-file=A=A.pcm
   $ md5sum B.pcm
   6c2bd452ca32ab418bf35cd141b060b9  B.pcm
 
@@ -831,8 +831,8 @@ and recompile the example:
 
 .. code-block:: console
 
-  $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm  
-fexperimental-modules-reduced-bmi -o A.o
-  $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm  
-fexperimental-modules-reduced-bmi -o B.o -fmodule-file=A=A.pcm
+  $ clang++ -std=c++20 A.cppm -c -fmodule-output=A.pcm  -fmodules-reduced-bmi 
-o A.o
+  $ clang++ -std=c++20 B.cppm -c -fmodule-output=B.pcm  -fmodules-reduced-bmi 
-o B.o -fmodule-file=A=A.pcm
   $ md5sum B.pcm
   6c2bd452ca32ab418bf35cd141b060b9  B.pcm
 
diff --git a/clang/include/clang/Basic/DiagnosticDriverKinds.td 
b/clang/include/clang/Basic/DiagnosticDriverKinds.td
index 65551bd7761a9d..7589c6f52419dd 100644
--- a/clang/include/clang/Basic/DiagnosticDriverKinds.td
+++ b/clang/include/clang/Basic/DiagnosticDriverKinds.td
@@ -556,6 +556,14 @@ def err_test_module_file_extension_format : Error<
 def err_drv_module_output_with_multiple_arch : Error<
   "option '-fmodule-output' can't be used with multiple arch options">;
 
+def warn_drv_module_reduced_bmi_not_enabled : Warning<
+  "reduced BMI is expected to be ena

[clang] [C++20] [Modules] Convert '-fexperimental-modules-reduced-bmi' to '-fmodules-reduced-bmi' (PR #114382)

2024-11-03 Thread Chuanqi Xu via cfe-commits


@@ -556,6 +556,14 @@ def err_test_module_file_extension_format : Error<
 def err_drv_module_output_with_multiple_arch : Error<
   "option '-fmodule-output' can't be used with multiple arch options">;
 
+def warn_drv_module_reduced_bmi_not_enabled : Warning<
+  "reduced BMI is expected to be enabled by default in Clang 21. It is 
encouraged to "
+  "enable it ahead of time to avoid potential breaking change. You can enable 
it "
+  "by offering '-fmodules-reduced-bmi' option in one phase compilation model 
(e.g., CMake). "
+  "Or if your build system support two phase compilation model, please contact 
the "
+  "build system authors to support reduced BMI and turn off the warning 
temporarily">,

ChuanqiXu9 wrote:

Done. I feel the new wording is pretty cool and fine enough : )

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


[clang] [llvm] [PassBuilder] Add `ThinOrFullLTOPhase` to early simplication EP call backs (PR #114547)

2024-11-03 Thread Matt Arsenault via cfe-commits

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


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


[clang] 88823d0 - [clang][bytecode][NFC] Switch BitcastBuffer to SmallVector (#114677)

2024-11-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-11-03T11:16:59+01:00
New Revision: 88823d08ab850efc40cf20498a697f4532aad1fd

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

LOG: [clang][bytecode][NFC] Switch BitcastBuffer to SmallVector (#114677)

This is a little easier to work with since we are guaranteed that the
item type of the vector is byte sized and not something else.

Added: 


Modified: 
clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
clang/test/AST/ByteCode/builtin-bit-cast.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index fde2c6d9b11ac8..1acd49de307b96 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -83,39 +83,33 @@ static void swapBytes(std::byte *M, size_t N) {
 /// have indeterminate value.
 /// All offsets are in bits.
 struct BitcastBuffer {
-  llvm::BitVector Data;
+  size_t SizeInBits = 0;
+  llvm::SmallVector Data;
 
   BitcastBuffer() = default;
 
-  size_t size() const { return Data.size(); }
+  size_t size() const { return SizeInBits; }
 
-  const std::byte *data() const {
-unsigned NBytes = Data.size() / 8;
-unsigned BitVectorWordSize = sizeof(uintptr_t);
-bool FullWord = (NBytes % BitVectorWordSize == 0);
-
-// llvm::BitVector uses 64-bit fields internally, so when we have
-// fewer bytes than that, we need to compensate for that on
-// big endian hosts.
-unsigned DataPlus;
-if (llvm::sys::IsBigEndianHost)
-  DataPlus = BitVectorWordSize - (NBytes % BitVectorWordSize);
-else
-  DataPlus = 0;
-
-return reinterpret_cast(Data.getData().data()) +
-   (FullWord ? 0 : DataPlus);
-  }
+  const std::byte *data() const { return Data.data(); }
 
   bool allInitialized() const {
 // FIXME: Implement.
 return true;
   }
 
+  bool atByteBoundary() const { return (Data.size() * 8) == SizeInBits; }
+
+  void pushBit(bool Value) {
+if (atByteBoundary())
+  Data.push_back(std::byte{0});
+
+if (Value)
+  Data.back() |= (std::byte{1} << (SizeInBits % 8));
+++SizeInBits;
+  }
+
   void pushData(const std::byte *data, size_t BitOffset, size_t BitWidth,
 bool BigEndianTarget) {
-Data.reserve(BitOffset + BitWidth);
-
 bool OnlyFullBytes = BitWidth % 8 == 0;
 unsigned NBytes = BitWidth / 8;
 
@@ -125,7 +119,7 @@ struct BitcastBuffer {
   std::byte B =
   BigEndianTarget ? data[NBytes - OnlyFullBytes - I] : data[I];
   for (unsigned X = 0; X != 8; ++X) {
-Data.push_back(bitof(B, X));
+pushBit(bitof(B, X));
 ++BitsHandled;
   }
 }
@@ -137,7 +131,7 @@ struct BitcastBuffer {
 assert((BitWidth - BitsHandled) < 8);
 std::byte B = BigEndianTarget ? data[0] : data[NBytes];
 for (size_t I = 0, E = (BitWidth - BitsHandled); I != E; ++I) {
-  Data.push_back(bitof(B, I));
+  pushBit(bitof(B, I));
   ++BitsHandled;
 }
 
@@ -363,5 +357,8 @@ bool clang::interp::DoBitCast(InterpState &S, CodePtr OpPC, 
const Pointer &Ptr,
   HasIndeterminateBits = !Buffer.allInitialized();
   std::memcpy(Buff, Buffer.data(), BuffSize);
 
+  if (llvm::sys::IsBigEndianHost)
+swapBytes(Buff, BuffSize);
+
   return Success;
 }

diff  --git a/clang/test/AST/ByteCode/builtin-bit-cast.cpp 
b/clang/test/AST/ByteCode/builtin-bit-cast.cpp
index 0e86da9133b33d..c5380647c94aee 100644
--- a/clang/test/AST/ByteCode/builtin-bit-cast.cpp
+++ b/clang/test/AST/ByteCode/builtin-bit-cast.cpp
@@ -74,6 +74,17 @@ constexpr bool operator==(const struct bits& lhs, 
const struct bits((__int128_t)34));
 static_assert(check_round_trip<__int128_t>((__int128_t)-34));
+
+constexpr unsigned char OneBit[] = {
+  0x1, 0x0,  0x0,  0x0,
+  0x0, 0x0,  0x0,  0x0,
+  0x0, 0x0,  0x0,  0x0,
+  0x0, 0x0,  0x0,  0x0,
+};
+constexpr __int128_t One = 1;
+constexpr __int128_t Expected = One << 120;
+static_assert(__builtin_bit_cast(__int128_t, OneBit) == (LITTLE_END ? 1 : 
Expected));
+
 #endif
 
 



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


[clang] [clang][bytecode][NFC] Switch BitcastBuffer to SmallVector (PR #114677)

2024-11-03 Thread Timm Baeder via cfe-commits

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


[clang] [clang-tools-extra] [analyzer] Remove alpha.core.IdenticalExpr Checker (PR #114715)

2024-11-03 Thread via cfe-commits

llvmbot wrote:



@llvm/pr-subscribers-clang

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

Author: None (vabridgers)


Changes

This change removes the alpha.core.IdenticalExpr static analysis checker since 
it's checks are present in the clang-tidy checks misc-redundant-expression and 
bugprone-branch-clone. This check was implemented as a static analysis check 
using AST matching, and since alpha and duplicated in 2 clang-tidy checks may 
be removed.

---

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


8 Files Affected:

- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp (+547) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp 
(+1325) 
- (modified) clang/docs/ReleaseNotes.rst (+6) 
- (modified) clang/docs/analyzer/checkers.rst (-30) 
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (-4) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt (-1) 
- (removed) clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp (-520) 
- (removed) clang/test/Analysis/identical-expressions.cpp (-1564) 


``diff
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
index 42231746149f2c..c6af207d795c5d 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
@@ -1069,3 +1069,550 @@ namespace PR62693 {
 }
   }
 }
+
+// Start of identical expressions port
+int func(void)
+{
+  return 0;
+}
+
+int func2(void)
+{
+  return 0;
+}
+
+int funcParam(int a)
+{
+  return 0;
+}
+unsigned test_unsigned(unsigned a) {
+  unsigned b = 1;
+  a = a > 5 ? b : b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+  return a;
+}
+void test_signed() {
+  int a = 0;
+  a = a > 5 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_bool(bool a) {
+  a = a > 0 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_float() {
+  float a = 0;
+  float b = 0;
+  a = a > 5 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+const char *test_string() {
+  float a = 0;
+  return a > 5 ? "abc" : "abc";
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_unsigned_expr() {
+  unsigned a = 0;
+  unsigned b = 0;
+  a = a > 5 ? a+b : a+b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_signed_expr() {
+  int a = 0;
+  int b = 1;
+  a = a > 5 ? a+b : a+b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_bool_expr(bool a) {
+  bool b = 0;
+  a = a > 0 ? a&&b : a&&b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_unsigned_expr_negative() {
+  unsigned a = 0;
+  unsigned b = 0;
+  a = a > 5 ? a+b : b+a; // no warning
+}
+
+void test_signed_expr_negative() {
+  int a = 0;
+  int b = 1;
+  a = a > 5 ? b+a : a+b; // no warning
+}
+
+void test_bool_expr_negative(bool a) {
+  bool b = 0;
+  a = a > 0 ? a&&b : b&&a; // no warning
+}
+
+void test_float_expr_positive() {
+  float a = 0;
+  float b = 0;
+  a = a > 5 ? a+b : a+b; 
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_positive_func() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+func() : a+func(); 
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_negative_func() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+func() : a+func2(); // no warning
+}
+
+void test_expr_positive_funcParam() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+funcParam(b) : a+funcParam(b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_negative_funcParam() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+funcParam(a) : a+funcParam(b); // no warning
+}
+
+void test_expr_positive_inc() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a++ : a++;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warnin

[clang] [clang-tools-extra] [analyzer] Remove alpha.core.IdenticalExpr Checker (PR #114715)

2024-11-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-tools-extra

Author: None (vabridgers)


Changes

This change removes the alpha.core.IdenticalExpr static analysis checker since 
it's checks are present in the clang-tidy checks misc-redundant-expression and 
bugprone-branch-clone. This check was implemented as a static analysis check 
using AST matching, and since alpha and duplicated in 2 clang-tidy checks may 
be removed.

---

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


8 Files Affected:

- (modified) 
clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp (+547) 
- (modified) 
clang-tools-extra/test/clang-tidy/checkers/misc/redundant-expression.cpp 
(+1325) 
- (modified) clang/docs/ReleaseNotes.rst (+6) 
- (modified) clang/docs/analyzer/checkers.rst (-30) 
- (modified) clang/include/clang/StaticAnalyzer/Checkers/Checkers.td (-4) 
- (modified) clang/lib/StaticAnalyzer/Checkers/CMakeLists.txt (-1) 
- (removed) clang/lib/StaticAnalyzer/Checkers/IdenticalExprChecker.cpp (-520) 
- (removed) clang/test/Analysis/identical-expressions.cpp (-1564) 


``diff
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
index 42231746149f2c..c6af207d795c5d 100644
--- a/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
+++ b/clang-tools-extra/test/clang-tidy/checkers/bugprone/branch-clone.cpp
@@ -1069,3 +1069,550 @@ namespace PR62693 {
 }
   }
 }
+
+// Start of identical expressions port
+int func(void)
+{
+  return 0;
+}
+
+int func2(void)
+{
+  return 0;
+}
+
+int funcParam(int a)
+{
+  return 0;
+}
+unsigned test_unsigned(unsigned a) {
+  unsigned b = 1;
+  a = a > 5 ? b : b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+  return a;
+}
+void test_signed() {
+  int a = 0;
+  a = a > 5 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_bool(bool a) {
+  a = a > 0 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_float() {
+  float a = 0;
+  float b = 0;
+  a = a > 5 ? a : a;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+const char *test_string() {
+  float a = 0;
+  return a > 5 ? "abc" : "abc";
+  // CHECK-MESSAGES: :[[@LINE-1]]:16: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_unsigned_expr() {
+  unsigned a = 0;
+  unsigned b = 0;
+  a = a > 5 ? a+b : a+b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_signed_expr() {
+  int a = 0;
+  int b = 1;
+  a = a > 5 ? a+b : a+b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_bool_expr(bool a) {
+  bool b = 0;
+  a = a > 0 ? a&&b : a&&b;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_unsigned_expr_negative() {
+  unsigned a = 0;
+  unsigned b = 0;
+  a = a > 5 ? a+b : b+a; // no warning
+}
+
+void test_signed_expr_negative() {
+  int a = 0;
+  int b = 1;
+  a = a > 5 ? b+a : a+b; // no warning
+}
+
+void test_bool_expr_negative(bool a) {
+  bool b = 0;
+  a = a > 0 ? a&&b : b&&a; // no warning
+}
+
+void test_float_expr_positive() {
+  float a = 0;
+  float b = 0;
+  a = a > 5 ? a+b : a+b; 
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_positive_func() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+func() : a+func(); 
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_negative_func() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+func() : a+func2(); // no warning
+}
+
+void test_expr_positive_funcParam() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+funcParam(b) : a+funcParam(b);
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
identical true and false expressions [bugprone-branch-clone] 
+}
+
+void test_expr_negative_funcParam() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a+funcParam(a) : a+funcParam(b); // no warning
+}
+
+void test_expr_positive_inc() {
+  unsigned a = 0;
+  unsigned b = 1;
+  a = a > 5 ? a++ : a++;
+  // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: conditional operator with 
ide

[clang] 5b32c59 - [clang][bytecode] Implement bitcasts to floating-point values (#114485) (#114712)

2024-11-03 Thread via cfe-commits

Author: Timm Baeder
Date: 2024-11-03T19:42:26+01:00
New Revision: 5b32c5954b1d00435a2264f8d1bd1fd9db9cb022

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

LOG: [clang][bytecode] Implement bitcasts to floating-point values (#114485) 
(#114712)

This time I tested on big-endian hosts.

Added: 
clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp

Modified: 
clang/lib/AST/ByteCode/Interp.h
clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
clang/test/AST/ByteCode/builtin-bit-cast.cpp

Removed: 




diff  --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index ade6f7424b1fd6..153da14503a140 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -3062,7 +3062,17 @@ inline bool BitCast(InterpState &S, CodePtr OpPC, bool 
TargetIsUCharOrByte,
 return false;
 
   if constexpr (std::is_same_v) {
-assert(false && "Implement bitcasting to a floating type");
+assert(Sem);
+ptr
diff _t Offset = 0;
+
+if (llvm::sys::IsBigEndianHost) {
+  unsigned NumBits = llvm::APFloatBase::getSizeInBits(*Sem);
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= ResultBitWidth);
+  Offset = (ResultBitWidth - NumBits) / 8;
+}
+
+S.Stk.push(T::bitcastFromMemory(Buff.data() + Offset, *Sem));
   } else {
 assert(!Sem);
 S.Stk.push(T::bitcastFromMemory(Buff.data(), ResultBitWidth));

diff  --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 1acd49de307b96..8160707e8654d6 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -315,19 +315,34 @@ static bool readPointerToBuffer(const Context &Ctx, const 
Pointer &FromPtr,
   assert(false && "Implement casting to pointer types");
 
 CharUnits ObjectReprChars = ASTCtx.getTypeSizeInChars(P.getType());
-unsigned BitWidth;
-if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
-  BitWidth = FD->getBitWidthValue(ASTCtx);
-else
-  BitWidth = ASTCtx.toBits(ObjectReprChars);
-
+unsigned BitWidth = ASTCtx.toBits(ObjectReprChars);
 llvm::SmallVector Buff(ObjectReprChars.getQuantity());
-BITCAST_TYPE_SWITCH_WITH_FLOAT(T, {
-  T Val = P.deref();
-  Val.bitcastToMemory(Buff.data());
-});
-if (SwapData)
-  swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+// Work around floating point types that contain unused padding bytes.
+// This is really just `long double` on x86, which is the only
+// fundamental type with padding bytes.
+if (T == PT_Float) {
+  Floating &F = P.deref();
+  unsigned NumBits =
+  llvm::APFloatBase::getSizeInBits(F.getAPFloat().getSemantics());
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= (ObjectReprChars.getQuantity() * 8));
+  F.bitcastToMemory(Buff.data());
+  // Now, only (maybe) swap the actual size of the float, excluding the
+  // padding bits.
+  if (SwapData)
+swapBytes(Buff.data(), NumBits / 8);
+
+} else {
+  if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
+BitWidth = FD->getBitWidthValue(ASTCtx);
+
+  BITCAST_TYPE_SWITCH(T, {
+T Val = P.deref();
+Val.bitcastToMemory(Buff.data());
+  });
+  if (SwapData)
+swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+}
 
 if (BitWidth != (Buff.size() * 8) && BigEndianTarget) {
   Buffer.pushData(Buff.data() + (Buff.size() - 1 - (BitWidth / 8)),

diff  --git a/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp 
b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
new file mode 100644
index 00..230680ff3ced7d
--- /dev/null
+++ b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s
+
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s -fexperimental-new-constant-interpreter
+
+// both-no-

[clang] [clang][bytecode] Implement bitcasts to floating-point values (#114485) (PR #114712)

2024-11-03 Thread Timm Baeder via cfe-commits

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


[clang] [Tooling/Inclusion] Update std symbols mapping (PR #113612)

2024-11-03 Thread Vadim D. via cfe-commits

https://github.com/vvd170501 updated 
https://github.com/llvm/llvm-project/pull/113612

>From 1baa1c2aebd37da2f2ccc3918fa3425698860566 Mon Sep 17 00:00:00 2001
From: vvd170501 <36827317+vvd170...@users.noreply.github.com>
Date: Sat, 26 Oct 2024 00:17:26 +0300
Subject: [PATCH] Update std symbol mapping to v20240610; Update mapping
 generator; Move assertion to detect all ungrouped mappings

(rebase to test with updated StdSpecialSymbolMap.inc)
---
 .../Inclusions/Stdlib/StandardLibrary.cpp |  10 +-
 .../Inclusions/Stdlib/StdSpecialSymbolMap.inc |  47 ++-
 .../Inclusions/Stdlib/StdSymbolMap.inc| 116 ++
 .../include-mapping/cppreference_parser.py|  51 ++--
 4 files changed, 178 insertions(+), 46 deletions(-)

diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp 
b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
index 0832bcf66145fa..90c95d5cf60d86 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StandardLibrary.cpp
@@ -115,19 +115,19 @@ static int initialize(Lang Language) {
   NSLen = 0;
 }
 
-if (SymIndex >= 0 &&
-Mapping->SymbolNames[SymIndex].qualifiedName() == QName) {
-  // Not a new symbol, use the same index.
+if (SymIndex > 0) {
   assert(llvm::none_of(llvm::ArrayRef(Mapping->SymbolNames, SymIndex),
[&QName](const SymbolHeaderMapping::SymbolName &S) {
  return S.qualifiedName() == QName;
}) &&
  "The symbol has been added before, make sure entries in the .inc "
  "file are grouped by symbol name!");
-} else {
+}
+if (SymIndex < 0 ||
+Mapping->SymbolNames[SymIndex].qualifiedName() != QName) {
   // First symbol or new symbol, increment next available index.
   ++SymIndex;
-}
+} // Else use the same index.
 Mapping->SymbolNames[SymIndex] = {
 QName.data(), NSLen, static_cast(QName.size() - NSLen)};
 if (!HeaderName.empty())
diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc
index 4d466013eeac3f..8f20ce98152f08 100644
--- a/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc
+++ b/clang/lib/Tooling/Inclusions/Stdlib/StdSpecialSymbolMap.inc
@@ -232,6 +232,38 @@ SYMBOL(ssize, std::, )
 SYMBOL(ssize, std::, )
 SYMBOL(ssize, std::, )
 SYMBOL(ssize, std::, )
+// C++ [range.access.general]: ... the customization point objects
+// in [range.access] are available when the header  is included.
+// (see https://eel.is/c++draft/range.access#general)
+SYMBOL(begin, std::ranges::, )
+SYMBOL(begin, std::ranges::, )
+SYMBOL(end, std::ranges::, )
+SYMBOL(end, std::ranges::, )
+SYMBOL(cbegin, std::ranges::, )
+SYMBOL(cbegin, std::ranges::, )
+SYMBOL(cend, std::ranges::, )
+SYMBOL(cend, std::ranges::, )
+SYMBOL(rbegin, std::ranges::, )
+SYMBOL(rbegin, std::ranges::, )
+SYMBOL(rend, std::ranges::, )
+SYMBOL(rend, std::ranges::, )
+SYMBOL(crbegin, std::ranges::, )
+SYMBOL(crbegin, std::ranges::, )
+SYMBOL(crend, std::ranges::, )
+SYMBOL(crend, std::ranges::, )
+SYMBOL(size, std::ranges::, )
+SYMBOL(size, std::ranges::, )
+SYMBOL(ssize, std::ranges::, )
+SYMBOL(ssize, std::ranges::, )
+SYMBOL(empty, std::ranges::, )
+SYMBOL(empty, std::ranges::, )
+SYMBOL(data, std::ranges::, )
+SYMBOL(data, std::ranges::, )
+SYMBOL(cdata, std::ranges::, )
+SYMBOL(cdata, std::ranges::, )
+
+// Ignore specializations
+SYMBOL(hash, std::, )
 
 // Add headers for generic integer-type abs.
 // Ignore other variants (std::complex, std::valarray, std::intmax_t)
@@ -352,20 +384,23 @@ SYMBOL(get, std::, /*no headers*/)
 // providing the type.
 SYMBOL(make_error_code, std::, /*no headers*/)
 SYMBOL(make_error_condition, std::, /*no headers*/)
+// Similar to std::get, has variants for multiple containers
+// (vector, deque, list, etc.)
+SYMBOL(erase, std::, /*no headers*/)
+SYMBOL(erase_if, std::, /*no headers*/)
 
 // cppreference symbol index page was missing these symbols.
 // Remove them when the cppreference offline archive catches up.
-SYMBOL(index_sequence, std::, )
-SYMBOL(index_sequence_for, std::, )
-SYMBOL(make_index_sequence, std::, )
-SYMBOL(make_integer_sequence, std::, )
+SYMBOL(regular_invocable, std::, )
 
 // Symbols missing from the generated symbol map as reported by users.
 // Remove when the generator starts producing them.
-SYMBOL(make_any, std::, )
-SYMBOL(any_cast, std::, )
 SYMBOL(div, std::, )
 SYMBOL(abort, std::, )
+SYMBOL(atomic_wait, std::, )
+SYMBOL(atomic_wait_explicit, std::, )
+SYMBOL(move_backward, std::, )
+SYMBOL(month_weekday, std::chrono::, )
 
 SYMBOL(binary_search, std::ranges::, )
 SYMBOL(equal_range, std::ranges::, )
diff --git a/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc 
b/clang/lib/Tooling/Inclusions/Stdlib/StdSymbolMap.inc
index b46bd2e4d7a4b5..b4afd0228694ff 100644
--- a/clang/lib/Tooling

[clang] [clang][docs] Revise documentation for `__builtin_reduce_(max|min)`. (PR #114637)

2024-11-03 Thread via cfe-commits


@@ -745,12 +745,8 @@ Let ``VT`` be a vector type and ``ET`` the element type of 
``VT``.
 === 
== 
==
  NameOperation 
 Supported element types
 === 
== 
==
- ET __builtin_reduce_max(VT a)   return x or y, whichever is larger; 
If exactly one argument is integer and floating point types
- a NaN, return the other argument. If 
both arguments are NaNs,
- fmax() return a NaN.
- ET __builtin_reduce_min(VT a)   return x or y, whichever is smaller; 
If exactly one argument   integer and floating point types
- is a NaN, return the other argument. 
If both arguments are
- NaNs, fmax() return a NaN.
+ ET __builtin_reduce_max(VT a)   return the largest element of the 
vector.  integer and floating point types
+ ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. integer and floating point types

c8ef wrote:

LLVM LangRef states: "This instruction has the same comparison semantics as the 
‘llvm.maxnum.*’ intrinsic." Can I add a link to 
https://llvm.org/docs/LangRef.html#vector-reduction-intrinsics?

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


[clang] [clang][docs] Revise documentation for `__builtin_reduce_(max|min)`. (PR #114637)

2024-11-03 Thread via cfe-commits


@@ -745,12 +745,8 @@ Let ``VT`` be a vector type and ``ET`` the element type of 
``VT``.
 === 
== 
==
  NameOperation 
 Supported element types
 === 
== 
==
- ET __builtin_reduce_max(VT a)   return x or y, whichever is larger; 
If exactly one argument is integer and floating point types
- a NaN, return the other argument. If 
both arguments are NaNs,
- fmax() return a NaN.
- ET __builtin_reduce_min(VT a)   return x or y, whichever is smaller; 
If exactly one argument   integer and floating point types
- is a NaN, return the other argument. 
If both arguments are
- NaNs, fmax() return a NaN.
+ ET __builtin_reduce_max(VT a)   return the largest element of the 
vector.  integer and floating point types
+ ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. integer and floating point types

c8ef wrote:

Add pointers to the floating point min/max function.

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


[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)

2024-11-03 Thread Younan Zhang via cfe-commits


@@ -1109,12 +1109,50 @@ bool Sema::EnsureTemplateArgumentListConstraints(
   return false;
 }
 
-bool Sema::CheckInstantiatedFunctionTemplateConstraints(
+static bool CheckFunctionConstraintsWithoutInstantiation(
+Sema &SemaRef, SourceLocation PointOfInstantiation,
+FunctionTemplateDecl *Template, ArrayRef TemplateArgs,
+ConstraintSatisfaction &Satisfaction) {
+  SmallVector TemplateAC;
+  Template->getAssociatedConstraints(TemplateAC);
+  if (TemplateAC.empty()) {
+Satisfaction.IsSatisfied = true;
+return false;
+  }
+
+  LocalInstantiationScope Scope(SemaRef);
+
+  FunctionDecl *FD = Template->getTemplatedDecl();
+  // Collect the list of template arguments relative to the 'primary'
+  // template. We need the entire list, since the constraint is completely
+  // uninstantiated at this point.
+  MultiLevelTemplateArgumentList MLTAL =
+  SemaRef.getTemplateInstantiationArgs(FD, /*DC=*/nullptr,
+   /*Final=*/false,
+   /*Innermost=*/TemplateArgs,
+   /*RelativeToPrimary=*/true,
+   
/*ForConstraintInstantiation=*/true);
+
+  std::optional ThisScope;
+  if (auto *Method = dyn_cast(FD))
+ThisScope.emplace(SemaRef, /*Record=*/Method->getParent(),
+  /*ThisQuals=*/Method->getMethodQualifiers());

zyn0217 wrote:

I tried to contrive a case like

```cpp
template 
struct S {
  void foo() requires(__is_same_as(S&, decltype(*this))) {}
};

void g() {
  S().foo();
}
```

But there would still be no difference if we did the `CXXThisScopeRAII` things 
away. (It always compiles.)

Maybe I'm running out of ideas right now, so let's just preserve these "strange 
but plausible" things?

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


[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)

2024-11-03 Thread Younan Zhang via cfe-commits


@@ -1109,12 +1109,50 @@ bool Sema::EnsureTemplateArgumentListConstraints(
   return false;
 }
 
-bool Sema::CheckInstantiatedFunctionTemplateConstraints(
+static bool CheckFunctionConstraintsWithoutInstantiation(
+Sema &SemaRef, SourceLocation PointOfInstantiation,
+FunctionTemplateDecl *Template, ArrayRef TemplateArgs,
+ConstraintSatisfaction &Satisfaction) {
+  SmallVector TemplateAC;
+  Template->getAssociatedConstraints(TemplateAC);
+  if (TemplateAC.empty()) {
+Satisfaction.IsSatisfied = true;
+return false;
+  }
+
+  LocalInstantiationScope Scope(SemaRef);
+
+  FunctionDecl *FD = Template->getTemplatedDecl();
+  // Collect the list of template arguments relative to the 'primary'
+  // template. We need the entire list, since the constraint is completely
+  // uninstantiated at this point.
+  MultiLevelTemplateArgumentList MLTAL =
+  SemaRef.getTemplateInstantiationArgs(FD, /*DC=*/nullptr,
+   /*Final=*/false,
+   /*Innermost=*/TemplateArgs,
+   /*RelativeToPrimary=*/true,
+   
/*ForConstraintInstantiation=*/true);
+
+  std::optional ThisScope;

zyn0217 wrote:

Added a ContextRAII anyway

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread Luke Lau via cfe-commits


@@ -205,14 +288,60 @@ uses the function `buffer-file-name'."
   (delete-file temp-file)
   (when (buffer-name temp-buffer) (kill-buffer temp-buffer)
 
+;;;###autoload
+(defun clang-format-git-diffs (&optional style assume-file-name)

lukel97 wrote:

I think the term diff would be more consistent with existing emacs functions 
e.g. vc-diff, diff-delete-trailing-whitespace etc. 

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

https://github.com/goldsteinn updated 
https://github.com/llvm/llvm-project/pull/112792

>From 802764e879862541e205ba1a070824b71d2fef9a Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 17 Oct 2024 17:31:24 -0500
Subject: [PATCH 1/2] [emacs][clang-format] Add elisp API for clang-format on
 git diffs

New proposed function `clang-format-git-diffs`.

It is the same as calling `clang-format-region` on all diffs between
the content of a buffer-file and the content of the file at git
revision HEAD. This is essentially the same thing as:
`git-clang-format -f {filename}`
If the current buffer is saved.

The motivation is many project (LLVM included) both have code that is
non-compliant with there clang-format style and disallow unrelated
format diffs in PRs. This means users can't just run
`clang-format-buffer` on the buffer they are working on, and need to
manually go through all the regions by hand to get them
formatted. This is both an error prone and annoying workflow.
---
 clang/tools/clang-format/clang-format.el | 159 ---
 1 file changed, 144 insertions(+), 15 deletions(-)

diff --git a/clang/tools/clang-format/clang-format.el 
b/clang/tools/clang-format/clang-format.el
index fb943b7b722f8a..d3f874de41c550 100644
--- a/clang/tools/clang-format/clang-format.el
+++ b/clang/tools/clang-format/clang-format.el
@@ -146,18 +146,97 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--git-diffs-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Printout changes as only the line groups.
+   "--changed-group-format=--lines=%dF:%dL "
+   ;; Ignore unchanged content.
+   "--unchanged-group-format="
+   file-orig
+   file-new
+   )
+  )
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position)
+  (when (stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+  (unless (= status 0)
+(unless (= status 1)
+  (error "(diff returned unsuccessfully %s%s)" status stderr)))
+
+
+  (if (= status 0)
+  ;; Status == 0 -> no Diff.
+  nil
+(progn
+  ;; Split "--lines=:... --lines=:" output to
+  ;; a list for return.
+  (s-split
+   " "
+   (string-trim
+(buffer-substring-no-properties
+ (point-min) (point-max)
+
+(defun clang-format--git-diffs-get-git-head-file ()
+  "Returns a temporary file with the content of 'buffer-file-name' at
+git revision HEAD. If the current buffer is either not a file or not
+in a git repo, this results in an error"
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Need to be able to find version control (git) root
+  (unless (vc-root-dir)
+(error "File not known to git"))
+  ;; Need version control to in fact be git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")
+(error "Not using git"))
+
+  (let ((tmpfile-git-head (make-temp-file 
"clang-format-tmp-git-head-content")))
+;; Get filename relative to git root
+(let ((git-file-name (substring
+  (expand-file-name (buffer-file-name))
+  (string-width (expand-file-name (vc-root-dir)))
+  nil)))
+  (let ((status (call-process
+ "git"
+ nil
+ `(:file, tmpfile-git-head)
+ nil
+ "show" (concat "HEAD:" git-file-name)

[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

https://github.com/goldsteinn updated 
https://github.com/llvm/llvm-project/pull/112792

>From 802764e879862541e205ba1a070824b71d2fef9a Mon Sep 17 00:00:00 2001
From: Noah Goldstein 
Date: Thu, 17 Oct 2024 17:31:24 -0500
Subject: [PATCH 1/3] [emacs][clang-format] Add elisp API for clang-format on
 git diffs

New proposed function `clang-format-git-diffs`.

It is the same as calling `clang-format-region` on all diffs between
the content of a buffer-file and the content of the file at git
revision HEAD. This is essentially the same thing as:
`git-clang-format -f {filename}`
If the current buffer is saved.

The motivation is many project (LLVM included) both have code that is
non-compliant with there clang-format style and disallow unrelated
format diffs in PRs. This means users can't just run
`clang-format-buffer` on the buffer they are working on, and need to
manually go through all the regions by hand to get them
formatted. This is both an error prone and annoying workflow.
---
 clang/tools/clang-format/clang-format.el | 159 ---
 1 file changed, 144 insertions(+), 15 deletions(-)

diff --git a/clang/tools/clang-format/clang-format.el 
b/clang/tools/clang-format/clang-format.el
index fb943b7b722f8a..d3f874de41c550 100644
--- a/clang/tools/clang-format/clang-format.el
+++ b/clang/tools/clang-format/clang-format.el
@@ -146,18 +146,97 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
-
+(defun clang-format--git-diffs-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Printout changes as only the line groups.
+   "--changed-group-format=--lines=%dF:%dL "
+   ;; Ignore unchanged content.
+   "--unchanged-group-format="
+   file-orig
+   file-new
+   )
+  )
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position)
+  (when (stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+  (unless (= status 0)
+(unless (= status 1)
+  (error "(diff returned unsuccessfully %s%s)" status stderr)))
+
+
+  (if (= status 0)
+  ;; Status == 0 -> no Diff.
+  nil
+(progn
+  ;; Split "--lines=:... --lines=:" output to
+  ;; a list for return.
+  (s-split
+   " "
+   (string-trim
+(buffer-substring-no-properties
+ (point-min) (point-max)
+
+(defun clang-format--git-diffs-get-git-head-file ()
+  "Returns a temporary file with the content of 'buffer-file-name' at
+git revision HEAD. If the current buffer is either not a file or not
+in a git repo, this results in an error"
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Need to be able to find version control (git) root
+  (unless (vc-root-dir)
+(error "File not known to git"))
+  ;; Need version control to in fact be git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")
+(error "Not using git"))
+
+  (let ((tmpfile-git-head (make-temp-file 
"clang-format-tmp-git-head-content")))
+;; Get filename relative to git root
+(let ((git-file-name (substring
+  (expand-file-name (buffer-file-name))
+  (string-width (expand-file-name (vc-root-dir)))
+  nil)))
+  (let ((status (call-process
+ "git"
+ nil
+ `(:file, tmpfile-git-head)
+ nil
+ "show" (concat "HEAD:" git-file-name)

[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

goldsteinn wrote:

NB: The new API is 'clang-format-vc-diff'. I will update commit title when 
merging.

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


[clang] [clang][bytecode] Implement bitcasts to floating-point values (#114485) (PR #114712)

2024-11-03 Thread Timm Baeder via cfe-commits

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

This time I tested on big-endian hosts.

>From 80bf7b638711a93ee2b9fd86dc5b6139f0f63fee Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 2 Nov 2024 01:56:47 +0100
Subject: [PATCH] [clang][bytecode] Implement bitcasts to floating-point values
 (#114485)

This time I tested on big-endian hosts.
---
 clang/lib/AST/ByteCode/Interp.h   | 12 ++-
 .../lib/AST/ByteCode/InterpBuiltinBitCast.cpp | 39 +---
 .../ByteCode/builtin-bit-cast-long-double.cpp | 89 +++
 clang/test/AST/ByteCode/builtin-bit-cast.cpp  |  4 +-
 4 files changed, 130 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp

diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index ade6f7424b1fd6..153da14503a140 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -3062,7 +3062,17 @@ inline bool BitCast(InterpState &S, CodePtr OpPC, bool 
TargetIsUCharOrByte,
 return false;
 
   if constexpr (std::is_same_v) {
-assert(false && "Implement bitcasting to a floating type");
+assert(Sem);
+ptrdiff_t Offset = 0;
+
+if (llvm::sys::IsBigEndianHost) {
+  unsigned NumBits = llvm::APFloatBase::getSizeInBits(*Sem);
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= ResultBitWidth);
+  Offset = (ResultBitWidth - NumBits) / 8;
+}
+
+S.Stk.push(T::bitcastFromMemory(Buff.data() + Offset, *Sem));
   } else {
 assert(!Sem);
 S.Stk.push(T::bitcastFromMemory(Buff.data(), ResultBitWidth));
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 1acd49de307b96..8160707e8654d6 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -315,19 +315,34 @@ static bool readPointerToBuffer(const Context &Ctx, const 
Pointer &FromPtr,
   assert(false && "Implement casting to pointer types");
 
 CharUnits ObjectReprChars = ASTCtx.getTypeSizeInChars(P.getType());
-unsigned BitWidth;
-if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
-  BitWidth = FD->getBitWidthValue(ASTCtx);
-else
-  BitWidth = ASTCtx.toBits(ObjectReprChars);
-
+unsigned BitWidth = ASTCtx.toBits(ObjectReprChars);
 llvm::SmallVector Buff(ObjectReprChars.getQuantity());
-BITCAST_TYPE_SWITCH_WITH_FLOAT(T, {
-  T Val = P.deref();
-  Val.bitcastToMemory(Buff.data());
-});
-if (SwapData)
-  swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+// Work around floating point types that contain unused padding bytes.
+// This is really just `long double` on x86, which is the only
+// fundamental type with padding bytes.
+if (T == PT_Float) {
+  Floating &F = P.deref();
+  unsigned NumBits =
+  llvm::APFloatBase::getSizeInBits(F.getAPFloat().getSemantics());
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= (ObjectReprChars.getQuantity() * 8));
+  F.bitcastToMemory(Buff.data());
+  // Now, only (maybe) swap the actual size of the float, excluding the
+  // padding bits.
+  if (SwapData)
+swapBytes(Buff.data(), NumBits / 8);
+
+} else {
+  if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
+BitWidth = FD->getBitWidthValue(ASTCtx);
+
+  BITCAST_TYPE_SWITCH(T, {
+T Val = P.deref();
+Val.bitcastToMemory(Buff.data());
+  });
+  if (SwapData)
+swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+}
 
 if (BitWidth != (Buff.size() * 8) && BigEndianTarget) {
   Buffer.pushData(Buff.data() + (Buff.size() - 1 - (BitWidth / 8)),
diff --git a/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp 
b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
new file mode 100644
index 00..c80c6fe1f67aa5
--- /dev/null
+++ b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
@@ -0,0 +1,89 @@
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only %s
+
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fs

[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

goldsteinn wrote:

Current return from `package-lint`:

```
3 issues found:

1:0: error: Package should have a Homepage or URL header.
1:60: warning: You should depend on (emacs "24.1") if you need lexical-binding.
223:19: error: You should depend on (emacs "25.1") if you need `vc-root-dir'.
```

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


[clang-tools-extra] [clang-tidy] Improved readability redundant casting with enums (PR #111424)

2024-11-03 Thread Félix-Antoine Constantin via cfe-commits

https://github.com/felix642 updated 
https://github.com/llvm/llvm-project/pull/111424

From a786f626beb418cf6b8847c6250f0490b60affdb Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Mon, 7 Oct 2024 15:27:36 -0400
Subject: [PATCH 1/4] [clang-tidy] Improved readability redundant casting with
 enums

Fixed false negatives with readability-redundant-casting when the underlying
types are the same and the option IgnoreTypeAliases is set to true.

Fixes #37
---
 .../readability/RedundantCastingCheck.cpp |  9 -
 clang-tools-extra/docs/ReleaseNotes.rst   |  6 ++
 .../readability/redundant-casting.cpp | 20 +++
 3 files changed, 34 insertions(+), 1 deletion(-)

diff --git a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp 
b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
index b9ff0e81cbc522..612a5a91593359 100644
--- a/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
+++ b/clang-tools-extra/clang-tidy/readability/RedundantCastingCheck.cpp
@@ -40,8 +40,15 @@ static bool areTypesEqual(QualType S, QualType D) {
 
 static bool areTypesEqual(QualType TypeS, QualType TypeD,
   bool IgnoreTypeAliases) {
-  const QualType CTypeS = TypeS.getCanonicalType();
   const QualType CTypeD = TypeD.getCanonicalType();
+
+  QualType CTypeS;
+  const auto *const EnumTypeS = TypeS->getAs();
+  if (EnumTypeS != nullptr && !EnumTypeS->getDecl()->isScoped())
+CTypeS = EnumTypeS->getDecl()->getIntegerType();
+  else
+CTypeS = TypeS.getCanonicalType();
+
   if (CTypeS != CTypeD)
 return false;
 
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 3e051c7db6adcc..32bae30821092f 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -222,6 +222,12 @@ Changes in existing checks
   by adding the option `UseUpperCaseLiteralSuffix` to select the
   case of the literal suffix in fixes.
 
+- Improved :doc:`readability-redundant-casting
+  ` check by fixing
+  false negatives related to ``enum`` when setting ``IgnoreTypeAliases``
+  to true.
+
+
 - Improved :doc:`readability-redundant-smartptr-get
   ` check to
   remove `->`, when redundant `get()` is removed.
diff --git 
a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp 
b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
index 30cac6bd5cca06..ed49f32364cba8 100644
--- 
a/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
+++ 
b/clang-tools-extra/test/clang-tidy/checkers/readability/redundant-casting.cpp
@@ -221,3 +221,23 @@ void testRedundantDependentNTTPCasting() {
   // CHECK-MESSAGES: :[[@LINE-4]]:25: note: source type originates from 
referencing this non-type template parameter
   // CHECK-FIXES: {{^}}  T a = V;
 }
+
+enum E1 : char {};
+enum class E2 : char {};
+enum E3 {};
+
+void testEnum(E1 e1, E2 e2, E3 e3){
+  char a = static_cast(e1);
+  // CHECK-MESSAGES-ALIASES: :[[@LINE-1]]:12: warning: redundant explicit 
casting to the same type 'char' as the sub-expression, remove this casting 
[readability-redundant-casting]
+  // CHECK-MESSAGES-ALIASES: :[[@LINE-3]]:18: note: source type originates 
from referencing this parameter
+  // CHECK-FIXES-ALIASES: {{^}}  char a = e1;
+
+  unsigned int d = static_cast(e3);
+  // CHECK-MESSAGES-ALIASES: :[[@LINE-1]]:20: warning: redundant explicit 
casting to the same type 'unsigned int' as the sub-expression, remove this 
casting [readability-redundant-casting]
+  // CHECK-MESSAGES-ALIASES: :[[@LINE-8]]:32: note: source type originates 
from referencing this parameter
+  // CHECK-FIXES-ALIASES: {{^}}  unsigned int d = e3;
+
+  char b = static_cast(e2);
+  char c = static_cast(e3);
+  E1 e = static_cast('0');
+}

From af97ade285dbb590763173b0d82b0edff9a9c5e9 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?F=C3=A9lix-Antoine=20Constantin?=
 
Date: Sat, 2 Nov 2024 12:02:30 -0400
Subject: [PATCH 2/4] fixup! [clang-tidy] Improved readability redundant
 casting with enums

Code Review & Removed non-portable test
---
 clang-tools-extra/docs/ReleaseNotes.rst  | 4 ++--
 .../checkers/readability/redundant-casting.cpp   | 9 +
 2 files changed, 3 insertions(+), 10 deletions(-)

diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 32bae30821092f..cbb2880be6bfe9 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -224,8 +224,8 @@ Changes in existing checks
 
 - Improved :doc:`readability-redundant-casting
   ` check by fixing
-  false negatives related to ``enum`` when setting ``IgnoreTypeAliases``
-  to true.
+  false negatives related to ``enum`` when setting `IgnoreTypeAliases`
+  to `true`.
 
 
 - Improved :doc:`readability-redundant-smartptr-get
diff --git 
a/clang-tools-extra/test/clang-tidy

[clang] [clang][bytecode] Implement bitcasts to floating-point values (#114485) (PR #114712)

2024-11-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Timm Baeder (tbaederr)


Changes

This time I tested on big-endian hosts.

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


4 Files Affected:

- (modified) clang/lib/AST/ByteCode/Interp.h (+11-1) 
- (modified) clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp (+27-12) 
- (added) clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp (+89) 
- (modified) clang/test/AST/ByteCode/builtin-bit-cast.cpp (+3-1) 


``diff
diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index ade6f7424b1fd6..153da14503a140 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -3062,7 +3062,17 @@ inline bool BitCast(InterpState &S, CodePtr OpPC, bool 
TargetIsUCharOrByte,
 return false;
 
   if constexpr (std::is_same_v) {
-assert(false && "Implement bitcasting to a floating type");
+assert(Sem);
+ptrdiff_t Offset = 0;
+
+if (llvm::sys::IsBigEndianHost) {
+  unsigned NumBits = llvm::APFloatBase::getSizeInBits(*Sem);
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= ResultBitWidth);
+  Offset = (ResultBitWidth - NumBits) / 8;
+}
+
+S.Stk.push(T::bitcastFromMemory(Buff.data() + Offset, *Sem));
   } else {
 assert(!Sem);
 S.Stk.push(T::bitcastFromMemory(Buff.data(), ResultBitWidth));
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 1acd49de307b96..8160707e8654d6 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -315,19 +315,34 @@ static bool readPointerToBuffer(const Context &Ctx, const 
Pointer &FromPtr,
   assert(false && "Implement casting to pointer types");
 
 CharUnits ObjectReprChars = ASTCtx.getTypeSizeInChars(P.getType());
-unsigned BitWidth;
-if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
-  BitWidth = FD->getBitWidthValue(ASTCtx);
-else
-  BitWidth = ASTCtx.toBits(ObjectReprChars);
-
+unsigned BitWidth = ASTCtx.toBits(ObjectReprChars);
 llvm::SmallVector Buff(ObjectReprChars.getQuantity());
-BITCAST_TYPE_SWITCH_WITH_FLOAT(T, {
-  T Val = P.deref();
-  Val.bitcastToMemory(Buff.data());
-});
-if (SwapData)
-  swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+// Work around floating point types that contain unused padding bytes.
+// This is really just `long double` on x86, which is the only
+// fundamental type with padding bytes.
+if (T == PT_Float) {
+  Floating &F = P.deref();
+  unsigned NumBits =
+  llvm::APFloatBase::getSizeInBits(F.getAPFloat().getSemantics());
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= (ObjectReprChars.getQuantity() * 8));
+  F.bitcastToMemory(Buff.data());
+  // Now, only (maybe) swap the actual size of the float, excluding the
+  // padding bits.
+  if (SwapData)
+swapBytes(Buff.data(), NumBits / 8);
+
+} else {
+  if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
+BitWidth = FD->getBitWidthValue(ASTCtx);
+
+  BITCAST_TYPE_SWITCH(T, {
+T Val = P.deref();
+Val.bitcastToMemory(Buff.data());
+  });
+  if (SwapData)
+swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+}
 
 if (BitWidth != (Buff.size() * 8) && BigEndianTarget) {
   Buffer.pushData(Buff.data() + (Buff.size() - 1 - (BitWidth / 8)),
diff --git a/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp 
b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
new file mode 100644
index 00..c80c6fe1f67aa5
--- /dev/null
+++ b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
@@ -0,0 +1,89 @@
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only %s
+
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only %s 
-fexperimental-new-constant-interpreter
+
+// both-no-diagnostics
+
+typedef decltype(nullptr) nullptr_t;
+typedef __INTPTR_TYP

[clang] [libcxx] [Clang] Implement CWG2369 "Ordering between constraints and substitution" (PR #102857)

2024-11-03 Thread Younan Zhang via cfe-commits


@@ -4008,6 +3996,38 @@ TemplateDeductionResult 
Sema::FinishTemplateArgumentDeduction(
 Owner = FunctionTemplate->getLexicalDeclContext();
   FunctionDecl *FD = FunctionTemplate->getTemplatedDecl();
 
+  // C++20 [temp.deduct.general]p5: (CWG2369)
+  // If the function template has associated constraints, those constraints are
+  // checked for satisfaction. If the constraints are not satisfied, type
+  // deduction fails.
+  // FIXME: We haven't implemented CWG2369 for lambdas yet, because we need
+  // to figure out how to instantiate lambda captures to the scope without
+  // first instantiating the lambda.
+  bool IsLambda = isLambdaCallOperator(FD) || isLambdaConversionOperator(FD);
+  if (!IsLambda && !IsIncomplete) {
+if (CheckFunctionTemplateConstraints(
+Info.getLocation(),
+FunctionTemplate->getCanonicalDecl()->getTemplatedDecl(),
+CanonicalBuilder, Info.AssociatedConstraintsSatisfaction))
+  return TemplateDeductionResult::MiscellaneousDeductionFailure;
+if (!Info.AssociatedConstraintsSatisfaction.IsSatisfied) {
+  Info.reset(Info.takeSugared(),
+ TemplateArgumentList::CreateCopy(Context, CanonicalBuilder));

zyn0217 wrote:

(Frankly these lines are also copied from the previous failure handling)

I *guess* the instantiated concept-related nodes that were created during the 
checking would use the TemplateArgumentLists created on the ASTContext, or 
rather they would take ownership of the TemplateArgumentList. So, in order for 
the pilfered argument lists to work for other clients of TemplateDeductionInfo, 
we have to make a copy of the list.

(I saw the patch that tried to preserve sugars in concepts turn this line into 
"copy sugared arguments, but do nothing for canonical arguments")

But I'm not entirely sure of such deduction things, so probably @mizvekov would 
correct my understanding in some way.

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


[clang] [clang][bytecode][NFC] Switch BitcastBuffer to SmallVector (PR #114677)

2024-11-03 Thread LLVM Continuous Integration via cfe-commits

llvm-ci wrote:

LLVM Buildbot has detected a new failure on builder 
`sanitizer-x86_64-linux-bootstrap-asan` running on `sanitizer-buildbot1` while 
building `clang` at step 2 "annotate".

Full details are available at: 
https://lab.llvm.org/buildbot/#/builders/52/builds/3429


Here is the relevant piece of the build log for the reference

```
Step 2 (annotate) failure: 'python 
../sanitizer_buildbot/sanitizers/zorg/buildbot/builders/sanitizers/buildbot_selector.py'
 (failure)
...
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using lld-link: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/lld-link
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using ld64.lld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/ld64.lld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/llvm/config.py:506:
 note: using wasm-ld: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/wasm-ld
llvm-lit: 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/llvm/utils/lit/lit/main.py:72:
 note: The test suite configuration requested an individual test timeout of 0 
seconds but a timeout of 900 seconds was requested on the command line. Forcing 
timeout to be 900 seconds.
-- Testing: 86841 of 86842 tests, 88 workers --
Testing:  0.. 10
FAIL: Clang :: Interpreter/inline-virtual.cpp (12584 of 86841)
 TEST 'Clang :: Interpreter/inline-virtual.cpp' FAILED 

Exit Code: 1

Command Output (stderr):
--
RUN: at line 6: cat 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
 | 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl
 -Xcc -fno-rtti -Xcc -fno-sized-deallocation  | 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
+ cat 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl
 -Xcc -fno-rtti -Xcc -fno-sized-deallocation
RUN: at line 8: cat 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
 | 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl
 -Xcc -fno-rtti -Xcc -fno-sized-deallocation  -Xcc -O2 | 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/FileCheck
 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
+ 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm_build_asan/bin/clang-repl
 -Xcc -fno-rtti -Xcc -fno-sized-deallocation -Xcc -O2
+ cat 
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp
JIT session error: In graph incr_module_25-jitted-objectbuffer, section 
.text.startup: relocation target "_ZTV1A" at address 0x74a45701e000 is out of 
range of Delta32 fixup at 0x70a45510f013 ( @ 0x70a45510f010 + 
0x3)
error: Failed to materialize symbols: { (main, { 
__orc_init_func.incr_module_25, a2, $.incr_module_25.__inits.0 }) }
error: Failed to materialize symbols: { (main, { __orc_init_func.incr_module_25 
}) }
/home/b/sanitizer-x86_64-linux-bootstrap-asan/build/llvm-project/clang/test/Interpreter/inline-virtual.cpp:26:11:
 error: CHECK: expected string not found in input
// CHECK: ~A(2)
 

[clang] [clang][docs] Revise documentation for `__builtin_reduce_(max|min)`. (PR #114637)

2024-11-03 Thread via cfe-commits

https://github.com/c8ef updated https://github.com/llvm/llvm-project/pull/114637

>From 13d9d0771b666c5ba2262004f45dcbe34e6fd893 Mon Sep 17 00:00:00 2001
From: c8ef 
Date: Sat, 2 Nov 2024 11:53:54 +0800
Subject: [PATCH 1/2] Update LanguageExtensions.rst

---
 clang/docs/LanguageExtensions.rst | 8 ++--
 1 file changed, 2 insertions(+), 6 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 10232ff41da15a..b7676bab623ef8 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -745,12 +745,8 @@ Let ``VT`` be a vector type and ``ET`` the element type of 
``VT``.
 === 
== 
==
  NameOperation 
 Supported element types
 === 
== 
==
- ET __builtin_reduce_max(VT a)   return x or y, whichever is larger; 
If exactly one argument is integer and floating point types
- a NaN, return the other argument. If 
both arguments are NaNs,
- fmax() return a NaN.
- ET __builtin_reduce_min(VT a)   return x or y, whichever is smaller; 
If exactly one argument   integer and floating point types
- is a NaN, return the other argument. 
If both arguments are
- NaNs, fmax() return a NaN.
+ ET __builtin_reduce_max(VT a)   return the largest element of the 
vector.  integer and floating point types
+ ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. integer and floating point types
  ET __builtin_reduce_add(VT a)   \+
 integer types
  ET __builtin_reduce_mul(VT a)   \*
 integer types
  ET __builtin_reduce_and(VT a)   & 
 integer types

>From 2a7cb73cb24cc3c32a3fe14401b7051db8bad8a2 Mon Sep 17 00:00:00 2001
From: c8ef 
Date: Sun, 3 Nov 2024 20:28:01 +0800
Subject: [PATCH 2/2] Update LanguageExtensions.rst

---
 clang/docs/LanguageExtensions.rst | 8 ++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index b7676bab623ef8..e4157d59e3892c 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -745,8 +745,12 @@ Let ``VT`` be a vector type and ``ET`` the element type of 
``VT``.
 === 
== 
==
  NameOperation 
 Supported element types
 === 
== 
==
- ET __builtin_reduce_max(VT a)   return the largest element of the 
vector.  integer and floating point types
- ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. integer and floating point types
+ ET __builtin_reduce_max(VT a)   return the largest element of the 
vector. If the element type is   integer and floating point types
+ floating point, this function has the 
same comparison semantics as 
+ ``__builtin_reduce_maximum``.
+ ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. If the element type is  integer and floating point types
+ floating point, this function has the 
same comparison semantics as 
+ ``__builtin_reduce_minimum``.
  ET __builtin_reduce_add(VT a)   \+
 integer types
  ET __builtin_reduce_mul(VT a)   \*
 integer types
  ET __builtin_reduce_and(VT a)   & 
 integer types

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


[clang] [clang][docs] Revise documentation for `__builtin_reduce_(max|min)`. (PR #114637)

2024-11-03 Thread Simon Pilgrim via cfe-commits


@@ -745,12 +745,8 @@ Let ``VT`` be a vector type and ``ET`` the element type of 
``VT``.
 === 
== 
==
  NameOperation 
 Supported element types
 === 
== 
==
- ET __builtin_reduce_max(VT a)   return x or y, whichever is larger; 
If exactly one argument is integer and floating point types
- a NaN, return the other argument. If 
both arguments are NaNs,
- fmax() return a NaN.
- ET __builtin_reduce_min(VT a)   return x or y, whichever is smaller; 
If exactly one argument   integer and floating point types
- is a NaN, return the other argument. 
If both arguments are
- NaNs, fmax() return a NaN.
+ ET __builtin_reduce_max(VT a)   return the largest element of the 
vector.  integer and floating point types
+ ET __builtin_reduce_min(VT a)   return the smallest element of the 
vector. integer and floating point types

RKSimon wrote:

Please can you add back the NaN semantics - AFAICT they should always return 
the largest/smallest non-NAN value if any vector element is non-NAN, otherwise 
it could return any of the NAN values in the (all NAN) vector. There might be a 
better way of phrasing that..

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits


@@ -132,18 +132,97 @@ is a zero-based file offset, assuming ‘utf-8-unix’ 
coding."
 (lambda (byte &optional _quality _coding-system)
   (byte-to-position (1+ byte)
 
-;;;###autoload
-(defun clang-format-region (start end &optional style assume-file-name)
-  "Use clang-format to format the code between START and END according to 
STYLE.
-If called interactively uses the region or the current statement if there is no
-no active region. If no STYLE is given uses `clang-format-style'. Use
-ASSUME-FILE-NAME to locate a style config file, if no ASSUME-FILE-NAME is given
-uses the function `buffer-file-name'."
-  (interactive
-   (if (use-region-p)
-   (list (region-beginning) (region-end))
- (list (point) (point
+(defun clang-format--git-diffs-get-diff-lines (file-orig file-new)
+  "Return all line regions that contain diffs between FILE-ORIG and
+FILE-NEW.  If there is no diff 'nil' is returned. Otherwise the
+return is a 'list' of lines in the format '--lines=:'
+which can be passed directly to 'clang-format'"
+  ;; Temporary buffer for output of diff.
+  (with-temp-buffer
+(let ((status (call-process
+   "diff"
+   nil
+   (current-buffer)
+   nil
+   ;; Binary diff has different behaviors that we
+   ;; aren't interested in.
+   "-a"
+   ;; Printout changes as only the line groups.
+   "--changed-group-format=--lines=%dF:%dL "
+   ;; Ignore unchanged content.
+   "--unchanged-group-format="
+   file-orig
+   file-new
+   )
+  )
+  (stderr (concat (if (zerop (buffer-size)) "" ": ")
+  (buffer-substring-no-properties
+   (point-min) (line-end-position)
+  (when (stringp status)
+(error "(diff killed by signal %s%s)" status stderr))
+  (unless (= status 0)
+(unless (= status 1)
+  (error "(diff returned unsuccessfully %s%s)" status stderr)))
+
+
+  (if (= status 0)
+  ;; Status == 0 -> no Diff.
+  nil
+(progn
+  ;; Split "--lines=:... --lines=:" output to
+  ;; a list for return.
+  (s-split
+   " "
+   (string-trim
+(buffer-substring-no-properties
+ (point-min) (point-max)
+
+(defun clang-format--git-diffs-get-git-head-file ()
+  "Returns a temporary file with the content of 'buffer-file-name' at
+git revision HEAD. If the current buffer is either not a file or not
+in a git repo, this results in an error"
+  ;; Needs current buffer to be a file
+  (unless (buffer-file-name)
+(error "Buffer is not visiting a file"))
+  ;; Need to be able to find version control (git) root
+  (unless (vc-root-dir)
+(error "File not known to git"))
+  ;; Need version control to in fact be git
+  (unless (string-equal (vc-backend (buffer-file-name)) "Git")
+(error "Not using git"))
+
+  (let ((tmpfile-git-head (make-temp-file 
"clang-format-tmp-git-head-content")))

goldsteinn wrote:

`with-temp-file` doesn't quite work here, V2 I just wrap the thing in an 
`unwind-protect` and delete the temp files in it.

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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits


@@ -205,14 +288,60 @@ uses the function `buffer-file-name'."
   (delete-file temp-file)
   (when (buffer-name temp-buffer) (kill-buffer temp-buffer)
 
+;;;###autoload
+(defun clang-format-git-diffs (&optional style assume-file-name)

goldsteinn wrote:

The reason I chose `diffs` was to indicate it wasn't just the diff at point or 
something, but Ill rename `clang-format-vc-diff`

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


[clang] [Clang] update reasoned delete diagnostic kind to use Extension, making it pedantic only (PR #114713)

2024-11-03 Thread Oleksandr T. via cfe-commits

https://github.com/a-tarasyuk created 
https://github.com/llvm/llvm-project/pull/114713

Fixes #109311

--- 

https://github.com/llvm/llvm-project/issues/109311#issuecomment-2422963686

>From c07fa270194eadde3ccecab368b2225702fc2e63 Mon Sep 17 00:00:00 2001
From: Oleksandr T 
Date: Sun, 3 Nov 2024 19:22:56 +0200
Subject: [PATCH] [Clang] update reasoned delete diagnostic kind to use
 Extension, making it pedantic only

---
 clang/docs/ReleaseNotes.rst   |  2 ++
 clang/include/clang/Basic/DiagnosticParseKinds.td |  2 +-
 clang/test/Parser/cxx2c-delete-with-message.cpp   | 13 -
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1372e49dfac03c..3db2aa472902bc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -464,6 +464,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses ``[[deprecated]]`` attribute usage on local variables 
(#GH90073).
 
+- Clang now diagnoses misused reasoned ``delete("reason")`` warnings only in 
pedantic mode. (#GH109311).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 78510e61a639fa..6fbe874c5e6425 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -971,7 +971,7 @@ def warn_cxx98_compat_defaulted_deleted_function : Warning<
   "%select{defaulted|deleted}0 function definitions are incompatible with 
C++98">,
   InGroup, DefaultIgnore;
 
-def ext_delete_with_message : ExtWarn<
+def ext_delete_with_message : Extension<
   "'= delete' with a message is a C++2c extension">, InGroup;
 def warn_cxx23_delete_with_message : Warning<
   "'= delete' with a message is incompatible with C++ standards before C++2c">,
diff --git a/clang/test/Parser/cxx2c-delete-with-message.cpp 
b/clang/test/Parser/cxx2c-delete-with-message.cpp
index 1767a080a7dcd8..5796c548632ae4 100644
--- a/clang/test/Parser/cxx2c-delete-with-message.cpp
+++ b/clang/test/Parser/cxx2c-delete-with-message.cpp
@@ -1,7 +1,17 @@
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify=expected,pre26 -pedantic %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify=expected 
-DTEST_NON_PEDANTIC %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify=expected,pre26 -pedantic %s
 // RUN: %clang_cc1 -std=c++2c -fsyntax-only -verify=expected,compat 
-Wpre-c++26-compat %s
 // RUN: %clang_cc1 -std=c++2c -fsyntax-only -verify %s
 
+#ifdef DTEST_NON_PEDANTIC
+namespace GH109311 {
+void f() = delete
+#if __cpp_deleted_function >= 202403L
+("reason") // ok
+#endif
+;
+}
+#else
 struct S {
   void a() = delete;
   void b() = delete(; // expected-error {{expected string literal}} 
expected-error {{expected ')'}} expected-note {{to match this '('}}
@@ -49,3 +59,4 @@ struct C {
   U f = delete ("hello"); // expected-error {{cannot delete expression of type 
'const char[6]'}}
 };
 }
+#endif
\ No newline at end of file

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


[clang] [Clang] update reasoned delete diagnostic kind to use Extension, making it pedantic only (PR #114713)

2024-11-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Oleksandr T. (a-tarasyuk)


Changes

Fixes #109311

--- 

https://github.com/llvm/llvm-project/issues/109311#issuecomment-2422963686

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


3 Files Affected:

- (modified) clang/docs/ReleaseNotes.rst (+2) 
- (modified) clang/include/clang/Basic/DiagnosticParseKinds.td (+1-1) 
- (modified) clang/test/Parser/cxx2c-delete-with-message.cpp (+12-1) 


``diff
diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1372e49dfac03c..3db2aa472902bc 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -464,6 +464,8 @@ Improvements to Clang's diagnostics
 
 - Clang now diagnoses ``[[deprecated]]`` attribute usage on local variables 
(#GH90073).
 
+- Clang now diagnoses misused reasoned ``delete("reason")`` warnings only in 
pedantic mode. (#GH109311).
+
 Improvements to Clang's time-trace
 --
 
diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index 78510e61a639fa..6fbe874c5e6425 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -971,7 +971,7 @@ def warn_cxx98_compat_defaulted_deleted_function : Warning<
   "%select{defaulted|deleted}0 function definitions are incompatible with 
C++98">,
   InGroup, DefaultIgnore;
 
-def ext_delete_with_message : ExtWarn<
+def ext_delete_with_message : Extension<
   "'= delete' with a message is a C++2c extension">, InGroup;
 def warn_cxx23_delete_with_message : Warning<
   "'= delete' with a message is incompatible with C++ standards before C++2c">,
diff --git a/clang/test/Parser/cxx2c-delete-with-message.cpp 
b/clang/test/Parser/cxx2c-delete-with-message.cpp
index 1767a080a7dcd8..5796c548632ae4 100644
--- a/clang/test/Parser/cxx2c-delete-with-message.cpp
+++ b/clang/test/Parser/cxx2c-delete-with-message.cpp
@@ -1,7 +1,17 @@
-// RUN: %clang_cc1 -std=c++23 -fsyntax-only -verify=expected,pre26 -pedantic %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify=expected 
-DTEST_NON_PEDANTIC %s
+// RUN: %clang_cc1 -std=c++17 -fsyntax-only -verify=expected,pre26 -pedantic %s
 // RUN: %clang_cc1 -std=c++2c -fsyntax-only -verify=expected,compat 
-Wpre-c++26-compat %s
 // RUN: %clang_cc1 -std=c++2c -fsyntax-only -verify %s
 
+#ifdef DTEST_NON_PEDANTIC
+namespace GH109311 {
+void f() = delete
+#if __cpp_deleted_function >= 202403L
+("reason") // ok
+#endif
+;
+}
+#else
 struct S {
   void a() = delete;
   void b() = delete(; // expected-error {{expected string literal}} 
expected-error {{expected ')'}} expected-note {{to match this '('}}
@@ -49,3 +59,4 @@ struct C {
   U f = delete ("hello"); // expected-error {{cannot delete expression of type 
'const char[6]'}}
 };
 }
+#endif
\ No newline at end of file

``




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


[clang] [clang][bytecode] Implement bitcasts to floating-point values (#114485) (PR #114712)

2024-11-03 Thread Timm Baeder via cfe-commits

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

>From 662447b6dfaad52d38a66f9fd59f43a0ac61b974 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Timm=20B=C3=A4der?= 
Date: Sat, 2 Nov 2024 01:56:47 +0100
Subject: [PATCH] [clang][bytecode] Implement bitcasts to floating-point values
 (#114485)

This time I tested on big-endian hosts.
---
 clang/lib/AST/ByteCode/Interp.h   | 12 ++-
 .../lib/AST/ByteCode/InterpBuiltinBitCast.cpp | 39 ++---
 .../ByteCode/builtin-bit-cast-long-double.cpp | 87 +++
 clang/test/AST/ByteCode/builtin-bit-cast.cpp  |  4 +-
 4 files changed, 128 insertions(+), 14 deletions(-)
 create mode 100644 clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp

diff --git a/clang/lib/AST/ByteCode/Interp.h b/clang/lib/AST/ByteCode/Interp.h
index ade6f7424b1fd6..153da14503a140 100644
--- a/clang/lib/AST/ByteCode/Interp.h
+++ b/clang/lib/AST/ByteCode/Interp.h
@@ -3062,7 +3062,17 @@ inline bool BitCast(InterpState &S, CodePtr OpPC, bool 
TargetIsUCharOrByte,
 return false;
 
   if constexpr (std::is_same_v) {
-assert(false && "Implement bitcasting to a floating type");
+assert(Sem);
+ptrdiff_t Offset = 0;
+
+if (llvm::sys::IsBigEndianHost) {
+  unsigned NumBits = llvm::APFloatBase::getSizeInBits(*Sem);
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= ResultBitWidth);
+  Offset = (ResultBitWidth - NumBits) / 8;
+}
+
+S.Stk.push(T::bitcastFromMemory(Buff.data() + Offset, *Sem));
   } else {
 assert(!Sem);
 S.Stk.push(T::bitcastFromMemory(Buff.data(), ResultBitWidth));
diff --git a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp 
b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
index 1acd49de307b96..8160707e8654d6 100644
--- a/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
+++ b/clang/lib/AST/ByteCode/InterpBuiltinBitCast.cpp
@@ -315,19 +315,34 @@ static bool readPointerToBuffer(const Context &Ctx, const 
Pointer &FromPtr,
   assert(false && "Implement casting to pointer types");
 
 CharUnits ObjectReprChars = ASTCtx.getTypeSizeInChars(P.getType());
-unsigned BitWidth;
-if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
-  BitWidth = FD->getBitWidthValue(ASTCtx);
-else
-  BitWidth = ASTCtx.toBits(ObjectReprChars);
-
+unsigned BitWidth = ASTCtx.toBits(ObjectReprChars);
 llvm::SmallVector Buff(ObjectReprChars.getQuantity());
-BITCAST_TYPE_SWITCH_WITH_FLOAT(T, {
-  T Val = P.deref();
-  Val.bitcastToMemory(Buff.data());
-});
-if (SwapData)
-  swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+// Work around floating point types that contain unused padding bytes.
+// This is really just `long double` on x86, which is the only
+// fundamental type with padding bytes.
+if (T == PT_Float) {
+  Floating &F = P.deref();
+  unsigned NumBits =
+  llvm::APFloatBase::getSizeInBits(F.getAPFloat().getSemantics());
+  assert(NumBits % 8 == 0);
+  assert(NumBits <= (ObjectReprChars.getQuantity() * 8));
+  F.bitcastToMemory(Buff.data());
+  // Now, only (maybe) swap the actual size of the float, excluding the
+  // padding bits.
+  if (SwapData)
+swapBytes(Buff.data(), NumBits / 8);
+
+} else {
+  if (const FieldDecl *FD = P.getField(); FD && FD->isBitField())
+BitWidth = FD->getBitWidthValue(ASTCtx);
+
+  BITCAST_TYPE_SWITCH(T, {
+T Val = P.deref();
+Val.bitcastToMemory(Buff.data());
+  });
+  if (SwapData)
+swapBytes(Buff.data(), ObjectReprChars.getQuantity());
+}
 
 if (BitWidth != (Buff.size() * 8) && BigEndianTarget) {
   Buffer.pushData(Buff.data() + (Buff.size() - 1 - (BitWidth / 8)),
diff --git a/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp 
b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
new file mode 100644
index 00..230680ff3ced7d
--- /dev/null
+++ b/clang/test/AST/ByteCode/builtin-bit-cast-long-double.cpp
@@ -0,0 +1,87 @@
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char
+// RUN: %clang_cc1 -verify=ref,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s
+
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
x86_64-apple-macosx10.14.0 %s -fno-signed-char 
-fexperimental-new-constant-interpreter
+// RUN: %clang_cc1 -verify=expected,both -std=c++2a -fsyntax-only -triple 
aarch64_be-linux-gnu %s -fexperimental-new-constant-interpreter
+
+// both-no-diagnos

[clang] [clang][CodeGen] `sret` args should always point to the `alloca` AS, so use that (PR #114062)

2024-11-03 Thread John McCall via cfe-commits


@@ -1672,10 +1672,11 @@ CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) 
{
 
   // Add type for sret argument.
   if (IRFunctionArgs.hasSRetArg()) {
-QualType Ret = FI.getReturnType();
-unsigned AddressSpace = CGM.getTypes().getTargetAddressSpace(Ret);
+auto AddressSpace = CGM.getTarget().getIndirectArgAddressSpace();

rjmccall wrote:

That's what I was thinking, yeah.  There should be plenty of space for that 
without inflating `ABIInfo`, right?

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


[clang] [Tooling/Inclusion] Update std symbols mapping (PR #113612)

2024-11-03 Thread Vadim D. via cfe-commits

vvd170501 wrote:

@kadircet, ping. Could you commit these changes, please?

I've rebased to make sure that 68daf7d27ecc085fe7347552736197db6453f71c didn't 
cause any conflicts.

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


[clang-tools-extra] [clangd] Check for editsNearCursor client capability under experimental capabilities (PR #114699)

2024-11-03 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Nathan Ridge (HighCommander4)


Changes

This is done to support clients which only support adding custom 
(language-specific or server-specific) capabilities under 'experimental'.

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

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


1 Files Affected:

- (modified) clang-tools-extra/clangd/Protocol.cpp (+10) 


``diff
diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index c08f80442eaa06..5a303123b5ce84 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -504,6 +504,16 @@ bool fromJSON(const llvm::json::Value &Params, 
ClientCapabilities &R,
   P.field("offsetEncoding")))
   return false;
   }
+
+  if (auto *Experimental = O->getObject("experimental")) {
+if (auto *TextDocument = Experimental->getObject("textDocument")) {
+  if (auto *Completion = TextDocument->getObject("completion")) {
+if (auto EditsNearCursor = Completion->getBoolean("editsNearCursor"))
+  R.CompletionFixes |= *EditsNearCursor;
+  }
+}
+  }
+
   return true;
 }
 

``




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


[clang] [emacs][clang-format] Add elisp API for clang-format on git diffs (PR #112792)

2024-11-03 Thread via cfe-commits

goldsteinn wrote:

> Note that I'm not a regular clang contributor, I just submitted a small 
> improvement to `clang-format.el`, and maintain some emacs packages in elpa & 
> melpa.
> 
> Overall the PR looks like it needs more attention to detail, as far as I can 
> tell it's creating temporary files and never removing them, various minor 
> issues noted inline.
> 
> * This PR needs to be rebased on top of the recently added 
> `clang-format-on-save-mode` commit.
> 
> * Running `package-lint` reports.
> 
> 
> ```
> 156:19: warning: Closing parens should not be wrapped onto new lines.
> 157:18: warning: Closing parens should not be wrapped onto new lines.
> 176:12: error: You should depend on (emacs "24.4") or the compat package if 
> you need `string-trim'.
> 188:11: error: You should depend on (emacs "25.1") if you need `vc-root-dir'.
> 198:59: error: You should depend on (emacs "25.1") if you need `vc-root-dir'.
> ```

Thank you for the detailed feedback, I will have v2 up tomorrow.

Regarding the package lints, is requiring 25.1 acceptable? I'm not really sure 
how to implement this without `vc-root-dir`.

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


[clang-tools-extra] [clangd] Check for editsNearCursor client capability under experimental capabilities (PR #114699)

2024-11-03 Thread Nathan Ridge via cfe-commits

https://github.com/HighCommander4 created 
https://github.com/llvm/llvm-project/pull/114699

This is done to support clients which only support adding custom 
(language-specific or server-specific) capabilities under 'experimental'.

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

>From 52a5625e0806c2a70b6ca728f9f3e42d88b83021 Mon Sep 17 00:00:00 2001
From: Nathan Ridge 
Date: Sun, 3 Nov 2024 02:42:46 -0500
Subject: [PATCH] [clangd] Check for editsNearCursor client capability under
 experimental capabilities

This is done to support clients which only support adding custom
(language-specific or server-specific) capabilities under
'experimental'.

Fixes https://github.com/clangd/clangd/issues/2201
---
 clang-tools-extra/clangd/Protocol.cpp | 10 ++
 1 file changed, 10 insertions(+)

diff --git a/clang-tools-extra/clangd/Protocol.cpp 
b/clang-tools-extra/clangd/Protocol.cpp
index c08f80442eaa06..5a303123b5ce84 100644
--- a/clang-tools-extra/clangd/Protocol.cpp
+++ b/clang-tools-extra/clangd/Protocol.cpp
@@ -504,6 +504,16 @@ bool fromJSON(const llvm::json::Value &Params, 
ClientCapabilities &R,
   P.field("offsetEncoding")))
   return false;
   }
+
+  if (auto *Experimental = O->getObject("experimental")) {
+if (auto *TextDocument = Experimental->getObject("textDocument")) {
+  if (auto *Completion = TextDocument->getObject("completion")) {
+if (auto EditsNearCursor = Completion->getBoolean("editsNearCursor"))
+  R.CompletionFixes |= *EditsNearCursor;
+  }
+}
+  }
+
   return true;
 }
 

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