[clang] [WIP] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-25 Thread via cfe-commits

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


[clang] [ASAN] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-25 Thread via cfe-commits

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


[clang] [analyzer][NFC] Combine similar methods in StreamChecker (PR #70170)

2023-10-25 Thread Ben Shi via cfe-commits

https://github.com/benshi001 created 
https://github.com/llvm/llvm-project/pull/70170

Methods StreamChecker::preFread and StreamChecker::preFwrite are quite similar, 
so they can be combined to StreamChecker::preFreadFwrite.

>From 99a826f3a2219ea6ee368e4ffd3db8c391e9ae2c Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 25 Oct 2023 14:58:55 +0800
Subject: [PATCH] [analyzer][NFC] Combine similar methods in StreamChecker

Methods StreamChecker::preFread and StreamChecker::preFwrite are quite
similar, so they can be combined to StreamChecker::preFreadFwrite.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 39 ++-
 1 file changed, 12 insertions(+), 27 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index ef209f64f0c372c..843748c832ff97f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,10 +245,10 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -652,6 +650,11 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   if (!State)
 return;
 
+  if (!IsFread) {
+C.addTransition(State);
+return;
+  }
+
   SymbolRef Sym = StreamVal.getAsSymbol();
   if (Sym && State->get(Sym)) {
 const StreamState *SS = State->get(Sym);
@@ -662,24 +665,6 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   }
 }
 
