[clang-tools-extra] [clang-tidy] Add check hicpp-ignored-remove-result (PR #73119)

2023-12-07 Thread Björn Svensson via cfe-commits

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


[clang] [clang][AMDGPU] Update amdgpu_waves_per_eu attr docs (PR #74587)

2023-12-07 Thread Matt Arsenault via cfe-commits

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


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


[clang] [clang][AMDGPU] Update amdgpu_waves_per_eu attr docs (PR #74587)

2023-12-07 Thread Matt Arsenault via cfe-commits


@@ -2659,8 +2659,9 @@ An error will be given if:
   - Specified values violate subtarget specifications;
   - Specified values are not compatible with values provided through other
 attributes;
-  - The AMDGPU target backend is unable to create machine code that can meet 
the
-request.
+
+The AMDGPU target backend will emit a warning whenever it is unable to

arsenm wrote:

Oh, I wasn't looking at the header bit here. I was also assuming this is using 
the sphinx formatting rules? I suppose it doesn't really matter 

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


[clang] 39ac5ee - [clang][AMDGPU] Update amdgpu_waves_per_eu attr docs (#74587)

2023-12-07 Thread via cfe-commits

Author: Pierre van Houtryve
Date: 2023-12-07T09:25:27+01:00
New Revision: 39ac5eecbbd7c45436fab4569aee82cc74411c53

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

LOG: [clang][AMDGPU] Update amdgpu_waves_per_eu attr docs (#74587)

Added: 


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

Removed: 




diff  --git a/clang/include/clang/Basic/AttrDocs.td 
b/clang/include/clang/Basic/AttrDocs.td
index bbe4de94cbabe..88f7c65e6e847 100644
--- a/clang/include/clang/Basic/AttrDocs.td
+++ b/clang/include/clang/Basic/AttrDocs.td
@@ -2659,8 +2659,9 @@ An error will be given if:
   - Specified values violate subtarget specifications;
   - Specified values are not compatible with values provided through other
 attributes;
-  - The AMDGPU target backend is unable to create machine code that can meet 
the
-request.
+
+The AMDGPU target backend will emit a warning whenever it is unable to
+create machine code that meets the request.
   }];
 }
 



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


[clang] [clang][AMDGPU] Update amdgpu_waves_per_eu attr docs (PR #74587)

2023-12-07 Thread Pierre van Houtryve via cfe-commits

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Ben Shi via cfe-commits

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

>From 65ce18117f99056aafcf58151b64f4243f4d5e26 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Mon, 4 Dec 2023 15:51:20 +0800
Subject: [PATCH 1/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp| 16 
 .../Analysis/Inputs/system-header-simulator.h|  1 +
 clang/test/Analysis/stream-error.c   |  9 +
 3 files changed, 26 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 925fc90e35543..2c725c01dc285 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,6 +266,7 @@ class StreamChecker : public CheckerStreamArgNo)
+   ->isNullPointerConstant(C.getASTContext(),
+   Expr::NPC_ValueDependentIsNotNull)) {
+ProgramStateRef State = C.getState();
+if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  C.addTransition(State);
+  }
+}
+
 ProgramStateRef
 StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
CheckerContext &C,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 7089bd8bfc9d9..409a969a0d4cc 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -61,6 +61,7 @@ void clearerr(FILE *stream);
 int feof(FILE *stream);
 int ferror(FILE *stream);
 int fileno(FILE *stream);
+int fflush(FILE *stream);
 
 size_t strlen(const char *);
 
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index c8332bcbfa8ca..aa5b6be851773 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -299,6 +299,15 @@ void error_fseek_0(void) {
   fclose(F);
 }
 
+void error_fflush(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  fclose(F);
+  fflush(F);// expected-warning {{Stream might be already closed}}
+  fflush(NULL); // no-warning
+}
+
 void error_indeterminate(void) {
   FILE *F = fopen("file", "r+");
   if (!F)

>From dcb766b468a2f29df30451f8f196d7a2371fd038 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 6 Dec 2023 15:47:35 +0800
Subject: [PATCH 2/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 49 ---
 clang/test/Analysis/stream-error.c| 12 +++--
 2 files changed, 51 insertions(+), 10 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 2c725c01dc285..a368619fd37d2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,7 +266,8 @@ class StreamChecker : public CheckerStreamArgNo)
-   ->isNullPointerConstant(C.getASTContext(),
-   Expr::NPC_ValueDependentIsNotNull)) {
-ProgramStateRef State = C.getState();
-if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  if (!Stream)
+return;
+
+  ConstraintManager::ProgramStatePair SP =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (State = SP.first)
+if (State = ensureStreamOpened(StreamVal, C, State))
   C.addTransition(State);
+}
+
+void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent 
&Call,
+   CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  // We will check the result even if the input is `NULL`,
+  // but do nothing if the input state is unknown.
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (StreamSym) {
+const StreamState *OldSS = State->get(StreamSym);
+if (!OldSS)
+  return;
+assertStreamStateOpened(OldSS);
   }
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  // `fflush` returns 0 on success, otherwise returns EOF.
+  ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
+  // This function does not affect the stream state.
+  // Still we add success and failure state with the appropriate return value.
+  C.addTransition(StateNotFailed);
+  C.addTransition(StateFailed);
 }
 
 ProgramStateRef
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index aa5b6be851773..94787874cf839 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -301,11 +301,17 @@ void error_fseek_0(void) {
 
 void error_fflush(void) {
 

[clang] [llvm] [ValueTracking] Add dominating condition support in computeKnownBits() (PR #73662)

2023-12-07 Thread Mikhail Goncharov via cfe-commits

metaflow wrote:

heads up - we see a much larger regression for one of the cases in TensorFlow 
(trying to confirm it)

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


[clang] [llvm] [clang][RISCV] Change default abi with f extension but without d extension (PR #73489)

2023-12-07 Thread Ben Shi via cfe-commits

benshi001 wrote:

I think this is reasonable, even I myself made such a change months ago in 
Phabracator, but finally not approved. 

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


[clang] [llvm] [clang][RISCV] Change default abi with f extension but without d extension (PR #73489)

2023-12-07 Thread Ben Shi via cfe-commits

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


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


[clang] [llvm] [libcxx] [clang-tools-extra] [FIX] Fix the function isctype failed in arm64-big-endian (PR #73200)

2023-12-07 Thread via cfe-commits


@@ -384,7 +384,7 @@ public:
 static const mask punct  = _ISpunct;
 static const mask xdigit = _ISxdigit;
 static const mask blank  = _ISblank;
-#if defined(__mips__)
+#if defined(__mips__) || (BYTE_ORDER == BIG_ENDIAN)

W-50243 wrote:

Yes, that's it. Getting the character mask on arm64be and arm64le will run this 
function`_LIBCPP_GET_C_LOCALE->__ctype_b`. The character mask obtained from 
this is dependent on the endianness of current platform. For example,  "-', 
it's character mask is 01001100 on arm64e while on arm64le is 
11000100

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


[clang] [llvm] [clang][RISCV] Change default abi with f extension but without d extension (PR #73489)

2023-12-07 Thread Wang Pengcheng via cfe-commits

wangpc-pp wrote:

As @kito-cheng has pointed out, we should fix multilib issue before landing 
this. It seems we don't generate multilib for ilp32f and lp64f in 
riscv-gnu-toolchain?

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


[clang] b499466 - [Driver][MachineOutliner] Support -moutline option for aarch64_be (#73223)

2023-12-07 Thread via cfe-commits

Author: dong jianqiang
Date: 2023-12-07T16:47:41+08:00
New Revision: b499466361b6a27fad873431a9b7e529e39e73e6

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

LOG: [Driver][MachineOutliner] Support -moutline option for aarch64_be (#73223)

This patch propagates the -moutline flag when target is aarch64_be, 
fix warning: 'aarch64_be' does not support '-moutline'; flag ignored
[-Woption-ignored]

Added: 


Modified: 
clang/lib/Driver/ToolChains/CommonArgs.cpp
clang/test/Driver/aarch64-outliner.c

Removed: 




diff  --git a/clang/lib/Driver/ToolChains/CommonArgs.cpp 
b/clang/lib/Driver/ToolChains/CommonArgs.cpp
index 0ae8e2dce32e9..51b336216c565 100644
--- a/clang/lib/Driver/ToolChains/CommonArgs.cpp
+++ b/clang/lib/Driver/ToolChains/CommonArgs.cpp
@@ -2583,9 +2583,7 @@ void tools::addMachineOutlinerArgs(const Driver &D,
   // We only support -moutline in AArch64 and ARM targets right now. If
   // we're not compiling for these, emit a warning and ignore the flag.
   // Otherwise, add the proper mllvm flags.
-  if (!(Triple.isARM() || Triple.isThumb() ||
-Triple.getArch() == llvm::Triple::aarch64 ||
-Triple.getArch() == llvm::Triple::aarch64_32)) {
+  if (!(Triple.isARM() || Triple.isThumb() || Triple.isAArch64())) {
 D.Diag(diag::warn_drv_moutline_unsupported_opt) << 
Triple.getArchName();
   } else {
 addArg(Twine("-enable-machine-outliner"));

diff  --git a/clang/test/Driver/aarch64-outliner.c 
b/clang/test/Driver/aarch64-outliner.c
index 42e43b433e282..06e5de11ec49e 100644
--- a/clang/test/Driver/aarch64-outliner.c
+++ b/clang/test/Driver/aarch64-outliner.c
@@ -1,7 +1,9 @@
 // REQUIRES: aarch64-registered-target
 // RUN: %clang --target=aarch64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
+// RUN: %clang --target=aarch64_be -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=ON
 // ON: "-mllvm" "-enable-machine-outliner"
 // RUN: %clang --target=aarch64 -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
+// RUN: %clang --target=aarch64_be -moutline -mno-outline -S %s -### 2>&1 | 
FileCheck %s -check-prefix=OFF
 // OFF: "-mllvm" "-enable-machine-outliner=never"
 // RUN: %clang --target=x86_64 -moutline -S %s -### 2>&1 | FileCheck %s 
-check-prefix=WARN
 // WARN: warning: 'x86_64' does not support '-moutline'; flag ignored 
[-Woption-ignored]



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


[clang] [Driver][MachineOutliner] Support -moutline option for aarch64_be (PR #73223)

2023-12-07 Thread via cfe-commits

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


[clang] [flang] [flang][driver] Add -fno-fortran-main (link time) option to remove Fortran_main from link line (PR #74139)

2023-12-07 Thread Andrzej Warzyński via cfe-commits

https://github.com/banach-space commented:

Thanks for pushing on!

I've made one small suggestion and I also have one more request for the 
summary. I know that you added links to relevant PRs, but I would still 
appreciate if the summary (and the commit msg) where self-contained and 
included the justification for this new flag. You could use the example by 
@tblah to show where the flag might be needed. Please do keep the links :) 

I think that it would also be helpful to include what could be an alternative 
to this and that wouldn't require a flag - I think that the only option would 
be to mimic what Classic Flang does?

I know that it's extra work, but it's also super useful bit of documentation. 
And I would only rarely try to track the history beyond commit messages 
(there's just too much otherwise). 

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


[flang] [clang] [flang][driver] Add -fno-fortran-main (link time) option to remove Fortran_main from link line (PR #74139)

2023-12-07 Thread Andrzej Warzyński via cfe-commits

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


[flang] [clang] [flang][driver] Add -fno-fortran-main (link time) option to remove Fortran_main from link line (PR #74139)

2023-12-07 Thread Andrzej Warzyński via cfe-commits


@@ -6345,6 +6345,10 @@ def J : JoinedOrSeparate<["-"], "J">,
   Group,
   Alias;
 
+def no_fortran_main : Flag<["-"], "fno-fortran-main">,
+  Visibility<[FlangOption]>, Group,
+  HelpText<"Don't link in Fortran main">;
+

banach-space wrote:

```suggestion
def J : JoinedOrSeparate<["-"], "J">,
  Flags<[RenderJoined]>, Visibility<[FlangOption, FC1Option]>,
  Group,
  Alias;
  
} // let Visibility = [FC1Option, FlangOption]
//===--===//
// FLang Options
//===--===//
let Visibility = [FlangOption] in {
def no_fortran_main : Flag<["-"], "fno-fortran-main">,
  Visibility<[FlangOption]>, Group,
  HelpText<"Don't link in Fortran main">;
}
} // let Visibility = [ FlangOption]
```

I hope this suggestion is clear - sadly GitHub is not allowing me to make a 
proper suggestion for the code above of what you added. 

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


[llvm] [clang] [clang-tools-extra] [LoopVectorize] Improve algorithm for hoisting runtime checks (PR #73515)

2023-12-07 Thread David Sherwood via cfe-commits

david-arm wrote:

Gentle ping!

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


[clang] b768b39 - [C++20] [Modules] Skip Writing diagnostic options, header search paths and pragma diagnostic mappings

2023-12-07 Thread Chuanqi Xu via cfe-commits

Author: Chuanqi Xu
Date: 2023-12-07T16:54:00+08:00
New Revision: b768b393429419d27e3f76518842136bac9d5b25

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

LOG: [C++20] [Modules] Skip Writing diagnostic options, header search paths and 
pragma diagnostic mappings

It simply wastes of space and time to write diagnostic options, header
search paths and pragma diagnostic mappings for C++20 Named modules.
This patch tries to avoid the unnecessary writings.

Added: 


Modified: 
clang/include/clang/Frontend/FrontendActions.h
clang/lib/Frontend/FrontendActions.cpp

Removed: 




diff  --git a/clang/include/clang/Frontend/FrontendActions.h 
b/clang/include/clang/Frontend/FrontendActions.h
index 3940e00eeb8db..fcce31ac0590f 100644
--- a/clang/include/clang/Frontend/FrontendActions.h
+++ b/clang/include/clang/Frontend/FrontendActions.h
@@ -151,6 +151,9 @@ class GenerateModuleInterfaceAction : public 
GenerateModuleAction {
 private:
   bool BeginSourceFileAction(CompilerInstance &CI) override;
 
+  std::unique_ptr CreateASTConsumer(CompilerInstance &CI,
+ StringRef InFile) override;
+
   std::unique_ptr
   CreateOutputFile(CompilerInstance &CI, StringRef InFile) override;
 };

diff  --git a/clang/lib/Frontend/FrontendActions.cpp 
b/clang/lib/Frontend/FrontendActions.cpp
index 2afcf1cf9f68c..c1d6e71455365 100644
--- a/clang/lib/Frontend/FrontendActions.cpp
+++ b/clang/lib/Frontend/FrontendActions.cpp
@@ -258,6 +258,16 @@ bool GenerateModuleInterfaceAction::BeginSourceFileAction(
   return GenerateModuleAction::BeginSourceFileAction(CI);
 }
 
+std::unique_ptr
+GenerateModuleInterfaceAction::CreateASTConsumer(CompilerInstance &CI,
+ StringRef InFile) {
+  CI.getHeaderSearchOpts().ModulesSkipDiagnosticOptions = true;
+  CI.getHeaderSearchOpts().ModulesSkipHeaderSearchPaths = true;
+  CI.getHeaderSearchOpts().ModulesSkipPragmaDiagnosticMappings = true;
+
+  return GenerateModuleAction::CreateASTConsumer(CI, InFile);
+}
+
 std::unique_ptr
 GenerateModuleInterfaceAction::CreateOutputFile(CompilerInstance &CI,
 StringRef InFile) {



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


[clang] [clang] Stub out gcc_struct attribute (PR #71148)

2023-12-07 Thread Dan Klishch via cfe-commits

DanShaders wrote:

@rjmccall
The problem will arise only if GCC implements support for MSVC C++ ABI and 
decides that there is a better way to implement `gcc_struct`. Since, AFAIC, 
MSVC-compatibility for GCC is not even planned, it's unlikely anybody there 
will have strong opinions on this. Yet I posted a question on gcc mailing list 
(https://gcc.gnu.org/pipermail/gcc/2023-December/242963.html) and, 
unsurprisingly, got no replies in a week.

At the same time, I agree that inventing behavior for attributes in gnu:: 
namespace feels wrong. So, what do think about putting gcc_struct into 
`clang::` and disallowing `__attribute__((gcc_struct))`? Looks like this would 
require minimal changes:
```diff
@@ -3672,7 +3672,7 @@ def MSStruct : InheritableAttr {
 }
 
 def GCCStruct : InheritableAttr {
-  let Spellings = [GCC<"gcc_struct">];
+  let Spellings = [CXX11<"clang", "gcc_struct">, C23<"clang", "gcc_struct">];
   let Subjects = SubjectList<[Record]>;
   let Documentation = [MSStructDocs]; // Covers this attribute too.
   let SimpleHandler = 1;
```

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


[clang] [flang] [llvm] [NFC][AMDGPU] Move address space enum to LLVM directory (PR #73944)

2023-12-07 Thread Dominik Adamski via cfe-commits


@@ -0,0 +1,31 @@
+//=== AMDGPUAddrSpace.h -*- 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
+//
+//===--===//
+//
+/// \file
+/// AMDGPU address space definition
+///
+//
+//===--===//
+
+#ifndef LLVM_SUPPORT_AMDGPUADDRSPACE_H
+#define LLVM_SUPPORT_AMDGPUADDRSPACE_H
+
+namespace llvm {
+namespace AMDGPU {
+enum class AddrSpace {

DominikAdamski wrote:

@arsenm I can consolidate these enums but I would like to be sure that I am 
allowed to do it. I was not sure why Clang enum has smaller range in comparison 
to LLVM enum.
My initial aim of this patch was to perform minimal code refactoring so that 
Clang and Flang can reuse the same enum. If you wish I can consolidate Flang, 
Clang and LLVM enums.

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


[clang] [flang] [llvm] [NFC][AMDGPU] Move address space enum to LLVM directory (PR #73944)

2023-12-07 Thread Matt Arsenault via cfe-commits


@@ -0,0 +1,31 @@
+//=== AMDGPUAddrSpace.h -*- 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
+//
+//===--===//
+//
+/// \file
+/// AMDGPU address space definition
+///
+//
+//===--===//
+
+#ifndef LLVM_SUPPORT_AMDGPUADDRSPACE_H
+#define LLVM_SUPPORT_AMDGPUADDRSPACE_H
+
+namespace llvm {
+namespace AMDGPU {
+enum class AddrSpace {

arsenm wrote:

The clang enum is very OpenCL centric and ignores AMDGPU and graphics specific 
address spaces. I don't see a point in keeping two overlapping enums 

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


[libcxxabi] [flang] [clang-tools-extra] [libcxx] [lldb] [clang] [llvm] [compiler-rt] [lld] [AMDGPU] GFX12: select @llvm.prefetch intrinsic (PR #74576)

2023-12-07 Thread Mariusz Sikora via cfe-commits

https://github.com/mariusz-sikora-at-amd updated 
https://github.com/llvm/llvm-project/pull/74576

>From 23759746b66c33028ad2340b1e98067ebf1f8074 Mon Sep 17 00:00:00 2001
From: Stanislav Mekhanoshin 
Date: Tue, 28 Jun 2022 15:24:24 -0700
Subject: [PATCH] [AMDGPU] GFX12: select @llvm.prefetch intrinsic

---
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  21 +
 llvm/lib/Target/AMDGPU/GCNSubtarget.h |   2 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  22 +
 llvm/lib/Target/AMDGPU/SIISelLowering.h   |   2 +
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp|   2 +
 llvm/lib/Target/AMDGPU/SIInstructions.td  |  12 +
 llvm/lib/Target/AMDGPU/SMInstructions.td  |  34 ++
 llvm/test/CodeGen/AMDGPU/llvm.prefetch.ll | 496 ++
 8 files changed, 591 insertions(+)
 create mode 100644 llvm/test/CodeGen/AMDGPU/llvm.prefetch.ll

diff --git a/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
index 62996a3b3fb79..f0b3ed7adc294 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
@@ -3101,6 +3101,24 @@ void AMDGPURegisterBankInfo::applyMappingImpl(
   applyDefaultMapping(OpdMapper);
   constrainOpWithReadfirstlane(B, MI, 8); // M0
   return;
+case Intrinsic::prefetch: {
+  if (!Subtarget.hasPrefetch()) {
+MI.eraseFromParent();
+return;
+  }
+  unsigned PtrBank =
+  getRegBankID(MI.getOperand(1).getReg(), MRI, AMDGPU::SGPRRegBankID);
+  if (PtrBank == AMDGPU::VGPRRegBankID) {
+MI.eraseFromParent();
+return;
+  }
+  // FIXME: There is currently no support for prefetch in global isel.
+  // There is no node equivalence and what's worse there is no MMO produced
+  // for a prefetch on global isel path.
+  // Prefetch does not affect execution so erase it for now.
+  MI.eraseFromParent();
+  return;
+}
 default: {
   if (const AMDGPU::RsrcIntrinsic *RSrcIntrin =
   AMDGPU::lookupRsrcIntrinsic(IntrID)) {
@@ -4830,6 +4848,9 @@ AMDGPURegisterBankInfo::getInstrMapping(const 
MachineInstr &MI) const {
   getVGPROpMapping(MI.getOperand(5).getReg(), MRI, *TRI); // %data1
   break;
 }
+case Intrinsic::prefetch:
+  OpdsMapping[1] = getSGPROpMapping(MI.getOperand(1).getReg(), MRI, *TRI);
+  break;
 
 default:
   return getInvalidInstructionMapping();
diff --git a/llvm/lib/Target/AMDGPU/GCNSubtarget.h 
b/llvm/lib/Target/AMDGPU/GCNSubtarget.h
index 94b9e49b765a6..21a9b8147034f 100644
--- a/llvm/lib/Target/AMDGPU/GCNSubtarget.h
+++ b/llvm/lib/Target/AMDGPU/GCNSubtarget.h
@@ -828,6 +828,8 @@ class GCNSubtarget final : public AMDGPUGenSubtargetInfo,
 
   bool hasInstPrefetch() const { return getGeneration() >= GFX10; }
 
+  bool hasPrefetch() const { return GFX12Insts; }
+
   // Scratch is allocated in 256 dword per wave blocks for the entire
   // wavefront. When viewed from the perspective of an arbitrary workitem, this
   // is 4-byte aligned.
diff --git a/llvm/lib/Target/AMDGPU/SIISelLowering.cpp 
b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
index a7f4d63229b7e..93af38d877c5d 100644
--- a/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
+++ b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
@@ -763,6 +763,9 @@ SITargetLowering::SITargetLowering(const TargetMachine &TM,
   if (Subtarget->hasMad64_32())
 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
 
+  if (Subtarget->hasPrefetch())
+setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
+
   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
  {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
   MVT::v2i16, MVT::v2f16, MVT::i128},
@@ -3858,6 +3861,23 @@ SDValue SITargetLowering::lowerGET_ROUNDING(SDValue Op,
   return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
 }
 
+SDValue SITargetLowering::lowerPREFETCH(SDValue Op, SelectionDAG &DAG) const {
+  if (Op->isDivergent())
+return SDValue();
+
+  switch (cast(Op)->getAddressSpace()) {
+  case AMDGPUAS::FLAT_ADDRESS:
+  case AMDGPUAS::GLOBAL_ADDRESS:
+  case AMDGPUAS::CONSTANT_ADDRESS:
+  case AMDGPUAS::CONSTANT_ADDRESS_32BIT:
+break;
+  default:
+return SDValue();
+  }
+
+  return Op;
+}
+
 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
  const MachineFunction &MF) const {
   Register Reg = StringSwitch(RegName)
@@ -5395,6 +5415,8 @@ SDValue SITargetLowering::LowerOperation(SDValue Op, 
SelectionDAG &DAG) const {
 return LowerSTACKSAVE(Op, DAG);
   case ISD::GET_ROUNDING:
 return lowerGET_ROUNDING(Op, DAG);
+  case ISD::PREFETCH:
+return lowerPREFETCH(Op, DAG);
   }
   return SDValue();
 }
diff --git a/llvm/lib/Target/AMDGPU/SIISelLowering.h 
b/llvm/lib/Target/AMDGPU/SIISelLowering.h
index c9cc149218a99..5bc091d6e84de 100644
--- a/llvm/lib/Target/AMDGPU/SIISelLowering.h

[libcxxabi] [flang] [clang-tools-extra] [libcxx] [lldb] [clang] [llvm] [compiler-rt] [lld] [AMDGPU] GFX12: select @llvm.prefetch intrinsic (PR #74576)

2023-12-07 Thread Matt Arsenault via cfe-commits


@@ -959,6 +967,32 @@ def : GCNPat <
 }
 } // let OtherPredicates = [HasShaderCyclesRegister]
 
+def SIMM24bitPtr : ImmLeaf (Imm);}]
+>;
+
+multiclass SMPrefetchPat {
+  def : GCNPat <
+(smrd_prefetch (SMRDImm i64:$sbase, i32:$offset), timm, timm, (i32 
cache_type)),
+(!cast("S_PREFETCH_"#type) $sbase, $offset, (i32 
SGPR_NULL), (i8 0))
+  >;
+
+  def : GCNPat <
+(smrd_prefetch (i64 SReg_64:$sbase), timm, timm, (i32 cache_type)),
+(!cast("S_PREFETCH_"#type) $sbase, 0, (i32 SGPR_NULL), 
(i8 0))
+  >;
+
+  def : GCNPat <
+(prefetch SIMM24bitPtr:$offset, timm, timm, (i32 cache_type)),
+(!cast("S_PREFETCH_"#type#"_PC_REL") (as_i32timm 
$offset), (i32 SGPR_NULL), (i8 0))
+  > {
+let AddedComplexity = 10;
+  }

arsenm wrote:

I would interpret this as using the absolute address, you would need something 
else to represent a PC relative input 

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


[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits

https://github.com/david-arm updated 
https://github.com/llvm/llvm-project/pull/73326

>From af76f6b6b3469fd0f5f24427c5a175c8d9d7c83a Mon Sep 17 00:00:00 2001
From: David Sherwood 
Date: Fri, 24 Nov 2023 13:20:23 +
Subject: [PATCH 1/3] [Clang] Emit TBAA info for enums in C

When emitting TBAA information for enums in C code we
currently just treat the data as an 'omnipotent char'.
However, with C strict aliasing this means we fail to
optimise certain cases. For example, in the SPEC2017
xz benchmark there are structs that contain arrays of
enums, and clang pessmistically assumes that accesses
to those enums could alias with other struct members
that have a different type.

According to

https://en.cppreference.com/w/c/language/enum

enums should be treated as 'int' types unless
explicitly specified (C23) or if 'int' would not be
large enough to hold all the enumerated values. In the
latter case the compiler is free to choose a suitable
integer that would hold all such values.

When compiling C code this patch generates TBAA
information for the enum by using an equivalent integer
of the size clang has already chosen for the enum. I
have ignored C++ for now because the rules are more
complex.

New test added here:

  clang/test/CodeGen/tbaa.c
---
 clang/lib/CodeGen/CodeGenTBAA.cpp |   5 +-
 clang/test/CodeGen/tbaa.c | 116 ++
 2 files changed, 120 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/tbaa.c

diff --git a/clang/lib/CodeGen/CodeGenTBAA.cpp 
b/clang/lib/CodeGen/CodeGenTBAA.cpp
index 8705d3d65f1a5..f59d3d422d520 100644
--- a/clang/lib/CodeGen/CodeGenTBAA.cpp
+++ b/clang/lib/CodeGen/CodeGenTBAA.cpp
@@ -196,11 +196,14 @@ llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type 
*Ty) {
   // Enum types are distinct types. In C++ they have "underlying types",
   // however they aren't related for TBAA.
   if (const EnumType *ETy = dyn_cast(Ty)) {
+if (!Features.CPlusPlus)
+  return getTypeInfo(Context.getIntTypeForBitwidth(Size * 8, 0));
+
 // In C++ mode, types have linkage, so we can rely on the ODR and
 // on their mangled names, if they're external.
 // TODO: Is there a way to get a program-wide unique name for a
 // decl with local linkage or no linkage?
-if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
+if (!ETy->getDecl()->isExternallyVisible())
   return getChar();
 
 SmallString<256> OutName;
diff --git a/clang/test/CodeGen/tbaa.c b/clang/test/CodeGen/tbaa.c
new file mode 100644
index 0..0ab81f60a7194
--- /dev/null
+++ b/clang/test/CodeGen/tbaa.c
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -no-struct-path-tbaa 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefixes=PATH
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O0 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -relaxed-aliasing 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// Test TBAA metadata generated by front-end.
+//
+// NO-TBAA-NOT: !tbaa
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+
+typedef enum {
+  RED_AUTO_32,
+  GREEN_AUTO_32,
+  BLUE_AUTO_32
+} EnumAuto32;
+
+typedef enum {
+  RED_AUTO_64,
+  GREEN_AUTO_64,
+  BLUE_AUTO_64 = 0x1ull
+} EnumAuto64;
+
+typedef enum : uint16_t {
+  RED_16,
+  GREEN_16,
+  BLUE_16
+} Enum16;
+
+typedef enum : uint8_t {
+  RED_8,
+  GREEN_8,
+  BLUE_8
+} Enum8;
+
+uint32_t g0(EnumAuto32 *E, uint32_t *val) {
+// CHECK-LABEL: define{{.*}} i32 @g0(
+// CHECK: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// CHECK: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// CHECK: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH-LABEL: define{{.*}} i32 @g0(
+// PATH: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// PATH: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+  *val = 5;
+  *E = RED_AUTO_32;
+  return *val;
+}
+
+uint64_t g1(EnumAuto64 *E, uint64_t *val) {
+// CHECK-LABEL: define{{.*}} i64 @g1(
+// CHECK: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// CHECK: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// CHECK: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+// PATH-LABEL: define{{.*}} i64 @g1(
+// PATH: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// PATH: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// PATH: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+  *val = 5;
+  *E = RED_AUTO_64;
+  return *val;
+}
+
+uint16_t g2(Enum16 *E, uint16_t *val) {
+// CHECK-LABEL: define{{.*}} i16 @g2(
+// CHECK: store i16 5, ptr %{{.*}}, align 2, !tbaa [[TAG_i16:!.

[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits

david-arm wrote:

> Do you think it's worth adding something to the Clang release note?

Done. Hope the documentation I added makes sense!

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


[flang] [clang] [libcxxabi] [lld] [lldb] [mlir] [llvm] [clang-tools-extra] [openmp] [compiler-rt] [libcxx] [AMDGPU] Add GFX12 encoding for VINTERP instructions (PR #74616)

2023-12-07 Thread Jay Foad via cfe-commits

https://github.com/jayfoad updated 
https://github.com/llvm/llvm-project/pull/74616

>From 69580e5f77514fecf0aabe2a80c98881f9bd7288 Mon Sep 17 00:00:00 2001
From: Jay Foad 
Date: Tue, 7 Feb 2023 16:27:27 +
Subject: [PATCH 1/2] [AMDGPU] Add GFX12 encoding for VINTERP instructions

---
 .../Disassembler/AMDGPUDisassembler.cpp   |   6 +-
 llvm/lib/Target/AMDGPU/VINTERPInstructions.td |  38 ++-
 llvm/test/MC/AMDGPU/gfx11_asm_vinterp.s   | 187 ++---
 .../AMDGPU/gfx12_dasm_vinterp.txt | 251 ++
 4 files changed, 378 insertions(+), 104 deletions(-)
 create mode 100644 llvm/test/MC/Disassembler/AMDGPU/gfx12_dasm_vinterp.txt

diff --git a/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp 
b/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
index 3175f6358a045..c37af739e2019 100644
--- a/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
+++ b/llvm/lib/Target/AMDGPU/Disassembler/AMDGPUDisassembler.cpp
@@ -782,9 +782,13 @@ DecodeStatus AMDGPUDisassembler::convertEXPInst(MCInst 
&MI) const {
 
 DecodeStatus AMDGPUDisassembler::convertVINTERPInst(MCInst &MI) const {
   if (MI.getOpcode() == AMDGPU::V_INTERP_P10_F16_F32_inreg_gfx11 ||
+  MI.getOpcode() == AMDGPU::V_INTERP_P10_F16_F32_inreg_gfx12 ||
   MI.getOpcode() == AMDGPU::V_INTERP_P10_RTZ_F16_F32_inreg_gfx11 ||
+  MI.getOpcode() == AMDGPU::V_INTERP_P10_RTZ_F16_F32_inreg_gfx12 ||
   MI.getOpcode() == AMDGPU::V_INTERP_P2_F16_F32_inreg_gfx11 ||
-  MI.getOpcode() == AMDGPU::V_INTERP_P2_RTZ_F16_F32_inreg_gfx11) {
+  MI.getOpcode() == AMDGPU::V_INTERP_P2_F16_F32_inreg_gfx12 ||
+  MI.getOpcode() == AMDGPU::V_INTERP_P2_RTZ_F16_F32_inreg_gfx11 ||
+  MI.getOpcode() == AMDGPU::V_INTERP_P2_RTZ_F16_F32_inreg_gfx12) {
 // The MCInst has this field that is not directly encoded in the
 // instruction.
 insertNamedMCOperand(MI, MCOperand::createImm(0), AMDGPU::OpName::op_sel);
diff --git a/llvm/lib/Target/AMDGPU/VINTERPInstructions.td 
b/llvm/lib/Target/AMDGPU/VINTERPInstructions.td
index 7d03150bf5b11..fc563b7493adf 100644
--- a/llvm/lib/Target/AMDGPU/VINTERPInstructions.td
+++ b/llvm/lib/Target/AMDGPU/VINTERPInstructions.td
@@ -10,7 +10,7 @@
 // VINTERP encoding
 
//===--===//
 
-class VINTERPe_gfx11  op, VOPProfile P> : Enc64 {
+class VINTERPe  : Enc64 {
   bits<8> vdst;
   bits<4> src0_modifiers;
   bits<9> src0;
@@ -31,7 +31,6 @@ class VINTERPe_gfx11  op, VOPProfile P> : Enc64 {
   let Inst{13}= !if(P.HasOpSel, src2_modifiers{2}, 0); // op_sel(2)
   let Inst{14}= !if(P.HasOpSel, src0_modifiers{3}, 0); // op_sel(3)
   let Inst{15}= clamp;
-  let Inst{22-16} = op;
   let Inst{40-32} = src0;
   let Inst{49-41} = src1;
   let Inst{58-50} = src2;
@@ -40,6 +39,14 @@ class VINTERPe_gfx11  op, VOPProfile P> : Enc64 {
   let Inst{63}= src2_modifiers{0}; // neg(2)
 }
 
+class VINTERPe_gfx11  op, VOPProfile P> : VINTERPe {
+  let Inst{22-16} = op;
+}
+
+class VINTERPe_gfx12  op, VOPProfile P> : VINTERPe {
+  let Inst{20-16} = op{4-0};
+}
+
 
//===--===//
 // VOP3 VINTERP
 
//===--===//
@@ -171,17 +178,28 @@ defm : VInterpF16Pat op> {
+multiclass VINTERP_Real_gfx11  op> {
+  let AssemblerPredicate = isGFX11Only, DecoderNamespace = "GFX11" in {
 def _gfx11 :
   VINTERP_Real(NAME), SIEncodingFamily.GFX11>,
   VINTERPe_gfx11(NAME).Pfl>;
   }
 }
 
-defm V_INTERP_P10_F32_inreg  : VINTERP_Real_gfx11<0x000>;
-defm V_INTERP_P2_F32_inreg  : VINTERP_Real_gfx11<0x001>;
-defm V_INTERP_P10_F16_F32_inreg  : VINTERP_Real_gfx11<0x002>;
-defm V_INTERP_P2_F16_F32_inreg  : VINTERP_Real_gfx11<0x003>;
-defm V_INTERP_P10_RTZ_F16_F32_inreg  : VINTERP_Real_gfx11<0x004>;
-defm V_INTERP_P2_RTZ_F16_F32_inreg  : VINTERP_Real_gfx11<0x005>;
+multiclass VINTERP_Real_gfx12  op> {
+  let AssemblerPredicate = isGFX12Only, DecoderNamespace = "GFX12" in {
+def _gfx12 :
+  VINTERP_Real(NAME), SIEncodingFamily.GFX12>,
+  VINTERPe_gfx12(NAME).Pfl>;
+  }
+}
+
+multiclass VINTERP_Real_gfx11_gfx12  op> :
+  VINTERP_Real_gfx11, VINTERP_Real_gfx12;
+
+defm V_INTERP_P10_F32_inreg : VINTERP_Real_gfx11_gfx12<0x000>;
+defm V_INTERP_P2_F32_inreg : VINTERP_Real_gfx11_gfx12<0x001>;
+defm V_INTERP_P10_F16_F32_inreg : VINTERP_Real_gfx11_gfx12<0x002>;
+defm V_INTERP_P2_F16_F32_inreg : VINTERP_Real_gfx11_gfx12<0x003>;
+defm V_INTERP_P10_RTZ_F16_F32_inreg : VINTERP_Real_gfx11_gfx12<0x004>;
+defm V_INTERP_P2_RTZ_F16_F32_inreg : VINTERP_Real_gfx11_gfx12<0x005>;
diff --git a/llvm/test/MC/AMDGPU/gfx11_asm_vinterp.s 
b/llvm/test/MC/AMDGPU/gfx11_asm_vinterp.s
index e2e53776783f3..fdfbf65c0e3cf 100644
--- a/llvm/test/MC/AMDGPU/gfx11_asm_vinterp.s
+++ b/llvm/test/MC/AMDGPU/gfx11_asm_vinterp.s
@@ -1,277 +1,278 @@
-// RUN: llvm-mc -triple=amdgcn -mcpu=gfx1100 -show-encoding %s | FileCheck 
-check-p

[clang] e4c7ee3 - [analyzer][NFC] Simplify BugType handling in core.BitwiseShift (#74609)

2023-12-07 Thread via cfe-commits

Author: DonatNagyE
Date: 2023-12-07T10:23:19+01:00
New Revision: e4c7ee3c4418c1558c3a1c7337f031717ac100dd

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

LOG: [analyzer][NFC] Simplify BugType handling in core.BitwiseShift (#74609)

Eliminate the `mutable unique_ptr` hack because it's no longer needed.
(This cleanup could be done anywhere, I'm doing it here now because it
was me who published this checker with the old hack when it was already
superfluous.)

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
index d4aa9fa1339f4..339927c165fe0 100644
--- a/clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/BitwiseShiftChecker.cpp
@@ -344,7 +344,7 @@ BitwiseShiftValidator::createBugReport(StringRef ShortMsg, 
StringRef Msg) const
 } // anonymous namespace
 
 class BitwiseShiftChecker : public Checker> {
-  mutable std::unique_ptr BTPtr;
+  BugType BT{this, "Bitwise shift", "Suspicious operation"};
 
 public:
   void checkPreStmt(const BinaryOperator *B, CheckerContext &Ctx) const {
@@ -353,11 +353,7 @@ class BitwiseShiftChecker : public 
Checker> {
 if (Op != BO_Shl && Op != BO_Shr)
   return;
 
-if (!BTPtr)
-  BTPtr = std::make_unique(this, "Bitwise shift",
-"Suspicious operation");
-
-BitwiseShiftValidator(B, Ctx, *BTPtr, Pedantic).run();
+BitwiseShiftValidator(B, Ctx, BT, Pedantic).run();
   }
 
   bool Pedantic = false;



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


[clang] [analyzer][NFC] Simplify BugType handling in core.BitwiseShift (PR #74609)

2023-12-07 Thread via cfe-commits

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


[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Momchil Velikov via cfe-commits

momchil-velikov wrote:

I thought the suggestion was to add a few lines to 
https://github.com/llvm/llvm-project/blob/main/clang/docs/ReleaseNotes.rst

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


[clang] [llvm] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits

david-arm wrote:

> I thought the suggestion was to add a few lines to 
> https://github.com/llvm/llvm-project/blob/main/clang/docs/ReleaseNotes.rst

Yes you're right! For some reason I got mixed up with the LangRef, but I guess 
adding something to the LangRef does no harm either. I'll put something in the 
release notes too. :)

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


[clang] [llvm] [mlir] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Jessica Del via cfe-commits

OutOfCache wrote:

> How do you intend to rewrite these operations down to the underlying 
> instructions?
> 
> That is, what's your planned equivalent to https://reviews.llvm.org/D158463 ?

Thank you for the link to the code review, I was not aware of your changes 
before. Up until now, we intended to use the address space in llpc exclusively 
and lower the pointers to buffer load instructions in `PatchBufferOp`. If we 
also need to lower these pointers like you did for the fat buffers, maybe we 
can extend your new pass to also handle these strided buffer pointers?

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Ben Shi via cfe-commits

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

>From 65ce18117f99056aafcf58151b64f4243f4d5e26 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Mon, 4 Dec 2023 15:51:20 +0800
Subject: [PATCH 1/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp| 16 
 .../Analysis/Inputs/system-header-simulator.h|  1 +
 clang/test/Analysis/stream-error.c   |  9 +
 3 files changed, 26 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 925fc90e35543..2c725c01dc285 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,6 +266,7 @@ class StreamChecker : public CheckerStreamArgNo)
+   ->isNullPointerConstant(C.getASTContext(),
+   Expr::NPC_ValueDependentIsNotNull)) {
+ProgramStateRef State = C.getState();
+if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  C.addTransition(State);
+  }
+}
+
 ProgramStateRef
 StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
CheckerContext &C,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 7089bd8bfc9d9..409a969a0d4cc 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -61,6 +61,7 @@ void clearerr(FILE *stream);
 int feof(FILE *stream);
 int ferror(FILE *stream);
 int fileno(FILE *stream);
+int fflush(FILE *stream);
 
 size_t strlen(const char *);
 
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index c8332bcbfa8ca..aa5b6be851773 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -299,6 +299,15 @@ void error_fseek_0(void) {
   fclose(F);
 }
 
+void error_fflush(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  fclose(F);
+  fflush(F);// expected-warning {{Stream might be already closed}}
+  fflush(NULL); // no-warning
+}
+
 void error_indeterminate(void) {
   FILE *F = fopen("file", "r+");
   if (!F)

>From dcb766b468a2f29df30451f8f196d7a2371fd038 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 6 Dec 2023 15:47:35 +0800
Subject: [PATCH 2/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 49 ---
 clang/test/Analysis/stream-error.c| 12 +++--
 2 files changed, 51 insertions(+), 10 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 2c725c01dc285..a368619fd37d2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,7 +266,8 @@ class StreamChecker : public CheckerStreamArgNo)
-   ->isNullPointerConstant(C.getASTContext(),
-   Expr::NPC_ValueDependentIsNotNull)) {
-ProgramStateRef State = C.getState();
-if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  if (!Stream)
+return;
+
+  ConstraintManager::ProgramStatePair SP =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (State = SP.first)
+if (State = ensureStreamOpened(StreamVal, C, State))
   C.addTransition(State);
+}
+
+void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent 
&Call,
+   CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  // We will check the result even if the input is `NULL`,
+  // but do nothing if the input state is unknown.
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (StreamSym) {
+const StreamState *OldSS = State->get(StreamSym);
+if (!OldSS)
+  return;
+assertStreamStateOpened(OldSS);
   }
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  // `fflush` returns 0 on success, otherwise returns EOF.
+  ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
+  // This function does not affect the stream state.
+  // Still we add success and failure state with the appropriate return value.
+  C.addTransition(StateNotFailed);
+  C.addTransition(StateFailed);
 }
 
 ProgramStateRef
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index aa5b6be851773..94787874cf839 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -301,11 +301,17 @@ void error_fseek_0(void) {
 
 void error_fflush(void) {
 

[mlir] [clang] [llvm] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits

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


[clang] [llvm] [mlir] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits

https://github.com/nhaehnle commented:

Thanks!

Since the plan for now is to have the lowering in LLPC, it's unclear to me how 
many of the codegen-related changes we actually want in here, though I suppose 
they don't hurt.

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


[clang] [llvm] [mlir] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits


@@ -864,6 +865,17 @@ supported for the ``amdgcn`` target.
   (bits `127:96`). The specific interpretation of these fields varies by the
   target architecture and is detailed in the ISA descriptions.
 
+**Buffer Strided Pointer**
+  The buffer index pointer is an experimental address space. It is supposed to
+  model a 128-bit buffer descriptor and a 32-bit offset, like the **Buffer Fat
+  Pointer**. Additionally, it contains an index into the descriptor, which
+  allows the direct addressing of structured elements.
+
+  The buffer descriptor must be *raw*:
+  the stride is the size of a structured element, the "add tid" flag must be 
0, the
+  swizzle eneable bits must be off, and the extent (NumRecords) must be 
measured in

nhaehnle wrote:

Typo: enable

Also, drop the part about the extent (NumRecords) -- that's not a requirement 
of the compiler, it's a requirement of the HW and should be implied by stating 
that the buffer descriptor is "raw". (And it is also incorrect on IIRC gfx8, 
which had NUM_RECORDS always in units of bytes)

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


[mlir] [clang] [llvm] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits


@@ -1,7 +1,7 @@
 ; RUN: opt -S -mtriple=amdgcn-- -passes=load-store-vectorizer < %s | FileCheck 
-check-prefix=OPT %s

nhaehnle wrote:

I think it's fine. It's still a kind of buffer fat pointer in a sense.

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


[mlir] [clang] [llvm] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits


@@ -864,6 +865,17 @@ supported for the ``amdgcn`` target.
   (bits `127:96`). The specific interpretation of these fields varies by the
   target architecture and is detailed in the ISA descriptions.
 
+**Buffer Strided Pointer**
+  The buffer index pointer is an experimental address space. It is supposed to
+  model a 128-bit buffer descriptor and a 32-bit offset, like the **Buffer Fat
+  Pointer**. Additionally, it contains an index into the descriptor, which

nhaehnle wrote:

index into the **buffer**

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


[llvm] [mlir] [clang] [AMDGPU] - Add address space for strided buffers (PR #74471)

2023-12-07 Thread Nicolai Hähnle via cfe-commits


@@ -864,6 +865,17 @@ supported for the ``amdgcn`` target.
   (bits `127:96`). The specific interpretation of these fields varies by the
   target architecture and is detailed in the ISA descriptions.
 
+**Buffer Strided Pointer**
+  The buffer index pointer is an experimental address space. It is supposed to
+  model a 128-bit buffer descriptor and a 32-bit offset, like the **Buffer Fat
+  Pointer**. Additionally, it contains an index into the descriptor, which
+  allows the direct addressing of structured elements.
+
+  The buffer descriptor must be *raw*:

nhaehnle wrote:

It's the same language as for addrspace 7, and I think it makes sense: it's the 
raw bits as expected by the hardware.

I recall that the buffer intrinsics have a `swz` bit in their flags -- probably 
due to some HW issue at some point? I don't remember the details.

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


[clang] [clang][dataflow] Convert `SpecialBoolAnalysis` to synthetic fields. (PR #74706)

2023-12-07 Thread via cfe-commits

https://github.com/martinboehme created 
https://github.com/llvm/llvm-project/pull/74706

We're working towards eliminating `RecordValue`; this eliminates one more
blocker on that path.


>From 064a3b51400e158aeb074a1e6db8fbfd2b011949 Mon Sep 17 00:00:00 2001
From: Martin Braenne 
Date: Thu, 7 Dec 2023 09:48:15 +
Subject: [PATCH] [clang][dataflow] Convert `SpecialBoolAnalysis` to synthetic
 fields.

We're working towards eliminating `RecordValue`; this eliminates one more
blocker on that path.
---
 .../TypeErasedDataflowAnalysisTest.cpp| 78 +--
 1 file changed, 20 insertions(+), 58 deletions(-)

diff --git 
a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
index f92afd8c3d84a..4c3cb322eacfb 100644
--- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -514,8 +514,17 @@ TEST_F(NoreturnDestructorTest, 
ConditionalOperatorNestedBranchReturns) {
 class SpecialBoolAnalysis final
 : public DataflowAnalysis {
 public:
-  explicit SpecialBoolAnalysis(ASTContext &Context)
-  : DataflowAnalysis(Context) {}
+  explicit SpecialBoolAnalysis(ASTContext &Context, Environment &Env)
+  : DataflowAnalysis(Context) {
+Env.getDataflowAnalysisContext().setSyntheticFieldCallback(
+[](QualType Ty) -> llvm::StringMap {
+  RecordDecl *RD = Ty->getAsRecordDecl();
+  if (RD == nullptr || RD->getIdentifier() == nullptr ||
+  RD->getName() != "SpecialBool")
+return {};
+  return {{"is_set", RD->getASTContext().BoolTy}};
+});
+  }
 
   static NoopLattice initialElement() { return {}; }
 
@@ -530,67 +539,18 @@ class SpecialBoolAnalysis final
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), 
*S,
   getASTContext( {
-  cast(Env.getValue(*E))
-  ->setProperty("is_set", Env.getBoolLiteralValue(false));
+  Env.setValue(Env.getResultObjectLocation(*E).getSyntheticField("is_set"),
+   Env.getBoolLiteralValue(false));
 } else if (const auto *E = selectFirst(
"call", 
match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(

SpecialBoolRecordDecl
  .bind("call"),
  *S, getASTContext( {
-  auto &ObjectLoc =
-  *cast(getImplicitObjectLocation(*E, Env));
-
-  refreshRecordValue(ObjectLoc, Env)
-  .setProperty("is_set", Env.getBoolLiteralValue(true));
+  if (RecordStorageLocation *ObjectLoc = getImplicitObjectLocation(*E, 
Env))
+Env.setValue(ObjectLoc->getSyntheticField("is_set"),
+ Env.getBoolLiteralValue(true));
 }
   }
-
-  ComparisonResult compare(QualType Type, const Value &Val1,
-   const Environment &Env1, const Value &Val2,
-   const Environment &Env2) override {
-const auto *Decl = Type->getAsCXXRecordDecl();
-if (Decl == nullptr || Decl->getIdentifier() == nullptr ||
-Decl->getName() != "SpecialBool")
-  return ComparisonResult::Unknown;
-
-auto *IsSet1 = cast_or_null(Val1.getProperty("is_set"));
-auto *IsSet2 = cast_or_null(Val2.getProperty("is_set"));
-if (IsSet1 == nullptr)
-  return IsSet2 == nullptr ? ComparisonResult::Same
-   : ComparisonResult::Different;
-
-if (IsSet2 == nullptr)
-  return ComparisonResult::Different;
-
-return Env1.proves(IsSet1->formula()) == Env2.proves(IsSet2->formula())
-   ? ComparisonResult::Same
-   : ComparisonResult::Different;
-  }
-
-  // Always returns `true` to accept the `MergedVal`.
-  bool merge(QualType Type, const Value &Val1, const Environment &Env1,
- const Value &Val2, const Environment &Env2, Value &MergedVal,
- Environment &MergedEnv) override {
-const auto *Decl = Type->getAsCXXRecordDecl();
-if (Decl == nullptr || Decl->getIdentifier() == nullptr ||
-Decl->getName() != "SpecialBool")
-  return true;
-
-auto *IsSet1 = cast_or_null(Val1.getProperty("is_set"));
-if (IsSet1 == nullptr)
-  return true;
-
-auto *IsSet2 = cast_or_null(Val2.getProperty("is_set"));
-if (IsSet2 == nullptr)
-  return true;
-
-auto &IsSet = MergedEnv.makeAtomicBoolValue();
-MergedVal.setProperty("is_set", IsSet);
-if (Env1.proves(IsSet1->formula()) && Env2.proves(IsSet2->formula()))
-  MergedEnv.assume(IsSet.formula());
-
-return true;
-  }
 };
 
 class JoinFlowConditionsTest : public Test {
@@ -602,7 +562,7 @@ class JoinFlowConditionsTest : public Test {
 AnalysisInputs(
 Code, ast_matchers::hasName("target")

[clang] [clang][dataflow] Convert `SpecialBoolAnalysis` to synthetic fields. (PR #74706)

2023-12-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clang

Author: None (martinboehme)


Changes

We're working towards eliminating `RecordValue`; this eliminates one more
blocker on that path.


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


1 Files Affected:

- (modified) 
clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp 
(+20-58) 


``diff
diff --git 
a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp 
b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
index f92afd8c3d84a..4c3cb322eacfb 100644
--- a/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
+++ b/clang/unittests/Analysis/FlowSensitive/TypeErasedDataflowAnalysisTest.cpp
@@ -514,8 +514,17 @@ TEST_F(NoreturnDestructorTest, 
ConditionalOperatorNestedBranchReturns) {
 class SpecialBoolAnalysis final
 : public DataflowAnalysis {
 public:
-  explicit SpecialBoolAnalysis(ASTContext &Context)
-  : DataflowAnalysis(Context) {}
+  explicit SpecialBoolAnalysis(ASTContext &Context, Environment &Env)
+  : DataflowAnalysis(Context) {
+Env.getDataflowAnalysisContext().setSyntheticFieldCallback(
+[](QualType Ty) -> llvm::StringMap {
+  RecordDecl *RD = Ty->getAsRecordDecl();
+  if (RD == nullptr || RD->getIdentifier() == nullptr ||
+  RD->getName() != "SpecialBool")
+return {};
+  return {{"is_set", RD->getASTContext().BoolTy}};
+});
+  }
 
   static NoopLattice initialElement() { return {}; }
 
@@ -530,67 +539,18 @@ class SpecialBoolAnalysis final
 if (const auto *E = selectFirst(
 "call", match(cxxConstructExpr(HasSpecialBoolType).bind("call"), 
*S,
   getASTContext( {
-  cast(Env.getValue(*E))
-  ->setProperty("is_set", Env.getBoolLiteralValue(false));
+  Env.setValue(Env.getResultObjectLocation(*E).getSyntheticField("is_set"),
+   Env.getBoolLiteralValue(false));
 } else if (const auto *E = selectFirst(
"call", 
match(cxxMemberCallExpr(callee(cxxMethodDecl(ofClass(

SpecialBoolRecordDecl
  .bind("call"),
  *S, getASTContext( {
-  auto &ObjectLoc =
-  *cast(getImplicitObjectLocation(*E, Env));
-
-  refreshRecordValue(ObjectLoc, Env)
-  .setProperty("is_set", Env.getBoolLiteralValue(true));
+  if (RecordStorageLocation *ObjectLoc = getImplicitObjectLocation(*E, 
Env))
+Env.setValue(ObjectLoc->getSyntheticField("is_set"),
+ Env.getBoolLiteralValue(true));
 }
   }
-
-  ComparisonResult compare(QualType Type, const Value &Val1,
-   const Environment &Env1, const Value &Val2,
-   const Environment &Env2) override {
-const auto *Decl = Type->getAsCXXRecordDecl();
-if (Decl == nullptr || Decl->getIdentifier() == nullptr ||
-Decl->getName() != "SpecialBool")
-  return ComparisonResult::Unknown;
-
-auto *IsSet1 = cast_or_null(Val1.getProperty("is_set"));
-auto *IsSet2 = cast_or_null(Val2.getProperty("is_set"));
-if (IsSet1 == nullptr)
-  return IsSet2 == nullptr ? ComparisonResult::Same
-   : ComparisonResult::Different;
-
-if (IsSet2 == nullptr)
-  return ComparisonResult::Different;
-
-return Env1.proves(IsSet1->formula()) == Env2.proves(IsSet2->formula())
-   ? ComparisonResult::Same
-   : ComparisonResult::Different;
-  }
-
-  // Always returns `true` to accept the `MergedVal`.
-  bool merge(QualType Type, const Value &Val1, const Environment &Env1,
- const Value &Val2, const Environment &Env2, Value &MergedVal,
- Environment &MergedEnv) override {
-const auto *Decl = Type->getAsCXXRecordDecl();
-if (Decl == nullptr || Decl->getIdentifier() == nullptr ||
-Decl->getName() != "SpecialBool")
-  return true;
-
-auto *IsSet1 = cast_or_null(Val1.getProperty("is_set"));
-if (IsSet1 == nullptr)
-  return true;
-
-auto *IsSet2 = cast_or_null(Val2.getProperty("is_set"));
-if (IsSet2 == nullptr)
-  return true;
-
-auto &IsSet = MergedEnv.makeAtomicBoolValue();
-MergedVal.setProperty("is_set", IsSet);
-if (Env1.proves(IsSet1->formula()) && Env2.proves(IsSet2->formula()))
-  MergedEnv.assume(IsSet.formula());
-
-return true;
-  }
 };
 
 class JoinFlowConditionsTest : public Test {
@@ -602,7 +562,7 @@ class JoinFlowConditionsTest : public Test {
 AnalysisInputs(
 Code, ast_matchers::hasName("target"),
 [](ASTContext &Context, Environment &Env) {
-  return SpecialBoolAnalysis(Context);
+  return SpecialBoolAnalysis(Context, Env);
 })
 .withASTBuildArgs({"-fsyn

[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits

https://github.com/david-arm updated 
https://github.com/llvm/llvm-project/pull/73326

>From af76f6b6b3469fd0f5f24427c5a175c8d9d7c83a Mon Sep 17 00:00:00 2001
From: David Sherwood 
Date: Fri, 24 Nov 2023 13:20:23 +
Subject: [PATCH 1/4] [Clang] Emit TBAA info for enums in C

When emitting TBAA information for enums in C code we
currently just treat the data as an 'omnipotent char'.
However, with C strict aliasing this means we fail to
optimise certain cases. For example, in the SPEC2017
xz benchmark there are structs that contain arrays of
enums, and clang pessmistically assumes that accesses
to those enums could alias with other struct members
that have a different type.

According to

https://en.cppreference.com/w/c/language/enum

enums should be treated as 'int' types unless
explicitly specified (C23) or if 'int' would not be
large enough to hold all the enumerated values. In the
latter case the compiler is free to choose a suitable
integer that would hold all such values.

When compiling C code this patch generates TBAA
information for the enum by using an equivalent integer
of the size clang has already chosen for the enum. I
have ignored C++ for now because the rules are more
complex.

New test added here:

  clang/test/CodeGen/tbaa.c
---
 clang/lib/CodeGen/CodeGenTBAA.cpp |   5 +-
 clang/test/CodeGen/tbaa.c | 116 ++
 2 files changed, 120 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/tbaa.c

diff --git a/clang/lib/CodeGen/CodeGenTBAA.cpp 
b/clang/lib/CodeGen/CodeGenTBAA.cpp
index 8705d3d65f1a5..f59d3d422d520 100644
--- a/clang/lib/CodeGen/CodeGenTBAA.cpp
+++ b/clang/lib/CodeGen/CodeGenTBAA.cpp
@@ -196,11 +196,14 @@ llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type 
*Ty) {
   // Enum types are distinct types. In C++ they have "underlying types",
   // however they aren't related for TBAA.
   if (const EnumType *ETy = dyn_cast(Ty)) {
+if (!Features.CPlusPlus)
+  return getTypeInfo(Context.getIntTypeForBitwidth(Size * 8, 0));
+
 // In C++ mode, types have linkage, so we can rely on the ODR and
 // on their mangled names, if they're external.
 // TODO: Is there a way to get a program-wide unique name for a
 // decl with local linkage or no linkage?
-if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
+if (!ETy->getDecl()->isExternallyVisible())
   return getChar();
 
 SmallString<256> OutName;
diff --git a/clang/test/CodeGen/tbaa.c b/clang/test/CodeGen/tbaa.c
new file mode 100644
index 0..0ab81f60a7194
--- /dev/null
+++ b/clang/test/CodeGen/tbaa.c
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -no-struct-path-tbaa 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefixes=PATH
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O0 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -relaxed-aliasing 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// Test TBAA metadata generated by front-end.
+//
+// NO-TBAA-NOT: !tbaa
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+
+typedef enum {
+  RED_AUTO_32,
+  GREEN_AUTO_32,
+  BLUE_AUTO_32
+} EnumAuto32;
+
+typedef enum {
+  RED_AUTO_64,
+  GREEN_AUTO_64,
+  BLUE_AUTO_64 = 0x1ull
+} EnumAuto64;
+
+typedef enum : uint16_t {
+  RED_16,
+  GREEN_16,
+  BLUE_16
+} Enum16;
+
+typedef enum : uint8_t {
+  RED_8,
+  GREEN_8,
+  BLUE_8
+} Enum8;
+
+uint32_t g0(EnumAuto32 *E, uint32_t *val) {
+// CHECK-LABEL: define{{.*}} i32 @g0(
+// CHECK: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// CHECK: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// CHECK: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH-LABEL: define{{.*}} i32 @g0(
+// PATH: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// PATH: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+  *val = 5;
+  *E = RED_AUTO_32;
+  return *val;
+}
+
+uint64_t g1(EnumAuto64 *E, uint64_t *val) {
+// CHECK-LABEL: define{{.*}} i64 @g1(
+// CHECK: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// CHECK: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// CHECK: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+// PATH-LABEL: define{{.*}} i64 @g1(
+// PATH: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// PATH: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// PATH: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+  *val = 5;
+  *E = RED_AUTO_64;
+  return *val;
+}
+
+uint16_t g2(Enum16 *E, uint16_t *val) {
+// CHECK-LABEL: define{{.*}} i16 @g2(
+// CHECK: store i16 5, ptr %{{.*}}, align 2, !tbaa [[TAG_i16:!.

[clang] [analyzer] EnumCastOutOfRangeChecker: report the value (PR #74503)

2023-12-07 Thread Endre Fülöp via cfe-commits

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


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


[clang] [clang] Crash when referencing capture in static lambda (PR #74661)

2023-12-07 Thread Ben Jackson via cfe-commits

https://github.com/puremourning updated 
https://github.com/llvm/llvm-project/pull/74661

>From 8a72385996824f9cdd0feb5a1ca7aa771c03fe99 Mon Sep 17 00:00:00 2001
From: Ben Jackson 
Date: Wed, 6 Dec 2023 21:59:21 +
Subject: [PATCH] Crash when referencing capture in static lambda

The constant evaluator could try to reference a lambda capture in a
static lambda call operator. Static lambdas can't have captures, so we
simply abort. Either the lambda needs to be made non-static, or the
capture (and reference to it) need to be removed.
---
 clang/docs/ReleaseNotes.rst |  4 
 clang/lib/AST/ExprConstant.cpp  | 14 --
 clang/test/Parser/cxx2b-lambdas.cpp | 12 
 3 files changed, 28 insertions(+), 2 deletions(-)

diff --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1fbd332f74057..43292d1eef227 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -848,6 +848,10 @@ Miscellaneous Clang Crashes Fixed
   `Issue 41302 `_
 - Fixed a crash when ``-ast-dump=json`` was used for code using class
   template deduction guides.
+- Fixed a crash when a lambda marked as `static` referenced a captured variable
+  in an expression.
+  `Issue 74608 `_
+
 
 OpenACC Specific Changes
 
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 986302e1fd225..e806318efd8a5 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -8492,14 +8492,24 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);
+
+  // Static lambda function call operators can't have captures. We already
+  // diagnosed this, so bail out here.
+  if (MD->isStatic()) {
+assert(Info.CurrentCall->This == nullptr &&
+   "This should not be set for a static call operator");
+return false;
+  }
+
   // Start with 'Result' referring to the complete closure object...
-  if (auto *MD = cast(Info.CurrentCall->Callee);
-  MD->isExplicitObjectMemberFunction()) {
+  if (MD->isExplicitObjectMemberFunction()) {
 APValue *RefValue =
 Info.getParamSlot(Info.CurrentCall->Arguments, 
MD->getParamDecl(0));
 Result.setFrom(Info.Ctx, *RefValue);
   } else
 Result = *Info.CurrentCall->This;
+
   // ... then update it to refer to the field of the closure object
   // that represents the capture.
   if (!HandleLValueMember(Info, E, Result, FD))
diff --git a/clang/test/Parser/cxx2b-lambdas.cpp 
b/clang/test/Parser/cxx2b-lambdas.cpp
index bb9ed226afffa..ad975a17b6e47 100644
--- a/clang/test/Parser/cxx2b-lambdas.cpp
+++ b/clang/test/Parser/cxx2b-lambdas.cpp
@@ -66,3 +66,15 @@ void static_captures() {
 }
   };
 }
+
+constexpr auto static_capture_constexpr() {
+  char n = 'n';
+  return [n] static { return n; }(); // expected-error {{a static lambda 
cannot have any captures}}
+}
+static_assert(static_capture_constexpr()); // expected-error {{static 
assertion expression is not an integral constant expression}}
+
+constexpr auto capture_constexpr() {
+  char n = 'n';
+  return [n] { return n; }();
+}
+static_assert(capture_constexpr());

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


[clang] [clang] Crash when referencing capture in static lambda (PR #74661)

2023-12-07 Thread Ben Jackson via cfe-commits

puremourning wrote:

> Can you add a release note? Otherwise it looks good to me

Yep, sure thing. Done.

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


[llvm] [clang-tools-extra] [clang] [clang] Fix false positive -Wmissing-field-initializer for anonymous unions (PR #70829)

2023-12-07 Thread Mariya Podchishchaeva via cfe-commits

https://github.com/Fznamznon updated 
https://github.com/llvm/llvm-project/pull/70829

>From ac30780250875802d13450d17e6959f9e2ad3a70 Mon Sep 17 00:00:00 2001
From: "Podchishchaeva, Mariya" 
Date: Tue, 31 Oct 2023 09:27:51 -0700
Subject: [PATCH 1/6] [clang] Fix false positive -Wmissing-field-initializer
 for anonymous unions

Normally warning is not reported when a field has default initializer.
Do so for anonymous unions with default initializers as well.
No release note since it is a regression in clang 18.

Fixes https://github.com/llvm/llvm-project/issues/70384
---
 clang/lib/Sema/SemaInit.cpp   | 99 +++
 .../SemaCXX/cxx2a-initializer-aggregates.cpp  | 66 -
 2 files changed, 122 insertions(+), 43 deletions(-)

diff --git a/clang/lib/Sema/SemaInit.cpp b/clang/lib/Sema/SemaInit.cpp
index ec796def96ad3..881e67587e430 100644
--- a/clang/lib/Sema/SemaInit.cpp
+++ b/clang/lib/Sema/SemaInit.cpp
@@ -349,17 +349,13 @@ class InitListChecker {
   bool SubobjectIsDesignatorContext, unsigned &Index,
   InitListExpr *StructuredList,
   unsigned &StructuredIndex);
-  bool CheckDesignatedInitializer(const InitializedEntity &Entity,
-  InitListExpr *IList, DesignatedInitExpr *DIE,
-  unsigned DesigIdx,
-  QualType &CurrentObjectType,
-  RecordDecl::field_iterator *NextField,
-  llvm::APSInt *NextElementIndex,
-  unsigned &Index,
-  InitListExpr *StructuredList,
-  unsigned &StructuredIndex,
-  bool FinishSubobjectInit,
-  bool TopLevelObject);
+  bool CheckDesignatedInitializer(
+  const InitializedEntity &Entity, InitListExpr *IList,
+  DesignatedInitExpr *DIE, unsigned DesigIdx, QualType &CurrentObjectType,
+  RecordDecl::field_iterator *NextField, llvm::APSInt *NextElementIndex,
+  unsigned &Index, InitListExpr *StructuredList, unsigned &StructuredIndex,
+  bool FinishSubobjectInit, bool TopLevelObject,
+  llvm::SmallPtrSetImpl *InitializedFields = nullptr);
   InitListExpr *getStructuredSubobjectInit(InitListExpr *IList, unsigned Index,
QualType CurrentObjectType,
InitListExpr *StructuredList,
@@ -2248,7 +2244,8 @@ void InitListChecker::CheckStructUnionTypes(
   // the next field that we'll be initializing.
   bool DesignatedInitFailed = CheckDesignatedInitializer(
   Entity, IList, DIE, 0, DeclType, &Field, nullptr, Index,
-  StructuredList, StructuredIndex, true, TopLevelObject);
+  StructuredList, StructuredIndex, true, TopLevelObject,
+  &InitializedFields);
   if (DesignatedInitFailed)
 hadError = true;
 
@@ -2256,7 +2253,6 @@ void InitListChecker::CheckStructUnionTypes(
   DesignatedInitExpr::Designator *D = DIE->getDesignator(0);
   if (!VerifyOnly && D->isFieldDesignator()) {
 FieldDecl *F = D->getFieldDecl();
-InitializedFields.insert(F);
 if (!DesignatedInitFailed) {
   QualType ET = SemaRef.Context.getBaseElementType(F->getType());
   if (checkDestructorReference(ET, InitLoc, SemaRef)) {
@@ -2365,21 +2361,43 @@ void InitListChecker::CheckStructUnionTypes(
   !RD->isUnion()) {
 // It is possible we have one or more unnamed bitfields remaining.
 // Find first (if any) named field and emit warning.
-for (RecordDecl::field_iterator it = HasDesignatedInit ? RD->field_begin()
-   : Field,
-end = RD->field_end();
- it != end; ++it) {
-  if (HasDesignatedInit && InitializedFields.count(*it))
-continue;
+auto MissingFieldCheck = [&](const RecordDecl *Record,
+ RecordDecl::field_iterator StartField,
+ auto &&MissingFieldCheck) -> bool {
+  FieldDecl *FirstUninitialized = nullptr;
+  for (RecordDecl::field_iterator it = StartField,
+  end = Record->field_end();
+   it != end; ++it) {
+bool AllSet = false;
+if (it->isAnonymousStructOrUnion()) {
+  RecordDecl *RDAnon = it->getType()->getAsRecordDecl();
+  AllSet = MissingFieldCheck(RDAnon, RDAnon->field_begin(),
+ MissingFieldCheck);
+}
+
+if ((HasDesignatedInit && InitializedFields.count(*it)) ||
+it->hasInClassInitializer() || AllSet) {
+  if (Record->isUnion())
+return true;
+  continue;
+}
 
-  if (!it->isUnnamedBitfield() && !it->hasInClassInitializer() &&
-   

[clang] [llvm] [ValueTracking] Add dominating condition support in computeKnownBits() (PR #73662)

2023-12-07 Thread Mikhail Goncharov via cfe-commits

metaflow wrote:

looks like we just had a pathological case that was on a threshold. Thank you!

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


[lld] [mlir] [clang-tools-extra] [libcxxabi] [lldb] [flang] [compiler-rt] [openmp] [libcxx] [clang] [llvm] [AMDGPU] Add GFX12 encoding for VINTERP instructions (PR #74616)

2023-12-07 Thread Jay Foad via cfe-commits

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Ben Shi via cfe-commits

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

>From 65ce18117f99056aafcf58151b64f4243f4d5e26 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Mon, 4 Dec 2023 15:51:20 +0800
Subject: [PATCH 1/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp| 16 
 .../Analysis/Inputs/system-header-simulator.h|  1 +
 clang/test/Analysis/stream-error.c   |  9 +
 3 files changed, 26 insertions(+)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 925fc90e35543..2c725c01dc285 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,6 +266,7 @@ class StreamChecker : public CheckerStreamArgNo)
+   ->isNullPointerConstant(C.getASTContext(),
+   Expr::NPC_ValueDependentIsNotNull)) {
+ProgramStateRef State = C.getState();
+if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  C.addTransition(State);
+  }
+}
+
 ProgramStateRef
 StreamChecker::ensureStreamNonNull(SVal StreamVal, const Expr *StreamE,
CheckerContext &C,
diff --git a/clang/test/Analysis/Inputs/system-header-simulator.h 
b/clang/test/Analysis/Inputs/system-header-simulator.h
index 7089bd8bfc9d9..409a969a0d4cc 100644
--- a/clang/test/Analysis/Inputs/system-header-simulator.h
+++ b/clang/test/Analysis/Inputs/system-header-simulator.h
@@ -61,6 +61,7 @@ void clearerr(FILE *stream);
 int feof(FILE *stream);
 int ferror(FILE *stream);
 int fileno(FILE *stream);
+int fflush(FILE *stream);
 
 size_t strlen(const char *);
 
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index c8332bcbfa8ca..aa5b6be851773 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -299,6 +299,15 @@ void error_fseek_0(void) {
   fclose(F);
 }
 
+void error_fflush(void) {
+  FILE *F = tmpfile();
+  if (!F)
+return;
+  fclose(F);
+  fflush(F);// expected-warning {{Stream might be already closed}}
+  fflush(NULL); // no-warning
+}
+
 void error_indeterminate(void) {
   FILE *F = fopen("file", "r+");
   if (!F)

>From dcb766b468a2f29df30451f8f196d7a2371fd038 Mon Sep 17 00:00:00 2001
From: Ben Shi 
Date: Wed, 6 Dec 2023 15:47:35 +0800
Subject: [PATCH 2/3] [clang][analyzer] Support `fflush` in the StreamChecker

---
 .../StaticAnalyzer/Checkers/StreamChecker.cpp | 49 ---
 clang/test/Analysis/stream-error.c| 12 +++--
 2 files changed, 51 insertions(+), 10 deletions(-)

diff --git a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
index 2c725c01dc285..a368619fd37d2 100644
--- a/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/StreamChecker.cpp
@@ -266,7 +266,8 @@ class StreamChecker : public CheckerStreamArgNo)
-   ->isNullPointerConstant(C.getASTContext(),
-   Expr::NPC_ValueDependentIsNotNull)) {
-ProgramStateRef State = C.getState();
-if (State = ensureStreamOpened(getStreamArg(Desc, Call), C, State))
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  if (!Stream)
+return;
+
+  ConstraintManager::ProgramStatePair SP =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (State = SP.first)
+if (State = ensureStreamOpened(StreamVal, C, State))
   C.addTransition(State);
+}
+
+void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent 
&Call,
+   CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  // We will check the result even if the input is `NULL`,
+  // but do nothing if the input state is unknown.
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  if (StreamSym) {
+const StreamState *OldSS = State->get(StreamSym);
+if (!OldSS)
+  return;
+assertStreamStateOpened(OldSS);
   }
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  // `fflush` returns 0 on success, otherwise returns EOF.
+  ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+
+  // This function does not affect the stream state.
+  // Still we add success and failure state with the appropriate return value.
+  C.addTransition(StateNotFailed);
+  C.addTransition(StateFailed);
 }
 
 ProgramStateRef
diff --git a/clang/test/Analysis/stream-error.c 
b/clang/test/Analysis/stream-error.c
index aa5b6be851773..94787874cf839 100644
--- a/clang/test/Analysis/stream-error.c
+++ b/clang/test/Analysis/stream-error.c
@@ -301,11 +301,17 @@ void error_fseek_0(void) {
 
 void error_fflush(void) {
 

[clang] [clang] Substitute alias templates from correct context (PR #74335)

2023-12-07 Thread Mariya Podchishchaeva via cfe-commits

Fznamznon wrote:

Thanks, I reproduced the problem with
```

template  class shared_ptr {
T* data;
};

template  class cfftpass {
static shared_ptr make_pass();
};

template using Tcpass = shared_ptr>;

template Tcpass cfftpass::make_pass() { return 
Tcpass{};};
   
```

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


[flang] [clang] [flang][Driver] Let the linker fail on multiple definitions of main() (PR #73124)

2023-12-07 Thread Ricardo Jesus via cfe-commits

rj-jesus wrote:

> > Chipping into the discussion, since this patch I can also no longer build 
> > OpenBLAS or PETSc. OpenBLAS for example fails with
> > ```
> > $ clang -v -O3 -mcpu=native  -DHAVE_C11 -Wall -DF_INTERFACE_GFORT -fPIC 
> > -DSMP_SERVER -DNO_WARMUP -DMAX_CPU_NUMBER=72 -DMAX_PARALLEL_NUMBER=1 
> > -DMAX_STACK_ALLOC=2048 -DNO_AFFINITY -DVERSION="\"0.3.25\"" -DBUILD_SINGLE 
> > -DBUILD_DOUBLE -DBUILD_COMPLEX -DBUILD_COMPLEX16  
> > utest/CMakeFiles/openblas_utest.dir/utest_main.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_min.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_amax.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_ismin.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_rotmg.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_rot.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_axpy.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dsdot.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dnrm2.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_swap.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dotu.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_potrs.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_kernel_regress.c.o -o 
> > utest/openblas_utest  -Wl,-rpath,/.../openblas/build/lib  
> > lib/libopenblas.so.0.3  -lm
> > clang version 18.0.0 (g...@github.com:llvm/llvm-project.git 
> > 17feb330aab39c6c0c21ee9b02efb484dfb2261e)
> > Target: aarch64-unknown-linux-gnu
> > Thread model: posix
> > InstalledDir: /.../llvm/trunk/bin
> > Found candidate GCC installation: /usr/lib/gcc/aarch64-linux-gnu/11
> > Found candidate GCC installation: /usr/lib/gcc/aarch64-linux-gnu/12
> > Selected GCC installation: /usr/lib/gcc/aarch64-linux-gnu/12
> > Candidate multilib: .;@m64
> > Selected multilib: .;@m64
> > Found CUDA installation: /usr/local/cuda, version 
> >  "/usr/bin/ld" -EL -z relro --hash-style=gnu --eh-frame-hdr -m aarch64linux 
> > -pie -dynamic-linker /lib/ld-linux-aarch64.so.1 -o utest/openblas_utest 
> > /lib/aarch64-linux-gnu/Scrt1.o /lib/aarch64-linux-gnu/crti.o 
> > /usr/lib/gcc/aarch64-linux-gnu/12/crtbeginS.o 
> > -L/.../llvm/trunk/lib/clang/18/lib/aarch64-unknown-linux-gnu 
> > -L/usr/lib/gcc/aarch64-linux-gnu/12 -L/lib/aarch64-linux-gnu 
> > -L/usr/lib/aarch64-linux-gnu -L/lib -L/usr/lib -L/.../llvm/trunk/lib 
> > utest/CMakeFiles/openblas_utest.dir/utest_main.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_min.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_amax.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_ismin.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_rotmg.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_rot.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_axpy.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dsdot.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dnrm2.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_swap.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_dotu.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_potrs.c.o 
> > utest/CMakeFiles/openblas_utest.dir/test_kernel_regress.c.o -rpath 
> > /.../openblas/build/lib lib/libopenblas.so.0.3 -lm -lgcc --as-needed 
> > -lgcc_s --no-as-needed -lc -lgcc --as-needed -lgcc_s --no-as-needed 
> > /usr/lib/gcc/aarch64-linux-gnu/12/crtendS.o /lib/aarch64-linux-gnu/crtn.o
> > /usr/bin/ld: lib/libopenblas.so.0.3: undefined reference to 
> > `_QQEnvironmentDefaults'
> > /usr/bin/ld: lib/libopenblas.so.0.3: undefined reference to `_QQmain'
> > ```
> 
> Thanks for the report! Can you please tell me how OpenBLAS was built? I'm 
> trying to replicate this, but I do not see a reference to `_QQmain` or the 
> likes in the OpenBLAS library that I build on x86.

Hi @mjklemm! This was on an AArch64 box (not that that should make a 
difference) doing something like:
```
git clone -b v0.3.25 https://github.com/OpenMathLib/OpenBLAS.git

cd OpenBLAS
mkdir build && cd build
cmake -G Ninja \
  -DCMAKE_C_COMPILER=clang \
  -DCMAKE_CXX_COMPILER=clang++ \
  -DCMAKE_Fortran_COMPILER=flang-new \
  -DCMAKE_C_FLAGS="-O3 -mcpu=native" \
  -DCMAKE_CXX_FLAGS="-O3 -mcpu=native" \
  -DCMAKE_Fortran_FLAGS="-O3 -mcpu=native" \
  -DBUILD_SHARED_LIBS=ON \
  -DCMAKE_INSTALL_PREFIX=$INSTALL_DIR ..
sed -i 's/-m64//g' build.ninja
sed -i 's/-rdynamic//' build.ninja
cmake --build . -j32
cmake --install .
```
The error shows up when linking a C program with a Fortran shared library, so 
maybe you weren't enabling building shared libraries?

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


[clang] [Clang][AArch64] Add fix vector types to header into SVE (PR #73258)

2023-12-07 Thread via cfe-commits

https://github.com/CarolineConcatto updated 
https://github.com/llvm/llvm-project/pull/73258

>From e0f245e8d6a395afac5de471b55358c7b730a170 Mon Sep 17 00:00:00 2001
From: Caroline Concatto 
Date: Wed, 22 Nov 2023 10:03:50 +
Subject: [PATCH 1/4] [Clang][AArch64] Add  fix vector types to header into SVE

This patch is needed for the reduction instructions in sve2.1

It add ta new header to sve with all the fixed vector types.
The new types are only added if neon is not declared.
---
 clang/include/clang/Basic/arm_vector_type.td  |  13 ++
 clang/lib/Headers/CMakeLists.txt  |   3 +
 .../CodeGen/arm-vector_type-params-returns.c  | 113 ++
 clang/utils/TableGen/NeonEmitter.cpp  |  44 +++
 clang/utils/TableGen/SveEmitter.cpp   |   2 +
 clang/utils/TableGen/TableGen.cpp |  15 ++-
 clang/utils/TableGen/TableGenBackends.h   |   1 +
 7 files changed, 188 insertions(+), 3 deletions(-)
 create mode 100644 clang/include/clang/Basic/arm_vector_type.td
 create mode 100644 clang/test/CodeGen/arm-vector_type-params-returns.c

diff --git a/clang/include/clang/Basic/arm_vector_type.td 
b/clang/include/clang/Basic/arm_vector_type.td
new file mode 100644
index 0..5018b0cdfc137
--- /dev/null
+++ b/clang/include/clang/Basic/arm_vector_type.td
@@ -0,0 +1,13 @@
+//===--- arm_vector_type.td - ARM Fixed vector types compiler interface 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the TableGen definitions from which the ARM BF16 header
+//  file will be generated.
+//
+//===--===//
+include "arm_neon_incl.td"
diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt
index 8b1e2bc4afa4d..0beb6ade42920 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -385,6 +385,8 @@ if(ARM IN_LIST LLVM_TARGETS_TO_BUILD OR AArch64 IN_LIST 
LLVM_TARGETS_TO_BUILD)
   clang_generate_header(-gen-arm-mve-header arm_mve.td arm_mve.h)
   # Generate arm_cde.h
   clang_generate_header(-gen-arm-cde-header arm_cde.td arm_cde.h)
+  # Generate arm_vector_type.h
+  clang_generate_header(-gen-arm-vector-type arm_vector_type.td 
arm_vector_type.h)
 
   # Add headers to target specific lists
   list(APPEND arm_common_generated_files
@@ -401,6 +403,7 @@ if(ARM IN_LIST LLVM_TARGETS_TO_BUILD OR AArch64 IN_LIST 
LLVM_TARGETS_TO_BUILD)
 "${CMAKE_CURRENT_BINARY_DIR}/arm_sve.h"
 "${CMAKE_CURRENT_BINARY_DIR}/arm_sme_draft_spec_subject_to_change.h"
 "${CMAKE_CURRENT_BINARY_DIR}/arm_bf16.h"
+"${CMAKE_CURRENT_BINARY_DIR}/arm_vector_type.h"
 )
 endif()
 if(RISCV IN_LIST LLVM_TARGETS_TO_BUILD)
diff --git a/clang/test/CodeGen/arm-vector_type-params-returns.c 
b/clang/test/CodeGen/arm-vector_type-params-returns.c
new file mode 100644
index 0..48c19d01b6257
--- /dev/null
+++ b/clang/test/CodeGen/arm-vector_type-params-returns.c
@@ -0,0 +1,113 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -emit-llvm -O2 -o - %s 
| opt -S -passes=mem2reg,sroa | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve2p1 -S 
-disable-O0-optnone -Werror -Wall -o - /dev/null %s
+#include 
+
+// function return types
+// CHECK-LABEL: define dso_local <8 x half> @test_ret_v8f16(
+// CHECK-SAME: <8 x half> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <8 x half> [[V]]
+//
+float16x8_t test_ret_v8f16(float16x8_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <4 x float> @test_ret_v4f32(
+// CHECK-SAME: <4 x float> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <4 x float> [[V]]
+//
+float32x4_t test_ret_v4f32(float32x4_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <2 x double> @test_ret_v2f64(
+// CHECK-SAME: <2 x double> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <2 x double> [[V]]
+//
+float64x2_t test_ret_v2f64(float64x2_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <8 x bfloat> @test_ret_v8bf16(
+// CHECK-SAME: <8 x bfloat> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <8 x bfloat> [[V]]
+//
+bfloat16x8_t test_ret_v8bf16(bfloat16x8_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <16 x i8> @test_ret_v16s8(
+// CHECK-SAME: <16 x i8> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <16 x i8> [[

[clang] [Clang][AArch64] Add fix vector types to header into SVE (PR #73258)

2023-12-07 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 c308d903a8fd479e49271ae9f08f7260ff5f58a7 
e41718e88a0fd0efb0ee17d002e1cc50ff286a19 -- 
clang/test/CodeGen/arm-vector_type-params-returns.c 
clang/utils/TableGen/NeonEmitter.cpp clang/utils/TableGen/SveEmitter.cpp 
clang/utils/TableGen/TableGen.cpp clang/utils/TableGen/TableGenBackends.h
``





View the diff from clang-format here.


``diff
diff --git a/clang/utils/TableGen/TableGen.cpp 
b/clang/utils/TableGen/TableGen.cpp
index 9a986b532e..8a183531a6 100644
--- a/clang/utils/TableGen/TableGen.cpp
+++ b/clang/utils/TableGen/TableGen.cpp
@@ -282,11 +282,14 @@ cl::opt Action(
"Generate riscv_vector_builtin_cg.inc for clang"),
 clEnumValN(GenRISCVVectorBuiltinSema, "gen-riscv-vector-builtin-sema",
"Generate riscv_vector_builtin_sema.inc for clang"),
-clEnumValN(GenRISCVSiFiveVectorBuiltins, 
"gen-riscv-sifive-vector-builtins",
+clEnumValN(GenRISCVSiFiveVectorBuiltins,
+   "gen-riscv-sifive-vector-builtins",
"Generate riscv_sifive_vector_builtins.inc for clang"),
-clEnumValN(GenRISCVSiFiveVectorBuiltinCG, 
"gen-riscv-sifive-vector-builtin-codegen",
+clEnumValN(GenRISCVSiFiveVectorBuiltinCG,
+   "gen-riscv-sifive-vector-builtin-codegen",
"Generate riscv_sifive_vector_builtin_cg.inc for clang"),
-clEnumValN(GenRISCVSiFiveVectorBuiltinSema, 
"gen-riscv-sifive-vector-builtin-sema",
+clEnumValN(GenRISCVSiFiveVectorBuiltinSema,
+   "gen-riscv-sifive-vector-builtin-sema",
"Generate riscv_sifive_vector_builtin_sema.inc for clang"),
 clEnumValN(GenAttrDocs, "gen-attr-docs",
"Generate attribute documentation"),

``




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


[clang] [flang] [llvm] [clang-tools-extra] [flang] GETLOG runtime and extension implementation: get login username (PR #74628)

2023-12-07 Thread Yi Wu via cfe-commits

https://github.com/yi-wu-arm updated 
https://github.com/llvm/llvm-project/pull/74628

>From 0e98aa7ca15b05b91813eaeeb6ae1305e5f5384d Mon Sep 17 00:00:00 2001
From: Yi Wu 
Date: Mon, 6 Nov 2023 19:49:13 +
Subject: [PATCH 01/23] GETLOG runtime and extension implementation: get login
 username

Get login username, ussage:
CHARACTER(32) :: login
CALL getlog(login)
WRITE(*,*) login
---
 flang/docs/Intrinsics.md  |  2 +-
 .../Optimizer/Builder/Runtime/RTBuilder.h |  8 
 flang/include/flang/Runtime/command.h |  6 +++
 flang/include/flang/Runtime/extensions.h  |  2 +
 flang/runtime/command.cpp | 40 +++
 flang/runtime/extensions.cpp  |  6 +++
 flang/unittests/Runtime/CommandTest.cpp   | 15 ++-
 7 files changed, 77 insertions(+), 2 deletions(-)

diff --git a/flang/docs/Intrinsics.md b/flang/docs/Intrinsics.md
index ab0a940e53e55..cfe5dcd141e98 100644
--- a/flang/docs/Intrinsics.md
+++ b/flang/docs/Intrinsics.md
@@ -751,7 +751,7 @@ This phase currently supports all the intrinsic procedures 
listed above but the
 | Object characteristic inquiry functions | ALLOCATED, ASSOCIATED, 
EXTENDS_TYPE_OF, IS_CONTIGUOUS, PRESENT, RANK, SAME_TYPE, STORAGE_SIZE |
 | Type inquiry intrinsic functions | BIT_SIZE, DIGITS, EPSILON, HUGE, KIND, 
MAXEXPONENT, MINEXPONENT, NEW_LINE, PRECISION, RADIX, RANGE, TINY|
 | Non-standard intrinsic functions | AND, OR, XOR, SHIFT, ZEXT, IZEXT, COSD, 
SIND, TAND, ACOSD, ASIND, ATAND, ATAN2D, COMPL, EQV, NEQV, INT8, JINT, JNINT, 
KNINT, QCMPLX, DREAL, DFLOAT, QEXT, QFLOAT, QREAL, DNUM, NUM, JNUM, KNUM, QNUM, 
RNUM, RAN, RANF, ILEN, SIZEOF, MCLOCK, SECNDS, COTAN, IBCHNG, ISHA, ISHC, ISHL, 
IXOR, IARG, IARGC, NARGS, NUMARG, BADDRESS, IADDR, CACHESIZE, EOF, FP_CLASS, 
INT_PTR_KIND, ISNAN, MALLOC |
-| Intrinsic subroutines |MVBITS (elemental), CPU_TIME, DATE_AND_TIME, 
EVENT_QUERY, EXECUTE_COMMAND_LINE, GET_COMMAND, GET_COMMAND_ARGUMENT, 
GET_ENVIRONMENT_VARIABLE, MOVE_ALLOC, RANDOM_INIT, RANDOM_NUMBER, RANDOM_SEED, 
SYSTEM_CLOCK |
+| Intrinsic subroutines |MVBITS (elemental), CPU_TIME, DATE_AND_TIME, 
EVENT_QUERY, EXECUTE_COMMAND_LINE, GET_COMMAND, GET_COMMAND_ARGUMENT, 
GET_ENVIRONMENT_VARIABLE, GETLOG, MOVE_ALLOC, RANDOM_INIT, RANDOM_NUMBER, 
RANDOM_SEED, SYSTEM_CLOCK |
 | Atomic intrinsic subroutines | ATOMIC_ADD |
 | Collective intrinsic subroutines | CO_REDUCE |
 
diff --git a/flang/include/flang/Optimizer/Builder/Runtime/RTBuilder.h 
b/flang/include/flang/Optimizer/Builder/Runtime/RTBuilder.h
index b2774263e7a31..830df7ad006b5 100644
--- a/flang/include/flang/Optimizer/Builder/Runtime/RTBuilder.h
+++ b/flang/include/flang/Optimizer/Builder/Runtime/RTBuilder.h
@@ -62,6 +62,14 @@ using FuncTypeBuilderFunc = mlir::FunctionType 
(*)(mlir::MLIRContext *);
 /// standard type `i32` when `sizeof(int)` is 4.
 template 
 static constexpr TypeBuilderFunc getModel();
+
+template <>
+constexpr TypeBuilderFunc getModel() {
+  return [](mlir::MLIRContext *context) -> mlir::Type {
+return mlir::IntegerType::get(context, 8 * sizeof(unsigned int));
+  };
+}
+
 template <>
 constexpr TypeBuilderFunc getModel() {
   return [](mlir::MLIRContext *context) -> mlir::Type {
diff --git a/flang/include/flang/Runtime/command.h 
b/flang/include/flang/Runtime/command.h
index ec62893905454..1c212ef61697c 100644
--- a/flang/include/flang/Runtime/command.h
+++ b/flang/include/flang/Runtime/command.h
@@ -47,6 +47,12 @@ std::int32_t RTNAME(GetEnvVariable)(const Descriptor &name,
 bool trim_name = true, const Descriptor *errmsg = nullptr,
 const char *sourceFile = nullptr, int line = 0);
 }
+
+// Try to get the name of current user
+// Returns a STATUS as described in the standard.
+std::int32_t RTNAME(GetLog)(
+const Descriptor *argument = nullptr, const Descriptor *errmsg = nullptr);
+
 } // namespace Fortran::runtime
 
 #endif // FORTRAN_RUNTIME_COMMAND_H_
diff --git a/flang/include/flang/Runtime/extensions.h 
b/flang/include/flang/Runtime/extensions.h
index ad592814e5acb..d199d5e387b86 100644
--- a/flang/include/flang/Runtime/extensions.h
+++ b/flang/include/flang/Runtime/extensions.h
@@ -28,5 +28,7 @@ std::int32_t FORTRAN_PROCEDURE_NAME(iargc)();
 void FORTRAN_PROCEDURE_NAME(getarg)(
 std::int32_t &n, std::int8_t *arg, std::int64_t length);
 
+void FORTRAN_PROCEDURE_NAME(getlog)(std::int8_t *name, std::int64_t length);
+
 } // extern "C"
 #endif // FORTRAN_RUNTIME_EXTENSIONS_H_
diff --git a/flang/runtime/command.cpp b/flang/runtime/command.cpp
index b81a0791c5e57..6b2f313e227a1 100644
--- a/flang/runtime/command.cpp
+++ b/flang/runtime/command.cpp
@@ -15,6 +15,30 @@
 #include 
 #include 
 
+#ifdef _WIN32
+#define WIN32_LEAN_AND_MEAN
+#define NOMINMAX
+#include 
+
+#include  // UNLEN=256
+
+inline char *getlogin() {
+  char *username = NULL;
+  DWORD size = UNLEN + 1; // Constant for the maximum username length
+  username = (char *)malloc(size);
+
+  if (GetUserName(username, &size)) {
+// Username 

[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Paul Walker via cfe-commits

https://github.com/paulwalker-arm approved this pull request.

This looks broadly good to me.  I suggest reverting the LangRef change because 
it doesn't add any new information relevant to LLVM IR.

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


[clang] [llvm] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Paul Walker via cfe-commits

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


[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Paul Walker via cfe-commits


@@ -196,6 +196,9 @@ C Language Changes
   number of elements in the flexible array member. This information can improve
   the results of the array bound sanitizer and the
   ``__builtin_dynamic_object_size`` builtin.
+- Enums will now be represented in TBAA metadata using their actual underlying

paulwalker-arm wrote:

Perhaps worth saying `Enums in C...` since the behaviour for C++ is different 
and remains unchanged.

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


[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Paul Walker via cfe-commits


@@ -6376,13 +6376,26 @@ aliases a memory access with an access tag ``(BaseTy2, 
AccessTy2,
 Offset2)`` if either ``(BaseTy1, Offset1)`` is reachable from ``(Base2,
 Offset2)`` via the ``Parent`` relation or vice versa.
 
+In C an enum will be compatible with an underlying integer type that is large
+enough to hold all enumerated values. In most cases this will be an ``int``,
+which is the default when no type is specified. However, if an ``int`` is not

paulwalker-arm wrote:

I don't think this information belongs in the LangRef, especially as it doesn't 
add any value to the underlying description of what the metadata represents.

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


[clang-tools-extra] [llvm] [clang] [Clang][AArch64] Add fix vector types to header into SVE (PR #73258)

2023-12-07 Thread via cfe-commits

https://github.com/CarolineConcatto updated 
https://github.com/llvm/llvm-project/pull/73258

>From e0f245e8d6a395afac5de471b55358c7b730a170 Mon Sep 17 00:00:00 2001
From: Caroline Concatto 
Date: Wed, 22 Nov 2023 10:03:50 +
Subject: [PATCH 1/4] [Clang][AArch64] Add  fix vector types to header into SVE

This patch is needed for the reduction instructions in sve2.1

It add ta new header to sve with all the fixed vector types.
The new types are only added if neon is not declared.
---
 clang/include/clang/Basic/arm_vector_type.td  |  13 ++
 clang/lib/Headers/CMakeLists.txt  |   3 +
 .../CodeGen/arm-vector_type-params-returns.c  | 113 ++
 clang/utils/TableGen/NeonEmitter.cpp  |  44 +++
 clang/utils/TableGen/SveEmitter.cpp   |   2 +
 clang/utils/TableGen/TableGen.cpp |  15 ++-
 clang/utils/TableGen/TableGenBackends.h   |   1 +
 7 files changed, 188 insertions(+), 3 deletions(-)
 create mode 100644 clang/include/clang/Basic/arm_vector_type.td
 create mode 100644 clang/test/CodeGen/arm-vector_type-params-returns.c

diff --git a/clang/include/clang/Basic/arm_vector_type.td 
b/clang/include/clang/Basic/arm_vector_type.td
new file mode 100644
index 0..5018b0cdfc137
--- /dev/null
+++ b/clang/include/clang/Basic/arm_vector_type.td
@@ -0,0 +1,13 @@
+//===--- arm_vector_type.td - ARM Fixed vector types compiler interface 
---===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM 
Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===--===//
+//
+//  This file defines the TableGen definitions from which the ARM BF16 header
+//  file will be generated.
+//
+//===--===//
+include "arm_neon_incl.td"
diff --git a/clang/lib/Headers/CMakeLists.txt b/clang/lib/Headers/CMakeLists.txt
index 8b1e2bc4afa4d..0beb6ade42920 100644
--- a/clang/lib/Headers/CMakeLists.txt
+++ b/clang/lib/Headers/CMakeLists.txt
@@ -385,6 +385,8 @@ if(ARM IN_LIST LLVM_TARGETS_TO_BUILD OR AArch64 IN_LIST 
LLVM_TARGETS_TO_BUILD)
   clang_generate_header(-gen-arm-mve-header arm_mve.td arm_mve.h)
   # Generate arm_cde.h
   clang_generate_header(-gen-arm-cde-header arm_cde.td arm_cde.h)
+  # Generate arm_vector_type.h
+  clang_generate_header(-gen-arm-vector-type arm_vector_type.td 
arm_vector_type.h)
 
   # Add headers to target specific lists
   list(APPEND arm_common_generated_files
@@ -401,6 +403,7 @@ if(ARM IN_LIST LLVM_TARGETS_TO_BUILD OR AArch64 IN_LIST 
LLVM_TARGETS_TO_BUILD)
 "${CMAKE_CURRENT_BINARY_DIR}/arm_sve.h"
 "${CMAKE_CURRENT_BINARY_DIR}/arm_sme_draft_spec_subject_to_change.h"
 "${CMAKE_CURRENT_BINARY_DIR}/arm_bf16.h"
+"${CMAKE_CURRENT_BINARY_DIR}/arm_vector_type.h"
 )
 endif()
 if(RISCV IN_LIST LLVM_TARGETS_TO_BUILD)
diff --git a/clang/test/CodeGen/arm-vector_type-params-returns.c 
b/clang/test/CodeGen/arm-vector_type-params-returns.c
new file mode 100644
index 0..48c19d01b6257
--- /dev/null
+++ b/clang/test/CodeGen/arm-vector_type-params-returns.c
@@ -0,0 +1,113 @@
+// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py 
UTC_ARGS: --version 3
+// RUN: %clang_cc1 -triple aarch64 -target-feature +sve -emit-llvm -O2 -o - %s 
| opt -S -passes=mem2reg,sroa | FileCheck %s
+// RUN: %clang_cc1 -triple aarch64-none-linux-gnu -target-feature +sve2p1 -S 
-disable-O0-optnone -Werror -Wall -o - /dev/null %s
+#include 
+
+// function return types
+// CHECK-LABEL: define dso_local <8 x half> @test_ret_v8f16(
+// CHECK-SAME: <8 x half> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0:[0-9]+]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <8 x half> [[V]]
+//
+float16x8_t test_ret_v8f16(float16x8_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <4 x float> @test_ret_v4f32(
+// CHECK-SAME: <4 x float> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <4 x float> [[V]]
+//
+float32x4_t test_ret_v4f32(float32x4_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <2 x double> @test_ret_v2f64(
+// CHECK-SAME: <2 x double> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <2 x double> [[V]]
+//
+float64x2_t test_ret_v2f64(float64x2_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <8 x bfloat> @test_ret_v8bf16(
+// CHECK-SAME: <8 x bfloat> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <8 x bfloat> [[V]]
+//
+bfloat16x8_t test_ret_v8bf16(bfloat16x8_t v) {
+  return v;
+}
+
+// CHECK-LABEL: define dso_local <16 x i8> @test_ret_v16s8(
+// CHECK-SAME: <16 x i8> noundef returned [[V:%.*]]) local_unnamed_addr 
#[[ATTR0]] {
+// CHECK-NEXT:  entry:
+// CHECK-NEXT:ret <16 x i8> [[

[clang] 2f29ded - [analyzer] EnumCastOutOfRangeChecker: report the value (#74503)

2023-12-07 Thread via cfe-commits

Author: DonatNagyE
Date: 2023-12-07T11:38:34+01:00
New Revision: 2f29ded4f98e8e1fa26725c618a08082a09b405a

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

LOG: [analyzer] EnumCastOutOfRangeChecker: report the value (#74503)

...that is causing the bug report when it's converted to the enum type.
This commit only improves the diagnostics and does not affect the set of
reports.

Added: 


Modified: 
clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
clang/test/Analysis/enum-cast-out-of-range.cpp

Removed: 




diff  --git a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp 
b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
index 5844f43991001..14433d06c2d04 100644
--- a/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
+++ b/clang/lib/StaticAnalyzer/Checkers/EnumCastOutOfRangeChecker.cpp
@@ -22,10 +22,12 @@
 #include "clang/StaticAnalyzer/Checkers/BuiltinCheckerRegistration.h"
 #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
 #include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
+#include "llvm/Support/FormatVariadic.h"
 #include 
 
 using namespace clang;
 using namespace ento;
+using llvm::formatv;
 
 namespace {
 // This evaluator checks two SVals for equality. The first SVal is provided via
@@ -87,17 +89,22 @@ void 
EnumCastOutOfRangeChecker::reportWarning(CheckerContext &C,
   EnumValueCastOutOfRange.reset(
   new BugType(this, "Enum cast out of range"));
 
-llvm::SmallString<128> Msg{"The value provided to the cast expression is "
-   "not in the valid range of values for "};
-StringRef EnumName{E->getName()};
-if (EnumName.empty()) {
-  Msg += "the enum";
-} else {
-  Msg += '\'';
-  Msg += EnumName;
-  Msg += '\'';
+std::string ValueStr = "", NameStr = "the enum";
+
+// Try to add details to the message:
+const auto ConcreteValue =
+C.getSVal(CE->getSubExpr()).getAs();
+if (ConcreteValue) {
+  ValueStr = formatv(" '{0}'", ConcreteValue->getValue());
+}
+if (StringRef EnumName{E->getName()}; !EnumName.empty()) {
+  NameStr = formatv("'{0}'", EnumName);
 }
 
+std::string Msg = formatv("The value{0} provided to the cast expression is 
"
+  "not in the valid range of values for {1}",
+  ValueStr, NameStr);
+
 auto BR = 
std::make_unique(*EnumValueCastOutOfRange,
Msg, N);
 bugreporter::trackExpressionValue(N, CE->getSubExpr(), *BR);

diff  --git a/clang/test/Analysis/enum-cast-out-of-range.cpp 
b/clang/test/Analysis/enum-cast-out-of-range.cpp
index 0eb740664ecdc..09835d420672b 100644
--- a/clang/test/Analysis/enum-cast-out-of-range.cpp
+++ b/clang/test/Analysis/enum-cast-out-of-range.cpp
@@ -43,115 +43,115 @@ struct S {
 };
 
 void unscopedUnspecified() {
-  unscoped_unspecified_t InvalidBeforeRangeBegin = 
static_cast(-5); // expected-warning {{The value 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
+  unscoped_unspecified_t InvalidBeforeRangeBegin = 
static_cast(-5); // expected-warning {{The value '-5' 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
   unscoped_unspecified_t ValidNegativeValue1 = 
static_cast(-4); // OK.
   unscoped_unspecified_t ValidNegativeValue2 = 
static_cast(-3); // OK.
-  unscoped_unspecified_t InvalidInsideRange1 = 
static_cast(-2); // expected-warning {{The value 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
-  unscoped_unspecified_t InvalidInsideRange2 = 
static_cast(-1); // expected-warning {{The value 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
-  unscoped_unspecified_t InvalidInsideRange3 = 
static_cast(0); // expected-warning {{The value 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
+  unscoped_unspecified_t InvalidInsideRange1 = 
static_cast(-2); // expected-warning {{The value '-2' 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
+  unscoped_unspecified_t InvalidInsideRange2 = 
static_cast(-1); // expected-warning {{The value '-1' 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
+  unscoped_unspecified_t InvalidInsideRange3 = 
static_cast(0); // expected-warning {{The value '0' 
provided to the cast expression is not in the valid range of values for 
'unscoped_unspecified_t'}}
   unscoped_unspecified_t ValidPositiveValue1 = 
static_cast(1); // OK.
 

[clang] [analyzer] EnumCastOutOfRangeChecker: report the value (PR #74503)

2023-12-07 Thread via cfe-commits

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


[flang] [llvm] [clang] [openmp] [mlir] [libcxx] [clang-tools-extra] [clang-tidy] Replace memcpy with std::copy (PR #74663)

2023-12-07 Thread Giovanni Martins via cfe-commits

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Ben Shi via cfe-commits

benshi001 wrote:

I can not understand why the new test `error_fflush_1` failed on windows, it 
did succeed on my local linux. So shall we 
1. Add a `#if _win32` in the test?
2. Or only commit `fflush(not_null_stream) == 0` part, and leave `fflush(NULL) 
== 0` in the next patch?

I hope the second one, at least we can break down this change.

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


[clang-tools-extra] [clangd] Add tweak to abbreviate function templates (PR #74710)

2023-12-07 Thread Jeremy Stucki via cfe-commits

https://github.com/jeremystucki created 
https://github.com/llvm/llvm-project/pull/74710

# Description

This introduces a new refactoring for function templates. It converts them to 
their abbreviated form using auto parameters.

Here is an example of what it does:

**Before**
```cpp
template 
void foo(T, U, V... params);
```
**After**
```cpp
void foo(auto, std::integral auto, auto... params);
```

# Demo

[Screencast from 2023-12-07 
10-44-46.webm](https://github.com/sa-concept-refactoring/llvm-project/assets/7629727/8d5f2bf1-03ce-4644-9311-1b3942594adc)


>From b0507f05e5b2fa4d840757b8d7fce1b60df626ec Mon Sep 17 00:00:00 2001
From: Jeremy Stucki 
Date: Fri, 27 Oct 2023 16:33:13 +0200
Subject: [PATCH] [clangd] Add tweak to abbreviate function templates

Co-authored-by: Vina Zahnd 
---
 .../tweaks/AbbreviateFunctionTemplate.cpp | 352 ++
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../AbbreviateFunctionTemplateTests.cpp   |  76 
 clang-tools-extra/docs/ReleaseNotes.rst   |   3 +
 5 files changed, 433 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/AbbreviateFunctionTemplateTests.cpp

diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
new file mode 100644
index 0..a2cfc6e13b01f
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
@@ -0,0 +1,352 @@
+//===-- AbbreviateFunctionTemplate.cpp ---*- 
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
+//
+//===--===//
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Converts a function template to its abbreviated form using auto parameters.
+/// Before:
+/// template 
+/// auto foo(T param) { }
+///  ^^^
+/// After:
+/// auto foo(std::integral auto param) { }
+class AbbreviateFunctionTemplate : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+
+  auto title() const -> std::string override {
+return llvm::formatv("Abbreviate function template");
+  }
+
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  static const char *AutoKeywordSpelling;
+  const FunctionTemplateDecl *FunctionTemplateDeclaration;
+
+  struct TemplateParameterInfo {
+const TypeConstraint *Constraint;
+unsigned int FunctionParameterIndex;
+std::vector FunctionParameterQualifiers;
+std::vector FunctionParameterTypeQualifiers;
+  };
+
+  std::vector TemplateParameterInfoList;
+
+  auto traverseFunctionParameters(size_t NumberOfTemplateParameters) -> bool;
+
+  auto generateFunctionParameterReplacements(const ASTContext &Context)
+  -> llvm::Expected;
+
+  auto generateFunctionParameterReplacement(
+  const TemplateParameterInfo &TemplateParameterInfo,
+  const ASTContext &Context) -> llvm::Expected;
+
+  auto generateTemplateDeclarationReplacement(const ASTContext &Context)
+  -> llvm::Expected;
+
+  static auto deconstructType(QualType Type)
+  -> std::tuple,
+std::vector>;
+};
+
+REGISTER_TWEAK(AbbreviateFunctionTemplate)
+
+const char *AbbreviateFunctionTemplate::AutoKeywordSpelling =
+getKeywordSpelling(tok::kw_auto);
+
+template 
+auto findDeclaration(const SelectionTree::Node &Root) -> const T * {
+  for (const auto *Node = &Root; Node; Node = Node->Parent) {
+if (const T *Result = dyn_cast_or_null(Node->ASTNode.get()))
+  return Result;
+  }
+
+  return nullptr;
+}
+
+auto getSpellingForQualifier(tok::TokenKind const &Qualifier) -> const char * {
+  if (const auto *Spelling = getKeywordSpelling(Qualifier))
+return Spelling;
+
+  if (const auto *Spelling = getPunctuatorSpelling(Qualifier))
+return Spelling;
+
+  return nullptr;
+}
+
+bool AbbreviateFunctionTemplate::prepare(const Selection &Inputs) {
+  const auto *CommonAncestor = Inputs.ASTSelection.commonAncestor();
+  if (!CommonAncestor)
+return false;
+
+  FunctionTemplateDeclaration =
+  findDeclaration(*CommonAncestor);
+
+  if (!Function

[clang-tools-extra] [clangd] Add tweak to abbreviate function templates (PR #74710)

2023-12-07 Thread via cfe-commits

llvmbot wrote:




@llvm/pr-subscribers-clangd

Author: Jeremy Stucki (jeremystucki)


Changes

# Description

This introduces a new refactoring for function templates. It converts them to 
their abbreviated form using auto parameters.

Here is an example of what it does:

**Before**
```cpp
template 
void foo(T, U, V... params);
```
**After**
```cpp
void foo(auto, std::integral auto, auto... params);
```

# Demo

[Screencast from 2023-12-07 
10-44-46.webm](https://github.com/sa-concept-refactoring/llvm-project/assets/7629727/8d5f2bf1-03ce-4644-9311-1b3942594adc)


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


5 Files Affected:

- (added) 
clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp (+352) 
- (modified) clang-tools-extra/clangd/refactor/tweaks/CMakeLists.txt (+1) 
- (modified) clang-tools-extra/clangd/unittests/CMakeLists.txt (+1) 
- (added) 
clang-tools-extra/clangd/unittests/tweaks/AbbreviateFunctionTemplateTests.cpp 
(+76) 
- (modified) clang-tools-extra/docs/ReleaseNotes.rst (+3) 


``diff
diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
new file mode 100644
index 0..a2cfc6e13b01f
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
@@ -0,0 +1,352 @@
+//===-- AbbreviateFunctionTemplate.cpp ---*- 
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
+//
+//===--===//
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Converts a function template to its abbreviated form using auto parameters.
+/// Before:
+/// template 
+/// auto foo(T param) { }
+///  ^^^
+/// After:
+/// auto foo(std::integral auto param) { }
+class AbbreviateFunctionTemplate : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+
+  auto title() const -> std::string override {
+return llvm::formatv("Abbreviate function template");
+  }
+
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  static const char *AutoKeywordSpelling;
+  const FunctionTemplateDecl *FunctionTemplateDeclaration;
+
+  struct TemplateParameterInfo {
+const TypeConstraint *Constraint;
+unsigned int FunctionParameterIndex;
+std::vector FunctionParameterQualifiers;
+std::vector FunctionParameterTypeQualifiers;
+  };
+
+  std::vector TemplateParameterInfoList;
+
+  auto traverseFunctionParameters(size_t NumberOfTemplateParameters) -> bool;
+
+  auto generateFunctionParameterReplacements(const ASTContext &Context)
+  -> llvm::Expected;
+
+  auto generateFunctionParameterReplacement(
+  const TemplateParameterInfo &TemplateParameterInfo,
+  const ASTContext &Context) -> llvm::Expected;
+
+  auto generateTemplateDeclarationReplacement(const ASTContext &Context)
+  -> llvm::Expected;
+
+  static auto deconstructType(QualType Type)
+  -> std::tuple,
+std::vector>;
+};
+
+REGISTER_TWEAK(AbbreviateFunctionTemplate)
+
+const char *AbbreviateFunctionTemplate::AutoKeywordSpelling =
+getKeywordSpelling(tok::kw_auto);
+
+template 
+auto findDeclaration(const SelectionTree::Node &Root) -> const T * {
+  for (const auto *Node = &Root; Node; Node = Node->Parent) {
+if (const T *Result = dyn_cast_or_null(Node->ASTNode.get()))
+  return Result;
+  }
+
+  return nullptr;
+}
+
+auto getSpellingForQualifier(tok::TokenKind const &Qualifier) -> const char * {
+  if (const auto *Spelling = getKeywordSpelling(Qualifier))
+return Spelling;
+
+  if (const auto *Spelling = getPunctuatorSpelling(Qualifier))
+return Spelling;
+
+  return nullptr;
+}
+
+bool AbbreviateFunctionTemplate::prepare(const Selection &Inputs) {
+  const auto *CommonAncestor = Inputs.ASTSelection.commonAncestor();
+  if (!CommonAncestor)
+return false;
+
+  FunctionTemplateDeclaration =
+  findDeclaration(*CommonAncestor);
+
+  if (!FunctionTemplateDeclaration)
+return false;
+
+  auto *TemplateParameters =
+  FunctionTemplateDeclaration->getTemplateParameters();
+
+  auto NumberOfTemplateParameters = TemplateParameters->size();
+  Templat

[clang-tools-extra] [clangd] Add tweak to abbreviate function templates (PR #74710)

2023-12-07 Thread Jeremy Stucki via cfe-commits

https://github.com/jeremystucki updated 
https://github.com/llvm/llvm-project/pull/74710

>From b3ae4235ccca0b2c859b33f7d12ee7940daabd1a Mon Sep 17 00:00:00 2001
From: Jeremy Stucki 
Date: Fri, 27 Oct 2023 16:33:13 +0200
Subject: [PATCH] [clangd] Add tweak to abbreviate function templates

Co-authored-by: Vina Zahnd 
---
 .../tweaks/AbbreviateFunctionTemplate.cpp | 352 ++
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../AbbreviateFunctionTemplateTests.cpp   |  76 
 clang-tools-extra/docs/ReleaseNotes.rst   |   3 +
 5 files changed, 433 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/AbbreviateFunctionTemplateTests.cpp

diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
new file mode 100644
index 0..a2cfc6e13b01f
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
@@ -0,0 +1,352 @@
+//===-- AbbreviateFunctionTemplate.cpp ---*- 
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
+//
+//===--===//
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Converts a function template to its abbreviated form using auto parameters.
+/// Before:
+/// template 
+/// auto foo(T param) { }
+///  ^^^
+/// After:
+/// auto foo(std::integral auto param) { }
+class AbbreviateFunctionTemplate : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+
+  auto title() const -> std::string override {
+return llvm::formatv("Abbreviate function template");
+  }
+
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  static const char *AutoKeywordSpelling;
+  const FunctionTemplateDecl *FunctionTemplateDeclaration;
+
+  struct TemplateParameterInfo {
+const TypeConstraint *Constraint;
+unsigned int FunctionParameterIndex;
+std::vector FunctionParameterQualifiers;
+std::vector FunctionParameterTypeQualifiers;
+  };
+
+  std::vector TemplateParameterInfoList;
+
+  auto traverseFunctionParameters(size_t NumberOfTemplateParameters) -> bool;
+
+  auto generateFunctionParameterReplacements(const ASTContext &Context)
+  -> llvm::Expected;
+
+  auto generateFunctionParameterReplacement(
+  const TemplateParameterInfo &TemplateParameterInfo,
+  const ASTContext &Context) -> llvm::Expected;
+
+  auto generateTemplateDeclarationReplacement(const ASTContext &Context)
+  -> llvm::Expected;
+
+  static auto deconstructType(QualType Type)
+  -> std::tuple,
+std::vector>;
+};
+
+REGISTER_TWEAK(AbbreviateFunctionTemplate)
+
+const char *AbbreviateFunctionTemplate::AutoKeywordSpelling =
+getKeywordSpelling(tok::kw_auto);
+
+template 
+auto findDeclaration(const SelectionTree::Node &Root) -> const T * {
+  for (const auto *Node = &Root; Node; Node = Node->Parent) {
+if (const T *Result = dyn_cast_or_null(Node->ASTNode.get()))
+  return Result;
+  }
+
+  return nullptr;
+}
+
+auto getSpellingForQualifier(tok::TokenKind const &Qualifier) -> const char * {
+  if (const auto *Spelling = getKeywordSpelling(Qualifier))
+return Spelling;
+
+  if (const auto *Spelling = getPunctuatorSpelling(Qualifier))
+return Spelling;
+
+  return nullptr;
+}
+
+bool AbbreviateFunctionTemplate::prepare(const Selection &Inputs) {
+  const auto *CommonAncestor = Inputs.ASTSelection.commonAncestor();
+  if (!CommonAncestor)
+return false;
+
+  FunctionTemplateDeclaration =
+  findDeclaration(*CommonAncestor);
+
+  if (!FunctionTemplateDeclaration)
+return false;
+
+  auto *TemplateParameters =
+  FunctionTemplateDeclaration->getTemplateParameters();
+
+  auto NumberOfTemplateParameters = TemplateParameters->size();
+  TemplateParameterInfoList =
+  std::vector(NumberOfTemplateParameters);
+
+  // Check how many times each template parameter is referenced.
+  // Depending on the number of references it can be checked
+  // if the refactoring is possible:
+  // - exactly one: The tem

[clang-tools-extra] [flang] [compiler-rt] [llvm] [clang] [PowerPC][CodeGen] Exploit STMW and LMW in 32-bit big-endian mode. (PR #74415)

2023-12-07 Thread Chen Zheng via cfe-commits


@@ -2399,6 +2405,29 @@ bool PPCFrameLowering::assignCalleeSavedSpillSlots(
   return AllSpilledToReg;
 }
 
+static void findContinuousLoadStore(ArrayRef CSI,
+Register &MergeFrom) {
+  unsigned I = 1, E = CSI.size(), BeginI = 0;
+  for (; I < E; ++I) {
+// Find continuous store/load.
+int RegDiff = CSI[I].getReg() - CSI[I - 1].getReg();
+int FrameIdxDiff = CSI[I - 1].getFrameIdx() - CSI[I].getFrameIdx();
+Register BeginReg = CSI[BeginI].getReg();
+if (BeginReg < PPC::R0 || BeginReg > PPC::R31 ||
+CSI[BeginI].isSpilledToReg() || RegDiff != 1 || FrameIdxDiff != 1)
+  BeginI = I;
+if (CSI[I].getReg() == PPC::R31)
+  break;
+  }
+
+  if (I == E || CSI[BeginI].getReg() >= PPC::R31)
+return;
+
+  // Record the first reg that STMW/LMW are going to merge since STMW/LMW save
+  // from rN to r31.
+  MergeFrom = CSI[BeginI].getReg();

chenzheng1030 wrote:

This is unnecessary complicating. LMW/STMW only applies for AIX 32-bit. For 
AIX, we just need to find the first GPR(assume the CSI is sorted on ascending 
ordering), that would be the MergeFrom. On AIX, CSRs always contain the lowest 
GPR till R31.

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1191,6 +1199,84 @@ void StreamChecker::evalSetFeofFerror(const 
FnDescription *Desc,
   C.addTransition(State);
 }
 
+void StreamChecker::preFflush(const FnDescription *Desc, const CallEvent &Call,
+  CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  SymbolRef StreamSym = StreamVal.getAsSymbol();
+  if (!Stream || !StreamSym)
+return;
+
+  ProgramStateRef StateNotNull, StateNull;
+  std::tie(StateNotNull, StateNull) =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (StateNotNull)
+if (State = ensureStreamOpened(StreamVal, C, StateNotNull))
+  C.addTransition(State);
+  if (StateNull) {
+const StreamState *SS = StateNull->get(StreamSym);
+if (!SS || !SS->isOpenFailed()) {
+  StateNull = StateNull->set(StreamSym,
+StreamState::getOpenFailed(Desc));
+  if (StateNull)
+C.addTransition(StateNull);
+}
+  }
+}
+
+void StreamChecker::evalFflush(const FnDescription *Desc, const CallEvent 
&Call,
+   CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+
+  // We will check the result even if the input is `NULL`,
+  // but do nothing if the input state is unknown.
+  SymbolRef StreamSym = getStreamArg(Desc, Call).getAsSymbol();
+  const StreamState *SS;
+  if (StreamSym) {
+if (!(SS = State->get(StreamSym)))
+  return;
+assert((SS->isOpened() || SS->isOpenFailed()) &&
+   "Stream is expected to opened or open-failed");
+  }
+
+  const CallExpr *CE = dyn_cast_or_null(Call.getOriginExpr());
+  if (!CE)
+return;
+
+  // `fflush` returns EOF on failure, otherwise returns 0.
+  ProgramStateRef StateFailed = bindInt(*EofVal, State, C, CE);
+  C.addTransition(StateFailed);
+
+  // Clear error states if `fflush` returns 0, but retain their EOF flags.
+  ProgramStateRef StateNotFailed = bindInt(0, State, C, CE);
+  auto ClearError = [&StateNotFailed, Desc](SymbolRef Sym,
+const StreamState *SS) {
+if (SS->ErrorState & ErrorFError) {
+  StreamErrorState NewES =
+  (SS->ErrorState & ErrorFEof) ? ErrorFEof : ErrorNone;
+  StreamState NewSS = StreamState::getOpened(Desc, NewES, false);
+  StateNotFailed = StateNotFailed->set(Sym, NewSS);
+}
+  };
+
+  if (SS->isOpened()) {

alejandro-alvarez-sonarsource wrote:

Unless I am mistaken, `SS` can be uninitialized here. If `StreamSym` is `NULL`, 
SS does not get initialized.

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


[clang-tools-extra] [clangd] Add tweak to abbreviate function templates (PR #74710)

2023-12-07 Thread Jeremy Stucki via cfe-commits

https://github.com/jeremystucki updated 
https://github.com/llvm/llvm-project/pull/74710

>From b0b22b716bfc60274814cedc82c237d13477869c Mon Sep 17 00:00:00 2001
From: Jeremy Stucki 
Date: Fri, 27 Oct 2023 16:33:13 +0200
Subject: [PATCH] [clangd] Add tweak to abbreviate function templates

Co-authored-by: Vina Zahnd 
---
 .../tweaks/AbbreviateFunctionTemplate.cpp | 352 ++
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../AbbreviateFunctionTemplateTests.cpp   |  76 
 clang-tools-extra/docs/ReleaseNotes.rst   |   3 +
 5 files changed, 433 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/AbbreviateFunctionTemplateTests.cpp

diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
new file mode 100644
index 0..a2cfc6e13b01f
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
@@ -0,0 +1,352 @@
+//===-- AbbreviateFunctionTemplate.cpp ---*- 
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
+//
+//===--===//
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Converts a function template to its abbreviated form using auto parameters.
+/// Before:
+/// template 
+/// auto foo(T param) { }
+///  ^^^
+/// After:
+/// auto foo(std::integral auto param) { }
+class AbbreviateFunctionTemplate : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+
+  auto title() const -> std::string override {
+return llvm::formatv("Abbreviate function template");
+  }
+
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  static const char *AutoKeywordSpelling;
+  const FunctionTemplateDecl *FunctionTemplateDeclaration;
+
+  struct TemplateParameterInfo {
+const TypeConstraint *Constraint;
+unsigned int FunctionParameterIndex;
+std::vector FunctionParameterQualifiers;
+std::vector FunctionParameterTypeQualifiers;
+  };
+
+  std::vector TemplateParameterInfoList;
+
+  auto traverseFunctionParameters(size_t NumberOfTemplateParameters) -> bool;
+
+  auto generateFunctionParameterReplacements(const ASTContext &Context)
+  -> llvm::Expected;
+
+  auto generateFunctionParameterReplacement(
+  const TemplateParameterInfo &TemplateParameterInfo,
+  const ASTContext &Context) -> llvm::Expected;
+
+  auto generateTemplateDeclarationReplacement(const ASTContext &Context)
+  -> llvm::Expected;
+
+  static auto deconstructType(QualType Type)
+  -> std::tuple,
+std::vector>;
+};
+
+REGISTER_TWEAK(AbbreviateFunctionTemplate)
+
+const char *AbbreviateFunctionTemplate::AutoKeywordSpelling =
+getKeywordSpelling(tok::kw_auto);
+
+template 
+auto findDeclaration(const SelectionTree::Node &Root) -> const T * {
+  for (const auto *Node = &Root; Node; Node = Node->Parent) {
+if (const T *Result = dyn_cast_or_null(Node->ASTNode.get()))
+  return Result;
+  }
+
+  return nullptr;
+}
+
+auto getSpellingForQualifier(tok::TokenKind const &Qualifier) -> const char * {
+  if (const auto *Spelling = getKeywordSpelling(Qualifier))
+return Spelling;
+
+  if (const auto *Spelling = getPunctuatorSpelling(Qualifier))
+return Spelling;
+
+  return nullptr;
+}
+
+bool AbbreviateFunctionTemplate::prepare(const Selection &Inputs) {
+  const auto *CommonAncestor = Inputs.ASTSelection.commonAncestor();
+  if (!CommonAncestor)
+return false;
+
+  FunctionTemplateDeclaration =
+  findDeclaration(*CommonAncestor);
+
+  if (!FunctionTemplateDeclaration)
+return false;
+
+  auto *TemplateParameters =
+  FunctionTemplateDeclaration->getTemplateParameters();
+
+  auto NumberOfTemplateParameters = TemplateParameters->size();
+  TemplateParameterInfoList =
+  std::vector(NumberOfTemplateParameters);
+
+  // Check how many times each template parameter is referenced.
+  // Depending on the number of references it can be checked
+  // if the refactoring is possible:
+  // - exactly one: The tem

[clang-tools-extra] [clang] [llvm] [compiler-rt] [flang] [PowerPC][CodeGen] Exploit STMW and LMW in 32-bit big-endian mode. (PR #74415)

2023-12-07 Thread Chen Zheng via cfe-commits


@@ -0,0 +1,138 @@
+; RUN: llc -mtriple=powerpc-unknown-aix-xcoff -verify-machineinstrs \
+; RUN: -mcpu=pwr4 -mattr=-altivec --ppc-enable-load-store-multiple < %s \
+; RUN: | FileCheck %s
+
+; CHECK:  # %bb.0:# %entry
+; CHECK-NEXT:  mflr 0
+; CHECK-NEXT:  stwu 1, -128(1)
+; CHECK-NEXT:  cmpwi   5, 0
+; CHECK-NEXT:  stw 0, 136(1)
+; CHECK-NEXT:  stmw 16, 64(1)  # 4-byte Folded Spill
+; CHECK-NEXT:  ble 0, L..BB0_11
+
+; CHECK:  L..BB0_12:  # %for.cond.cleanup
+; CHECK-NEXT:  lwz 3, L..C0(2) # @a
+; CHECK-NEXT:  lwz 4, L..C1(2) # @b
+; CHECK-NEXT:  lwz 5, L..C4(2) # @c
+; CHECK-NEXT:  lwz 6, L..C7(2) # @d
+; CHECK-NEXT:  lwz 7, L..C6(2) # @e
+; CHECK-NEXT:  lmw 16, 64(1)   # 4-byte Folded Reload
+; CHECK-NEXT:  lwz 3, 0(3)
+; CHECK-NEXT:  lwz 4, 0(4)
+; CHECK-NEXT:  add 3, 3, 28
+; CHECK-NEXT:  lwz 5, 0(5)
+; CHECK-NEXT:  add 3, 3, 4
+; CHECK-NEXT:  lwz 6, 0(6)
+; CHECK-NEXT:  add 3, 3, 5
+; CHECK-NEXT:  lwz 4, 0(7)
+; CHECK-NEXT:  add 3, 3, 6
+; CHECK-NEXT:  add 3, 3, 4
+; CHECK-NEXT:  lwz 31, 124(1)  # 4-byte Folded Reload
+; CHECK-NEXT:  addi 1, 1, 128
+; CHECK-NEXT:  lwz 0, 8(1)
+; CHECK-NEXT:  mtlr 0
+; CHECK-NEXT:  bl
+
+@a = external local_unnamed_addr global i32, align 4

chenzheng1030 wrote:

case is too complicated. Please use below one

```
define dso_local void @test_simple() #0 {
entry:
  call void asm sideeffect "nop", "~{r13}"()
  ret void
}
```

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


[clang-tools-extra] [clang] [llvm] [compiler-rt] [flang] [PowerPC][CodeGen] Exploit STMW and LMW in 32-bit big-endian mode. (PR #74415)

2023-12-07 Thread Chen Zheng via cfe-commits

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


[clang] [clang][analyzer] Support `fflush` in the StreamChecker (PR #74296)

2023-12-07 Thread Alejandro Álvarez Ayllón via cfe-commits


@@ -1191,6 +1199,84 @@ void StreamChecker::evalSetFeofFerror(const 
FnDescription *Desc,
   C.addTransition(State);
 }
 
+void StreamChecker::preFflush(const FnDescription *Desc, const CallEvent &Call,
+  CheckerContext &C) const {
+  ProgramStateRef State = C.getState();
+  SVal StreamVal = getStreamArg(Desc, Call);
+  std::optional Stream = StreamVal.getAs();
+  SymbolRef StreamSym = StreamVal.getAsSymbol();
+  if (!Stream || !StreamSym)
+return;
+
+  ProgramStateRef StateNotNull, StateNull;
+  std::tie(StateNotNull, StateNull) =
+  C.getConstraintManager().assumeDual(State, *Stream);
+  if (StateNotNull)
+if (State = ensureStreamOpened(StreamVal, C, StateNotNull))
+  C.addTransition(State);
+  if (StateNull) {

alejandro-alvarez-sonarsource wrote:

Due to this transition, these two test cases will behave differently:

```cpp
void test_fflush_2(FILE *F1) {
  fflush(F1);
  // Due to fflush, the analyzer follows a path where F1 is NULL, and another 
where it isn't.
  // Raises a "Stream pointer might be NULL" on the next line
  if (fwrite("1", 1, 1, F1) == 0)
return;
  fclose(F1);
}

void test_fflush_3(FILE *F1) {
  // no fflush, the warning does not raise
  if (fwrite("1", 1, 1, F1) == 0)
return;
  fclose(F1);
}
```

I feel this could be noisy. What do you think about adding the StateNull 
transition if, and only if, FILE* can be `NULL`?

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


[llvm] [clang-tools-extra] [compiler-rt] [flang] [clang] [PowerPC][CodeGen] Exploit STMW and LMW in 32-bit big-endian mode. (PR #74415)

2023-12-07 Thread Chen Zheng via cfe-commits


@@ -40,6 +40,12 @@ EnablePEVectorSpills("ppc-enable-pe-vector-spills",
  cl::desc("Enable spills in prologue to vector 
registers."),
  cl::init(false), cl::Hidden);
 
+static cl::opt
+EnableLoadStoreMultiple("ppc-enable-load-store-multiple",
+cl::desc("Enable load/store multiple (only "
+ "support in 32-bit big-endian mode)."),

chenzheng1030 wrote:

Instead of 32-bit big-endian, maybe it is better to limit this under AIX-32 bit.

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


[clang-tools-extra] [clangd] Add tweak to abbreviate function templates (PR #74710)

2023-12-07 Thread Jeremy Stucki via cfe-commits

https://github.com/jeremystucki updated 
https://github.com/llvm/llvm-project/pull/74710

>From 64573476024103cf94f6cfc690e5396a368fc3df Mon Sep 17 00:00:00 2001
From: Jeremy Stucki 
Date: Fri, 27 Oct 2023 16:33:13 +0200
Subject: [PATCH] [clangd] Add tweak to abbreviate function templates

Co-authored-by: Vina Zahnd 
---
 .../tweaks/AbbreviateFunctionTemplate.cpp | 352 ++
 .../clangd/refactor/tweaks/CMakeLists.txt |   1 +
 .../clangd/unittests/CMakeLists.txt   |   1 +
 .../AbbreviateFunctionTemplateTests.cpp   |  76 
 clang-tools-extra/docs/ReleaseNotes.rst   |   3 +
 5 files changed, 433 insertions(+)
 create mode 100644 
clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
 create mode 100644 
clang-tools-extra/clangd/unittests/tweaks/AbbreviateFunctionTemplateTests.cpp

diff --git 
a/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp 
b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
new file mode 100644
index 0..a2cfc6e13b01f
--- /dev/null
+++ b/clang-tools-extra/clangd/refactor/tweaks/AbbreviateFunctionTemplate.cpp
@@ -0,0 +1,352 @@
+//===-- AbbreviateFunctionTemplate.cpp ---*- 
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
+//
+//===--===//
+#include "FindTarget.h"
+#include "SourceCode.h"
+#include "XRefs.h"
+#include "refactor/Tweak.h"
+#include "support/Logger.h"
+#include "clang/AST/ASTContext.h"
+#include "clang/AST/ExprConcepts.h"
+#include "clang/Tooling/Core/Replacement.h"
+#include "llvm/ADT/StringRef.h"
+#include "llvm/Support/Casting.h"
+#include "llvm/Support/Error.h"
+#include 
+
+namespace clang {
+namespace clangd {
+namespace {
+/// Converts a function template to its abbreviated form using auto parameters.
+/// Before:
+/// template 
+/// auto foo(T param) { }
+///  ^^^
+/// After:
+/// auto foo(std::integral auto param) { }
+class AbbreviateFunctionTemplate : public Tweak {
+public:
+  const char *id() const final;
+
+  auto prepare(const Selection &Inputs) -> bool override;
+  auto apply(const Selection &Inputs) -> Expected override;
+
+  auto title() const -> std::string override {
+return llvm::formatv("Abbreviate function template");
+  }
+
+  auto kind() const -> llvm::StringLiteral override {
+return CodeAction::REFACTOR_KIND;
+  }
+
+private:
+  static const char *AutoKeywordSpelling;
+  const FunctionTemplateDecl *FunctionTemplateDeclaration;
+
+  struct TemplateParameterInfo {
+const TypeConstraint *Constraint;
+unsigned int FunctionParameterIndex;
+std::vector FunctionParameterQualifiers;
+std::vector FunctionParameterTypeQualifiers;
+  };
+
+  std::vector TemplateParameterInfoList;
+
+  auto traverseFunctionParameters(size_t NumberOfTemplateParameters) -> bool;
+
+  auto generateFunctionParameterReplacements(const ASTContext &Context)
+  -> llvm::Expected;
+
+  auto generateFunctionParameterReplacement(
+  const TemplateParameterInfo &TemplateParameterInfo,
+  const ASTContext &Context) -> llvm::Expected;
+
+  auto generateTemplateDeclarationReplacement(const ASTContext &Context)
+  -> llvm::Expected;
+
+  static auto deconstructType(QualType Type)
+  -> std::tuple,
+std::vector>;
+};
+
+REGISTER_TWEAK(AbbreviateFunctionTemplate)
+
+const char *AbbreviateFunctionTemplate::AutoKeywordSpelling =
+getKeywordSpelling(tok::kw_auto);
+
+template 
+auto findDeclaration(const SelectionTree::Node &Root) -> const T * {
+  for (const auto *Node = &Root; Node; Node = Node->Parent) {
+if (const T *Result = dyn_cast_or_null(Node->ASTNode.get()))
+  return Result;
+  }
+
+  return nullptr;
+}
+
+auto getSpellingForQualifier(tok::TokenKind const &Qualifier) -> const char * {
+  if (const auto *Spelling = getKeywordSpelling(Qualifier))
+return Spelling;
+
+  if (const auto *Spelling = getPunctuatorSpelling(Qualifier))
+return Spelling;
+
+  return nullptr;
+}
+
+bool AbbreviateFunctionTemplate::prepare(const Selection &Inputs) {
+  const auto *CommonAncestor = Inputs.ASTSelection.commonAncestor();
+  if (!CommonAncestor)
+return false;
+
+  FunctionTemplateDeclaration =
+  findDeclaration(*CommonAncestor);
+
+  if (!FunctionTemplateDeclaration)
+return false;
+
+  auto *TemplateParameters =
+  FunctionTemplateDeclaration->getTemplateParameters();
+
+  auto NumberOfTemplateParameters = TemplateParameters->size();
+  TemplateParameterInfoList =
+  std::vector(NumberOfTemplateParameters);
+
+  // Check how many times each template parameter is referenced.
+  // Depending on the number of references it can be checked
+  // if the refactoring is possible:
+  // - exactly one: The tem

[llvm] [clang-tools-extra] [openmp] [libcxx] [mlir] [flang] [clang] [clang-tidy] Replace memcpy with std::copy (PR #74663)

2023-12-07 Thread Giovanni Martins via cfe-commits

https://github.com/giovannism20 updated 
https://github.com/llvm/llvm-project/pull/74663

>From 992fd1fbc3568116da55c6b7cb40831757e4da6b Mon Sep 17 00:00:00 2001
From: Giovanni Martins 
Date: Wed, 6 Dec 2023 11:26:53 -0300
Subject: [PATCH 1/6] replace memcpy with std::copy on clang-tidy

---
 .../clang-tidy/modernize/CMakeLists.txt   |   1 +
 .../modernize/ModernizeTidyModule.cpp |   3 +
 .../modernize/ReplaceMemcpyWithStdCopy.cpp| 117 ++
 .../modernize/ReplaceMemcpyWithStdCopy.h  |  48 +++
 clang-tools-extra/docs/ReleaseNotes.rst   |   5 +
 .../docs/clang-tidy/checks/list.rst   |   1 +
 .../modernize-replace-memcpy-with-stdcopy.rst |  47 +++
 7 files changed, 222 insertions(+)
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/ReplaceMemcpyWithStdCopy.cpp
 create mode 100644 
clang-tools-extra/clang-tidy/modernize/ReplaceMemcpyWithStdCopy.h
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/modernize/modernize-replace-memcpy-with-stdcopy.rst

diff --git a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt 
b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
index c40065358d2dc..d0a996d3be729 100644
--- a/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
+++ b/clang-tools-extra/clang-tidy/modernize/CMakeLists.txt
@@ -22,6 +22,7 @@ add_clang_library(clangTidyModernizeModule
   RedundantVoidArgCheck.cpp
   ReplaceAutoPtrCheck.cpp
   ReplaceDisallowCopyAndAssignMacroCheck.cpp
+  ReplaceMemcpyWithStdCopy.cpp
   ReplaceRandomShuffleCheck.cpp
   ReturnBracedInitListCheck.cpp
   ShrinkToFitCheck.cpp
diff --git a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp 
b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
index e994ffd2a75c8..590005c0ff371 100644
--- a/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/modernize/ModernizeTidyModule.cpp
@@ -22,6 +22,7 @@
 #include "RawStringLiteralCheck.h"
 #include "RedundantVoidArgCheck.h"
 #include "ReplaceAutoPtrCheck.h"
+#include "ReplaceMemcpyWithStdCopy.h"
 #include "ReplaceDisallowCopyAndAssignMacroCheck.h"
 #include "ReplaceRandomShuffleCheck.h"
 #include "ReturnBracedInitListCheck.h"
@@ -78,6 +79,8 @@ class ModernizeModule : public ClangTidyModule {
 "modernize-replace-auto-ptr");
 CheckFactories.registerCheck(
 "modernize-replace-disallow-copy-and-assign-macro");
+CheckFactories.registerCheck(
+"modernize-replace-memcpy-by-stdcopy");
 CheckFactories.registerCheck(
 "modernize-replace-random-shuffle");
 CheckFactories.registerCheck(
diff --git 
a/clang-tools-extra/clang-tidy/modernize/ReplaceMemcpyWithStdCopy.cpp 
b/clang-tools-extra/clang-tidy/modernize/ReplaceMemcpyWithStdCopy.cpp
new file mode 100644
index 0..5a635d22d9a33
--- /dev/null
+++ b/clang-tools-extra/clang-tidy/modernize/ReplaceMemcpyWithStdCopy.cpp
@@ -0,0 +1,117 @@
+//===--- ReplaceMemcpyByStdCopy.cpp - clang-tidy--*- 
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
+//
+//===--===//
+
+#include "ReplaceMemcpyByStdCopy.h"
+#include "../utils/OptionsUtils.h"
+#include 
+
+using namespace clang;
+using namespace clang::ast_matchers;
+
+namespace clang {
+namespace tidy {
+namespace modernize {
+
+ReplaceMemcpyByStdCopy::ReplaceMemcpyByStdCopy(StringRef Name,
+   ClangTidyContext *Context)
+: ClangTidyCheck(Name, Context),
+  IncludeStyle(utils::IncludeSorter::parseIncludeStyle(
+  Options.getLocalOrGlobal("IncludeStyle", "llvm"))) {}
+
+void ReplaceMemcpyByStdCopy::registerMatchers(MatchFinder *Finder) {
+  assert(Finder != nullptr);
+
+  if (!getLangOpts().CPlusPlus)
+return;
+
+  auto MemcpyMatcher =
+  callExpr(hasDeclaration(functionDecl(hasName("memcpy"),
+   isExpansionInSystemHeader())),
+   isExpansionInMainFile())
+  .bind("memcpy_function");
+
+  Finder->addMatcher(MemcpyMatcher, this);
+}
+
+void ReplaceMemcpyByStdCopy::registerPPCallbacks(
+const SourceManager &SM, Preprocessor *PP, Preprocessor *ModuleExpanderPP) 
{
+  if (!getLangOpts().CPlusPlus)
+return;
+
+  Inserter = llvm::make_unique(SM, getLangOpts(),
+   IncludeStyle);
+  PP->addPPCallbacks(Inserter->CreatePPCallbacks());
+}
+
+void ReplaceMemcpyByStdCopy::check(const MatchFinder::MatchResult &Result) {
+  const auto *MemcpyNode = Result.Nodes.getNodeAs("memcpy_function");
+  assert(MemcpyNode != nullptr);
+
+  DiagnosticBuilder Diag =
+  diag(MemcpyNode->getExprLoc(), "use std::copy instead of memcpy");
+
+  renameFunction(Diag, MemcpyNode);
+  reorderArgs(Diag, MemcpyNo

[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-07 Thread Felix via cfe-commits


@@ -2058,6 +2089,10 @@ void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
 }
   }
 
+  // Do not emit the _$TLSML symbol.
+  if (GVSym->getName() == "_Renamed..5f24__TLSML[TC]")

orcguru wrote:

I think `MCContext::createXCOFFSymbolImpl` is the logic that replaced the 
invalid characters. According to ASCII table, `_$` maps to `5f24`.

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-07 Thread Felix via cfe-commits


@@ -2058,6 +2089,10 @@ void PPCAIXAsmPrinter::emitLinkage(const GlobalValue *GV,
 }
   }
 
+  // Do not emit the _$TLSML symbol.
+  if (GVSym->getName() == "_Renamed..5f24__TLSML[TC]")

orcguru wrote:

I think `MCContext::createXCOFFSymbolImpl` is the logic that replaced the 
invalid characters. According to ASCII table, `_$` maps to `5f24`...

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


[clang] [llvm] [PowerPC] Support local-dynamic TLS relocation on AIX (PR #66316)

2023-12-07 Thread Felix via cfe-commits

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


[clang] [Clang] Mark WG14 N2939 (Identifier Syntax Fixes) as available in Clang 15 (PR #74666)

2023-12-07 Thread Aaron Ballman via cfe-commits

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


[clang] [Clang] Mark WG14 N2939 (Identifier Syntax Fixes) as available in Clang 15 (PR #74666)

2023-12-07 Thread Aaron Ballman via cfe-commits


@@ -0,0 +1,83 @@
+// RUN: %clang_cc1 -x c -std=c2x -fsyntax-only -verify %s
+// RUN: %clang_cc1 -x c -std=c2x -E -DPP_ONLY=1 %s | FileCheck %s 
--strict-whitespace
+
+/* WG14 N2863: Clang 15

AaronBallman wrote:

```suggestion
/* WG14 N2836: Clang 15
```

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


[clang] [Clang] Mark WG14 N2939 (Identifier Syntax Fixes) as available in Clang 15 (PR #74666)

2023-12-07 Thread Aaron Ballman via cfe-commits

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

LGTM aside from a typo in a comment.

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


[clang] [clang] Crash when referencing capture in static lambda (PR #74661)

2023-12-07 Thread Timm Baeder via cfe-commits


@@ -8492,14 +8492,24 @@ bool LValueExprEvaluator::VisitVarDecl(const Expr *E, 
const VarDecl *VD) {
   return false;
 
 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
+  auto *MD = cast(Info.CurrentCall->Callee);

tbaederr wrote:

```suggestion
  const auto *MD = cast(Info.CurrentCall->Callee);
```

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


[libcxxabi] [flang] [lld] [llvm] [compiler-rt] [lldb] [clang] [clang-tools-extra] [libcxx] [AMDGPU] GFX12: select @llvm.prefetch intrinsic (PR #74576)

2023-12-07 Thread Mariusz Sikora via cfe-commits


@@ -959,6 +967,32 @@ def : GCNPat <
 }
 } // let OtherPredicates = [HasShaderCyclesRegister]
 
+def SIMM24bitPtr : ImmLeaf (Imm);}]
+>;
+
+multiclass SMPrefetchPat {
+  def : GCNPat <
+(smrd_prefetch (SMRDImm i64:$sbase, i32:$offset), timm, timm, (i32 
cache_type)),
+(!cast("S_PREFETCH_"#type) $sbase, $offset, (i32 
SGPR_NULL), (i8 0))
+  >;
+
+  def : GCNPat <
+(smrd_prefetch (i64 SReg_64:$sbase), timm, timm, (i32 cache_type)),
+(!cast("S_PREFETCH_"#type) $sbase, 0, (i32 SGPR_NULL), 
(i8 0))
+  >;
+
+  def : GCNPat <
+(prefetch SIMM24bitPtr:$offset, timm, timm, (i32 cache_type)),
+(!cast("S_PREFETCH_"#type#"_PC_REL") (as_i32timm 
$offset), (i32 SGPR_NULL), (i8 0))
+  > {
+let AddedComplexity = 10;
+  }

mariusz-sikora-at-amd wrote:

Maybe for now I will remove PC_REL part.

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


[libcxx] [flang] [clang-tools-extra] [libcxxabi] [compiler-rt] [clang] [lldb] [lld] [llvm] [AMDGPU] GFX12: select @llvm.prefetch intrinsic (PR #74576)

2023-12-07 Thread Mariusz Sikora via cfe-commits

https://github.com/mariusz-sikora-at-amd updated 
https://github.com/llvm/llvm-project/pull/74576

>From 23759746b66c33028ad2340b1e98067ebf1f8074 Mon Sep 17 00:00:00 2001
From: Stanislav Mekhanoshin 
Date: Tue, 28 Jun 2022 15:24:24 -0700
Subject: [PATCH 1/2] [AMDGPU] GFX12: select @llvm.prefetch intrinsic

---
 .../Target/AMDGPU/AMDGPURegisterBankInfo.cpp  |  21 +
 llvm/lib/Target/AMDGPU/GCNSubtarget.h |   2 +
 llvm/lib/Target/AMDGPU/SIISelLowering.cpp |  22 +
 llvm/lib/Target/AMDGPU/SIISelLowering.h   |   2 +
 llvm/lib/Target/AMDGPU/SIInstrInfo.cpp|   2 +
 llvm/lib/Target/AMDGPU/SIInstructions.td  |  12 +
 llvm/lib/Target/AMDGPU/SMInstructions.td  |  34 ++
 llvm/test/CodeGen/AMDGPU/llvm.prefetch.ll | 496 ++
 8 files changed, 591 insertions(+)
 create mode 100644 llvm/test/CodeGen/AMDGPU/llvm.prefetch.ll

diff --git a/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp 
b/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
index 62996a3b3fb79..f0b3ed7adc294 100644
--- a/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
+++ b/llvm/lib/Target/AMDGPU/AMDGPURegisterBankInfo.cpp
@@ -3101,6 +3101,24 @@ void AMDGPURegisterBankInfo::applyMappingImpl(
   applyDefaultMapping(OpdMapper);
   constrainOpWithReadfirstlane(B, MI, 8); // M0
   return;
+case Intrinsic::prefetch: {
+  if (!Subtarget.hasPrefetch()) {
+MI.eraseFromParent();
+return;
+  }
+  unsigned PtrBank =
+  getRegBankID(MI.getOperand(1).getReg(), MRI, AMDGPU::SGPRRegBankID);
+  if (PtrBank == AMDGPU::VGPRRegBankID) {
+MI.eraseFromParent();
+return;
+  }
+  // FIXME: There is currently no support for prefetch in global isel.
+  // There is no node equivalence and what's worse there is no MMO produced
+  // for a prefetch on global isel path.
+  // Prefetch does not affect execution so erase it for now.
+  MI.eraseFromParent();
+  return;
+}
 default: {
   if (const AMDGPU::RsrcIntrinsic *RSrcIntrin =
   AMDGPU::lookupRsrcIntrinsic(IntrID)) {
@@ -4830,6 +4848,9 @@ AMDGPURegisterBankInfo::getInstrMapping(const 
MachineInstr &MI) const {
   getVGPROpMapping(MI.getOperand(5).getReg(), MRI, *TRI); // %data1
   break;
 }
+case Intrinsic::prefetch:
+  OpdsMapping[1] = getSGPROpMapping(MI.getOperand(1).getReg(), MRI, *TRI);
+  break;
 
 default:
   return getInvalidInstructionMapping();
diff --git a/llvm/lib/Target/AMDGPU/GCNSubtarget.h 
b/llvm/lib/Target/AMDGPU/GCNSubtarget.h
index 94b9e49b765a6..21a9b8147034f 100644
--- a/llvm/lib/Target/AMDGPU/GCNSubtarget.h
+++ b/llvm/lib/Target/AMDGPU/GCNSubtarget.h
@@ -828,6 +828,8 @@ class GCNSubtarget final : public AMDGPUGenSubtargetInfo,
 
   bool hasInstPrefetch() const { return getGeneration() >= GFX10; }
 
+  bool hasPrefetch() const { return GFX12Insts; }
+
   // Scratch is allocated in 256 dword per wave blocks for the entire
   // wavefront. When viewed from the perspective of an arbitrary workitem, this
   // is 4-byte aligned.
diff --git a/llvm/lib/Target/AMDGPU/SIISelLowering.cpp 
b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
index a7f4d63229b7e..93af38d877c5d 100644
--- a/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
+++ b/llvm/lib/Target/AMDGPU/SIISelLowering.cpp
@@ -763,6 +763,9 @@ SITargetLowering::SITargetLowering(const TargetMachine &TM,
   if (Subtarget->hasMad64_32())
 setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, MVT::i32, Custom);
 
+  if (Subtarget->hasPrefetch())
+setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
+
   setOperationAction(ISD::INTRINSIC_WO_CHAIN,
  {MVT::Other, MVT::f32, MVT::v4f32, MVT::i16, MVT::f16,
   MVT::v2i16, MVT::v2f16, MVT::i128},
@@ -3858,6 +3861,23 @@ SDValue SITargetLowering::lowerGET_ROUNDING(SDValue Op,
   return DAG.getMergeValues({Result, GetReg.getValue(1)}, SL);
 }
 
+SDValue SITargetLowering::lowerPREFETCH(SDValue Op, SelectionDAG &DAG) const {
+  if (Op->isDivergent())
+return SDValue();
+
+  switch (cast(Op)->getAddressSpace()) {
+  case AMDGPUAS::FLAT_ADDRESS:
+  case AMDGPUAS::GLOBAL_ADDRESS:
+  case AMDGPUAS::CONSTANT_ADDRESS:
+  case AMDGPUAS::CONSTANT_ADDRESS_32BIT:
+break;
+  default:
+return SDValue();
+  }
+
+  return Op;
+}
+
 Register SITargetLowering::getRegisterByName(const char* RegName, LLT VT,
  const MachineFunction &MF) const {
   Register Reg = StringSwitch(RegName)
@@ -5395,6 +5415,8 @@ SDValue SITargetLowering::LowerOperation(SDValue Op, 
SelectionDAG &DAG) const {
 return LowerSTACKSAVE(Op, DAG);
   case ISD::GET_ROUNDING:
 return lowerGET_ROUNDING(Op, DAG);
+  case ISD::PREFETCH:
+return lowerPREFETCH(Op, DAG);
   }
   return SDValue();
 }
diff --git a/llvm/lib/Target/AMDGPU/SIISelLowering.h 
b/llvm/lib/Target/AMDGPU/SIISelLowering.h
index c9cc149218a99..5bc091d6e84de 100644
--- a/llvm/lib/Target/AMDGPU/SIISelLowerin

[clang] 3293c08 - Remove dead code; NFC

2023-12-07 Thread Aaron Ballman via cfe-commits

Author: Aaron Ballman
Date: 2023-12-07T08:26:33-05:00
New Revision: 3293c088c25db5be6042d20bd95c80a0863a88d0

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

LOG: Remove dead code; NFC

This code was added 17 years ago but never enabled or tested. GCC warns
that -I- is deprecated for them, and Clang gives an error when passed
-I-, so we may as well remove this code rather than hook it up to the
driver and maintain it.

Added: 


Modified: 
clang/include/clang/Lex/HeaderSearch.h
clang/lib/Lex/HeaderSearch.cpp
clang/lib/Lex/InitHeaderSearch.cpp

Removed: 




diff  --git a/clang/include/clang/Lex/HeaderSearch.h 
b/clang/include/clang/Lex/HeaderSearch.h
index a100598c80155..a2c33842924b1 100644
--- a/clang/include/clang/Lex/HeaderSearch.h
+++ b/clang/include/clang/Lex/HeaderSearch.h
@@ -247,16 +247,13 @@ class HeaderSearch {
   /// \#include search path information.  Requests for \#include "x" search the
   /// directory of the \#including file first, then each directory in 
SearchDirs
   /// consecutively. Requests for  search the current dir first, then each
-  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.  If
-  /// NoCurDirSearch is true, then the check for the file in the current
-  /// directory is suppressed.
+  /// directory in SearchDirs, starting at AngledDirIdx, consecutively.
   std::vector SearchDirs;
   /// Whether the DirectoryLookup at the corresponding index in SearchDirs has
   /// been successfully used to lookup a file.
   std::vector SearchDirsUsage;
   unsigned AngledDirIdx = 0;
   unsigned SystemDirIdx = 0;
-  bool NoCurDirSearch = false;
 
   /// Maps HeaderMap keys to SearchDir indices. When HeaderMaps are used
   /// heavily, SearchDirs can start with thousands of HeaderMaps, so this Index
@@ -373,7 +370,7 @@ class HeaderSearch {
 
   /// Interface for setting the file search paths.
   void SetSearchPaths(std::vector dirs, unsigned angledDirIdx,
-  unsigned systemDirIdx, bool noCurDirSearch,
+  unsigned systemDirIdx,
   llvm::DenseMap searchDirToHSEntry);
 
   /// Add an additional search path.

diff  --git a/clang/lib/Lex/HeaderSearch.cpp b/clang/lib/Lex/HeaderSearch.cpp
index cf1c0cc5284f3..c03cf19688d96 100644
--- a/clang/lib/Lex/HeaderSearch.cpp
+++ b/clang/lib/Lex/HeaderSearch.cpp
@@ -105,7 +105,7 @@ void HeaderSearch::PrintStats() {
 
 void HeaderSearch::SetSearchPaths(
 std::vector dirs, unsigned int angledDirIdx,
-unsigned int systemDirIdx, bool noCurDirSearch,
+unsigned int systemDirIdx,
 llvm::DenseMap searchDirToHSEntry) {
   assert(angledDirIdx <= systemDirIdx && systemDirIdx <= dirs.size() &&
  "Directory indices are unordered");
@@ -113,7 +113,6 @@ void HeaderSearch::SetSearchPaths(
   SearchDirsUsage.assign(SearchDirs.size(), false);
   AngledDirIdx = angledDirIdx;
   SystemDirIdx = systemDirIdx;
-  NoCurDirSearch = noCurDirSearch;
   SearchDirToHSEntry = std::move(searchDirToHSEntry);
   //LookupFileCache.clear();
   indexInitialHeaderMaps();
@@ -904,12 +903,12 @@ OptionalFileEntryRef HeaderSearch::LookupFile(
   ModuleMap::KnownHeader MSSuggestedModule;
   OptionalFileEntryRef MSFE;
 
-  // Unless disabled, check to see if the file is in the #includer's
-  // directory.  This cannot be based on CurDir, because each includer could be
-  // a #include of a subdirectory (#include "foo/bar.h") and a subsequent
-  // include of "baz.h" should resolve to "whatever/foo/baz.h".
-  // This search is not done for <> headers.
-  if (!Includers.empty() && !isAngled && !NoCurDirSearch) {
+  // Check to see if the file is in the #includer's directory. This cannot be
+  // based on CurDir, because each includer could be a #include of a
+  // subdirectory (#include "foo/bar.h") and a subsequent include of "baz.h"
+  // should resolve to "whatever/foo/baz.h". This search is not done for <>
+  // headers.
+  if (!Includers.empty() && !isAngled) {
 SmallString<1024> TmpDir;
 bool First = true;
 for (const auto &IncluderAndDir : Includers) {

diff  --git a/clang/lib/Lex/InitHeaderSearch.cpp 
b/clang/lib/Lex/InitHeaderSearch.cpp
index 1f4c7a6d67b7f..5b1b7c859c85d 100644
--- a/clang/lib/Lex/InitHeaderSearch.cpp
+++ b/clang/lib/Lex/InitHeaderSearch.cpp
@@ -513,9 +513,8 @@ void InitHeaderSearch::Realize(const LangOptions &Lang) {
   unsigned NonSystemRemoved = RemoveDuplicates(SearchList, NumQuoted, Verbose);
   NumAngled -= NonSystemRemoved;
 
-  bool DontSearchCurDir = false;  // TODO: set to true if -I- is set?
   Headers.SetSearchPaths(extractLookups(SearchList), NumQuoted, NumAngled,
- DontSearchCurDir, mapToUserEntries(SearchList));
+ mapToUserEntries(SearchList));
 
   Headers.SetS

[clang] [AArch64][SME] Warn when using a streaming builtin from a non-streaming function (PR #74064)

2023-12-07 Thread Sam Tebbs via cfe-commits


@@ -3183,6 +3140,114 @@ bool Sema::CheckSVEBuiltinFunctionCall(unsigned 
BuiltinID, CallExpr *TheCall) {
   return HasError;
 }
 
+static ArmStreamingType getArmStreamingFnType(const FunctionDecl *FD) {
+  if (FD->hasAttr())
+return ArmStreaming;
+  if (const auto *T = FD->getType()->getAs()) {
+if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateSMEnabledMask)
+  return ArmStreaming;
+if (T->getAArch64SMEAttributes() & 
FunctionType::SME_PStateSMCompatibleMask)
+  return ArmStreamingCompatible;
+  }
+  return ArmNonStreaming;
+}
+
+static void checkArmStreamingBuiltin(Sema &S, CallExpr *TheCall,
+ const FunctionDecl *FD,
+ ArmStreamingType BuiltinType) {
+  ArmStreamingType FnType = getArmStreamingFnType(FD);
+
+  if (FnType == ArmStreaming && BuiltinType == ArmNonStreaming) {
+S.Diag(TheCall->getBeginLoc(), 
diag::warn_attribute_arm_sm_incompat_builtin)
+<< TheCall->getSourceRange() << "streaming";
+  }
+
+  if (FnType == ArmStreamingCompatible &&
+  BuiltinType != ArmStreamingCompatible) {
+S.Diag(TheCall->getBeginLoc(), 
diag::warn_attribute_arm_sm_incompat_builtin)
+<< TheCall->getSourceRange() << "streaming compatible";
+return;
+  }
+
+  if (FnType == ArmNonStreaming && BuiltinType == ArmStreaming) {
+S.Diag(TheCall->getBeginLoc(), 
diag::warn_attribute_arm_sm_incompat_builtin)
+<< TheCall->getSourceRange() << "non-streaming";
+  }
+}
+
+static bool hasSMEZAState(const FunctionDecl *FD) {
+  if (FD->hasAttr())
+return true;
+  if (const auto *T = FD->getType()->getAs())
+if (T->getAArch64SMEAttributes() & FunctionType::SME_PStateZASharedMask)
+  return true;
+  return false;
+}
+
+static bool hasSMEZAState(unsigned BuiltinID) {
+  switch (BuiltinID) {
+  default:
+return false;
+#define GET_SME_BUILTIN_HAS_ZA_STATE
+#include "clang/Basic/arm_sme_builtins_za_state.inc"
+#undef GET_SME_BUILTIN_HAS_ZA_STATE
+  }
+}
+
+bool Sema::CheckSMEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
+  if (const FunctionDecl *FD = getCurFunctionDecl()) {
+std::optional BuiltinType;
+
+switch (BuiltinID) {
+default:
+  break;
+#define GET_SME_STREAMING_ATTRS
+#include "clang/Basic/arm_sme_streaming_attrs.inc"
+#undef GET_SME_STREAMING_ATTRS
+}
+
+if (BuiltinType)
+  checkArmStreamingBuiltin(*this, TheCall, FD, *BuiltinType);
+
+if (hasSMEZAState(BuiltinID) && !hasSMEZAState(FD))
+  Diag(TheCall->getBeginLoc(),
+   diag::warn_attribute_arm_za_builtin_no_za_state)
+  << TheCall->getSourceRange();
+  }
+
+  // Range check SME intrinsics that take immediate values.
+  SmallVector, 3> ImmChecks;
+
+  switch (BuiltinID) {
+  default:
+return false;
+#define GET_SME_IMMEDIATE_CHECK
+#include "clang/Basic/arm_sme_sema_rangechecks.inc"
+#undef GET_SME_IMMEDIATE_CHECK
+  }
+
+  return ParseSVEImmChecks(TheCall, ImmChecks);
+}
+
+bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {

SamTebbs33 wrote:

Done! Rebased and should be ready for review again now.

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


[clang-tools-extra] [clang-tidy] Add check hicpp-ignored-remove-result (PR #73119)

2023-12-07 Thread Björn Svensson via cfe-commits

https://github.com/bjosv updated https://github.com/llvm/llvm-project/pull/73119

From 91cf412abcfd231ab399c3e44c6a9bc14109537c Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Bj=C3=B6rn=20Svensson?= 
Date: Tue, 21 Nov 2023 23:30:07 +0100
Subject: [PATCH 1/5] [clang-tidy] Add check hicpp-ignored-remove-result

This check implements the rule 17.5.1 of the HICPP standard
which states:

- Do not ignore the result of std::remove, std::remove_if or std::unique

  The mutating algorithms std::remove, std::remove_if and both overloads of
  std::unique operate by swapping or moving elements of the range they are
  operating over. On completion, they return an iterator to the last valid 
element.
  In the majority of cases the correct behavior is to use this result as the
  first operand in a call to std::erase.

Suppressing issues by casting to `void` is enabled by default, but can be
disabled by setting `AllowCastToVoid` option to `false`.
---
 .../clang-tidy/hicpp/HICPPTidyModule.cpp  | 20 
 clang-tools-extra/docs/ReleaseNotes.rst   |  4 ++
 .../checks/hicpp/ignored-remove-result.rst| 20 
 .../docs/clang-tidy/checks/list.rst   |  1 +
 .../checkers/hicpp/ignored-remove-result.cpp  | 47 +++
 5 files changed, 92 insertions(+)
 create mode 100644 
clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
 create mode 100644 
clang-tools-extra/test/clang-tidy/checkers/hicpp/ignored-remove-result.cpp

diff --git a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp 
b/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
index 3749796877120..09d15ccab3f29 100644
--- a/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
+++ b/clang-tools-extra/clang-tidy/hicpp/HICPPTidyModule.cpp
@@ -10,6 +10,7 @@
 #include "../ClangTidyModule.h"
 #include "../ClangTidyModuleRegistry.h"
 #include "../bugprone/UndelegatedConstructorCheck.h"
+#include "../bugprone/UnusedReturnValueCheck.h"
 #include "../bugprone/UseAfterMoveCheck.h"
 #include "../cppcoreguidelines/AvoidGotoCheck.h"
 #include "../cppcoreguidelines/NoMallocCheck.h"
@@ -41,6 +42,15 @@
 #include "NoAssemblerCheck.h"
 #include "SignedBitwiseCheck.h"
 
+namespace {
+
+// Checked functions for hicpp-ignored-remove-result.
+const llvm::StringRef CheckedFunctions = "::std::remove;"
+ "::std::remove_if;"
+ "::std::unique;";
+
+} // namespace
+
 namespace clang::tidy {
 namespace hicpp {
 
@@ -64,6 +74,8 @@ class HICPPModule : public ClangTidyModule {
 "hicpp-explicit-conversions");
 CheckFactories.registerCheck(
 "hicpp-function-size");
+CheckFactories.registerCheck(
+"hicpp-ignored-remove-result");
 CheckFactories.registerCheck(
 "hicpp-named-parameter");
 CheckFactories.registerCheck(
@@ -107,6 +119,14 @@ class HICPPModule : public ClangTidyModule {
 CheckFactories.registerCheck(
 "hicpp-vararg");
   }
+
+  ClangTidyOptions getModuleOptions() override {
+ClangTidyOptions Options;
+ClangTidyOptions::OptionMap &Opts = Options.CheckOptions;
+Opts["hicpp-ignored-remove-result.CheckedFunctions"] = CheckedFunctions;
+Opts["hicpp-ignored-remove-result.AllowCastToVoid"] = "true";
+return Options;
+  }
 };
 
 // Register the HICPPModule using this statically initialized variable.
diff --git a/clang-tools-extra/docs/ReleaseNotes.rst 
b/clang-tools-extra/docs/ReleaseNotes.rst
index 6d5f49dc06254..c940025df1c63 100644
--- a/clang-tools-extra/docs/ReleaseNotes.rst
+++ b/clang-tools-extra/docs/ReleaseNotes.rst
@@ -205,6 +205,10 @@ New check aliases
   ` to 
:doc:`modernize-macro-to-enum
   ` was added.
 
+- New alias :doc:`hicpp-ignored-remove-result
+  ` to 
:doc:`bugprone-unused-return-value
+  ` was added.
+
 Changes in existing checks
 ^^
 
diff --git 
a/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst 
b/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
new file mode 100644
index 0..4b6188b886db1
--- /dev/null
+++ b/clang-tools-extra/docs/clang-tidy/checks/hicpp/ignored-remove-result.rst
@@ -0,0 +1,20 @@
+.. title:: clang-tidy - hicpp-ignored-remove-result
+
+hicpp-ignored-remove-result
+===
+
+Ensure that the result of ``std::remove``, ``std::remove_if`` and 
``std::unique``
+are not ignored according to
+`rule 17.5.1 
`_.
+
+The mutating algorithms ``std::remove``, ``std::remove_if`` and both overloads
+of ``std::unique`` operate by swapping or moving elements of the range they are
+operating over. On completion, they return an iterator to the last valid
+element. In the majority of cases the correct behavior is to use this result as
+the first operand in a call to std::erase.
+
+This check is an alias of check :doc:`bugprone-unused-return-value 
<../bugprone/unused-

[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-12-07 Thread Aaron Ballman via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 



@@ -53,6 +53,10 @@ LLVM_READNONE inline bool isASCII(int64_t c) { return 0 <= c 
&& c <= 127; }
 /// which is [a-zA-Z_].
 LLVM_READONLY inline bool isAsciiIdentifierStart(unsigned char c,
  bool AllowDollar = false) {
+  if (!AllowDollar) {
+return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+  }
+

AaronBallman wrote:

Why do we need this change?

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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-12-07 Thread Aaron Ballman via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 



@@ -1112,6 +1121,140 @@ prepareAndFilterRanges(const 
SmallVectorImpl &Ranges,
   return LineRanges;
 }
 
+/// Creates syntax highlighting information in form of StyleRanges.
+///
+/// The returned unique ptr has always exactly size
+/// (\p EndLineNumber - \p StartLineNumber + 1). Each SmallVector in there
+/// corresponds to syntax highlighting information in one line. In each line,
+/// the StyleRanges are non-overlapping and sorted from start to end of the
+/// line.
+std::unique_ptr[]>
+highlightLines(StringRef FileData, unsigned StartLineNumber,
+   unsigned EndLineNumber, const Preprocessor *PP,
+   const LangOptions &LangOpts, uint32_t MaxHighlightFileSize,
+   FileID FID, const SourceManager &SM) {
+  assert(StartLineNumber <= EndLineNumber);
+  auto SnippetRanges =
+  std::make_unique[]>(
+  EndLineNumber - StartLineNumber + 1);
+
+  if (!PP)
+return SnippetRanges;
+
+  // Might cause emission of another diagnostic.
+  if (PP->getIdentifierTable().getExternalIdentifierLookup())
+return SnippetRanges;
+
+  auto Buff = llvm::MemoryBuffer::getMemBuffer(FileData);
+  if (Buff->getBufferSize() > MaxHighlightFileSize)
+return SnippetRanges;
+
+  Lexer L{FID, *Buff, SM, LangOpts};
+  L.SetKeepWhitespaceMode(true);
+
+  // Classify the given token and append it to the given vector.
+  auto appendStyle =
+  [PP, &LangOpts](SmallVector &Vec,
+  const Token &T, unsigned Start, unsigned Length) -> void 
{
+if (T.is(tok::raw_identifier)) {
+  StringRef RawIdent = T.getRawIdentifier();
+  // Special case true/false/nullptr literals, since they will otherwise be
+  // treated as keywords.
+  if (RawIdent == "true" || RawIdent == "false" || RawIdent == "nullptr") {

AaronBallman wrote:

I think there are more cases like this: `__func__`, `__objc_yes`, `__objc_no`, 
`__null`, `__FUNCDNAME__`, `__FUNCSIG__`, `L__FUNCTION__`, and `L__FUNCSIG__`, 
at least from my reading of TokenKinds.def.

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


[clang] [clang][Diagnostics] Highlight code snippets (PR #66514)

2023-12-07 Thread Aaron Ballman via cfe-commits
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= ,
Timm =?utf-8?q?Bäder?= 
Message-ID:
In-Reply-To: 


AaronBallman wrote:

> @tbaederr I will need time to review/discuss this patch with other folks 
> (@AaronBallman). I thought we had agreement on a direction before it got 
> reverted completely and it is not clear to me that doing whole file lexing 
> for each warning isn't going to negatively impact some folks.
> 
> But I haven't forgotten about it!

Re-lexing the file on each diagnostic works well enough for cases where there's 
only a few diagnostics in the file. But I do worry about the pathological case 
where there's a diagnostic on every line: that means compiling the file is 
O(N^2) in terms of lexing tokens whereas using checkpoints would still be O(N). 
Do you have an idea how bad the worst case performance looks compared to the 
best case? e.g., can you write a ~1MB test file that has no diagnostics and 
another similar ~1MB test file that has a warning diagnostic per line, and see 
what the performance difference is between runs of the compiler for those files?

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


[clang] [clang] Add separate C++23 extension flag for attrs on lambda (PR #74553)

2023-12-07 Thread Aaron Ballman via cfe-commits

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

LGTM, thank you!

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


[clang] e825cc4 - [clang] Add separate C++23 extension flag for attrs on lambda (#74553)

2023-12-07 Thread via cfe-commits

Author: Utkarsh Saxena
Date: 2023-12-07T14:52:10+01:00
New Revision: e825cc4eba5fee546fd90032cfbdc6ac1c57a50e

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

LOG: [clang] Add separate C++23 extension flag for attrs on lambda (#74553)

Added: 


Modified: 
clang/docs/LanguageExtensions.rst
clang/docs/ReleaseNotes.rst
clang/include/clang/Basic/DiagnosticGroups.td
clang/include/clang/Basic/DiagnosticParseKinds.td
clang/test/SemaCXX/coro-lifetimebound.cpp
clang/test/SemaCXX/coro-return-type-and-wrapper.cpp

Removed: 




diff  --git a/clang/docs/LanguageExtensions.rst 
b/clang/docs/LanguageExtensions.rst
index 286405850900a..4b1cc1d500c84 100644
--- a/clang/docs/LanguageExtensions.rst
+++ b/clang/docs/LanguageExtensions.rst
@@ -1483,6 +1483,7 @@ Conditional ``explicit``   
__cpp_conditional_explicit   C++20
 ``using enum`` __cpp_using_enum C++20  
   C++03
 ``if consteval``   __cpp_if_consteval   C++23  
   C++20
 ``static operator()``  __cpp_static_call_operator   C++23  
   C++03
+Attributes on Lambda-ExpressionsC++23  
   C++11
 --  
- -
 Designated initializers (N494)  C99
   C89
 Array & element qualification (N2607)   C23
   C89

diff  --git a/clang/docs/ReleaseNotes.rst b/clang/docs/ReleaseNotes.rst
index 1fbd332f74057..5c04465819713 100644
--- a/clang/docs/ReleaseNotes.rst
+++ b/clang/docs/ReleaseNotes.rst
@@ -156,6 +156,9 @@ C++23 Feature Support
   support for this feature is still experimental, the feature test macro 
``__cpp_explicit_this_parameter``
   was not set in this version.
 
+- Added a separate warning to warn the use of attributes on lambdas as a C++23 
extension
+  in previous language versions: ``-Wc++23-lambda-attributes``.
+
 C++2c Feature Support
 ^
 

diff  --git a/clang/include/clang/Basic/DiagnosticGroups.td 
b/clang/include/clang/Basic/DiagnosticGroups.td
index 12b11527b3057..caee2dc6daadb 100644
--- a/clang/include/clang/Basic/DiagnosticGroups.td
+++ b/clang/include/clang/Basic/DiagnosticGroups.td
@@ -1126,6 +1126,8 @@ def FutureAttrs : 
DiagGroup<"future-attribute-extensions", [CXX14Attrs,
 CXX17Attrs,
 CXX20Attrs]>;
 
+def CXX23AttrsOnLambda : DiagGroup<"c++23-lambda-attributes">;
+
 // A warning group for warnings about using C++11 features as extensions in
 // earlier C++ versions.
 def CXX11 : DiagGroup<"c++11-extensions", [CXX11ExtraSemi, 
CXX11InlineNamespace,
@@ -1145,7 +1147,7 @@ def CXX20 : DiagGroup<"c++20-extensions", 
[CXX20Designator, CXX20Attrs]>;
 
 // A warning group for warnings about using C++23 features as extensions in
 // earlier C++ versions.
-def CXX23 : DiagGroup<"c++23-extensions">;
+def CXX23 : DiagGroup<"c++23-extensions", [CXX23AttrsOnLambda]>;
 
 // A warning group for warnings about using C++26 features as extensions in
 // earlier C++ versions.

diff  --git a/clang/include/clang/Basic/DiagnosticParseKinds.td 
b/clang/include/clang/Basic/DiagnosticParseKinds.td
index e0e199e0d7300..6150fc36430ab 100644
--- a/clang/include/clang/Basic/DiagnosticParseKinds.td
+++ b/clang/include/clang/Basic/DiagnosticParseKinds.td
@@ -1035,7 +1035,7 @@ def err_capture_default_first : Error<
   "capture default must be first">;
 def ext_decl_attrs_on_lambda : ExtWarn<
   "%select{an attribute specifier sequence|%0}1 in this position "
-  "is a C++23 extension">, InGroup;
+  "is a C++23 extension">, InGroup;
 def ext_lambda_missing_parens : ExtWarn<
   "lambda without a parameter clause is a C++23 extension">,
   InGroup;

diff  --git a/clang/test/SemaCXX/coro-lifetimebound.cpp 
b/clang/test/SemaCXX/coro-lifetimebound.cpp
index d3e2d673ebb3c..b4dc029a13984 100644
--- a/clang/test/SemaCXX/coro-lifetimebound.cpp
+++ b/clang/test/SemaCXX/coro-lifetimebound.cpp
@@ -1,4 +1,4 @@
-// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 -fsyntax-only 
-verify -Wall -Wextra -Wno-error=unreachable-code -Wno-unused
+// RUN: %clang_cc1 -triple x86_64-apple-darwin9 %s -std=c++20 -fsyntax-only 
-verify -Wall -Wextra -Wno-error=unreachable-code -Wno-unused 
-Wno-c++23-lambda-attributes
 
 #include "Inputs/std-coroutine.h"
 
@@ -64,14 +64,8 @@ Co bar_coro(const int &b, int c) {
   : bar_coro(0, 1); // expected-warning {{returning address of local 
temporary object}}
 }
 
-#define CORO_WRAPPER \
-  _Pragma("clang diagnostic push") \
-  _Pragma("clang 

[clang] [clang] Add separate C++23 extension flag for attrs on lambda (PR #74553)

2023-12-07 Thread Utkarsh Saxena via cfe-commits

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


[clang] [openmp] [OpenMP] Fix runtime problem due wrong map size. (PR #74692)

2023-12-07 Thread Alexey Bataev via cfe-commits


@@ -0,0 +1,23 @@
+// clang-format off
+// RUN: %libomptarget-compilexx-generic && env LIBOMPTARGET_DEBUG=1 
%libomptarget-run-generic 2>&1 | %fcheck-generic
+// clang-format on
+
+struct DataTy {
+  float a;
+  float b[2];

alexey-bataev wrote:

Could you change the size of the array to, say, 3 instead of 2? Required to 
check that we map the requested array section, not the whole array.

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


[clang-tools-extra] [clang] [llvm] [libcxx] [FIX] Fix the function isctype failed in arm64-big-endian (PR #73200)

2023-12-07 Thread Louis Dionne via cfe-commits

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


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


[clang-tools-extra] [clang] [llvm] [libcxx] [FIX] Fix the function isctype failed in arm64-big-endian (PR #73200)

2023-12-07 Thread Louis Dionne via cfe-commits

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


[clang] [llvm] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits

https://github.com/david-arm updated 
https://github.com/llvm/llvm-project/pull/73326

>From af76f6b6b3469fd0f5f24427c5a175c8d9d7c83a Mon Sep 17 00:00:00 2001
From: David Sherwood 
Date: Fri, 24 Nov 2023 13:20:23 +
Subject: [PATCH 1/5] [Clang] Emit TBAA info for enums in C

When emitting TBAA information for enums in C code we
currently just treat the data as an 'omnipotent char'.
However, with C strict aliasing this means we fail to
optimise certain cases. For example, in the SPEC2017
xz benchmark there are structs that contain arrays of
enums, and clang pessmistically assumes that accesses
to those enums could alias with other struct members
that have a different type.

According to

https://en.cppreference.com/w/c/language/enum

enums should be treated as 'int' types unless
explicitly specified (C23) or if 'int' would not be
large enough to hold all the enumerated values. In the
latter case the compiler is free to choose a suitable
integer that would hold all such values.

When compiling C code this patch generates TBAA
information for the enum by using an equivalent integer
of the size clang has already chosen for the enum. I
have ignored C++ for now because the rules are more
complex.

New test added here:

  clang/test/CodeGen/tbaa.c
---
 clang/lib/CodeGen/CodeGenTBAA.cpp |   5 +-
 clang/test/CodeGen/tbaa.c | 116 ++
 2 files changed, 120 insertions(+), 1 deletion(-)
 create mode 100644 clang/test/CodeGen/tbaa.c

diff --git a/clang/lib/CodeGen/CodeGenTBAA.cpp 
b/clang/lib/CodeGen/CodeGenTBAA.cpp
index 8705d3d65f1a5..f59d3d422d520 100644
--- a/clang/lib/CodeGen/CodeGenTBAA.cpp
+++ b/clang/lib/CodeGen/CodeGenTBAA.cpp
@@ -196,11 +196,14 @@ llvm::MDNode *CodeGenTBAA::getTypeInfoHelper(const Type 
*Ty) {
   // Enum types are distinct types. In C++ they have "underlying types",
   // however they aren't related for TBAA.
   if (const EnumType *ETy = dyn_cast(Ty)) {
+if (!Features.CPlusPlus)
+  return getTypeInfo(Context.getIntTypeForBitwidth(Size * 8, 0));
+
 // In C++ mode, types have linkage, so we can rely on the ODR and
 // on their mangled names, if they're external.
 // TODO: Is there a way to get a program-wide unique name for a
 // decl with local linkage or no linkage?
-if (!Features.CPlusPlus || !ETy->getDecl()->isExternallyVisible())
+if (!ETy->getDecl()->isExternallyVisible())
   return getChar();
 
 SmallString<256> OutName;
diff --git a/clang/test/CodeGen/tbaa.c b/clang/test/CodeGen/tbaa.c
new file mode 100644
index 0..0ab81f60a7194
--- /dev/null
+++ b/clang/test/CodeGen/tbaa.c
@@ -0,0 +1,116 @@
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -no-struct-path-tbaa 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefixes=PATH
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O0 -disable-llvm-passes %s 
-emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// RUN: %clang_cc1 -triple x86_64-apple-darwin -O1 -relaxed-aliasing 
-disable-llvm-passes %s -emit-llvm -o - | FileCheck %s -check-prefix=NO-TBAA
+// Test TBAA metadata generated by front-end.
+//
+// NO-TBAA-NOT: !tbaa
+
+typedef unsigned char uint8_t;
+typedef unsigned short uint16_t;
+typedef unsigned int uint32_t;
+typedef unsigned long long uint64_t;
+
+typedef enum {
+  RED_AUTO_32,
+  GREEN_AUTO_32,
+  BLUE_AUTO_32
+} EnumAuto32;
+
+typedef enum {
+  RED_AUTO_64,
+  GREEN_AUTO_64,
+  BLUE_AUTO_64 = 0x1ull
+} EnumAuto64;
+
+typedef enum : uint16_t {
+  RED_16,
+  GREEN_16,
+  BLUE_16
+} Enum16;
+
+typedef enum : uint8_t {
+  RED_8,
+  GREEN_8,
+  BLUE_8
+} Enum8;
+
+uint32_t g0(EnumAuto32 *E, uint32_t *val) {
+// CHECK-LABEL: define{{.*}} i32 @g0(
+// CHECK: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// CHECK: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// CHECK: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH-LABEL: define{{.*}} i32 @g0(
+// PATH: store i32 5, ptr %{{.*}}, align 4, !tbaa [[TAG_i32:!.*]]
+// PATH: store i32 0, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+// PATH: load i32, ptr %{{.*}}, align 4, !tbaa [[TAG_i32]]
+  *val = 5;
+  *E = RED_AUTO_32;
+  return *val;
+}
+
+uint64_t g1(EnumAuto64 *E, uint64_t *val) {
+// CHECK-LABEL: define{{.*}} i64 @g1(
+// CHECK: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// CHECK: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// CHECK: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+// PATH-LABEL: define{{.*}} i64 @g1(
+// PATH: store i64 5, ptr %{{.*}}, align 8, !tbaa [[TAG_i64:!.*]]
+// PATH: store i64 0, ptr %{{.*}}, align 8, !tbaa [[TAG_long:!.*]]
+// PATH: load i64, ptr %{{.*}}, align 8, !tbaa [[TAG_i64]]
+  *val = 5;
+  *E = RED_AUTO_64;
+  return *val;
+}
+
+uint16_t g2(Enum16 *E, uint16_t *val) {
+// CHECK-LABEL: define{{.*}} i16 @g2(
+// CHECK: store i16 5, ptr %{{.*}}, align 2, !tbaa [[TAG_i16:!.

[clang] 9406d2a - [clang][Interp][NFC] Remove unused include

2023-12-07 Thread Timm Bäder via cfe-commits

Author: Timm Bäder
Date: 2023-12-07T15:20:22+01:00
New Revision: 9406d2a345e827146b7bf369542d8778982bfc6c

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

LOG: [clang][Interp][NFC] Remove unused include

Added: 


Modified: 
clang/lib/AST/Interp/ByteCodeExprGen.cpp

Removed: 




diff  --git a/clang/lib/AST/Interp/ByteCodeExprGen.cpp 
b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
index f45e8624a7741..f7f8e6c73d84e 100644
--- a/clang/lib/AST/Interp/ByteCodeExprGen.cpp
+++ b/clang/lib/AST/Interp/ByteCodeExprGen.cpp
@@ -15,7 +15,6 @@
 #include "Function.h"
 #include "PrimType.h"
 #include "Program.h"
-#include "State.h"
 
 using namespace clang;
 using namespace clang::interp;



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


[llvm] [clang] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread David Sherwood via cfe-commits


@@ -196,6 +196,9 @@ C Language Changes
   number of elements in the flexible array member. This information can improve
   the results of the array bound sanitizer and the
   ``__builtin_dynamic_object_size`` builtin.
+- Enums will now be represented in TBAA metadata using their actual underlying

david-arm wrote:

The comment is actually under the heading `C Language Changes` so I think that 
should be clear enough. Is that ok?

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


[openmp] [clang] [OpenMP] Fix runtime problem due wrong map size. (PR #74692)

2023-12-07 Thread Alexey Bataev via cfe-commits

https://github.com/alexey-bataev commented:

I think the description is not quite correct. Looks like %arrayidx is correct, 
but %2 is incorrect.


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


[clang] [llvm] [Clang] Emit TBAA info for enums in C (PR #73326)

2023-12-07 Thread Paul Walker via cfe-commits


@@ -196,6 +196,9 @@ C Language Changes
   number of elements in the flexible array member. This information can improve
   the results of the array bound sanitizer and the
   ``__builtin_dynamic_object_size`` builtin.
+- Enums will now be represented in TBAA metadata using their actual underlying

paulwalker-arm wrote:

Works for me.

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


  1   2   3   4   >