-void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
-  CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-  SVal StreamVal = getStreamArg(Desc, Call);
-  State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
-  State);
-  if (!State)
-return;
-  State = ensureStreamOpened(StreamVal, C, State);
-  if (!State)
-return;
-  State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
-  if (!State)
-return;
-
-  C.addTransition(State);
-}
-
 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
 const CallEvent &Call, CheckerContext &C,
 bool IsFread) const {

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


[clang] [ASAN] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-25 Thread via cfe-commits


@@ -868,14 +881,27 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
 
   MCSymbol *EmittedInitSym = GVSym;
 
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {

skc7 wrote:

This would be replaced by "asan_instrumented" attribute, once #68865 gets 
accepted.

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


[clang] [ASAN] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-25 Thread via cfe-commits


@@ -2441,6 +2441,9 @@ void 
ModuleAddressSanitizer::instrumentGlobals(IRBuilder<> &IRB, Module &M,
 // zero so we can copy the metadata over as is.
 NewGlobal->copyMetadata(G, 0);
 
+// Attach "asan_instrumented" attribute to the new global.
+NewGlobal->addAttribute(Attribute::SanitizeAddress);

skc7 wrote:

This would be replaced by "asan_instrumented" attributes, once #68865 gets 
approved and merged.

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


[clang] [ASAN] For Asan instrumented global, emit two symbols, one with actual size and other with instrumented size. (PR #70166)

2023-10-25 Thread via cfe-commits


@@ -758,6 +758,19 @@ void AsmPrinter::emitGlobalVariable(const GlobalVariable 
*GV) {
   // sections and expected to be contiguous (e.g. ObjC metadata).
   const Align Alignment = getGVAlignment(GV, DL);
 
+  // Identify globals with "asan_instrumented" attribute and extract
+  // the actual global variable size.
+  uint64_t ActualSize = 0;
+  if (GV->hasAttribute(Attribute::SanitizeAddress)) {

skc7 wrote:

This would be replaced by "asan_instrumented" attributes, once #68865 gets 
approved and merged.

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


[clang] [clang][dataflow] Add `Environment::allows()`. (PR #70046)

2023-10-25 Thread Stanislav Gatev via cfe-commits

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


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


[clang] [analyzer][NFC] Combine similar methods in StreamChecker (PR #70170)

2023-10-25 Thread via cfe-commits

llvmbot wrote:




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

Author: Ben Shi (benshi001)


Changes

Methods StreamChecker::preFread and StreamChecker::preFwrite are quite similar, 
so they can be combined to StreamChecker::preFreadFwrite.

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


1 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp (+12-27) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index ef209f64f0c372c..843748c832ff97f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,10 +245,10 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -652,6 +650,11 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   if (!State)
 return;
 
+  if (!IsFread) {
+C.addTransition(State);
+return;
+  }
+
   SymbolRef Sym = StreamVal.getAsSymbol();
   if (Sym && State->get(Sym)) {
 const StreamState *SS = State->get(Sym);
@@ -662,24 +665,6 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   }
 }
 
-void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
-  CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-  SVal StreamVal = getStreamArg(Desc, Call);
-  State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
-  State);
-  if (!State)
-return;
-  State = ensureStreamOpened(StreamVal, C, State);
-  if (!State)
-return;
-  State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
-  if (!State)
-return;
-
-  C.addTransition(State);
-}
-
 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
 const CallEvent &Call, CheckerContext &C,
 bool IsFread) const {

``




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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Ben Shi via cfe-commits

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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/70170

>From d32442f4f38d45ca9a8fab490f3618ccc31dd632 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 25 Oct 2023 14:58:55 +0800
Subject: [PATCH] [analyzer][NFC] Combine similar methods of StreamChecker

Methods StreamChecker::preFread and StreamChecker::preFwrite are quite
similar, so they can be combined to StreamChecker::preFreadFwrite.
---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 39 ++-
 1 file changed, 12 insertions(+), 27 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index ef209f64f0c372c..843748c832ff97f 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,10 +245,10 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -652,6 +650,11 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   if (!State)
 return;
 
+  if (!IsFread) {
+C.addTransition(State);
+return;
+  }
+
   SymbolRef Sym = StreamVal.getAsSymbol();
   if (Sym && State->get(Sym)) {
 const StreamState *SS = State->get(Sym);
@@ -662,24 +665,6 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   }
 }
 
-void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
-  CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-  SVal StreamVal = getStreamArg(Desc, Call);
-  State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
-  State);
-  if (!State)
-return;
-  State = ensureStreamOpened(StreamVal, C, State);
-  if (!State)
-return;
-  State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
-  if (!State)
-return;
-
-  C.addTransition(State);
-}
-
 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
 const CallEvent &Call, CheckerContext &C,
 bool IsFread) const {

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


[clang] [Driver] Add ExclusiveGroup feature to multilib.yaml. (PR #69447)

2023-10-25 Thread Petr Hosek via cfe-commits


@@ -152,6 +180,7 @@ template <> struct 
llvm::yaml::MappingTraits {
   static void mapping(llvm::yaml::IO &io, MultilibSerialization &V) {
 io.mapRequired("Dir", V.Dir);
 io.mapRequired("Flags", V.Flags);
+io.mapOptional("ExclusiveGroup", V.ExclusiveGroup);

petrhosek wrote:

Could we just call it a `Group` for simplicity?

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


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

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


@@ -182,7 +182,7 @@ TEST_F(FormatTestComments, UnderstandsSingleLineComments) {
"int   a; // This is unrelated"));
   EXPECT_EQ("class C {\n"
 "  void f() { // This does something ..\n"
-"  }  // awesome..\n"
+"  } // awesome..\n"

owenca wrote:

I think it's been long enough.

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


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

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

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


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


[clang] [PassBuilder] Add a mechanism for adding passbuilder callbacks for static builds (PR #70171)

2023-10-25 Thread William Moses via cfe-commits

https://github.com/wsmoses created 
https://github.com/llvm/llvm-project/pull/70171

Adding passbuilder callbacks presently can be done one of two ways:
* a shared library plugin
* modifying the extensions list (and thus extensions.def)

This prevents the use of such functionality for static builds on build systems 
that cannot be modified, as well as prevents such functionality from being 
usable when using llvm/clang as a library.

This creates a third mechanism for adding these callbacks, an explicit list of 
said callbacks. It's otherwise identical to the plugin approach, except now 
instead of the list of plugins each being queried for the callback function, 
this just runs the callback function.

>From d77dd6718c0e5148d3d818717de3b6e7779cd3ac Mon Sep 17 00:00:00 2001
From: "William S. Moses" 
Date: Wed, 25 Oct 2023 02:10:32 -0500
Subject: [PATCH] [PassBuilder] Add a mechanism for adding passbuilder
 callbacks without an extension mechanism or dlopen of plugin

---
 clang/lib/CodeGen/BackendUtil.cpp  | 3 +++
 llvm/include/llvm/Passes/PassBuilder.h | 5 +
 llvm/lib/LTO/LTOBackend.cpp| 3 +++
 llvm/tools/opt/NewPMDriver.cpp | 6 ++
 4 files changed, 17 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..8dbe4d942df278d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -909,6 +909,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Register the target library analysis directly and give it a customized
   // preset TLI.
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 2c7ceda7998eda1..d018dd1e69166f0 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -739,6 +739,11 @@ bool parseAnalysisUtilityPasses(
 
   return false;
 }
+
+//! List of pass builder callbacks to be applied, in addition to those imported
+//! from plugins or LLVM extensions.
+extern SmallVector>
+ListRegisterPassBuilderCallbacks;
 }
 
 #endif
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index ccc4276e36dacf0..28aabf8bdebb4d6 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -187,6 +187,9 @@ static void RegisterPassPlugins(ArrayRef 
PassPlugins,
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Load requested pass plugins and let them register pass builder callbacks
   for (auto &PluginFN : PassPlugins) {
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 6ae3f87099afd64..595bc4acddee6c4 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -431,6 +431,9 @@ bool llvm::runPassPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Specially handle the alias analysis manager so that we can register
   // a custom pipeline of AA passes with it.
@@ -546,3 +549,6 @@ void llvm::printPasses(raw_ostream &OS) {
   PassBuilder PB;
   PB.printPassNames(OS);
 }
+
+llvm::SmallVector>
+ListRegisterPassBuilderCallbacks;
\ 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] 9ae11a5 - [Driver] Add `--` to some test clang-cl command lines. (#70055)

2023-10-25 Thread via cfe-commits

Author: Simon Tatham
Date: 2023-10-25T08:27:06+01:00
New Revision: 9ae11a5bacb781f6899861ab2197a8cd711c5e6c

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

LOG: [Driver] Add `--` to some test clang-cl command lines. (#70055)

If clang/test/Driver/cl-offload.cu is run on Unix in a directory whose
absolute pathname starts with `/w`, such as the `/workspace` used by at
least some Jenkins CI setups, then the file name on the clang command
line is misinterpreted as some kind of MSVC warning-control option, and
ignored by the catch-all `_SLASH_w` option in Options.td.

Other clang-cl tests take care to put a `--` before the input file name,
to force clang to treat it as a filename even if it starts with a / and
accidentally looks like a cl option. Do the same here.

Added: 


Modified: 
clang/test/Driver/cl-offload.cu

Removed: 




diff  --git a/clang/test/Driver/cl-offload.cu b/clang/test/Driver/cl-offload.cu
index 650c13da15b5b58..b05bf3b97b7eb71 100644
--- a/clang/test/Driver/cl-offload.cu
+++ b/clang/test/Driver/cl-offload.cu
@@ -1,15 +1,14 @@
-// REQUIRES: !system-darwin
 // REQUIRES: !system-solaris
 
 // The test cannot be run on Darwin because /Users will be treated as a MSVC 
option.
 
 // RUN: %clang_cl -### -target x86_64-pc-windows-msvc --offload-arch=sm_35 
-fgpu-rdc \
 // RUN:   --cuda-path=%S/Inputs/CUDA/usr/local/cuda \
-// RUN:   /Wall -x cuda %s 2>&1 \
+// RUN:   /Wall -x cuda -- %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=CUDA
 
 // RUN: %clang_cl -### -target x86_64-pc-windows-msvc --offload-arch=gfx1010 
-fgpu-rdc --hip-link \
-// RUN:   --rocm-path=%S/Inputs/rocm /Wall -x hip %s 2>&1 \
+// RUN:   --rocm-path=%S/Inputs/rocm /Wall -x hip -- %s 2>&1 \
 // RUN:   | FileCheck %s -check-prefix=HIP
 
 // CUDA: "-cc1" "-triple" "nvptx64-nvidia-cuda" "-aux-triple" 
"x86_64-pc-windows-msvc"



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


[clang] [Driver] Add `--` to some test clang-cl command lines. (PR #70055)

2023-10-25 Thread Simon Tatham via cfe-commits

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


[clang] [PassBuilder] Add a mechanism for adding passbuilder callbacks for static builds (PR #70171)

2023-10-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang-codegen

Author: William Moses (wsmoses)


Changes

Adding passbuilder callbacks presently can be done one of two ways:
* a shared library plugin
* modifying the extensions list (and thus extensions.def)

This prevents the use of such functionality for static builds on build systems 
that cannot be modified, as well as prevents such functionality from being 
usable when using llvm/clang as a library.

This creates a third mechanism for adding these callbacks, an explicit list of 
said callbacks. It's otherwise identical to the plugin approach, except now 
instead of the list of plugins each being queried for the callback function, 
this just runs the callback function.

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


4 Files Affected:

- (modified) clang/lib/CodeGen/BackendUtil.cpp (+3) 
- (modified) llvm/include/llvm/Passes/PassBuilder.h (+5) 
- (modified) llvm/lib/LTO/LTOBackend.cpp (+3) 
- (modified) llvm/tools/opt/NewPMDriver.cpp (+6) 


``diff
diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..8dbe4d942df278d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -909,6 +909,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Register the target library analysis directly and give it a customized
   // preset TLI.
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 2c7ceda7998eda1..d018dd1e69166f0 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -739,6 +739,11 @@ bool parseAnalysisUtilityPasses(
 
   return false;
 }
+
+//! List of pass builder callbacks to be applied, in addition to those imported
+//! from plugins or LLVM extensions.
+extern SmallVector>
+ListRegisterPassBuilderCallbacks;
 }
 
 #endif
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index ccc4276e36dacf0..28aabf8bdebb4d6 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -187,6 +187,9 @@ static void RegisterPassPlugins(ArrayRef 
PassPlugins,
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Load requested pass plugins and let them register pass builder callbacks
   for (auto &PluginFN : PassPlugins) {
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 6ae3f87099afd64..595bc4acddee6c4 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -431,6 +431,9 @@ bool llvm::runPassPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Specially handle the alias analysis manager so that we can register
   // a custom pipeline of AA passes with it.
@@ -546,3 +549,6 @@ void llvm::printPasses(raw_ostream &OS) {
   PassBuilder PB;
   PB.printPassNames(OS);
 }
+
+llvm::SmallVector>
+ListRegisterPassBuilderCallbacks;
\ No newline at end of file

``




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


[clang] [Driver] Add ExclusiveGroup feature to multilib.yaml. (PR #69447)

2023-10-25 Thread Petr Hosek via cfe-commits


@@ -0,0 +1,69 @@
+# REQUIRES: shell
+# UNSUPPORTED: system-windows
+
+# RUN: rm -rf %t
+
+# RUN: mkdir -p %t/baremetal_multilib/bin
+# RUN: ln -s %clang %t/baremetal_multilib/bin/clang
+
+# RUN: mkdir -p %t/baremetal_multilib/lib/clang-runtimes
+# RUN: ln -s %s %t/baremetal_multilib/lib/clang-runtimes/multilib.yaml
+
+# RUN: %t/baremetal_multilib/bin/clang -no-canonical-prefixes -x c++ %s -### 
-o %t.out --target=thumbv7em-none-unknown-eabi --sysroot= 2>%t.err
+
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR1_NON_EXCLUSIVE
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR2_NON_EXCLUSIVE
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR1_EXCLUSIVE
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR2_EXCLUSIVE
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR1_OWN_GROUP
+# RUN: FileCheck -DSYSROOT=%t/baremetal_multilib %s < %t.err 
--check-prefix=TESTDIR2_OWN_GROUP
+
+# Expected results:
+#
+# Due to the Mappings section, all six of these library directories should
+# match the command-line flag --target=thumbv7em-none-unknown-eabi.
+#
+# The two "non_exclusive" directories, which don't have an ExclusiveGroup at
+# all, should both be selected. So should the two "own_group", each of which
+# specifies a different value of ExclusiveGroup. But the two "exclusive", which
+# have the _same_ ExclusiveGroup value, should not: the second one wins. So we
+# expect five of these six directories to show up in the clang-cc1 command
+# line, but not testdir1_exclusive.
+
+# TESTDIR1_NON_EXCLUSIVE: "-internal-isystem" 
"[[SYSROOT]]/bin/../lib/clang-runtimes/testdir1_non_exclusive/include/c++/v1"
+# TESTDIR2_NON_EXCLUSIVE: "-internal-isystem" 
"[[SYSROOT]]/bin/../lib/clang-runtimes/testdir2_non_exclusive/include/c++/v1"
+# TESTDIR2_EXCLUSIVE: "-internal-isystem" 
"[[SYSROOT]]/bin/../lib/clang-runtimes/testdir2_exclusive/include/c++/v1"
+# TESTDIR1_OWN_GROUP: "-internal-isystem" 
"[[SYSROOT]]/bin/../lib/clang-runtimes/testdir1_own_group/include/c++/v1"
+# TESTDIR2_OWN_GROUP: "-internal-isystem" 
"[[SYSROOT]]/bin/../lib/clang-runtimes/testdir2_own_group/include/c++/v1"

petrhosek wrote:

This comment is unrelated to this change, but the fact that we end up with 
`[[SYSROOT]]/bin/../lib/clang-runtimes//include/c++/v1` is suboptimal.

libc++ headers are designed to be target agnostic with the exception of 
`__config_site` to avoid having to distribute multiple copies of headers, one 
for each target or multilib.

Ideally, what we should end up with is something like this:
```
-internal-isystem 
[[SYSROOT]]/bin/../include/thumbv7m-none-unknown-eabi/testdir1_non_exclusive/include/c++/v1
-internal-isystem 
[[SYSROOT]]/bin/../include/thumbv7m-none-unknown-eabi/testdir2_non_exclusive/include/c++/v1
-internal-isystem 
[[SYSROOT]]/bin/../include/thumbv7m-none-unknown-eabi/testdir2_exclusive/include/c++/v1
-internal-isystem 
[[SYSROOT]]/bin/../include/thumbv7m-none-unknown-eabi/testdir1_own_group/include/c++/v1
-internal-isystem 
[[SYSROOT]]/bin/../include/thumbv7m-none-unknown-eabi/testdir2_own_group/include/c++/v1
-internal-isystem [[SYSROOT]]/bin/../include/c++/v1
```
I have filed https://github.com/llvm/llvm-project/issues/70172 to track this.

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


[clang] [AMDGPU] Lower __builtin_amdgcn_read_exec_hi to use amdgcn_ballot (PR #69567)

2023-10-25 Thread Matt Arsenault via cfe-commits

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


[clang] [AMDGPU] Lower __builtin_amdgcn_read_exec_hi to use amdgcn_ballot (PR #69567)

2023-10-25 Thread Matt Arsenault via cfe-commits

https://github.com/arsenm commented:

lgtm with a nit

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


[clang] [AMDGPU] Lower __builtin_amdgcn_read_exec_hi to use amdgcn_ballot (PR #69567)

2023-10-25 Thread Matt Arsenault via cfe-commits


@@ -21,6 +23,28 @@ void test_ballot_wave32_target_attr(global uint* out, int a, 
int b)
   *out = __builtin_amdgcn_ballot_w32(a == b);
 }
 
+// CHECK-LABEL: @test_read_exec(
+// CHECK: call i64 @llvm.amdgcn.ballot.i64(i1 true)
+void test_read_exec(global uint* out) {
+  *out = __builtin_amdgcn_read_exec();
+}
+
+// CHECK: declare i64 @llvm.amdgcn.ballot.i64(i1) 
#[[$NOUNWIND_READONLY:[0-9]+]]
+
+// CHECK-LABEL: @test_read_exec_lo(
+// CHECK: call i32 @llvm.amdgcn.ballot.i32(i1 true)
+void test_read_exec_lo(global uint* out) {
+  *out = __builtin_amdgcn_read_exec_lo();
+}
+
+// CHECK-LABEL: @test_read_exec_hi(
+// CHECK: call i64 @llvm.amdgcn.ballot.i64(i1 true)

arsenm wrote:

Does this codegen on wave32? Or should this directly emit 0?

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


[clang] [AMDGPU] Lower __builtin_amdgcn_read_exec_hi to use amdgcn_ballot (PR #69567)

2023-10-25 Thread Matt Arsenault via cfe-commits


@@ -7995,15 +7995,24 @@ enum SpecialRegisterAccessKind {
   Write,
 };
 
+// Generates the IR for __builtin_read_exec_*.
+// Lowers the builtin to amdgcn_ballot intrinsic.
 static Value *EmitAMDGCNBallotForExec(CodeGenFunction &CGF, const CallExpr *E,
   llvm::Type *RegisterType,
-  llvm::Type *ValueType) {
+  llvm::Type *ValueType, bool isExecHi) {
   CodeGen::CGBuilderTy &Builder = CGF.Builder;
   CodeGen::CodeGenModule &CGM = CGF.CGM;
 
-  llvm::Type *ResultType = CGF.ConvertType(E->getType());
-  Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_ballot, {ResultType});
+  Function *F = CGM.getIntrinsic(Intrinsic::amdgcn_ballot, {RegisterType});
   llvm::Value *Call = Builder.CreateCall(F, {Builder.getInt1(true)});
+
+  if (isExecHi) {
+Value *C1 = llvm::ConstantInt::get(ValueType, 32);
+Value *Rt2 = Builder.CreateLShr(Call, C1);

arsenm wrote:

There's a CreateLShr overload that takes the constant integer, you don't need 
the ConstantInt::get

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


[clang] [clang][Sema] Avoid non-empty unexpanded pack assertion for FunctionParmPackExpr (PR #69224)

2023-10-25 Thread via cfe-commits

cor3ntin wrote:

Looks generally good to me. can you remove the whitespace only changes? thanks!

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


[clang] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -738,6 +738,37 @@ objcopy::parseObjcopyOptions(ArrayRef 
RawArgsArr,
   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
 Config.ExtractPartition = Arg->getValue();
 
+  if (const auto *A = InputArgs.getLastArg(OBJCOPY_gap_fill)) {
+if (Config.OutputFormat != FileFormat::Binary)
+  return createStringError(
+  errc::invalid_argument,
+  "'--gap-fill' is only supported for binary output");
+ErrorOr Val = getAsInteger(A->getValue());
+if (!Val)
+  return createStringError(Val.getError(), "--gap-fill: bad number: %s",
+   A->getValue());
+uint8_t ByteVal = Val.get();
+if (ByteVal != Val.get())
+  llvm::errs() << "warning: truncating gap-fill from 0x"
+   << llvm::utohexstr(Val.get(), true) << " to 0x"
+   << llvm::utohexstr(ByteVal, true) << '\n';

jh7370 wrote:

Don't print direct to `llvm::errs`. This won't follow the proper formatting 
style for warnings produced by tools (see what other tools do). 
llvm-objcopy.cpp already has a `reportWarning` method. It seems reasonable to 
declare that in a header file so that you can also use it here.

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


[clang] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -0,0 +1,198 @@
+# RUN: yaml2obj --docnum=1 %s -o %t
+
+# RUN: not llvm-objcopy --gap-fill 1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
+# NOT-BINARY: error: '--gap-fill' is only supported for binary output
+
+# RUN: not llvm-objcopy -O binary --gap-fill= %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-FORMAT
+# BAD-FORMAT: error: --gap-fill: bad number:
+
+# RUN: not llvm-objcopy -O binary --gap-fill=x %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT
+# BAD-INPUT: error: --gap-fill: bad number: x
+
+# RUN: not llvm-objcopy -O binary --gap-fill=0x %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT2
+# BAD-INPUT2: error: --gap-fill: bad number: 0x
+
+# RUN: not llvm-objcopy -O binary --gap-fill=0x1G %t %t.bin 2>&1 | FileCheck 
%s --check-prefix=BAD-INPUT3
+# BAD-INPUT3: error: --gap-fill: bad number: 0x1G
+
+# RUN: not llvm-objcopy -O binary --gap-fill=ff %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT4
+# BAD-INPUT4: error: --gap-fill: bad number: ff
+
+# RUN: llvm-objcopy -O binary --gap-fill=0x1122 %t %t-val16 2>&1 | FileCheck 
%s --check-prefix=TRUNCATED-ERR
+# TRUNCATED-ERR: warning: truncating gap-fill from 0x1122 to 0x22
+
+# RUN: od -v -Ax -t x1 %t-val16 | FileCheck %s --check-prefix=TRUNCATED 
--match-full-lines
+# TRUNCATED:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 22 a1 b2
+# TRUNCATED-NEXT: 10 c3 d4 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 20 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 30 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 40 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 50 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 60 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 70 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 80 22 22 89 ab cd ef
+# TRUNCATED-NEXT: 86
+
+## Test no gap fill with all allocatable output sections.
+# RUN: llvm-objcopy -O binary %t %t-default
+# RUN: od -v -Ax -t x1 %t-default | FileCheck %s --check-prefix=DEFAULT 
--match-full-lines
+# DEFAULT:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 00 a1 b2
+# DEFAULT-NEXT: 10 c3 d4 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 70 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 80 00 00 89 ab cd ef
+# DEFAULT-NEXT: 86
+
+## Test gap fill with all allocatable output sections.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 %t %t-filled
+# RUN: od -v -Ax -t x1 %t-filled | FileCheck %s --check-prefix=FULL 
--match-full-lines
+# FULL:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba e9 a1 b2
+# FULL-NEXT: 10 c3 d4 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 20 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 30 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 40 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 50 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 60 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 70 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 80 e9 e9 89 ab cd ef
+# FULL-NEXT: 86
+
+## Test gap fill with a decimal value.
+# RUN: llvm-objcopy -O binary --gap-fill=99 %t %t-filled-decimal
+# RUN: od -v -Ax -t x1 %t-filled-decimal | FileCheck %s --check-prefix=DEC 
--match-full-lines
+# DEC:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 63 a1 b2
+# DEC-NEXT: 10 c3 d4 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 20 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 30 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 40 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 50 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 60 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 70 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 80 63 63 89 ab cd ef
+# DEC-NEXT: 86
+
+## Test gap fill with the last section removed, should be truncated.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 --remove-section=.foo %t 
%t-filled
+# RUN: od -v -Ax -t x1 %t-filled | FileCheck %s 
--check-prefix=REMOVE-LAST-SECTION --match-full-lines
+# REMOVE-LAST-SECTION: 00 ee ff 11 22 33 44 aa bb cc dd fe dc ba e9 a1 b2
+# REMOVE-LAST-SECTION-NEXT: 10 c3 d4
+# REMOVE-LAST-SECTION-NEXT: 12
+
+## Test gap fill with the middle section removed, should be filled.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 --remove-section=.gap2 %t 
%t-filled
+# RUN: od 

[clang] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -0,0 +1,94 @@
+# RUN: yaml2obj %s -o %t
+
+# RUN: not llvm-objcopy --pad-to=1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
+# NOT-BINARY: error: '--pad-to' is only supported for binary output
+
+# RUN: not llvm-objcopy -O binary --pad-to= %t 2>&1 | FileCheck %s 
--check-prefix=BAD-FORMAT
+# BAD-FORMAT: error: --pad-to: bad number:
+
+# RUN: not llvm-objcopy -O binary --pad-to=x %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT
+# BAD-INPUT: error: --pad-to: bad number: x
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x1G %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT2
+# BAD-INPUT2: error: --pad-to: bad number: 0x1G
+
+# RUN: not llvm-objcopy -O binary --pad-to=ff %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT3
+# BAD-INPUT3: error: --pad-to: bad number: ff
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x112233445566778899 %t 2>&1 | 
FileCheck %s --check-prefix=BAD-NUMBER
+# BAD-NUMBER: error: --pad-to: bad number: 0x112233445566778899
+
+## Save the baseline, not padded output.
+# RUN: llvm-objcopy -O binary %t %t.bin
+
+## Pad to an address smaller than the binary size.
+# RUN: llvm-objcopy -O binary --pad-to=0x20 %t %t-p1
+# RUN: cmp %t.bin %t-p1
+# RUN: llvm-objcopy -O binary --pad-to=0x200 %t %t-p2
+# RUN: cmp %t.bin %t-p2
+
+## Pad all allocatable sections to a valid address.
+# RUN: llvm-objcopy -O binary --pad-to=0x218 %t %t-pad-default
+# RUN: od -v -Ax -t x1 %t-pad-default | FileCheck %s --check-prefix=DEFAULT 
--match-full-lines
+# DEFAULT:  00 11 22 33 44 55 66 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 10 77 88 99 aa 00 00 00 00
+# DEFAULT-NEXT: 18
+
+## Use a decimal number of padding address, verify it's not misunderstood.
+# RUN: llvm-objcopy -O binary --pad-to=536 %t %t-pad-decimal
+# RUN: od -v -Ax -t x1 %t-pad-decimal | FileCheck %s --check-prefix=DECIMAL 
--match-full-lines
+# DECIMAL:  00 11 22 33 44 55 66 00 00 00 00 00 00 00 00 00 00
+# DECIMAL-NEXT: 10 77 88 99 aa 00 00 00 00
+# DECIMAL-NEXT: 18
+
+## Pad all allocatable sections to a valid address, using --gap-fill.
+# RUN: llvm-objcopy -O binary --pad-to=0x218 --gap-fill=0xe9 %t %t-pad-fill
+# RUN: od -v -Ax -t x1 %t-pad-fill | FileCheck %s --check-prefix=FILL 
--match-full-lines
+# FILL:  00 11 22 33 44 55 66 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FILL-NEXT: 10 77 88 99 aa e9 e9 e9 e9
+# FILL-NEXT: 18
+
+## Test gap fill with a section removed.

jh7370 wrote:

This test file is about `--pad-to`. This comment probably needs expanding to 
better explain the test case.

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


[clang-tools-extra] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -0,0 +1,94 @@
+# RUN: yaml2obj %s -o %t
+
+# RUN: not llvm-objcopy --pad-to=1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
+# NOT-BINARY: error: '--pad-to' is only supported for binary output
+
+# RUN: not llvm-objcopy -O binary --pad-to= %t 2>&1 | FileCheck %s 
--check-prefix=BAD-FORMAT
+# BAD-FORMAT: error: --pad-to: bad number:
+
+# RUN: not llvm-objcopy -O binary --pad-to=x %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT
+# BAD-INPUT: error: --pad-to: bad number: x
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x1G %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT2
+# BAD-INPUT2: error: --pad-to: bad number: 0x1G
+
+# RUN: not llvm-objcopy -O binary --pad-to=ff %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT3
+# BAD-INPUT3: error: --pad-to: bad number: ff
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x112233445566778899 %t 2>&1 | 
FileCheck %s --check-prefix=BAD-NUMBER
+# BAD-NUMBER: error: --pad-to: bad number: 0x112233445566778899
+
+## Save the baseline, not padded output.
+# RUN: llvm-objcopy -O binary %t %t.bin
+
+## Pad to an address smaller than the binary size.
+# RUN: llvm-objcopy -O binary --pad-to=0x20 %t %t-p1
+# RUN: cmp %t.bin %t-p1
+# RUN: llvm-objcopy -O binary --pad-to=0x200 %t %t-p2
+# RUN: cmp %t.bin %t-p2
+
+## Pad all allocatable sections to a valid address.
+# RUN: llvm-objcopy -O binary --pad-to=0x218 %t %t-pad-default
+# RUN: od -v -Ax -t x1 %t-pad-default | FileCheck %s --check-prefix=DEFAULT 
--match-full-lines
+# DEFAULT:  00 11 22 33 44 55 66 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 10 77 88 99 aa 00 00 00 00
+# DEFAULT-NEXT: 18
+
+## Use a decimal number of padding address, verify it's not misunderstood.

jh7370 wrote:

```suggestion
## Use a decimal number for the padding address and verify it's not 
misunderstood.
```

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


[clang] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -2635,9 +2635,36 @@ template  Error ELFWriter::finalize() {
 }
 
 Error BinaryWriter::write() {
-  for (const SectionBase &Sec : Obj.allocSections())
+  SmallVector LoadableSections;
+  for (const SectionBase &Sec : Obj.allocSections()) {
+if (Sec.Type != SHT_NOBITS)
+  LoadableSections.push_back(&Sec);

jh7370 wrote:

NOBITS sections are loadable, so I don't think this variable name makes sense.

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


[clang-tools-extra] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -738,6 +738,37 @@ objcopy::parseObjcopyOptions(ArrayRef 
RawArgsArr,
   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
 Config.ExtractPartition = Arg->getValue();
 
+  if (const auto *A = InputArgs.getLastArg(OBJCOPY_gap_fill)) {
+if (Config.OutputFormat != FileFormat::Binary)
+  return createStringError(
+  errc::invalid_argument,
+  "'--gap-fill' is only supported for binary output");
+ErrorOr Val = getAsInteger(A->getValue());
+if (!Val)
+  return createStringError(Val.getError(), "--gap-fill: bad number: %s",
+   A->getValue());
+uint8_t ByteVal = Val.get();
+if (ByteVal != Val.get())
+  llvm::errs() << "warning: truncating gap-fill from 0x"
+   << llvm::utohexstr(Val.get(), true) << " to 0x"
+   << llvm::utohexstr(ByteVal, true) << '\n';
+Config.GapFill = ByteVal;
+  } else
+Config.GapFill = 0; // The value of zero is equivalent to no fill.

jh7370 wrote:

The value of `GapFill` is initialized to 0 already. Do you really need this? 
Same below for `PadTo`.

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


[clang-tools-extra] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -1,39 +1,32 @@
-# RUN: yaml2obj %s > %t
+# RUN: yaml2obj %s -o %t
 
-## Verify section headers before we perform several testings.
-# RUN: llvm-readelf -S %t | FileCheck %s --check-prefix=ORG-SHDR
-# ORG-SHDR: Section Headers:
-# ORG-SHDR:  [Nr] Name  TypeAddress  Off
Size   ES Flg Lk Inf Al
-# ORG-SHDR:  [ 0]   NULL 00 
00 00  0   0  0
-# ORG-SHDR:  [ 1] .nogapPROGBITS0102 42 
06 00   A  0   0  1
-# ORG-SHDR:  [ 2] .gap1 PROGBITS0108 48 
07 00  AX  0   0  1
-# ORG-SHDR:  [ 3] .gap2 PROGBITS0110 50 
04 00   A  0   0  1
-# ORG-SHDR:  [ 4] .nobit_tbss   NOBITS  0180 58 
18 00 WAT  0   0  8
-# ORG-SHDR:  [ 5] .foo  PROGBITS0184 5c 
04 00  WA  0   0  1
-# ORG-SHDR:  [ 6] .nobit_bssNOBITS  018a 60 
08 00  WA  0   0  1
+## This test is partially based on one from D67689.
 
 # RUN: not llvm-objcopy --gap-fill 1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
 # NOT-BINARY: error: '--gap-fill' is only supported for binary output
 
 # RUN: not llvm-objcopy -O binary --gap-fill %t 2>&1 | FileCheck %s 
--check-prefix=EMPTY

jh7370 wrote:

> if the last option in the command line has no value, it is silently ignored.

This was the case that surprised me. I feel like this is a bug in the 
command-line option parser (it's more generic than for llvm-objcopy). Could you 
file a bug for this, please?

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


[clang] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -0,0 +1,94 @@
+# RUN: yaml2obj %s -o %t
+
+# RUN: not llvm-objcopy --pad-to=1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
+# NOT-BINARY: error: '--pad-to' is only supported for binary output
+
+# RUN: not llvm-objcopy -O binary --pad-to= %t 2>&1 | FileCheck %s 
--check-prefix=BAD-FORMAT
+# BAD-FORMAT: error: --pad-to: bad number:
+
+# RUN: not llvm-objcopy -O binary --pad-to=x %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT
+# BAD-INPUT: error: --pad-to: bad number: x
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x1G %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT2
+# BAD-INPUT2: error: --pad-to: bad number: 0x1G
+
+# RUN: not llvm-objcopy -O binary --pad-to=ff %t 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT3
+# BAD-INPUT3: error: --pad-to: bad number: ff
+
+# RUN: not llvm-objcopy -O binary --pad-to=0x112233445566778899 %t 2>&1 | 
FileCheck %s --check-prefix=BAD-NUMBER
+# BAD-NUMBER: error: --pad-to: bad number: 0x112233445566778899
+
+## Save the baseline, not padded output.
+# RUN: llvm-objcopy -O binary %t %t.bin
+
+## Pad to an address smaller than the binary size.
+# RUN: llvm-objcopy -O binary --pad-to=0x20 %t %t-p1
+# RUN: cmp %t.bin %t-p1
+# RUN: llvm-objcopy -O binary --pad-to=0x200 %t %t-p2
+# RUN: cmp %t.bin %t-p2
+
+## Pad all allocatable sections to a valid address.
+# RUN: llvm-objcopy -O binary --pad-to=0x218 %t %t-pad-default
+# RUN: od -v -Ax -t x1 %t-pad-default | FileCheck %s --check-prefix=DEFAULT 
--match-full-lines
+# DEFAULT:  00 11 22 33 44 55 66 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 10 77 88 99 aa 00 00 00 00
+# DEFAULT-NEXT: 18
+
+## Use a decimal number of padding address, verify it's not misunderstood.

jh7370 wrote:

```suggestion
## Use a decimal number for the padding address and verify it's not 
misunderstood.
```

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


[clang-tools-extra] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -0,0 +1,198 @@
+# RUN: yaml2obj --docnum=1 %s -o %t
+
+# RUN: not llvm-objcopy --gap-fill 1 %t 2>&1 | FileCheck %s 
--check-prefix=NOT-BINARY
+# NOT-BINARY: error: '--gap-fill' is only supported for binary output
+
+# RUN: not llvm-objcopy -O binary --gap-fill= %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-FORMAT
+# BAD-FORMAT: error: --gap-fill: bad number:
+
+# RUN: not llvm-objcopy -O binary --gap-fill=x %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT
+# BAD-INPUT: error: --gap-fill: bad number: x
+
+# RUN: not llvm-objcopy -O binary --gap-fill=0x %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT2
+# BAD-INPUT2: error: --gap-fill: bad number: 0x
+
+# RUN: not llvm-objcopy -O binary --gap-fill=0x1G %t %t.bin 2>&1 | FileCheck 
%s --check-prefix=BAD-INPUT3
+# BAD-INPUT3: error: --gap-fill: bad number: 0x1G
+
+# RUN: not llvm-objcopy -O binary --gap-fill=ff %t %t.bin 2>&1 | FileCheck %s 
--check-prefix=BAD-INPUT4
+# BAD-INPUT4: error: --gap-fill: bad number: ff
+
+# RUN: llvm-objcopy -O binary --gap-fill=0x1122 %t %t-val16 2>&1 | FileCheck 
%s --check-prefix=TRUNCATED-ERR
+# TRUNCATED-ERR: warning: truncating gap-fill from 0x1122 to 0x22
+
+# RUN: od -v -Ax -t x1 %t-val16 | FileCheck %s --check-prefix=TRUNCATED 
--match-full-lines
+# TRUNCATED:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 22 a1 b2
+# TRUNCATED-NEXT: 10 c3 d4 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 20 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 30 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 40 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 50 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 60 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 70 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22
+# TRUNCATED-NEXT: 80 22 22 89 ab cd ef
+# TRUNCATED-NEXT: 86
+
+## Test no gap fill with all allocatable output sections.
+# RUN: llvm-objcopy -O binary %t %t-default
+# RUN: od -v -Ax -t x1 %t-default | FileCheck %s --check-prefix=DEFAULT 
--match-full-lines
+# DEFAULT:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 00 a1 b2
+# DEFAULT-NEXT: 10 c3 d4 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 20 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 30 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 60 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 70 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
+# DEFAULT-NEXT: 80 00 00 89 ab cd ef
+# DEFAULT-NEXT: 86
+
+## Test gap fill with all allocatable output sections.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 %t %t-filled
+# RUN: od -v -Ax -t x1 %t-filled | FileCheck %s --check-prefix=FULL 
--match-full-lines
+# FULL:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba e9 a1 b2
+# FULL-NEXT: 10 c3 d4 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 20 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 30 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 40 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 50 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 60 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 70 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9 e9
+# FULL-NEXT: 80 e9 e9 89 ab cd ef
+# FULL-NEXT: 86
+
+## Test gap fill with a decimal value.
+# RUN: llvm-objcopy -O binary --gap-fill=99 %t %t-filled-decimal
+# RUN: od -v -Ax -t x1 %t-filled-decimal | FileCheck %s --check-prefix=DEC 
--match-full-lines
+# DEC:  00 ee ff 11 22 33 44 aa bb cc dd fe dc ba 63 a1 b2
+# DEC-NEXT: 10 c3 d4 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 20 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 30 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 40 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 50 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 60 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 70 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63 63
+# DEC-NEXT: 80 63 63 89 ab cd ef
+# DEC-NEXT: 86
+
+## Test gap fill with the last section removed, should be truncated.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 --remove-section=.foo %t 
%t-filled
+# RUN: od -v -Ax -t x1 %t-filled | FileCheck %s 
--check-prefix=REMOVE-LAST-SECTION --match-full-lines
+# REMOVE-LAST-SECTION: 00 ee ff 11 22 33 44 aa bb cc dd fe dc ba e9 a1 b2
+# REMOVE-LAST-SECTION-NEXT: 10 c3 d4
+# REMOVE-LAST-SECTION-NEXT: 12
+
+## Test gap fill with the middle section removed, should be filled.
+# RUN: llvm-objcopy -O binary --gap-fill=0xe9 --remove-section=.gap2 %t 
%t-filled
+# RUN: od 

[clang-tools-extra] [llvm-objcopy] Add --gap-fill and --pad-to options (PR #65815)

2023-10-25 Thread James Henderson via cfe-commits


@@ -738,6 +738,37 @@ objcopy::parseObjcopyOptions(ArrayRef 
RawArgsArr,
   if (auto Arg = InputArgs.getLastArg(OBJCOPY_extract_partition))
 Config.ExtractPartition = Arg->getValue();
 
+  if (const auto *A = InputArgs.getLastArg(OBJCOPY_gap_fill)) {
+if (Config.OutputFormat != FileFormat::Binary)
+  return createStringError(
+  errc::invalid_argument,
+  "'--gap-fill' is only supported for binary output");
+ErrorOr Val = getAsInteger(A->getValue());
+if (!Val)
+  return createStringError(Val.getError(), "--gap-fill: bad number: %s",
+   A->getValue());
+uint8_t ByteVal = Val.get();
+if (ByteVal != Val.get())
+  llvm::errs() << "warning: truncating gap-fill from 0x"
+   << llvm::utohexstr(Val.get(), true) << " to 0x"
+   << llvm::utohexstr(ByteVal, true) << '\n';

jh7370 wrote:

Don't print direct to `llvm::errs`. This won't follow the proper formatting 
style for warnings produced by tools (see what other tools do). 
llvm-objcopy.cpp already has a `reportWarning` method. It seems reasonable to 
declare that in a header file so that you can also use it here.

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


[clang] d25e0aa - [Sema] Fixed faulty shift count warning (#69521)

2023-10-25 Thread via cfe-commits

Author: Karl-Johan Karlsson
Date: 2023-10-25T09:48:01+02:00
New Revision: d25e0aac415f45ce98c3700010acb5a98f016cef

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

LOG: [Sema] Fixed faulty shift count warning (#69521)

Constant values of _BitInt have the bitwith to exactly fit the constant
number. This patch fix a problem in Sema when building an APInt where
the supplied bitwidth can become too small and simply truncate the value
leading to a faulty warning.

Added: 


Modified: 
clang/docs/ReleaseNotes.rst
clang/lib/Sema/SemaExpr.cpp
clang/test/Sema/c2x-expr-range.c

Removed: 




diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index a063733e96cb74c..4cc148905d4e130 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -488,6 +488,9 @@ Bug Fixes in This Version
 - Clang no longer permits using the `_BitInt` types as an underlying type for 
an
   enumeration as specified in the C23 Standard.
   Fixes (`#69619 `_)
+- Fixed an issue when a shift count specified by a small constant 
``_BitInt()``,
+  in a left shift operation, could result in a faulty warnings about
+  ``shift count >= width of type``.
 - Clang now accepts anonymous members initialized with designated initializers
   inside templates.
   Fixes (`#65143 `_)

diff  --git a/clang/lib/Sema/SemaExpr.cpp b/clang/lib/Sema/SemaExpr.cpp
index 895b22805860d98..c2772bfb71c77e9 100644
--- a/clang/lib/Sema/SemaExpr.cpp
+++ b/clang/lib/Sema/SemaExpr.cpp
@@ -12143,8 +12143,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 auto FXSema = S.Context.getFixedPointSemantics(LHSExprType);
 LeftSize = FXSema.getWidth() - (unsigned)FXSema.hasUnsignedPadding();
   }
-  llvm::APInt LeftBits(Right.getBitWidth(), LeftSize);
-  if (Right.uge(LeftBits)) {
+  if (Right.uge(LeftSize)) {
 S.DiagRuntimeBehavior(Loc, RHS.get(),
   S.PDiag(diag::warn_shift_gt_typewidth)
 << RHS.get()->getSourceRange());
@@ -12186,7 +12185,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
 
   llvm::APInt ResultBits =
   static_cast(Right) + Left.getSignificantBits();
-  if (LeftBits.uge(ResultBits))
+  if (ResultBits.ule(LeftSize))
 return;
   llvm::APSInt Result = Left.extend(ResultBits.getLimitedValue());
   Result = Result.shl(Right);
@@ -12200,7 +12199,7 @@ static void DiagnoseBadShiftValues(Sema& S, ExprResult 
&LHS, ExprResult &RHS,
   // bugs -- if the result is cast back to an unsigned type, it will have the
   // expected value. Thus we place this behind a 
diff erent warning that can be
   // turned off separately if needed.
-  if (LeftBits == ResultBits - 1) {
+  if (ResultBits - 1 == LeftSize) {
 S.Diag(Loc, diag::warn_shift_result_sets_sign_bit)
 << HexResult << LHSType
 << LHS.get()->getSourceRange() << RHS.get()->getSourceRange();

diff  --git a/clang/test/Sema/c2x-expr-range.c 
b/clang/test/Sema/c2x-expr-range.c
index 73683e6bfe684aa..eff0b7cd4d9f546 100644
--- a/clang/test/Sema/c2x-expr-range.c
+++ b/clang/test/Sema/c2x-expr-range.c
@@ -12,3 +12,15 @@ void test1(int *a) {
 void test2(__uint128_t *a) {
   (void)(*a >> ((__uint128_t)__UINT64_MAX__ + 1) <= 0); // expected-warning 
{{shift count >= width of type}}
 }
+
+// Regression test for bug where a faulty warning was given. We don't expect to
+// see any warning in this case.
+_BitInt(128) test3(_BitInt(128) a) {
+  return a << 12wb;
+}
+
+// Similar to test3 above, but with a too large shift count. We expect to see a
+// warning in this case.
+_BitInt(128) test4(_BitInt(128) a) {
+  return a << 129wb; // expected-warning {{shift count >= width of type}}
+}



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


[clang] [Sema] Fixed faulty shift count warning (PR #69521)

2023-10-25 Thread Karl-Johan Karlsson via cfe-commits

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


[clang] [clang][Interp] Fix truncateCast() (PR #69911)

2023-10-25 Thread via cfe-commits


@@ -81,14 +89,20 @@ template  class IntegralAP final {
   }
 
   explicit operator bool() const { return !V.isZero(); }
-  explicit operator int8_t() const { return truncateCast(V); }
-  explicit operator uint8_t() const { return truncateCast(V); }
-  explicit operator int16_t() const { return truncateCast(V); }
-  explicit operator uint16_t() const { return truncateCast(V); }
-  explicit operator int32_t() const { return truncateCast(V); }
-  explicit operator uint32_t() const { return truncateCast(V); }
-  explicit operator int64_t() const { return truncateCast(V); }
-  explicit operator uint64_t() const { return truncateCast(V); }
+  explicit operator int8_t() const { return truncateCast(V); }
+  explicit operator uint8_t() const { return truncateCast(V); 
}
+  explicit operator int16_t() const { return truncateCast(V); 
}
+  explicit operator uint16_t() const {
+return truncateCast(V);
+  }
+  explicit operator int32_t() const { return truncateCast(V); 
}
+  explicit operator uint32_t() const {
+return truncateCast(V);
+  }
+  explicit operator int64_t() const { return truncateCast(V); 
}
+  explicit operator uint64_t() const {
+return truncateCast(V);
+  }

cor3ntin wrote:

That sounds like a great idea

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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Ben Shi via cfe-commits

https://github.com/benshi001 updated 
https://github.com/llvm/llvm-project/pull/70170

>From 3c23adbb74972c5ba98e08561a48bfd14a06b70f Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 25 Oct 2023 14:58:55 +0800
Subject: [PATCH] [analyzer][NFC] Combine similar methods of StreamChecker

Methods StreamChecker::preFread and StreamChecker::preFwrite are quite
similar, so they can be combined to StreamChecker::preFreadFwrite.
---
 .../clang/Basic/DiagnosticParseKinds.td   |  2 +-
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 41 ++-
 2 files changed, 14 insertions(+), 29 deletions(-)

diff --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index d6652e6a610c1be..902fbf4a0d692c0 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1349,7 +1349,7 @@ def warn_omp_extra_tokens_at_eol : Warning<
   "extra tokens at the end of '#pragma omp %0' are ignored">,
   InGroup;
 def err_omp_multiple_step_or_linear_modifier : Error<
-  "multiple %select{'step size'|'linear modifier'}0 found in linear clause">; 
+  "multiple %select{'step size'|'linear modifier'}0 found in linear clause">;
 def warn_pragma_expected_colon_r_paren : Warning<
   "missing ':' or ')' after %0 - ignoring">, InGroup;
 def err_omp_unknown_directive : Error<
diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index ef209f64f0c372c..4b7103c20557cc4 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -245,10 +245,10 @@ class StreamChecker : public CheckerStreamArgNo), C,
@@ -652,6 +650,11 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   if (!State)
 return;
 
+  if (!IsFread) {
+C.addTransition(State);
+return;
+  }
+
   SymbolRef Sym = StreamVal.getAsSymbol();
   if (Sym && State->get(Sym)) {
 const StreamState *SS = State->get(Sym);
@@ -662,24 +665,6 @@ void StreamChecker::preFread(const FnDescription *Desc, 
const CallEvent &Call,
   }
 }
 
-void StreamChecker::preFwrite(const FnDescription *Desc, const CallEvent &Call,
-  CheckerContext &C) const {
-  ProgramStateRef State = C.getState();
-  SVal StreamVal = getStreamArg(Desc, Call);
-  State = ensureStreamNonNull(StreamVal, Call.getArgExpr(Desc->StreamArgNo), C,
-  State);
-  if (!State)
-return;
-  State = ensureStreamOpened(StreamVal, C, State);
-  if (!State)
-return;
-  State = ensureNoFilePositionIndeterminate(StreamVal, C, State);
-  if (!State)
-return;
-
-  C.addTransition(State);
-}
-
 void StreamChecker::evalFreadFwrite(const FnDescription *Desc,
 const CallEvent &Call, CheckerContext &C,
 bool IsFread) const {
@@ -1222,7 +1207,7 @@ StreamChecker::reportLeaks(const SmallVector &LeakedSyms,
 
 PathDiagnosticLocation LocUsedForUniqueing;
 if (const Stmt *StreamStmt = StreamOpenNode->getStmtForDiagnostics())
-   LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
+  LocUsedForUniqueing = PathDiagnosticLocation::createBegin(
   StreamStmt, C.getSourceManager(),
   StreamOpenNode->getLocationContext());
 

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


[clang] [clang][Sema] Avoid non-empty unexpanded pack assertion for FunctionParmPackExpr (PR #69224)

2023-10-25 Thread Younan Zhang via cfe-commits

https://github.com/zyn0217 updated 
https://github.com/llvm/llvm-project/pull/69224

>From 880f271cbad4aacb7647bc402f636adf12ca1147 Mon Sep 17 00:00:00 2001
From: Younan Zhang 
Date: Mon, 16 Oct 2023 22:50:08 +0800
Subject: [PATCH] [clang][Sema] Avoid non-empty unexpanded pack assertion for
 FunctionParmPackExpr

Closes https://github.com/llvm/llvm-project/issues/61460.

We have FunctionParmPackExpr that serves as the unexpanded
expression but from which the visitor collects none, which may
lead to assertion failure during the template instantiation.
---
 clang/docs/ReleaseNotes.rst |  2 ++
 clang/lib/Sema/SemaTemplateVariadic.cpp | 13 +
 clang/test/SemaCXX/pr61460.cpp  | 13 +
 3 files changed, 28 insertions(+)
 create mode 100644 clang/test/SemaCXX/pr61460.cpp

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 4cc148905d4e130..66f2bc3efefa8bf 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -496,6 +496,8 @@ Bug Fixes in This Version
   Fixes (`#65143 `_)
 - Fix crash in formatting the real/imaginary part of a complex lvalue.
   Fixes (`#69218 `_)
+- Fixed an issue that a benign assertion might hit when instantiating a pack 
expansion
+  inside a lambda. (`#61460 
`_)
 
 Bug Fixes to Compiler Builtins
 ^^
diff --git a/clang/lib/Sema/SemaTemplateVariadic.cpp 
b/clang/lib/Sema/SemaTemplateVariadic.cpp
index dfcc78dafdc4c31..6ec7fb9ef331190 100644
--- a/clang/lib/Sema/SemaTemplateVariadic.cpp
+++ b/clang/lib/Sema/SemaTemplateVariadic.cpp
@@ -402,6 +402,19 @@ bool Sema::DiagnoseUnexpandedParameterPack(Expr *E,
   if (!E->containsUnexpandedParameterPack())
 return false;
 
+  // Exception: The `CollectUnexpandedParameterPacksVisitor` collects nothing
+  // from a FunctionParmPackExpr. In the context where the collector is being
+  // used such as `collectUnexpandedParameterPacks`, this type of expression
+  // is not expected to be collected.
+  //
+  // Nonetheless, this function for diagnosis is still called anyway during
+  // template instantiation, with an expression of such a type if we're inside 
a
+  // lambda with unexpanded parameters.
+  //
+  // Rule out this case to prevent the assertion failure.
+  if (isa(E) && getEnclosingLambda())
+return false;
+
   SmallVector Unexpanded;
   CollectUnexpandedParameterPacksVisitor(Unexpanded).TraverseStmt(E);
   assert(!Unexpanded.empty() && "Unable to find unexpanded parameter packs");
diff --git a/clang/test/SemaCXX/pr61460.cpp b/clang/test/SemaCXX/pr61460.cpp
new file mode 100644
index 000..471b1b39d23c2b7
--- /dev/null
+++ b/clang/test/SemaCXX/pr61460.cpp
@@ -0,0 +1,13 @@
+// RUN: %clang_cc1 -std=c++17 %s -fsyntax-only -verify
+
+template  void g(Ts... p1s) {
+  (void)[&](auto... p2s) { ([&] { p1s; p2s; }, ...); };
+}
+
+void f1() {
+  g();
+}
+
+template  void g2(Ts... p1s) {
+  (void)[&](auto... p2s) { [&] { p1s; p2s; }; }; // expected-error 
{{expression contains unexpanded parameter pack 'p2s'}}
+}

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


[clang] [clang][Sema] Avoid non-empty unexpanded pack assertion for FunctionParmPackExpr (PR #69224)

2023-10-25 Thread Younan Zhang via cfe-commits

zyn0217 wrote:

Done. Sorry for leaving irrelevant changes ;)

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


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

2023-10-25 Thread Nikita Popov via cfe-commits


@@ -6397,6 +6397,48 @@ static Value *simplifyBinaryIntrinsic(Function *F, Value 
*Op0, Value *Op1,
   return Constant::getNullValue(ReturnType);
 break;
   }
+  case Intrinsic::ptrmask: {
+// Fail loudly in case this is ever changed.
+// TODO: If vector types are supported the logic that checks if the mask is
+// useless should be updated to use generic constants.
+assert(!Op0->getType()->isVectorTy() && !Op1->getType()->isVectorTy() &&
+   "These simplifications where written at a time when ptrmask did not 
"
+   "support vector types and may not work for vectors");
+
+// NOTE: We can't apply these simplifications based on the value of Op1
+// because we need to preserve provenance.
+if (isa(Op0) || isa(Op1))
+  return PoisonValue::get(Op0->getType());
+
+if (Q.isUndefValue(Op0))
+  return Constant::getNullValue(Op0->getType());
+
+if (match(Op0, m_Zero()))
+  return Constant::getNullValue(Op0->getType());
+
+if (Op1->getType()->getScalarSizeInBits() ==
+Q.DL.getPointerTypeSizeInBits(Op0->getType())) {

nikic wrote:

Drop this check now? For the following transforms:

 * The ptrtoint one is safe, but you won't actually be able to trigger it if 
index type is smaller.
 * The allones/undef ones are safe and can be tested.
 * The knownbits one is safe with a truncate of the known bits. Can be tested.

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


[clang] [NFC] [Serializer] Pack information in serializer (PR #69287)

2023-10-25 Thread Vassil Vassilev via cfe-commits


@@ -617,24 +617,27 @@ void ASTDeclReader::VisitDecl(Decl *D) {
Reader.getContext());
   }
   D->setLocation(ThisDeclLoc);
-  D->InvalidDecl = Record.readInt();
-  if (Record.readInt()) { // hasAttrs
+
+  uint64_t DeclBits = Record.readInt();
+  D->InvalidDecl = DeclBits & 0x1;
+  D->setImplicit(DeclBits & (1 << 2));
+  D->Used = (DeclBits >> 3) & 0x1;
+  IsDeclMarkedUsed |= D->Used;
+  D->setReferenced(DeclBits & (1 << 4));
+  D->setTopLevelDeclInObjCContainer(DeclBits & (1 << 5));
+  D->setAccess((AccessSpecifier)((DeclBits >> 6) & 0x3));
+  D->FromASTFile = true;
+  auto ModuleOwnership = (Decl::ModuleOwnershipKind)((DeclBits >> 8) & 0x7);

vgvassilev wrote:

That looks more readable to me. In the case of `ModuleOwnershipKind` can we use 
the bit size either with `sizeof` or via `NextInContextAndBits`? If we use 
`sizeof` this could look like:
`auto ModuleOwnership = Bits.getNextBit());` but we 
will likely read/write 8 bits instead of 3 in this case...

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


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

2023-10-25 Thread Nikita Popov via cfe-commits


@@ -1973,6 +1978,28 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst 
&CI) {
   *II, Builder.CreateIntrinsic(InnerPtr->getType(), Intrinsic::ptrmask,
{InnerPtr, NewMask}));
 }
+bool Changed = false;
+// See if we can deduce non-null.
+if (!CI.hasRetAttr(Attribute::NonNull) &&
+(Known.isNonZero() ||
+ isKnownNonZero(II, DL, /*Depth*/ 0, &AC, II, &DT))) {
+  CI.addRetAttr(Attribute::NonNull);
+  Changed = true;
+}
+
+unsigned NewAlignmentLog =
+std::min(Value::MaxAlignmentExponent,
+ std::min(BitWidth - 1, Known.countMinTrailingZeros()));
+// Known bits will capture if we had alignment information associated with
+// the pointer argument.
+if (NewAlignmentLog > Log2(CI.getRetAlign().valueOrOne())) {
+  CI.removeRetAttr(Attribute::Alignment);

nikic wrote:

No need to explicitly remove the old attribute.

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


[clang] [PassBuilder] Add a mechanism for adding passbuilder callbacks for static builds (PR #70171)

2023-10-25 Thread William Moses via cfe-commits

https://github.com/wsmoses updated 
https://github.com/llvm/llvm-project/pull/70171

>From 9ccb8b7bff8adc03bf027766005762b350a803bc Mon Sep 17 00:00:00 2001
From: "William S. Moses" 
Date: Wed, 25 Oct 2023 02:10:32 -0500
Subject: [PATCH] [PassBuilder] Add a mechanism for adding passbuilder
 callbacks without an extension mechanism or dlopen of plugin

---
 clang/lib/CodeGen/BackendUtil.cpp  | 3 +++
 llvm/include/llvm/Passes/PassBuilder.h | 5 +
 llvm/lib/LTO/LTOBackend.cpp| 3 +++
 llvm/lib/Passes/PassBuilder.cpp| 3 +++
 llvm/tools/opt/NewPMDriver.cpp | 5 -
 5 files changed, 18 insertions(+), 1 deletion(-)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..8dbe4d942df278d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -909,6 +909,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Register the target library analysis directly and give it a customized
   // preset TLI.
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 2c7ceda7998eda1..d018dd1e69166f0 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -739,6 +739,11 @@ bool parseAnalysisUtilityPasses(
 
   return false;
 }
+
+//! List of pass builder callbacks to be applied, in addition to those imported
+//! from plugins or LLVM extensions.
+extern SmallVector>
+ListRegisterPassBuilderCallbacks;
 }
 
 #endif
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index ccc4276e36dacf0..28aabf8bdebb4d6 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -187,6 +187,9 @@ static void RegisterPassPlugins(ArrayRef 
PassPlugins,
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Load requested pass plugins and let them register pass builder callbacks
   for (auto &PluginFN : PassPlugins) {
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index fde759026e5d780..ff63988566b8649 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -2099,3 +2099,6 @@ void PassBuilder::registerParseTopLevelPipelineCallback(
 &C) {
   TopLevelPipelineParsingCallbacks.push_back(C);
 }
+
+llvm::SmallVector>
+ListRegisterPassBuilderCallbacks;
\ No newline at end of file
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 6ae3f87099afd64..b6b73f8d0ec7842 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -431,6 +431,9 @@ bool llvm::runPassPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Specially handle the alias analysis manager so that we can register
   // a custom pipeline of AA passes with it.
@@ -545,4 +548,4 @@ bool llvm::runPassPipeline(
 void llvm::printPasses(raw_ostream &OS) {
   PassBuilder PB;
   PB.printPassNames(OS);
-}
+}
\ 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] [PassBuilder] Add a mechanism for adding passbuilder callbacks for static builds (PR #70171)

2023-10-25 Thread William Moses via cfe-commits

https://github.com/wsmoses updated 
https://github.com/llvm/llvm-project/pull/70171

>From 8b0e0939ea51768b9e1257e816556d245c91134b Mon Sep 17 00:00:00 2001
From: "William S. Moses" 
Date: Wed, 25 Oct 2023 02:10:32 -0500
Subject: [PATCH] [PassBuilder] Add a mechanism for adding passbuilder
 callbacks without an extension mechanism or dlopen of plugin

---
 clang/lib/CodeGen/BackendUtil.cpp  | 3 +++
 llvm/include/llvm/Passes/PassBuilder.h | 5 +
 llvm/lib/LTO/LTOBackend.cpp| 3 +++
 llvm/lib/Passes/PassBuilder.cpp| 3 +++
 llvm/tools/opt/NewPMDriver.cpp | 3 +++
 5 files changed, 17 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..8dbe4d942df278d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -909,6 +909,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Register the target library analysis directly and give it a customized
   // preset TLI.
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 2c7ceda7998eda1..d018dd1e69166f0 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -739,6 +739,11 @@ bool parseAnalysisUtilityPasses(
 
   return false;
 }
+
+//! List of pass builder callbacks to be applied, in addition to those imported
+//! from plugins or LLVM extensions.
+extern SmallVector>
+ListRegisterPassBuilderCallbacks;
 }
 
 #endif
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index ccc4276e36dacf0..28aabf8bdebb4d6 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -187,6 +187,9 @@ static void RegisterPassPlugins(ArrayRef 
PassPlugins,
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Load requested pass plugins and let them register pass builder callbacks
   for (auto &PluginFN : PassPlugins) {
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index fde759026e5d780..ff63988566b8649 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -2099,3 +2099,6 @@ void PassBuilder::registerParseTopLevelPipelineCallback(
 &C) {
   TopLevelPipelineParsingCallbacks.push_back(C);
 }
+
+llvm::SmallVector>
+ListRegisterPassBuilderCallbacks;
\ No newline at end of file
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 6ae3f87099afd64..f072120d7461d4e 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -431,6 +431,9 @@ bool llvm::runPassPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Specially handle the alias analysis manager so that we can register
   // a custom pipeline of AA passes with it.

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


[clang] [NFC] [Serializer] Pack information in serializer (PR #69287)

2023-10-25 Thread Chuanqi Xu via cfe-commits


@@ -617,24 +617,27 @@ void ASTDeclReader::VisitDecl(Decl *D) {
Reader.getContext());
   }
   D->setLocation(ThisDeclLoc);
-  D->InvalidDecl = Record.readInt();
-  if (Record.readInt()) { // hasAttrs
+
+  uint64_t DeclBits = Record.readInt();
+  D->InvalidDecl = DeclBits & 0x1;
+  D->setImplicit(DeclBits & (1 << 2));
+  D->Used = (DeclBits >> 3) & 0x1;
+  IsDeclMarkedUsed |= D->Used;
+  D->setReferenced(DeclBits & (1 << 4));
+  D->setTopLevelDeclInObjCContainer(DeclBits & (1 << 5));
+  D->setAccess((AccessSpecifier)((DeclBits >> 6) & 0x3));
+  D->FromASTFile = true;
+  auto ModuleOwnership = (Decl::ModuleOwnershipKind)((DeclBits >> 8) & 0x7);

ChuanqiXu9 wrote:

Yes... and I feel the magic numbers for some types (e.g., `AccessSpecifier` and 
`ModuleOwnershipKind`) might not be so scaring. Since the devs can see 
`AccessSpecifier` and `ModuleOwnershipKind` here then they can get the size 
quickly. Also even if now we have to look at both ASTWriterDecl.cpp and 
ASTReaderDecl.cpp to change anything. I mean, it is already tightly bounded.

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


[clang] [PassBuilder] Add a mechanism for adding passbuilder callbacks for static builds (PR #70171)

2023-10-25 Thread William Moses via cfe-commits

https://github.com/wsmoses updated 
https://github.com/llvm/llvm-project/pull/70171

>From fca61de1d6cf5fe68cfb51bfe5ca73d5d3948ba5 Mon Sep 17 00:00:00 2001
From: "William S. Moses" 
Date: Wed, 25 Oct 2023 02:10:32 -0500
Subject: [PATCH] [PassBuilder] Add a mechanism for adding passbuilder
 callbacks without an extension mechanism or dlopen of plugin

---
 clang/lib/CodeGen/BackendUtil.cpp  | 3 +++
 llvm/include/llvm/Passes/PassBuilder.h | 5 +
 llvm/lib/LTO/LTOBackend.cpp| 3 +++
 llvm/lib/Passes/PassBuilder.cpp| 3 +++
 llvm/tools/opt/NewPMDriver.cpp | 3 +++
 5 files changed, 17 insertions(+)

diff --git a/clang/lib/CodeGen/BackendUtil.cpp 
b/clang/lib/CodeGen/BackendUtil.cpp
index 70accce456d3c07..8dbe4d942df278d 100644
--- a/clang/lib/CodeGen/BackendUtil.cpp
+++ b/clang/lib/CodeGen/BackendUtil.cpp
@@ -909,6 +909,9 @@ void EmitAssemblyHelper::RunOptimizationPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Register the target library analysis directly and give it a customized
   // preset TLI.
diff --git a/llvm/include/llvm/Passes/PassBuilder.h 
b/llvm/include/llvm/Passes/PassBuilder.h
index 2c7ceda7998eda1..d018dd1e69166f0 100644
--- a/llvm/include/llvm/Passes/PassBuilder.h
+++ b/llvm/include/llvm/Passes/PassBuilder.h
@@ -739,6 +739,11 @@ bool parseAnalysisUtilityPasses(
 
   return false;
 }
+
+//! List of pass builder callbacks to be applied, in addition to those imported
+//! from plugins or LLVM extensions.
+extern SmallVector>
+ListRegisterPassBuilderCallbacks;
 }
 
 #endif
diff --git a/llvm/lib/LTO/LTOBackend.cpp b/llvm/lib/LTO/LTOBackend.cpp
index ccc4276e36dacf0..28aabf8bdebb4d6 100644
--- a/llvm/lib/LTO/LTOBackend.cpp
+++ b/llvm/lib/LTO/LTOBackend.cpp
@@ -187,6 +187,9 @@ static void RegisterPassPlugins(ArrayRef 
PassPlugins,
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Load requested pass plugins and let them register pass builder callbacks
   for (auto &PluginFN : PassPlugins) {
diff --git a/llvm/lib/Passes/PassBuilder.cpp b/llvm/lib/Passes/PassBuilder.cpp
index fde759026e5d780..21a7ecb88e96418 100644
--- a/llvm/lib/Passes/PassBuilder.cpp
+++ b/llvm/lib/Passes/PassBuilder.cpp
@@ -2099,3 +2099,6 @@ void PassBuilder::registerParseTopLevelPipelineCallback(
 &C) {
   TopLevelPipelineParsingCallbacks.push_back(C);
 }
+
+llvm::SmallVector>
+ListRegisterPassBuilderCallbacks;
diff --git a/llvm/tools/opt/NewPMDriver.cpp b/llvm/tools/opt/NewPMDriver.cpp
index 6ae3f87099afd64..f072120d7461d4e 100644
--- a/llvm/tools/opt/NewPMDriver.cpp
+++ b/llvm/tools/opt/NewPMDriver.cpp
@@ -431,6 +431,9 @@ bool llvm::runPassPipeline(
 #define HANDLE_EXTENSION(Ext)  
\
   get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
 #include "llvm/Support/Extension.def"
+  for (auto PassCallback : ListRegisterPassBuilderCallbacks) {
+PassCallback(PB);
+  }
 
   // Specially handle the alias analysis manager so that we can register
   // a custom pipeline of AA passes with it.

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


[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

2023-10-25 Thread via cfe-commits

https://github.com/cor3ntin created 
https://github.com/llvm/llvm-project/pull/70176

Per https://eel.is/c++draft/dcl.fct.def.default#2.2, the explicit object 
parameter of a defaulted special member function must be of the same type as 
the one of an equivalent implicitly defaulted function, ignoring references.

Fixes #69233

>From 441f24714729f35588487d3109e3c42d59e0a610 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 25 Oct 2023 10:08:24 +0200
Subject: [PATCH] [Clang] Diagnose defaulted assignment operator with
 incompatible object parameter.

Per https://eel.is/c++draft/dcl.fct.def.default#2.2, the explicit object
parameter of a defaulted special member function must be of the same type
as the one of an equivalent implicitly defaulted function,
ignoring references.

Fixes #69233
---
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/lib/Sema/SemaDeclCXX.cpp| 15 +
 clang/test/SemaCXX/cxx2b-deducing-this.cpp| 31 +++
 3 files changed, 49 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a673ce726d6c220..6e138683334c2c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9481,6 +9481,9 @@ def err_defaulted_special_member_return_type : Error<
 def err_defaulted_special_member_quals : Error<
   "an explicitly-defaulted %select{copy|move}0 assignment operator may not "
   "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">;
+def err_defaulted_special_member_explicit_object_mismatch : Error<
+  "the type of the explicit object parameter of an explicitly-defaulted "
+  "%select{copy|move}0 assignment operator should match the type of the class 
%1">;
 def err_defaulted_special_member_volatile_param : Error<
   "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 
"
   "may not be volatile">;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6ec..35554fca5776f2c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7748,6 +7748,21 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 HadError = true;
   }
 }
+// [C++23][dcl.fct.def.default]/p2.2
+// if F2 has an implicit object parameter of type “reference to C”,
+// F1 may be an explicit object member function whose explicit object
+// parameter is of (possibly different) type “reference to C”,
+// in which case the type of F1 would differ from the type of F2
+// in that the type of F1 has an additional parameter;
+
if(!Context.hasSameType(ThisType.getNonReferenceType().getUnqualifiedType(), 
Context.getRecordType(RD))) {
+  if (DeleteOnTypeMismatch)
+ShouldDeleteForTypeMismatch = true;
+  else {
+Diag(MD->getLocation(), 
diag::err_defaulted_special_member_explicit_object_mismatch)
+<< (CSM == CXXMoveAssignment) << RD;
+HadError = true;
+  }
+}
   }
 
   // Check for parameter type matching.
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 535381e876da9c7..f9e73b41e2c330f 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -585,3 +585,34 @@ class Server : public Thing {
 S name_;
 };
 }
+
+namespace GH69233 {
+struct Base {};
+struct S : Base {
+int j;
+S& operator=(this Base& self, const S&) = default;
+// expected-warning@-1 {{explicitly defaulted copy assignment operator is 
implicitly deleted}}
+// expected-note@-2 {{function is implicitly deleted because its declared 
type does not match the type of an implicit copy assignment operator}}
+// expected-note@-3 {{explicitly defaulted function was implicitly deleted 
here}}
+};
+
+struct S2 {
+S2& operator=(this int&& self, const S2&);
+S2& operator=(this int&& self, S2&&);
+operator int();
+};
+
+S2& S2::operator=(this int&& self, const S2&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted copy assignment operator should match the type of the 
class 'S2'}}
+
+S2& S2::operator=(this int&& self, S2&&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted move assignment operator should match the type of the 
class 'S2'}}
+
+void test() {
+S s;
+s = s; // expected-error {{object of type 'S' cannot be assigned because 
its copy assignment operator is implicitly deleted}}
+S2 s2;
+s2 = s2;
+}
+
+}

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


[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

2023-10-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: cor3ntin (cor3ntin)


Changes

Per https://eel.is/c++draft/dcl.fct.def.default#2.2, the explicit 
object parameter of a defaulted special member function must be of the same 
type as the one of an equivalent implicitly defaulted function, ignoring 
references.

Fixes #69233

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


3 Files Affected:

- (modified) clang/include/clang/Basic/DiagnosticSemaKinds.td (+3) 
- (modified) clang/lib/Sema/SemaDeclCXX.cpp (+15) 
- (modified) clang/test/SemaCXX/cxx2b-deducing-this.cpp (+31) 


``diff
diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a673ce726d6c220..6e138683334c2c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9481,6 +9481,9 @@ def err_defaulted_special_member_return_type : Error<
 def err_defaulted_special_member_quals : Error<
   "an explicitly-defaulted %select{copy|move}0 assignment operator may not "
   "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">;
+def err_defaulted_special_member_explicit_object_mismatch : Error<
+  "the type of the explicit object parameter of an explicitly-defaulted "
+  "%select{copy|move}0 assignment operator should match the type of the class 
%1">;
 def err_defaulted_special_member_volatile_param : Error<
   "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 
"
   "may not be volatile">;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6ec..35554fca5776f2c 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7748,6 +7748,21 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 HadError = true;
   }
 }
+// [C++23][dcl.fct.def.default]/p2.2
+// if F2 has an implicit object parameter of type “reference to C”,
+// F1 may be an explicit object member function whose explicit object
+// parameter is of (possibly different) type “reference to C”,
+// in which case the type of F1 would differ from the type of F2
+// in that the type of F1 has an additional parameter;
+
if(!Context.hasSameType(ThisType.getNonReferenceType().getUnqualifiedType(), 
Context.getRecordType(RD))) {
+  if (DeleteOnTypeMismatch)
+ShouldDeleteForTypeMismatch = true;
+  else {
+Diag(MD->getLocation(), 
diag::err_defaulted_special_member_explicit_object_mismatch)
+<< (CSM == CXXMoveAssignment) << RD;
+HadError = true;
+  }
+}
   }
 
   // Check for parameter type matching.
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 535381e876da9c7..f9e73b41e2c330f 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -585,3 +585,34 @@ class Server : public Thing {
 S name_;
 };
 }
+
+namespace GH69233 {
+struct Base {};
+struct S : Base {
+int j;
+S& operator=(this Base& self, const S&) = default;
+// expected-warning@-1 {{explicitly defaulted copy assignment operator is 
implicitly deleted}}
+// expected-note@-2 {{function is implicitly deleted because its declared 
type does not match the type of an implicit copy assignment operator}}
+// expected-note@-3 {{explicitly defaulted function was implicitly deleted 
here}}
+};
+
+struct S2 {
+S2& operator=(this int&& self, const S2&);
+S2& operator=(this int&& self, S2&&);
+operator int();
+};
+
+S2& S2::operator=(this int&& self, const S2&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted copy assignment operator should match the type of the 
class 'S2'}}
+
+S2& S2::operator=(this int&& self, S2&&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted move assignment operator should match the type of the 
class 'S2'}}
+
+void test() {
+S s;
+s = s; // expected-error {{object of type 'S' cannot be assigned because 
its copy assignment operator is implicitly deleted}}
+S2 s2;
+s2 = s2;
+}
+
+}

``




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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-25 Thread Yeting Kuo via cfe-commits

https://github.com/yetingk updated 
https://github.com/llvm/llvm-project/pull/66043

>From 91bb1d9884276a37f93515a648aa6ece353fdc70 Mon Sep 17 00:00:00 2001
From: Yeting Kuo 
Date: Tue, 12 Sep 2023 12:28:00 +0800
Subject: [PATCH 1/3] [RISCV] Add MC layer support for Zicfiss.

The patch adds the instructions in Zicfiss extension. Zicfiss extension is
to support shadow stack for control flow integrity.

Differential Revision: https://reviews.llvm.org/D152793
---
 .../test/Preprocessor/riscv-target-features.c |   9 ++
 llvm/docs/RISCVUsage.rst  |   3 +
 llvm/lib/Support/RISCVISAInfo.cpp |   2 +
 .../RISCV/Disassembler/RISCVDisassembler.cpp  |  29 +
 llvm/lib/Target/RISCV/RISCVFeatures.td|   7 ++
 llvm/lib/Target/RISCV/RISCVInstrInfo.td   |   9 +-
 .../lib/Target/RISCV/RISCVInstrInfoZicfiss.td |  86 +++
 llvm/lib/Target/RISCV/RISCVRegisterInfo.cpp   |   3 +
 llvm/lib/Target/RISCV/RISCVRegisterInfo.td|   9 ++
 llvm/test/MC/RISCV/attribute-arch.s   |   3 +
 llvm/test/MC/RISCV/rv32zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv32zicfiss-valid.s| 103 ++
 llvm/test/MC/RISCV/rv64zicfiss-invalid.s  |  20 
 llvm/test/MC/RISCV/rv64zicfiss-valid.s| 103 ++
 14 files changed, 402 insertions(+), 4 deletions(-)
 create mode 100644 llvm/lib/Target/RISCV/RISCVInstrInfoZicfiss.td
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv32zicfiss-valid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-invalid.s
 create mode 100644 llvm/test/MC/RISCV/rv64zicfiss-valid.s

diff --git a/clang/test/Preprocessor/riscv-target-features.c 
b/clang/test/Preprocessor/riscv-target-features.c
index 02b67dc7944ba88..163eba81543ee5b 100644
--- a/clang/test/Preprocessor/riscv-target-features.c
+++ b/clang/test/Preprocessor/riscv-target-features.c
@@ -113,6 +113,7 @@
 // CHECK-NOT: __riscv_zfa {{.*$}}
 // CHECK-NOT: __riscv_zfbfmin {{.*$}}
 // CHECK-NOT: __riscv_zicfilp {{.*$}}
+// CHECK-NOT: __riscv_zicfiss {{.*$}}
 // CHECK-NOT: __riscv_zicond {{.*$}}
 // CHECK-NOT: __riscv_ztso {{.*$}}
 // CHECK-NOT: __riscv_zvbb {{.*$}}
@@ -1220,3 +1221,11 @@
 // RUN: -march=rv64i_zve32x_zvkt1p0 -x c -E -dM %s \
 // RUN: -o - | FileCheck --check-prefix=CHECK-ZVKT-EXT %s
 // CHECK-ZVKT-EXT: __riscv_zvkt 100{{$}}
+
+// RUN: %clang -target riscv32 -menable-experimental-extensions \
+// RUN: -march=rv32izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// RUN: %clang -target riscv64 -menable-experimental-extensions \
+// RUN: -march=rv64izicfiss0p3 -x c -E -dM %s \
+// RUN: -o - | FileCheck --check-prefix=CHECK-ZICFISS-EXT %s
+// CHECK-ZICFISS-EXT: __riscv_zicfiss 3000{{$}}
diff --git a/llvm/docs/RISCVUsage.rst b/llvm/docs/RISCVUsage.rst
index 8d12d58738c609a..31c55def0a7694a 100644
--- a/llvm/docs/RISCVUsage.rst
+++ b/llvm/docs/RISCVUsage.rst
@@ -205,6 +205,9 @@ The primary goal of experimental support is to assist in 
the process of ratifica
 ``experimental-zicfilp``
   LLVM implements the `0.2 draft specification 
`__.
 
+``experimental-zicfiss``
+  LLVM implements the `0.3.1 draft specification 
`__.
+
 ``experimental-zicond``
   LLVM implements the `1.0-rc1 draft specification 
`__.
 
diff --git a/llvm/lib/Support/RISCVISAInfo.cpp 
b/llvm/lib/Support/RISCVISAInfo.cpp
index a02c9842e85839a..c414b62c5f31092 100644
--- a/llvm/lib/Support/RISCVISAInfo.cpp
+++ b/llvm/lib/Support/RISCVISAInfo.cpp
@@ -170,6 +170,8 @@ static const RISCVSupportedExtension 
SupportedExperimentalExtensions[] = {
 {"zfbfmin", RISCVExtensionVersion{0, 8}},
 
 {"zicfilp", RISCVExtensionVersion{0, 2}},
+{"zicfiss", RISCVExtensionVersion{0, 3}},
+
 {"zicond", RISCVExtensionVersion{1, 0}},
 
 {"ztso", RISCVExtensionVersion{0, 1}},
diff --git a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp 
b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
index d561d90d3088c1a..14b3122f0fecbdb 100644
--- a/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
+++ b/llvm/lib/Target/RISCV/Disassembler/RISCVDisassembler.cpp
@@ -74,6 +74,17 @@ static DecodeStatus DecodeGPRRegisterClass(MCInst &Inst, 
uint32_t RegNo,
   return MCDisassembler::Success;
 }
 
+static DecodeStatus DecodeGPRRARegisterClass(MCInst &Inst, uint32_t RegNo,
+ uint64_t Address,
+ const MCDisassembler *Decoder) {
+  MCRegister Reg = RISCV::X0 + RegNo;
+  if (Reg != RISCV::X1 && Reg != RISCV::X5)
+return MCDisassembler::Fail;
+
+  Inst.addOperand(MCOperand::createReg(Reg));
+  return MCDisassembler::Success;
+}
+
 static DecodeStatus DecodeFPR16RegisterClass(MCInst &Inst, uint32_t RegNo,

[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-25 Thread Yeting Kuo via cfe-commits


@@ -0,0 +1,86 @@
+//===-- RISCVInstrInfoZicfiss.td - RISC-V Zicfiss -*- tablegen 
-*--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+//===--===//
+// Instruction class templates
+//===--===//
+
+class RVC_SSInst rs1val, RegisterClass reg_class, string opcodestr> :
+  RVInst16<(outs), (ins reg_class:$rs1), opcodestr, "$rs1", [], 
InstFormatOther> {
+  let Inst{15-13} = 0b011;
+  let Inst{12} = 0;
+  let Inst{11-7} = rs1val;
+  let Inst{6-2} = 0b0;
+  let Inst{1-0} = 0b01;
+  let DecoderMethod = "decodeCSSPushPopchk";
+}
+
+//===--===//
+// Instructions
+//===--===//
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in {
+let DecoderNamespace = "RV32Zicfiss", Predicates = [HasStdExtZicfiss, IsRV32] 
in
+def SSLW : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "sslw", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+
+let Predicates = [HasStdExtZicfiss, IsRV64] in
+def SSLD : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "ssld", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Predicates = [HasStdExtZicfiss] in {
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+def SSPOPCHK : RVInstI<0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs1), 
"sspopchk",
+   "$rs1"> {
+  let rd = 0;
+  let imm12 = 0b10011100;
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0 in {
+def SSINCP : RVInstI<0b100, OPC_SYSTEM, (outs), (ins), "ssincp", ""> {

yetingk wrote:

Done.

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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-25 Thread Yeting Kuo via cfe-commits


@@ -0,0 +1,86 @@
+//===-- RISCVInstrInfoZicfiss.td - RISC-V Zicfiss -*- tablegen 
-*--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+//===--===//
+// Instruction class templates
+//===--===//
+
+class RVC_SSInst rs1val, RegisterClass reg_class, string opcodestr> :
+  RVInst16<(outs), (ins reg_class:$rs1), opcodestr, "$rs1", [], 
InstFormatOther> {
+  let Inst{15-13} = 0b011;
+  let Inst{12} = 0;
+  let Inst{11-7} = rs1val;
+  let Inst{6-2} = 0b0;
+  let Inst{1-0} = 0b01;
+  let DecoderMethod = "decodeCSSPushPopchk";
+}
+
+//===--===//
+// Instructions
+//===--===//
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in {
+let DecoderNamespace = "RV32Zicfiss", Predicates = [HasStdExtZicfiss, IsRV32] 
in
+def SSLW : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "sslw", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+
+let Predicates = [HasStdExtZicfiss, IsRV64] in
+def SSLD : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "ssld", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Predicates = [HasStdExtZicfiss] in {
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+def SSPOPCHK : RVInstI<0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs1), 
"sspopchk",
+   "$rs1"> {
+  let rd = 0;
+  let imm12 = 0b10011100;
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0 in {
+def SSINCP : RVInstI<0b100, OPC_SYSTEM, (outs), (ins), "ssincp", ""> {
+  let imm12 = 0b10011100;
+  let rs1 = 0b0;
+  let rd = 0b0;
+}
+
+def SSRDP : RVInstI<0b100, OPC_SYSTEM, (outs GPRNoX0:$rd), (ins), "ssrdp", 
"$rd"> {
+  let imm12 = 0b10011101;
+  let rs1 = 0b0;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def SSPUSH : RVInstR<0b101, 0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs2),
+ "sspush", "$rs2"> {
+  let rd = 0b0;
+  let rs1 = 0b0;
+}
+} // Predicates = [HasStdExtZicfiss]
+
+let Predicates = [HasStdExtZicfiss, HasStdExtCOrZca] in {
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def C_SSPUSH : RVC_SSInst<0b1, GPRX1, "c.sspush">;
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in

yetingk wrote:

Done.

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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-25 Thread Yeting Kuo via cfe-commits


@@ -0,0 +1,86 @@
+//===-- RISCVInstrInfoZicfiss.td - RISC-V Zicfiss -*- tablegen 
-*--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+//===--===//
+// Instruction class templates
+//===--===//
+
+class RVC_SSInst rs1val, RegisterClass reg_class, string opcodestr> :
+  RVInst16<(outs), (ins reg_class:$rs1), opcodestr, "$rs1", [], 
InstFormatOther> {
+  let Inst{15-13} = 0b011;
+  let Inst{12} = 0;
+  let Inst{11-7} = rs1val;
+  let Inst{6-2} = 0b0;
+  let Inst{1-0} = 0b01;
+  let DecoderMethod = "decodeCSSPushPopchk";
+}
+
+//===--===//
+// Instructions
+//===--===//
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in {
+let DecoderNamespace = "RV32Zicfiss", Predicates = [HasStdExtZicfiss, IsRV32] 
in
+def SSLW : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "sslw", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+
+let Predicates = [HasStdExtZicfiss, IsRV64] in
+def SSLD : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "ssld", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Predicates = [HasStdExtZicfiss] in {
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+def SSPOPCHK : RVInstI<0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs1), 
"sspopchk",
+   "$rs1"> {
+  let rd = 0;
+  let imm12 = 0b10011100;
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0 in {
+def SSINCP : RVInstI<0b100, OPC_SYSTEM, (outs), (ins), "ssincp", ""> {
+  let imm12 = 0b10011100;
+  let rs1 = 0b0;
+  let rd = 0b0;
+}
+
+def SSRDP : RVInstI<0b100, OPC_SYSTEM, (outs GPRNoX0:$rd), (ins), "ssrdp", 
"$rd"> {
+  let imm12 = 0b10011101;
+  let rs1 = 0b0;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def SSPUSH : RVInstR<0b101, 0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs2),
+ "sspush", "$rs2"> {
+  let rd = 0b0;
+  let rs1 = 0b0;
+}
+} // Predicates = [HasStdExtZicfiss]
+
+let Predicates = [HasStdExtZicfiss, HasStdExtCOrZca] in {
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def C_SSPUSH : RVC_SSInst<0b1, GPRX1, "c.sspush">;
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def C_SSPOPCHK : RVC_SSInst<0b00101, GPRX5, "c.sspopchk">;
+} // Predicates = [HasStdExtZicfiss, HasStdExtCOrZca]
+
+let Predicates = [HasStdExtZicfiss, HasStdExtC], Uses = [SSP], Defs = [SSP],

yetingk wrote:

Done.

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


[clang] [RISCV] Add MC layer support for Zicfiss. (PR #66043)

2023-10-25 Thread Yeting Kuo via cfe-commits


@@ -0,0 +1,86 @@
+//===-- RISCVInstrInfoZicfiss.td - RISC-V Zicfiss -*- tablegen 
-*--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+//===--===//
+// Instruction class templates
+//===--===//
+
+class RVC_SSInst rs1val, RegisterClass reg_class, string opcodestr> :
+  RVInst16<(outs), (ins reg_class:$rs1), opcodestr, "$rs1", [], 
InstFormatOther> {
+  let Inst{15-13} = 0b011;
+  let Inst{12} = 0;
+  let Inst{11-7} = rs1val;
+  let Inst{6-2} = 0b0;
+  let Inst{1-0} = 0b01;
+  let DecoderMethod = "decodeCSSPushPopchk";
+}
+
+//===--===//
+// Instructions
+//===--===//
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in {
+let DecoderNamespace = "RV32Zicfiss", Predicates = [HasStdExtZicfiss, IsRV32] 
in
+def SSLW : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "sslw", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+
+let Predicates = [HasStdExtZicfiss, IsRV64] in
+def SSLD : RVInstI<0b100, OPC_SYSTEM, (outs GPRX1X5:$rd), (ins), "ssld", 
"$rd"> {
+  let rs1 = 0;
+  let imm12 = 0b10011100;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Predicates = [HasStdExtZicfiss] in {
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0 in
+def SSPOPCHK : RVInstI<0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs1), 
"sspopchk",
+   "$rs1"> {
+  let rd = 0;
+  let imm12 = 0b10011100;
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 1, mayStore = 0
+
+let Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0 in {
+def SSINCP : RVInstI<0b100, OPC_SYSTEM, (outs), (ins), "ssincp", ""> {
+  let imm12 = 0b10011100;
+  let rs1 = 0b0;
+  let rd = 0b0;
+}
+
+def SSRDP : RVInstI<0b100, OPC_SYSTEM, (outs GPRNoX0:$rd), (ins), "ssrdp", 
"$rd"> {
+  let imm12 = 0b10011101;
+  let rs1 = 0b0;
+}
+} // Uses = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 0
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def SSPUSH : RVInstR<0b101, 0b100, OPC_SYSTEM, (outs), (ins GPRX1X5:$rs2),
+ "sspush", "$rs2"> {
+  let rd = 0b0;
+  let rs1 = 0b0;
+}
+} // Predicates = [HasStdExtZicfiss]
+
+let Predicates = [HasStdExtZicfiss, HasStdExtCOrZca] in {
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def C_SSPUSH : RVC_SSInst<0b1, GPRX1, "c.sspush">;
+
+let Uses = [SSP], Defs = [SSP], hasSideEffects = 0, mayLoad = 0, mayStore = 1 
in
+def C_SSPOPCHK : RVC_SSInst<0b00101, GPRX5, "c.sspopchk">;
+} // Predicates = [HasStdExtZicfiss, HasStdExtCOrZca]
+
+let Predicates = [HasStdExtZicfiss, HasStdExtC], Uses = [SSP], Defs = [SSP],
+hasSideEffects = 0, mayLoad = 0, mayStore = 0 in
+def C_SSINCP : RVInst16<(outs), (ins), "c.ssincp", "", [], InstFormatOther> {
+  let Inst{15-13} = 0b011;
+  let Inst{12} = 0;
+  let Inst{11-7} = 0b00011;
+  let Inst{6-2} = 0b0;
+  let Inst{1-0} = 0b01;
+}

yetingk wrote:

Done.

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


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

2023-10-25 Thread Nikita Popov via cfe-commits


@@ -143,7 +155,7 @@ Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, 
APInt DemandedMask,
 return SimplifyMultipleUseDemandedBits(I, DemandedMask, Known, Depth, 
CxtI);
 
   KnownBits LHSKnown(BitWidth), RHSKnown(BitWidth);
-
+  bool MaySimplifyAsConstant = true;

nikic wrote:

Possibly this flag can be replaced by a isPointerTy check below? This seems 
like it should also hold for other instructions working on pointers, if we were 
to handle them.

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


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

2023-10-25 Thread Nikita Popov via cfe-commits


@@ -984,7 +1041,7 @@ Value *InstCombinerImpl::SimplifyDemandedUseBits(Value *V, 
APInt DemandedMask,
 
   // If the client is only demanding bits that we know, return the known
   // constant.
-  if (DemandedMask.isSubsetOf(Known.Zero|Known.One))
+  if (MaySimplifyAsConstant && DemandedMask.isSubsetOf(Known.Zero | Known.One))

nikic wrote:

FWIW, it would be legal to return a inttoptr constant for non-zero values. But 
not sure if it would be a good idea, so staying conservative is reasonable.

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


[clang] 0e27cbe - [RISCV] Run mem2reg to simplify Zbc tests (#70169)

2023-10-25 Thread via cfe-commits

Author: Wang Pengcheng
Date: 2023-10-25T16:23:32+08:00
New Revision: 0e27cbe1879f400d64088d8770803e884782a34e

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

LOG: [RISCV] Run mem2reg to simplify Zbc tests (#70169)

Added: 


Modified: 
clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c

Removed: 




diff  --git a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c 
b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
index aa5bebe38dd6b2d..ae9153eff155e19 100644
--- a/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
+++ b/clang/test/CodeGen/RISCV/rvb-intrinsics/zbc.c
@@ -1,7 +1,9 @@
 // NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py
 // RUN: %clang_cc1 -triple riscv32 -target-feature +zbc -emit-llvm %s -o - \
+// RUN: -disable-O0-optnone | opt -S -passes=mem2reg \
 // RUN: | FileCheck %s  -check-prefix=RV32ZBC
 // RUN: %clang_cc1 -triple riscv64 -target-feature +zbc -emit-llvm %s -o - \
+// RUN: -disable-O0-optnone | opt -S -passes=mem2reg \
 // RUN: | FileCheck %s  -check-prefix=RV64ZBC
 
 #include 
@@ -9,14 +11,8 @@
 #if __riscv_xlen == 64
 // RV64ZBC-LABEL: @clmul_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmul.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmul.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmul_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmul_64(a, b);
@@ -24,14 +20,8 @@ uint64_t clmul_64(uint64_t a, uint64_t b) {
 
 // RV64ZBC-LABEL: @clmulh_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmulh.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmulh.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulh_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmulh_64(a, b);
@@ -39,14 +29,8 @@ uint64_t clmulh_64(uint64_t a, uint64_t b) {
 
 // RV64ZBC-LABEL: @clmulr_64(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i64, align 8
-// RV64ZBC-NEXT:store i64 [[A:%.*]], ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:store i64 [[B:%.*]], ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP0:%.*]] = load i64, ptr [[A_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP1:%.*]] = load i64, ptr [[B_ADDR]], align 8
-// RV64ZBC-NEXT:[[TMP2:%.*]] = call i64 @llvm.riscv.clmulr.i64(i64 
[[TMP0]], i64 [[TMP1]])
-// RV64ZBC-NEXT:ret i64 [[TMP2]]
+// RV64ZBC-NEXT:[[TMP0:%.*]] = call i64 @llvm.riscv.clmulr.i64(i64 
[[A:%.*]], i64 [[B:%.*]])
+// RV64ZBC-NEXT:ret i64 [[TMP0]]
 //
 uint64_t clmulr_64(uint64_t a, uint64_t b) {
   return __builtin_riscv_clmulr_64(a, b);
@@ -55,25 +39,13 @@ uint64_t clmulr_64(uint64_t a, uint64_t b) {
 
 // RV32ZBC-LABEL: @clmul_32(
 // RV32ZBC-NEXT:  entry:
-// RV32ZBC-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
-// RV32ZBC-NEXT:[[B_ADDR:%.*]] = alloca i32, align 4
-// RV32ZBC-NEXT:store i32 [[A:%.*]], ptr [[A_ADDR]], align 4
-// RV32ZBC-NEXT:store i32 [[B:%.*]], ptr [[B_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP0:%.*]] = load i32, ptr [[A_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP1:%.*]] = load i32, ptr [[B_ADDR]], align 4
-// RV32ZBC-NEXT:[[TMP2:%.*]] = call i32 @llvm.riscv.clmul.i32(i32 
[[TMP0]], i32 [[TMP1]])
-// RV32ZBC-NEXT:ret i32 [[TMP2]]
+// RV32ZBC-NEXT:[[TMP0:%.*]] = call i32 @llvm.riscv.clmul.i32(i32 
[[A:%.*]], i32 [[B:%.*]])
+// RV32ZBC-NEXT:ret i32 [[TMP0]]
 //
 // RV64ZBC-LABEL: @clmul_32(
 // RV64ZBC-NEXT:  entry:
-// RV64ZBC-NEXT:[[A_ADDR:%.*]] = alloca i32, align 4
-// RV64ZBC-NEXT:[[B_ADDR:%.*]] = alloca i32, align 4
-// RV64ZBC-NEXT:store i32 [[A:%.*]], ptr [[A_ADDR]], align 4
-// RV64ZBC-NEXT:store i32 [[B:%.*]], ptr [[B_ADDR]], align 4
-// RV64ZBC-NEXT:[[TMP0:%.*]] =

[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

2023-10-25 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff a7700985577694d6cc2498833f27b4fb5eeaf252 
441f24714729f35588487d3109e3c42d59e0a610 -- clang/lib/Sema/SemaDeclCXX.cpp 
clang/test/SemaCXX/cxx2b-deducing-this.cpp
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index 35554fca5776..fb27168f7d2a 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7754,11 +7754,14 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 // parameter is of (possibly different) type “reference to C”,
 // in which case the type of F1 would differ from the type of F2
 // in that the type of F1 has an additional parameter;
-
if(!Context.hasSameType(ThisType.getNonReferenceType().getUnqualifiedType(), 
Context.getRecordType(RD))) {
+if (!Context.hasSameType(
+ThisType.getNonReferenceType().getUnqualifiedType(),
+Context.getRecordType(RD))) {
   if (DeleteOnTypeMismatch)
 ShouldDeleteForTypeMismatch = true;
   else {
-Diag(MD->getLocation(), 
diag::err_defaulted_special_member_explicit_object_mismatch)
+Diag(MD->getLocation(),
+ diag::err_defaulted_special_member_explicit_object_mismatch)
 << (CSM == CXXMoveAssignment) << RD;
 HadError = true;
   }

``




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


[clang] [RISCV] Run mem2reg to simplify Zbc tests (PR #70169)

2023-10-25 Thread Wang Pengcheng via cfe-commits

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


[clang] [clang][NFC] Refactor `Selector` to use `PointerIntPair` inside (PR #69916)

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


@@ -809,43 +927,42 @@ class Selector {
   enum IdentifierInfoFlag {
 // Empty selector = 0. Note that these enumeration values must
 // correspond to the enumeration values of DeclarationName::StoredNameKind
-ZeroArg  = 0x01,
-OneArg   = 0x02,
+ZeroArg = 0x01,
+OneArg = 0x02,
 MultiArg = 0x07,
-ArgFlags = 0x07
   };
 
   /// A pointer to the MultiKeywordSelector or IdentifierInfo. We use the low
-  /// three bits of InfoPtr to store an IdentifierInfoFlag. Note that in any
+  /// three bits of InfoPtr to store an IdentifierInfoFlag, but the highest
+  /// of them is also a discriminator for pointer type. Note that in any
   /// case IdentifierInfo and MultiKeywordSelector are already aligned to
   /// 8 bytes even on 32 bits archs because of DeclarationName.
-  uintptr_t InfoPtr = 0;
+  llvm::PointerIntPair<
+  llvm::PointerUnion, 2>
+  InfoPtr;

Endilll wrote:

Applied with an addition we discussed offline.

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


[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

2023-10-25 Thread via cfe-commits

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

>From 6fd05adec162b2d18b4b163cc0a0f6d6e6710139 Mon Sep 17 00:00:00 2001
From: Corentin Jabot 
Date: Wed, 25 Oct 2023 10:08:24 +0200
Subject: [PATCH] [Clang] Diagnose defaulted assignment operator with
 incompatible object parameter.

Per https://eel.is/c++draft/dcl.fct.def.default#2.2, the explicit object
parameter of a defaulted special member function must be of the same type
as the one of an equivalent implicitly defaulted function,
ignoring references.

Fixes #69233
---
 .../clang/Basic/DiagnosticSemaKinds.td|  3 ++
 clang/lib/Sema/SemaDeclCXX.cpp| 18 +++
 clang/test/SemaCXX/cxx2b-deducing-this.cpp| 31 +++
 3 files changed, 52 insertions(+)

diff --git a/clang/include/clang/Basic/DiagnosticSemaKinds.td 
b/clang/include/clang/Basic/DiagnosticSemaKinds.td
index a673ce726d6c220..6e138683334c2c3 100644
--- a/clang/include/clang/Basic/DiagnosticSemaKinds.td
+++ b/clang/include/clang/Basic/DiagnosticSemaKinds.td
@@ -9481,6 +9481,9 @@ def err_defaulted_special_member_return_type : Error<
 def err_defaulted_special_member_quals : Error<
   "an explicitly-defaulted %select{copy|move}0 assignment operator may not "
   "have 'const'%select{, 'constexpr'|}1 or 'volatile' qualifiers">;
+def err_defaulted_special_member_explicit_object_mismatch : Error<
+  "the type of the explicit object parameter of an explicitly-defaulted "
+  "%select{copy|move}0 assignment operator should match the type of the class 
%1">;
 def err_defaulted_special_member_volatile_param : Error<
   "the parameter for an explicitly-defaulted %sub{select_special_member_kind}0 
"
   "may not be volatile">;
diff --git a/clang/lib/Sema/SemaDeclCXX.cpp b/clang/lib/Sema/SemaDeclCXX.cpp
index a3f68d4ffc0f6ec..fb27168f7d2a700 100644
--- a/clang/lib/Sema/SemaDeclCXX.cpp
+++ b/clang/lib/Sema/SemaDeclCXX.cpp
@@ -7748,6 +7748,24 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 HadError = true;
   }
 }
+// [C++23][dcl.fct.def.default]/p2.2
+// if F2 has an implicit object parameter of type “reference to C”,
+// F1 may be an explicit object member function whose explicit object
+// parameter is of (possibly different) type “reference to C”,
+// in which case the type of F1 would differ from the type of F2
+// in that the type of F1 has an additional parameter;
+if (!Context.hasSameType(
+ThisType.getNonReferenceType().getUnqualifiedType(),
+Context.getRecordType(RD))) {
+  if (DeleteOnTypeMismatch)
+ShouldDeleteForTypeMismatch = true;
+  else {
+Diag(MD->getLocation(),
+ diag::err_defaulted_special_member_explicit_object_mismatch)
+<< (CSM == CXXMoveAssignment) << RD;
+HadError = true;
+  }
+}
   }
 
   // Check for parameter type matching.
diff --git a/clang/test/SemaCXX/cxx2b-deducing-this.cpp 
b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
index 535381e876da9c7..f9e73b41e2c330f 100644
--- a/clang/test/SemaCXX/cxx2b-deducing-this.cpp
+++ b/clang/test/SemaCXX/cxx2b-deducing-this.cpp
@@ -585,3 +585,34 @@ class Server : public Thing {
 S name_;
 };
 }
+
+namespace GH69233 {
+struct Base {};
+struct S : Base {
+int j;
+S& operator=(this Base& self, const S&) = default;
+// expected-warning@-1 {{explicitly defaulted copy assignment operator is 
implicitly deleted}}
+// expected-note@-2 {{function is implicitly deleted because its declared 
type does not match the type of an implicit copy assignment operator}}
+// expected-note@-3 {{explicitly defaulted function was implicitly deleted 
here}}
+};
+
+struct S2 {
+S2& operator=(this int&& self, const S2&);
+S2& operator=(this int&& self, S2&&);
+operator int();
+};
+
+S2& S2::operator=(this int&& self, const S2&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted copy assignment operator should match the type of the 
class 'S2'}}
+
+S2& S2::operator=(this int&& self, S2&&) = default;
+// expected-error@-1 {{the type of the explicit object parameter of an 
explicitly-defaulted move assignment operator should match the type of the 
class 'S2'}}
+
+void test() {
+S s;
+s = s; // expected-error {{object of type 'S' cannot be assigned because 
its copy assignment operator is implicitly deleted}}
+S2 s2;
+s2 = s2;
+}
+
+}

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


[clang] [clang][NFC] Refactor `Selector` to use `PointerIntPair` inside (PR #69916)

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


@@ -809,43 +927,42 @@ class Selector {
   enum IdentifierInfoFlag {
 // Empty selector = 0. Note that these enumeration values must
 // correspond to the enumeration values of DeclarationName::StoredNameKind
-ZeroArg  = 0x01,
-OneArg   = 0x02,
+ZeroArg = 0x01,
+OneArg = 0x02,
 MultiArg = 0x07,

Endilll wrote:

Applied.

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


[clang] [clang][NFC] Refactor `Selector` to use `PointerIntPair` inside (PR #69916)

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


@@ -809,43 +927,42 @@ class Selector {
   enum IdentifierInfoFlag {
 // Empty selector = 0. Note that these enumeration values must
 // correspond to the enumeration values of DeclarationName::StoredNameKind
-ZeroArg  = 0x01,
-OneArg   = 0x02,
+ZeroArg = 0x01,
+OneArg = 0x02,
 MultiArg = 0x07,
-ArgFlags = 0x07
   };
 
   /// A pointer to the MultiKeywordSelector or IdentifierInfo. We use the low
-  /// three bits of InfoPtr to store an IdentifierInfoFlag. Note that in any
+  /// three bits of InfoPtr to store an IdentifierInfoFlag, but the highest
+  /// of them is also a discriminator for pointer type. Note that in any
   /// case IdentifierInfo and MultiKeywordSelector are already aligned to
   /// 8 bytes even on 32 bits archs because of DeclarationName.
-  uintptr_t InfoPtr = 0;
+  llvm::PointerIntPair<
+  llvm::PointerUnion, 2>
+  InfoPtr;
 
   Selector(IdentifierInfo *II, unsigned nArgs) {
-InfoPtr = reinterpret_cast(II);
-assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned 
IdentifierInfo");
 assert(nArgs < 2 && "nArgs not equal to 0/1");
-InfoPtr |= nArgs+1;
+InfoPtr.setPointerAndInt(II, nArgs + 1);
   }
 
   Selector(MultiKeywordSelector *SI) {
-InfoPtr = reinterpret_cast(SI);
-assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned 
IdentifierInfo");
-InfoPtr |= MultiArg;
+InfoPtr.setPointerAndInt(SI, MultiArg & 0b11);

Endilll wrote:

Applied.

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


[clang] [clang][NFC] Refactor `Selector` to use `PointerIntPair` inside (PR #69916)

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


@@ -809,43 +927,42 @@ class Selector {
   enum IdentifierInfoFlag {
 // Empty selector = 0. Note that these enumeration values must
 // correspond to the enumeration values of DeclarationName::StoredNameKind
-ZeroArg  = 0x01,
-OneArg   = 0x02,
+ZeroArg = 0x01,
+OneArg = 0x02,
 MultiArg = 0x07,
-ArgFlags = 0x07
   };
 
   /// A pointer to the MultiKeywordSelector or IdentifierInfo. We use the low
-  /// three bits of InfoPtr to store an IdentifierInfoFlag. Note that in any
+  /// three bits of InfoPtr to store an IdentifierInfoFlag, but the highest
+  /// of them is also a discriminator for pointer type. Note that in any
   /// case IdentifierInfo and MultiKeywordSelector are already aligned to
   /// 8 bytes even on 32 bits archs because of DeclarationName.
-  uintptr_t InfoPtr = 0;
+  llvm::PointerIntPair<
+  llvm::PointerUnion, 2>
+  InfoPtr;
 
   Selector(IdentifierInfo *II, unsigned nArgs) {
-InfoPtr = reinterpret_cast(II);
-assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned 
IdentifierInfo");
 assert(nArgs < 2 && "nArgs not equal to 0/1");
-InfoPtr |= nArgs+1;
+InfoPtr.setPointerAndInt(II, nArgs + 1);
   }
 
   Selector(MultiKeywordSelector *SI) {
-InfoPtr = reinterpret_cast(SI);
-assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned 
IdentifierInfo");
-InfoPtr |= MultiArg;
+InfoPtr.setPointerAndInt(SI, MultiArg & 0b11);
   }
 
   IdentifierInfo *getAsIdentifierInfo() const {
-if (getIdentifierInfoFlag() < MultiArg)
-  return reinterpret_cast(InfoPtr & ~ArgFlags);
-return nullptr;
+return InfoPtr.getPointer().dyn_cast();
   }
 
   MultiKeywordSelector *getMultiKeywordSelector() const {
-return reinterpret_cast(InfoPtr & ~ArgFlags);
+return InfoPtr.getPointer().get();
   }
 
   unsigned getIdentifierInfoFlag() const {
-return InfoPtr & ArgFlags;
+unsigned new_flags = InfoPtr.getInt();
+if (InfoPtr.getPointer().is())
+  new_flags |= MultiArg;

Endilll wrote:

Applied.

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


[clang] [C23] Use thread_local semantics (PR #70107)

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


@@ -493,6 +493,9 @@ Bug Fixes in This Version
   Fixes (`#65143 `_)
 - Fix crash in formatting the real/imaginary part of a complex lvalue.
   Fixes (`#69218 `_)
+- No longer use C++ ``thread_local`` semantics in C23 when using

Fznamznon wrote:

Does this patch also help with 
https://github.com/llvm/llvm-project/issues/69167 ?

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


[clang] [mlir][LLVM] Verify too many indices in GEP verifier (PR #70174)

2023-10-25 Thread Markus Böck via cfe-commits

https://github.com/zero9178 updated 
https://github.com/llvm/llvm-project/pull/70174

From 03fb7aceae81227c3a64cf4b9ba1e53a69e46511 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Markus=20B=C3=B6ck?= 
Date: Wed, 25 Oct 2023 09:54:16 +0200
Subject: [PATCH 1/3] [mlir][LLVM] Verify too many indices in GEP verifier

The current verifier stopped verification with a success value as soon as a 
type was encountered that cannot be indexed into. The correct behaviour in this 
case is to error out as there are too many indices for the element type. Not 
doing so leads to bad user-experience as an invalid GEP is likely to fail only 
later during LLVM IR translation.

This PR implements the correct verification behaviour. Some tests upstream had 
to also be fixed as they were creating invalid GEPs.

Fixes https://github.com/llvm/llvm-project/issues/70168
---
 mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp| 69 ---
 mlir/test/Dialect/LLVMIR/invalid.mlir |  8 +++
 mlir/test/Dialect/LLVMIR/mem2reg.mlir |  9 ++-
 .../LLVMIR/roundtrip-typed-pointers.mlir  |  4 +-
 mlir/test/Dialect/LLVMIR/roundtrip.mlir   |  4 +-
 5 files changed, 60 insertions(+), 34 deletions(-)

diff --git a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp 
b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
index 95c04098d05fc2f..70045d028cc3214 100644
--- a/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
+++ b/mlir/lib/Dialect/LLVMIR/IR/LLVMDialect.cpp
@@ -704,50 +704,72 @@ struct GEPStaticIndexError
<< "to be constant";
   }
 };
+
+/// llvm::Error for non-static GEP index indexing a struct.
+struct GEPCannotIndexError
+: public llvm::ErrorInfo {
+  static char ID;
+
+  using ErrorInfo::ErrorInfo;
+
+  void log(llvm::raw_ostream &os) const override {
+os << "expected index " << indexPos << " indexing a struct "
+   << "to be constant";
+  }
+};
+
 } // end anonymous namespace
 
 char GEPIndexError::ID = 0;
 char GEPIndexOutOfBoundError::ID = 0;
 char GEPStaticIndexError::ID = 0;
-
-/// For the given `structIndices` and `indices`, check if they're complied
-/// with `baseGEPType`, especially check against LLVMStructTypes nested within.
-static llvm::Error verifyStructIndices(Type baseGEPType, unsigned indexPos,
-   GEPIndicesAdaptor indices) {
+char GEPCannotIndexError::ID = 0;
+
+/// For the given `indices`, check if they comply with `baseGEPType`,
+// especially check against LLVMStructTypes nested within.
+static LogicalResult
+verifyStructIndices(Type baseGEPType, unsigned indexPos,
+GEPIndicesAdaptor indices,
+function_ref emitOpError) {
   if (indexPos >= indices.size())
 // Stop searching
-return llvm::Error::success();
+return success();
 
-  return llvm::TypeSwitch(baseGEPType)
-  .Case([&](LLVMStructType structType) -> llvm::Error {
+  return llvm::TypeSwitch(baseGEPType)
+  .Case([&](LLVMStructType structType) -> LogicalResult {
 if (!indices[indexPos].is())
-  return llvm::make_error(indexPos);
+  return emitOpError() << "expected index " << indexPos
+   << " indexing a struct to be constant";
 
 int32_t gepIndex = indices[indexPos].get().getInt();
 ArrayRef elementTypes = structType.getBody();
 if (gepIndex < 0 ||
 static_cast(gepIndex) >= elementTypes.size())
-  return llvm::make_error(indexPos);
+  return emitOpError() << "index " << indexPos
+   << " indexing a struct is out of bounds";
 
 // Instead of recursively going into every children types, we only
 // dive into the one indexed by gepIndex.
 return verifyStructIndices(elementTypes[gepIndex], indexPos + 1,
-   indices);
+   indices, emitOpError);
   })
   .Case([&](auto containerType) -> llvm::Error {
+LLVMArrayType>([&](auto containerType) -> LogicalResult {
 return verifyStructIndices(containerType.getElementType(), indexPos + 
1,
-   indices);
+   indices, emitOpError);
   })
-  .Default(
-  [](auto otherType) -> llvm::Error { return llvm::Error::success(); 
});
+  .Default([&](auto otherType) -> LogicalResult {
+return emitOpError()
+   << "type " << otherType << " cannot be indexed (index #"
+   << indexPos << ")";
+  });
 }
 
-/// Driver function around `recordStructIndices`. Note that we always check
-/// from the second GEP index since the first one is always dynamic.
-static llvm::Error verifyStructIndices(Type baseGEPType,
-   GEPIndicesAdaptor indices) {
-  return verifyStructIndices(baseGEPType, /*indexPos=*/1, indices);
+/// Driver function around `verifyStructIndices`.
+static LogicalResult
+verifyStructIndices(Type baseGEPType, GEPIndicesAd

[clang] [Clang][LoongArch] Support builtin functions for LSX and LASX (PR #69313)

2023-10-25 Thread via cfe-commits

github-actions[bot] wrote:




:warning: C/C++ code formatter, clang-format found issues in your code. 
:warning:



You can test this locally with the following command:


``bash
git-clang-format --diff 7df92fbe74e3c1b41c06f5fc784473f7f22aeed7 
0bd36f11c5d1da2447b1c123445a1472372a096b -- clang/lib/Headers/lasxintrin.h 
clang/lib/Headers/lsxintrin.h 
clang/test/CodeGen/LoongArch/lasx/builtin-alias-error.c 
clang/test/CodeGen/LoongArch/lasx/builtin-alias.c 
clang/test/CodeGen/LoongArch/lasx/builtin-error.c 
clang/test/CodeGen/LoongArch/lasx/builtin.c 
clang/test/CodeGen/LoongArch/lsx/builtin-alias-error.c 
clang/test/CodeGen/LoongArch/lsx/builtin-alias.c 
clang/test/CodeGen/LoongArch/lsx/builtin-error.c 
clang/test/CodeGen/LoongArch/lsx/builtin.c 
clang/test/Driver/loongarch-mlasx-error.c clang/test/Driver/loongarch-mlasx.c 
clang/test/Driver/loongarch-mlsx-error.c clang/test/Driver/loongarch-mlsx.c 
clang/lib/Basic/Targets/LoongArch.cpp clang/lib/Basic/Targets/LoongArch.h 
clang/lib/CodeGen/Targets/LoongArch.cpp 
clang/lib/Driver/ToolChains/Arch/LoongArch.cpp clang/lib/Sema/SemaChecking.cpp 
clang/test/Preprocessor/init-loongarch.c
``





View the diff from clang-format here.


``diff
diff --git a/clang/lib/Sema/SemaChecking.cpp b/clang/lib/Sema/SemaChecking.cpp
index b4b4571a4c4f..3518ed86751e 100644
--- a/clang/lib/Sema/SemaChecking.cpp
+++ b/clang/lib/Sema/SemaChecking.cpp
@@ -9201,8 +9201,7 @@ ExprResult Sema::SemaConvertVectorExpr(Expr *E, 
TypeSourceInfo *TInfo,
   diag::err_convertvector_non_vector)
  << E->getSourceRange());
   if (!DstTy->isVectorType() && !DstTy->isDependentType())
-return ExprError(Diag(BuiltinLoc,
-  diag::err_convertvector_non_vector_type));
+return ExprError(Diag(BuiltinLoc, 
diag::err_convertvector_non_vector_type));
 
   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
 unsigned SrcElts = SrcTy->castAs()->getNumElements();

``




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


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

2023-10-25 Thread Carlos Alberto Enciso via cfe-commits

https://github.com/CarlosAlbertoEnciso updated 
https://github.com/llvm/llvm-project/pull/69681

>From 42df544996bb8fee93e5d1bab72e71578645bcc4 Mon Sep 17 00:00:00 2001
From: Carlos Alberto Enciso 
Date: Fri, 20 Oct 2023 06:09:04 +0100
Subject: [PATCH 1/3] [Clang][DebugInfo] Clang generates an extra spurious
 unnamed 'dbg.declare'.

Do not emit call to llvm.dbg.declare when the variable declaration
is a DecompositionDecl as its instance class is always unnamed.

The emitted debug declare looks like:

  call void @llvm.dbg.declare(metadata ..., metadata !xx, metadata ...)
  !xx = !DILocalVariable(scope: !..., file: !..., line: ..., type: !...)
---
 clang/lib/CodeGen/CGDebugInfo.cpp |  6 +-
 ...debug-info-structured-binding-bitfield.cpp |  3 ---
 .../debug-info-structured-binding-field.cpp   | 20 +++
 .../debug-info-structured-binding.cpp |  2 --
 4 files changed, 25 insertions(+), 6 deletions(-)
 create mode 100644 
clang/test/CodeGenCXX/debug-info-structured-binding-field.cpp

diff --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 181e500b9671759..0aaf678bf287c6e 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4881,11 +4881,15 @@ CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl 
*VD, llvm::Value *Storage,
const bool UsePointerValue) {
   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
 
-  if (auto *DD = dyn_cast(VD))
+  if (auto *DD = dyn_cast(VD)) {
 for (auto *B : DD->bindings()) {
   EmitDeclare(B, Storage, std::nullopt, Builder,
   VD->getType()->isReferenceType());
 }
+// Don't emit an llvm.dbg.declare for the composite storage as it doesn't
+// correspond to a user variable.
+return nullptr;
+  }
 
   return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
 }
diff --git a/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
index b5ee96224565d3a..0234e41009f6225 100644
--- a/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
@@ -189,7 +189,6 @@ struct S11 {
 // CHECK-LABEL: define dso_local void @_Z4fS11v
 // CHECK:alloca %struct.S11, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S11, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS11() {
@@ -206,7 +205,6 @@ struct S12 {
 // CHECK:alloca %struct.S12, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S12, align 4
 // CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S12_A:![0-9]+]], metadata !DIExpression())
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS12() {
@@ -222,7 +220,6 @@ struct __attribute__((packed)) S13 {
 // CHECK-LABEL: define dso_local void @_Z4fS13v
 // CHECK:alloca %struct.S13, align 1
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S13, align 1
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
{{.*}}, metadata !DIExpression())
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS13() {
diff --git a/clang/test/CodeGenCXX/debug-info-structured-binding-field.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding-field.cpp
new file mode 100644
index 000..928d22776d21093
--- /dev/null
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding-field.cpp
@@ -0,0 +1,20 @@
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone %s -o - | FileCheck 
%s
+
+struct Tuple {
+  int Fld_1;
+  int Fld_2;
+};
+__attribute__((optnone)) Tuple get() { return {10, 20}; }
+
+// CHECK-LABEL: define dso_local noundef i32 @main
+// CHECK:  %retval = alloca i32, align 4
+// CHECK-NEXT: [[T0:%.*]] = alloca %struct.Tuple, align 4
+// CHECK:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression())
+// CHECK:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression(DW_OP_plus_uconst, {{[0-9]+}}))
+// CHECK-NOT:  call void @llvm.dbg.declare(metadata ptr [[T0]], metadata 
{{.*}}, metadata !DIExpression())
+//
+int main() {
+  auto [Var_1, Var_2] = get();
+
+  return Var_1 + Var_2;
+}
diff --git a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
index 8d4ae0aaf32636b..163c152efa19d0b 100644
--- a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
@@ -2,10 +2,8 @@
 
 // CHECK: call void @llvm.dbg.declare(metadata ptr %{{[0-9]+}}, metadata 
!{{[0-9]+}}, metadata !DIExpressio

[clang] [analyzer] Improve reports from ArrayBoundCheckerV2 (PR #70056)

2023-10-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


https://github.com/DonatNagyE updated 
https://github.com/llvm/llvm-project/pull/70056

>From 77143e74edda6177248bebdf0424db915aa68a05 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Don=C3=A1t=20Nagy?= 
Date: Mon, 2 Oct 2023 13:32:31 +0200
Subject: [PATCH 1/2] [analyzer] Improve reports from ArrayBoundCheckerV2

Previously alpha.security.ArrayBoundV2 produced very spartan bug
reports; this commit ensures that the relevant (and known) details are
reported to the user.

The logic for detecting bugs is not changed, after this commit the
checker will report the same set of issues, but with better messages.

To test the details of the message generation this commit adds a new
test file 'out-of-bounds-diagnostics.c'. Three of the testcases are
added with FIXME notes because they reveal shortcomings of the existing
modeling and bounds checking code. I will try to fix them in separate
follow-up commits.
---
 .../Checkers/ArrayBoundCheckerV2.cpp  | 181 ++
 .../test/Analysis/out-of-bounds-diagnostics.c | 149 ++
 clang/test/Analysis/out-of-bounds-new.cpp |  26 +--
 clang/test/Analysis/out-of-bounds.c   |  28 +--
 .../test/Analysis/taint-diagnostic-visitor.c  |   4 +-
 clang/test/Analysis/taint-generic.c   |  20 +-
 clang/test/Analysis/taint-generic.cpp |  14 +-
 7 files changed, 339 insertions(+), 83 deletions(-)
 create mode 100644 clang/test/Analysis/out-of-bounds-diagnostics.c

diff --git a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp 
b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
index e80a06e38587520..7d97f36e4cffe44 100644
--- a/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/ArrayBoundCheckerV2.cpp
@@ -22,23 +22,25 @@
 #include "clang/StaticAnalyzer/Core/PathSensitive/DynamicExtent.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
 #include "llvm/ADT/SmallString.h"
+#include "llvm/Support/FormatVariadic.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 
 using namespace clang;
 using namespace ento;
 using namespace taint;
+using llvm::formatv;
 
 namespace {
+enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
+
 class ArrayBoundCheckerV2 :
 public Checker {
   BugType BT{this, "Out-of-bound access"};
   BugType TaintBT{this, "Out-of-bound access", categories::TaintedData};
 
-  enum OOB_Kind { OOB_Precedes, OOB_Exceeds, OOB_Taint };
-
   void reportOOB(CheckerContext &C, ProgramStateRef ErrorState, OOB_Kind Kind,
- SVal TaintedSVal = UnknownVal()) const;
+ NonLoc Offset, std::string RegName, std::string Msg) const;
 
   static bool isFromCtypeMacro(const Stmt *S, ASTContext &AC);
 
@@ -53,7 +55,7 @@ class ArrayBoundCheckerV2 :
 /// Arr and the distance of Location from the beginning of Arr (expressed in a
 /// NonLoc that specifies the number of CharUnits). Returns nullopt when these
 /// cannot be determined.
-std::optional>
+static std::optional>
 computeOffset(ProgramStateRef State, SValBuilder &SVB, SVal Location) {
   QualType T = SVB.getArrayIndexType();
   auto EvalBinOp = [&SVB, State, T](BinaryOperatorKind Op, NonLoc L, NonLoc R) 
{
@@ -174,9 +176,119 @@ compareValueToThreshold(ProgramStateRef State, NonLoc 
Value, NonLoc Threshold,
   return {nullptr, nullptr};
 }
 
+static std::string getRegionName(const SubRegion *Region) {
+  std::string RegName = Region->getDescriptiveName();
+  if (!RegName.empty())
+return RegName;
+
+  // Field regions only have descriptive names when their parent has a
+  // descriptive name; so we provide a fallback representation for them:
+  if (const auto *FR = Region->getAs()) {
+StringRef Name = FR->getDecl()->getName();
+if (!Name.empty())
+  return formatv("the field '{0}'", Name);
+return "the unnamed field";
+  }
+
+  if (isa(Region))
+return "the memory returned by 'alloca'";
+
+  if (isa(Region) &&
+  isa(Region->getMemorySpace()))
+return "the heap area";
+
+  if (isa(Region))
+return "the string literal";
+
+  return "the region";
+}
+
+static std::optional getConcreteValue(NonLoc SV) {
+  if (auto ConcreteVal = SV.getAs()) {
+const llvm::APSInt &IntVal = ConcreteVal->getValue();
+return IntVal.tryExtValue();
+  }
+  return std::nullopt;
+}
+
+static const char *ShortMsgTemplates[] = {
+"Out of bound access to memory preceding {0}",
+"Out of bound access to memory after the end of {0}",
+"Potential out of bound access to {0} with tainted offset"};
+
+static std::string getShortMsg(OOB_Kind Kind, std::string RegName) {
+  return formatv(ShortMsgTemplates[Kind], RegName);
+}
+
+static std::string getPrecedesMsg(std::string RegName, NonLoc Offset) {
+  SmallString<128> Buf;
+  llvm::raw_svector_ostream Out(Buf);
+  Out << "Access of " << RegName << " at negative byte offset";
+  if (auto ConcreteIdx = Offset.getAs())
+Out << ' ' << ConcreteIdx->getValue();
+  

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

2023-10-25 Thread Carlos Alberto Enciso via cfe-commits

CarlosAlbertoEnciso wrote:

Uploaded new patch to address minor details with the test case:
- Added check for missing captured `a` variable.
- Check for the specific values in `DW_OP_plus_uconst`.

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


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

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

momchil-velikov wrote:


> I haven't been able to produce a minimal, sharable example as of yet, but I'm 
> encountering a runtime error associated with an inlined function where stack 
> probing is active. The error manifests as a null pointer dereference, 
> originating from a stack value that is probed (and set to 0) before being 
> subsequently dereferenced.

All the stack probing should have already finished before the call to `malloc`.

> I'm working to isolate this issue and will share a repro ASAP. In the 
> meantime, any insights or suggestions based on this description would be 
> greatly appreciated.

Just to make things simpler, can you try disabling the shrink-wrapping and see 
what happens?

> Also is it required to write to the value? Would reading the value be 
> sufficient?
I can't really see a compelling reason to prefer one over another. Maybe for 
the odd chance some
kernel/runtime allocates read-only (as opposed to no access at all) guard 
regions.

Anyway, changing that won't solve the problem here, at most it could hide it.


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


[clang] [analyzer] Improve reports from ArrayBoundCheckerV2 (PR #70056)

2023-10-25 Thread via cfe-commits
=?utf-8?q?Donát?= Nagy 
Message-ID:
In-Reply-To: 


DonatNagyE wrote:

I renamed some variables because (1) they weren't CamelCased because they were 
"inherited" from the old versions of this checker and (2) their names were 
slightly too long and they introduced extra linebreaks in the newly added code.

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-25 Thread via cfe-commits


@@ -0,0 +1,54 @@
+// -*- C++ -*-
+//===--===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+
+#ifndef _LIBCPP___NUMERIC_RANGES_IOTA_H
+#define _LIBCPP___NUMERIC_RANGES_IOTA_H
+
+#include <__algorithm/out_value_result.h>
+#include <__config>
+#include <__ranges/concepts.h>
+#include <__utility/as_const.h>
+
+#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
+#  pragma GCC system_header
+#endif
+
+_LIBCPP_BEGIN_NAMESPACE_STD
+
+#if _LIBCPP_STD_VER >= 23
+namespace ranges {
+template 
+using iota_result = ranges::out_value_result<_Out, _Tp>;
+
+struct __iota_fn {
+  template  _Sent, 
weakly_incrementable _Tp>
+requires indirectly_writable<_Out, const _Tp&>
+  constexpr iota_result<_Out, _Tp> operator()(_Out __first, _Sent __last, _Tp 
__value) const {

philnik777 wrote:

`static operator()` has been introduced in C++23, so we can't (currently) use 
it for C++20 algorithms. Otherwise we would also use it there. The simple 
reason to use it is that we don't care about the object and the `static` 
version has slightly better code gen (https://godbolt.org/z/8E1f77q6f).

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


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

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

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

New changes LGTM, thanks!

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


[clang-tools-extra] [libc++] Implement ranges::iota (PR #68494)

2023-10-25 Thread via cfe-commits

philnik777 wrote:

Yes, it should be the `ranges_robust_against_*` tests in both `test/libcxx` and 
`test/std`.

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


[clang] [libc++] Implement ranges::iota (PR #68494)

2023-10-25 Thread via cfe-commits

philnik777 wrote:

Yes, it should be the `ranges_robust_against_*` tests in both `test/libcxx` and 
`test/std`.

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


[clang] [Clang] Diagnose defaulted assignment operator with incompatible object parameter (PR #70176)

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


@@ -7748,6 +7748,24 @@ bool 
Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
 HadError = true;
   }
 }
+// [C++23][dcl.fct.def.default]/p2.2
+// if F2 has an implicit object parameter of type “reference to C”,
+// F1 may be an explicit object member function whose explicit object
+// parameter is of (possibly different) type “reference to C”,
+// in which case the type of F1 would differ from the type of F2
+// in that the type of F1 has an additional parameter;
+if (!Context.hasSameType(
+ThisType.getNonReferenceType().getUnqualifiedType(),
+Context.getRecordType(RD))) {
+  if (DeleteOnTypeMismatch)
+ShouldDeleteForTypeMismatch = true;
+  else {
+Diag(MD->getLocation(),
+ diag::err_defaulted_special_member_explicit_object_mismatch)
+<< (CSM == CXXMoveAssignment) << RD;

tbaederr wrote:

Is there a useful source range we can supply here?

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


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

2023-10-25 Thread Carlos Alberto Enciso via cfe-commits

CarlosAlbertoEnciso wrote:

@adrian-prantl, @OCHyams Thanks for your reviews.

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


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

2023-10-25 Thread via cfe-commits

Author: Carlos Alberto Enciso
Date: 2023-10-25T10:35:03+01:00
New Revision: 2399c77c8593b0ed3bd3988a5b72f8bf6b30b0de

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

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

Do not emit call to llvm.dbg.declare when the variable declaration
is a DecompositionDecl as its instance class is always unnamed.

The emitted debug declare looks like:

call void @llvm.dbg.declare(metadata ..., metadata !xx, metadata ...)
!xx = !DILocalVariable(scope: !..., file: !..., line: ..., type: !...)

Added: 


Modified: 
clang/lib/CodeGen/CGDebugInfo.cpp
clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
clang/test/CodeGenCXX/debug-info-structured-binding.cpp

Removed: 




diff  --git a/clang/lib/CodeGen/CGDebugInfo.cpp 
b/clang/lib/CodeGen/CGDebugInfo.cpp
index 181e500b9671759..0aaf678bf287c6e 100644
--- a/clang/lib/CodeGen/CGDebugInfo.cpp
+++ b/clang/lib/CodeGen/CGDebugInfo.cpp
@@ -4881,11 +4881,15 @@ CGDebugInfo::EmitDeclareOfAutoVariable(const VarDecl 
*VD, llvm::Value *Storage,
const bool UsePointerValue) {
   assert(CGM.getCodeGenOpts().hasReducedDebugInfo());
 
-  if (auto *DD = dyn_cast(VD))
+  if (auto *DD = dyn_cast(VD)) {
 for (auto *B : DD->bindings()) {
   EmitDeclare(B, Storage, std::nullopt, Builder,
   VD->getType()->isReferenceType());
 }
+// Don't emit an llvm.dbg.declare for the composite storage as it doesn't
+// correspond to a user variable.
+return nullptr;
+  }
 
   return EmitDeclare(VD, Storage, std::nullopt, Builder, UsePointerValue);
 }

diff  --git a/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
index b5ee96224565d3a..0234e41009f6225 100644
--- a/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding-bitfield.cpp
@@ -189,7 +189,6 @@ struct S11 {
 // CHECK-LABEL: define dso_local void @_Z4fS11v
 // CHECK:alloca %struct.S11, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S11, align 4
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS11() {
@@ -206,7 +205,6 @@ struct S12 {
 // CHECK:alloca %struct.S12, align 4
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S12, align 4
 // CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
[[S12_A:![0-9]+]], metadata !DIExpression())
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS12() {
@@ -222,7 +220,6 @@ struct __attribute__((packed)) S13 {
 // CHECK-LABEL: define dso_local void @_Z4fS13v
 // CHECK:alloca %struct.S13, align 1
 // CHECK-NEXT:[[TMP0:%.*]] = alloca %struct.S13, align 1
-// CHECK: call void @llvm.dbg.declare(metadata ptr [[TMP0]], metadata 
{{.*}}, metadata !DIExpression())
 // CHECK-NOT: call void @llvm.dbg.declare(metadata ptr [[TMP0]]
 //
 void fS13() {

diff  --git a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp 
b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
index 8d4ae0aaf32636b..7f3c3a08941abce 100644
--- a/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
+++ b/clang/test/CodeGenCXX/debug-info-structured-binding.cpp
@@ -1,11 +1,16 @@
-// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone -triple 
%itanium_abi_triple %s -o - | FileCheck %s
+// RUN: %clang_cc1 -emit-llvm -debug-info-kind=standalone -triple 
%itanium_abi_triple %s -o - | FileCheck %s --implicit-check-not="call void 
@llvm.dbg.declare"
+
+// CHECK: call void @llvm.dbg.declare(metadata ptr %{{[a-z]+}}, metadata 
![[VAR_0:[0-9]+]], metadata !DIExpression())
+// CHECK: call void @llvm.dbg.declare(metadata ptr %{{[0-9]+}}, metadata 
![[VAR_1:[0-9]+]], metadata !DIExpression())
+// CHECK: call void @llvm.dbg.declare(metadata ptr %{{[0-9]+}}, metadata 
![[VAR_2:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 4))
+// CHECK: call void @llvm.dbg.declare(metadata ptr %{{[0-9]+}}, metadata 
![[VAR_3:[0-9]+]], metadata !DIExpression(DW_OP_deref))
+// CHECK: call void @llvm.dbg.declare(metadata ptr %{{[0-9]+}}, metadata 
![[VAR_4:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 4))
+// CHECK: ![[VAR_0]] = !DILocalVariable(name: "a"
+// CHECK: ![[VAR_1]] = !DILocalVariable(name: "x1"
+// CHECK: ![[VAR_2]] = !DILocalVariable(name: "y1"
+// CHECK: ![[VAR_3]] = !DILocalVariable(name: "x2"
+// CHECK: ![[VAR_4]] = !DILocalVariable(name: "y2"
 
-// CHECK: call void

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

2023-10-25 Thread Carlos Alberto Enciso via cfe-commits

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


[clang] [mlir][LLVM] Verify too many indices in GEP verifier (PR #70174)

2023-10-25 Thread Markus Böck via cfe-commits

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


[clang] Disable memtag sanitization for global fnptrs going into .ctors (PR #70186)

2023-10-25 Thread Mitch Phillips via cfe-commits

https://github.com/hctim created https://github.com/llvm/llvm-project/pull/70186

Looks like there's code out there that, instead of using
'__attribute__((constructor(x)))' to add constructor functions, they
just declare a global function pointer and use
'__attribute__((section('.ctors')))' instead.

Problem is, with memtag-globals, we pad the global function pointer to
be 16 bytes large. This of course means we have an 8-byte real function
pointer, then 8 bytes of zero padding, and this trips up the loader when
it processes this section.

Fixes #69939


>From f70a2dba661163a436c40e9e8f97cd9a27a726ca Mon Sep 17 00:00:00 2001
From: Mitch Phillips 
Date: Wed, 25 Oct 2023 11:35:29 +0200
Subject: [PATCH] Disable memtag sanitization for global fnptrs going into
 .ctors

Looks like there's code out there that, instead of using
'__attribute__((constructor(x)))' to add constructor functions, they
just declare a global function pointer and use
'__attribute__((section('.ctors')))' instead.

Problem is, with memtag-globals, we pad the global function pointer to
be 16 bytes large. This of course means we have an 8-byte real function
pointer, then 8 bytes of zero padding, and this trips up the loader when
it processes this section.

Fixes #69939
---
 clang/test/CodeGen/memtag-globals-asm.cpp | 20 +++
 .../Target/AArch64/AArch64GlobalsTagging.cpp  | 12 +++
 2 files changed, 32 insertions(+)

diff --git a/clang/test/CodeGen/memtag-globals-asm.cpp 
b/clang/test/CodeGen/memtag-globals-asm.cpp
index 3f18671562def71..4b76b394e0c1dc3 100644
--- a/clang/test/CodeGen/memtag-globals-asm.cpp
+++ b/clang/test/CodeGen/memtag-globals-asm.cpp
@@ -259,3 +259,23 @@ int f(int x) {
   // CHECK-Q-DAG: ldr   {{.*}}, [[[REG_O2]]]
   function_int;
 }
+
+typedef void (*func_t)(void);
+#define CONSTRUCTOR(section_name) \
+  __attribute__((used)) __attribute__((section(section_name)))
+
+__attribute__((constructor(0))) void func_constructor() {}
+CONSTRUCTOR(".init") func_t func_init = func_constructor;
+CONSTRUCTOR(".fini") func_t func_fini = func_constructor;
+CONSTRUCTOR(".ctors") func_t func_ctors = func_constructor;
+CONSTRUCTOR(".dtors") func_t func_dtors = func_constructor;
+CONSTRUCTOR(".init_array") func_t func_init_array = func_constructor;
+CONSTRUCTOR(".fini_array") func_t func_fini_array = func_constructor;
+
+// CHECK-NOT: .memtag func_constructor
+// CHECK-NOT: .memtag func_init
+// CHECK-NOT: .memtag func_fini
+// CHECK-NOT: .memtag func_ctors
+// CHECK-NOT: .memtag func_dtors
+// CHECK-NOT: .memtag func_init_array
+// CHECK-NOT: .memtag func_fini_array
diff --git a/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp 
b/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
index 2ed668712897ce7..88e44eb0bfbb99f 100644
--- a/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
+++ b/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
@@ -43,6 +43,18 @@ static bool shouldTagGlobal(GlobalVariable &G) {
 return false;
   }
 
+  // Don't instrument function pointers that are going into various init arrays
+  // via `__attribute__((section()))`:
+  // https://github.com/llvm/llvm-project/issues/69939
+  if (G.hasSection() &&
+  (G.getSection() == ".init" || G.getSection() == ".fini" ||
+   G.getSection() == ".init_array" || G.getSection() == ".fini_array" ||
+   G.getSection() == ".ctors" || G.getSection() == ".dtors")) {
+Meta.Memtag = false;
+G.setSanitizerMetadata(Meta);
+return false;
+  }
+
   return true;
 }
 

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


[clang] Disable memtag sanitization for global fnptrs going into .ctors (PR #70186)

2023-10-25 Thread Mitch Phillips via cfe-commits

hctim wrote:

@P1119r1m

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


[clang] Disable memtag sanitization for global fnptrs going into .ctors (PR #70186)

2023-10-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Mitch Phillips (hctim)


Changes

Looks like there's code out there that, instead of using
'__attribute__((constructor(x)))' to add constructor functions, they
just declare a global function pointer and use
'__attribute__((section('.ctors')))' instead.

Problem is, with memtag-globals, we pad the global function pointer to
be 16 bytes large. This of course means we have an 8-byte real function
pointer, then 8 bytes of zero padding, and this trips up the loader when
it processes this section.

Fixes #69939


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


2 Files Affected:

- (modified) clang/test/CodeGen/memtag-globals-asm.cpp (+20) 
- (modified) llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp (+12) 


``diff
diff --git a/clang/test/CodeGen/memtag-globals-asm.cpp 
b/clang/test/CodeGen/memtag-globals-asm.cpp
index 3f18671562def71..4b76b394e0c1dc3 100644
--- a/clang/test/CodeGen/memtag-globals-asm.cpp
+++ b/clang/test/CodeGen/memtag-globals-asm.cpp
@@ -259,3 +259,23 @@ int f(int x) {
   // CHECK-Q-DAG: ldr   {{.*}}, [[[REG_O2]]]
   function_int;
 }
+
+typedef void (*func_t)(void);
+#define CONSTRUCTOR(section_name) \
+  __attribute__((used)) __attribute__((section(section_name)))
+
+__attribute__((constructor(0))) void func_constructor() {}
+CONSTRUCTOR(".init") func_t func_init = func_constructor;
+CONSTRUCTOR(".fini") func_t func_fini = func_constructor;
+CONSTRUCTOR(".ctors") func_t func_ctors = func_constructor;
+CONSTRUCTOR(".dtors") func_t func_dtors = func_constructor;
+CONSTRUCTOR(".init_array") func_t func_init_array = func_constructor;
+CONSTRUCTOR(".fini_array") func_t func_fini_array = func_constructor;
+
+// CHECK-NOT: .memtag func_constructor
+// CHECK-NOT: .memtag func_init
+// CHECK-NOT: .memtag func_fini
+// CHECK-NOT: .memtag func_ctors
+// CHECK-NOT: .memtag func_dtors
+// CHECK-NOT: .memtag func_init_array
+// CHECK-NOT: .memtag func_fini_array
diff --git a/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp 
b/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
index 2ed668712897ce7..88e44eb0bfbb99f 100644
--- a/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
+++ b/llvm/lib/Target/AArch64/AArch64GlobalsTagging.cpp
@@ -43,6 +43,18 @@ static bool shouldTagGlobal(GlobalVariable &G) {
 return false;
   }
 
+  // Don't instrument function pointers that are going into various init arrays
+  // via `__attribute__((section()))`:
+  // https://github.com/llvm/llvm-project/issues/69939
+  if (G.hasSection() &&
+  (G.getSection() == ".init" || G.getSection() == ".fini" ||
+   G.getSection() == ".init_array" || G.getSection() == ".fini_array" ||
+   G.getSection() == ".ctors" || G.getSection() == ".dtors")) {
+Meta.Memtag = false;
+G.setSanitizerMetadata(Meta);
+return false;
+  }
+
   return true;
 }
 

``




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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Balázs Kéri via cfe-commits

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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Balázs Kéri via cfe-commits

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

Probably add [clang] tag to the commit message, and remove the change in 
DiagnosticParseKinds.td, otherwise the change looks good.

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


[clang] [analyzer][NFC] Combine similar methods of StreamChecker (PR #70170)

2023-10-25 Thread Balázs Kéri via cfe-commits


@@ -1349,7 +1349,7 @@ def warn_omp_extra_tokens_at_eol : Warning<
   "extra tokens at the end of '#pragma omp %0' are ignored">,
   InGroup;
 def err_omp_multiple_step_or_linear_modifier : Error<
-  "multiple %select{'step size'|'linear modifier'}0 found in linear clause">; 
+  "multiple %select{'step size'|'linear modifier'}0 found in linear clause">;

balazske wrote:

This change is not related (or not intentional), it belongs into another commit.

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


[clang] [analyzer] Loop should contain CXXForRangeStmt (PR #70190)

2023-10-25 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky created 
https://github.com/llvm/llvm-project/pull/70190

Static analyze can't report diagnose when statement after a CXXForRangeStmt and 
enable widen, because `ExprEngine::processCFGBlockEntrance` lacks of 
CXXForRangeStmt and when `AMgr.options.maxBlockVisitOnPath - 1` equals to 
`blockCount`, it can't widen. After next iteration, `BlockCount >= 
AMgr.options.maxBlockVisitOnPath` holds and generate a sink node. Add 
`CXXForRangeStmt` makes it work.

>From dcd607df487ea04d2f1b6be9621b6a35ac7c2900 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 25 Oct 2023 18:13:21 +0800
Subject: [PATCH] [analyzer] Loop should contain CXXForRangeStmt

---
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp   |  2 +-
 clang/lib/StaticAnalyzer/Core/LoopWidening.cpp |  7 +--
 clang/test/Analysis/loop-widening-notes.cpp| 12 
 3 files changed, 18 insertions(+), 3 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 451ee91b94533d5..2e67fb953e45611 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2509,7 +2509,7 @@ void ExprEngine::processCFGBlockEntrance(const BlockEdge 
&L,
   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
   AMgr.options.ShouldWidenLoops) {
 const Stmt *Term = 
nodeBuilder.getContext().getBlock()->getTerminatorStmt();
-if (!isa_and_nonnull(Term))
+if (!isa_and_nonnull(Term))
   return;
 // Widen.
 const LocationContext *LCtx = Pred->getLocationContext();
diff --git a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
index a3b29ff487e4edc..180c50cf3e0d20f 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -13,10 +13,11 @@
 ///
 
//===--===//
 
+#include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 #include "clang/AST/AST.h"
+#include "clang/AST/StmtCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 
 using namespace clang;
 using namespace ento;
@@ -35,6 +36,8 @@ static const Expr *getLoopCondition(const Stmt *LoopStmt) {
 return cast(LoopStmt)->getCond();
   case Stmt::DoStmtClass:
 return cast(LoopStmt)->getCond();
+  case Stmt::CXXForRangeStmtClass:
+return cast(LoopStmt)->getCond();
   }
 }
 
@@ -45,7 +48,7 @@ ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState,
 const LocationContext *LCtx,
 unsigned BlockCount, const Stmt *LoopStmt) 
{
 
-  assert((isa(LoopStmt)));
+  assert((isa(LoopStmt)));
 
   // Invalidate values in the current state.
   // TODO Make this more conservative by only invalidating values that might
diff --git a/clang/test/Analysis/loop-widening-notes.cpp 
b/clang/test/Analysis/loop-widening-notes.cpp
index 0ba71d030d058a6..a3f030dfe988261 100644
--- a/clang/test/Analysis/loop-widening-notes.cpp
+++ b/clang/test/Analysis/loop-widening-notes.cpp
@@ -70,3 +70,15 @@ int test_for_loop() {
   return flag_d / num; // no-crash expected-warning {{Division by zero}} 
// expected-note@-1 {{Division by zero}}
 }
+
+int test_for_range_loop() {
+  int arr[10] = {0};
+  for(auto x : arr) { // expected-note {{Assigning value}} 
+++x;
+  }
+  if (arr[0] == 0)   // expected-note {{Assuming the condition is true}} 
+ // expected-note@-1 {{Taking true branch}}
+return 1/arr[0]; // expected-warning {{Division by zero}}
+ // expected-note@-1 {{Division by zero}}
+  return 0;
+}

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


[clang] [analyzer] Loop should contain CXXForRangeStmt (PR #70190)

2023-10-25 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: Qizhi Hu (jcsxky)


Changes

Static analyze can't report diagnose when statement after a CXXForRangeStmt and 
enable widen, because `ExprEngine::processCFGBlockEntrance` lacks of 
CXXForRangeStmt and when `AMgr.options.maxBlockVisitOnPath - 1` equals to 
`blockCount`, it can't widen. After next iteration, `BlockCount >= 
AMgr.options.maxBlockVisitOnPath` holds and generate a sink node. Add 
`CXXForRangeStmt` makes it work.

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


3 Files Affected:

- (modified) clang/lib/StaticAnalyzer/Core/ExprEngine.cpp (+1-1) 
- (modified) clang/lib/StaticAnalyzer/Core/LoopWidening.cpp (+5-2) 
- (modified) clang/test/Analysis/loop-widening-notes.cpp (+12) 


``diff
diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 451ee91b94533d5..2e67fb953e45611 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2509,7 +2509,7 @@ void ExprEngine::processCFGBlockEntrance(const BlockEdge 
&L,
   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
   AMgr.options.ShouldWidenLoops) {
 const Stmt *Term = 
nodeBuilder.getContext().getBlock()->getTerminatorStmt();
-if (!isa_and_nonnull(Term))
+if (!isa_and_nonnull(Term))
   return;
 // Widen.
 const LocationContext *LCtx = Pred->getLocationContext();
diff --git a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
index a3b29ff487e4edc..180c50cf3e0d20f 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -13,10 +13,11 @@
 ///
 
//===--===//
 
+#include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 #include "clang/AST/AST.h"
+#include "clang/AST/StmtCXX.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 
 using namespace clang;
 using namespace ento;
@@ -35,6 +36,8 @@ static const Expr *getLoopCondition(const Stmt *LoopStmt) {
 return cast(LoopStmt)->getCond();
   case Stmt::DoStmtClass:
 return cast(LoopStmt)->getCond();
+  case Stmt::CXXForRangeStmtClass:
+return cast(LoopStmt)->getCond();
   }
 }
 
@@ -45,7 +48,7 @@ ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState,
 const LocationContext *LCtx,
 unsigned BlockCount, const Stmt *LoopStmt) 
{
 
-  assert((isa(LoopStmt)));
+  assert((isa(LoopStmt)));
 
   // Invalidate values in the current state.
   // TODO Make this more conservative by only invalidating values that might
diff --git a/clang/test/Analysis/loop-widening-notes.cpp 
b/clang/test/Analysis/loop-widening-notes.cpp
index 0ba71d030d058a6..a3f030dfe988261 100644
--- a/clang/test/Analysis/loop-widening-notes.cpp
+++ b/clang/test/Analysis/loop-widening-notes.cpp
@@ -70,3 +70,15 @@ int test_for_loop() {
   return flag_d / num; // no-crash expected-warning {{Division by zero}} 
// expected-note@-1 {{Division by zero}}
 }
+
+int test_for_range_loop() {
+  int arr[10] = {0};
+  for(auto x : arr) { // expected-note {{Assigning value}} 
+++x;
+  }
+  if (arr[0] == 0)   // expected-note {{Assuming the condition is true}} 
+ // expected-note@-1 {{Taking true branch}}
+return 1/arr[0]; // expected-warning {{Division by zero}}
+ // expected-note@-1 {{Division by zero}}
+  return 0;
+}

``




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


[clang] [analyzer] Loop should contain CXXForRangeStmt (PR #70190)

2023-10-25 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/70190

>From f65ad2217e169b1d6876696201b97ffca5f9c886 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 25 Oct 2023 18:13:21 +0800
Subject: [PATCH] [analyzer] Loop should contain CXXForRangeStmt

---
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp   |  2 +-
 clang/lib/StaticAnalyzer/Core/LoopWidening.cpp |  5 +++--
 clang/test/Analysis/loop-widening-notes.cpp| 12 
 3 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 451ee91b94533d5..2e67fb953e45611 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2509,7 +2509,7 @@ void ExprEngine::processCFGBlockEntrance(const BlockEdge 
&L,
   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
   AMgr.options.ShouldWidenLoops) {
 const Stmt *Term = 
nodeBuilder.getContext().getBlock()->getTerminatorStmt();
-if (!isa_and_nonnull(Term))
+if (!isa_and_nonnull(Term))
   return;
 // Widen.
 const LocationContext *LCtx = Pred->getLocationContext();
diff --git a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
index a3b29ff487e4edc..d2479827355cf76 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -16,7 +16,6 @@
 #include "clang/AST/AST.h"
 #include "clang/ASTMatchers/ASTMatchFinder.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
-#include "clang/StaticAnalyzer/Core/PathSensitive/LoopWidening.h"
 
 using namespace clang;
 using namespace ento;
@@ -35,6 +34,8 @@ static const Expr *getLoopCondition(const Stmt *LoopStmt) {
 return cast(LoopStmt)->getCond();
   case Stmt::DoStmtClass:
 return cast(LoopStmt)->getCond();
+  case Stmt::CXXForRangeStmtClass:
+return cast(LoopStmt)->getCond();
   }
 }
 
@@ -45,7 +46,7 @@ ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState,
 const LocationContext *LCtx,
 unsigned BlockCount, const Stmt *LoopStmt) 
{
 
-  assert((isa(LoopStmt)));
+  assert((isa(LoopStmt)));
 
   // Invalidate values in the current state.
   // TODO Make this more conservative by only invalidating values that might
diff --git a/clang/test/Analysis/loop-widening-notes.cpp 
b/clang/test/Analysis/loop-widening-notes.cpp
index 0ba71d030d058a6..a3f030dfe988261 100644
--- a/clang/test/Analysis/loop-widening-notes.cpp
+++ b/clang/test/Analysis/loop-widening-notes.cpp
@@ -70,3 +70,15 @@ int test_for_loop() {
   return flag_d / num; // no-crash expected-warning {{Division by zero}} 
// expected-note@-1 {{Division by zero}}
 }
+
+int test_for_range_loop() {
+  int arr[10] = {0};
+  for(auto x : arr) { // expected-note {{Assigning value}} 
+++x;
+  }
+  if (arr[0] == 0)   // expected-note {{Assuming the condition is true}} 
+ // expected-note@-1 {{Taking true branch}}
+return 1/arr[0]; // expected-warning {{Division by zero}}
+ // expected-note@-1 {{Division by zero}}
+  return 0;
+}

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


[clang] [analyzer] Loop should contain CXXForRangeStmt (PR #70190)

2023-10-25 Thread Qizhi Hu via cfe-commits

https://github.com/jcsxky updated 
https://github.com/llvm/llvm-project/pull/70190

>From b1b49db9f155d0bf0aef626d620b6287509fb538 Mon Sep 17 00:00:00 2001
From: huqizhi 
Date: Wed, 25 Oct 2023 18:13:21 +0800
Subject: [PATCH] [analyzer] Loop should contain CXXForRangeStmt

---
 clang/lib/StaticAnalyzer/Core/ExprEngine.cpp   |  2 +-
 clang/lib/StaticAnalyzer/Core/LoopWidening.cpp |  4 +++-
 clang/test/Analysis/loop-widening-notes.cpp| 12 
 3 files changed, 16 insertions(+), 2 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp 
b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 451ee91b94533d5..2e67fb953e45611 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -2509,7 +2509,7 @@ void ExprEngine::processCFGBlockEntrance(const BlockEdge 
&L,
   if (BlockCount == AMgr.options.maxBlockVisitOnPath - 1 &&
   AMgr.options.ShouldWidenLoops) {
 const Stmt *Term = 
nodeBuilder.getContext().getBlock()->getTerminatorStmt();
-if (!isa_and_nonnull(Term))
+if (!isa_and_nonnull(Term))
   return;
 // Widen.
 const LocationContext *LCtx = Pred->getLocationContext();
diff --git a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp 
b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
index a3b29ff487e4edc..9e42801760622df 100644
--- a/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
+++ b/clang/lib/StaticAnalyzer/Core/LoopWidening.cpp
@@ -35,6 +35,8 @@ static const Expr *getLoopCondition(const Stmt *LoopStmt) {
 return cast(LoopStmt)->getCond();
   case Stmt::DoStmtClass:
 return cast(LoopStmt)->getCond();
+  case Stmt::CXXForRangeStmtClass:
+return cast(LoopStmt)->getCond();
   }
 }
 
@@ -45,7 +47,7 @@ ProgramStateRef getWidenedLoopState(ProgramStateRef PrevState,
 const LocationContext *LCtx,
 unsigned BlockCount, const Stmt *LoopStmt) 
{
 
-  assert((isa(LoopStmt)));
+  assert((isa(LoopStmt)));
 
   // Invalidate values in the current state.
   // TODO Make this more conservative by only invalidating values that might
diff --git a/clang/test/Analysis/loop-widening-notes.cpp 
b/clang/test/Analysis/loop-widening-notes.cpp
index 0ba71d030d058a6..a3f030dfe988261 100644
--- a/clang/test/Analysis/loop-widening-notes.cpp
+++ b/clang/test/Analysis/loop-widening-notes.cpp
@@ -70,3 +70,15 @@ int test_for_loop() {
   return flag_d / num; // no-crash expected-warning {{Division by zero}} 
// expected-note@-1 {{Division by zero}}
 }
+
+int test_for_range_loop() {
+  int arr[10] = {0};
+  for(auto x : arr) { // expected-note {{Assigning value}} 
+++x;
+  }
+  if (arr[0] == 0)   // expected-note {{Assuming the condition is true}} 
+ // expected-note@-1 {{Taking true branch}}
+return 1/arr[0]; // expected-warning {{Division by zero}}
+ // expected-note@-1 {{Division by zero}}
+  return 0;
+}

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


[clang-tools-extra] [InstCombine] Fold xored one-complemented operand comparisons (PR #69882)

2023-10-25 Thread via cfe-commits

https://github.com/elhewaty updated 
https://github.com/llvm/llvm-project/pull/69882

>From 3a6ddf5192264e2dc32adc67184e06529151b343 Mon Sep 17 00:00:00 2001
From: Mohamed Atef 
Date: Tue, 24 Oct 2023 16:54:14 +0300
Subject: [PATCH 1/2] [InstCombine] Add test coverage for comparisons of
 operands including one-complemented oparands(NFC)

---
 .../Transforms/InstCombine/icmp-of-xor-x.ll   | 295 ++
 1 file changed, 295 insertions(+)

diff --git a/llvm/test/Transforms/InstCombine/icmp-of-xor-x.ll 
b/llvm/test/Transforms/InstCombine/icmp-of-xor-x.ll
index 9b6572697cf5e8f..94856424e102b03 100644
--- a/llvm/test/Transforms/InstCombine/icmp-of-xor-x.ll
+++ b/llvm/test/Transforms/InstCombine/icmp-of-xor-x.ll
@@ -3,6 +3,301 @@
 
 declare void @llvm.assume(i1)
 declare void @barrier()
+declare void @use.i8(i8)
+
+; test for (~x ^ y) < ~z
+define i1 @test_xor1(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor1(
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[X:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[Y:%.*]]
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[R:%.*]] = icmp slt i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %xor = xor i8 %x, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %y
+  %nz = xor i8 %z, -1
+  %r = icmp slt i8 %xor2, %nz
+  ret i1 %r
+}
+
+; test for ~z <= (x ^ ~y)
+define i1 @test_xor2(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor2(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[Y:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[X:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp sge i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %y, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %x
+  %r = icmp sle i8 %nz, %xor2
+  ret i1 %r
+}
+
+; test for ~z > (~x ^ y)
+define i1 @test_xor3(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor3(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[X:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[Y:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp slt i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %x, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %y
+  %r = icmp sgt i8 %nz, %xor2
+  ret i1 %r
+}
+
+; tests for equality
+define i1 @test_xor_ne(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor_ne(
+; CHECK-NEXT:[[TMP1:%.*]] = xor i8 [[Y:%.*]], [[X:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp ne i8 [[TMP1]], [[Z:%.*]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %y, -1
+  %xor2 = xor i8 %xor, %x
+  %r = icmp ne i8 %nz, %xor2
+  ret i1 %r
+}
+
+define i1 @test_xor_eq(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor_eq(
+; CHECK-NEXT:[[TMP1:%.*]] = xor i8 [[Y:%.*]], [[X:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp eq i8 [[TMP1]], [[Z:%.*]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %y, -1
+  %xor2 = xor i8 %xor, %x
+  %r = icmp eq i8 %nz, %xor2
+  ret i1 %r
+}
+
+; other tests
+define i1 @test_xor4(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor4(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[X:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[Y:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp sge i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %x, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %y
+  %r = icmp sge i8 %xor2, %nz
+  ret i1 %r
+}
+
+define i1 @test_xor5(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor5(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[X:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[Y:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp ult i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %x, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %y
+  %r = icmp ult i8 %xor2, %nz
+  ret i1 %r
+}
+
+define i1 @test_xor6(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor6(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] = xor i8 [[X:%.*]], -1
+; CHECK-NEXT:call void @use.i8(i8 [[XOR]])
+; CHECK-NEXT:[[XOR2:%.*]] = xor i8 [[XOR]], [[Y:%.*]]
+; CHECK-NEXT:[[R:%.*]] = icmp ule i8 [[XOR2]], [[NZ]]
+; CHECK-NEXT:ret i1 [[R]]
+;
+  %nz = xor i8 %z, -1
+  %xor = xor i8 %x, -1
+  call void @use.i8(i8 %xor)
+  %xor2 = xor i8 %xor, %y
+  %r = icmp ule i8 %xor2, %nz
+  ret i1 %r
+}
+
+define i1 @test_xor7(i8 %x, i8 %y, i8 %z) {
+; CHECK-LABEL: @test_xor7(
+; CHECK-NEXT:[[NZ:%.*]] = xor i8 [[Z:%.*]], -1
+; CHECK-NEXT:[[XOR:%.*]] =

[PATCH] D158266: [OpenMP] Patch for Support to loop bind clause : Checking Parent Region

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

Removing multiple calls to Sema::checkNestingOfRegions() in 
Sema::ActOnOpenMPExecutableDirective() .


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

https://reviews.llvm.org/D158266

Files:
  clang/include/clang/Sema/Sema.h
  clang/lib/Sema/SemaOpenMP.cpp
  clang/test/OpenMP/loop_bind_messages.cpp
  clang/test/PCH/pragma-loop.cpp

Index: clang/test/PCH/pragma-loop.cpp
===
--- clang/test/PCH/pragma-loop.cpp
+++ clang/test/PCH/pragma-loop.cpp
@@ -116,9 +116,13 @@
 
   inline void run10(int *List, int Length) {
 int i = 0;
-#pragma omp loop bind(teams)
+int j = 0;
+#pragma omp teams
 for (int i = 0; i < Length; i++) {
-  List[i] = i;
+  #pragma omp loop bind(teams)
+  for (int j = 0; j < Length; j++) {
+List[i] = i+j;
+  }
 }
   }
 
Index: clang/test/OpenMP/loop_bind_messages.cpp
===
--- clang/test/OpenMP/loop_bind_messages.cpp
+++ clang/test/OpenMP/loop_bind_messages.cpp
@@ -4,6 +4,7 @@
 
 #define NNN 50
 int aaa[NNN];
+int aaa2[NNN][NNN];
 
 void parallel_loop() {
   #pragma omp parallel
@@ -15,6 +16,91 @@
}
 }
 
+void parallel_for_AND_loop_bind() {
+  #pragma omp parallel for
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_nowait() {
+  #pragma omp parallel
+  #pragma omp for nowait
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_for_with_nothing() {
+  #pragma omp parallel for
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp nothing
+#pragma omp loop // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_targetfor_with_loop_bind() {
+  #pragma omp target teams distribute parallel for 
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'target teams distribute parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void parallel_targetparallel_with_loop() {
+  #pragma omp target parallel
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(parallel)
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
+  }
+}
+
+void loop_bind_AND_loop_bind() {
+  #pragma omp parallel for
+  for (int i = 0; i < 100; ++i) {
+#pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'parallel for' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}} 
+for (int i = 0 ; i < NNN ; i++) {
+  #pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'loop' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}} 
+  for (int j = 0 ; j < NNN ; j++) {
+aaa[j] = j*NNN;
+  }
+}
+  }
+}
+
+void parallel_with_sections_loop() {
+  #pragma omp parallel
+  {
+ #pragma omp sections
+ {
+for (int i = 0 ; i < NNN ; i++) {
+  #pragma omp loop bind(parallel) // expected-error{{region cannot be closely nested inside 'sections' region; perhaps you forget to enclose 'omp loop' directive into a parallel region?}}
+  for (int j = 0 ; j < NNN ; j++) {
+aaa2[i][j] = i+j;
+  }
+}
+
+#pragma omp section
+	{
+  aaa[NNN-1] = NNN;
+}
+ }
+  }
+}
+
 void teams_loop() {
   int var1, var2;
 
@@ -34,17 +120,23 @@
}
 }
 
-void orphan_loop_with_bind() {
-  #pragma omp loop bind(parallel) 
-  for (int j = 0 ; j < NNN ; j++) {
-aaa[j] = j*NNN;
+void teams_targetteams_with_loop() {
+  #pragma omp target teams
+  for (int i = 0 ; i < NNN ; i++) {
+#pragma omp loop bind(teams)
+for (int j = 0 ; j < NNN ; j++) {
+  aaa2[i][j] = i+j;
+}
   }
 }
 
-void orphan_loop_no_bind() {
-  #pragma omp loop  // expected-error{{expected 'bind' clause for 'loop' construct without an enclosing OpenMP construct}}
-  for (int j = 0 ; j < NNN ; j++) {
-aaa[j] = j*NNN;
+void teams_targetfor_with_loop_bind() {
+  #pragma omp target teams distribute parallel for 
+  for (int i = 0 ; i <

[clang-tools-extra] [InstCombine] Fold xored one-complemented operand comparisons (PR #69882)

2023-10-25 Thread via cfe-commits

elhewaty wrote:

@dtcxzyw can you help me, what is wrong here?

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


[clang] [flang] add tbaa tags to global and direct values (PR #68727)

2023-10-25 Thread Tom Eccles via cfe-commits

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


[clang] [flang] add tbaa tags to global and direct values (PR #68727)

2023-10-25 Thread Tom Eccles via cfe-commits

tblah wrote:

Merged manually in 
https://github.com/llvm/llvm-project/commit/6242c8ca18bcd6765094c73dd2c8b49200a6cec8

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


[clang] 5efa84c - [clang-format] Don't align comments over scopes

2023-10-25 Thread via cfe-commits

Author: Björn Schäpers
Date: 2023-10-25T12:50:15+02:00
New Revision: 5efa84cf6feaaa03e6325836f89503b0ab2be0d8

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

LOG: [clang-format] Don't align comments over scopes

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

Fixes #67906.

Added: 


Modified: 
clang/docs/ClangFormatStyleOptions.rst
clang/include/clang/Format/Format.h
clang/lib/Format/WhitespaceManager.cpp
clang/unittests/Format/FormatTestComments.cpp

Removed: 




diff  --git a/clang/docs/ClangFormatStyleOptions.rst 
b/clang/docs/ClangFormatStyleOptions.rst
index cfd57f5fa8153f4..5f369ea9759edad 100644
--- a/clang/docs/ClangFormatStyleOptions.rst
+++ b/clang/docs/ClangFormatStyleOptions.rst
@@ -980,6 +980,10 @@ the configuration (without a prefix: ``Auto``).
 **AlignTrailingComments** (``TrailingCommentsAlignmentStyle``) 
:versionbadge:`clang-format 3.7` :ref:`¶ `
   Control of trailing comments.
 
+  The alignment stops at closing braces after a line break, and only
+  followed by other closing braces, a (``do-``) ``while``, a lambda call, or
+  a semicolon.
+
 
   .. note::
 

diff  --git a/clang/include/clang/Format/Format.h 
b/clang/include/clang/Format/Format.h
index 4c344135d25163c..d0145fa9272cdd6 100644
--- a/clang/include/clang/Format/Format.h
+++ b/clang/include/clang/Format/Format.h
@@ -539,6 +539,10 @@ struct FormatStyle {
 
   /// Control of trailing comments.
   ///
+  /// The alignment stops at closing braces after a line break, and only
+  /// followed by other closing braces, a (``do-``) ``while``, a lambda call, 
or
+  /// a semicolon.
+  ///
   /// \note
   ///  As of clang-format 16 this option is not a bool but can be set
   ///  to the options. Conventional bool options still can be parsed as before.

diff  --git a/clang/lib/Format/WhitespaceManager.cpp 
b/clang/lib/Format/WhitespaceManager.cpp
index dbe6175fb9653ed..ff8b1e6e13a3f77 100644
--- a/clang/lib/Format/WhitespaceManager.cpp
+++ b/clang/lib/Format/WhitespaceManager.cpp
@@ -1048,6 +1048,9 @@ void WhitespaceManager::alignChainedConditionals() {
 }
 
 void WhitespaceManager::alignTrailingComments() {
+  if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never)
+return;
+
   const int Size = Changes.size();
   int MinColumn = 0;
   int StartOfSequence = 0;
@@ -1118,16 +1121,48 @@ void WhitespaceManager::alignTrailingComments() {
   }
 }
 
-// We don't want to align namespace end comments.
-const bool DontAlignThisComment =
-I > 0 && C.NewlinesBefore == 0 &&
-Changes[I - 1].Tok->is(TT_NamespaceRBrace);
-if (Style.AlignTrailingComments.Kind == FormatStyle::TCAS_Never ||
-DontAlignThisComment) {
+// We don't want to align comments which end a scope, which are here
+// identified by most closing braces.
+auto DontAlignThisComment = [](const auto *Tok) {
+  if (Tok->is(tok::semi)) {
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+  }
+  if (Tok->is(tok::r_paren)) {
+// Back up past the parentheses and a `TT_DoWhile` that may precede.
+Tok = Tok->MatchingParen;
+if (!Tok)
+  return false;
+Tok = Tok->getPreviousNonComment();
+if (!Tok)
+  return false;
+if (Tok->is(TT_DoWhile)) {
+  const auto *Prev = Tok->getPreviousNonComment();
+  if (!Prev) {
+// A do-while-loop without braces.
+return true;
+  }
+  Tok = Prev;
+}
+  }
+
+  if (Tok->isNot(tok::r_brace))
+return false;
+
+  while (Tok->Previous && Tok->Previous->is(tok::r_brace))
+Tok = Tok->Previous;
+  return Tok->NewlinesBefore > 0;
+};
+
+if (I > 0 && C.NewlinesBefore == 0 &&
+DontAlignThisComment(Changes[I - 1].Tok)) {
   alignTrailingComments(StartOfSequence, I, MinColumn);
-  MinColumn = ChangeMinColumn;
-  MaxColumn = ChangeMinColumn;
-  StartOfSequence = I;
+  // Reset to initial values, but skip this change for the next alignment
+  // pass.
+  MinColumn = 0;
+  MaxColumn = INT_MAX;
+  StartOfSequence = I + 1;
 } else if (BreakBeforeNext || Newlines > NewLineThreshold ||
(ChangeMinColumn > MaxColumn || ChangeMaxColumn < MinColumn) ||
// Break the comment sequence if the previous line did not end

diff  --git a/clang/unittests/Format/FormatTestComments.cpp 
b/clang/unittests/Format/FormatTestComments.cpp
index 1198329b7b5a8f0..5e5324f01d8670a 100644
--- a/clang/unittests/Format/FormatTestComments.cpp
+++ b/clang/unittests/Format/FormatTestComments.cpp
@@ -182,7 +182,

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

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

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


[clang] [Driver] Add ExclusiveGroup feature to multilib.yaml. (PR #69447)

2023-10-25 Thread Simon Tatham via cfe-commits


@@ -152,6 +180,7 @@ template <> struct 
llvm::yaml::MappingTraits {
   static void mapping(llvm::yaml::IO &io, MultilibSerialization &V) {
 io.mapRequired("Dir", V.Dir);
 io.mapRequired("Flags", V.Flags);
+io.mapOptional("ExclusiveGroup", V.ExclusiveGroup);

statham-arm wrote:

I'll rename it if you like, but I worry that that might be ambiguous, or at 
least unclear. Within the general context of linking and libraries, "group" 
need not mean a _mutually exclusive_ group; it could mean a grouping of 
libraries for other purposes too, like a mutually _dependent_ group (you must 
select all of these or none).

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


[clang] [NFC][Clang] Fix potential deref of end iterator (PR #70193)

2023-10-25 Thread Nathan Gauër via cfe-commits

https://github.com/Keenuts created 
https://github.com/llvm/llvm-project/pull/70193

This was found by doing bound-checking on SmallVector iterator usage. When the 
count is 0, the end iterator is dereferenced to get its address. This doesn't 
seem to be an issue in practice as most of the time, and we are allowed to 
deref this address, but I don't think this is correct.

From cde1bc9613fa384e4355d39ea29b705b1140dc83 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Nathan=20Gau=C3=ABr?= 
Date: Wed, 25 Oct 2023 12:40:22 +0200
Subject: [PATCH] [NFC][Clang] Fix potential deref of end iterator
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

This was found by doing bound-checking on SmallVector iterator usage.
When the count is 0, the end iterator is dereferenced to get its
address. This doesn't seem to be an issue in practice as most of the
time, and we are allowed to deref this address, but I don't think
this is correct.

Signed-off-by: Nathan Gauër 
---
 clang/include/clang/Sema/CXXFieldCollector.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/clang/include/clang/Sema/CXXFieldCollector.h 
b/clang/include/clang/Sema/CXXFieldCollector.h
index f6ecd9f46e5ebdb..ce066581c93fda7 100644
--- a/clang/include/clang/Sema/CXXFieldCollector.h
+++ b/clang/include/clang/Sema/CXXFieldCollector.h
@@ -65,7 +65,7 @@ class CXXFieldCollector {
 
   /// getCurFields - Pointer to array of fields added to the currently parsed
   /// class.
-  FieldDecl **getCurFields() { return &*(Fields.end() - getCurNumFields()); }
+  FieldDecl **getCurFields() { return Fields.end() - getCurNumFields(); }
 
   /// FinishClass - Called by Sema::ActOnFinishCXXClassDef.
   void FinishClass() {

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


[clang-tools-extra] [AMDGPU] Rematerialize scalar loads (PR #68778)

2023-10-25 Thread Piotr Sobczak via cfe-commits

https://github.com/piotrAMD updated 
https://github.com/llvm/llvm-project/pull/68778

>From 6b5ada294d999ba1412020806ce8fab8e34a408e Mon Sep 17 00:00:00 2001
From: Piotr Sobczak 
Date: Wed, 11 Oct 2023 10:32:57 +0200
Subject: [PATCH 1/5] [AMDGPU] Rematerialize scalar loads

Extend the list of instructions that can be rematerialized in
SIInstrInfo::isReallyTriviallyReMaterializable() to support scalar loads.

Try shrinking instructions to remat only the part needed for current
context. Add SIInstrInfo::reMaterialize target hook, and handle shrinking
of S_LOAD_DWORDX16_IMM to S_LOAD_DWORDX8_IMM as a proof of concept.
---
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp| 110 +
 llvm/lib/Target/AMDGPU/SIInstrInfo.h  |   5 +
 .../hsa-metadata-kernel-code-props-v3.ll  |   4 +-
 llvm/test/CodeGen/AMDGPU/remat-smrd.mir   | 116 +-
 .../AMDGPU/snippet-copy-bundle-regression.mir |  42 +--
 5 files changed, 151 insertions(+), 126 deletions(-)

diff --git a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp 
b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
index 51397cbb791469d..31a086cd2a61820 100644
--- a/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/SIInstrInfo.cpp
@@ -108,7 +108,18 @@ static bool nodesHaveSameOperandValue(SDNode *N0, SDNode* 
N1, unsigned OpName) {
 
 bool SIInstrInfo::isReallyTriviallyReMaterializable(
 const MachineInstr &MI) const {
+
+  bool CanRemat = false;
   if (isVOP1(MI) || isVOP2(MI) || isVOP3(MI) || isSDWA(MI) || isSALU(MI)) {
+CanRemat = true;
+  } else if (isSMRD(MI)) {
+CanRemat = !MI.memoperands_empty() &&
+   llvm::all_of(MI.memoperands(), [](const MachineMemOperand *MMO) 
{
+ return MMO->isLoad() && MMO->isInvariant();
+   });
+  }
+
+  if (CanRemat) {
 // Normally VALU use of exec would block the rematerialization, but that
 // is OK in this case to have an implicit exec read as all VALU do.
 // We really want all of the generic logic for this except for this.
@@ -2434,6 +2445,105 @@ bool SIInstrInfo::expandPostRAPseudo(MachineInstr &MI) 
const {
   return true;
 }
 
+void SIInstrInfo::reMaterialize(MachineBasicBlock &MBB,
+MachineBasicBlock::iterator I, Register 
DestReg,
+unsigned SubIdx, const MachineInstr &Orig,
+const TargetRegisterInfo &RI) const {
+
+  // Try shrinking the instruction to remat only the part needed for current
+  // context.
+  // TODO: Handle more cases.
+  unsigned Opcode = Orig.getOpcode();
+  switch (Opcode) {
+  case AMDGPU::S_LOAD_DWORDX16_IMM:
+  case AMDGPU::S_LOAD_DWORDX8_IMM: {
+if (SubIdx != 0)
+  break;
+
+if (I == MBB.end())
+  break;
+
+if (I->isBundled())
+  break;
+
+// Look for a single use of the register that is also a subreg.
+Register RegToFind = Orig.getOperand(0).getReg();
+int SingleUseIdx = -1;
+for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
+  const MachineOperand &CandMO = I->getOperand(i);
+  if (!CandMO.isReg())
+continue;
+  Register CandReg = CandMO.getReg();
+  if (!CandReg)
+continue;
+
+  if (CandReg == RegToFind || RI.regsOverlap(CandReg, RegToFind)) {
+if (SingleUseIdx == -1 && CandMO.isUse()) {
+  SingleUseIdx = i;
+} else {
+  SingleUseIdx = -1;
+  break;
+}
+  }
+}
+if (SingleUseIdx == -1)
+  break;
+MachineOperand *UseMO = &I->getOperand(SingleUseIdx);
+if (UseMO->getSubReg() == AMDGPU::NoSubRegister)
+  break;
+
+unsigned Offset = RI.getSubRegIdxOffset(UseMO->getSubReg());
+unsigned SubregSize = RI.getSubRegIdxSize(UseMO->getSubReg());
+
+MachineFunction *MF = MBB.getParent();
+MachineRegisterInfo &MRI = MF->getRegInfo();
+assert(MRI.hasAtMostUserInstrs(DestReg, 0) &&
+   "DestReg should have no users yet.");
+
+unsigned NewOpcode = -1;
+if (SubregSize == 256)
+  NewOpcode = AMDGPU::S_LOAD_DWORDX8_IMM;
+else if (SubregSize == 128)
+  NewOpcode = AMDGPU::S_LOAD_DWORDX4_IMM;
+else
+  break;
+
+const MCInstrDesc &TID = get(NewOpcode);
+const TargetRegisterClass *NewRC =
+RI.getAllocatableClass(getRegClass(TID, 0, &RI, *MF));
+MRI.setRegClass(DestReg, NewRC);
+
+UseMO->setReg(DestReg);
+UseMO->setSubReg(AMDGPU::NoSubRegister);
+
+// Use a smaller load with the desired size, possibly with updated offset.
+MachineInstr *MI = MF->CloneMachineInstr(&Orig);
+MI->setDesc(TID);
+MI->getOperand(0).setReg(DestReg);
+MI->getOperand(0).setSubReg(AMDGPU::NoSubRegister);
+if (Offset) {
+  MachineOperand *OffsetMO = getNamedOperand(*MI, AMDGPU::OpName::offset);
+  int64_t FinalOffset = OffsetMO->getImm() + Offset / 8;
+  OffsetMO->setImm(FinalOffset);
+}
+SmallVector NewMMOs;
+for (const MachineMemOperand *MemOp : Orig.memoperands()

  1   2   3   4   5   6   >